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 void SetIdle(uv_prepare_t* handle, int) {
2298 Environment* env = Environment::from_idle_prepare_handle(handle);
2299 env->isolate()->GetCpuProfiler()->SetIdle(true);
2303 void ClearIdle(uv_check_t* handle, int) {
2304 Environment* env = Environment::from_idle_check_handle(handle);
2305 env->isolate()->GetCpuProfiler()->SetIdle(false);
2309 void StartProfilerIdleNotifier(Environment* env) {
2310 uv_prepare_start(env->idle_prepare_handle(), SetIdle);
2311 uv_check_start(env->idle_check_handle(), ClearIdle);
2315 void StopProfilerIdleNotifier(Environment* env) {
2316 uv_prepare_stop(env->idle_prepare_handle());
2317 uv_check_stop(env->idle_check_handle());
2321 void StartProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2322 StartProfilerIdleNotifier(Environment::GetCurrent(args.GetIsolate()));
2326 void StopProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2327 StopProfilerIdleNotifier(Environment::GetCurrent(args.GetIsolate()));
2331 #define READONLY_PROPERTY(obj, str, var) \
2333 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2337 void SetupProcessObject(Environment* env,
2339 const char* const* argv,
2341 const char* const* exec_argv) {
2342 HandleScope scope(node_isolate);
2345 Local<Object> process = env->process_object();
2347 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2349 ProcessTitleSetter);
2352 READONLY_PROPERTY(process,
2354 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2356 // process.moduleLoadList
2357 READONLY_PROPERTY(process,
2359 env->module_load_list_array());
2362 Local<Object> versions = Object::New();
2363 READONLY_PROPERTY(process, "versions", versions);
2365 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2367 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2368 READONLY_PROPERTY(versions,
2370 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2372 // +1 to get rid of the leading 'v'
2373 READONLY_PROPERTY(versions,
2375 OneByteString(node_isolate, NODE_VERSION + 1));
2376 READONLY_PROPERTY(versions,
2378 OneByteString(node_isolate, V8::GetVersion()));
2379 READONLY_PROPERTY(versions,
2381 OneByteString(node_isolate, uv_version_string()));
2382 READONLY_PROPERTY(versions,
2384 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2386 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2387 READONLY_PROPERTY(versions,
2389 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2392 // Stupid code to slice out the version string.
2393 int c, l = strlen(OPENSSL_VERSION_TEXT);
2394 for (i = j = 0; i < l; i++) {
2395 c = OPENSSL_VERSION_TEXT[i];
2396 if ('0' <= c && c <= '9') {
2397 for (j = i + 1; j < l; j++) {
2398 c = OPENSSL_VERSION_TEXT[j];
2399 if (c == ' ') break;
2407 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2411 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2414 READONLY_PROPERTY(process,
2416 OneByteString(node_isolate, PLATFORM));
2419 Local<Array> arguments = Array::New(argc);
2420 for (int i = 0; i < argc; ++i) {
2421 arguments->Set(i, String::NewFromUtf8(node_isolate, argv[i]));
2423 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2426 Local<Array> exec_arguments = Array::New(exec_argc);
2427 for (int i = 0; i < exec_argc; ++i) {
2428 exec_arguments->Set(i, String::NewFromUtf8(node_isolate, exec_argv[i]));
2430 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_arguments);
2432 // create process.env
2433 Local<ObjectTemplate> process_env_template = ObjectTemplate::New();
2434 process_env_template->SetNamedPropertyHandler(EnvGetter,
2440 Local<Object> process_env = process_env_template->NewInstance();
2441 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), process_env);
2443 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2444 READONLY_PROPERTY(process, "features", GetFeatures());
2445 process->SetAccessor(
2446 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2447 NeedImmediateCallbackGetter,
2448 NeedImmediateCallbackSetter);
2452 READONLY_PROPERTY(process,
2454 String::NewFromUtf8(node_isolate, eval_string));
2459 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2462 // -i, --interactive
2464 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2468 if (no_deprecation) {
2469 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2472 // --throw-deprecation
2473 if (throw_deprecation) {
2474 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2477 // --trace-deprecation
2478 if (trace_deprecation) {
2479 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2482 size_t exec_path_len = 2 * PATH_MAX;
2483 char* exec_path = new char[exec_path_len];
2484 Local<String> exec_path_value;
2485 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2486 exec_path_value = String::NewFromUtf8(node_isolate,
2488 String::kNormalString,
2491 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2493 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2497 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2501 // define various internal methods
2502 NODE_SET_METHOD(process,
2503 "_startProfilerIdleNotifier",
2504 StartProfilerIdleNotifier);
2505 NODE_SET_METHOD(process,
2506 "_stopProfilerIdleNotifier",
2507 StopProfilerIdleNotifier);
2508 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2509 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2510 NODE_SET_METHOD(process, "reallyExit", Exit);
2511 NODE_SET_METHOD(process, "abort", Abort);
2512 NODE_SET_METHOD(process, "chdir", Chdir);
2513 NODE_SET_METHOD(process, "cwd", Cwd);
2515 NODE_SET_METHOD(process, "umask", Umask);
2517 #if defined(__POSIX__) && !defined(__ANDROID__)
2518 NODE_SET_METHOD(process, "getuid", GetUid);
2519 NODE_SET_METHOD(process, "setuid", SetUid);
2521 NODE_SET_METHOD(process, "setgid", SetGid);
2522 NODE_SET_METHOD(process, "getgid", GetGid);
2524 NODE_SET_METHOD(process, "getgroups", GetGroups);
2525 NODE_SET_METHOD(process, "setgroups", SetGroups);
2526 NODE_SET_METHOD(process, "initgroups", InitGroups);
2527 #endif // __POSIX__ && !defined(__ANDROID__)
2529 NODE_SET_METHOD(process, "_kill", Kill);
2531 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2532 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2533 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2535 NODE_SET_METHOD(process, "hrtime", Hrtime);
2537 NODE_SET_METHOD(process, "dlopen", DLOpen);
2539 NODE_SET_METHOD(process, "uptime", Uptime);
2540 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2542 NODE_SET_METHOD(process, "binding", Binding);
2544 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2546 // values use to cross communicate with processNextTick
2547 Local<Object> tick_info_obj = Object::New();
2548 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
2549 env->tick_info()->fields(),
2550 kExternalUnsignedIntArray,
2551 env->tick_info()->fields_count());
2552 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfo"), tick_info_obj);
2554 // pre-set _events object for faster emit checks
2555 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2559 #undef READONLY_PROPERTY
2562 static void AtExit() {
2563 uv_tty_reset_mode();
2567 static void SignalExit(int signal) {
2568 uv_tty_reset_mode();
2569 _exit(128 + signal);
2573 // Most of the time, it's best to use `console.error` to write
2574 // to the process.stderr stream. However, in some cases, such as
2575 // when debugging the stream.Writable class or the process.nextTick
2576 // function, it is useful to bypass JavaScript entirely.
2577 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2578 HandleScope scope(node_isolate);
2580 assert(args.Length() == 1 && args[0]->IsString() &&
2581 "must be called with a single string");
2583 String::Utf8Value message(args[0]);
2584 fprintf(stderr, "%s\n", *message);
2589 void Load(Environment* env) {
2590 HandleScope handle_scope(node_isolate);
2592 // Compile, execute the src/node.js file. (Which was included as static C
2593 // string in node_natives.h. 'natve_node' is the string containing that
2596 // The node.js file returns a function 'f'
2601 // Disable verbose mode to stop FatalException() handler from trying
2602 // to handle the exception. Errors this early in the start-up phase
2603 // are not safe to ignore.
2604 try_catch.SetVerbose(false);
2606 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2607 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2608 if (try_catch.HasCaught()) {
2609 ReportException(try_catch);
2612 assert(f_value->IsFunction());
2613 Local<Function> f = Local<Function>::Cast(f_value);
2615 // Now we call 'f' with the 'process' variable that we've built up with
2616 // all our bindings. Inside node.js we'll take care of assigning things to
2619 // We start the process this way in order to be more modular. Developers
2620 // who do not like how 'src/node.js' setups the module system but do like
2621 // Node's I/O bindings may want to replace 'f' with their own function.
2623 // Add a reference to the global object
2624 Local<Object> global = env->context()->Global();
2626 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2630 #if defined HAVE_PERFCTR
2631 InitPerfCounters(global);
2634 // Enable handling of uncaught exceptions
2635 // (FatalException(), break on uncaught exception in debugger)
2637 // This is not strictly necessary since it's almost impossible
2638 // to attach the debugger fast enought to break on exception
2639 // thrown during process startup.
2640 try_catch.SetVerbose(true);
2642 NODE_SET_METHOD(env->process_object(), "_rawDebug", RawDebug);
2644 Local<Value> arg = env->process_object();
2645 f->Call(global, 1, &arg);
2648 static void PrintHelp();
2650 static void ParseDebugOpt(const char* arg) {
2653 if (strstr(arg, "--debug-port=") == arg) {
2654 p = 1 + strchr(arg, '=');
2655 debug_port = atoi(p);
2657 use_debug_agent = true;
2658 if (!strcmp(arg, "--debug-brk")) {
2659 debug_wait_connect = true;
2661 } else if (!strcmp(arg, "--debug")) {
2663 } else if (strstr(arg, "--debug-brk=") == arg) {
2664 debug_wait_connect = true;
2665 p = 1 + strchr(arg, '=');
2666 debug_port = atoi(p);
2667 } else if (strstr(arg, "--debug=") == arg) {
2668 p = 1 + strchr(arg, '=');
2669 debug_port = atoi(p);
2672 if (p && debug_port > 1024 && debug_port < 65536)
2675 fprintf(stderr, "Bad debug option.\n");
2676 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2682 static void PrintHelp() {
2683 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2684 " node debug script.js [arguments] \n"
2687 " -v, --version print node's version\n"
2688 " -e, --eval script evaluate script\n"
2689 " -p, --print evaluate script and print result\n"
2690 " -i, --interactive always enter the REPL even if stdin\n"
2691 " does not appear to be a terminal\n"
2692 " --no-deprecation silence deprecation warnings\n"
2693 " --trace-deprecation show stack traces on deprecations\n"
2694 " --v8-options print v8 command line options\n"
2695 " --max-stack-size=val set max v8 stack size (bytes)\n"
2697 "Environment variables:\n"
2699 "NODE_PATH ';'-separated list of directories\n"
2701 "NODE_PATH ':'-separated list of directories\n"
2703 " prefixed to the module search path.\n"
2704 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2705 " global contexts.\n"
2706 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2708 "Documentation can be found at http://nodejs.org/\n");
2712 // Parse command line arguments.
2714 // argv is modified in place. exec_argv and v8_argv are out arguments that
2715 // ParseArgs() allocates memory for and stores a pointer to the output
2716 // vector in. The caller should free them with delete[].
2720 // * argv contains the arguments with node and V8 options filtered out.
2721 // * exec_argv contains both node and V8 options and nothing else.
2722 // * v8_argv contains argv[0] plus any V8 options
2723 static void ParseArgs(int* argc,
2726 const char*** exec_argv,
2728 const char*** v8_argv) {
2729 const unsigned int nargs = static_cast<unsigned int>(*argc);
2730 const char** new_exec_argv = new const char*[nargs];
2731 const char** new_v8_argv = new const char*[nargs];
2732 const char** new_argv = new const char*[nargs];
2734 for (unsigned int i = 0; i < nargs; ++i) {
2735 new_exec_argv[i] = NULL;
2736 new_v8_argv[i] = NULL;
2740 // exec_argv starts with the first option, the other two start with argv[0].
2741 unsigned int new_exec_argc = 0;
2742 unsigned int new_v8_argc = 1;
2743 unsigned int new_argc = 1;
2744 new_v8_argv[0] = argv[0];
2745 new_argv[0] = argv[0];
2747 unsigned int index = 1;
2748 while (index < nargs && argv[index][0] == '-') {
2749 const char* const arg = argv[index];
2750 unsigned int args_consumed = 1;
2752 if (strstr(arg, "--debug") == arg) {
2754 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2755 printf("%s\n", NODE_VERSION);
2757 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2760 } else if (strcmp(arg, "--eval") == 0 ||
2761 strcmp(arg, "-e") == 0 ||
2762 strcmp(arg, "--print") == 0 ||
2763 strcmp(arg, "-pe") == 0 ||
2764 strcmp(arg, "-p") == 0) {
2765 bool is_eval = strchr(arg, 'e') != NULL;
2766 bool is_print = strchr(arg, 'p') != NULL;
2767 print_eval = print_eval || is_print;
2768 // --eval, -e and -pe always require an argument.
2769 if (is_eval == true) {
2771 eval_string = argv[index + 1];
2772 if (eval_string == NULL) {
2773 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
2776 } else if (argv[index + 1] != NULL && argv[index + 1][0] != '-') {
2778 eval_string = argv[index + 1];
2779 if (strncmp(eval_string, "\\-", 2) == 0) {
2780 // Starts with "\\-": escaped expression, drop the backslash.
2784 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2786 } else if (strcmp(arg, "--no-deprecation") == 0) {
2787 no_deprecation = true;
2788 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2789 trace_deprecation = true;
2790 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2791 throw_deprecation = true;
2792 } else if (strcmp(arg, "--v8-options") == 0) {
2793 new_v8_argv[new_v8_argc] = "--help";
2796 // V8 option. Pass through as-is.
2797 new_v8_argv[new_v8_argc] = arg;
2801 memcpy(new_exec_argv + new_exec_argc,
2803 args_consumed * sizeof(*argv));
2805 new_exec_argc += args_consumed;
2806 index += args_consumed;
2809 // Copy remaining arguments.
2810 const unsigned int args_left = nargs - index;
2811 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
2812 new_argc += args_left;
2814 *exec_argc = new_exec_argc;
2815 *exec_argv = new_exec_argv;
2816 *v8_argc = new_v8_argc;
2817 *v8_argv = new_v8_argv;
2819 // Copy new_argv over argv and update argc.
2820 memcpy(argv, new_argv, new_argc * sizeof(*argv));
2822 *argc = static_cast<int>(new_argc);
2826 // Called from the main thread.
2827 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2828 v8::Debug::ProcessDebugMessages();
2832 // Called from V8 Debug Agent TCP thread.
2833 static void DispatchMessagesDebugAgentCallback() {
2834 uv_async_send(&dispatch_debug_messages_async);
2838 // Called from the main thread
2839 static void EmitDebugEnabledAsyncCallback(uv_async_t* handle, int status) {
2840 Environment* env = Environment::GetCurrent(node_isolate);
2841 Context::Scope context_scope(env->context());
2842 HandleScope handle_scope(env->isolate());
2843 Local<Object> message = Object::New();
2844 message->Set(FIXED_ONE_BYTE_STRING(node_isolate, "cmd"),
2845 FIXED_ONE_BYTE_STRING(node_isolate, "NODE_DEBUG_ENABLED"));
2846 Local<Value> args[] = {
2847 FIXED_ONE_BYTE_STRING(node_isolate, "internalMessage"),
2850 MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(args), args);
2854 // Called from the signal watcher callback
2855 static void EmitDebugEnabled() {
2856 uv_async_send(&emit_debug_enabled_async);
2860 static void EnableDebug(bool wait_connect) {
2861 // If we're called from another thread, make sure to enter the right
2863 node_isolate->Enter();
2865 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2868 // Start the debug thread and it's associated TCP server on port 5858.
2869 bool r = v8::Debug::EnableAgent("node " NODE_VERSION,
2873 // Crappy check that everything went well. FIXME
2876 // Print out some information.
2877 fprintf(stderr, "debugger listening on port %d\n", debug_port);
2880 debugger_running = true;
2882 if (Environment::GetCurrentChecked(node_isolate) != NULL) {
2886 node_isolate->Exit();
2891 static void EnableDebugSignalHandler(uv_signal_t* handle, int) {
2892 // Break once process will return execution to v8
2893 v8::Debug::DebugBreak(node_isolate);
2895 if (!debugger_running) {
2896 fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n");
2902 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2903 struct sigaction sa;
2905 memset(&sa, 0, sizeof(sa));
2906 sa.sa_handler = handler;
2907 sigfillset(&sa.sa_mask);
2908 sigaction(signal, &sa, NULL);
2912 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2913 HandleScope scope(node_isolate);
2915 if (args.Length() != 1) {
2916 return ThrowError("Invalid number of arguments.");
2922 pid = args[0]->IntegerValue();
2923 r = kill(pid, SIGUSR1);
2925 return ThrowErrnoException(errno, "kill");
2932 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2933 // Break once process will return execution to v8
2934 if (!debugger_running) {
2935 for (int i = 0; i < 1; i++) {
2936 fprintf(stderr, "Starting debugger agent.\r\n");
2942 v8::Debug::DebugBreak(node_isolate);
2948 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2950 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2954 static int RegisterDebugSignalHandler() {
2955 wchar_t mapping_name[32];
2956 HANDLE mapping_handle;
2958 LPTHREAD_START_ROUTINE* handler;
2960 pid = GetCurrentProcessId();
2962 if (GetDebugSignalHandlerMappingName(pid,
2964 ARRAY_SIZE(mapping_name)) < 0) {
2968 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2974 if (mapping_handle == NULL) {
2978 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2979 MapViewOfFile(mapping_handle,
2980 FILE_MAP_ALL_ACCESS,
2984 if (handler == NULL) {
2985 CloseHandle(mapping_handle);
2989 *handler = EnableDebugThreadProc;
2991 UnmapViewOfFile(static_cast<void*>(handler));
2997 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2998 HandleScope scope(node_isolate);
3000 HANDLE process = NULL;
3001 HANDLE thread = NULL;
3002 HANDLE mapping = NULL;
3003 wchar_t mapping_name[32];
3004 LPTHREAD_START_ROUTINE* handler = NULL;
3006 if (args.Length() != 1) {
3007 ThrowError("Invalid number of arguments.");
3011 pid = (DWORD) args[0]->IntegerValue();
3013 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
3014 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
3018 if (process == NULL) {
3019 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
3023 if (GetDebugSignalHandlerMappingName(pid,
3025 ARRAY_SIZE(mapping_name)) < 0) {
3026 ThrowErrnoException(errno, "sprintf");
3030 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
3031 if (mapping == NULL) {
3032 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
3036 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3037 MapViewOfFile(mapping,
3042 if (handler == NULL || *handler == NULL) {
3043 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
3047 thread = CreateRemoteThread(process,
3054 if (thread == NULL) {
3055 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
3059 // Wait for the thread to terminate
3060 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3061 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
3066 if (process != NULL)
3067 CloseHandle(process);
3069 CloseHandle(thread);
3070 if (handler != NULL)
3071 UnmapViewOfFile(handler);
3072 if (mapping != NULL)
3073 CloseHandle(mapping);
3078 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3079 v8::Debug::DebugBreak(node_isolate);
3083 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3084 if (debugger_running) {
3085 v8::Debug::DisableAgent();
3086 debugger_running = false;
3091 void Init(int* argc,
3094 const char*** exec_argv) {
3095 // Initialize prog_start_time to get relative uptime.
3096 uv_uptime(&prog_start_time);
3098 // Make inherited handles noninheritable.
3099 uv_disable_stdio_inheritance();
3101 // init async debug messages dispatching
3102 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3103 uv_async_init(uv_default_loop(),
3104 &dispatch_debug_messages_async,
3105 DispatchDebugMessagesAsyncCallback);
3106 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3108 // init async NODE_DEBUG_ENABLED emitter
3109 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3110 uv_async_init(uv_default_loop(),
3111 &emit_debug_enabled_async,
3112 EmitDebugEnabledAsyncCallback);
3113 uv_unref(reinterpret_cast<uv_handle_t*>(&emit_debug_enabled_async));
3115 // Parse a few arguments which are specific to Node.
3117 const char** v8_argv;
3118 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3120 // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
3121 // manually? That would give us a little more control over its runtime
3122 // behavior but it could also interfere with the user's intentions in ways
3123 // we fail to anticipate. Dillema.
3124 for (int i = 1; i < v8_argc; ++i) {
3125 if (strncmp(v8_argv[i], "--prof", sizeof("--prof") - 1) == 0) {
3126 v8_is_profiling = true;
3131 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3132 // the argv array or the elements it points to.
3133 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3135 // Anything that's still in v8_argv is not a V8 or a node option.
3136 for (int i = 1; i < v8_argc; i++) {
3137 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3146 if (debug_wait_connect) {
3147 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3148 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3151 const char typed_arrays_flag[] = "--harmony_typed_arrays";
3152 V8::SetFlagsFromString(typed_arrays_flag, sizeof(typed_arrays_flag) - 1);
3153 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3155 // Fetch a reference to the main isolate, so we have a reference to it
3156 // even when we need it to access it from another (debugger) thread.
3157 node_isolate = Isolate::GetCurrent();
3160 // Raise the open file descriptor limit.
3163 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3164 // Do a binary search for the limit.
3165 rlim_t min = lim.rlim_cur;
3166 rlim_t max = 1 << 20;
3167 // But if there's a defined upper bound, don't search, just set it.
3168 if (lim.rlim_max != RLIM_INFINITY) {
3173 lim.rlim_cur = min + (max - min) / 2;
3174 if (setrlimit(RLIMIT_NOFILE, &lim)) {
3179 } while (min + 1 < max);
3183 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3184 RegisterSignalHandler(SIGINT, SignalExit);
3185 RegisterSignalHandler(SIGTERM, SignalExit);
3188 V8::SetFatalErrorHandler(node::OnFatalError);
3189 V8::AddMessageListener(OnMessage);
3191 // If the --debug flag was specified then initialize the debug thread.
3192 if (use_debug_agent) {
3193 EnableDebug(debug_wait_connect);
3196 RegisterDebugSignalHandler();
3198 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3199 static uv_signal_t signal_watcher;
3200 uv_signal_init(uv_default_loop(), &signal_watcher);
3201 uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1);
3202 uv_unref(reinterpret_cast<uv_handle_t*>(&signal_watcher));
3208 struct AtExitCallback {
3209 AtExitCallback* next_;
3210 void (*cb_)(void* arg);
3214 static AtExitCallback* at_exit_functions_;
3217 // TODO(bnoordhuis) Turn into per-context event.
3218 void RunAtExit(Environment* env) {
3219 AtExitCallback* p = at_exit_functions_;
3220 at_exit_functions_ = NULL;
3223 AtExitCallback* q = p->next_;
3231 void AtExit(void (*cb)(void* arg), void* arg) {
3232 AtExitCallback* p = new AtExitCallback;
3235 p->next_ = at_exit_functions_;
3236 at_exit_functions_ = p;
3240 void EmitExit(Environment* env) {
3241 // process.emit('exit')
3242 Context::Scope context_scope(env->context());
3243 HandleScope handle_scope(env->isolate());
3244 Local<Object> process_object = env->process_object();
3245 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3246 True(node_isolate));
3248 Handle<String> exitCode = FIXED_ONE_BYTE_STRING(node_isolate, "exitCode");
3249 int code = process_object->Get(exitCode)->IntegerValue();
3251 Local<Value> args[] = {
3252 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3253 Integer::New(code, node_isolate)
3256 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3261 Environment* CreateEnvironment(Isolate* isolate,
3263 const char* const* argv,
3265 const char* const* exec_argv) {
3266 HandleScope handle_scope(isolate);
3268 Local<Context> context = Context::New(isolate);
3269 Context::Scope context_scope(context);
3270 Environment* env = Environment::New(context);
3272 uv_check_init(env->event_loop(), env->immediate_check_handle());
3274 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3275 uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3277 // Inform V8's CPU profiler when we're idle. The profiler is sampling-based
3278 // but not all samples are created equal; mark the wall clock time spent in
3279 // epoll_wait() and friends so profiling tools can filter it out. The samples
3280 // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
3281 // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
3282 // probably fortify in the API contract, namely that the last started prepare
3283 // or check watcher runs first. It's not 100% foolproof; if an add-on starts
3284 // a prepare or check watcher after us, any samples attributed to its callback
3285 // will be recorded with state=IDLE.
3286 uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
3287 uv_prepare_start(env->idle_prepare_handle(), SetIdle);
3288 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
3289 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
3291 if (v8_is_profiling) {
3292 uv_check_init(env->event_loop(), env->idle_check_handle());
3293 uv_check_start(env->idle_check_handle(), ClearIdle);
3296 Local<FunctionTemplate> process_template = FunctionTemplate::New();
3297 process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3299 Local<Object> process_object = process_template->GetFunction()->NewInstance();
3300 env->set_process_object(process_object);
3302 SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3309 int Start(int argc, char** argv) {
3312 // Hack around with the argv pointer. Used for process.title = "blah".
3313 argv = uv_setup_args(argc, argv);
3315 // This needs to run *before* V8::Initialize(). The const_cast is not
3316 // optional, in case you're wondering.
3318 const char** exec_argv;
3319 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3322 // V8 on Windows doesn't have a good source of entropy. Seed it from
3324 V8::SetEntropySource(crypto::EntropySource);
3329 Locker locker(node_isolate);
3331 CreateEnvironment(node_isolate, argc, argv, exec_argc, exec_argv);
3332 Context::Scope context_scope(env->context());
3333 HandleScope handle_scope(env->isolate());
3334 uv_run(env->event_loop(), UV_RUN_DEFAULT);
3342 // Clean up. Not strictly necessary.