1 // Copyright Joyent, Inc. and other Node contributors.
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
23 #include "node_buffer.h"
24 #include "node_constants.h"
25 #include "node_file.h"
26 #include "node_http_parser.h"
27 #include "node_javascript.h"
28 #include "node_version.h"
30 #if defined HAVE_PERFCTR
31 #include "node_counters.h"
35 #include "node_crypto.h"
38 #if defined HAVE_DTRACE || defined HAVE_ETW
39 #include "node_dtrace.h"
43 #include "async-wrap.h"
44 #include "async-wrap-inl.h"
47 #include "handle_wrap.h"
49 #include "string_bytes.h"
52 #include "v8-profiler.h"
57 #include <limits.h> // PATH_MAX
63 #include <sys/types.h>
69 #define strcasecmp _stricmp
70 #define getpid _getpid
74 #include <sys/resource.h> // getrlimit, setrlimit
75 #include <unistd.h> // setuid, getuid
78 #if defined(__POSIX__) && !defined(__ANDROID__)
79 #include <pwd.h> // getpwnam()
80 #include <grp.h> // getgrnam()
84 #include <crt_externs.h>
85 #define environ (*_NSGetEnviron())
86 #elif !defined(_MSC_VER)
87 extern char **environ;
93 using v8::ArrayBuffer;
98 using v8::FunctionCallbackInfo;
99 using v8::FunctionTemplate;
101 using v8::HandleScope;
102 using v8::HeapStatistics;
110 using v8::ObjectTemplate;
111 using v8::PropertyCallbackInfo;
113 using v8::ThrowException;
118 using v8::kExternalUnsignedIntArray;
120 // FIXME(bnoordhuis) Make these per-context?
121 QUEUE handle_wrap_queue = { &handle_wrap_queue, &handle_wrap_queue };
122 QUEUE req_wrap_queue = { &req_wrap_queue, &req_wrap_queue };
124 static bool print_eval = false;
125 static bool force_repl = false;
126 static bool trace_deprecation = false;
127 static bool throw_deprecation = false;
128 static const char* eval_string = NULL;
129 static bool use_debug_agent = false;
130 static bool debug_wait_connect = false;
131 static int debug_port = 5858;
132 static bool v8_is_profiling = false;
134 // used by C++ modules as well
135 bool no_deprecation = false;
137 // process-relative uptime base, initialized at start-up
138 static double prog_start_time;
139 static bool debugger_running;
140 static uv_async_t dispatch_debug_messages_async;
142 // Declared in node_internals.h
143 Isolate* node_isolate = NULL;
146 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
148 // Impose an upper limit to avoid out of memory errors that bring down
150 static const size_t kMaxLength = 0x3fffffff;
151 static ArrayBufferAllocator the_singleton;
152 virtual ~ArrayBufferAllocator() {}
153 virtual void* Allocate(size_t length);
154 virtual void* AllocateUninitialized(size_t length);
155 virtual void Free(void* data, size_t length);
157 ArrayBufferAllocator() {}
158 ArrayBufferAllocator(const ArrayBufferAllocator&);
159 void operator=(const ArrayBufferAllocator&);
162 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
165 void* ArrayBufferAllocator::Allocate(size_t length) {
166 if (length > kMaxLength)
168 return new char[length];
172 void* ArrayBufferAllocator::AllocateUninitialized(size_t length) {
173 if (length > kMaxLength)
175 return new char[length];
179 void ArrayBufferAllocator::Free(void* data, size_t length) {
180 delete[] static_cast<char*>(data);
184 static void CheckImmediate(uv_check_t* handle, int status) {
185 HandleScope scope(node_isolate);
186 Environment* env = Environment::from_immediate_check_handle(handle);
187 Context::Scope context_scope(env->context());
188 MakeCallback(env, env->process_object(), env->immediate_callback_string());
192 static void IdleImmediateDummy(uv_idle_t*, int) {
193 // Do nothing. Only for maintaining event loop.
194 // TODO(bnoordhuis) Maybe make libuv accept NULL idle callbacks.
198 static inline const char *errno_string(int errorno) {
199 #define ERRNO_CASE(e) case e: return #e;
206 ERRNO_CASE(EADDRINUSE);
210 ERRNO_CASE(EADDRNOTAVAIL);
214 ERRNO_CASE(EAFNOSUPPORT);
222 # if EAGAIN != EWOULDBLOCK
223 ERRNO_CASE(EWOULDBLOCK);
228 ERRNO_CASE(EALREADY);
244 ERRNO_CASE(ECANCELED);
252 ERRNO_CASE(ECONNABORTED);
256 ERRNO_CASE(ECONNREFUSED);
260 ERRNO_CASE(ECONNRESET);
268 ERRNO_CASE(EDESTADDRREQ);
292 ERRNO_CASE(EHOSTUNREACH);
304 ERRNO_CASE(EINPROGRESS);
340 ERRNO_CASE(EMSGSIZE);
344 ERRNO_CASE(EMULTIHOP);
348 ERRNO_CASE(ENAMETOOLONG);
352 ERRNO_CASE(ENETDOWN);
356 ERRNO_CASE(ENETRESET);
360 ERRNO_CASE(ENETUNREACH);
392 # if ENOLINK != ENOLCK
406 ERRNO_CASE(ENOPROTOOPT);
426 ERRNO_CASE(ENOTCONN);
434 ERRNO_CASE(ENOTEMPTY);
438 ERRNO_CASE(ENOTSOCK);
445 ERRNO_CASE(EOPNOTSUPP);
459 ERRNO_CASE(EOVERFLOW);
474 #ifdef EPROTONOSUPPORT
475 ERRNO_CASE(EPROTONOSUPPORT);
479 ERRNO_CASE(EPROTOTYPE);
507 ERRNO_CASE(ETIMEDOUT);
522 const char *signo_string(int signo) {
523 #define SIGNO_CASE(e) case e: return #e;
550 # if SIGABRT != SIGIOT
594 SIGNO_CASE(SIGSTKFLT);
611 SIGNO_CASE(SIGBREAK);
635 SIGNO_CASE(SIGVTALRM);
643 SIGNO_CASE(SIGWINCH);
651 # if SIGPOLL != SIGIO
661 # if SIGPWR != SIGLOST
675 Local<Value> ErrnoException(int errorno,
679 Environment* env = Environment::GetCurrent(node_isolate);
682 Local<String> estring = OneByteString(node_isolate, errno_string(errorno));
683 if (msg == NULL || msg[0] == '\0') {
684 msg = strerror(errorno);
686 Local<String> message = OneByteString(node_isolate, msg);
688 Local<String> cons1 =
689 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
690 Local<String> cons2 = String::Concat(cons1, message);
693 Local<String> cons3 =
694 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
695 Local<String> cons4 =
696 String::Concat(cons3, String::NewFromUtf8(node_isolate, path));
697 Local<String> cons5 =
698 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
699 e = Exception::Error(cons5);
701 e = Exception::Error(cons2);
704 Local<Object> obj = e->ToObject();
705 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
706 obj->Set(env->code_string(), estring);
709 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
712 if (syscall != NULL) {
713 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
720 // hack alert! copy of ErrnoException, tuned for uv errors
721 Local<Value> UVException(int errorno,
725 Environment* env = Environment::GetCurrent(node_isolate);
728 msg = uv_strerror(errorno);
730 Local<String> estring = OneByteString(node_isolate, uv_err_name(errorno));
731 Local<String> message = OneByteString(node_isolate, msg);
732 Local<String> cons1 =
733 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
734 Local<String> cons2 = String::Concat(cons1, message);
738 Local<String> path_str;
742 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
743 path_str = String::Concat(FIXED_ONE_BYTE_STRING(node_isolate, "\\\\"),
744 String::NewFromUtf8(node_isolate, path + 8));
745 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
746 path_str = String::NewFromUtf8(node_isolate, path + 4);
748 path_str = String::NewFromUtf8(node_isolate, path);
751 path_str = String::NewFromUtf8(node_isolate, path);
754 Local<String> cons3 =
755 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
756 Local<String> cons4 =
757 String::Concat(cons3, path_str);
758 Local<String> cons5 =
759 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
760 e = Exception::Error(cons5);
762 e = Exception::Error(cons2);
765 Local<Object> obj = e->ToObject();
766 // TODO(piscisaureus) errno should probably go
767 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
768 obj->Set(env->code_string(), estring);
771 obj->Set(env->path_string(), path_str);
774 if (syscall != NULL) {
775 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
783 // Does about the same as strerror(),
784 // but supports all windows error messages
785 static const char *winapi_strerror(const int errorno) {
788 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
789 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
790 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
793 // Remove trailing newlines
794 for (int i = strlen(errmsg) - 1;
795 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
801 // FormatMessage failed
802 return "Unknown error";
807 Local<Value> WinapiErrnoException(int errorno,
811 Environment* env = Environment::GetCurrent(node_isolate);
814 if (!msg || !msg[0]) {
815 msg = winapi_strerror(errorno);
817 Local<String> message = OneByteString(node_isolate, msg);
820 Local<String> cons1 =
821 String::Concat(message, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
822 Local<String> cons2 =
823 String::Concat(cons1, String::NewFromUtf8(node_isolate, path));
824 Local<String> cons3 =
825 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
826 e = Exception::Error(cons3);
828 e = Exception::Error(message);
831 Local<Object> obj = e->ToObject();
832 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
835 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
838 if (syscall != NULL) {
839 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
847 void SetupAsyncListener(const FunctionCallbackInfo<Value>& args) {
848 HandleScope handle_scope(args.GetIsolate());
849 Environment* env = Environment::GetCurrent(args.GetIsolate());
851 assert(args[0]->IsObject());
852 assert(args[1]->IsFunction());
853 assert(args[2]->IsFunction());
854 assert(args[3]->IsFunction());
855 assert(args[4]->IsFunction());
856 assert(args[5]->IsFunction());
858 env->set_async_listener_run_function(args[1].As<Function>());
859 env->set_async_listener_load_function(args[2].As<Function>());
860 env->set_async_listener_unload_function(args[3].As<Function>());
861 env->set_async_listener_push_function(args[4].As<Function>());
862 env->set_async_listener_strip_function(args[5].As<Function>());
864 Local<Object> async_listener_flag_obj = args[0].As<Object>();
865 Environment::AsyncListener* async_listener = env->async_listener();
866 async_listener_flag_obj->SetIndexedPropertiesToExternalArrayData(
867 async_listener->fields(),
868 kExternalUnsignedIntArray,
869 async_listener->fields_count());
871 // Do a little housekeeping.
872 env->process_object()->Delete(
873 FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupAsyncListener"));
877 void SetupNextTick(const FunctionCallbackInfo<Value>& args) {
878 HandleScope handle_scope(args.GetIsolate());
879 Environment* env = Environment::GetCurrent(args.GetIsolate());
881 assert(args[0]->IsObject() && args[1]->IsFunction());
883 // Values use to cross communicate with processNextTick.
884 Local<Object> tick_info_obj = args[0].As<Object>();
885 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
886 env->tick_info()->fields(),
887 kExternalUnsignedIntArray,
888 env->tick_info()->fields_count());
890 env->set_tick_callback_function(args[1].As<Function>());
892 // Do a little housekeeping.
893 env->process_object()->Delete(
894 FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupNextTick"));
898 Handle<Value> MakeCallback(Environment* env,
899 Handle<Object> object,
900 const Handle<Function> callback,
902 Handle<Value> argv[]) {
903 // If you hit this assertion, you forgot to enter the v8::Context first.
904 assert(env->context() == env->isolate()->GetCurrentContext());
906 Local<Object> process = env->process_object();
909 try_catch.SetVerbose(true);
911 // TODO(trevnorris): This is sucky for performance. Fix it.
912 bool has_async_queue = object->Has(env->async_queue_string());
913 if (has_async_queue) {
914 Local<Value> argv[] = { object };
915 env->async_listener_load_function()->Call(process, ARRAY_SIZE(argv), argv);
917 if (try_catch.HasCaught())
918 return Undefined(node_isolate);
921 Local<Value> ret = callback->Call(object, argc, argv);
923 if (try_catch.HasCaught()) {
924 return Undefined(node_isolate);
927 if (has_async_queue) {
928 Local<Value> val = object.As<Value>();
929 env->async_listener_unload_function()->Call(process, 1, &val);
931 if (try_catch.HasCaught())
932 return Undefined(node_isolate);
935 Environment::TickInfo* tick_info = env->tick_info();
937 if (tick_info->in_tick()) {
941 if (tick_info->length() == 0) {
942 tick_info->set_index(0);
946 tick_info->set_in_tick(true);
948 // process nextTicks after call
949 env->tick_callback_function()->Call(process, 0, NULL);
951 tick_info->set_in_tick(false);
953 if (try_catch.HasCaught()) {
954 tick_info->set_last_threw(true);
955 return Undefined(node_isolate);
963 Handle<Value> MakeCallback(Environment* env,
964 const Handle<Object> object,
967 Handle<Value> argv[]) {
968 Local<Function> callback = object->Get(index).As<Function>();
969 assert(callback->IsFunction());
971 return MakeCallback(env, object, callback, argc, argv);
975 Handle<Value> MakeCallback(Environment* env,
976 const Handle<Object> object,
977 const Handle<String> symbol,
979 Handle<Value> argv[]) {
980 Local<Function> callback = object->Get(symbol).As<Function>();
981 assert(callback->IsFunction());
982 return MakeCallback(env, object, callback, argc, argv);
986 Handle<Value> MakeCallback(Environment* env,
987 const Handle<Object> object,
990 Handle<Value> argv[]) {
991 Local<String> method_string = OneByteString(node_isolate, method);
992 return MakeCallback(env, object, method_string, argc, argv);
996 Handle<Value> MakeCallback(const Handle<Object> object,
999 Handle<Value> argv[]) {
1000 Local<Context> context = object->CreationContext();
1001 Environment* env = Environment::GetCurrent(context);
1002 Context::Scope context_scope(context);
1003 HandleScope handle_scope(env->isolate());
1004 return handle_scope.Close(MakeCallback(env, object, method, argc, argv));
1008 Handle<Value> MakeCallback(const Handle<Object> object,
1009 const Handle<String> symbol,
1011 Handle<Value> argv[]) {
1012 Local<Context> context = object->CreationContext();
1013 Environment* env = Environment::GetCurrent(context);
1014 Context::Scope context_scope(context);
1015 HandleScope handle_scope(env->isolate());
1016 return handle_scope.Close(MakeCallback(env, object, symbol, argc, argv));
1020 Handle<Value> MakeCallback(const Handle<Object> object,
1021 const Handle<Function> callback,
1023 Handle<Value> argv[]) {
1024 Local<Context> context = object->CreationContext();
1025 Environment* env = Environment::GetCurrent(context);
1026 Context::Scope context_scope(context);
1027 HandleScope handle_scope(env->isolate());
1028 return handle_scope.Close(MakeCallback(env, object, callback, argc, argv));
1032 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1033 HandleScope scope(node_isolate);
1035 if (!encoding_v->IsString())
1038 String::Utf8Value encoding(encoding_v);
1040 if (strcasecmp(*encoding, "utf8") == 0) {
1042 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1044 } else if (strcasecmp(*encoding, "ascii") == 0) {
1046 } else if (strcasecmp(*encoding, "base64") == 0) {
1048 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1050 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1052 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1054 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1056 } else if (strcasecmp(*encoding, "binary") == 0) {
1058 } else if (strcasecmp(*encoding, "buffer") == 0) {
1060 } else if (strcasecmp(*encoding, "hex") == 0) {
1062 } else if (strcasecmp(*encoding, "raw") == 0) {
1063 if (!no_deprecation) {
1064 fprintf(stderr, "'raw' (array of integers) has been removed. "
1068 } else if (strcasecmp(*encoding, "raws") == 0) {
1069 if (!no_deprecation) {
1070 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1071 "Please update your code.\n");
1079 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1080 return StringBytes::Encode(static_cast<const char*>(buf),
1085 // Returns -1 if the handle was not valid for decoding
1086 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1087 HandleScope scope(node_isolate);
1089 if (val->IsArray()) {
1090 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1096 return StringBytes::Size(val, encoding);
1100 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1103 // Returns number of bytes written.
1104 ssize_t DecodeWrite(char *buf,
1106 v8::Handle<v8::Value> val,
1107 enum encoding encoding) {
1108 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1111 void DisplayExceptionLine(Handle<Message> message) {
1112 // Prevent re-entry into this function. For example, if there is
1113 // a throw from a program in vm.runInThisContext(code, filename, true),
1114 // then we want to show the original failure, not the secondary one.
1115 static bool displayed_error = false;
1117 if (displayed_error)
1119 displayed_error = true;
1121 uv_tty_reset_mode();
1123 fprintf(stderr, "\n");
1125 if (!message.IsEmpty()) {
1126 // Print (filename):(line number): (message).
1127 String::Utf8Value filename(message->GetScriptResourceName());
1128 const char* filename_string = *filename;
1129 int linenum = message->GetLineNumber();
1130 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1131 // Print line of source code.
1132 String::Utf8Value sourceline(message->GetSourceLine());
1133 const char* sourceline_string = *sourceline;
1135 // Because of how node modules work, all scripts are wrapped with a
1136 // "function (module, exports, __filename, ...) {"
1137 // to provide script local variables.
1139 // When reporting errors on the first line of a script, this wrapper
1140 // function is leaked to the user. There used to be a hack here to
1141 // truncate off the first 62 characters, but it caused numerous other
1142 // problems when vm.runIn*Context() methods were used for non-module
1145 // If we ever decide to re-instate such a hack, the following steps
1148 // 1. Pass a flag around to say "this code was wrapped"
1149 // 2. Update the stack frame output so that it is also correct.
1151 // It would probably be simpler to add a line rather than add some
1152 // number of characters to the first line, since V8 truncates the
1153 // sourceline to 78 characters, and we end up not providing very much
1154 // useful debugging info to the user if we remove 62 characters.
1156 int start = message->GetStartColumn();
1157 int end = message->GetEndColumn();
1159 fprintf(stderr, "%s\n", sourceline_string);
1160 // Print wavy underline (GetUnderline is deprecated).
1161 for (int i = 0; i < start; i++) {
1162 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1164 for (int i = start; i < end; i++) {
1167 fputc('\n', stderr);
1172 static void ReportException(Handle<Value> er, Handle<Message> message) {
1173 HandleScope scope(node_isolate);
1175 DisplayExceptionLine(message);
1177 Local<Value> trace_value(
1178 er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack")));
1179 String::Utf8Value trace(trace_value);
1181 // range errors have a trace member set to undefined
1182 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1183 fprintf(stderr, "%s\n", *trace);
1185 // this really only happens for RangeErrors, since they're the only
1186 // kind that won't have all this info in the trace, or when non-Error
1187 // objects are thrown manually.
1188 Local<Value> message;
1191 if (er->IsObject()) {
1192 Local<Object> err_obj = er.As<Object>();
1193 message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1194 name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1197 if (message.IsEmpty() ||
1198 message->IsUndefined() ||
1200 name->IsUndefined()) {
1201 // Not an error object. Just print as-is.
1202 String::Utf8Value message(er);
1203 fprintf(stderr, "%s\n", *message);
1205 String::Utf8Value name_string(name);
1206 String::Utf8Value message_string(message);
1207 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1215 static void ReportException(const TryCatch& try_catch) {
1216 ReportException(try_catch.Exception(), try_catch.Message());
1220 // Executes a str within the current v8 context.
1221 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1222 HandleScope scope(node_isolate);
1225 // try_catch must be nonverbose to disable FatalException() handler,
1226 // we will handle exceptions ourself.
1227 try_catch.SetVerbose(false);
1229 Local<v8::Script> script = v8::Script::Compile(source, filename);
1230 if (script.IsEmpty()) {
1231 ReportException(try_catch);
1235 Local<Value> result = script->Run();
1236 if (result.IsEmpty()) {
1237 ReportException(try_catch);
1241 return scope.Close(result);
1245 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1246 HandleScope scope(node_isolate);
1248 Local<Array> ary = Array::New();
1252 QUEUE_FOREACH(q, &req_wrap_queue) {
1253 ReqWrap<uv_req_t>* w = CONTAINER_OF(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1254 if (w->persistent().IsEmpty())
1256 ary->Set(i++, w->object());
1259 args.GetReturnValue().Set(ary);
1263 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1264 // implemented here for consistency with GetActiveRequests().
1265 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1266 HandleScope scope(node_isolate);
1268 Local<Array> ary = Array::New();
1272 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1274 QUEUE_FOREACH(q, &handle_wrap_queue) {
1275 HandleWrap* w = CONTAINER_OF(q, HandleWrap, handle_wrap_queue_);
1276 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref))
1278 Local<Object> object = w->object();
1279 Local<Value> owner = object->Get(owner_sym);
1280 if (owner->IsUndefined())
1282 ary->Set(i++, owner);
1285 args.GetReturnValue().Set(ary);
1289 static void Abort(const FunctionCallbackInfo<Value>& args) {
1294 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1295 HandleScope scope(node_isolate);
1297 if (args.Length() != 1 || !args[0]->IsString()) {
1298 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1301 String::Utf8Value path(args[0]);
1302 int err = uv_chdir(*path);
1304 return ThrowUVException(err, "uv_chdir");
1309 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1310 HandleScope scope(node_isolate);
1312 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1313 char buf[MAX_PATH * 4 + 1];
1315 char buf[PATH_MAX + 1];
1318 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1320 return ThrowUVException(err, "uv_cwd");
1323 buf[ARRAY_SIZE(buf) - 1] = '\0';
1324 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1326 args.GetReturnValue().Set(cwd);
1330 static void Umask(const FunctionCallbackInfo<Value>& args) {
1331 HandleScope scope(node_isolate);
1334 if (args.Length() < 1 || args[0]->IsUndefined()) {
1336 umask(static_cast<mode_t>(old));
1337 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1338 return ThrowTypeError("argument must be an integer or octal string.");
1341 if (args[0]->IsInt32()) {
1342 oct = args[0]->Uint32Value();
1345 String::Utf8Value str(args[0]);
1347 // Parse the octal string.
1348 for (int i = 0; i < str.length(); i++) {
1350 if (c > '7' || c < '0') {
1351 return ThrowTypeError("invalid octal string");
1357 old = umask(static_cast<mode_t>(oct));
1360 args.GetReturnValue().Set(old);
1364 #if defined(__POSIX__) && !defined(__ANDROID__)
1366 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1367 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1370 static uid_t uid_by_name(const char* name) {
1378 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1382 return uid_not_found;
1386 static char* name_by_uid(uid_t uid) {
1395 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1396 return strdup(pp->pw_name);
1407 static gid_t gid_by_name(const char* name) {
1415 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1419 return gid_not_found;
1423 #if 0 // For future use.
1424 static const char* name_by_gid(gid_t gid) {
1433 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1434 return strdup(pp->gr_name);
1446 static uid_t uid_by_name(Handle<Value> value) {
1447 if (value->IsUint32()) {
1448 return static_cast<uid_t>(value->Uint32Value());
1450 String::Utf8Value name(value);
1451 return uid_by_name(*name);
1456 static gid_t gid_by_name(Handle<Value> value) {
1457 if (value->IsUint32()) {
1458 return static_cast<gid_t>(value->Uint32Value());
1460 String::Utf8Value name(value);
1461 return gid_by_name(*name);
1466 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1467 // uid_t is an uint32_t on all supported platforms.
1468 args.GetReturnValue().Set(static_cast<uint32_t>(getuid()));
1472 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1473 // gid_t is an uint32_t on all supported platforms.
1474 args.GetReturnValue().Set(static_cast<uint32_t>(getgid()));
1478 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1479 HandleScope scope(node_isolate);
1481 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1482 return ThrowTypeError("setgid argument must be a number or a string");
1485 gid_t gid = gid_by_name(args[0]);
1487 if (gid == gid_not_found) {
1488 return ThrowError("setgid group id does not exist");
1492 return ThrowErrnoException(errno, "setgid");
1497 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1498 HandleScope scope(node_isolate);
1500 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1501 return ThrowTypeError("setuid argument must be a number or a string");
1504 uid_t uid = uid_by_name(args[0]);
1506 if (uid == uid_not_found) {
1507 return ThrowError("setuid user id does not exist");
1511 return ThrowErrnoException(errno, "setuid");
1516 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1517 HandleScope scope(node_isolate);
1519 int ngroups = getgroups(0, NULL);
1521 if (ngroups == -1) {
1522 return ThrowErrnoException(errno, "getgroups");
1525 gid_t* groups = new gid_t[ngroups];
1527 ngroups = getgroups(ngroups, groups);
1529 if (ngroups == -1) {
1531 return ThrowErrnoException(errno, "getgroups");
1534 Local<Array> groups_list = Array::New(ngroups);
1535 bool seen_egid = false;
1536 gid_t egid = getegid();
1538 for (int i = 0; i < ngroups; i++) {
1539 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1540 if (groups[i] == egid)
1546 if (seen_egid == false) {
1547 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1550 args.GetReturnValue().Set(groups_list);
1554 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1555 HandleScope scope(node_isolate);
1557 if (!args[0]->IsArray()) {
1558 return ThrowTypeError("argument 1 must be an array");
1561 Local<Array> groups_list = args[0].As<Array>();
1562 size_t size = groups_list->Length();
1563 gid_t* groups = new gid_t[size];
1565 for (size_t i = 0; i < size; i++) {
1566 gid_t gid = gid_by_name(groups_list->Get(i));
1568 if (gid == gid_not_found) {
1570 return ThrowError("group name not found");
1576 int rc = setgroups(size, groups);
1580 return ThrowErrnoException(errno, "setgroups");
1585 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1586 HandleScope scope(node_isolate);
1588 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1589 return ThrowTypeError("argument 1 must be a number or a string");
1592 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1593 return ThrowTypeError("argument 2 must be a number or a string");
1596 String::Utf8Value arg0(args[0]);
1601 if (args[0]->IsUint32()) {
1602 user = name_by_uid(args[0]->Uint32Value());
1610 return ThrowError("initgroups user not found");
1613 extra_group = gid_by_name(args[1]);
1615 if (extra_group == gid_not_found) {
1618 return ThrowError("initgroups extra group not found");
1621 int rc = initgroups(user, extra_group);
1628 return ThrowErrnoException(errno, "initgroups");
1632 #endif // __POSIX__ && !defined(__ANDROID__)
1635 void Exit(const FunctionCallbackInfo<Value>& args) {
1636 HandleScope scope(node_isolate);
1637 exit(args[0]->IntegerValue());
1641 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1642 HandleScope scope(node_isolate);
1644 if (uv_uptime(&uptime))
1646 args.GetReturnValue().Set(uptime - prog_start_time);
1650 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1651 HandleScope handle_scope(args.GetIsolate());
1652 Environment* env = Environment::GetCurrent(args.GetIsolate());
1655 int err = uv_resident_set_memory(&rss);
1657 return ThrowUVException(err, "uv_resident_set_memory");
1661 HeapStatistics v8_heap_stats;
1662 node_isolate->GetHeapStatistics(&v8_heap_stats);
1664 Local<Integer> heap_total =
1665 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(), node_isolate);
1666 Local<Integer> heap_used =
1667 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(), node_isolate);
1669 Local<Object> info = Object::New();
1670 info->Set(env->rss_string(), Number::New(node_isolate, rss));
1671 info->Set(env->heap_total_string(), heap_total);
1672 info->Set(env->heap_used_string(), heap_used);
1674 args.GetReturnValue().Set(info);
1678 void Kill(const FunctionCallbackInfo<Value>& args) {
1679 HandleScope scope(node_isolate);
1681 if (args.Length() != 2) {
1682 return ThrowError("Bad argument.");
1685 int pid = args[0]->IntegerValue();
1686 int sig = args[1]->Int32Value();
1687 int err = uv_kill(pid, sig);
1688 args.GetReturnValue().Set(err);
1691 // used in Hrtime() below
1692 #define NANOS_PER_SEC 1000000000
1694 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1695 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1696 // so this function instead returns an Array with 2 entries representing seconds
1697 // and nanoseconds, to avoid any integer overflow possibility.
1698 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1699 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1700 HandleScope scope(node_isolate);
1702 uint64_t t = uv_hrtime();
1704 if (args.Length() > 0) {
1705 // return a time diff tuple
1706 if (!args[0]->IsArray()) {
1707 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1709 Local<Array> inArray = Local<Array>::Cast(args[0]);
1710 uint64_t seconds = inArray->Get(0)->Uint32Value();
1711 uint64_t nanos = inArray->Get(1)->Uint32Value();
1712 t -= (seconds * NANOS_PER_SEC) + nanos;
1715 Local<Array> tuple = Array::New(2);
1716 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1717 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1718 args.GetReturnValue().Set(tuple);
1722 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1724 // DLOpen is process.dlopen(module, filename).
1725 // Used to load 'module.node' dynamically shared objects.
1727 // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
1728 // when two contexts try to load the same shared object. Maybe have a shadow
1729 // cache that's a plain C list or hash table that's shared across contexts?
1730 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1731 HandleScope handle_scope(args.GetIsolate());
1732 Environment* env = Environment::GetCurrent(args.GetIsolate());
1733 char symbol[1024], *base, *pos;
1737 if (args.Length() < 2) {
1738 return ThrowError("process.dlopen takes exactly 2 arguments.");
1741 Local<Object> module = args[0]->ToObject(); // Cast
1742 String::Utf8Value filename(args[1]); // Cast
1744 Local<String> exports_string = env->exports_string();
1745 Local<Object> exports = module->Get(exports_string)->ToObject();
1747 if (uv_dlopen(*filename, &lib)) {
1748 Local<String> errmsg = OneByteString(env->isolate(), uv_dlerror(&lib));
1750 // Windows needs to add the filename into the error message
1751 errmsg = String::Concat(errmsg, args[1]->ToString());
1753 ThrowException(Exception::Error(errmsg));
1757 String::Utf8Value path(args[1]);
1760 /* Find the shared library filename within the full path. */
1762 pos = strrchr(base, '/');
1768 pos = strpbrk(base, "\\/:");
1776 /* Strip the .node extension. */
1777 pos = strrchr(base, '.');
1782 /* Add the `_module` suffix to the extension name. */
1783 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1784 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1785 return ThrowError("Out of memory.");
1788 /* Replace dashes with underscores. When loading foo-bar.node,
1789 * look for foo_bar_module, not foo-bar_module.
1791 for (pos = symbol; *pos != '\0'; ++pos) {
1796 node_module_struct *mod;
1797 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1799 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1800 return ThrowError(errmsg);
1803 if (mod->version != NODE_MODULE_VERSION) {
1807 "Module version mismatch. Expected %d, got %d.",
1808 NODE_MODULE_VERSION, mod->version);
1809 return ThrowError(errmsg);
1812 // Execute the C++ module
1813 if (mod->register_context_func != NULL) {
1814 mod->register_context_func(exports, module, env->context());
1815 } else if (mod->register_func != NULL) {
1816 mod->register_func(exports, module);
1818 return ThrowError("Module has no declared entry point.");
1821 // Tell coverity that 'handle' should not be freed when we return.
1822 // coverity[leaked_storage]
1826 static void OnFatalError(const char* location, const char* message) {
1828 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1830 fprintf(stderr, "FATAL ERROR: %s\n", message);
1840 NO_RETURN void FatalError(const char* location, const char* message) {
1841 OnFatalError(location, message);
1842 // to supress compiler warning
1847 void FatalException(Handle<Value> error, Handle<Message> message) {
1848 HandleScope scope(node_isolate);
1850 Environment* env = Environment::GetCurrent(node_isolate);
1851 Local<Object> process_object = env->process_object();
1852 Local<String> fatal_exception_string = env->fatal_exception_string();
1853 Local<Function> fatal_exception_function =
1854 process_object->Get(fatal_exception_string).As<Function>();
1856 if (!fatal_exception_function->IsFunction()) {
1857 // failed before the process._fatalException function was added!
1858 // this is probably pretty bad. Nothing to do but report and exit.
1859 ReportException(error, message);
1863 TryCatch fatal_try_catch;
1865 // Do not call FatalException when _fatalException handler throws
1866 fatal_try_catch.SetVerbose(false);
1868 // this will return true if the JS layer handled it, false otherwise
1869 Local<Value> caught =
1870 fatal_exception_function->Call(process_object, 1, &error);
1872 if (fatal_try_catch.HasCaught()) {
1873 // the fatal exception function threw, so we must exit
1874 ReportException(fatal_try_catch);
1878 if (false == caught->BooleanValue()) {
1879 ReportException(error, message);
1885 void FatalException(const TryCatch& try_catch) {
1886 HandleScope scope(node_isolate);
1887 // TODO(bajtos) do not call FatalException if try_catch is verbose
1888 // (requires V8 API to expose getter for try_catch.is_verbose_)
1889 FatalException(try_catch.Exception(), try_catch.Message());
1893 void OnMessage(Handle<Message> message, Handle<Value> error) {
1894 // The current version of V8 sends messages for errors only
1895 // (thus `error` is always set).
1896 FatalException(error, message);
1900 static void Binding(const FunctionCallbackInfo<Value>& args) {
1901 HandleScope handle_scope(args.GetIsolate());
1902 Environment* env = Environment::GetCurrent(args.GetIsolate());
1904 Local<String> module = args[0]->ToString();
1905 String::Utf8Value module_v(module);
1907 Local<Object> cache = env->binding_cache_object();
1908 Local<Object> exports;
1910 if (cache->Has(module)) {
1911 exports = cache->Get(module)->ToObject();
1912 args.GetReturnValue().Set(exports);
1916 // Append a string to process.moduleLoadList
1918 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
1920 Local<Array> modules = env->module_load_list_array();
1921 uint32_t l = modules->Length();
1922 modules->Set(l, OneByteString(node_isolate, buf));
1924 node_module_struct* mod = get_builtin_module(*module_v);
1926 exports = Object::New();
1927 // Internal bindings don't have a "module" object, only exports.
1928 assert(mod->register_func == NULL);
1929 assert(mod->register_context_func != NULL);
1930 Local<Value> unused = Undefined(env->isolate());
1931 mod->register_context_func(exports, unused, env->context());
1932 cache->Set(module, exports);
1933 } else if (!strcmp(*module_v, "constants")) {
1934 exports = Object::New();
1935 DefineConstants(exports);
1936 cache->Set(module, exports);
1937 } else if (!strcmp(*module_v, "natives")) {
1938 exports = Object::New();
1939 DefineJavaScript(exports);
1940 cache->Set(module, exports);
1942 return ThrowError("No such module");
1945 args.GetReturnValue().Set(exports);
1949 static void ProcessTitleGetter(Local<String> property,
1950 const PropertyCallbackInfo<Value>& info) {
1951 HandleScope scope(node_isolate);
1953 uv_get_process_title(buffer, sizeof(buffer));
1954 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
1958 static void ProcessTitleSetter(Local<String> property,
1960 const PropertyCallbackInfo<void>& info) {
1961 HandleScope scope(node_isolate);
1962 String::Utf8Value title(value);
1963 // TODO(piscisaureus): protect with a lock
1964 uv_set_process_title(*title);
1968 static void EnvGetter(Local<String> property,
1969 const PropertyCallbackInfo<Value>& info) {
1970 HandleScope scope(node_isolate);
1972 String::Utf8Value key(property);
1973 const char* val = getenv(*key);
1975 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
1978 String::Value key(property);
1979 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
1980 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
1982 ARRAY_SIZE(buffer));
1983 // If result >= sizeof buffer the buffer was too small. That should never
1984 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
1986 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
1987 result < ARRAY_SIZE(buffer)) {
1988 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
1989 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
1990 return info.GetReturnValue().Set(rc);
1993 // Not found. Fetch from prototype.
1994 info.GetReturnValue().Set(
1995 info.Data().As<Object>()->Get(property));
1999 static void EnvSetter(Local<String> property,
2001 const PropertyCallbackInfo<Value>& info) {
2002 HandleScope scope(node_isolate);
2004 String::Utf8Value key(property);
2005 String::Utf8Value val(value);
2006 setenv(*key, *val, 1);
2008 String::Value key(property);
2009 String::Value val(value);
2010 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2011 // Environment variables that start with '=' are read-only.
2012 if (key_ptr[0] != L'=') {
2013 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2016 // Whether it worked or not, always return rval.
2017 info.GetReturnValue().Set(value);
2021 static void EnvQuery(Local<String> property,
2022 const PropertyCallbackInfo<Integer>& info) {
2023 HandleScope scope(node_isolate);
2024 int32_t rc = -1; // Not found unless proven otherwise.
2026 String::Utf8Value key(property);
2030 String::Value key(property);
2031 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2032 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2033 GetLastError() == ERROR_SUCCESS) {
2035 if (key_ptr[0] == L'=') {
2036 // Environment variables that start with '=' are hidden and read-only.
2037 rc = static_cast<int32_t>(v8::ReadOnly) |
2038 static_cast<int32_t>(v8::DontDelete) |
2039 static_cast<int32_t>(v8::DontEnum);
2044 info.GetReturnValue().Set(rc);
2048 static void EnvDeleter(Local<String> property,
2049 const PropertyCallbackInfo<Boolean>& info) {
2050 HandleScope scope(node_isolate);
2053 String::Utf8Value key(property);
2054 rc = getenv(*key) != NULL;
2058 String::Value key(property);
2059 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2060 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2061 // Deletion failed. Return true if the key wasn't there in the first place,
2062 // false if it is still there.
2063 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2064 GetLastError() != ERROR_SUCCESS;
2067 info.GetReturnValue().Set(rc);
2071 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2072 HandleScope scope(node_isolate);
2075 while (environ[size])
2078 Local<Array> env = Array::New(size);
2080 for (int i = 0; i < size; ++i) {
2081 const char* var = environ[i];
2082 const char* s = strchr(var, '=');
2083 const int length = s ? s - var : strlen(var);
2084 Local<String> name = String::NewFromUtf8(node_isolate,
2086 String::kNormalString,
2091 WCHAR* environment = GetEnvironmentStringsW();
2092 if (environment == NULL)
2093 return; // This should not happen.
2094 Local<Array> env = Array::New();
2095 WCHAR* p = environment;
2097 while (*p != NULL) {
2100 // If the key starts with '=' it is a hidden environment variable.
2104 s = wcschr(p, L'=');
2109 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2110 const size_t two_byte_buffer_len = s - p;
2111 Local<String> value = String::NewFromTwoByte(node_isolate,
2113 String::kNormalString,
2114 two_byte_buffer_len);
2115 env->Set(i++, value);
2116 p = s + wcslen(s) + 1;
2118 FreeEnvironmentStringsW(environment);
2121 info.GetReturnValue().Set(env);
2125 static Handle<Object> GetFeatures() {
2126 HandleScope scope(node_isolate);
2128 Local<Object> obj = Object::New();
2129 #if defined(DEBUG) && DEBUG
2130 Local<Value> debug = True(node_isolate);
2132 Local<Value> debug = False(node_isolate);
2133 #endif // defined(DEBUG) && DEBUG
2135 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2137 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2138 // TODO(bnoordhuis) ping libuv
2139 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2141 #ifdef OPENSSL_NPN_NEGOTIATED
2142 Local<Boolean> tls_npn = True(node_isolate);
2144 Local<Boolean> tls_npn = False(node_isolate);
2146 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"), tls_npn);
2148 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2149 Local<Boolean> tls_sni = True(node_isolate);
2151 Local<Boolean> tls_sni = False(node_isolate);
2153 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"), tls_sni);
2155 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2156 Boolean::New(get_builtin_module("crypto") != NULL));
2158 return scope.Close(obj);
2162 static void DebugPortGetter(Local<String> property,
2163 const PropertyCallbackInfo<Value>& info) {
2164 HandleScope scope(node_isolate);
2165 info.GetReturnValue().Set(debug_port);
2169 static void DebugPortSetter(Local<String> property,
2171 const PropertyCallbackInfo<void>& info) {
2172 HandleScope scope(node_isolate);
2173 debug_port = value->NumberValue();
2177 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2178 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2179 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2182 void NeedImmediateCallbackGetter(Local<String> property,
2183 const PropertyCallbackInfo<Value>& info) {
2184 HandleScope handle_scope(info.GetIsolate());
2185 Environment* env = Environment::GetCurrent(info.GetIsolate());
2186 const uv_check_t* immediate_check_handle = env->immediate_check_handle();
2187 bool active = uv_is_active(
2188 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2189 info.GetReturnValue().Set(active);
2193 static void NeedImmediateCallbackSetter(
2194 Local<String> property,
2196 const PropertyCallbackInfo<void>& info) {
2197 HandleScope handle_scope(info.GetIsolate());
2198 Environment* env = Environment::GetCurrent(info.GetIsolate());
2200 uv_check_t* immediate_check_handle = env->immediate_check_handle();
2201 bool active = uv_is_active(
2202 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2204 if (active == value->BooleanValue())
2207 uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
2210 uv_check_stop(immediate_check_handle);
2211 uv_idle_stop(immediate_idle_handle);
2213 uv_check_start(immediate_check_handle, CheckImmediate);
2214 // Idle handle is needed only to stop the event loop from blocking in poll.
2215 uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
2220 void SetIdle(uv_prepare_t* handle, int) {
2221 Environment* env = Environment::from_idle_prepare_handle(handle);
2222 env->isolate()->GetCpuProfiler()->SetIdle(true);
2226 void ClearIdle(uv_check_t* handle, int) {
2227 Environment* env = Environment::from_idle_check_handle(handle);
2228 env->isolate()->GetCpuProfiler()->SetIdle(false);
2232 void StartProfilerIdleNotifier(Environment* env) {
2233 uv_prepare_start(env->idle_prepare_handle(), SetIdle);
2234 uv_check_start(env->idle_check_handle(), ClearIdle);
2238 void StopProfilerIdleNotifier(Environment* env) {
2239 uv_prepare_stop(env->idle_prepare_handle());
2240 uv_check_stop(env->idle_check_handle());
2244 void StartProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2245 HandleScope handle_scope(args.GetIsolate());
2246 Environment* env = Environment::GetCurrent(args.GetIsolate());
2247 StartProfilerIdleNotifier(env);
2251 void StopProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2252 HandleScope handle_scope(args.GetIsolate());
2253 Environment* env = Environment::GetCurrent(args.GetIsolate());
2254 StopProfilerIdleNotifier(env);
2258 #define READONLY_PROPERTY(obj, str, var) \
2260 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2264 void SetupProcessObject(Environment* env,
2266 const char* const* argv,
2268 const char* const* exec_argv) {
2269 HandleScope scope(node_isolate);
2271 Local<Object> process = env->process_object();
2273 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2275 ProcessTitleSetter);
2278 READONLY_PROPERTY(process,
2280 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2282 // process.moduleLoadList
2283 READONLY_PROPERTY(process,
2285 env->module_load_list_array());
2288 Local<Object> versions = Object::New();
2289 READONLY_PROPERTY(process, "versions", versions);
2291 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2293 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2294 READONLY_PROPERTY(versions,
2296 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2298 // +1 to get rid of the leading 'v'
2299 READONLY_PROPERTY(versions,
2301 OneByteString(node_isolate, NODE_VERSION + 1));
2302 READONLY_PROPERTY(versions,
2304 OneByteString(node_isolate, V8::GetVersion()));
2305 READONLY_PROPERTY(versions,
2307 OneByteString(node_isolate, uv_version_string()));
2308 READONLY_PROPERTY(versions,
2310 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2312 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2313 READONLY_PROPERTY(versions,
2315 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2318 // Stupid code to slice out the version string.
2319 { // NOLINT(whitespace/braces)
2322 for (i = j = 0, k = sizeof(OPENSSL_VERSION_TEXT) - 1; i < k; ++i) {
2323 c = OPENSSL_VERSION_TEXT[i];
2324 if ('0' <= c && c <= '9') {
2325 for (j = i + 1; j < k; ++j) {
2326 c = OPENSSL_VERSION_TEXT[j];
2336 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2341 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2344 READONLY_PROPERTY(process,
2346 OneByteString(node_isolate, PLATFORM));
2349 Local<Array> arguments = Array::New(argc);
2350 for (int i = 0; i < argc; ++i) {
2351 arguments->Set(i, String::NewFromUtf8(node_isolate, argv[i]));
2353 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2356 Local<Array> exec_arguments = Array::New(exec_argc);
2357 for (int i = 0; i < exec_argc; ++i) {
2358 exec_arguments->Set(i, String::NewFromUtf8(node_isolate, exec_argv[i]));
2360 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_arguments);
2362 // create process.env
2363 Local<ObjectTemplate> process_env_template = ObjectTemplate::New();
2364 process_env_template->SetNamedPropertyHandler(EnvGetter,
2370 Local<Object> process_env = process_env_template->NewInstance();
2371 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), process_env);
2373 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2374 READONLY_PROPERTY(process, "features", GetFeatures());
2375 process->SetAccessor(
2376 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2377 NeedImmediateCallbackGetter,
2378 NeedImmediateCallbackSetter);
2382 READONLY_PROPERTY(process,
2384 String::NewFromUtf8(node_isolate, eval_string));
2389 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2392 // -i, --interactive
2394 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2398 if (no_deprecation) {
2399 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2402 // --throw-deprecation
2403 if (throw_deprecation) {
2404 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2407 // --trace-deprecation
2408 if (trace_deprecation) {
2409 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2412 size_t exec_path_len = 2 * PATH_MAX;
2413 char* exec_path = new char[exec_path_len];
2414 Local<String> exec_path_value;
2415 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2416 exec_path_value = String::NewFromUtf8(node_isolate,
2418 String::kNormalString,
2421 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2423 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2427 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2431 // define various internal methods
2432 NODE_SET_METHOD(process,
2433 "_startProfilerIdleNotifier",
2434 StartProfilerIdleNotifier);
2435 NODE_SET_METHOD(process,
2436 "_stopProfilerIdleNotifier",
2437 StopProfilerIdleNotifier);
2438 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2439 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2440 NODE_SET_METHOD(process, "reallyExit", Exit);
2441 NODE_SET_METHOD(process, "abort", Abort);
2442 NODE_SET_METHOD(process, "chdir", Chdir);
2443 NODE_SET_METHOD(process, "cwd", Cwd);
2445 NODE_SET_METHOD(process, "umask", Umask);
2447 #if defined(__POSIX__) && !defined(__ANDROID__)
2448 NODE_SET_METHOD(process, "getuid", GetUid);
2449 NODE_SET_METHOD(process, "setuid", SetUid);
2451 NODE_SET_METHOD(process, "setgid", SetGid);
2452 NODE_SET_METHOD(process, "getgid", GetGid);
2454 NODE_SET_METHOD(process, "getgroups", GetGroups);
2455 NODE_SET_METHOD(process, "setgroups", SetGroups);
2456 NODE_SET_METHOD(process, "initgroups", InitGroups);
2457 #endif // __POSIX__ && !defined(__ANDROID__)
2459 NODE_SET_METHOD(process, "_kill", Kill);
2461 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2462 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2463 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2465 NODE_SET_METHOD(process, "hrtime", Hrtime);
2467 NODE_SET_METHOD(process, "dlopen", DLOpen);
2469 NODE_SET_METHOD(process, "uptime", Uptime);
2470 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2472 NODE_SET_METHOD(process, "binding", Binding);
2474 NODE_SET_METHOD(process, "_setupAsyncListener", SetupAsyncListener);
2475 NODE_SET_METHOD(process, "_setupNextTick", SetupNextTick);
2477 // values use to cross communicate with processNextTick
2478 Local<Object> tick_info_obj = Object::New();
2479 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
2480 env->tick_info()->fields(),
2481 kExternalUnsignedIntArray,
2482 env->tick_info()->fields_count());
2483 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfo"), tick_info_obj);
2485 // pre-set _events object for faster emit checks
2486 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2490 #undef READONLY_PROPERTY
2493 static void AtExit() {
2494 uv_tty_reset_mode();
2498 static void SignalExit(int signal) {
2499 uv_tty_reset_mode();
2500 _exit(128 + signal);
2504 // Most of the time, it's best to use `console.error` to write
2505 // to the process.stderr stream. However, in some cases, such as
2506 // when debugging the stream.Writable class or the process.nextTick
2507 // function, it is useful to bypass JavaScript entirely.
2508 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2509 HandleScope scope(node_isolate);
2511 assert(args.Length() == 1 && args[0]->IsString() &&
2512 "must be called with a single string");
2514 String::Utf8Value message(args[0]);
2515 fprintf(stderr, "%s\n", *message);
2520 void Load(Environment* env) {
2521 HandleScope handle_scope(node_isolate);
2523 // Compile, execute the src/node.js file. (Which was included as static C
2524 // string in node_natives.h. 'natve_node' is the string containing that
2527 // The node.js file returns a function 'f'
2532 // Disable verbose mode to stop FatalException() handler from trying
2533 // to handle the exception. Errors this early in the start-up phase
2534 // are not safe to ignore.
2535 try_catch.SetVerbose(false);
2537 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2538 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2539 if (try_catch.HasCaught()) {
2540 ReportException(try_catch);
2543 assert(f_value->IsFunction());
2544 Local<Function> f = Local<Function>::Cast(f_value);
2546 // Now we call 'f' with the 'process' variable that we've built up with
2547 // all our bindings. Inside node.js we'll take care of assigning things to
2550 // We start the process this way in order to be more modular. Developers
2551 // who do not like how 'src/node.js' setups the module system but do like
2552 // Node's I/O bindings may want to replace 'f' with their own function.
2554 // Add a reference to the global object
2555 Local<Object> global = env->context()->Global();
2557 #if defined HAVE_DTRACE || defined HAVE_ETW
2561 #if defined HAVE_PERFCTR
2562 InitPerfCounters(global);
2565 // Enable handling of uncaught exceptions
2566 // (FatalException(), break on uncaught exception in debugger)
2568 // This is not strictly necessary since it's almost impossible
2569 // to attach the debugger fast enought to break on exception
2570 // thrown during process startup.
2571 try_catch.SetVerbose(true);
2573 NODE_SET_METHOD(env->process_object(), "_rawDebug", RawDebug);
2575 Local<Value> arg = env->process_object();
2576 f->Call(global, 1, &arg);
2579 static void PrintHelp();
2581 static void ParseDebugOpt(const char* arg) {
2584 if (strstr(arg, "--debug-port=") == arg) {
2585 p = 1 + strchr(arg, '=');
2586 debug_port = atoi(p);
2588 use_debug_agent = true;
2589 if (!strcmp(arg, "--debug-brk")) {
2590 debug_wait_connect = true;
2592 } else if (!strcmp(arg, "--debug")) {
2594 } else if (strstr(arg, "--debug-brk=") == arg) {
2595 debug_wait_connect = true;
2596 p = 1 + strchr(arg, '=');
2597 debug_port = atoi(p);
2598 } else if (strstr(arg, "--debug=") == arg) {
2599 p = 1 + strchr(arg, '=');
2600 debug_port = atoi(p);
2603 if (p && debug_port > 1024 && debug_port < 65536)
2606 fprintf(stderr, "Bad debug option.\n");
2608 fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2614 static void PrintHelp() {
2615 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2616 " node debug script.js [arguments] \n"
2619 " -v, --version print node's version\n"
2620 " -e, --eval script evaluate script\n"
2621 " -p, --print evaluate script and print result\n"
2622 " -i, --interactive always enter the REPL even if stdin\n"
2623 " does not appear to be a terminal\n"
2624 " --no-deprecation silence deprecation warnings\n"
2625 " --trace-deprecation show stack traces on deprecations\n"
2626 " --v8-options print v8 command line options\n"
2627 " --max-stack-size=val set max v8 stack size (bytes)\n"
2629 "Environment variables:\n"
2631 "NODE_PATH ';'-separated list of directories\n"
2633 "NODE_PATH ':'-separated list of directories\n"
2635 " prefixed to the module search path.\n"
2636 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2637 " global contexts.\n"
2638 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2640 "Documentation can be found at http://nodejs.org/\n");
2644 // Parse command line arguments.
2646 // argv is modified in place. exec_argv and v8_argv are out arguments that
2647 // ParseArgs() allocates memory for and stores a pointer to the output
2648 // vector in. The caller should free them with delete[].
2652 // * argv contains the arguments with node and V8 options filtered out.
2653 // * exec_argv contains both node and V8 options and nothing else.
2654 // * v8_argv contains argv[0] plus any V8 options
2655 static void ParseArgs(int* argc,
2658 const char*** exec_argv,
2660 const char*** v8_argv) {
2661 const unsigned int nargs = static_cast<unsigned int>(*argc);
2662 const char** new_exec_argv = new const char*[nargs];
2663 const char** new_v8_argv = new const char*[nargs];
2664 const char** new_argv = new const char*[nargs];
2666 for (unsigned int i = 0; i < nargs; ++i) {
2667 new_exec_argv[i] = NULL;
2668 new_v8_argv[i] = NULL;
2672 // exec_argv starts with the first option, the other two start with argv[0].
2673 unsigned int new_exec_argc = 0;
2674 unsigned int new_v8_argc = 1;
2675 unsigned int new_argc = 1;
2676 new_v8_argv[0] = argv[0];
2677 new_argv[0] = argv[0];
2679 unsigned int index = 1;
2680 while (index < nargs && argv[index][0] == '-') {
2681 const char* const arg = argv[index];
2682 unsigned int args_consumed = 1;
2684 if (strstr(arg, "--debug") == arg) {
2686 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2687 printf("%s\n", NODE_VERSION);
2689 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2692 } else if (strcmp(arg, "--eval") == 0 ||
2693 strcmp(arg, "-e") == 0 ||
2694 strcmp(arg, "--print") == 0 ||
2695 strcmp(arg, "-pe") == 0 ||
2696 strcmp(arg, "-p") == 0) {
2697 bool is_eval = strchr(arg, 'e') != NULL;
2698 bool is_print = strchr(arg, 'p') != NULL;
2699 print_eval = print_eval || is_print;
2700 // --eval, -e and -pe always require an argument.
2701 if (is_eval == true) {
2703 eval_string = argv[index + 1];
2704 if (eval_string == NULL) {
2705 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
2708 } else if (argv[index + 1] != NULL && argv[index + 1][0] != '-') {
2710 eval_string = argv[index + 1];
2711 if (strncmp(eval_string, "\\-", 2) == 0) {
2712 // Starts with "\\-": escaped expression, drop the backslash.
2716 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2718 } else if (strcmp(arg, "--no-deprecation") == 0) {
2719 no_deprecation = true;
2720 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2721 trace_deprecation = true;
2722 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2723 throw_deprecation = true;
2724 } else if (strcmp(arg, "--v8-options") == 0) {
2725 new_v8_argv[new_v8_argc] = "--help";
2728 // V8 option. Pass through as-is.
2729 new_v8_argv[new_v8_argc] = arg;
2733 memcpy(new_exec_argv + new_exec_argc,
2735 args_consumed * sizeof(*argv));
2737 new_exec_argc += args_consumed;
2738 index += args_consumed;
2741 // Copy remaining arguments.
2742 const unsigned int args_left = nargs - index;
2743 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
2744 new_argc += args_left;
2746 *exec_argc = new_exec_argc;
2747 *exec_argv = new_exec_argv;
2748 *v8_argc = new_v8_argc;
2749 *v8_argv = new_v8_argv;
2751 // Copy new_argv over argv and update argc.
2752 memcpy(argv, new_argv, new_argc * sizeof(*argv));
2754 *argc = static_cast<int>(new_argc);
2758 // Called from V8 Debug Agent TCP thread.
2759 static void DispatchMessagesDebugAgentCallback() {
2760 uv_async_send(&dispatch_debug_messages_async);
2764 // Called from the main thread.
2765 static void EnableDebug(bool wait_connect) {
2766 assert(debugger_running == false);
2767 Isolate* isolate = node_isolate; // TODO(bnoordhuis) Multi-isolate support.
2768 Isolate::Scope isolate_scope(isolate);
2769 HandleScope handle_scope(isolate);
2770 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2772 debugger_running = v8::Debug::EnableAgent("node " NODE_VERSION,
2775 if (debugger_running == false) {
2776 fprintf(stderr, "Starting debugger on port %d failed\n", debug_port);
2780 fprintf(stderr, "Debugger listening on port %d\n", debug_port);
2783 Environment* env = Environment::GetCurrentChecked(isolate);
2785 return; // Still starting up.
2787 Context::Scope context_scope(env->context());
2788 Local<Object> message = Object::New();
2789 message->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "cmd"),
2790 FIXED_ONE_BYTE_STRING(env->isolate(), "NODE_DEBUG_ENABLED"));
2791 Local<Value> argv[] = {
2792 FIXED_ONE_BYTE_STRING(env->isolate(), "internalMessage"),
2795 MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(argv), argv);
2799 // Called from the main thread.
2800 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2801 if (debugger_running == false) {
2802 fprintf(stderr, "Starting debugger agent.\n");
2805 Isolate::Scope isolate_scope(node_isolate);
2806 v8::Debug::ProcessDebugMessages();
2811 static volatile sig_atomic_t caught_early_debug_signal;
2814 static void EarlyDebugSignalHandler(int signo) {
2815 caught_early_debug_signal = 1;
2819 static void InstallEarlyDebugSignalHandler() {
2820 struct sigaction sa;
2821 memset(&sa, 0, sizeof(sa));
2822 sa.sa_handler = EarlyDebugSignalHandler;
2823 sigaction(SIGUSR1, &sa, NULL);
2827 static void EnableDebugSignalHandler(int signo) {
2828 // Call only async signal-safe functions here!
2829 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
2830 uv_async_send(&dispatch_debug_messages_async);
2834 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2835 struct sigaction sa;
2836 memset(&sa, 0, sizeof(sa));
2837 sa.sa_handler = handler;
2838 sigfillset(&sa.sa_mask);
2839 sigaction(signal, &sa, NULL);
2843 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2844 HandleScope scope(node_isolate);
2846 if (args.Length() != 1) {
2847 return ThrowError("Invalid number of arguments.");
2853 pid = args[0]->IntegerValue();
2854 r = kill(pid, SIGUSR1);
2856 return ThrowErrnoException(errno, "kill");
2861 static int RegisterDebugSignalHandler() {
2862 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
2863 RegisterSignalHandler(SIGUSR1, EnableDebugSignalHandler);
2864 // If we caught a SIGUSR1 during the bootstrap process, re-raise it
2865 // now that the debugger infrastructure is in place.
2866 if (caught_early_debug_signal)
2874 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2875 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
2876 uv_async_send(&dispatch_debug_messages_async);
2881 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2883 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2887 static int RegisterDebugSignalHandler() {
2888 wchar_t mapping_name[32];
2889 HANDLE mapping_handle;
2891 LPTHREAD_START_ROUTINE* handler;
2893 pid = GetCurrentProcessId();
2895 if (GetDebugSignalHandlerMappingName(pid,
2897 ARRAY_SIZE(mapping_name)) < 0) {
2901 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2907 if (mapping_handle == NULL) {
2911 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2912 MapViewOfFile(mapping_handle,
2913 FILE_MAP_ALL_ACCESS,
2917 if (handler == NULL) {
2918 CloseHandle(mapping_handle);
2922 *handler = EnableDebugThreadProc;
2924 UnmapViewOfFile(static_cast<void*>(handler));
2930 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2931 HandleScope scope(node_isolate);
2933 HANDLE process = NULL;
2934 HANDLE thread = NULL;
2935 HANDLE mapping = NULL;
2936 wchar_t mapping_name[32];
2937 LPTHREAD_START_ROUTINE* handler = NULL;
2939 if (args.Length() != 1) {
2940 ThrowError("Invalid number of arguments.");
2944 pid = (DWORD) args[0]->IntegerValue();
2946 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2947 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2951 if (process == NULL) {
2952 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2956 if (GetDebugSignalHandlerMappingName(pid,
2958 ARRAY_SIZE(mapping_name)) < 0) {
2959 ThrowErrnoException(errno, "sprintf");
2963 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2964 if (mapping == NULL) {
2965 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
2969 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2970 MapViewOfFile(mapping,
2975 if (handler == NULL || *handler == NULL) {
2976 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
2980 thread = CreateRemoteThread(process,
2987 if (thread == NULL) {
2988 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
2992 // Wait for the thread to terminate
2993 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
2994 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
2999 if (process != NULL)
3000 CloseHandle(process);
3002 CloseHandle(thread);
3003 if (handler != NULL)
3004 UnmapViewOfFile(handler);
3005 if (mapping != NULL)
3006 CloseHandle(mapping);
3011 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3012 v8::Debug::DebugBreak(node_isolate);
3016 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3017 if (debugger_running) {
3018 v8::Debug::DisableAgent();
3019 debugger_running = false;
3024 void Init(int* argc,
3027 const char*** exec_argv) {
3028 // Initialize prog_start_time to get relative uptime.
3029 uv_uptime(&prog_start_time);
3031 // Make inherited handles noninheritable.
3032 uv_disable_stdio_inheritance();
3034 // init async debug messages dispatching
3035 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3036 uv_async_init(uv_default_loop(),
3037 &dispatch_debug_messages_async,
3038 DispatchDebugMessagesAsyncCallback);
3039 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3041 // Parse a few arguments which are specific to Node.
3043 const char** v8_argv;
3044 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3046 // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
3047 // manually? That would give us a little more control over its runtime
3048 // behavior but it could also interfere with the user's intentions in ways
3049 // we fail to anticipate. Dillema.
3050 for (int i = 1; i < v8_argc; ++i) {
3051 if (strncmp(v8_argv[i], "--prof", sizeof("--prof") - 1) == 0) {
3052 v8_is_profiling = true;
3057 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3058 // the argv array or the elements it points to.
3059 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3061 // Anything that's still in v8_argv is not a V8 or a node option.
3062 for (int i = 1; i < v8_argc; i++) {
3063 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3072 if (debug_wait_connect) {
3073 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3074 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3077 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3079 // Fetch a reference to the main isolate, so we have a reference to it
3080 // even when we need it to access it from another (debugger) thread.
3081 node_isolate = Isolate::GetCurrent();
3084 // Raise the open file descriptor limit.
3085 { // NOLINT (whitespace/braces)
3087 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3088 // Do a binary search for the limit.
3089 rlim_t min = lim.rlim_cur;
3090 rlim_t max = 1 << 20;
3091 // But if there's a defined upper bound, don't search, just set it.
3092 if (lim.rlim_max != RLIM_INFINITY) {
3097 lim.rlim_cur = min + (max - min) / 2;
3098 if (setrlimit(RLIMIT_NOFILE, &lim)) {
3103 } while (min + 1 < max);
3107 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3108 RegisterSignalHandler(SIGINT, SignalExit);
3109 RegisterSignalHandler(SIGTERM, SignalExit);
3112 V8::SetFatalErrorHandler(node::OnFatalError);
3113 V8::AddMessageListener(OnMessage);
3115 // If the --debug flag was specified then initialize the debug thread.
3116 if (use_debug_agent) {
3117 EnableDebug(debug_wait_connect);
3119 RegisterDebugSignalHandler();
3124 struct AtExitCallback {
3125 AtExitCallback* next_;
3126 void (*cb_)(void* arg);
3130 static AtExitCallback* at_exit_functions_;
3133 // TODO(bnoordhuis) Turn into per-context event.
3134 void RunAtExit(Environment* env) {
3135 AtExitCallback* p = at_exit_functions_;
3136 at_exit_functions_ = NULL;
3139 AtExitCallback* q = p->next_;
3147 void AtExit(void (*cb)(void* arg), void* arg) {
3148 AtExitCallback* p = new AtExitCallback;
3151 p->next_ = at_exit_functions_;
3152 at_exit_functions_ = p;
3156 void EmitExit(Environment* env) {
3157 // process.emit('exit')
3158 HandleScope handle_scope(env->isolate());
3159 Context::Scope context_scope(env->context());
3160 Local<Object> process_object = env->process_object();
3161 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3162 True(node_isolate));
3164 Handle<String> exitCode = FIXED_ONE_BYTE_STRING(node_isolate, "exitCode");
3165 int code = process_object->Get(exitCode)->IntegerValue();
3167 Local<Value> args[] = {
3168 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3169 Integer::New(code, node_isolate)
3172 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3177 Environment* CreateEnvironment(Isolate* isolate,
3179 const char* const* argv,
3181 const char* const* exec_argv) {
3182 HandleScope handle_scope(isolate);
3184 Local<Context> context = Context::New(isolate);
3185 Context::Scope context_scope(context);
3186 Environment* env = Environment::New(context);
3188 uv_check_init(env->event_loop(), env->immediate_check_handle());
3190 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3191 uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3193 // Inform V8's CPU profiler when we're idle. The profiler is sampling-based
3194 // but not all samples are created equal; mark the wall clock time spent in
3195 // epoll_wait() and friends so profiling tools can filter it out. The samples
3196 // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
3197 // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
3198 // probably fortify in the API contract, namely that the last started prepare
3199 // or check watcher runs first. It's not 100% foolproof; if an add-on starts
3200 // a prepare or check watcher after us, any samples attributed to its callback
3201 // will be recorded with state=IDLE.
3202 uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
3203 uv_check_init(env->event_loop(), env->idle_check_handle());
3204 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
3205 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
3207 if (v8_is_profiling) {
3208 StartProfilerIdleNotifier(env);
3211 Local<FunctionTemplate> process_template = FunctionTemplate::New();
3212 process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3214 Local<Object> process_object = process_template->GetFunction()->NewInstance();
3215 env->set_process_object(process_object);
3217 SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3224 int Start(int argc, char** argv) {
3225 #if !defined(_WIN32)
3226 // Try hard not to lose SIGUSR1 signals during the bootstrap process.
3227 InstallEarlyDebugSignalHandler();
3232 // Hack around with the argv pointer. Used for process.title = "blah".
3233 argv = uv_setup_args(argc, argv);
3235 // This needs to run *before* V8::Initialize(). The const_cast is not
3236 // optional, in case you're wondering.
3238 const char** exec_argv;
3239 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3242 // V8 on Windows doesn't have a good source of entropy. Seed it from
3244 V8::SetEntropySource(crypto::EntropySource);
3249 Locker locker(node_isolate);
3251 CreateEnvironment(node_isolate, argc, argv, exec_argc, exec_argv);
3252 // This Context::Scope is here so EnableDebug() can look up the current
3253 // environment with Environment::GetCurrentChecked().
3254 // TODO(bnoordhuis) Reorder the debugger initialization logic so it can
3256 Context::Scope context_scope(env->context());
3257 uv_run(env->event_loop(), UV_RUN_DEFAULT);
3265 // Clean up. Not strictly necessary.