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;
135 // used by C++ modules as well
136 bool no_deprecation = false;
138 // process-relative uptime base, initialized at start-up
139 static double prog_start_time;
141 static volatile bool debugger_running = false;
142 static uv_async_t dispatch_debug_messages_async;
143 static uv_async_t emit_debug_enabled_async;
145 // Declared in node_internals.h
146 Isolate* node_isolate = NULL;
149 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
151 // Impose an upper limit to avoid out of memory errors that bring down
153 static const size_t kMaxLength = 0x3fffffff;
154 static ArrayBufferAllocator the_singleton;
155 virtual ~ArrayBufferAllocator() {}
156 virtual void* Allocate(size_t length);
157 virtual void Free(void* data);
159 ArrayBufferAllocator() {}
160 ArrayBufferAllocator(const ArrayBufferAllocator&);
161 void operator=(const ArrayBufferAllocator&);
164 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
167 void* ArrayBufferAllocator::Allocate(size_t length) {
168 if (length > kMaxLength) return NULL;
169 return new char[length];
173 void ArrayBufferAllocator::Free(void* data) {
174 delete[] static_cast<char*>(data);
178 static void CheckImmediate(uv_check_t* handle, int status) {
179 Environment* env = Environment::from_immediate_check_handle(handle);
180 Context::Scope context_scope(env->context());
181 MakeCallback(env, env->process_object(), env->immediate_callback_string());
185 static void IdleImmediateDummy(uv_idle_t*, int) {
186 // Do nothing. Only for maintaining event loop.
187 // TODO(bnoordhuis) Maybe make libuv accept NULL idle callbacks.
191 static inline const char *errno_string(int errorno) {
192 #define ERRNO_CASE(e) case e: return #e;
199 ERRNO_CASE(EADDRINUSE);
203 ERRNO_CASE(EADDRNOTAVAIL);
207 ERRNO_CASE(EAFNOSUPPORT);
215 # if EAGAIN != EWOULDBLOCK
216 ERRNO_CASE(EWOULDBLOCK);
221 ERRNO_CASE(EALREADY);
237 ERRNO_CASE(ECANCELED);
245 ERRNO_CASE(ECONNABORTED);
249 ERRNO_CASE(ECONNREFUSED);
253 ERRNO_CASE(ECONNRESET);
261 ERRNO_CASE(EDESTADDRREQ);
285 ERRNO_CASE(EHOSTUNREACH);
297 ERRNO_CASE(EINPROGRESS);
333 ERRNO_CASE(EMSGSIZE);
337 ERRNO_CASE(EMULTIHOP);
341 ERRNO_CASE(ENAMETOOLONG);
345 ERRNO_CASE(ENETDOWN);
349 ERRNO_CASE(ENETRESET);
353 ERRNO_CASE(ENETUNREACH);
385 # if ENOLINK != ENOLCK
399 ERRNO_CASE(ENOPROTOOPT);
419 ERRNO_CASE(ENOTCONN);
427 ERRNO_CASE(ENOTEMPTY);
431 ERRNO_CASE(ENOTSOCK);
438 ERRNO_CASE(EOPNOTSUPP);
452 ERRNO_CASE(EOVERFLOW);
467 #ifdef EPROTONOSUPPORT
468 ERRNO_CASE(EPROTONOSUPPORT);
472 ERRNO_CASE(EPROTOTYPE);
500 ERRNO_CASE(ETIMEDOUT);
515 const char *signo_string(int signo) {
516 #define SIGNO_CASE(e) case e: return #e;
543 # if SIGABRT != SIGIOT
587 SIGNO_CASE(SIGSTKFLT);
604 SIGNO_CASE(SIGBREAK);
628 SIGNO_CASE(SIGVTALRM);
636 SIGNO_CASE(SIGWINCH);
644 # if SIGPOLL != SIGIO
654 # if SIGPWR != SIGLOST
668 Local<Value> ErrnoException(int errorno,
672 Environment* env = Environment::GetCurrent(node_isolate);
675 Local<String> estring = OneByteString(node_isolate, errno_string(errorno));
676 if (msg == NULL || msg[0] == '\0') {
677 msg = strerror(errorno);
679 Local<String> message = OneByteString(node_isolate, msg);
681 Local<String> cons1 =
682 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
683 Local<String> cons2 = String::Concat(cons1, message);
686 Local<String> cons3 =
687 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
688 Local<String> cons4 =
689 String::Concat(cons3, String::NewFromUtf8(node_isolate, path));
690 Local<String> cons5 =
691 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
692 e = Exception::Error(cons5);
694 e = Exception::Error(cons2);
697 Local<Object> obj = e->ToObject();
698 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
699 obj->Set(env->code_string(), estring);
702 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
705 if (syscall != NULL) {
706 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
713 // hack alert! copy of ErrnoException, tuned for uv errors
714 Local<Value> UVException(int errorno,
718 Environment* env = Environment::GetCurrent(node_isolate);
721 msg = uv_strerror(errorno);
723 Local<String> estring = OneByteString(node_isolate, uv_err_name(errorno));
724 Local<String> message = OneByteString(node_isolate, msg);
725 Local<String> cons1 =
726 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
727 Local<String> cons2 = String::Concat(cons1, message);
731 Local<String> path_str;
735 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
736 path_str = String::Concat(FIXED_ONE_BYTE_STRING(node_isolate, "\\\\"),
737 String::NewFromUtf8(node_isolate, path + 8));
738 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
739 path_str = String::NewFromUtf8(node_isolate, path + 4);
741 path_str = String::NewFromUtf8(node_isolate, path);
744 path_str = String::NewFromUtf8(node_isolate, path);
747 Local<String> cons3 =
748 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
749 Local<String> cons4 =
750 String::Concat(cons3, path_str);
751 Local<String> cons5 =
752 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
753 e = Exception::Error(cons5);
755 e = Exception::Error(cons2);
758 Local<Object> obj = e->ToObject();
759 // TODO(piscisaureus) errno should probably go
760 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
761 obj->Set(env->code_string(), estring);
764 obj->Set(env->path_string(), path_str);
767 if (syscall != NULL) {
768 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
776 // Does about the same as strerror(),
777 // but supports all windows error messages
778 static const char *winapi_strerror(const int errorno) {
781 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
782 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
783 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
786 // Remove trailing newlines
787 for (int i = strlen(errmsg) - 1;
788 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
794 // FormatMessage failed
795 return "Unknown error";
800 Local<Value> WinapiErrnoException(int errorno,
804 Environment* env = Environment::GetCurrent(node_isolate);
807 if (!msg || !msg[0]) {
808 msg = winapi_strerror(errorno);
810 Local<String> message = OneByteString(node_isolate, msg);
813 Local<String> cons1 =
814 String::Concat(message, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
815 Local<String> cons2 =
816 String::Concat(cons1, String::NewFromUtf8(node_isolate, path));
817 Local<String> cons3 =
818 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
819 e = Exception::Error(cons3);
821 e = Exception::Error(message);
824 Local<Object> obj = e->ToObject();
825 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
828 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
831 if (syscall != NULL) {
832 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
840 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
841 Environment* env = Environment::GetCurrent(args.GetIsolate());
843 if (env->using_domains()) return;
844 env->set_using_domains(true);
846 HandleScope scope(node_isolate);
847 Local<Object> process_object = env->process_object();
849 Local<String> tick_callback_function_key =
850 FIXED_ONE_BYTE_STRING(node_isolate, "_tickDomainCallback");
851 Local<Function> tick_callback_function =
852 process_object->Get(tick_callback_function_key).As<Function>();
854 if (!tick_callback_function->IsFunction()) {
855 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
859 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"),
860 tick_callback_function);
861 env->set_tick_callback_function(tick_callback_function);
863 if (!args[0]->IsArray()) {
864 fprintf(stderr, "_setupDomainUse first argument must be an array\n");
867 env->set_domain_array(args[0].As<Array>());
869 if (!args[1]->IsObject()) {
870 fprintf(stderr, "_setupDomainUse second argument must be an object\n");
874 Local<Object> domain_flag_obj = args[1].As<Object>();
875 Environment::DomainFlag* domain_flag = env->domain_flag();
876 domain_flag_obj->SetIndexedPropertiesToExternalArrayData(
877 domain_flag->fields(),
878 kExternalUnsignedIntArray,
879 domain_flag->fields_count());
883 Handle<Value> MakeDomainCallback(Environment* env,
884 const Handle<Object> object,
885 const Handle<Function> callback,
887 Handle<Value> argv[]) {
888 // If you hit this assertion, you forgot to enter the v8::Context first.
889 assert(env->context() == env->isolate()->GetCurrentContext());
891 // TODO(trevnorris) Hook for long stack traces to be made here.
893 Local<Value> domain_v = object->Get(env->domain_string());
894 Local<Object> domain;
897 try_catch.SetVerbose(true);
899 bool has_domain = domain_v->IsObject();
901 domain = domain_v.As<Object>();
903 if (domain->Get(env->disposed_string())->IsTrue()) {
904 // domain has been disposed of.
905 return Undefined(node_isolate);
908 Local<Function> enter =
909 domain->Get(env->enter_string()).As<Function>();
910 assert(enter->IsFunction());
911 enter->Call(domain, 0, NULL);
913 if (try_catch.HasCaught()) {
914 return Undefined(node_isolate);
918 Local<Value> ret = callback->Call(object, argc, argv);
920 if (try_catch.HasCaught()) {
921 return Undefined(node_isolate);
925 Local<Function> exit =
926 domain->Get(env->exit_string()).As<Function>();
927 assert(exit->IsFunction());
928 exit->Call(domain, 0, NULL);
930 if (try_catch.HasCaught()) {
931 return Undefined(node_isolate);
935 Environment::TickInfo* tick_info = env->tick_info();
937 if (tick_info->last_threw() == 1) {
938 tick_info->set_last_threw(0);
942 if (tick_info->in_tick() == 1) {
946 if (tick_info->length() == 0) {
947 tick_info->set_index(0);
951 // process nextTicks after call
952 Local<Object> process_object = env->process_object();
953 Local<Function> tick_callback_function = env->tick_callback_function();
954 tick_callback_function->Call(process_object, 0, NULL);
956 if (try_catch.HasCaught()) {
957 return Undefined(node_isolate);
964 Handle<Value> MakeCallback(Environment* env,
965 const Handle<Object> object,
966 const Handle<Function> callback,
968 Handle<Value> argv[]) {
969 // If you hit this assertion, you forgot to enter the v8::Context first.
970 assert(env->context() == env->isolate()->GetCurrentContext());
972 // TODO(trevnorris) Hook for long stack traces to be made here.
973 Local<Object> process_object = env->process_object();
975 if (env->using_domains())
976 return MakeDomainCallback(env, object, callback, argc, argv);
979 try_catch.SetVerbose(true);
981 Local<Value> ret = callback->Call(object, argc, argv);
983 if (try_catch.HasCaught()) {
984 return Undefined(node_isolate);
987 Environment::TickInfo* tick_info = env->tick_info();
989 if (tick_info->in_tick() == 1) {
993 if (tick_info->length() == 0) {
994 tick_info->set_index(0);
998 // lazy load no domain next tick callbacks
999 Local<Function> tick_callback_function = env->tick_callback_function();
1000 if (tick_callback_function.IsEmpty()) {
1001 Local<String> tick_callback_function_key =
1002 FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback");
1003 tick_callback_function =
1004 process_object->Get(tick_callback_function_key).As<Function>();
1005 if (!tick_callback_function->IsFunction()) {
1006 fprintf(stderr, "process._tickCallback assigned to non-function\n");
1009 env->set_tick_callback_function(tick_callback_function);
1012 // process nextTicks after call
1013 tick_callback_function->Call(process_object, 0, NULL);
1015 if (try_catch.HasCaught()) {
1016 return Undefined(node_isolate);
1024 Handle<Value> MakeCallback(Environment* env,
1025 const Handle<Object> object,
1028 Handle<Value> argv[]) {
1029 // If you hit this assertion, you forgot to enter the v8::Context first.
1030 assert(env->context() == env->isolate()->GetCurrentContext());
1032 Local<Function> callback = object->Get(index).As<Function>();
1033 assert(callback->IsFunction());
1035 if (env->using_domains()) {
1036 return MakeDomainCallback(env, object, callback, argc, argv);
1039 return MakeCallback(env, object, callback, argc, argv);
1043 Handle<Value> MakeCallback(Environment* env,
1044 const Handle<Object> object,
1045 const Handle<String> symbol,
1047 Handle<Value> argv[]) {
1048 // If you hit this assertion, you forgot to enter the v8::Context first.
1049 assert(env->context() == env->isolate()->GetCurrentContext());
1051 Local<Function> callback = object->Get(symbol).As<Function>();
1052 assert(callback->IsFunction());
1054 if (env->using_domains()) {
1055 return MakeDomainCallback(env, object, callback, argc, argv);
1058 return MakeCallback(env, object, callback, argc, argv);
1062 Handle<Value> MakeCallback(Environment* env,
1063 const Handle<Object> object,
1066 Handle<Value> argv[]) {
1067 // If you hit this assertion, you forgot to enter the v8::Context first.
1068 assert(env->context() == env->isolate()->GetCurrentContext());
1069 Local<String> method_string = OneByteString(node_isolate, method);
1070 return MakeCallback(env, object, method_string, argc, argv);
1074 Handle<Value> MakeCallback(const Handle<Object> object,
1077 Handle<Value> argv[]) {
1078 Local<Context> context = object->CreationContext();
1079 Environment* env = Environment::GetCurrent(context);
1080 Context::Scope context_scope(context);
1081 HandleScope handle_scope(env->isolate());
1082 return handle_scope.Close(MakeCallback(env, object, method, argc, argv));
1086 Handle<Value> MakeCallback(const Handle<Object> object,
1087 const Handle<String> symbol,
1089 Handle<Value> argv[]) {
1090 Local<Context> context = object->CreationContext();
1091 Environment* env = Environment::GetCurrent(context);
1092 Context::Scope context_scope(context);
1093 HandleScope handle_scope(env->isolate());
1094 return handle_scope.Close(MakeCallback(env, object, symbol, argc, argv));
1098 Handle<Value> MakeCallback(const Handle<Object> object,
1099 const Handle<Function> callback,
1101 Handle<Value> argv[]) {
1102 Local<Context> context = object->CreationContext();
1103 Environment* env = Environment::GetCurrent(context);
1104 Context::Scope context_scope(context);
1105 HandleScope handle_scope(env->isolate());
1106 return handle_scope.Close(MakeCallback(env, object, callback, argc, argv));
1110 Handle<Value> MakeDomainCallback(const Handle<Object> object,
1111 const Handle<Function> callback,
1113 Handle<Value> argv[]) {
1114 Local<Context> context = object->CreationContext();
1115 Environment* env = Environment::GetCurrent(context);
1116 Context::Scope context_scope(context);
1117 HandleScope handle_scope(env->isolate());
1118 return handle_scope.Close(
1119 MakeDomainCallback(env, object, callback, argc, argv));
1123 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1124 HandleScope scope(node_isolate);
1126 if (!encoding_v->IsString()) return _default;
1128 String::Utf8Value encoding(encoding_v);
1130 if (strcasecmp(*encoding, "utf8") == 0) {
1132 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1134 } else if (strcasecmp(*encoding, "ascii") == 0) {
1136 } else if (strcasecmp(*encoding, "base64") == 0) {
1138 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1140 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1142 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1144 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1146 } else if (strcasecmp(*encoding, "binary") == 0) {
1148 } else if (strcasecmp(*encoding, "buffer") == 0) {
1150 } else if (strcasecmp(*encoding, "hex") == 0) {
1152 } else if (strcasecmp(*encoding, "raw") == 0) {
1153 if (!no_deprecation) {
1154 fprintf(stderr, "'raw' (array of integers) has been removed. "
1158 } else if (strcasecmp(*encoding, "raws") == 0) {
1159 if (!no_deprecation) {
1160 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1161 "Please update your code.\n");
1169 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1170 return StringBytes::Encode(static_cast<const char*>(buf),
1175 // Returns -1 if the handle was not valid for decoding
1176 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1177 HandleScope scope(node_isolate);
1179 if (val->IsArray()) {
1180 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1186 return StringBytes::Size(val, encoding);
1190 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1193 // Returns number of bytes written.
1194 ssize_t DecodeWrite(char *buf,
1196 v8::Handle<v8::Value> val,
1197 enum encoding encoding) {
1198 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1201 void DisplayExceptionLine(Handle<Message> message) {
1202 // Prevent re-entry into this function. For example, if there is
1203 // a throw from a program in vm.runInThisContext(code, filename, true),
1204 // then we want to show the original failure, not the secondary one.
1205 static bool displayed_error = false;
1207 if (displayed_error) return;
1208 displayed_error = true;
1210 uv_tty_reset_mode();
1212 fprintf(stderr, "\n");
1214 if (!message.IsEmpty()) {
1215 // Print (filename):(line number): (message).
1216 String::Utf8Value filename(message->GetScriptResourceName());
1217 const char* filename_string = *filename;
1218 int linenum = message->GetLineNumber();
1219 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1220 // Print line of source code.
1221 String::Utf8Value sourceline(message->GetSourceLine());
1222 const char* sourceline_string = *sourceline;
1224 // Because of how node modules work, all scripts are wrapped with a
1225 // "function (module, exports, __filename, ...) {"
1226 // to provide script local variables.
1228 // When reporting errors on the first line of a script, this wrapper
1229 // function is leaked to the user. There used to be a hack here to
1230 // truncate off the first 62 characters, but it caused numerous other
1231 // problems when vm.runIn*Context() methods were used for non-module
1234 // If we ever decide to re-instate such a hack, the following steps
1237 // 1. Pass a flag around to say "this code was wrapped"
1238 // 2. Update the stack frame output so that it is also correct.
1240 // It would probably be simpler to add a line rather than add some
1241 // number of characters to the first line, since V8 truncates the
1242 // sourceline to 78 characters, and we end up not providing very much
1243 // useful debugging info to the user if we remove 62 characters.
1245 int start = message->GetStartColumn();
1246 int end = message->GetEndColumn();
1248 fprintf(stderr, "%s\n", sourceline_string);
1249 // Print wavy underline (GetUnderline is deprecated).
1250 for (int i = 0; i < start; i++) {
1251 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1253 for (int i = start; i < end; i++) {
1256 fputc('\n', stderr);
1261 static void ReportException(Handle<Value> er, Handle<Message> message) {
1262 HandleScope scope(node_isolate);
1264 DisplayExceptionLine(message);
1266 Local<Value> trace_value(
1267 er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack")));
1268 String::Utf8Value trace(trace_value);
1270 // range errors have a trace member set to undefined
1271 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1272 fprintf(stderr, "%s\n", *trace);
1274 // this really only happens for RangeErrors, since they're the only
1275 // kind that won't have all this info in the trace, or when non-Error
1276 // objects are thrown manually.
1277 Local<Value> message;
1280 if (er->IsObject()) {
1281 Local<Object> err_obj = er.As<Object>();
1282 message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1283 name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1286 if (message.IsEmpty() ||
1287 message->IsUndefined() ||
1289 name->IsUndefined()) {
1290 // Not an error object. Just print as-is.
1291 String::Utf8Value message(er);
1292 fprintf(stderr, "%s\n", *message);
1294 String::Utf8Value name_string(name);
1295 String::Utf8Value message_string(message);
1296 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1304 static void ReportException(const TryCatch& try_catch) {
1305 ReportException(try_catch.Exception(), try_catch.Message());
1309 // Executes a str within the current v8 context.
1310 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1311 HandleScope scope(node_isolate);
1314 // try_catch must be nonverbose to disable FatalException() handler,
1315 // we will handle exceptions ourself.
1316 try_catch.SetVerbose(false);
1318 Local<v8::Script> script = v8::Script::Compile(source, filename);
1319 if (script.IsEmpty()) {
1320 ReportException(try_catch);
1324 Local<Value> result = script->Run();
1325 if (result.IsEmpty()) {
1326 ReportException(try_catch);
1330 return scope.Close(result);
1334 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1335 HandleScope scope(node_isolate);
1337 Local<Array> ary = Array::New();
1341 QUEUE_FOREACH(q, &req_wrap_queue) {
1342 ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1343 if (w->persistent().IsEmpty()) continue;
1344 ary->Set(i++, w->object());
1347 args.GetReturnValue().Set(ary);
1351 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1352 // implemented here for consistency with GetActiveRequests().
1353 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1354 HandleScope scope(node_isolate);
1356 Local<Array> ary = Array::New();
1360 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1362 QUEUE_FOREACH(q, &handle_wrap_queue) {
1363 HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1364 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue;
1365 Local<Object> object = w->object();
1366 Local<Value> owner = object->Get(owner_sym);
1367 if (owner->IsUndefined()) owner = object;
1368 ary->Set(i++, owner);
1371 args.GetReturnValue().Set(ary);
1375 static void Abort(const FunctionCallbackInfo<Value>& args) {
1380 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1381 HandleScope scope(node_isolate);
1383 if (args.Length() != 1 || !args[0]->IsString()) {
1384 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1387 String::Utf8Value path(args[0]);
1388 int err = uv_chdir(*path);
1390 return ThrowUVException(err, "uv_chdir");
1395 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1396 HandleScope scope(node_isolate);
1398 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1399 char buf[MAX_PATH * 4 + 1];
1401 char buf[PATH_MAX + 1];
1404 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1406 return ThrowUVException(err, "uv_cwd");
1409 buf[ARRAY_SIZE(buf) - 1] = '\0';
1410 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1412 args.GetReturnValue().Set(cwd);
1416 static void Umask(const FunctionCallbackInfo<Value>& args) {
1417 HandleScope scope(node_isolate);
1420 if (args.Length() < 1 || args[0]->IsUndefined()) {
1422 umask(static_cast<mode_t>(old));
1423 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1424 return ThrowTypeError("argument must be an integer or octal string.");
1427 if (args[0]->IsInt32()) {
1428 oct = args[0]->Uint32Value();
1431 String::Utf8Value str(args[0]);
1433 // Parse the octal string.
1434 for (int i = 0; i < str.length(); i++) {
1436 if (c > '7' || c < '0') {
1437 return ThrowTypeError("invalid octal string");
1443 old = umask(static_cast<mode_t>(oct));
1446 args.GetReturnValue().Set(old);
1450 #if defined(__POSIX__) && !defined(__ANDROID__)
1452 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1453 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1456 static uid_t uid_by_name(const char* name) {
1464 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1468 return uid_not_found;
1472 static char* name_by_uid(uid_t uid) {
1481 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1482 return strdup(pp->pw_name);
1493 static gid_t gid_by_name(const char* name) {
1501 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1505 return gid_not_found;
1509 #if 0 // For future use.
1510 static const char* name_by_gid(gid_t gid) {
1519 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1520 return strdup(pp->gr_name);
1532 static uid_t uid_by_name(Handle<Value> value) {
1533 if (value->IsUint32()) {
1534 return static_cast<uid_t>(value->Uint32Value());
1536 String::Utf8Value name(value);
1537 return uid_by_name(*name);
1542 static gid_t gid_by_name(Handle<Value> value) {
1543 if (value->IsUint32()) {
1544 return static_cast<gid_t>(value->Uint32Value());
1546 String::Utf8Value name(value);
1547 return gid_by_name(*name);
1552 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1553 // uid_t is an uint32_t on all supported platforms.
1554 args.GetReturnValue().Set(static_cast<uint32_t>(getuid()));
1558 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1559 // gid_t is an uint32_t on all supported platforms.
1560 args.GetReturnValue().Set(static_cast<uint32_t>(getgid()));
1564 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1565 HandleScope scope(node_isolate);
1567 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1568 return ThrowTypeError("setgid argument must be a number or a string");
1571 gid_t gid = gid_by_name(args[0]);
1573 if (gid == gid_not_found) {
1574 return ThrowError("setgid group id does not exist");
1578 return ThrowErrnoException(errno, "setgid");
1583 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1584 HandleScope scope(node_isolate);
1586 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1587 return ThrowTypeError("setuid argument must be a number or a string");
1590 uid_t uid = uid_by_name(args[0]);
1592 if (uid == uid_not_found) {
1593 return ThrowError("setuid user id does not exist");
1597 return ThrowErrnoException(errno, "setuid");
1602 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1603 HandleScope scope(node_isolate);
1605 int ngroups = getgroups(0, NULL);
1607 if (ngroups == -1) {
1608 return ThrowErrnoException(errno, "getgroups");
1611 gid_t* groups = new gid_t[ngroups];
1613 ngroups = getgroups(ngroups, groups);
1615 if (ngroups == -1) {
1617 return ThrowErrnoException(errno, "getgroups");
1620 Local<Array> groups_list = Array::New(ngroups);
1621 bool seen_egid = false;
1622 gid_t egid = getegid();
1624 for (int i = 0; i < ngroups; i++) {
1625 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1626 if (groups[i] == egid) seen_egid = true;
1631 if (seen_egid == false) {
1632 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1635 args.GetReturnValue().Set(groups_list);
1639 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1640 HandleScope scope(node_isolate);
1642 if (!args[0]->IsArray()) {
1643 return ThrowTypeError("argument 1 must be an array");
1646 Local<Array> groups_list = args[0].As<Array>();
1647 size_t size = groups_list->Length();
1648 gid_t* groups = new gid_t[size];
1650 for (size_t i = 0; i < size; i++) {
1651 gid_t gid = gid_by_name(groups_list->Get(i));
1653 if (gid == gid_not_found) {
1655 return ThrowError("group name not found");
1661 int rc = setgroups(size, groups);
1665 return ThrowErrnoException(errno, "setgroups");
1670 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1671 HandleScope scope(node_isolate);
1673 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1674 return ThrowTypeError("argument 1 must be a number or a string");
1677 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1678 return ThrowTypeError("argument 2 must be a number or a string");
1681 String::Utf8Value arg0(args[0]);
1686 if (args[0]->IsUint32()) {
1687 user = name_by_uid(args[0]->Uint32Value());
1695 return ThrowError("initgroups user not found");
1698 extra_group = gid_by_name(args[1]);
1700 if (extra_group == gid_not_found) {
1701 if (must_free) free(user);
1702 return ThrowError("initgroups extra group not found");
1705 int rc = initgroups(user, extra_group);
1712 return ThrowErrnoException(errno, "initgroups");
1716 #endif // __POSIX__ && !defined(__ANDROID__)
1719 void Exit(const FunctionCallbackInfo<Value>& args) {
1720 HandleScope scope(node_isolate);
1721 exit(args[0]->IntegerValue());
1725 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1726 HandleScope scope(node_isolate);
1728 if (uv_uptime(&uptime)) return;
1729 args.GetReturnValue().Set(uptime - prog_start_time);
1733 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1734 Environment* env = Environment::GetCurrent(args.GetIsolate());
1735 HandleScope handle_scope(args.GetIsolate());
1738 int err = uv_resident_set_memory(&rss);
1740 return ThrowUVException(err, "uv_resident_set_memory");
1744 HeapStatistics v8_heap_stats;
1745 node_isolate->GetHeapStatistics(&v8_heap_stats);
1747 Local<Integer> heap_total =
1748 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(), node_isolate);
1749 Local<Integer> heap_used =
1750 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(), node_isolate);
1752 Local<Object> info = Object::New();
1753 info->Set(env->rss_string(), Number::New(node_isolate, rss));
1754 info->Set(env->heap_total_string(), heap_total);
1755 info->Set(env->heap_used_string(), heap_used);
1757 args.GetReturnValue().Set(info);
1761 void Kill(const FunctionCallbackInfo<Value>& args) {
1762 HandleScope scope(node_isolate);
1764 if (args.Length() != 2) {
1765 return ThrowError("Bad argument.");
1768 int pid = args[0]->IntegerValue();
1769 int sig = args[1]->Int32Value();
1770 int err = uv_kill(pid, sig);
1771 args.GetReturnValue().Set(err);
1774 // used in Hrtime() below
1775 #define NANOS_PER_SEC 1000000000
1777 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1778 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1779 // so this function instead returns an Array with 2 entries representing seconds
1780 // and nanoseconds, to avoid any integer overflow possibility.
1781 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1782 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1783 HandleScope scope(node_isolate);
1785 uint64_t t = uv_hrtime();
1787 if (args.Length() > 0) {
1788 // return a time diff tuple
1789 if (!args[0]->IsArray()) {
1790 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1792 Local<Array> inArray = Local<Array>::Cast(args[0]);
1793 uint64_t seconds = inArray->Get(0)->Uint32Value();
1794 uint64_t nanos = inArray->Get(1)->Uint32Value();
1795 t -= (seconds * NANOS_PER_SEC) + nanos;
1798 Local<Array> tuple = Array::New(2);
1799 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1800 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1801 args.GetReturnValue().Set(tuple);
1805 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1807 // DLOpen is process.dlopen(module, filename).
1808 // Used to load 'module.node' dynamically shared objects.
1810 // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
1811 // when two contexts try to load the same shared object. Maybe have a shadow
1812 // cache that's a plain C list or hash table that's shared across contexts?
1813 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1814 Environment* env = Environment::GetCurrent(args.GetIsolate());
1815 HandleScope handle_scope(args.GetIsolate());
1816 char symbol[1024], *base, *pos;
1820 if (args.Length() < 2) {
1821 return ThrowError("process.dlopen takes exactly 2 arguments.");
1824 Local<Object> module = args[0]->ToObject(); // Cast
1825 String::Utf8Value filename(args[1]); // Cast
1827 Local<String> exports_string = env->exports_string();
1828 Local<Object> exports = module->Get(exports_string)->ToObject();
1830 if (uv_dlopen(*filename, &lib)) {
1831 Local<String> errmsg = OneByteString(env->isolate(), uv_dlerror(&lib));
1833 // Windows needs to add the filename into the error message
1834 errmsg = String::Concat(errmsg, args[1]->ToString());
1836 ThrowException(Exception::Error(errmsg));
1840 String::Utf8Value path(args[1]);
1843 /* Find the shared library filename within the full path. */
1845 pos = strrchr(base, '/');
1851 pos = strpbrk(base, "\\/:");
1859 /* Strip the .node extension. */
1860 pos = strrchr(base, '.');
1865 /* Add the `_module` suffix to the extension name. */
1866 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1867 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1868 return ThrowError("Out of memory.");
1871 /* Replace dashes with underscores. When loading foo-bar.node,
1872 * look for foo_bar_module, not foo-bar_module.
1874 for (pos = symbol; *pos != '\0'; ++pos) {
1875 if (*pos == '-') *pos = '_';
1878 node_module_struct *mod;
1879 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1881 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1882 return ThrowError(errmsg);
1885 if (mod->version != NODE_MODULE_VERSION) {
1889 "Module version mismatch. Expected %d, got %d.",
1890 NODE_MODULE_VERSION, mod->version);
1891 return ThrowError(errmsg);
1894 // Execute the C++ module
1895 if (mod->register_context_func != NULL) {
1896 mod->register_context_func(exports, module, env->context());
1897 } else if (mod->register_func != NULL) {
1898 mod->register_func(exports, module);
1900 return ThrowError("Module has no declared entry point.");
1903 // Tell coverity that 'handle' should not be freed when we return.
1904 // coverity[leaked_storage]
1908 static void OnFatalError(const char* location, const char* message) {
1910 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1912 fprintf(stderr, "FATAL ERROR: %s\n", message);
1922 NO_RETURN void FatalError(const char* location, const char* message) {
1923 OnFatalError(location, message);
1924 // to supress compiler warning
1929 void FatalException(Handle<Value> error, Handle<Message> message) {
1930 HandleScope scope(node_isolate);
1932 Environment* env = Environment::GetCurrent(node_isolate);
1933 Local<Object> process_object = env->process_object();
1934 Local<String> fatal_exception_string = env->fatal_exception_string();
1935 Local<Function> fatal_exception_function =
1936 process_object->Get(fatal_exception_string).As<Function>();
1938 if (!fatal_exception_function->IsFunction()) {
1939 // failed before the process._fatalException function was added!
1940 // this is probably pretty bad. Nothing to do but report and exit.
1941 ReportException(error, message);
1945 TryCatch fatal_try_catch;
1947 // Do not call FatalException when _fatalException handler throws
1948 fatal_try_catch.SetVerbose(false);
1950 // this will return true if the JS layer handled it, false otherwise
1951 Local<Value> caught =
1952 fatal_exception_function->Call(process_object, 1, &error);
1954 if (fatal_try_catch.HasCaught()) {
1955 // the fatal exception function threw, so we must exit
1956 ReportException(fatal_try_catch);
1960 if (false == caught->BooleanValue()) {
1961 ReportException(error, message);
1967 void FatalException(const TryCatch& try_catch) {
1968 HandleScope scope(node_isolate);
1969 // TODO(bajtos) do not call FatalException if try_catch is verbose
1970 // (requires V8 API to expose getter for try_catch.is_verbose_)
1971 FatalException(try_catch.Exception(), try_catch.Message());
1975 void OnMessage(Handle<Message> message, Handle<Value> error) {
1976 // The current version of V8 sends messages for errors only
1977 // (thus `error` is always set).
1978 FatalException(error, message);
1982 static void Binding(const FunctionCallbackInfo<Value>& args) {
1983 Environment* env = Environment::GetCurrent(args.GetIsolate());
1984 HandleScope handle_scope(args.GetIsolate());
1986 Local<String> module = args[0]->ToString();
1987 String::Utf8Value module_v(module);
1989 Local<Object> cache = env->binding_cache_object();
1990 Local<Object> exports;
1992 if (cache->Has(module)) {
1993 exports = cache->Get(module)->ToObject();
1994 args.GetReturnValue().Set(exports);
1998 // Append a string to process.moduleLoadList
2000 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
2002 Local<Array> modules = env->module_load_list_array();
2003 uint32_t l = modules->Length();
2004 modules->Set(l, OneByteString(node_isolate, buf));
2006 node_module_struct* mod = get_builtin_module(*module_v);
2008 exports = Object::New();
2009 // Internal bindings don't have a "module" object, only exports.
2010 assert(mod->register_func == NULL);
2011 assert(mod->register_context_func != NULL);
2012 Local<Value> unused = Undefined(env->isolate());
2013 mod->register_context_func(exports, unused, env->context());
2014 cache->Set(module, exports);
2015 } else if (!strcmp(*module_v, "constants")) {
2016 exports = Object::New();
2017 DefineConstants(exports);
2018 cache->Set(module, exports);
2019 } else if (!strcmp(*module_v, "natives")) {
2020 exports = Object::New();
2021 DefineJavaScript(exports);
2022 cache->Set(module, exports);
2024 return ThrowError("No such module");
2027 args.GetReturnValue().Set(exports);
2031 static void ProcessTitleGetter(Local<String> property,
2032 const PropertyCallbackInfo<Value>& info) {
2033 HandleScope scope(node_isolate);
2035 uv_get_process_title(buffer, sizeof(buffer));
2036 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2040 static void ProcessTitleSetter(Local<String> property,
2042 const PropertyCallbackInfo<void>& info) {
2043 HandleScope scope(node_isolate);
2044 String::Utf8Value title(value);
2045 // TODO(piscisaureus): protect with a lock
2046 uv_set_process_title(*title);
2050 static void EnvGetter(Local<String> property,
2051 const PropertyCallbackInfo<Value>& info) {
2052 HandleScope scope(node_isolate);
2054 String::Utf8Value key(property);
2055 const char* val = getenv(*key);
2057 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2060 String::Value key(property);
2061 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2062 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2064 ARRAY_SIZE(buffer));
2065 // If result >= sizeof buffer the buffer was too small. That should never
2066 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2068 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2069 result < ARRAY_SIZE(buffer)) {
2070 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2071 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2072 return info.GetReturnValue().Set(rc);
2075 // Not found. Fetch from prototype.
2076 info.GetReturnValue().Set(
2077 info.Data().As<Object>()->Get(property));
2081 static void EnvSetter(Local<String> property,
2083 const PropertyCallbackInfo<Value>& info) {
2084 HandleScope scope(node_isolate);
2086 String::Utf8Value key(property);
2087 String::Utf8Value val(value);
2088 setenv(*key, *val, 1);
2090 String::Value key(property);
2091 String::Value val(value);
2092 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2093 // Environment variables that start with '=' are read-only.
2094 if (key_ptr[0] != L'=') {
2095 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2098 // Whether it worked or not, always return rval.
2099 info.GetReturnValue().Set(value);
2103 static void EnvQuery(Local<String> property,
2104 const PropertyCallbackInfo<Integer>& info) {
2105 HandleScope scope(node_isolate);
2106 int32_t rc = -1; // Not found unless proven otherwise.
2108 String::Utf8Value key(property);
2109 if (getenv(*key)) rc = 0;
2111 String::Value key(property);
2112 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2113 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2114 GetLastError() == ERROR_SUCCESS) {
2116 if (key_ptr[0] == L'=') {
2117 // Environment variables that start with '=' are hidden and read-only.
2118 rc = static_cast<int32_t>(v8::ReadOnly) |
2119 static_cast<int32_t>(v8::DontDelete) |
2120 static_cast<int32_t>(v8::DontEnum);
2124 if (rc != -1) info.GetReturnValue().Set(rc);
2128 static void EnvDeleter(Local<String> property,
2129 const PropertyCallbackInfo<Boolean>& info) {
2130 HandleScope scope(node_isolate);
2133 String::Utf8Value key(property);
2134 rc = getenv(*key) != NULL;
2135 if (rc) unsetenv(*key);
2137 String::Value key(property);
2138 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2139 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2140 // Deletion failed. Return true if the key wasn't there in the first place,
2141 // false if it is still there.
2142 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2143 GetLastError() != ERROR_SUCCESS;
2146 info.GetReturnValue().Set(rc);
2150 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2151 HandleScope scope(node_isolate);
2154 while (environ[size]) size++;
2156 Local<Array> env = Array::New(size);
2158 for (int i = 0; i < size; ++i) {
2159 const char* var = environ[i];
2160 const char* s = strchr(var, '=');
2161 const int length = s ? s - var : strlen(var);
2162 Local<String> name = String::NewFromUtf8(node_isolate,
2164 String::kNormalString,
2169 WCHAR* environment = GetEnvironmentStringsW();
2170 if (environment == NULL) return; // This should not happen.
2171 Local<Array> env = Array::New();
2172 WCHAR* p = environment;
2174 while (*p != NULL) {
2177 // If the key starts with '=' it is a hidden environment variable.
2181 s = wcschr(p, L'=');
2186 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2187 const size_t two_byte_buffer_len = s - p;
2188 Local<String> value = String::NewFromTwoByte(node_isolate,
2190 String::kNormalString,
2191 two_byte_buffer_len);
2192 env->Set(i++, value);
2193 p = s + wcslen(s) + 1;
2195 FreeEnvironmentStringsW(environment);
2198 info.GetReturnValue().Set(env);
2202 static Handle<Object> GetFeatures() {
2203 HandleScope scope(node_isolate);
2205 Local<Object> obj = Object::New();
2206 #if defined(DEBUG) && DEBUG
2207 Local<Value> debug = True(node_isolate);
2209 Local<Value> debug = False(node_isolate);
2210 #endif // defined(DEBUG) && DEBUG
2212 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2214 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2215 // TODO(bnoordhuis) ping libuv
2216 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2218 #ifdef OPENSSL_NPN_NEGOTIATED
2219 Local<Boolean> tls_npn = True(node_isolate);
2221 Local<Boolean> tls_npn = False(node_isolate);
2223 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"), tls_npn);
2225 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2226 Local<Boolean> tls_sni = True(node_isolate);
2228 Local<Boolean> tls_sni = False(node_isolate);
2230 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"), tls_sni);
2232 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2233 Boolean::New(get_builtin_module("crypto") != NULL));
2235 return scope.Close(obj);
2239 static void DebugPortGetter(Local<String> property,
2240 const PropertyCallbackInfo<Value>& info) {
2241 HandleScope scope(node_isolate);
2242 info.GetReturnValue().Set(debug_port);
2246 static void DebugPortSetter(Local<String> property,
2248 const PropertyCallbackInfo<void>& info) {
2249 HandleScope scope(node_isolate);
2250 debug_port = value->NumberValue();
2254 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2255 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2256 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2259 void NeedImmediateCallbackGetter(Local<String> property,
2260 const PropertyCallbackInfo<Value>& info) {
2261 Environment* env = Environment::GetCurrent(info.GetIsolate());
2262 const uv_check_t* immediate_check_handle = env->immediate_check_handle();
2263 bool active = uv_is_active(
2264 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2265 info.GetReturnValue().Set(active);
2269 static void NeedImmediateCallbackSetter(
2270 Local<String> property,
2272 const PropertyCallbackInfo<void>& info) {
2273 Environment* env = Environment::GetCurrent(info.GetIsolate());
2274 HandleScope handle_scope(info.GetIsolate());
2276 uv_check_t* immediate_check_handle = env->immediate_check_handle();
2277 bool active = uv_is_active(
2278 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2280 if (active == value->BooleanValue())
2283 uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
2286 uv_check_stop(immediate_check_handle);
2287 uv_idle_stop(immediate_idle_handle);
2289 uv_check_start(immediate_check_handle, CheckImmediate);
2290 // Idle handle is needed only to stop the event loop from blocking in poll.
2291 uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
2296 #define READONLY_PROPERTY(obj, str, var) \
2298 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2302 void SetupProcessObject(Environment* env,
2304 const char* const* argv,
2306 const char* const* exec_argv) {
2307 HandleScope scope(node_isolate);
2310 Local<Object> process = env->process_object();
2312 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2314 ProcessTitleSetter);
2317 READONLY_PROPERTY(process,
2319 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2321 // process.moduleLoadList
2322 READONLY_PROPERTY(process,
2324 env->module_load_list_array());
2327 Local<Object> versions = Object::New();
2328 READONLY_PROPERTY(process, "versions", versions);
2330 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2332 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2333 READONLY_PROPERTY(versions,
2335 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2337 // +1 to get rid of the leading 'v'
2338 READONLY_PROPERTY(versions,
2340 OneByteString(node_isolate, NODE_VERSION + 1));
2341 READONLY_PROPERTY(versions,
2343 OneByteString(node_isolate, V8::GetVersion()));
2344 READONLY_PROPERTY(versions,
2346 OneByteString(node_isolate, uv_version_string()));
2347 READONLY_PROPERTY(versions,
2349 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2351 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2352 READONLY_PROPERTY(versions,
2354 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2357 // Stupid code to slice out the version string.
2358 int c, l = strlen(OPENSSL_VERSION_TEXT);
2359 for (i = j = 0; i < l; i++) {
2360 c = OPENSSL_VERSION_TEXT[i];
2361 if ('0' <= c && c <= '9') {
2362 for (j = i + 1; j < l; j++) {
2363 c = OPENSSL_VERSION_TEXT[j];
2364 if (c == ' ') break;
2372 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2376 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2379 READONLY_PROPERTY(process,
2381 OneByteString(node_isolate, PLATFORM));
2384 Local<Array> arguments = Array::New(argc);
2385 for (int i = 0; i < argc; ++i) {
2386 arguments->Set(i, String::NewFromUtf8(node_isolate, argv[i]));
2388 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2391 Local<Array> exec_arguments = Array::New(exec_argc);
2392 for (int i = 0; i < exec_argc; ++i) {
2393 exec_arguments->Set(i, String::NewFromUtf8(node_isolate, exec_argv[i]));
2395 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_arguments);
2397 // create process.env
2398 Local<ObjectTemplate> process_env_template = ObjectTemplate::New();
2399 process_env_template->SetNamedPropertyHandler(EnvGetter,
2405 Local<Object> process_env = process_env_template->NewInstance();
2406 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), process_env);
2408 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2409 READONLY_PROPERTY(process, "features", GetFeatures());
2410 process->SetAccessor(
2411 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2412 NeedImmediateCallbackGetter,
2413 NeedImmediateCallbackSetter);
2417 READONLY_PROPERTY(process,
2419 String::NewFromUtf8(node_isolate, eval_string));
2424 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2427 // -i, --interactive
2429 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2433 if (no_deprecation) {
2434 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2437 // --throw-deprecation
2438 if (throw_deprecation) {
2439 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2442 // --trace-deprecation
2443 if (trace_deprecation) {
2444 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2447 size_t exec_path_len = 2 * PATH_MAX;
2448 char* exec_path = new char[exec_path_len];
2449 Local<String> exec_path_value;
2450 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2451 exec_path_value = String::NewFromUtf8(node_isolate,
2453 String::kNormalString,
2456 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2458 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2462 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2466 // define various internal methods
2467 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2468 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2469 NODE_SET_METHOD(process, "reallyExit", Exit);
2470 NODE_SET_METHOD(process, "abort", Abort);
2471 NODE_SET_METHOD(process, "chdir", Chdir);
2472 NODE_SET_METHOD(process, "cwd", Cwd);
2474 NODE_SET_METHOD(process, "umask", Umask);
2476 #if defined(__POSIX__) && !defined(__ANDROID__)
2477 NODE_SET_METHOD(process, "getuid", GetUid);
2478 NODE_SET_METHOD(process, "setuid", SetUid);
2480 NODE_SET_METHOD(process, "setgid", SetGid);
2481 NODE_SET_METHOD(process, "getgid", GetGid);
2483 NODE_SET_METHOD(process, "getgroups", GetGroups);
2484 NODE_SET_METHOD(process, "setgroups", SetGroups);
2485 NODE_SET_METHOD(process, "initgroups", InitGroups);
2486 #endif // __POSIX__ && !defined(__ANDROID__)
2488 NODE_SET_METHOD(process, "_kill", Kill);
2490 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2491 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2492 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2494 NODE_SET_METHOD(process, "hrtime", Hrtime);
2496 NODE_SET_METHOD(process, "dlopen", DLOpen);
2498 NODE_SET_METHOD(process, "uptime", Uptime);
2499 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2501 NODE_SET_METHOD(process, "binding", Binding);
2503 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2505 // values use to cross communicate with processNextTick
2506 Local<Object> tick_info_obj = Object::New();
2507 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
2508 env->tick_info()->fields(),
2509 kExternalUnsignedIntArray,
2510 env->tick_info()->fields_count());
2511 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfo"), tick_info_obj);
2513 // pre-set _events object for faster emit checks
2514 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2518 #undef READONLY_PROPERTY
2521 static void AtExit() {
2522 uv_tty_reset_mode();
2526 static void SignalExit(int signal) {
2527 uv_tty_reset_mode();
2528 _exit(128 + signal);
2532 // Most of the time, it's best to use `console.error` to write
2533 // to the process.stderr stream. However, in some cases, such as
2534 // when debugging the stream.Writable class or the process.nextTick
2535 // function, it is useful to bypass JavaScript entirely.
2536 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2537 HandleScope scope(node_isolate);
2539 assert(args.Length() == 1 && args[0]->IsString() &&
2540 "must be called with a single string");
2542 String::Utf8Value message(args[0]);
2543 fprintf(stderr, "%s\n", *message);
2548 void Load(Environment* env) {
2549 HandleScope handle_scope(node_isolate);
2551 // Compile, execute the src/node.js file. (Which was included as static C
2552 // string in node_natives.h. 'natve_node' is the string containing that
2555 // The node.js file returns a function 'f'
2560 // Disable verbose mode to stop FatalException() handler from trying
2561 // to handle the exception. Errors this early in the start-up phase
2562 // are not safe to ignore.
2563 try_catch.SetVerbose(false);
2565 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2566 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2567 if (try_catch.HasCaught()) {
2568 ReportException(try_catch);
2571 assert(f_value->IsFunction());
2572 Local<Function> f = Local<Function>::Cast(f_value);
2574 // Now we call 'f' with the 'process' variable that we've built up with
2575 // all our bindings. Inside node.js we'll take care of assigning things to
2578 // We start the process this way in order to be more modular. Developers
2579 // who do not like how 'src/node.js' setups the module system but do like
2580 // Node's I/O bindings may want to replace 'f' with their own function.
2582 // Add a reference to the global object
2583 Local<Object> global = env->context()->Global();
2585 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2589 #if defined HAVE_PERFCTR
2590 InitPerfCounters(global);
2593 // Enable handling of uncaught exceptions
2594 // (FatalException(), break on uncaught exception in debugger)
2596 // This is not strictly necessary since it's almost impossible
2597 // to attach the debugger fast enought to break on exception
2598 // thrown during process startup.
2599 try_catch.SetVerbose(true);
2601 NODE_SET_METHOD(env->process_object(), "_rawDebug", RawDebug);
2603 Local<Value> arg = env->process_object();
2604 f->Call(global, 1, &arg);
2607 static void PrintHelp();
2609 static void ParseDebugOpt(const char* arg) {
2612 if (strstr(arg, "--debug-port=") == arg) {
2613 p = 1 + strchr(arg, '=');
2614 debug_port = atoi(p);
2616 use_debug_agent = true;
2617 if (!strcmp(arg, "--debug-brk")) {
2618 debug_wait_connect = true;
2620 } else if (!strcmp(arg, "--debug")) {
2622 } else if (strstr(arg, "--debug-brk=") == arg) {
2623 debug_wait_connect = true;
2624 p = 1 + strchr(arg, '=');
2625 debug_port = atoi(p);
2626 } else if (strstr(arg, "--debug=") == arg) {
2627 p = 1 + strchr(arg, '=');
2628 debug_port = atoi(p);
2631 if (p && debug_port > 1024 && debug_port < 65536)
2634 fprintf(stderr, "Bad debug option.\n");
2635 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2641 static void PrintHelp() {
2642 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2643 " node debug script.js [arguments] \n"
2646 " -v, --version print node's version\n"
2647 " -e, --eval script evaluate script\n"
2648 " -p, --print evaluate script and print result\n"
2649 " -i, --interactive always enter the REPL even if stdin\n"
2650 " does not appear to be a terminal\n"
2651 " --no-deprecation silence deprecation warnings\n"
2652 " --trace-deprecation show stack traces on deprecations\n"
2653 " --v8-options print v8 command line options\n"
2654 " --max-stack-size=val set max v8 stack size (bytes)\n"
2656 "Environment variables:\n"
2658 "NODE_PATH ';'-separated list of directories\n"
2660 "NODE_PATH ':'-separated list of directories\n"
2662 " prefixed to the module search path.\n"
2663 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2664 " global contexts.\n"
2665 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2667 "Documentation can be found at http://nodejs.org/\n");
2671 // Parse command line arguments.
2673 // argv is modified in place. exec_argv and v8_argv are out arguments that
2674 // ParseArgs() allocates memory for and stores a pointer to the output
2675 // vector in. The caller should free them with delete[].
2679 // * argv contains the arguments with node and V8 options filtered out.
2680 // * exec_argv contains both node and V8 options and nothing else.
2681 // * v8_argv contains argv[0] plus any V8 options
2682 static void ParseArgs(int* argc,
2685 const char*** exec_argv,
2687 const char*** v8_argv) {
2688 const unsigned int nargs = static_cast<unsigned int>(*argc);
2689 const char** new_exec_argv = new const char*[nargs];
2690 const char** new_v8_argv = new const char*[nargs];
2691 const char** new_argv = new const char*[nargs];
2693 for (unsigned int i = 0; i < nargs; ++i) {
2694 new_exec_argv[i] = NULL;
2695 new_v8_argv[i] = NULL;
2699 // exec_argv starts with the first option, the other two start with argv[0].
2700 unsigned int new_exec_argc = 0;
2701 unsigned int new_v8_argc = 1;
2702 unsigned int new_argc = 1;
2703 new_v8_argv[0] = argv[0];
2704 new_argv[0] = argv[0];
2706 unsigned int index = 1;
2707 while (index < nargs && argv[index][0] == '-') {
2708 const char* const arg = argv[index];
2709 unsigned int args_consumed = 1;
2711 if (strstr(arg, "--debug") == arg) {
2713 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2714 printf("%s\n", NODE_VERSION);
2716 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2719 } else if (strcmp(arg, "--eval") == 0 ||
2720 strcmp(arg, "-e") == 0 ||
2721 strcmp(arg, "--print") == 0 ||
2722 strcmp(arg, "-pe") == 0 ||
2723 strcmp(arg, "-p") == 0) {
2724 bool is_eval = strchr(arg, 'e') != NULL;
2725 bool is_print = strchr(arg, 'p') != NULL;
2726 print_eval = print_eval || is_print;
2727 // --eval, -e and -pe always require an argument.
2728 if (is_eval == true) {
2730 eval_string = argv[index + 1];
2731 if (eval_string == NULL) {
2732 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
2735 } else if (argv[index + 1] != NULL && argv[index + 1][0] != '-') {
2737 eval_string = argv[index + 1];
2738 if (strncmp(eval_string, "\\-", 2) == 0) {
2739 // Starts with "\\-": escaped expression, drop the backslash.
2743 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2745 } else if (strcmp(arg, "--no-deprecation") == 0) {
2746 no_deprecation = true;
2747 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2748 trace_deprecation = true;
2749 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2750 throw_deprecation = true;
2751 } else if (strcmp(arg, "--v8-options") == 0) {
2752 new_v8_argv[new_v8_argc] = "--help";
2755 // V8 option. Pass through as-is.
2756 new_v8_argv[new_v8_argc] = arg;
2760 memcpy(new_exec_argv + new_exec_argc,
2762 args_consumed * sizeof(*argv));
2764 new_exec_argc += args_consumed;
2765 index += args_consumed;
2768 // Copy remaining arguments.
2769 const unsigned int args_left = nargs - index;
2770 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
2771 new_argc += args_left;
2773 *exec_argc = new_exec_argc;
2774 *exec_argv = new_exec_argv;
2775 *v8_argc = new_v8_argc;
2776 *v8_argv = new_v8_argv;
2778 // Copy new_argv over argv and update argc.
2779 memcpy(argv, new_argv, new_argc * sizeof(*argv));
2781 *argc = static_cast<int>(new_argc);
2785 // Called from the main thread.
2786 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2787 v8::Debug::ProcessDebugMessages();
2791 // Called from V8 Debug Agent TCP thread.
2792 static void DispatchMessagesDebugAgentCallback() {
2793 uv_async_send(&dispatch_debug_messages_async);
2797 // Called from the main thread
2798 static void EmitDebugEnabledAsyncCallback(uv_async_t* handle, int status) {
2799 Environment* env = Environment::GetCurrent(node_isolate);
2800 Context::Scope context_scope(env->context());
2801 HandleScope handle_scope(env->isolate());
2802 Local<Object> message = Object::New();
2803 message->Set(FIXED_ONE_BYTE_STRING(node_isolate, "cmd"),
2804 FIXED_ONE_BYTE_STRING(node_isolate, "NODE_DEBUG_ENABLED"));
2805 Local<Value> args[] = {
2806 FIXED_ONE_BYTE_STRING(node_isolate, "internalMessage"),
2809 MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(args), args);
2813 // Called from the signal watcher callback
2814 static void EmitDebugEnabled() {
2815 uv_async_send(&emit_debug_enabled_async);
2819 static void EnableDebug(bool wait_connect) {
2820 // If we're called from another thread, make sure to enter the right
2822 node_isolate->Enter();
2824 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2827 // Start the debug thread and it's associated TCP server on port 5858.
2828 bool r = v8::Debug::EnableAgent("node " NODE_VERSION,
2832 // Crappy check that everything went well. FIXME
2835 // Print out some information.
2836 fprintf(stderr, "debugger listening on port %d\n", debug_port);
2839 debugger_running = true;
2841 if (Environment::GetCurrentChecked(node_isolate) != NULL) {
2845 node_isolate->Exit();
2850 static void EnableDebugSignalHandler(uv_signal_t* handle, int) {
2851 // Break once process will return execution to v8
2852 v8::Debug::DebugBreak(node_isolate);
2854 if (!debugger_running) {
2855 fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n");
2861 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2862 struct sigaction sa;
2864 memset(&sa, 0, sizeof(sa));
2865 sa.sa_handler = handler;
2866 sigfillset(&sa.sa_mask);
2867 sigaction(signal, &sa, NULL);
2871 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2872 HandleScope scope(node_isolate);
2874 if (args.Length() != 1) {
2875 return ThrowError("Invalid number of arguments.");
2881 pid = args[0]->IntegerValue();
2882 r = kill(pid, SIGUSR1);
2884 return ThrowErrnoException(errno, "kill");
2891 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2892 // Break once process will return execution to v8
2893 if (!debugger_running) {
2894 for (int i = 0; i < 1; i++) {
2895 fprintf(stderr, "Starting debugger agent.\r\n");
2901 v8::Debug::DebugBreak(node_isolate);
2907 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2909 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2913 static int RegisterDebugSignalHandler() {
2914 wchar_t mapping_name[32];
2915 HANDLE mapping_handle;
2917 LPTHREAD_START_ROUTINE* handler;
2919 pid = GetCurrentProcessId();
2921 if (GetDebugSignalHandlerMappingName(pid,
2923 ARRAY_SIZE(mapping_name)) < 0) {
2927 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2933 if (mapping_handle == NULL) {
2937 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2938 MapViewOfFile(mapping_handle,
2939 FILE_MAP_ALL_ACCESS,
2943 if (handler == NULL) {
2944 CloseHandle(mapping_handle);
2948 *handler = EnableDebugThreadProc;
2950 UnmapViewOfFile(static_cast<void*>(handler));
2956 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2957 HandleScope scope(node_isolate);
2959 HANDLE process = NULL;
2960 HANDLE thread = NULL;
2961 HANDLE mapping = NULL;
2962 wchar_t mapping_name[32];
2963 LPTHREAD_START_ROUTINE* handler = NULL;
2965 if (args.Length() != 1) {
2966 ThrowError("Invalid number of arguments.");
2970 pid = (DWORD) args[0]->IntegerValue();
2972 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2973 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2977 if (process == NULL) {
2978 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2982 if (GetDebugSignalHandlerMappingName(pid,
2984 ARRAY_SIZE(mapping_name)) < 0) {
2985 ThrowErrnoException(errno, "sprintf");
2989 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2990 if (mapping == NULL) {
2991 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
2995 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2996 MapViewOfFile(mapping,
3001 if (handler == NULL || *handler == NULL) {
3002 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
3006 thread = CreateRemoteThread(process,
3013 if (thread == NULL) {
3014 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
3018 // Wait for the thread to terminate
3019 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3020 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
3025 if (process != NULL)
3026 CloseHandle(process);
3028 CloseHandle(thread);
3029 if (handler != NULL)
3030 UnmapViewOfFile(handler);
3031 if (mapping != NULL)
3032 CloseHandle(mapping);
3037 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3038 v8::Debug::DebugBreak(node_isolate);
3042 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3043 if (debugger_running) {
3044 v8::Debug::DisableAgent();
3045 debugger_running = false;
3050 void Init(int* argc,
3053 const char*** exec_argv) {
3054 // Initialize prog_start_time to get relative uptime.
3055 uv_uptime(&prog_start_time);
3057 // Make inherited handles noninheritable.
3058 uv_disable_stdio_inheritance();
3060 // init async debug messages dispatching
3061 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3062 uv_async_init(uv_default_loop(),
3063 &dispatch_debug_messages_async,
3064 DispatchDebugMessagesAsyncCallback);
3065 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3067 // init async NODE_DEBUG_ENABLED emitter
3068 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3069 uv_async_init(uv_default_loop(),
3070 &emit_debug_enabled_async,
3071 EmitDebugEnabledAsyncCallback);
3072 uv_unref(reinterpret_cast<uv_handle_t*>(&emit_debug_enabled_async));
3074 // Parse a few arguments which are specific to Node.
3076 const char** v8_argv;
3077 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3079 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3080 // the argv array or the elements it points to.
3081 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3083 // Anything that's still in v8_argv is not a V8 or a node option.
3084 for (int i = 1; i < v8_argc; i++) {
3085 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3094 if (debug_wait_connect) {
3095 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3096 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3099 const char typed_arrays_flag[] = "--harmony_typed_arrays";
3100 V8::SetFlagsFromString(typed_arrays_flag, sizeof(typed_arrays_flag) - 1);
3101 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3103 // Fetch a reference to the main isolate, so we have a reference to it
3104 // even when we need it to access it from another (debugger) thread.
3105 node_isolate = Isolate::GetCurrent();
3108 // Raise the open file descriptor limit.
3111 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3112 // Do a binary search for the limit.
3113 rlim_t min = lim.rlim_cur;
3114 rlim_t max = 1 << 20;
3115 // But if there's a defined upper bound, don't search, just set it.
3116 if (lim.rlim_max != RLIM_INFINITY) {
3121 lim.rlim_cur = min + (max - min) / 2;
3122 if (setrlimit(RLIMIT_NOFILE, &lim)) {
3127 } while (min + 1 < max);
3131 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3132 RegisterSignalHandler(SIGINT, SignalExit);
3133 RegisterSignalHandler(SIGTERM, SignalExit);
3136 V8::SetFatalErrorHandler(node::OnFatalError);
3137 V8::AddMessageListener(OnMessage);
3139 // If the --debug flag was specified then initialize the debug thread.
3140 if (use_debug_agent) {
3141 EnableDebug(debug_wait_connect);
3144 RegisterDebugSignalHandler();
3146 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3147 static uv_signal_t signal_watcher;
3148 uv_signal_init(uv_default_loop(), &signal_watcher);
3149 uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1);
3150 uv_unref(reinterpret_cast<uv_handle_t*>(&signal_watcher));
3156 struct AtExitCallback {
3157 AtExitCallback* next_;
3158 void (*cb_)(void* arg);
3162 static AtExitCallback* at_exit_functions_;
3165 // TODO(bnoordhuis) Turn into per-context event.
3166 void RunAtExit(Environment* env) {
3167 AtExitCallback* p = at_exit_functions_;
3168 at_exit_functions_ = NULL;
3171 AtExitCallback* q = p->next_;
3179 void AtExit(void (*cb)(void* arg), void* arg) {
3180 AtExitCallback* p = new AtExitCallback;
3183 p->next_ = at_exit_functions_;
3184 at_exit_functions_ = p;
3188 void EmitExit(Environment* env) {
3189 // process.emit('exit')
3190 Context::Scope context_scope(env->context());
3191 HandleScope handle_scope(env->isolate());
3192 Local<Object> process_object = env->process_object();
3193 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3194 True(node_isolate));
3196 Handle<String> exitCode = FIXED_ONE_BYTE_STRING(node_isolate, "exitCode");
3197 int code = process_object->Get(exitCode)->IntegerValue();
3199 Local<Value> args[] = {
3200 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3201 Integer::New(code, node_isolate)
3204 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3209 void SetIdle(uv_prepare_t* handle, int) {
3210 Environment* env = Environment::from_idle_prepare_handle(handle);
3211 env->isolate()->GetCpuProfiler()->SetIdle(true);
3215 void ClearIdle(uv_check_t* handle, int) {
3216 Environment* env = Environment::from_idle_check_handle(handle);
3217 env->isolate()->GetCpuProfiler()->SetIdle(false);
3221 Environment* CreateEnvironment(Isolate* isolate,
3223 const char* const* argv,
3225 const char* const* exec_argv) {
3226 HandleScope handle_scope(isolate);
3228 Local<Context> context = Context::New(isolate);
3229 Context::Scope context_scope(context);
3230 Environment* env = Environment::New(context);
3232 uv_check_init(env->event_loop(), env->immediate_check_handle());
3234 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3235 uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3237 Local<FunctionTemplate> process_template = FunctionTemplate::New();
3238 process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3240 Local<Object> process_object = process_template->GetFunction()->NewInstance();
3241 env->set_process_object(process_object);
3243 SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3246 // Inform V8's CPU profiler when we're idle. The profiler is sampling-based
3247 // but not all samples are created equal; mark the wall clock time spent in
3248 // epoll_wait() and friends so profiling tools can filter it out. The samples
3249 // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
3250 // TODO(bnoordhuis): Only start when profiling. OTOH, the performance impact
3251 // is probably negligible.
3252 // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
3253 // probably fortify in the API contract, namely that the last started prepare
3254 // or check watcher runs first. It's not 100% foolproof; if an add-on starts
3255 // a prepare or check watcher after us, any samples attributed to its callback
3256 // will be recorded with state=IDLE.
3257 uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
3258 uv_prepare_start(env->idle_prepare_handle(), SetIdle);
3259 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
3261 uv_check_init(env->event_loop(), env->idle_check_handle());
3262 uv_check_start(env->idle_check_handle(), ClearIdle);
3263 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
3269 int Start(int argc, char** argv) {
3272 // Hack around with the argv pointer. Used for process.title = "blah".
3273 argv = uv_setup_args(argc, argv);
3275 // This needs to run *before* V8::Initialize(). The const_cast is not
3276 // optional, in case you're wondering.
3278 const char** exec_argv;
3279 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3282 // V8 on Windows doesn't have a good source of entropy. Seed it from
3284 V8::SetEntropySource(crypto::EntropySource);
3289 Locker locker(node_isolate);
3291 CreateEnvironment(node_isolate, argc, argv, exec_argc, exec_argv);
3292 Context::Scope context_scope(env->context());
3293 HandleScope handle_scope(env->isolate());
3294 uv_run(env->event_loop(), UV_RUN_DEFAULT);
3302 // Clean up. Not strictly necessary.