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 Environment* env = Environment::GetCurrent(args.GetIsolate());
849 HandleScope handle_scope(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 Environment* env = Environment::GetCurrent(args.GetIsolate());
879 HandleScope handle_scope(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 Environment* env = Environment::GetCurrent(args.GetIsolate());
1652 HandleScope handle_scope(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 Environment* env = Environment::GetCurrent(args.GetIsolate());
1732 HandleScope handle_scope(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 Environment* env = Environment::GetCurrent(args.GetIsolate());
1902 HandleScope handle_scope(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 Environment* env = Environment::GetCurrent(info.GetIsolate());
2185 const uv_check_t* immediate_check_handle = env->immediate_check_handle();
2186 bool active = uv_is_active(
2187 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2188 info.GetReturnValue().Set(active);
2192 static void NeedImmediateCallbackSetter(
2193 Local<String> property,
2195 const PropertyCallbackInfo<void>& info) {
2196 Environment* env = Environment::GetCurrent(info.GetIsolate());
2197 HandleScope handle_scope(info.GetIsolate());
2199 uv_check_t* immediate_check_handle = env->immediate_check_handle();
2200 bool active = uv_is_active(
2201 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2203 if (active == value->BooleanValue())
2206 uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
2209 uv_check_stop(immediate_check_handle);
2210 uv_idle_stop(immediate_idle_handle);
2212 uv_check_start(immediate_check_handle, CheckImmediate);
2213 // Idle handle is needed only to stop the event loop from blocking in poll.
2214 uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
2219 void SetIdle(uv_prepare_t* handle, int) {
2220 Environment* env = Environment::from_idle_prepare_handle(handle);
2221 env->isolate()->GetCpuProfiler()->SetIdle(true);
2225 void ClearIdle(uv_check_t* handle, int) {
2226 Environment* env = Environment::from_idle_check_handle(handle);
2227 env->isolate()->GetCpuProfiler()->SetIdle(false);
2231 void StartProfilerIdleNotifier(Environment* env) {
2232 uv_prepare_start(env->idle_prepare_handle(), SetIdle);
2233 uv_check_start(env->idle_check_handle(), ClearIdle);
2237 void StopProfilerIdleNotifier(Environment* env) {
2238 uv_prepare_stop(env->idle_prepare_handle());
2239 uv_check_stop(env->idle_check_handle());
2243 void StartProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2244 StartProfilerIdleNotifier(Environment::GetCurrent(args.GetIsolate()));
2248 void StopProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2249 StopProfilerIdleNotifier(Environment::GetCurrent(args.GetIsolate()));
2253 #define READONLY_PROPERTY(obj, str, var) \
2255 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2259 void SetupProcessObject(Environment* env,
2261 const char* const* argv,
2263 const char* const* exec_argv) {
2264 HandleScope scope(node_isolate);
2266 Local<Object> process = env->process_object();
2268 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2270 ProcessTitleSetter);
2273 READONLY_PROPERTY(process,
2275 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2277 // process.moduleLoadList
2278 READONLY_PROPERTY(process,
2280 env->module_load_list_array());
2283 Local<Object> versions = Object::New();
2284 READONLY_PROPERTY(process, "versions", versions);
2286 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2288 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2289 READONLY_PROPERTY(versions,
2291 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2293 // +1 to get rid of the leading 'v'
2294 READONLY_PROPERTY(versions,
2296 OneByteString(node_isolate, NODE_VERSION + 1));
2297 READONLY_PROPERTY(versions,
2299 OneByteString(node_isolate, V8::GetVersion()));
2300 READONLY_PROPERTY(versions,
2302 OneByteString(node_isolate, uv_version_string()));
2303 READONLY_PROPERTY(versions,
2305 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2307 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2308 READONLY_PROPERTY(versions,
2310 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2313 // Stupid code to slice out the version string.
2314 { // NOLINT(whitespace/braces)
2317 for (i = j = 0, k = sizeof(OPENSSL_VERSION_TEXT) - 1; i < k; ++i) {
2318 c = OPENSSL_VERSION_TEXT[i];
2319 if ('0' <= c && c <= '9') {
2320 for (j = i + 1; j < k; ++j) {
2321 c = OPENSSL_VERSION_TEXT[j];
2331 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2336 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2339 READONLY_PROPERTY(process,
2341 OneByteString(node_isolate, PLATFORM));
2344 Local<Array> arguments = Array::New(argc);
2345 for (int i = 0; i < argc; ++i) {
2346 arguments->Set(i, String::NewFromUtf8(node_isolate, argv[i]));
2348 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2351 Local<Array> exec_arguments = Array::New(exec_argc);
2352 for (int i = 0; i < exec_argc; ++i) {
2353 exec_arguments->Set(i, String::NewFromUtf8(node_isolate, exec_argv[i]));
2355 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_arguments);
2357 // create process.env
2358 Local<ObjectTemplate> process_env_template = ObjectTemplate::New();
2359 process_env_template->SetNamedPropertyHandler(EnvGetter,
2365 Local<Object> process_env = process_env_template->NewInstance();
2366 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), process_env);
2368 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2369 READONLY_PROPERTY(process, "features", GetFeatures());
2370 process->SetAccessor(
2371 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2372 NeedImmediateCallbackGetter,
2373 NeedImmediateCallbackSetter);
2377 READONLY_PROPERTY(process,
2379 String::NewFromUtf8(node_isolate, eval_string));
2384 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2387 // -i, --interactive
2389 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2393 if (no_deprecation) {
2394 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2397 // --throw-deprecation
2398 if (throw_deprecation) {
2399 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2402 // --trace-deprecation
2403 if (trace_deprecation) {
2404 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2407 size_t exec_path_len = 2 * PATH_MAX;
2408 char* exec_path = new char[exec_path_len];
2409 Local<String> exec_path_value;
2410 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2411 exec_path_value = String::NewFromUtf8(node_isolate,
2413 String::kNormalString,
2416 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2418 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2422 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2426 // define various internal methods
2427 NODE_SET_METHOD(process,
2428 "_startProfilerIdleNotifier",
2429 StartProfilerIdleNotifier);
2430 NODE_SET_METHOD(process,
2431 "_stopProfilerIdleNotifier",
2432 StopProfilerIdleNotifier);
2433 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2434 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2435 NODE_SET_METHOD(process, "reallyExit", Exit);
2436 NODE_SET_METHOD(process, "abort", Abort);
2437 NODE_SET_METHOD(process, "chdir", Chdir);
2438 NODE_SET_METHOD(process, "cwd", Cwd);
2440 NODE_SET_METHOD(process, "umask", Umask);
2442 #if defined(__POSIX__) && !defined(__ANDROID__)
2443 NODE_SET_METHOD(process, "getuid", GetUid);
2444 NODE_SET_METHOD(process, "setuid", SetUid);
2446 NODE_SET_METHOD(process, "setgid", SetGid);
2447 NODE_SET_METHOD(process, "getgid", GetGid);
2449 NODE_SET_METHOD(process, "getgroups", GetGroups);
2450 NODE_SET_METHOD(process, "setgroups", SetGroups);
2451 NODE_SET_METHOD(process, "initgroups", InitGroups);
2452 #endif // __POSIX__ && !defined(__ANDROID__)
2454 NODE_SET_METHOD(process, "_kill", Kill);
2456 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2457 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2458 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2460 NODE_SET_METHOD(process, "hrtime", Hrtime);
2462 NODE_SET_METHOD(process, "dlopen", DLOpen);
2464 NODE_SET_METHOD(process, "uptime", Uptime);
2465 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2467 NODE_SET_METHOD(process, "binding", Binding);
2469 NODE_SET_METHOD(process, "_setupAsyncListener", SetupAsyncListener);
2470 NODE_SET_METHOD(process, "_setupNextTick", SetupNextTick);
2472 // values use to cross communicate with processNextTick
2473 Local<Object> tick_info_obj = Object::New();
2474 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
2475 env->tick_info()->fields(),
2476 kExternalUnsignedIntArray,
2477 env->tick_info()->fields_count());
2478 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfo"), tick_info_obj);
2480 // pre-set _events object for faster emit checks
2481 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2485 #undef READONLY_PROPERTY
2488 static void AtExit() {
2489 uv_tty_reset_mode();
2493 static void SignalExit(int signal) {
2494 uv_tty_reset_mode();
2495 _exit(128 + signal);
2499 // Most of the time, it's best to use `console.error` to write
2500 // to the process.stderr stream. However, in some cases, such as
2501 // when debugging the stream.Writable class or the process.nextTick
2502 // function, it is useful to bypass JavaScript entirely.
2503 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2504 HandleScope scope(node_isolate);
2506 assert(args.Length() == 1 && args[0]->IsString() &&
2507 "must be called with a single string");
2509 String::Utf8Value message(args[0]);
2510 fprintf(stderr, "%s\n", *message);
2515 void Load(Environment* env) {
2516 HandleScope handle_scope(node_isolate);
2518 // Compile, execute the src/node.js file. (Which was included as static C
2519 // string in node_natives.h. 'natve_node' is the string containing that
2522 // The node.js file returns a function 'f'
2527 // Disable verbose mode to stop FatalException() handler from trying
2528 // to handle the exception. Errors this early in the start-up phase
2529 // are not safe to ignore.
2530 try_catch.SetVerbose(false);
2532 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2533 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2534 if (try_catch.HasCaught()) {
2535 ReportException(try_catch);
2538 assert(f_value->IsFunction());
2539 Local<Function> f = Local<Function>::Cast(f_value);
2541 // Now we call 'f' with the 'process' variable that we've built up with
2542 // all our bindings. Inside node.js we'll take care of assigning things to
2545 // We start the process this way in order to be more modular. Developers
2546 // who do not like how 'src/node.js' setups the module system but do like
2547 // Node's I/O bindings may want to replace 'f' with their own function.
2549 // Add a reference to the global object
2550 Local<Object> global = env->context()->Global();
2552 #if defined HAVE_DTRACE || defined HAVE_ETW
2556 #if defined HAVE_PERFCTR
2557 InitPerfCounters(global);
2560 // Enable handling of uncaught exceptions
2561 // (FatalException(), break on uncaught exception in debugger)
2563 // This is not strictly necessary since it's almost impossible
2564 // to attach the debugger fast enought to break on exception
2565 // thrown during process startup.
2566 try_catch.SetVerbose(true);
2568 NODE_SET_METHOD(env->process_object(), "_rawDebug", RawDebug);
2570 Local<Value> arg = env->process_object();
2571 f->Call(global, 1, &arg);
2574 static void PrintHelp();
2576 static void ParseDebugOpt(const char* arg) {
2579 if (strstr(arg, "--debug-port=") == arg) {
2580 p = 1 + strchr(arg, '=');
2581 debug_port = atoi(p);
2583 use_debug_agent = true;
2584 if (!strcmp(arg, "--debug-brk")) {
2585 debug_wait_connect = true;
2587 } else if (!strcmp(arg, "--debug")) {
2589 } else if (strstr(arg, "--debug-brk=") == arg) {
2590 debug_wait_connect = true;
2591 p = 1 + strchr(arg, '=');
2592 debug_port = atoi(p);
2593 } else if (strstr(arg, "--debug=") == arg) {
2594 p = 1 + strchr(arg, '=');
2595 debug_port = atoi(p);
2598 if (p && debug_port > 1024 && debug_port < 65536)
2601 fprintf(stderr, "Bad debug option.\n");
2603 fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2609 static void PrintHelp() {
2610 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2611 " node debug script.js [arguments] \n"
2614 " -v, --version print node's version\n"
2615 " -e, --eval script evaluate script\n"
2616 " -p, --print evaluate script and print result\n"
2617 " -i, --interactive always enter the REPL even if stdin\n"
2618 " does not appear to be a terminal\n"
2619 " --no-deprecation silence deprecation warnings\n"
2620 " --trace-deprecation show stack traces on deprecations\n"
2621 " --v8-options print v8 command line options\n"
2622 " --max-stack-size=val set max v8 stack size (bytes)\n"
2624 "Environment variables:\n"
2626 "NODE_PATH ';'-separated list of directories\n"
2628 "NODE_PATH ':'-separated list of directories\n"
2630 " prefixed to the module search path.\n"
2631 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2632 " global contexts.\n"
2633 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2635 "Documentation can be found at http://nodejs.org/\n");
2639 // Parse command line arguments.
2641 // argv is modified in place. exec_argv and v8_argv are out arguments that
2642 // ParseArgs() allocates memory for and stores a pointer to the output
2643 // vector in. The caller should free them with delete[].
2647 // * argv contains the arguments with node and V8 options filtered out.
2648 // * exec_argv contains both node and V8 options and nothing else.
2649 // * v8_argv contains argv[0] plus any V8 options
2650 static void ParseArgs(int* argc,
2653 const char*** exec_argv,
2655 const char*** v8_argv) {
2656 const unsigned int nargs = static_cast<unsigned int>(*argc);
2657 const char** new_exec_argv = new const char*[nargs];
2658 const char** new_v8_argv = new const char*[nargs];
2659 const char** new_argv = new const char*[nargs];
2661 for (unsigned int i = 0; i < nargs; ++i) {
2662 new_exec_argv[i] = NULL;
2663 new_v8_argv[i] = NULL;
2667 // exec_argv starts with the first option, the other two start with argv[0].
2668 unsigned int new_exec_argc = 0;
2669 unsigned int new_v8_argc = 1;
2670 unsigned int new_argc = 1;
2671 new_v8_argv[0] = argv[0];
2672 new_argv[0] = argv[0];
2674 unsigned int index = 1;
2675 while (index < nargs && argv[index][0] == '-') {
2676 const char* const arg = argv[index];
2677 unsigned int args_consumed = 1;
2679 if (strstr(arg, "--debug") == arg) {
2681 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2682 printf("%s\n", NODE_VERSION);
2684 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2687 } else if (strcmp(arg, "--eval") == 0 ||
2688 strcmp(arg, "-e") == 0 ||
2689 strcmp(arg, "--print") == 0 ||
2690 strcmp(arg, "-pe") == 0 ||
2691 strcmp(arg, "-p") == 0) {
2692 bool is_eval = strchr(arg, 'e') != NULL;
2693 bool is_print = strchr(arg, 'p') != NULL;
2694 print_eval = print_eval || is_print;
2695 // --eval, -e and -pe always require an argument.
2696 if (is_eval == true) {
2698 eval_string = argv[index + 1];
2699 if (eval_string == NULL) {
2700 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
2703 } else if (argv[index + 1] != NULL && argv[index + 1][0] != '-') {
2705 eval_string = argv[index + 1];
2706 if (strncmp(eval_string, "\\-", 2) == 0) {
2707 // Starts with "\\-": escaped expression, drop the backslash.
2711 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2713 } else if (strcmp(arg, "--no-deprecation") == 0) {
2714 no_deprecation = true;
2715 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2716 trace_deprecation = true;
2717 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2718 throw_deprecation = true;
2719 } else if (strcmp(arg, "--v8-options") == 0) {
2720 new_v8_argv[new_v8_argc] = "--help";
2723 // V8 option. Pass through as-is.
2724 new_v8_argv[new_v8_argc] = arg;
2728 memcpy(new_exec_argv + new_exec_argc,
2730 args_consumed * sizeof(*argv));
2732 new_exec_argc += args_consumed;
2733 index += args_consumed;
2736 // Copy remaining arguments.
2737 const unsigned int args_left = nargs - index;
2738 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
2739 new_argc += args_left;
2741 *exec_argc = new_exec_argc;
2742 *exec_argv = new_exec_argv;
2743 *v8_argc = new_v8_argc;
2744 *v8_argv = new_v8_argv;
2746 // Copy new_argv over argv and update argc.
2747 memcpy(argv, new_argv, new_argc * sizeof(*argv));
2749 *argc = static_cast<int>(new_argc);
2753 // Called from V8 Debug Agent TCP thread.
2754 static void DispatchMessagesDebugAgentCallback() {
2755 uv_async_send(&dispatch_debug_messages_async);
2759 // Called from the main thread.
2760 static void EnableDebug(bool wait_connect) {
2761 assert(debugger_running == false);
2762 Isolate* isolate = node_isolate; // TODO(bnoordhuis) Multi-isolate support.
2763 Isolate::Scope isolate_scope(isolate);
2764 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2766 debugger_running = v8::Debug::EnableAgent("node " NODE_VERSION,
2769 if (debugger_running == false) {
2770 fprintf(stderr, "Starting debugger on port %d failed\n", debug_port);
2774 fprintf(stderr, "Debugger listening on port %d\n", debug_port);
2777 Environment* env = Environment::GetCurrentChecked(isolate);
2779 return; // Still starting up.
2781 Context::Scope context_scope(env->context());
2782 HandleScope handle_scope(env->isolate());
2783 Local<Object> message = Object::New();
2784 message->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "cmd"),
2785 FIXED_ONE_BYTE_STRING(env->isolate(), "NODE_DEBUG_ENABLED"));
2786 Local<Value> argv[] = {
2787 FIXED_ONE_BYTE_STRING(env->isolate(), "internalMessage"),
2790 MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(argv), argv);
2794 // Called from the main thread.
2795 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2796 if (debugger_running == false) {
2797 fprintf(stderr, "Starting debugger agent.\n");
2800 Isolate::Scope isolate_scope(node_isolate);
2801 v8::Debug::ProcessDebugMessages();
2806 static volatile sig_atomic_t caught_early_debug_signal;
2809 static void EarlyDebugSignalHandler(int signo) {
2810 caught_early_debug_signal = 1;
2814 static void InstallEarlyDebugSignalHandler() {
2815 struct sigaction sa;
2816 memset(&sa, 0, sizeof(sa));
2817 sa.sa_handler = EarlyDebugSignalHandler;
2818 sigaction(SIGUSR1, &sa, NULL);
2822 static void EnableDebugSignalHandler(int signo) {
2823 // Call only async signal-safe functions here!
2824 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
2825 uv_async_send(&dispatch_debug_messages_async);
2829 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2830 struct sigaction sa;
2831 memset(&sa, 0, sizeof(sa));
2832 sa.sa_handler = handler;
2833 sigfillset(&sa.sa_mask);
2834 sigaction(signal, &sa, NULL);
2838 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2839 HandleScope scope(node_isolate);
2841 if (args.Length() != 1) {
2842 return ThrowError("Invalid number of arguments.");
2848 pid = args[0]->IntegerValue();
2849 r = kill(pid, SIGUSR1);
2851 return ThrowErrnoException(errno, "kill");
2856 static int RegisterDebugSignalHandler() {
2857 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
2858 RegisterSignalHandler(SIGUSR1, EnableDebugSignalHandler);
2859 // If we caught a SIGUSR1 during the bootstrap process, re-raise it
2860 // now that the debugger infrastructure is in place.
2861 if (caught_early_debug_signal)
2869 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2870 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
2871 uv_async_send(&dispatch_debug_messages_async);
2876 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2878 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2882 static int RegisterDebugSignalHandler() {
2883 wchar_t mapping_name[32];
2884 HANDLE mapping_handle;
2886 LPTHREAD_START_ROUTINE* handler;
2888 pid = GetCurrentProcessId();
2890 if (GetDebugSignalHandlerMappingName(pid,
2892 ARRAY_SIZE(mapping_name)) < 0) {
2896 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2902 if (mapping_handle == NULL) {
2906 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2907 MapViewOfFile(mapping_handle,
2908 FILE_MAP_ALL_ACCESS,
2912 if (handler == NULL) {
2913 CloseHandle(mapping_handle);
2917 *handler = EnableDebugThreadProc;
2919 UnmapViewOfFile(static_cast<void*>(handler));
2925 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2926 HandleScope scope(node_isolate);
2928 HANDLE process = NULL;
2929 HANDLE thread = NULL;
2930 HANDLE mapping = NULL;
2931 wchar_t mapping_name[32];
2932 LPTHREAD_START_ROUTINE* handler = NULL;
2934 if (args.Length() != 1) {
2935 ThrowError("Invalid number of arguments.");
2939 pid = (DWORD) args[0]->IntegerValue();
2941 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2942 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2946 if (process == NULL) {
2947 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2951 if (GetDebugSignalHandlerMappingName(pid,
2953 ARRAY_SIZE(mapping_name)) < 0) {
2954 ThrowErrnoException(errno, "sprintf");
2958 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2959 if (mapping == NULL) {
2960 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
2964 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2965 MapViewOfFile(mapping,
2970 if (handler == NULL || *handler == NULL) {
2971 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
2975 thread = CreateRemoteThread(process,
2982 if (thread == NULL) {
2983 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
2987 // Wait for the thread to terminate
2988 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
2989 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
2994 if (process != NULL)
2995 CloseHandle(process);
2997 CloseHandle(thread);
2998 if (handler != NULL)
2999 UnmapViewOfFile(handler);
3000 if (mapping != NULL)
3001 CloseHandle(mapping);
3006 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3007 v8::Debug::DebugBreak(node_isolate);
3011 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3012 if (debugger_running) {
3013 v8::Debug::DisableAgent();
3014 debugger_running = false;
3019 void Init(int* argc,
3022 const char*** exec_argv) {
3023 // Initialize prog_start_time to get relative uptime.
3024 uv_uptime(&prog_start_time);
3026 // Make inherited handles noninheritable.
3027 uv_disable_stdio_inheritance();
3029 // init async debug messages dispatching
3030 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3031 uv_async_init(uv_default_loop(),
3032 &dispatch_debug_messages_async,
3033 DispatchDebugMessagesAsyncCallback);
3034 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3036 // Parse a few arguments which are specific to Node.
3038 const char** v8_argv;
3039 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3041 // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
3042 // manually? That would give us a little more control over its runtime
3043 // behavior but it could also interfere with the user's intentions in ways
3044 // we fail to anticipate. Dillema.
3045 for (int i = 1; i < v8_argc; ++i) {
3046 if (strncmp(v8_argv[i], "--prof", sizeof("--prof") - 1) == 0) {
3047 v8_is_profiling = true;
3052 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3053 // the argv array or the elements it points to.
3054 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3056 // Anything that's still in v8_argv is not a V8 or a node option.
3057 for (int i = 1; i < v8_argc; i++) {
3058 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3067 if (debug_wait_connect) {
3068 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3069 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3072 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3074 // Fetch a reference to the main isolate, so we have a reference to it
3075 // even when we need it to access it from another (debugger) thread.
3076 node_isolate = Isolate::GetCurrent();
3079 // Raise the open file descriptor limit.
3080 { // NOLINT (whitespace/braces)
3082 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3083 // Do a binary search for the limit.
3084 rlim_t min = lim.rlim_cur;
3085 rlim_t max = 1 << 20;
3086 // But if there's a defined upper bound, don't search, just set it.
3087 if (lim.rlim_max != RLIM_INFINITY) {
3092 lim.rlim_cur = min + (max - min) / 2;
3093 if (setrlimit(RLIMIT_NOFILE, &lim)) {
3098 } while (min + 1 < max);
3102 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3103 RegisterSignalHandler(SIGINT, SignalExit);
3104 RegisterSignalHandler(SIGTERM, SignalExit);
3107 V8::SetFatalErrorHandler(node::OnFatalError);
3108 V8::AddMessageListener(OnMessage);
3110 // If the --debug flag was specified then initialize the debug thread.
3111 if (use_debug_agent) {
3112 EnableDebug(debug_wait_connect);
3114 RegisterDebugSignalHandler();
3119 struct AtExitCallback {
3120 AtExitCallback* next_;
3121 void (*cb_)(void* arg);
3125 static AtExitCallback* at_exit_functions_;
3128 // TODO(bnoordhuis) Turn into per-context event.
3129 void RunAtExit(Environment* env) {
3130 AtExitCallback* p = at_exit_functions_;
3131 at_exit_functions_ = NULL;
3134 AtExitCallback* q = p->next_;
3142 void AtExit(void (*cb)(void* arg), void* arg) {
3143 AtExitCallback* p = new AtExitCallback;
3146 p->next_ = at_exit_functions_;
3147 at_exit_functions_ = p;
3151 void EmitExit(Environment* env) {
3152 // process.emit('exit')
3153 Context::Scope context_scope(env->context());
3154 HandleScope handle_scope(env->isolate());
3155 Local<Object> process_object = env->process_object();
3156 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3157 True(node_isolate));
3159 Handle<String> exitCode = FIXED_ONE_BYTE_STRING(node_isolate, "exitCode");
3160 int code = process_object->Get(exitCode)->IntegerValue();
3162 Local<Value> args[] = {
3163 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3164 Integer::New(code, node_isolate)
3167 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3172 Environment* CreateEnvironment(Isolate* isolate,
3174 const char* const* argv,
3176 const char* const* exec_argv) {
3177 HandleScope handle_scope(isolate);
3179 Local<Context> context = Context::New(isolate);
3180 Context::Scope context_scope(context);
3181 Environment* env = Environment::New(context);
3183 uv_check_init(env->event_loop(), env->immediate_check_handle());
3185 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3186 uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3188 // Inform V8's CPU profiler when we're idle. The profiler is sampling-based
3189 // but not all samples are created equal; mark the wall clock time spent in
3190 // epoll_wait() and friends so profiling tools can filter it out. The samples
3191 // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
3192 // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
3193 // probably fortify in the API contract, namely that the last started prepare
3194 // or check watcher runs first. It's not 100% foolproof; if an add-on starts
3195 // a prepare or check watcher after us, any samples attributed to its callback
3196 // will be recorded with state=IDLE.
3197 uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
3198 uv_check_init(env->event_loop(), env->idle_check_handle());
3199 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
3200 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
3202 if (v8_is_profiling) {
3203 StartProfilerIdleNotifier(env);
3206 Local<FunctionTemplate> process_template = FunctionTemplate::New();
3207 process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3209 Local<Object> process_object = process_template->GetFunction()->NewInstance();
3210 env->set_process_object(process_object);
3212 SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3219 int Start(int argc, char** argv) {
3220 #if !defined(_WIN32)
3221 // Try hard not to lose SIGUSR1 signals during the bootstrap process.
3222 InstallEarlyDebugSignalHandler();
3227 // Hack around with the argv pointer. Used for process.title = "blah".
3228 argv = uv_setup_args(argc, argv);
3230 // This needs to run *before* V8::Initialize(). The const_cast is not
3231 // optional, in case you're wondering.
3233 const char** exec_argv;
3234 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3237 // V8 on Windows doesn't have a good source of entropy. Seed it from
3239 V8::SetEntropySource(crypto::EntropySource);
3244 Locker locker(node_isolate);
3246 CreateEnvironment(node_isolate, argc, argv, exec_argc, exec_argv);
3247 Context::Scope context_scope(env->context());
3248 HandleScope handle_scope(env->isolate());
3249 uv_run(env->event_loop(), UV_RUN_DEFAULT);
3257 // Clean up. Not strictly necessary.