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 || defined HAVE_SYSTEMTAP
39 #include "node_dtrace.h"
43 #include "node_provider.h"
49 #include "handle_wrap.h"
51 #include "string_bytes.h"
54 #include "v8-profiler.h"
59 #include <limits.h> // PATH_MAX
65 #include <sys/types.h>
71 #define strcasecmp _stricmp
72 #define getpid _getpid
76 #include <sys/resource.h> // getrlimit, setrlimit
77 #include <unistd.h> // setuid, getuid
80 #if defined(__POSIX__) && !defined(__ANDROID__)
81 #include <pwd.h> // getpwnam()
82 #include <grp.h> // getgrnam()
86 #include <crt_externs.h>
87 #define environ (*_NSGetEnviron())
88 #elif !defined(_MSC_VER)
89 extern char **environ;
95 using v8::ArrayBuffer;
100 using v8::FunctionCallbackInfo;
101 using v8::FunctionTemplate;
103 using v8::HandleScope;
104 using v8::HeapStatistics;
112 using v8::ObjectTemplate;
113 using v8::PropertyCallbackInfo;
115 using v8::ThrowException;
120 using v8::kExternalUnsignedIntArray;
122 // FIXME(bnoordhuis) Make these per-context?
123 QUEUE handle_wrap_queue = { &handle_wrap_queue, &handle_wrap_queue };
124 QUEUE req_wrap_queue = { &req_wrap_queue, &req_wrap_queue };
126 static bool print_eval = false;
127 static bool force_repl = false;
128 static bool trace_deprecation = false;
129 static bool throw_deprecation = false;
130 static const char* eval_string = NULL;
131 static bool use_debug_agent = false;
132 static bool debug_wait_connect = false;
133 static int debug_port = 5858;
134 static bool v8_is_profiling = false;
136 // used by C++ modules as well
137 bool no_deprecation = false;
139 // process-relative uptime base, initialized at start-up
140 static double prog_start_time;
142 static volatile bool debugger_running = false;
143 static uv_async_t dispatch_debug_messages_async;
144 static uv_async_t emit_debug_enabled_async;
146 // Declared in node_internals.h
147 Isolate* node_isolate = NULL;
150 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
152 // Impose an upper limit to avoid out of memory errors that bring down
154 static const size_t kMaxLength = 0x3fffffff;
155 static ArrayBufferAllocator the_singleton;
156 virtual ~ArrayBufferAllocator() {}
157 virtual void* Allocate(size_t length);
158 virtual void Free(void* data);
160 ArrayBufferAllocator() {}
161 ArrayBufferAllocator(const ArrayBufferAllocator&);
162 void operator=(const ArrayBufferAllocator&);
165 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
168 void* ArrayBufferAllocator::Allocate(size_t length) {
169 if (length > kMaxLength) return NULL;
170 return new char[length];
174 void ArrayBufferAllocator::Free(void* data) {
175 delete[] static_cast<char*>(data);
179 static void CheckImmediate(uv_check_t* handle, int status) {
180 Environment* env = Environment::from_immediate_check_handle(handle);
181 Context::Scope context_scope(env->context());
182 MakeCallback(env, env->process_object(), env->immediate_callback_string());
186 static void IdleImmediateDummy(uv_idle_t*, int) {
187 // Do nothing. Only for maintaining event loop.
188 // TODO(bnoordhuis) Maybe make libuv accept NULL idle callbacks.
192 static inline const char *errno_string(int errorno) {
193 #define ERRNO_CASE(e) case e: return #e;
200 ERRNO_CASE(EADDRINUSE);
204 ERRNO_CASE(EADDRNOTAVAIL);
208 ERRNO_CASE(EAFNOSUPPORT);
216 # if EAGAIN != EWOULDBLOCK
217 ERRNO_CASE(EWOULDBLOCK);
222 ERRNO_CASE(EALREADY);
238 ERRNO_CASE(ECANCELED);
246 ERRNO_CASE(ECONNABORTED);
250 ERRNO_CASE(ECONNREFUSED);
254 ERRNO_CASE(ECONNRESET);
262 ERRNO_CASE(EDESTADDRREQ);
286 ERRNO_CASE(EHOSTUNREACH);
298 ERRNO_CASE(EINPROGRESS);
334 ERRNO_CASE(EMSGSIZE);
338 ERRNO_CASE(EMULTIHOP);
342 ERRNO_CASE(ENAMETOOLONG);
346 ERRNO_CASE(ENETDOWN);
350 ERRNO_CASE(ENETRESET);
354 ERRNO_CASE(ENETUNREACH);
386 # if ENOLINK != ENOLCK
400 ERRNO_CASE(ENOPROTOOPT);
420 ERRNO_CASE(ENOTCONN);
428 ERRNO_CASE(ENOTEMPTY);
432 ERRNO_CASE(ENOTSOCK);
439 ERRNO_CASE(EOPNOTSUPP);
453 ERRNO_CASE(EOVERFLOW);
468 #ifdef EPROTONOSUPPORT
469 ERRNO_CASE(EPROTONOSUPPORT);
473 ERRNO_CASE(EPROTOTYPE);
501 ERRNO_CASE(ETIMEDOUT);
516 const char *signo_string(int signo) {
517 #define SIGNO_CASE(e) case e: return #e;
544 # if SIGABRT != SIGIOT
588 SIGNO_CASE(SIGSTKFLT);
605 SIGNO_CASE(SIGBREAK);
629 SIGNO_CASE(SIGVTALRM);
637 SIGNO_CASE(SIGWINCH);
645 # if SIGPOLL != SIGIO
655 # if SIGPWR != SIGLOST
669 Local<Value> ErrnoException(int errorno,
673 Environment* env = Environment::GetCurrent(node_isolate);
676 Local<String> estring = OneByteString(node_isolate, errno_string(errorno));
677 if (msg == NULL || msg[0] == '\0') {
678 msg = strerror(errorno);
680 Local<String> message = OneByteString(node_isolate, msg);
682 Local<String> cons1 =
683 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
684 Local<String> cons2 = String::Concat(cons1, message);
687 Local<String> cons3 =
688 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
689 Local<String> cons4 =
690 String::Concat(cons3, String::NewFromUtf8(node_isolate, path));
691 Local<String> cons5 =
692 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
693 e = Exception::Error(cons5);
695 e = Exception::Error(cons2);
698 Local<Object> obj = e->ToObject();
699 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
700 obj->Set(env->code_string(), estring);
703 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
706 if (syscall != NULL) {
707 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
714 // hack alert! copy of ErrnoException, tuned for uv errors
715 Local<Value> UVException(int errorno,
719 Environment* env = Environment::GetCurrent(node_isolate);
722 msg = uv_strerror(errorno);
724 Local<String> estring = OneByteString(node_isolate, uv_err_name(errorno));
725 Local<String> message = OneByteString(node_isolate, msg);
726 Local<String> cons1 =
727 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
728 Local<String> cons2 = String::Concat(cons1, message);
732 Local<String> path_str;
736 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
737 path_str = String::Concat(FIXED_ONE_BYTE_STRING(node_isolate, "\\\\"),
738 String::NewFromUtf8(node_isolate, path + 8));
739 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
740 path_str = String::NewFromUtf8(node_isolate, path + 4);
742 path_str = String::NewFromUtf8(node_isolate, path);
745 path_str = String::NewFromUtf8(node_isolate, path);
748 Local<String> cons3 =
749 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
750 Local<String> cons4 =
751 String::Concat(cons3, path_str);
752 Local<String> cons5 =
753 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
754 e = Exception::Error(cons5);
756 e = Exception::Error(cons2);
759 Local<Object> obj = e->ToObject();
760 // TODO(piscisaureus) errno should probably go
761 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
762 obj->Set(env->code_string(), estring);
765 obj->Set(env->path_string(), path_str);
768 if (syscall != NULL) {
769 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
777 // Does about the same as strerror(),
778 // but supports all windows error messages
779 static const char *winapi_strerror(const int errorno) {
782 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
783 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
784 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
787 // Remove trailing newlines
788 for (int i = strlen(errmsg) - 1;
789 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
795 // FormatMessage failed
796 return "Unknown error";
801 Local<Value> WinapiErrnoException(int errorno,
805 Environment* env = Environment::GetCurrent(node_isolate);
808 if (!msg || !msg[0]) {
809 msg = winapi_strerror(errorno);
811 Local<String> message = OneByteString(node_isolate, msg);
814 Local<String> cons1 =
815 String::Concat(message, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
816 Local<String> cons2 =
817 String::Concat(cons1, String::NewFromUtf8(node_isolate, path));
818 Local<String> cons3 =
819 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
820 e = Exception::Error(cons3);
822 e = Exception::Error(message);
825 Local<Object> obj = e->ToObject();
826 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
829 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
832 if (syscall != NULL) {
833 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
841 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
842 Environment* env = Environment::GetCurrent(args.GetIsolate());
844 if (env->using_domains()) return;
845 env->set_using_domains(true);
847 HandleScope scope(node_isolate);
848 Local<Object> process_object = env->process_object();
850 Local<String> tick_callback_function_key =
851 FIXED_ONE_BYTE_STRING(node_isolate, "_tickDomainCallback");
852 Local<Function> tick_callback_function =
853 process_object->Get(tick_callback_function_key).As<Function>();
855 if (!tick_callback_function->IsFunction()) {
856 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
860 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"),
861 tick_callback_function);
862 env->set_tick_callback_function(tick_callback_function);
864 if (!args[0]->IsArray()) {
865 fprintf(stderr, "_setupDomainUse first argument must be an array\n");
868 env->set_domain_array(args[0].As<Array>());
870 if (!args[1]->IsObject()) {
871 fprintf(stderr, "_setupDomainUse second argument must be an object\n");
875 Local<Object> domain_flag_obj = args[1].As<Object>();
876 Environment::DomainFlag* domain_flag = env->domain_flag();
877 domain_flag_obj->SetIndexedPropertiesToExternalArrayData(
878 domain_flag->fields(),
879 kExternalUnsignedIntArray,
880 domain_flag->fields_count());
884 Handle<Value> MakeDomainCallback(Environment* env,
885 const Handle<Object> object,
886 const Handle<Function> callback,
888 Handle<Value> argv[]) {
889 // If you hit this assertion, you forgot to enter the v8::Context first.
890 assert(env->context() == env->isolate()->GetCurrentContext());
892 // TODO(trevnorris) Hook for long stack traces to be made here.
894 Local<Value> domain_v = object->Get(env->domain_string());
895 Local<Object> domain;
898 try_catch.SetVerbose(true);
900 bool has_domain = domain_v->IsObject();
902 domain = domain_v.As<Object>();
904 if (domain->Get(env->disposed_string())->IsTrue()) {
905 // domain has been disposed of.
906 return Undefined(node_isolate);
909 Local<Function> enter =
910 domain->Get(env->enter_string()).As<Function>();
911 assert(enter->IsFunction());
912 enter->Call(domain, 0, NULL);
914 if (try_catch.HasCaught()) {
915 return Undefined(node_isolate);
919 Local<Value> ret = callback->Call(object, argc, argv);
921 if (try_catch.HasCaught()) {
922 return Undefined(node_isolate);
926 Local<Function> exit =
927 domain->Get(env->exit_string()).As<Function>();
928 assert(exit->IsFunction());
929 exit->Call(domain, 0, NULL);
931 if (try_catch.HasCaught()) {
932 return Undefined(node_isolate);
936 Environment::TickInfo* tick_info = env->tick_info();
938 if (tick_info->last_threw() == 1) {
939 tick_info->set_last_threw(0);
943 if (tick_info->in_tick() == 1) {
947 if (tick_info->length() == 0) {
948 tick_info->set_index(0);
952 // process nextTicks after call
953 Local<Object> process_object = env->process_object();
954 Local<Function> tick_callback_function = env->tick_callback_function();
955 tick_callback_function->Call(process_object, 0, NULL);
957 if (try_catch.HasCaught()) {
958 return Undefined(node_isolate);
965 Handle<Value> MakeCallback(Environment* env,
966 const Handle<Object> object,
967 const Handle<Function> callback,
969 Handle<Value> argv[]) {
970 // If you hit this assertion, you forgot to enter the v8::Context first.
971 assert(env->context() == env->isolate()->GetCurrentContext());
973 // TODO(trevnorris) Hook for long stack traces to be made here.
974 Local<Object> process_object = env->process_object();
976 if (env->using_domains())
977 return MakeDomainCallback(env, object, callback, argc, argv);
980 try_catch.SetVerbose(true);
982 Local<Value> ret = callback->Call(object, argc, argv);
984 if (try_catch.HasCaught()) {
985 return Undefined(node_isolate);
988 Environment::TickInfo* tick_info = env->tick_info();
990 if (tick_info->in_tick() == 1) {
994 if (tick_info->length() == 0) {
995 tick_info->set_index(0);
999 // lazy load no domain next tick callbacks
1000 Local<Function> tick_callback_function = env->tick_callback_function();
1001 if (tick_callback_function.IsEmpty()) {
1002 Local<String> tick_callback_function_key =
1003 FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback");
1004 tick_callback_function =
1005 process_object->Get(tick_callback_function_key).As<Function>();
1006 if (!tick_callback_function->IsFunction()) {
1007 fprintf(stderr, "process._tickCallback assigned to non-function\n");
1010 env->set_tick_callback_function(tick_callback_function);
1013 // process nextTicks after call
1014 tick_callback_function->Call(process_object, 0, NULL);
1016 if (try_catch.HasCaught()) {
1017 return Undefined(node_isolate);
1025 Handle<Value> MakeCallback(Environment* env,
1026 const Handle<Object> object,
1029 Handle<Value> argv[]) {
1030 // If you hit this assertion, you forgot to enter the v8::Context first.
1031 assert(env->context() == env->isolate()->GetCurrentContext());
1033 Local<Function> callback = object->Get(index).As<Function>();
1034 assert(callback->IsFunction());
1036 if (env->using_domains()) {
1037 return MakeDomainCallback(env, object, callback, argc, argv);
1040 return MakeCallback(env, object, callback, argc, argv);
1044 Handle<Value> MakeCallback(Environment* env,
1045 const Handle<Object> object,
1046 const Handle<String> symbol,
1048 Handle<Value> argv[]) {
1049 // If you hit this assertion, you forgot to enter the v8::Context first.
1050 assert(env->context() == env->isolate()->GetCurrentContext());
1052 Local<Function> callback = object->Get(symbol).As<Function>();
1053 assert(callback->IsFunction());
1055 if (env->using_domains()) {
1056 return MakeDomainCallback(env, object, callback, argc, argv);
1059 return MakeCallback(env, object, callback, argc, argv);
1063 Handle<Value> MakeCallback(Environment* env,
1064 const Handle<Object> object,
1067 Handle<Value> argv[]) {
1068 // If you hit this assertion, you forgot to enter the v8::Context first.
1069 assert(env->context() == env->isolate()->GetCurrentContext());
1070 Local<String> method_string = OneByteString(node_isolate, method);
1071 return MakeCallback(env, object, method_string, argc, argv);
1075 Handle<Value> MakeCallback(const Handle<Object> object,
1078 Handle<Value> argv[]) {
1079 Local<Context> context = object->CreationContext();
1080 Environment* env = Environment::GetCurrent(context);
1081 Context::Scope context_scope(context);
1082 HandleScope handle_scope(env->isolate());
1083 return handle_scope.Close(MakeCallback(env, object, method, argc, argv));
1087 Handle<Value> MakeCallback(const Handle<Object> object,
1088 const Handle<String> symbol,
1090 Handle<Value> argv[]) {
1091 Local<Context> context = object->CreationContext();
1092 Environment* env = Environment::GetCurrent(context);
1093 Context::Scope context_scope(context);
1094 HandleScope handle_scope(env->isolate());
1095 return handle_scope.Close(MakeCallback(env, object, symbol, argc, argv));
1099 Handle<Value> MakeCallback(const Handle<Object> object,
1100 const Handle<Function> callback,
1102 Handle<Value> argv[]) {
1103 Local<Context> context = object->CreationContext();
1104 Environment* env = Environment::GetCurrent(context);
1105 Context::Scope context_scope(context);
1106 HandleScope handle_scope(env->isolate());
1107 return handle_scope.Close(MakeCallback(env, object, callback, argc, argv));
1111 Handle<Value> MakeDomainCallback(const Handle<Object> object,
1112 const Handle<Function> callback,
1114 Handle<Value> argv[]) {
1115 Local<Context> context = object->CreationContext();
1116 Environment* env = Environment::GetCurrent(context);
1117 Context::Scope context_scope(context);
1118 HandleScope handle_scope(env->isolate());
1119 return handle_scope.Close(
1120 MakeDomainCallback(env, object, callback, argc, argv));
1124 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1125 HandleScope scope(node_isolate);
1127 if (!encoding_v->IsString()) return _default;
1129 String::Utf8Value encoding(encoding_v);
1131 if (strcasecmp(*encoding, "utf8") == 0) {
1133 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1135 } else if (strcasecmp(*encoding, "ascii") == 0) {
1137 } else if (strcasecmp(*encoding, "base64") == 0) {
1139 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1141 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1143 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1145 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1147 } else if (strcasecmp(*encoding, "binary") == 0) {
1149 } else if (strcasecmp(*encoding, "buffer") == 0) {
1151 } else if (strcasecmp(*encoding, "hex") == 0) {
1153 } else if (strcasecmp(*encoding, "raw") == 0) {
1154 if (!no_deprecation) {
1155 fprintf(stderr, "'raw' (array of integers) has been removed. "
1159 } else if (strcasecmp(*encoding, "raws") == 0) {
1160 if (!no_deprecation) {
1161 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1162 "Please update your code.\n");
1170 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1171 return StringBytes::Encode(static_cast<const char*>(buf),
1176 // Returns -1 if the handle was not valid for decoding
1177 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1178 HandleScope scope(node_isolate);
1180 if (val->IsArray()) {
1181 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1187 return StringBytes::Size(val, encoding);
1191 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1194 // Returns number of bytes written.
1195 ssize_t DecodeWrite(char *buf,
1197 v8::Handle<v8::Value> val,
1198 enum encoding encoding) {
1199 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1202 void DisplayExceptionLine(Handle<Message> message) {
1203 // Prevent re-entry into this function. For example, if there is
1204 // a throw from a program in vm.runInThisContext(code, filename, true),
1205 // then we want to show the original failure, not the secondary one.
1206 static bool displayed_error = false;
1208 if (displayed_error) return;
1209 displayed_error = true;
1211 uv_tty_reset_mode();
1213 fprintf(stderr, "\n");
1215 if (!message.IsEmpty()) {
1216 // Print (filename):(line number): (message).
1217 String::Utf8Value filename(message->GetScriptResourceName());
1218 const char* filename_string = *filename;
1219 int linenum = message->GetLineNumber();
1220 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1221 // Print line of source code.
1222 String::Utf8Value sourceline(message->GetSourceLine());
1223 const char* sourceline_string = *sourceline;
1225 // Because of how node modules work, all scripts are wrapped with a
1226 // "function (module, exports, __filename, ...) {"
1227 // to provide script local variables.
1229 // When reporting errors on the first line of a script, this wrapper
1230 // function is leaked to the user. There used to be a hack here to
1231 // truncate off the first 62 characters, but it caused numerous other
1232 // problems when vm.runIn*Context() methods were used for non-module
1235 // If we ever decide to re-instate such a hack, the following steps
1238 // 1. Pass a flag around to say "this code was wrapped"
1239 // 2. Update the stack frame output so that it is also correct.
1241 // It would probably be simpler to add a line rather than add some
1242 // number of characters to the first line, since V8 truncates the
1243 // sourceline to 78 characters, and we end up not providing very much
1244 // useful debugging info to the user if we remove 62 characters.
1246 int start = message->GetStartColumn();
1247 int end = message->GetEndColumn();
1249 fprintf(stderr, "%s\n", sourceline_string);
1250 // Print wavy underline (GetUnderline is deprecated).
1251 for (int i = 0; i < start; i++) {
1252 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1254 for (int i = start; i < end; i++) {
1257 fputc('\n', stderr);
1262 static void ReportException(Handle<Value> er, Handle<Message> message) {
1263 HandleScope scope(node_isolate);
1265 DisplayExceptionLine(message);
1267 Local<Value> trace_value(
1268 er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack")));
1269 String::Utf8Value trace(trace_value);
1271 // range errors have a trace member set to undefined
1272 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1273 fprintf(stderr, "%s\n", *trace);
1275 // this really only happens for RangeErrors, since they're the only
1276 // kind that won't have all this info in the trace, or when non-Error
1277 // objects are thrown manually.
1278 Local<Value> message;
1281 if (er->IsObject()) {
1282 Local<Object> err_obj = er.As<Object>();
1283 message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1284 name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1287 if (message.IsEmpty() ||
1288 message->IsUndefined() ||
1290 name->IsUndefined()) {
1291 // Not an error object. Just print as-is.
1292 String::Utf8Value message(er);
1293 fprintf(stderr, "%s\n", *message);
1295 String::Utf8Value name_string(name);
1296 String::Utf8Value message_string(message);
1297 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1305 static void ReportException(const TryCatch& try_catch) {
1306 ReportException(try_catch.Exception(), try_catch.Message());
1310 // Executes a str within the current v8 context.
1311 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1312 HandleScope scope(node_isolate);
1315 // try_catch must be nonverbose to disable FatalException() handler,
1316 // we will handle exceptions ourself.
1317 try_catch.SetVerbose(false);
1319 Local<v8::Script> script = v8::Script::Compile(source, filename);
1320 if (script.IsEmpty()) {
1321 ReportException(try_catch);
1325 Local<Value> result = script->Run();
1326 if (result.IsEmpty()) {
1327 ReportException(try_catch);
1331 return scope.Close(result);
1335 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1336 HandleScope scope(node_isolate);
1338 Local<Array> ary = Array::New();
1342 QUEUE_FOREACH(q, &req_wrap_queue) {
1343 ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1344 if (w->persistent().IsEmpty()) continue;
1345 ary->Set(i++, w->object());
1348 args.GetReturnValue().Set(ary);
1352 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1353 // implemented here for consistency with GetActiveRequests().
1354 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1355 HandleScope scope(node_isolate);
1357 Local<Array> ary = Array::New();
1361 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1363 QUEUE_FOREACH(q, &handle_wrap_queue) {
1364 HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1365 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue;
1366 Local<Object> object = w->object();
1367 Local<Value> owner = object->Get(owner_sym);
1368 if (owner->IsUndefined()) owner = object;
1369 ary->Set(i++, owner);
1372 args.GetReturnValue().Set(ary);
1376 static void Abort(const FunctionCallbackInfo<Value>& args) {
1381 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1382 HandleScope scope(node_isolate);
1384 if (args.Length() != 1 || !args[0]->IsString()) {
1385 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1388 String::Utf8Value path(args[0]);
1389 int err = uv_chdir(*path);
1391 return ThrowUVException(err, "uv_chdir");
1396 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1397 HandleScope scope(node_isolate);
1399 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1400 char buf[MAX_PATH * 4 + 1];
1402 char buf[PATH_MAX + 1];
1405 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1407 return ThrowUVException(err, "uv_cwd");
1410 buf[ARRAY_SIZE(buf) - 1] = '\0';
1411 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1413 args.GetReturnValue().Set(cwd);
1417 static void Umask(const FunctionCallbackInfo<Value>& args) {
1418 HandleScope scope(node_isolate);
1421 if (args.Length() < 1 || args[0]->IsUndefined()) {
1423 umask(static_cast<mode_t>(old));
1424 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1425 return ThrowTypeError("argument must be an integer or octal string.");
1428 if (args[0]->IsInt32()) {
1429 oct = args[0]->Uint32Value();
1432 String::Utf8Value str(args[0]);
1434 // Parse the octal string.
1435 for (int i = 0; i < str.length(); i++) {
1437 if (c > '7' || c < '0') {
1438 return ThrowTypeError("invalid octal string");
1444 old = umask(static_cast<mode_t>(oct));
1447 args.GetReturnValue().Set(old);
1451 #if defined(__POSIX__) && !defined(__ANDROID__)
1453 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1454 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1457 static uid_t uid_by_name(const char* name) {
1465 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1469 return uid_not_found;
1473 static char* name_by_uid(uid_t uid) {
1482 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1483 return strdup(pp->pw_name);
1494 static gid_t gid_by_name(const char* name) {
1502 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1506 return gid_not_found;
1510 #if 0 // For future use.
1511 static const char* name_by_gid(gid_t gid) {
1520 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1521 return strdup(pp->gr_name);
1533 static uid_t uid_by_name(Handle<Value> value) {
1534 if (value->IsUint32()) {
1535 return static_cast<uid_t>(value->Uint32Value());
1537 String::Utf8Value name(value);
1538 return uid_by_name(*name);
1543 static gid_t gid_by_name(Handle<Value> value) {
1544 if (value->IsUint32()) {
1545 return static_cast<gid_t>(value->Uint32Value());
1547 String::Utf8Value name(value);
1548 return gid_by_name(*name);
1553 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1554 // uid_t is an uint32_t on all supported platforms.
1555 args.GetReturnValue().Set(static_cast<uint32_t>(getuid()));
1559 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1560 // gid_t is an uint32_t on all supported platforms.
1561 args.GetReturnValue().Set(static_cast<uint32_t>(getgid()));
1565 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1566 HandleScope scope(node_isolate);
1568 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1569 return ThrowTypeError("setgid argument must be a number or a string");
1572 gid_t gid = gid_by_name(args[0]);
1574 if (gid == gid_not_found) {
1575 return ThrowError("setgid group id does not exist");
1579 return ThrowErrnoException(errno, "setgid");
1584 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1585 HandleScope scope(node_isolate);
1587 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1588 return ThrowTypeError("setuid argument must be a number or a string");
1591 uid_t uid = uid_by_name(args[0]);
1593 if (uid == uid_not_found) {
1594 return ThrowError("setuid user id does not exist");
1598 return ThrowErrnoException(errno, "setuid");
1603 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1604 HandleScope scope(node_isolate);
1606 int ngroups = getgroups(0, NULL);
1608 if (ngroups == -1) {
1609 return ThrowErrnoException(errno, "getgroups");
1612 gid_t* groups = new gid_t[ngroups];
1614 ngroups = getgroups(ngroups, groups);
1616 if (ngroups == -1) {
1618 return ThrowErrnoException(errno, "getgroups");
1621 Local<Array> groups_list = Array::New(ngroups);
1622 bool seen_egid = false;
1623 gid_t egid = getegid();
1625 for (int i = 0; i < ngroups; i++) {
1626 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1627 if (groups[i] == egid) seen_egid = true;
1632 if (seen_egid == false) {
1633 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1636 args.GetReturnValue().Set(groups_list);
1640 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1641 HandleScope scope(node_isolate);
1643 if (!args[0]->IsArray()) {
1644 return ThrowTypeError("argument 1 must be an array");
1647 Local<Array> groups_list = args[0].As<Array>();
1648 size_t size = groups_list->Length();
1649 gid_t* groups = new gid_t[size];
1651 for (size_t i = 0; i < size; i++) {
1652 gid_t gid = gid_by_name(groups_list->Get(i));
1654 if (gid == gid_not_found) {
1656 return ThrowError("group name not found");
1662 int rc = setgroups(size, groups);
1666 return ThrowErrnoException(errno, "setgroups");
1671 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1672 HandleScope scope(node_isolate);
1674 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1675 return ThrowTypeError("argument 1 must be a number or a string");
1678 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1679 return ThrowTypeError("argument 2 must be a number or a string");
1682 String::Utf8Value arg0(args[0]);
1687 if (args[0]->IsUint32()) {
1688 user = name_by_uid(args[0]->Uint32Value());
1696 return ThrowError("initgroups user not found");
1699 extra_group = gid_by_name(args[1]);
1701 if (extra_group == gid_not_found) {
1702 if (must_free) free(user);
1703 return ThrowError("initgroups extra group not found");
1706 int rc = initgroups(user, extra_group);
1713 return ThrowErrnoException(errno, "initgroups");
1717 #endif // __POSIX__ && !defined(__ANDROID__)
1720 void Exit(const FunctionCallbackInfo<Value>& args) {
1721 HandleScope scope(node_isolate);
1722 exit(args[0]->IntegerValue());
1726 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1727 HandleScope scope(node_isolate);
1729 if (uv_uptime(&uptime)) return;
1730 args.GetReturnValue().Set(uptime - prog_start_time);
1734 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1735 Environment* env = Environment::GetCurrent(args.GetIsolate());
1736 HandleScope handle_scope(args.GetIsolate());
1739 int err = uv_resident_set_memory(&rss);
1741 return ThrowUVException(err, "uv_resident_set_memory");
1745 HeapStatistics v8_heap_stats;
1746 node_isolate->GetHeapStatistics(&v8_heap_stats);
1748 Local<Integer> heap_total =
1749 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(), node_isolate);
1750 Local<Integer> heap_used =
1751 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(), node_isolate);
1753 Local<Object> info = Object::New();
1754 info->Set(env->rss_string(), Number::New(node_isolate, rss));
1755 info->Set(env->heap_total_string(), heap_total);
1756 info->Set(env->heap_used_string(), heap_used);
1758 args.GetReturnValue().Set(info);
1762 void Kill(const FunctionCallbackInfo<Value>& args) {
1763 HandleScope scope(node_isolate);
1765 if (args.Length() != 2) {
1766 return ThrowError("Bad argument.");
1769 int pid = args[0]->IntegerValue();
1770 int sig = args[1]->Int32Value();
1771 int err = uv_kill(pid, sig);
1772 args.GetReturnValue().Set(err);
1775 // used in Hrtime() below
1776 #define NANOS_PER_SEC 1000000000
1778 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1779 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1780 // so this function instead returns an Array with 2 entries representing seconds
1781 // and nanoseconds, to avoid any integer overflow possibility.
1782 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1783 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1784 HandleScope scope(node_isolate);
1786 uint64_t t = uv_hrtime();
1788 if (args.Length() > 0) {
1789 // return a time diff tuple
1790 if (!args[0]->IsArray()) {
1791 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1793 Local<Array> inArray = Local<Array>::Cast(args[0]);
1794 uint64_t seconds = inArray->Get(0)->Uint32Value();
1795 uint64_t nanos = inArray->Get(1)->Uint32Value();
1796 t -= (seconds * NANOS_PER_SEC) + nanos;
1799 Local<Array> tuple = Array::New(2);
1800 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1801 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1802 args.GetReturnValue().Set(tuple);
1806 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1808 // DLOpen is process.dlopen(module, filename).
1809 // Used to load 'module.node' dynamically shared objects.
1811 // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
1812 // when two contexts try to load the same shared object. Maybe have a shadow
1813 // cache that's a plain C list or hash table that's shared across contexts?
1814 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1815 Environment* env = Environment::GetCurrent(args.GetIsolate());
1816 HandleScope handle_scope(args.GetIsolate());
1817 char symbol[1024], *base, *pos;
1821 if (args.Length() < 2) {
1822 return ThrowError("process.dlopen takes exactly 2 arguments.");
1825 Local<Object> module = args[0]->ToObject(); // Cast
1826 String::Utf8Value filename(args[1]); // Cast
1828 Local<String> exports_string = env->exports_string();
1829 Local<Object> exports = module->Get(exports_string)->ToObject();
1831 if (uv_dlopen(*filename, &lib)) {
1832 Local<String> errmsg = OneByteString(env->isolate(), uv_dlerror(&lib));
1834 // Windows needs to add the filename into the error message
1835 errmsg = String::Concat(errmsg, args[1]->ToString());
1837 ThrowException(Exception::Error(errmsg));
1841 String::Utf8Value path(args[1]);
1844 /* Find the shared library filename within the full path. */
1846 pos = strrchr(base, '/');
1852 pos = strpbrk(base, "\\/:");
1860 /* Strip the .node extension. */
1861 pos = strrchr(base, '.');
1866 /* Add the `_module` suffix to the extension name. */
1867 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1868 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1869 return ThrowError("Out of memory.");
1872 /* Replace dashes with underscores. When loading foo-bar.node,
1873 * look for foo_bar_module, not foo-bar_module.
1875 for (pos = symbol; *pos != '\0'; ++pos) {
1876 if (*pos == '-') *pos = '_';
1879 node_module_struct *mod;
1880 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1882 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1883 return ThrowError(errmsg);
1886 if (mod->version != NODE_MODULE_VERSION) {
1890 "Module version mismatch. Expected %d, got %d.",
1891 NODE_MODULE_VERSION, mod->version);
1892 return ThrowError(errmsg);
1895 // Execute the C++ module
1896 if (mod->register_context_func != NULL) {
1897 mod->register_context_func(exports, module, env->context());
1898 } else if (mod->register_func != NULL) {
1899 mod->register_func(exports, module);
1901 return ThrowError("Module has no declared entry point.");
1904 // Tell coverity that 'handle' should not be freed when we return.
1905 // coverity[leaked_storage]
1909 static void OnFatalError(const char* location, const char* message) {
1911 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1913 fprintf(stderr, "FATAL ERROR: %s\n", message);
1923 NO_RETURN void FatalError(const char* location, const char* message) {
1924 OnFatalError(location, message);
1925 // to supress compiler warning
1930 void FatalException(Handle<Value> error, Handle<Message> message) {
1931 HandleScope scope(node_isolate);
1933 Environment* env = Environment::GetCurrent(node_isolate);
1934 Local<Object> process_object = env->process_object();
1935 Local<String> fatal_exception_string = env->fatal_exception_string();
1936 Local<Function> fatal_exception_function =
1937 process_object->Get(fatal_exception_string).As<Function>();
1939 if (!fatal_exception_function->IsFunction()) {
1940 // failed before the process._fatalException function was added!
1941 // this is probably pretty bad. Nothing to do but report and exit.
1942 ReportException(error, message);
1946 TryCatch fatal_try_catch;
1948 // Do not call FatalException when _fatalException handler throws
1949 fatal_try_catch.SetVerbose(false);
1951 // this will return true if the JS layer handled it, false otherwise
1952 Local<Value> caught =
1953 fatal_exception_function->Call(process_object, 1, &error);
1955 if (fatal_try_catch.HasCaught()) {
1956 // the fatal exception function threw, so we must exit
1957 ReportException(fatal_try_catch);
1961 if (false == caught->BooleanValue()) {
1962 ReportException(error, message);
1968 void FatalException(const TryCatch& try_catch) {
1969 HandleScope scope(node_isolate);
1970 // TODO(bajtos) do not call FatalException if try_catch is verbose
1971 // (requires V8 API to expose getter for try_catch.is_verbose_)
1972 FatalException(try_catch.Exception(), try_catch.Message());
1976 void OnMessage(Handle<Message> message, Handle<Value> error) {
1977 // The current version of V8 sends messages for errors only
1978 // (thus `error` is always set).
1979 FatalException(error, message);
1983 static void Binding(const FunctionCallbackInfo<Value>& args) {
1984 Environment* env = Environment::GetCurrent(args.GetIsolate());
1985 HandleScope handle_scope(args.GetIsolate());
1987 Local<String> module = args[0]->ToString();
1988 String::Utf8Value module_v(module);
1990 Local<Object> cache = env->binding_cache_object();
1991 Local<Object> exports;
1993 if (cache->Has(module)) {
1994 exports = cache->Get(module)->ToObject();
1995 args.GetReturnValue().Set(exports);
1999 // Append a string to process.moduleLoadList
2001 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
2003 Local<Array> modules = env->module_load_list_array();
2004 uint32_t l = modules->Length();
2005 modules->Set(l, OneByteString(node_isolate, buf));
2007 node_module_struct* mod = get_builtin_module(*module_v);
2009 exports = Object::New();
2010 // Internal bindings don't have a "module" object, only exports.
2011 assert(mod->register_func == NULL);
2012 assert(mod->register_context_func != NULL);
2013 Local<Value> unused = Undefined(env->isolate());
2014 mod->register_context_func(exports, unused, env->context());
2015 cache->Set(module, exports);
2016 } else if (!strcmp(*module_v, "constants")) {
2017 exports = Object::New();
2018 DefineConstants(exports);
2019 cache->Set(module, exports);
2020 } else if (!strcmp(*module_v, "natives")) {
2021 exports = Object::New();
2022 DefineJavaScript(exports);
2023 cache->Set(module, exports);
2025 return ThrowError("No such module");
2028 args.GetReturnValue().Set(exports);
2032 static void ProcessTitleGetter(Local<String> property,
2033 const PropertyCallbackInfo<Value>& info) {
2034 HandleScope scope(node_isolate);
2036 uv_get_process_title(buffer, sizeof(buffer));
2037 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2041 static void ProcessTitleSetter(Local<String> property,
2043 const PropertyCallbackInfo<void>& info) {
2044 HandleScope scope(node_isolate);
2045 String::Utf8Value title(value);
2046 // TODO(piscisaureus): protect with a lock
2047 uv_set_process_title(*title);
2051 static void EnvGetter(Local<String> property,
2052 const PropertyCallbackInfo<Value>& info) {
2053 HandleScope scope(node_isolate);
2055 String::Utf8Value key(property);
2056 const char* val = getenv(*key);
2058 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2061 String::Value key(property);
2062 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2063 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2065 ARRAY_SIZE(buffer));
2066 // If result >= sizeof buffer the buffer was too small. That should never
2067 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2069 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2070 result < ARRAY_SIZE(buffer)) {
2071 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2072 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2073 return info.GetReturnValue().Set(rc);
2076 // Not found. Fetch from prototype.
2077 info.GetReturnValue().Set(
2078 info.Data().As<Object>()->Get(property));
2082 static void EnvSetter(Local<String> property,
2084 const PropertyCallbackInfo<Value>& info) {
2085 HandleScope scope(node_isolate);
2087 String::Utf8Value key(property);
2088 String::Utf8Value val(value);
2089 setenv(*key, *val, 1);
2091 String::Value key(property);
2092 String::Value val(value);
2093 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2094 // Environment variables that start with '=' are read-only.
2095 if (key_ptr[0] != L'=') {
2096 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2099 // Whether it worked or not, always return rval.
2100 info.GetReturnValue().Set(value);
2104 static void EnvQuery(Local<String> property,
2105 const PropertyCallbackInfo<Integer>& info) {
2106 HandleScope scope(node_isolate);
2107 int32_t rc = -1; // Not found unless proven otherwise.
2109 String::Utf8Value key(property);
2110 if (getenv(*key)) rc = 0;
2112 String::Value key(property);
2113 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2114 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2115 GetLastError() == ERROR_SUCCESS) {
2117 if (key_ptr[0] == L'=') {
2118 // Environment variables that start with '=' are hidden and read-only.
2119 rc = static_cast<int32_t>(v8::ReadOnly) |
2120 static_cast<int32_t>(v8::DontDelete) |
2121 static_cast<int32_t>(v8::DontEnum);
2125 if (rc != -1) info.GetReturnValue().Set(rc);
2129 static void EnvDeleter(Local<String> property,
2130 const PropertyCallbackInfo<Boolean>& info) {
2131 HandleScope scope(node_isolate);
2134 String::Utf8Value key(property);
2135 rc = getenv(*key) != NULL;
2136 if (rc) unsetenv(*key);
2138 String::Value key(property);
2139 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2140 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2141 // Deletion failed. Return true if the key wasn't there in the first place,
2142 // false if it is still there.
2143 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2144 GetLastError() != ERROR_SUCCESS;
2147 info.GetReturnValue().Set(rc);
2151 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2152 HandleScope scope(node_isolate);
2155 while (environ[size]) size++;
2157 Local<Array> env = Array::New(size);
2159 for (int i = 0; i < size; ++i) {
2160 const char* var = environ[i];
2161 const char* s = strchr(var, '=');
2162 const int length = s ? s - var : strlen(var);
2163 Local<String> name = String::NewFromUtf8(node_isolate,
2165 String::kNormalString,
2170 WCHAR* environment = GetEnvironmentStringsW();
2171 if (environment == NULL) return; // This should not happen.
2172 Local<Array> env = Array::New();
2173 WCHAR* p = environment;
2175 while (*p != NULL) {
2178 // If the key starts with '=' it is a hidden environment variable.
2182 s = wcschr(p, L'=');
2187 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2188 const size_t two_byte_buffer_len = s - p;
2189 Local<String> value = String::NewFromTwoByte(node_isolate,
2191 String::kNormalString,
2192 two_byte_buffer_len);
2193 env->Set(i++, value);
2194 p = s + wcslen(s) + 1;
2196 FreeEnvironmentStringsW(environment);
2199 info.GetReturnValue().Set(env);
2203 static Handle<Object> GetFeatures() {
2204 HandleScope scope(node_isolate);
2206 Local<Object> obj = Object::New();
2207 #if defined(DEBUG) && DEBUG
2208 Local<Value> debug = True(node_isolate);
2210 Local<Value> debug = False(node_isolate);
2211 #endif // defined(DEBUG) && DEBUG
2213 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2215 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2216 // TODO(bnoordhuis) ping libuv
2217 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2219 #ifdef OPENSSL_NPN_NEGOTIATED
2220 Local<Boolean> tls_npn = True(node_isolate);
2222 Local<Boolean> tls_npn = False(node_isolate);
2224 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"), tls_npn);
2226 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2227 Local<Boolean> tls_sni = True(node_isolate);
2229 Local<Boolean> tls_sni = False(node_isolate);
2231 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"), tls_sni);
2233 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2234 Boolean::New(get_builtin_module("crypto") != NULL));
2236 return scope.Close(obj);
2240 static void DebugPortGetter(Local<String> property,
2241 const PropertyCallbackInfo<Value>& info) {
2242 HandleScope scope(node_isolate);
2243 info.GetReturnValue().Set(debug_port);
2247 static void DebugPortSetter(Local<String> property,
2249 const PropertyCallbackInfo<void>& info) {
2250 HandleScope scope(node_isolate);
2251 debug_port = value->NumberValue();
2255 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2256 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2257 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2260 void NeedImmediateCallbackGetter(Local<String> property,
2261 const PropertyCallbackInfo<Value>& info) {
2262 Environment* env = Environment::GetCurrent(info.GetIsolate());
2263 const uv_check_t* immediate_check_handle = env->immediate_check_handle();
2264 bool active = uv_is_active(
2265 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2266 info.GetReturnValue().Set(active);
2270 static void NeedImmediateCallbackSetter(
2271 Local<String> property,
2273 const PropertyCallbackInfo<void>& info) {
2274 Environment* env = Environment::GetCurrent(info.GetIsolate());
2275 HandleScope handle_scope(info.GetIsolate());
2277 uv_check_t* immediate_check_handle = env->immediate_check_handle();
2278 bool active = uv_is_active(
2279 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2281 if (active == value->BooleanValue())
2284 uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
2287 uv_check_stop(immediate_check_handle);
2288 uv_idle_stop(immediate_idle_handle);
2290 uv_check_start(immediate_check_handle, CheckImmediate);
2291 // Idle handle is needed only to stop the event loop from blocking in poll.
2292 uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
2297 #define READONLY_PROPERTY(obj, str, var) \
2299 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2303 void SetupProcessObject(Environment* env,
2305 const char* const* argv,
2307 const char* const* exec_argv) {
2308 HandleScope scope(node_isolate);
2311 Local<Object> process = env->process_object();
2313 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2315 ProcessTitleSetter);
2318 READONLY_PROPERTY(process,
2320 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2322 // process.moduleLoadList
2323 READONLY_PROPERTY(process,
2325 env->module_load_list_array());
2328 Local<Object> versions = Object::New();
2329 READONLY_PROPERTY(process, "versions", versions);
2331 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2333 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2334 READONLY_PROPERTY(versions,
2336 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2338 // +1 to get rid of the leading 'v'
2339 READONLY_PROPERTY(versions,
2341 OneByteString(node_isolate, NODE_VERSION + 1));
2342 READONLY_PROPERTY(versions,
2344 OneByteString(node_isolate, V8::GetVersion()));
2345 READONLY_PROPERTY(versions,
2347 OneByteString(node_isolate, uv_version_string()));
2348 READONLY_PROPERTY(versions,
2350 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2352 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2353 READONLY_PROPERTY(versions,
2355 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2358 // Stupid code to slice out the version string.
2359 int c, l = strlen(OPENSSL_VERSION_TEXT);
2360 for (i = j = 0; i < l; i++) {
2361 c = OPENSSL_VERSION_TEXT[i];
2362 if ('0' <= c && c <= '9') {
2363 for (j = i + 1; j < l; j++) {
2364 c = OPENSSL_VERSION_TEXT[j];
2365 if (c == ' ') break;
2373 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2377 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2380 READONLY_PROPERTY(process,
2382 OneByteString(node_isolate, PLATFORM));
2385 Local<Array> arguments = Array::New(argc);
2386 for (int i = 0; i < argc; ++i) {
2387 arguments->Set(i, String::NewFromUtf8(node_isolate, argv[i]));
2389 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2392 Local<Array> exec_arguments = Array::New(exec_argc);
2393 for (int i = 0; i < exec_argc; ++i) {
2394 exec_arguments->Set(i, String::NewFromUtf8(node_isolate, exec_argv[i]));
2396 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_arguments);
2398 // create process.env
2399 Local<ObjectTemplate> process_env_template = ObjectTemplate::New();
2400 process_env_template->SetNamedPropertyHandler(EnvGetter,
2406 Local<Object> process_env = process_env_template->NewInstance();
2407 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), process_env);
2409 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2410 READONLY_PROPERTY(process, "features", GetFeatures());
2411 process->SetAccessor(
2412 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2413 NeedImmediateCallbackGetter,
2414 NeedImmediateCallbackSetter);
2418 READONLY_PROPERTY(process,
2420 String::NewFromUtf8(node_isolate, eval_string));
2425 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2428 // -i, --interactive
2430 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2434 if (no_deprecation) {
2435 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2438 // --throw-deprecation
2439 if (throw_deprecation) {
2440 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2443 // --trace-deprecation
2444 if (trace_deprecation) {
2445 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2448 size_t exec_path_len = 2 * PATH_MAX;
2449 char* exec_path = new char[exec_path_len];
2450 Local<String> exec_path_value;
2451 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2452 exec_path_value = String::NewFromUtf8(node_isolate,
2454 String::kNormalString,
2457 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2459 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2463 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2467 // define various internal methods
2468 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2469 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2470 NODE_SET_METHOD(process, "reallyExit", Exit);
2471 NODE_SET_METHOD(process, "abort", Abort);
2472 NODE_SET_METHOD(process, "chdir", Chdir);
2473 NODE_SET_METHOD(process, "cwd", Cwd);
2475 NODE_SET_METHOD(process, "umask", Umask);
2477 #if defined(__POSIX__) && !defined(__ANDROID__)
2478 NODE_SET_METHOD(process, "getuid", GetUid);
2479 NODE_SET_METHOD(process, "setuid", SetUid);
2481 NODE_SET_METHOD(process, "setgid", SetGid);
2482 NODE_SET_METHOD(process, "getgid", GetGid);
2484 NODE_SET_METHOD(process, "getgroups", GetGroups);
2485 NODE_SET_METHOD(process, "setgroups", SetGroups);
2486 NODE_SET_METHOD(process, "initgroups", InitGroups);
2487 #endif // __POSIX__ && !defined(__ANDROID__)
2489 NODE_SET_METHOD(process, "_kill", Kill);
2491 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2492 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2493 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2495 NODE_SET_METHOD(process, "hrtime", Hrtime);
2497 NODE_SET_METHOD(process, "dlopen", DLOpen);
2499 NODE_SET_METHOD(process, "uptime", Uptime);
2500 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2502 NODE_SET_METHOD(process, "binding", Binding);
2504 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2506 // values use to cross communicate with processNextTick
2507 Local<Object> tick_info_obj = Object::New();
2508 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
2509 env->tick_info()->fields(),
2510 kExternalUnsignedIntArray,
2511 env->tick_info()->fields_count());
2512 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfo"), tick_info_obj);
2514 // pre-set _events object for faster emit checks
2515 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2519 #undef READONLY_PROPERTY
2522 static void AtExit() {
2523 uv_tty_reset_mode();
2527 static void SignalExit(int signal) {
2528 uv_tty_reset_mode();
2529 _exit(128 + signal);
2533 // Most of the time, it's best to use `console.error` to write
2534 // to the process.stderr stream. However, in some cases, such as
2535 // when debugging the stream.Writable class or the process.nextTick
2536 // function, it is useful to bypass JavaScript entirely.
2537 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2538 HandleScope scope(node_isolate);
2540 assert(args.Length() == 1 && args[0]->IsString() &&
2541 "must be called with a single string");
2543 String::Utf8Value message(args[0]);
2544 fprintf(stderr, "%s\n", *message);
2549 void Load(Environment* env) {
2550 HandleScope handle_scope(node_isolate);
2552 // Compile, execute the src/node.js file. (Which was included as static C
2553 // string in node_natives.h. 'natve_node' is the string containing that
2556 // The node.js file returns a function 'f'
2561 // Disable verbose mode to stop FatalException() handler from trying
2562 // to handle the exception. Errors this early in the start-up phase
2563 // are not safe to ignore.
2564 try_catch.SetVerbose(false);
2566 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2567 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2568 if (try_catch.HasCaught()) {
2569 ReportException(try_catch);
2572 assert(f_value->IsFunction());
2573 Local<Function> f = Local<Function>::Cast(f_value);
2575 // Now we call 'f' with the 'process' variable that we've built up with
2576 // all our bindings. Inside node.js we'll take care of assigning things to
2579 // We start the process this way in order to be more modular. Developers
2580 // who do not like how 'src/node.js' setups the module system but do like
2581 // Node's I/O bindings may want to replace 'f' with their own function.
2583 // Add a reference to the global object
2584 Local<Object> global = env->context()->Global();
2586 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2590 #if defined HAVE_PERFCTR
2591 InitPerfCounters(global);
2594 // Enable handling of uncaught exceptions
2595 // (FatalException(), break on uncaught exception in debugger)
2597 // This is not strictly necessary since it's almost impossible
2598 // to attach the debugger fast enought to break on exception
2599 // thrown during process startup.
2600 try_catch.SetVerbose(true);
2602 NODE_SET_METHOD(env->process_object(), "_rawDebug", RawDebug);
2604 Local<Value> arg = env->process_object();
2605 f->Call(global, 1, &arg);
2608 static void PrintHelp();
2610 static void ParseDebugOpt(const char* arg) {
2613 if (strstr(arg, "--debug-port=") == arg) {
2614 p = 1 + strchr(arg, '=');
2615 debug_port = atoi(p);
2617 use_debug_agent = true;
2618 if (!strcmp(arg, "--debug-brk")) {
2619 debug_wait_connect = true;
2621 } else if (!strcmp(arg, "--debug")) {
2623 } else if (strstr(arg, "--debug-brk=") == arg) {
2624 debug_wait_connect = true;
2625 p = 1 + strchr(arg, '=');
2626 debug_port = atoi(p);
2627 } else if (strstr(arg, "--debug=") == arg) {
2628 p = 1 + strchr(arg, '=');
2629 debug_port = atoi(p);
2632 if (p && debug_port > 1024 && debug_port < 65536)
2635 fprintf(stderr, "Bad debug option.\n");
2636 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2642 static void PrintHelp() {
2643 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2644 " node debug script.js [arguments] \n"
2647 " -v, --version print node's version\n"
2648 " -e, --eval script evaluate script\n"
2649 " -p, --print evaluate script and print result\n"
2650 " -i, --interactive always enter the REPL even if stdin\n"
2651 " does not appear to be a terminal\n"
2652 " --no-deprecation silence deprecation warnings\n"
2653 " --trace-deprecation show stack traces on deprecations\n"
2654 " --v8-options print v8 command line options\n"
2655 " --max-stack-size=val set max v8 stack size (bytes)\n"
2657 "Environment variables:\n"
2659 "NODE_PATH ';'-separated list of directories\n"
2661 "NODE_PATH ':'-separated list of directories\n"
2663 " prefixed to the module search path.\n"
2664 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2665 " global contexts.\n"
2666 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2668 "Documentation can be found at http://nodejs.org/\n");
2672 // Parse command line arguments.
2674 // argv is modified in place. exec_argv and v8_argv are out arguments that
2675 // ParseArgs() allocates memory for and stores a pointer to the output
2676 // vector in. The caller should free them with delete[].
2680 // * argv contains the arguments with node and V8 options filtered out.
2681 // * exec_argv contains both node and V8 options and nothing else.
2682 // * v8_argv contains argv[0] plus any V8 options
2683 static void ParseArgs(int* argc,
2686 const char*** exec_argv,
2688 const char*** v8_argv) {
2689 const unsigned int nargs = static_cast<unsigned int>(*argc);
2690 const char** new_exec_argv = new const char*[nargs];
2691 const char** new_v8_argv = new const char*[nargs];
2692 const char** new_argv = new const char*[nargs];
2694 for (unsigned int i = 0; i < nargs; ++i) {
2695 new_exec_argv[i] = NULL;
2696 new_v8_argv[i] = NULL;
2700 // exec_argv starts with the first option, the other two start with argv[0].
2701 unsigned int new_exec_argc = 0;
2702 unsigned int new_v8_argc = 1;
2703 unsigned int new_argc = 1;
2704 new_v8_argv[0] = argv[0];
2705 new_argv[0] = argv[0];
2707 unsigned int index = 1;
2708 while (index < nargs && argv[index][0] == '-') {
2709 const char* const arg = argv[index];
2710 unsigned int args_consumed = 1;
2712 if (strstr(arg, "--debug") == arg) {
2714 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2715 printf("%s\n", NODE_VERSION);
2717 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2720 } else if (strcmp(arg, "--eval") == 0 ||
2721 strcmp(arg, "-e") == 0 ||
2722 strcmp(arg, "--print") == 0 ||
2723 strcmp(arg, "-pe") == 0 ||
2724 strcmp(arg, "-p") == 0) {
2725 bool is_eval = strchr(arg, 'e') != NULL;
2726 bool is_print = strchr(arg, 'p') != NULL;
2727 print_eval = print_eval || is_print;
2728 // --eval, -e and -pe always require an argument.
2729 if (is_eval == true) {
2731 eval_string = argv[index + 1];
2732 if (eval_string == NULL) {
2733 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
2736 } else if (argv[index + 1] != NULL && argv[index + 1][0] != '-') {
2738 eval_string = argv[index + 1];
2739 if (strncmp(eval_string, "\\-", 2) == 0) {
2740 // Starts with "\\-": escaped expression, drop the backslash.
2744 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2746 } else if (strcmp(arg, "--no-deprecation") == 0) {
2747 no_deprecation = true;
2748 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2749 trace_deprecation = true;
2750 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2751 throw_deprecation = true;
2752 } else if (strcmp(arg, "--v8-options") == 0) {
2753 new_v8_argv[new_v8_argc] = "--help";
2756 // V8 option. Pass through as-is.
2757 new_v8_argv[new_v8_argc] = arg;
2761 memcpy(new_exec_argv + new_exec_argc,
2763 args_consumed * sizeof(*argv));
2765 new_exec_argc += args_consumed;
2766 index += args_consumed;
2769 // Copy remaining arguments.
2770 const unsigned int args_left = nargs - index;
2771 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
2772 new_argc += args_left;
2774 *exec_argc = new_exec_argc;
2775 *exec_argv = new_exec_argv;
2776 *v8_argc = new_v8_argc;
2777 *v8_argv = new_v8_argv;
2779 // Copy new_argv over argv and update argc.
2780 memcpy(argv, new_argv, new_argc * sizeof(*argv));
2782 *argc = static_cast<int>(new_argc);
2786 // Called from the main thread.
2787 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2788 v8::Debug::ProcessDebugMessages();
2792 // Called from V8 Debug Agent TCP thread.
2793 static void DispatchMessagesDebugAgentCallback() {
2794 uv_async_send(&dispatch_debug_messages_async);
2798 // Called from the main thread
2799 static void EmitDebugEnabledAsyncCallback(uv_async_t* handle, int status) {
2800 Environment* env = Environment::GetCurrent(node_isolate);
2801 Context::Scope context_scope(env->context());
2802 HandleScope handle_scope(env->isolate());
2803 Local<Object> message = Object::New();
2804 message->Set(FIXED_ONE_BYTE_STRING(node_isolate, "cmd"),
2805 FIXED_ONE_BYTE_STRING(node_isolate, "NODE_DEBUG_ENABLED"));
2806 Local<Value> args[] = {
2807 FIXED_ONE_BYTE_STRING(node_isolate, "internalMessage"),
2810 MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(args), args);
2814 // Called from the signal watcher callback
2815 static void EmitDebugEnabled() {
2816 uv_async_send(&emit_debug_enabled_async);
2820 static void EnableDebug(bool wait_connect) {
2821 // If we're called from another thread, make sure to enter the right
2823 node_isolate->Enter();
2825 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2828 // Start the debug thread and it's associated TCP server on port 5858.
2829 bool r = v8::Debug::EnableAgent("node " NODE_VERSION,
2833 // Crappy check that everything went well. FIXME
2836 // Print out some information.
2837 fprintf(stderr, "debugger listening on port %d\n", debug_port);
2840 debugger_running = true;
2842 if (Environment::GetCurrentChecked(node_isolate) != NULL) {
2846 node_isolate->Exit();
2851 static void EnableDebugSignalHandler(uv_signal_t* handle, int) {
2852 // Break once process will return execution to v8
2853 v8::Debug::DebugBreak(node_isolate);
2855 if (!debugger_running) {
2856 fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n");
2862 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2863 struct sigaction sa;
2865 memset(&sa, 0, sizeof(sa));
2866 sa.sa_handler = handler;
2867 sigfillset(&sa.sa_mask);
2868 sigaction(signal, &sa, NULL);
2872 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2873 HandleScope scope(node_isolate);
2875 if (args.Length() != 1) {
2876 return ThrowError("Invalid number of arguments.");
2882 pid = args[0]->IntegerValue();
2883 r = kill(pid, SIGUSR1);
2885 return ThrowErrnoException(errno, "kill");
2892 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2893 // Break once process will return execution to v8
2894 if (!debugger_running) {
2895 for (int i = 0; i < 1; i++) {
2896 fprintf(stderr, "Starting debugger agent.\r\n");
2902 v8::Debug::DebugBreak(node_isolate);
2908 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2910 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2914 static int RegisterDebugSignalHandler() {
2915 wchar_t mapping_name[32];
2916 HANDLE mapping_handle;
2918 LPTHREAD_START_ROUTINE* handler;
2920 pid = GetCurrentProcessId();
2922 if (GetDebugSignalHandlerMappingName(pid,
2924 ARRAY_SIZE(mapping_name)) < 0) {
2928 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2934 if (mapping_handle == NULL) {
2938 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2939 MapViewOfFile(mapping_handle,
2940 FILE_MAP_ALL_ACCESS,
2944 if (handler == NULL) {
2945 CloseHandle(mapping_handle);
2949 *handler = EnableDebugThreadProc;
2951 UnmapViewOfFile(static_cast<void*>(handler));
2957 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2958 HandleScope scope(node_isolate);
2960 HANDLE process = NULL;
2961 HANDLE thread = NULL;
2962 HANDLE mapping = NULL;
2963 wchar_t mapping_name[32];
2964 LPTHREAD_START_ROUTINE* handler = NULL;
2966 if (args.Length() != 1) {
2967 ThrowError("Invalid number of arguments.");
2971 pid = (DWORD) args[0]->IntegerValue();
2973 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2974 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2978 if (process == NULL) {
2979 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2983 if (GetDebugSignalHandlerMappingName(pid,
2985 ARRAY_SIZE(mapping_name)) < 0) {
2986 ThrowErrnoException(errno, "sprintf");
2990 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2991 if (mapping == NULL) {
2992 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
2996 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2997 MapViewOfFile(mapping,
3002 if (handler == NULL || *handler == NULL) {
3003 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
3007 thread = CreateRemoteThread(process,
3014 if (thread == NULL) {
3015 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
3019 // Wait for the thread to terminate
3020 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3021 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
3026 if (process != NULL)
3027 CloseHandle(process);
3029 CloseHandle(thread);
3030 if (handler != NULL)
3031 UnmapViewOfFile(handler);
3032 if (mapping != NULL)
3033 CloseHandle(mapping);
3038 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3039 v8::Debug::DebugBreak(node_isolate);
3043 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3044 if (debugger_running) {
3045 v8::Debug::DisableAgent();
3046 debugger_running = false;
3051 void Init(int* argc,
3054 const char*** exec_argv) {
3055 // Initialize prog_start_time to get relative uptime.
3056 uv_uptime(&prog_start_time);
3058 // Make inherited handles noninheritable.
3059 uv_disable_stdio_inheritance();
3061 // init async debug messages dispatching
3062 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3063 uv_async_init(uv_default_loop(),
3064 &dispatch_debug_messages_async,
3065 DispatchDebugMessagesAsyncCallback);
3066 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3068 // init async NODE_DEBUG_ENABLED emitter
3069 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3070 uv_async_init(uv_default_loop(),
3071 &emit_debug_enabled_async,
3072 EmitDebugEnabledAsyncCallback);
3073 uv_unref(reinterpret_cast<uv_handle_t*>(&emit_debug_enabled_async));
3075 // Parse a few arguments which are specific to Node.
3077 const char** v8_argv;
3078 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3080 // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
3081 // manually? That would give us a little more control over its runtime
3082 // behavior but it could also interfere with the user's intentions in ways
3083 // we fail to anticipate. Dillema.
3084 for (int i = 1; i < v8_argc; ++i) {
3085 if (strncmp(v8_argv[i], "--prof", sizeof("--prof") - 1) == 0) {
3086 v8_is_profiling = true;
3091 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3092 // the argv array or the elements it points to.
3093 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3095 // Anything that's still in v8_argv is not a V8 or a node option.
3096 for (int i = 1; i < v8_argc; i++) {
3097 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3106 if (debug_wait_connect) {
3107 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3108 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3111 const char typed_arrays_flag[] = "--harmony_typed_arrays";
3112 V8::SetFlagsFromString(typed_arrays_flag, sizeof(typed_arrays_flag) - 1);
3113 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3115 // Fetch a reference to the main isolate, so we have a reference to it
3116 // even when we need it to access it from another (debugger) thread.
3117 node_isolate = Isolate::GetCurrent();
3120 // Raise the open file descriptor limit.
3123 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3124 // Do a binary search for the limit.
3125 rlim_t min = lim.rlim_cur;
3126 rlim_t max = 1 << 20;
3127 // But if there's a defined upper bound, don't search, just set it.
3128 if (lim.rlim_max != RLIM_INFINITY) {
3133 lim.rlim_cur = min + (max - min) / 2;
3134 if (setrlimit(RLIMIT_NOFILE, &lim)) {
3139 } while (min + 1 < max);
3143 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3144 RegisterSignalHandler(SIGINT, SignalExit);
3145 RegisterSignalHandler(SIGTERM, SignalExit);
3148 V8::SetFatalErrorHandler(node::OnFatalError);
3149 V8::AddMessageListener(OnMessage);
3151 // If the --debug flag was specified then initialize the debug thread.
3152 if (use_debug_agent) {
3153 EnableDebug(debug_wait_connect);
3156 RegisterDebugSignalHandler();
3158 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3159 static uv_signal_t signal_watcher;
3160 uv_signal_init(uv_default_loop(), &signal_watcher);
3161 uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1);
3162 uv_unref(reinterpret_cast<uv_handle_t*>(&signal_watcher));
3168 struct AtExitCallback {
3169 AtExitCallback* next_;
3170 void (*cb_)(void* arg);
3174 static AtExitCallback* at_exit_functions_;
3177 // TODO(bnoordhuis) Turn into per-context event.
3178 void RunAtExit(Environment* env) {
3179 AtExitCallback* p = at_exit_functions_;
3180 at_exit_functions_ = NULL;
3183 AtExitCallback* q = p->next_;
3191 void AtExit(void (*cb)(void* arg), void* arg) {
3192 AtExitCallback* p = new AtExitCallback;
3195 p->next_ = at_exit_functions_;
3196 at_exit_functions_ = p;
3200 void EmitExit(Environment* env) {
3201 // process.emit('exit')
3202 Context::Scope context_scope(env->context());
3203 HandleScope handle_scope(env->isolate());
3204 Local<Object> process_object = env->process_object();
3205 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3206 True(node_isolate));
3208 Handle<String> exitCode = FIXED_ONE_BYTE_STRING(node_isolate, "exitCode");
3209 int code = process_object->Get(exitCode)->IntegerValue();
3211 Local<Value> args[] = {
3212 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3213 Integer::New(code, node_isolate)
3216 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3221 void SetIdle(uv_prepare_t* handle, int) {
3222 Environment* env = Environment::from_idle_prepare_handle(handle);
3223 env->isolate()->GetCpuProfiler()->SetIdle(true);
3227 void ClearIdle(uv_check_t* handle, int) {
3228 Environment* env = Environment::from_idle_check_handle(handle);
3229 env->isolate()->GetCpuProfiler()->SetIdle(false);
3233 Environment* CreateEnvironment(Isolate* isolate,
3235 const char* const* argv,
3237 const char* const* exec_argv) {
3238 HandleScope handle_scope(isolate);
3240 Local<Context> context = Context::New(isolate);
3241 Context::Scope context_scope(context);
3242 Environment* env = Environment::New(context);
3244 uv_check_init(env->event_loop(), env->immediate_check_handle());
3246 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3247 uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3249 Local<FunctionTemplate> process_template = FunctionTemplate::New();
3250 process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3252 Local<Object> process_object = process_template->GetFunction()->NewInstance();
3253 env->set_process_object(process_object);
3255 SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3258 // Inform V8's CPU profiler when we're idle. The profiler is sampling-based
3259 // but not all samples are created equal; mark the wall clock time spent in
3260 // epoll_wait() and friends so profiling tools can filter it out. The samples
3261 // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
3262 // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
3263 // probably fortify in the API contract, namely that the last started prepare
3264 // or check watcher runs first. It's not 100% foolproof; if an add-on starts
3265 // a prepare or check watcher after us, any samples attributed to its callback
3266 // will be recorded with state=IDLE.
3267 uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
3268 uv_prepare_start(env->idle_prepare_handle(), SetIdle);
3269 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
3270 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
3272 if (v8_is_profiling) {
3273 uv_check_init(env->event_loop(), env->idle_check_handle());
3274 uv_check_start(env->idle_check_handle(), ClearIdle);
3281 int Start(int argc, char** argv) {
3284 // Hack around with the argv pointer. Used for process.title = "blah".
3285 argv = uv_setup_args(argc, argv);
3287 // This needs to run *before* V8::Initialize(). The const_cast is not
3288 // optional, in case you're wondering.
3290 const char** exec_argv;
3291 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3294 // V8 on Windows doesn't have a good source of entropy. Seed it from
3296 V8::SetEntropySource(crypto::EntropySource);
3301 Locker locker(node_isolate);
3303 CreateEnvironment(node_isolate, argc, argv, exec_argc, exec_argv);
3304 Context::Scope context_scope(env->context());
3305 HandleScope handle_scope(env->isolate());
3306 uv_run(env->event_loop(), UV_RUN_DEFAULT);
3314 // Clean up. Not strictly necessary.