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"
58 #include <limits.h> // PATH_MAX
64 #include <sys/types.h>
70 #define strcasecmp _stricmp
71 #define getpid _getpid
75 #include <sys/resource.h> // getrlimit, setrlimit
76 #include <unistd.h> // setuid, getuid
79 #if defined(__POSIX__) && !defined(__ANDROID__)
80 #include <pwd.h> // getpwnam()
81 #include <grp.h> // getgrnam()
85 #include <crt_externs.h>
86 #define environ (*_NSGetEnviron())
87 #elif !defined(_MSC_VER)
88 extern char **environ;
94 using v8::ArrayBuffer;
99 using v8::FunctionCallbackInfo;
100 using v8::FunctionTemplate;
102 using v8::HandleScope;
103 using v8::HeapStatistics;
111 using v8::ObjectTemplate;
112 using v8::PropertyCallbackInfo;
114 using v8::ThrowException;
119 using v8::kExternalUnsignedIntArray;
121 // FIXME(bnoordhuis) Make these per-context?
122 QUEUE handle_wrap_queue = { &handle_wrap_queue, &handle_wrap_queue };
123 QUEUE req_wrap_queue = { &req_wrap_queue, &req_wrap_queue };
125 static bool print_eval = false;
126 static bool force_repl = false;
127 static bool trace_deprecation = false;
128 static bool throw_deprecation = false;
129 static const char* eval_string = NULL;
130 static bool use_debug_agent = false;
131 static bool debug_wait_connect = false;
132 static int debug_port = 5858;
134 // used by C++ modules as well
135 bool no_deprecation = false;
137 // process-relative uptime base, initialized at start-up
138 static double prog_start_time;
140 static volatile bool debugger_running = false;
141 static uv_async_t dispatch_debug_messages_async;
142 static uv_async_t emit_debug_enabled_async;
144 // Declared in node_internals.h
145 Isolate* node_isolate = NULL;
148 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
150 // Impose an upper limit to avoid out of memory errors that bring down
152 static const size_t kMaxLength = 0x3fffffff;
153 static ArrayBufferAllocator the_singleton;
154 virtual ~ArrayBufferAllocator() {}
155 virtual void* Allocate(size_t length);
156 virtual void Free(void* data);
158 ArrayBufferAllocator() {}
159 ArrayBufferAllocator(const ArrayBufferAllocator&);
160 void operator=(const ArrayBufferAllocator&);
163 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
166 void* ArrayBufferAllocator::Allocate(size_t length) {
167 if (length > kMaxLength) return NULL;
168 return new char[length];
172 void ArrayBufferAllocator::Free(void* data) {
173 delete[] static_cast<char*>(data);
177 static void CheckImmediate(uv_check_t* handle, int status) {
178 Environment* env = Environment::from_immediate_check_handle(handle);
179 Context::Scope context_scope(env->context());
180 MakeCallback(env, env->process_object(), env->immediate_callback_string());
184 static void IdleImmediateDummy(uv_idle_t*, int) {
185 // Do nothing. Only for maintaining event loop.
186 // TODO(bnoordhuis) Maybe make libuv accept NULL idle callbacks.
190 static inline const char *errno_string(int errorno) {
191 #define ERRNO_CASE(e) case e: return #e;
198 ERRNO_CASE(EADDRINUSE);
202 ERRNO_CASE(EADDRNOTAVAIL);
206 ERRNO_CASE(EAFNOSUPPORT);
214 # if EAGAIN != EWOULDBLOCK
215 ERRNO_CASE(EWOULDBLOCK);
220 ERRNO_CASE(EALREADY);
236 ERRNO_CASE(ECANCELED);
244 ERRNO_CASE(ECONNABORTED);
248 ERRNO_CASE(ECONNREFUSED);
252 ERRNO_CASE(ECONNRESET);
260 ERRNO_CASE(EDESTADDRREQ);
284 ERRNO_CASE(EHOSTUNREACH);
296 ERRNO_CASE(EINPROGRESS);
332 ERRNO_CASE(EMSGSIZE);
336 ERRNO_CASE(EMULTIHOP);
340 ERRNO_CASE(ENAMETOOLONG);
344 ERRNO_CASE(ENETDOWN);
348 ERRNO_CASE(ENETRESET);
352 ERRNO_CASE(ENETUNREACH);
384 # if ENOLINK != ENOLCK
398 ERRNO_CASE(ENOPROTOOPT);
418 ERRNO_CASE(ENOTCONN);
426 ERRNO_CASE(ENOTEMPTY);
430 ERRNO_CASE(ENOTSOCK);
437 ERRNO_CASE(EOPNOTSUPP);
451 ERRNO_CASE(EOVERFLOW);
466 #ifdef EPROTONOSUPPORT
467 ERRNO_CASE(EPROTONOSUPPORT);
471 ERRNO_CASE(EPROTOTYPE);
499 ERRNO_CASE(ETIMEDOUT);
514 const char *signo_string(int signo) {
515 #define SIGNO_CASE(e) case e: return #e;
542 # if SIGABRT != SIGIOT
586 SIGNO_CASE(SIGSTKFLT);
603 SIGNO_CASE(SIGBREAK);
627 SIGNO_CASE(SIGVTALRM);
635 SIGNO_CASE(SIGWINCH);
643 # if SIGPOLL != SIGIO
653 # if SIGPWR != SIGLOST
667 Local<Value> ErrnoException(int errorno,
671 Environment* env = Environment::GetCurrent(node_isolate);
674 Local<String> estring = OneByteString(node_isolate, errno_string(errorno));
675 if (msg == NULL || msg[0] == '\0') {
676 msg = strerror(errorno);
678 Local<String> message = OneByteString(node_isolate, msg);
680 Local<String> cons1 =
681 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
682 Local<String> cons2 = String::Concat(cons1, message);
685 Local<String> cons3 =
686 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
687 Local<String> cons4 =
688 String::Concat(cons3, String::NewFromUtf8(node_isolate, path));
689 Local<String> cons5 =
690 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
691 e = Exception::Error(cons5);
693 e = Exception::Error(cons2);
696 Local<Object> obj = e->ToObject();
697 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
698 obj->Set(env->code_string(), estring);
701 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
704 if (syscall != NULL) {
705 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
712 // hack alert! copy of ErrnoException, tuned for uv errors
713 Local<Value> UVException(int errorno,
717 Environment* env = Environment::GetCurrent(node_isolate);
720 msg = uv_strerror(errorno);
722 Local<String> estring = OneByteString(node_isolate, uv_err_name(errorno));
723 Local<String> message = OneByteString(node_isolate, msg);
724 Local<String> cons1 =
725 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
726 Local<String> cons2 = String::Concat(cons1, message);
730 Local<String> path_str;
734 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
735 path_str = String::Concat(FIXED_ONE_BYTE_STRING(node_isolate, "\\\\"),
736 String::NewFromUtf8(node_isolate, path + 8));
737 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
738 path_str = String::NewFromUtf8(node_isolate, path + 4);
740 path_str = String::NewFromUtf8(node_isolate, path);
743 path_str = String::NewFromUtf8(node_isolate, path);
746 Local<String> cons3 =
747 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
748 Local<String> cons4 =
749 String::Concat(cons3, path_str);
750 Local<String> cons5 =
751 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
752 e = Exception::Error(cons5);
754 e = Exception::Error(cons2);
757 Local<Object> obj = e->ToObject();
758 // TODO(piscisaureus) errno should probably go
759 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
760 obj->Set(env->code_string(), estring);
763 obj->Set(env->path_string(), path_str);
766 if (syscall != NULL) {
767 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
775 // Does about the same as strerror(),
776 // but supports all windows error messages
777 static const char *winapi_strerror(const int errorno) {
780 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
781 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
782 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
785 // Remove trailing newlines
786 for (int i = strlen(errmsg) - 1;
787 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
793 // FormatMessage failed
794 return "Unknown error";
799 Local<Value> WinapiErrnoException(int errorno,
803 Environment* env = Environment::GetCurrent(node_isolate);
806 if (!msg || !msg[0]) {
807 msg = winapi_strerror(errorno);
809 Local<String> message = OneByteString(node_isolate, msg);
812 Local<String> cons1 =
813 String::Concat(message, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
814 Local<String> cons2 =
815 String::Concat(cons1, String::NewFromUtf8(node_isolate, path));
816 Local<String> cons3 =
817 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
818 e = Exception::Error(cons3);
820 e = Exception::Error(message);
823 Local<Object> obj = e->ToObject();
824 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
827 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
830 if (syscall != NULL) {
831 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
839 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
840 Environment* env = Environment::GetCurrent(args.GetIsolate());
842 if (env->using_domains()) return;
843 env->set_using_domains(true);
845 HandleScope scope(node_isolate);
846 Local<Object> process_object = env->process_object();
848 Local<String> tick_callback_function_key =
849 FIXED_ONE_BYTE_STRING(node_isolate, "_tickDomainCallback");
850 Local<Function> tick_callback_function =
851 process_object->Get(tick_callback_function_key).As<Function>();
853 if (!tick_callback_function->IsFunction()) {
854 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
858 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"),
859 tick_callback_function);
860 env->set_tick_callback_function(tick_callback_function);
862 if (!args[0]->IsArray()) {
863 fprintf(stderr, "_setupDomainUse first argument must be an array\n");
866 env->set_domain_array(args[0].As<Array>());
868 if (!args[1]->IsObject()) {
869 fprintf(stderr, "_setupDomainUse second argument must be an object\n");
873 Local<Object> domain_flag_obj = args[1].As<Object>();
874 Environment::DomainFlag* domain_flag = env->domain_flag();
875 domain_flag_obj->SetIndexedPropertiesToExternalArrayData(
876 domain_flag->fields(),
877 kExternalUnsignedIntArray,
878 domain_flag->fields_count());
882 Handle<Value> MakeDomainCallback(Environment* env,
883 const Handle<Object> object,
884 const Handle<Function> callback,
886 Handle<Value> argv[]) {
887 // If you hit this assertion, you forgot to enter the v8::Context first.
888 assert(env->context() == env->isolate()->GetCurrentContext());
890 // TODO(trevnorris) Hook for long stack traces to be made here.
892 Local<Value> domain_v = object->Get(env->domain_string());
893 Local<Object> domain;
896 try_catch.SetVerbose(true);
898 bool has_domain = domain_v->IsObject();
900 domain = domain_v.As<Object>();
902 if (domain->Get(env->disposed_string())->IsTrue()) {
903 // domain has been disposed of.
904 return Undefined(node_isolate);
907 Local<Function> enter =
908 domain->Get(env->enter_string()).As<Function>();
909 assert(enter->IsFunction());
910 enter->Call(domain, 0, NULL);
912 if (try_catch.HasCaught()) {
913 return Undefined(node_isolate);
917 Local<Value> ret = callback->Call(object, argc, argv);
919 if (try_catch.HasCaught()) {
920 return Undefined(node_isolate);
924 Local<Function> exit =
925 domain->Get(env->exit_string()).As<Function>();
926 assert(exit->IsFunction());
927 exit->Call(domain, 0, NULL);
929 if (try_catch.HasCaught()) {
930 return Undefined(node_isolate);
934 Environment::TickInfo* tick_info = env->tick_info();
936 if (tick_info->last_threw() == 1) {
937 tick_info->set_last_threw(0);
941 if (tick_info->in_tick() == 1) {
945 if (tick_info->length() == 0) {
946 tick_info->set_index(0);
950 // process nextTicks after call
951 Local<Object> process_object = env->process_object();
952 Local<Function> tick_callback_function = env->tick_callback_function();
953 tick_callback_function->Call(process_object, 0, NULL);
955 if (try_catch.HasCaught()) {
956 return Undefined(node_isolate);
963 Handle<Value> MakeCallback(Environment* env,
964 const Handle<Object> object,
965 const Handle<Function> callback,
967 Handle<Value> argv[]) {
968 // If you hit this assertion, you forgot to enter the v8::Context first.
969 assert(env->context() == env->isolate()->GetCurrentContext());
971 // TODO(trevnorris) Hook for long stack traces to be made here.
972 Local<Object> process_object = env->process_object();
974 if (env->using_domains())
975 return MakeDomainCallback(env, object, callback, argc, argv);
978 try_catch.SetVerbose(true);
980 Local<Value> ret = callback->Call(object, argc, argv);
982 if (try_catch.HasCaught()) {
983 return Undefined(node_isolate);
986 Environment::TickInfo* tick_info = env->tick_info();
988 if (tick_info->in_tick() == 1) {
992 if (tick_info->length() == 0) {
993 tick_info->set_index(0);
997 // lazy load no domain next tick callbacks
998 Local<Function> tick_callback_function = env->tick_callback_function();
999 if (tick_callback_function.IsEmpty()) {
1000 Local<String> tick_callback_function_key =
1001 FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback");
1002 tick_callback_function =
1003 process_object->Get(tick_callback_function_key).As<Function>();
1004 if (!tick_callback_function->IsFunction()) {
1005 fprintf(stderr, "process._tickCallback assigned to non-function\n");
1008 env->set_tick_callback_function(tick_callback_function);
1011 // process nextTicks after call
1012 tick_callback_function->Call(process_object, 0, NULL);
1014 if (try_catch.HasCaught()) {
1015 return Undefined(node_isolate);
1023 Handle<Value> MakeCallback(Environment* env,
1024 const Handle<Object> object,
1027 Handle<Value> argv[]) {
1028 // If you hit this assertion, you forgot to enter the v8::Context first.
1029 assert(env->context() == env->isolate()->GetCurrentContext());
1031 Local<Function> callback = object->Get(index).As<Function>();
1032 assert(callback->IsFunction());
1034 if (env->using_domains()) {
1035 return MakeDomainCallback(env, object, callback, argc, argv);
1038 return MakeCallback(env, object, callback, argc, argv);
1042 Handle<Value> MakeCallback(Environment* env,
1043 const Handle<Object> object,
1044 const Handle<String> symbol,
1046 Handle<Value> argv[]) {
1047 // If you hit this assertion, you forgot to enter the v8::Context first.
1048 assert(env->context() == env->isolate()->GetCurrentContext());
1050 Local<Function> callback = object->Get(symbol).As<Function>();
1051 assert(callback->IsFunction());
1053 if (env->using_domains()) {
1054 return MakeDomainCallback(env, object, callback, argc, argv);
1057 return MakeCallback(env, object, callback, argc, argv);
1061 Handle<Value> MakeCallback(Environment* env,
1062 const Handle<Object> object,
1065 Handle<Value> argv[]) {
1066 // If you hit this assertion, you forgot to enter the v8::Context first.
1067 assert(env->context() == env->isolate()->GetCurrentContext());
1068 Local<String> method_string = OneByteString(node_isolate, method);
1069 return MakeCallback(env, object, method_string, argc, argv);
1073 Handle<Value> MakeCallback(const Handle<Object> object,
1076 Handle<Value> argv[]) {
1077 Local<Context> context = object->CreationContext();
1078 Environment* env = Environment::GetCurrent(context);
1079 Context::Scope context_scope(context);
1080 HandleScope handle_scope(env->isolate());
1081 return handle_scope.Close(MakeCallback(env, object, method, argc, argv));
1085 Handle<Value> MakeCallback(const Handle<Object> object,
1086 const Handle<String> symbol,
1088 Handle<Value> argv[]) {
1089 Local<Context> context = object->CreationContext();
1090 Environment* env = Environment::GetCurrent(context);
1091 Context::Scope context_scope(context);
1092 HandleScope handle_scope(env->isolate());
1093 return handle_scope.Close(MakeCallback(env, object, symbol, argc, argv));
1097 Handle<Value> MakeCallback(const Handle<Object> object,
1098 const Handle<Function> callback,
1100 Handle<Value> argv[]) {
1101 Local<Context> context = object->CreationContext();
1102 Environment* env = Environment::GetCurrent(context);
1103 Context::Scope context_scope(context);
1104 HandleScope handle_scope(env->isolate());
1105 return handle_scope.Close(MakeCallback(env, object, callback, argc, argv));
1109 Handle<Value> MakeDomainCallback(const Handle<Object> object,
1110 const Handle<Function> callback,
1112 Handle<Value> argv[]) {
1113 Local<Context> context = object->CreationContext();
1114 Environment* env = Environment::GetCurrent(context);
1115 Context::Scope context_scope(context);
1116 HandleScope handle_scope(env->isolate());
1117 return handle_scope.Close(
1118 MakeDomainCallback(env, object, callback, argc, argv));
1122 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1123 HandleScope scope(node_isolate);
1125 if (!encoding_v->IsString()) return _default;
1127 String::Utf8Value encoding(encoding_v);
1129 if (strcasecmp(*encoding, "utf8") == 0) {
1131 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1133 } else if (strcasecmp(*encoding, "ascii") == 0) {
1135 } else if (strcasecmp(*encoding, "base64") == 0) {
1137 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1139 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1141 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1143 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1145 } else if (strcasecmp(*encoding, "binary") == 0) {
1147 } else if (strcasecmp(*encoding, "buffer") == 0) {
1149 } else if (strcasecmp(*encoding, "hex") == 0) {
1151 } else if (strcasecmp(*encoding, "raw") == 0) {
1152 if (!no_deprecation) {
1153 fprintf(stderr, "'raw' (array of integers) has been removed. "
1157 } else if (strcasecmp(*encoding, "raws") == 0) {
1158 if (!no_deprecation) {
1159 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1160 "Please update your code.\n");
1168 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1169 return StringBytes::Encode(static_cast<const char*>(buf),
1174 // Returns -1 if the handle was not valid for decoding
1175 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1176 HandleScope scope(node_isolate);
1178 if (val->IsArray()) {
1179 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1185 return StringBytes::Size(val, encoding);
1189 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1192 // Returns number of bytes written.
1193 ssize_t DecodeWrite(char *buf,
1195 v8::Handle<v8::Value> val,
1196 enum encoding encoding) {
1197 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1200 void DisplayExceptionLine(Handle<Message> message) {
1201 // Prevent re-entry into this function. For example, if there is
1202 // a throw from a program in vm.runInThisContext(code, filename, true),
1203 // then we want to show the original failure, not the secondary one.
1204 static bool displayed_error = false;
1206 if (displayed_error) return;
1207 displayed_error = true;
1209 uv_tty_reset_mode();
1211 fprintf(stderr, "\n");
1213 if (!message.IsEmpty()) {
1214 // Print (filename):(line number): (message).
1215 String::Utf8Value filename(message->GetScriptResourceName());
1216 const char* filename_string = *filename;
1217 int linenum = message->GetLineNumber();
1218 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1219 // Print line of source code.
1220 String::Utf8Value sourceline(message->GetSourceLine());
1221 const char* sourceline_string = *sourceline;
1223 // Because of how node modules work, all scripts are wrapped with a
1224 // "function (module, exports, __filename, ...) {"
1225 // to provide script local variables.
1227 // When reporting errors on the first line of a script, this wrapper
1228 // function is leaked to the user. There used to be a hack here to
1229 // truncate off the first 62 characters, but it caused numerous other
1230 // problems when vm.runIn*Context() methods were used for non-module
1233 // If we ever decide to re-instate such a hack, the following steps
1236 // 1. Pass a flag around to say "this code was wrapped"
1237 // 2. Update the stack frame output so that it is also correct.
1239 // It would probably be simpler to add a line rather than add some
1240 // number of characters to the first line, since V8 truncates the
1241 // sourceline to 78 characters, and we end up not providing very much
1242 // useful debugging info to the user if we remove 62 characters.
1244 int start = message->GetStartColumn();
1245 int end = message->GetEndColumn();
1247 fprintf(stderr, "%s\n", sourceline_string);
1248 // Print wavy underline (GetUnderline is deprecated).
1249 for (int i = 0; i < start; i++) {
1250 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1252 for (int i = start; i < end; i++) {
1255 fputc('\n', stderr);
1260 static void ReportException(Handle<Value> er, Handle<Message> message) {
1261 HandleScope scope(node_isolate);
1263 DisplayExceptionLine(message);
1265 Local<Value> trace_value(
1266 er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack")));
1267 String::Utf8Value trace(trace_value);
1269 // range errors have a trace member set to undefined
1270 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1271 fprintf(stderr, "%s\n", *trace);
1273 // this really only happens for RangeErrors, since they're the only
1274 // kind that won't have all this info in the trace, or when non-Error
1275 // objects are thrown manually.
1276 Local<Value> message;
1279 if (er->IsObject()) {
1280 Local<Object> err_obj = er.As<Object>();
1281 message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1282 name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1285 if (message.IsEmpty() ||
1286 message->IsUndefined() ||
1288 name->IsUndefined()) {
1289 // Not an error object. Just print as-is.
1290 String::Utf8Value message(er);
1291 fprintf(stderr, "%s\n", *message);
1293 String::Utf8Value name_string(name);
1294 String::Utf8Value message_string(message);
1295 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1303 static void ReportException(const TryCatch& try_catch) {
1304 ReportException(try_catch.Exception(), try_catch.Message());
1308 // Executes a str within the current v8 context.
1309 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1310 HandleScope scope(node_isolate);
1313 // try_catch must be nonverbose to disable FatalException() handler,
1314 // we will handle exceptions ourself.
1315 try_catch.SetVerbose(false);
1317 Local<v8::Script> script = v8::Script::Compile(source, filename);
1318 if (script.IsEmpty()) {
1319 ReportException(try_catch);
1323 Local<Value> result = script->Run();
1324 if (result.IsEmpty()) {
1325 ReportException(try_catch);
1329 return scope.Close(result);
1333 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1334 HandleScope scope(node_isolate);
1336 Local<Array> ary = Array::New();
1340 QUEUE_FOREACH(q, &req_wrap_queue) {
1341 ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1342 if (w->persistent().IsEmpty()) continue;
1343 ary->Set(i++, w->object());
1346 args.GetReturnValue().Set(ary);
1350 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1351 // implemented here for consistency with GetActiveRequests().
1352 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1353 HandleScope scope(node_isolate);
1355 Local<Array> ary = Array::New();
1359 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1361 QUEUE_FOREACH(q, &handle_wrap_queue) {
1362 HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1363 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue;
1364 Local<Object> object = w->object();
1365 Local<Value> owner = object->Get(owner_sym);
1366 if (owner->IsUndefined()) owner = object;
1367 ary->Set(i++, owner);
1370 args.GetReturnValue().Set(ary);
1374 static void Abort(const FunctionCallbackInfo<Value>& args) {
1379 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1380 HandleScope scope(node_isolate);
1382 if (args.Length() != 1 || !args[0]->IsString()) {
1383 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1386 String::Utf8Value path(args[0]);
1387 int err = uv_chdir(*path);
1389 return ThrowUVException(err, "uv_chdir");
1394 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1395 HandleScope scope(node_isolate);
1397 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1398 char buf[MAX_PATH * 4 + 1];
1400 char buf[PATH_MAX + 1];
1403 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1405 return ThrowUVException(err, "uv_cwd");
1408 buf[ARRAY_SIZE(buf) - 1] = '\0';
1409 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1411 args.GetReturnValue().Set(cwd);
1415 static void Umask(const FunctionCallbackInfo<Value>& args) {
1416 HandleScope scope(node_isolate);
1419 if (args.Length() < 1 || args[0]->IsUndefined()) {
1421 umask(static_cast<mode_t>(old));
1422 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1423 return ThrowTypeError("argument must be an integer or octal string.");
1426 if (args[0]->IsInt32()) {
1427 oct = args[0]->Uint32Value();
1430 String::Utf8Value str(args[0]);
1432 // Parse the octal string.
1433 for (int i = 0; i < str.length(); i++) {
1435 if (c > '7' || c < '0') {
1436 return ThrowTypeError("invalid octal string");
1442 old = umask(static_cast<mode_t>(oct));
1445 args.GetReturnValue().Set(old);
1449 #if defined(__POSIX__) && !defined(__ANDROID__)
1451 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1452 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1455 static uid_t uid_by_name(const char* name) {
1463 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1467 return uid_not_found;
1471 static char* name_by_uid(uid_t uid) {
1480 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1481 return strdup(pp->pw_name);
1492 static gid_t gid_by_name(const char* name) {
1500 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1504 return gid_not_found;
1508 #if 0 // For future use.
1509 static const char* name_by_gid(gid_t gid) {
1518 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1519 return strdup(pp->gr_name);
1531 static uid_t uid_by_name(Handle<Value> value) {
1532 if (value->IsUint32()) {
1533 return static_cast<uid_t>(value->Uint32Value());
1535 String::Utf8Value name(value);
1536 return uid_by_name(*name);
1541 static gid_t gid_by_name(Handle<Value> value) {
1542 if (value->IsUint32()) {
1543 return static_cast<gid_t>(value->Uint32Value());
1545 String::Utf8Value name(value);
1546 return gid_by_name(*name);
1551 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1552 // uid_t is an uint32_t on all supported platforms.
1553 args.GetReturnValue().Set(static_cast<uint32_t>(getuid()));
1557 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1558 // gid_t is an uint32_t on all supported platforms.
1559 args.GetReturnValue().Set(static_cast<uint32_t>(getgid()));
1563 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1564 HandleScope scope(node_isolate);
1566 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1567 return ThrowTypeError("setgid argument must be a number or a string");
1570 gid_t gid = gid_by_name(args[0]);
1572 if (gid == gid_not_found) {
1573 return ThrowError("setgid group id does not exist");
1577 return ThrowErrnoException(errno, "setgid");
1582 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1583 HandleScope scope(node_isolate);
1585 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1586 return ThrowTypeError("setuid argument must be a number or a string");
1589 uid_t uid = uid_by_name(args[0]);
1591 if (uid == uid_not_found) {
1592 return ThrowError("setuid user id does not exist");
1596 return ThrowErrnoException(errno, "setuid");
1601 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1602 HandleScope scope(node_isolate);
1604 int ngroups = getgroups(0, NULL);
1606 if (ngroups == -1) {
1607 return ThrowErrnoException(errno, "getgroups");
1610 gid_t* groups = new gid_t[ngroups];
1612 ngroups = getgroups(ngroups, groups);
1614 if (ngroups == -1) {
1616 return ThrowErrnoException(errno, "getgroups");
1619 Local<Array> groups_list = Array::New(ngroups);
1620 bool seen_egid = false;
1621 gid_t egid = getegid();
1623 for (int i = 0; i < ngroups; i++) {
1624 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1625 if (groups[i] == egid) seen_egid = true;
1630 if (seen_egid == false) {
1631 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1634 args.GetReturnValue().Set(groups_list);
1638 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1639 HandleScope scope(node_isolate);
1641 if (!args[0]->IsArray()) {
1642 return ThrowTypeError("argument 1 must be an array");
1645 Local<Array> groups_list = args[0].As<Array>();
1646 size_t size = groups_list->Length();
1647 gid_t* groups = new gid_t[size];
1649 for (size_t i = 0; i < size; i++) {
1650 gid_t gid = gid_by_name(groups_list->Get(i));
1652 if (gid == gid_not_found) {
1654 return ThrowError("group name not found");
1660 int rc = setgroups(size, groups);
1664 return ThrowErrnoException(errno, "setgroups");
1669 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1670 HandleScope scope(node_isolate);
1672 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1673 return ThrowTypeError("argument 1 must be a number or a string");
1676 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1677 return ThrowTypeError("argument 2 must be a number or a string");
1680 String::Utf8Value arg0(args[0]);
1685 if (args[0]->IsUint32()) {
1686 user = name_by_uid(args[0]->Uint32Value());
1694 return ThrowError("initgroups user not found");
1697 extra_group = gid_by_name(args[1]);
1699 if (extra_group == gid_not_found) {
1700 if (must_free) free(user);
1701 return ThrowError("initgroups extra group not found");
1704 int rc = initgroups(user, extra_group);
1711 return ThrowErrnoException(errno, "initgroups");
1715 #endif // __POSIX__ && !defined(__ANDROID__)
1718 void Exit(const FunctionCallbackInfo<Value>& args) {
1719 HandleScope scope(node_isolate);
1720 exit(args[0]->IntegerValue());
1724 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1725 HandleScope scope(node_isolate);
1727 if (uv_uptime(&uptime)) return;
1728 args.GetReturnValue().Set(uptime - prog_start_time);
1732 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1733 Environment* env = Environment::GetCurrent(args.GetIsolate());
1734 HandleScope handle_scope(args.GetIsolate());
1737 int err = uv_resident_set_memory(&rss);
1739 return ThrowUVException(err, "uv_resident_set_memory");
1743 HeapStatistics v8_heap_stats;
1744 node_isolate->GetHeapStatistics(&v8_heap_stats);
1746 Local<Integer> heap_total =
1747 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(), node_isolate);
1748 Local<Integer> heap_used =
1749 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(), node_isolate);
1751 Local<Object> info = Object::New();
1752 info->Set(env->rss_string(), Number::New(node_isolate, rss));
1753 info->Set(env->heap_total_string(), heap_total);
1754 info->Set(env->heap_used_string(), heap_used);
1756 args.GetReturnValue().Set(info);
1760 void Kill(const FunctionCallbackInfo<Value>& args) {
1761 HandleScope scope(node_isolate);
1763 if (args.Length() != 2) {
1764 return ThrowError("Bad argument.");
1767 int pid = args[0]->IntegerValue();
1768 int sig = args[1]->Int32Value();
1769 int err = uv_kill(pid, sig);
1770 args.GetReturnValue().Set(err);
1773 // used in Hrtime() below
1774 #define NANOS_PER_SEC 1000000000
1776 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1777 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1778 // so this function instead returns an Array with 2 entries representing seconds
1779 // and nanoseconds, to avoid any integer overflow possibility.
1780 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1781 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1782 HandleScope scope(node_isolate);
1784 uint64_t t = uv_hrtime();
1786 if (args.Length() > 0) {
1787 // return a time diff tuple
1788 if (!args[0]->IsArray()) {
1789 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1791 Local<Array> inArray = Local<Array>::Cast(args[0]);
1792 uint64_t seconds = inArray->Get(0)->Uint32Value();
1793 uint64_t nanos = inArray->Get(1)->Uint32Value();
1794 t -= (seconds * NANOS_PER_SEC) + nanos;
1797 Local<Array> tuple = Array::New(2);
1798 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1799 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1800 args.GetReturnValue().Set(tuple);
1804 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1806 // DLOpen is process.dlopen(module, filename).
1807 // Used to load 'module.node' dynamically shared objects.
1809 // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
1810 // when two contexts try to load the same shared object. Maybe have a shadow
1811 // cache that's a plain C list or hash table that's shared across contexts?
1812 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1813 Environment* env = Environment::GetCurrent(args.GetIsolate());
1814 HandleScope handle_scope(args.GetIsolate());
1815 char symbol[1024], *base, *pos;
1819 if (args.Length() < 2) {
1820 return ThrowError("process.dlopen takes exactly 2 arguments.");
1823 Local<Object> module = args[0]->ToObject(); // Cast
1824 String::Utf8Value filename(args[1]); // Cast
1826 Local<String> exports_string = env->exports_string();
1827 Local<Object> exports = module->Get(exports_string)->ToObject();
1829 if (uv_dlopen(*filename, &lib)) {
1830 Local<String> errmsg = OneByteString(env->isolate(), uv_dlerror(&lib));
1832 // Windows needs to add the filename into the error message
1833 errmsg = String::Concat(errmsg, args[1]->ToString());
1835 ThrowException(Exception::Error(errmsg));
1839 String::Utf8Value path(args[1]);
1842 /* Find the shared library filename within the full path. */
1844 pos = strrchr(base, '/');
1850 pos = strpbrk(base, "\\/:");
1858 /* Strip the .node extension. */
1859 pos = strrchr(base, '.');
1864 /* Add the `_module` suffix to the extension name. */
1865 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1866 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1867 return ThrowError("Out of memory.");
1870 /* Replace dashes with underscores. When loading foo-bar.node,
1871 * look for foo_bar_module, not foo-bar_module.
1873 for (pos = symbol; *pos != '\0'; ++pos) {
1874 if (*pos == '-') *pos = '_';
1877 node_module_struct *mod;
1878 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1880 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1881 return ThrowError(errmsg);
1884 if (mod->version != NODE_MODULE_VERSION) {
1888 "Module version mismatch. Expected %d, got %d.",
1889 NODE_MODULE_VERSION, mod->version);
1890 return ThrowError(errmsg);
1893 // Execute the C++ module
1894 if (mod->register_context_func != NULL) {
1895 mod->register_context_func(exports, module, env->context());
1896 } else if (mod->register_func != NULL) {
1897 mod->register_func(exports, module);
1899 return ThrowError("Module has no declared entry point.");
1902 // Tell coverity that 'handle' should not be freed when we return.
1903 // coverity[leaked_storage]
1907 static void OnFatalError(const char* location, const char* message) {
1909 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1911 fprintf(stderr, "FATAL ERROR: %s\n", message);
1921 NO_RETURN void FatalError(const char* location, const char* message) {
1922 OnFatalError(location, message);
1923 // to supress compiler warning
1928 void FatalException(Handle<Value> error, Handle<Message> message) {
1929 HandleScope scope(node_isolate);
1931 Environment* env = Environment::GetCurrent(node_isolate);
1932 Local<Object> process_object = env->process_object();
1933 Local<String> fatal_exception_string = env->fatal_exception_string();
1934 Local<Function> fatal_exception_function =
1935 process_object->Get(fatal_exception_string).As<Function>();
1937 if (!fatal_exception_function->IsFunction()) {
1938 // failed before the process._fatalException function was added!
1939 // this is probably pretty bad. Nothing to do but report and exit.
1940 ReportException(error, message);
1944 TryCatch fatal_try_catch;
1946 // Do not call FatalException when _fatalException handler throws
1947 fatal_try_catch.SetVerbose(false);
1949 // this will return true if the JS layer handled it, false otherwise
1950 Local<Value> caught =
1951 fatal_exception_function->Call(process_object, 1, &error);
1953 if (fatal_try_catch.HasCaught()) {
1954 // the fatal exception function threw, so we must exit
1955 ReportException(fatal_try_catch);
1959 if (false == caught->BooleanValue()) {
1960 ReportException(error, message);
1966 void FatalException(const TryCatch& try_catch) {
1967 HandleScope scope(node_isolate);
1968 // TODO(bajtos) do not call FatalException if try_catch is verbose
1969 // (requires V8 API to expose getter for try_catch.is_verbose_)
1970 FatalException(try_catch.Exception(), try_catch.Message());
1974 void OnMessage(Handle<Message> message, Handle<Value> error) {
1975 // The current version of V8 sends messages for errors only
1976 // (thus `error` is always set).
1977 FatalException(error, message);
1981 static void Binding(const FunctionCallbackInfo<Value>& args) {
1982 Environment* env = Environment::GetCurrent(args.GetIsolate());
1983 HandleScope handle_scope(args.GetIsolate());
1985 Local<String> module = args[0]->ToString();
1986 String::Utf8Value module_v(module);
1988 Local<Object> cache = env->binding_cache_object();
1989 Local<Object> exports;
1991 if (cache->Has(module)) {
1992 exports = cache->Get(module)->ToObject();
1993 args.GetReturnValue().Set(exports);
1997 // Append a string to process.moduleLoadList
1999 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
2001 Local<Array> modules = env->module_load_list_array();
2002 uint32_t l = modules->Length();
2003 modules->Set(l, OneByteString(node_isolate, buf));
2005 node_module_struct* mod = get_builtin_module(*module_v);
2007 exports = Object::New();
2008 // Internal bindings don't have a "module" object, only exports.
2009 assert(mod->register_func == NULL);
2010 assert(mod->register_context_func != NULL);
2011 Local<Value> unused = Undefined(env->isolate());
2012 mod->register_context_func(exports, unused, env->context());
2013 cache->Set(module, exports);
2014 } else if (!strcmp(*module_v, "constants")) {
2015 exports = Object::New();
2016 DefineConstants(exports);
2017 cache->Set(module, exports);
2018 } else if (!strcmp(*module_v, "natives")) {
2019 exports = Object::New();
2020 DefineJavaScript(exports);
2021 cache->Set(module, exports);
2023 return ThrowError("No such module");
2026 args.GetReturnValue().Set(exports);
2030 static void ProcessTitleGetter(Local<String> property,
2031 const PropertyCallbackInfo<Value>& info) {
2032 HandleScope scope(node_isolate);
2034 uv_get_process_title(buffer, sizeof(buffer));
2035 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2039 static void ProcessTitleSetter(Local<String> property,
2041 const PropertyCallbackInfo<void>& info) {
2042 HandleScope scope(node_isolate);
2043 String::Utf8Value title(value);
2044 // TODO(piscisaureus): protect with a lock
2045 uv_set_process_title(*title);
2049 static void EnvGetter(Local<String> property,
2050 const PropertyCallbackInfo<Value>& info) {
2051 HandleScope scope(node_isolate);
2053 String::Utf8Value key(property);
2054 const char* val = getenv(*key);
2056 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2059 String::Value key(property);
2060 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2061 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2063 ARRAY_SIZE(buffer));
2064 // If result >= sizeof buffer the buffer was too small. That should never
2065 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2067 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2068 result < ARRAY_SIZE(buffer)) {
2069 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2070 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2071 return info.GetReturnValue().Set(rc);
2074 // Not found. Fetch from prototype.
2075 info.GetReturnValue().Set(
2076 info.Data().As<Object>()->Get(property));
2080 static void EnvSetter(Local<String> property,
2082 const PropertyCallbackInfo<Value>& info) {
2083 HandleScope scope(node_isolate);
2085 String::Utf8Value key(property);
2086 String::Utf8Value val(value);
2087 setenv(*key, *val, 1);
2089 String::Value key(property);
2090 String::Value val(value);
2091 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2092 // Environment variables that start with '=' are read-only.
2093 if (key_ptr[0] != L'=') {
2094 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2097 // Whether it worked or not, always return rval.
2098 info.GetReturnValue().Set(value);
2102 static void EnvQuery(Local<String> property,
2103 const PropertyCallbackInfo<Integer>& info) {
2104 HandleScope scope(node_isolate);
2105 int32_t rc = -1; // Not found unless proven otherwise.
2107 String::Utf8Value key(property);
2108 if (getenv(*key)) rc = 0;
2110 String::Value key(property);
2111 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2112 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2113 GetLastError() == ERROR_SUCCESS) {
2115 if (key_ptr[0] == L'=') {
2116 // Environment variables that start with '=' are hidden and read-only.
2117 rc = static_cast<int32_t>(v8::ReadOnly) |
2118 static_cast<int32_t>(v8::DontDelete) |
2119 static_cast<int32_t>(v8::DontEnum);
2123 if (rc != -1) info.GetReturnValue().Set(rc);
2127 static void EnvDeleter(Local<String> property,
2128 const PropertyCallbackInfo<Boolean>& info) {
2129 HandleScope scope(node_isolate);
2132 String::Utf8Value key(property);
2133 rc = getenv(*key) != NULL;
2134 if (rc) unsetenv(*key);
2136 String::Value key(property);
2137 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2138 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2139 // Deletion failed. Return true if the key wasn't there in the first place,
2140 // false if it is still there.
2141 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2142 GetLastError() != ERROR_SUCCESS;
2145 info.GetReturnValue().Set(rc);
2149 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2150 HandleScope scope(node_isolate);
2153 while (environ[size]) size++;
2155 Local<Array> env = Array::New(size);
2157 for (int i = 0; i < size; ++i) {
2158 const char* var = environ[i];
2159 const char* s = strchr(var, '=');
2160 const int length = s ? s - var : strlen(var);
2161 Local<String> name = String::NewFromUtf8(node_isolate,
2163 String::kNormalString,
2168 WCHAR* environment = GetEnvironmentStringsW();
2169 if (environment == NULL) return; // This should not happen.
2170 Local<Array> env = Array::New();
2171 WCHAR* p = environment;
2173 while (*p != NULL) {
2176 // If the key starts with '=' it is a hidden environment variable.
2180 s = wcschr(p, L'=');
2185 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2186 const size_t two_byte_buffer_len = s - p;
2187 Local<String> value = String::NewFromTwoByte(node_isolate,
2189 String::kNormalString,
2190 two_byte_buffer_len);
2191 env->Set(i++, value);
2192 p = s + wcslen(s) + 1;
2194 FreeEnvironmentStringsW(environment);
2197 info.GetReturnValue().Set(env);
2201 static Handle<Object> GetFeatures() {
2202 HandleScope scope(node_isolate);
2204 Local<Object> obj = Object::New();
2205 #if defined(DEBUG) && DEBUG
2206 Local<Value> debug = True(node_isolate);
2208 Local<Value> debug = False(node_isolate);
2209 #endif // defined(DEBUG) && DEBUG
2211 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2213 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2214 // TODO(bnoordhuis) ping libuv
2215 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2217 #ifdef OPENSSL_NPN_NEGOTIATED
2218 Local<Boolean> tls_npn = True(node_isolate);
2220 Local<Boolean> tls_npn = False(node_isolate);
2222 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"), tls_npn);
2224 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2225 Local<Boolean> tls_sni = True(node_isolate);
2227 Local<Boolean> tls_sni = False(node_isolate);
2229 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"), tls_sni);
2231 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2232 Boolean::New(get_builtin_module("crypto") != NULL));
2234 return scope.Close(obj);
2238 static void DebugPortGetter(Local<String> property,
2239 const PropertyCallbackInfo<Value>& info) {
2240 HandleScope scope(node_isolate);
2241 info.GetReturnValue().Set(debug_port);
2245 static void DebugPortSetter(Local<String> property,
2247 const PropertyCallbackInfo<void>& info) {
2248 HandleScope scope(node_isolate);
2249 debug_port = value->NumberValue();
2253 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2254 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2255 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2258 void NeedImmediateCallbackGetter(Local<String> property,
2259 const PropertyCallbackInfo<Value>& info) {
2260 Environment* env = Environment::GetCurrent(info.GetIsolate());
2261 const uv_check_t* immediate_check_handle = env->immediate_check_handle();
2262 bool active = uv_is_active(
2263 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2264 info.GetReturnValue().Set(active);
2268 static void NeedImmediateCallbackSetter(
2269 Local<String> property,
2271 const PropertyCallbackInfo<void>& info) {
2272 Environment* env = Environment::GetCurrent(info.GetIsolate());
2273 HandleScope handle_scope(info.GetIsolate());
2275 uv_check_t* immediate_check_handle = env->immediate_check_handle();
2276 bool active = uv_is_active(
2277 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2279 if (active == value->BooleanValue())
2282 uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
2285 uv_check_stop(immediate_check_handle);
2286 uv_idle_stop(immediate_idle_handle);
2288 uv_check_start(immediate_check_handle, CheckImmediate);
2289 // Idle handle is needed only to stop the event loop from blocking in poll.
2290 uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
2295 #define READONLY_PROPERTY(obj, str, var) \
2297 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2301 void SetupProcessObject(Environment* env,
2303 const char* const* argv,
2305 const char* const* exec_argv) {
2306 HandleScope scope(node_isolate);
2309 Local<Object> process = env->process_object();
2311 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2313 ProcessTitleSetter);
2316 READONLY_PROPERTY(process,
2318 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2320 // process.moduleLoadList
2321 READONLY_PROPERTY(process,
2323 env->module_load_list_array());
2326 Local<Object> versions = Object::New();
2327 READONLY_PROPERTY(process, "versions", versions);
2329 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2331 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2332 READONLY_PROPERTY(versions,
2334 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2336 // +1 to get rid of the leading 'v'
2337 READONLY_PROPERTY(versions,
2339 OneByteString(node_isolate, NODE_VERSION + 1));
2340 READONLY_PROPERTY(versions,
2342 OneByteString(node_isolate, V8::GetVersion()));
2343 READONLY_PROPERTY(versions,
2345 OneByteString(node_isolate, uv_version_string()));
2346 READONLY_PROPERTY(versions,
2348 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2350 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2351 READONLY_PROPERTY(versions,
2353 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2356 // Stupid code to slice out the version string.
2357 int c, l = strlen(OPENSSL_VERSION_TEXT);
2358 for (i = j = 0; i < l; i++) {
2359 c = OPENSSL_VERSION_TEXT[i];
2360 if ('0' <= c && c <= '9') {
2361 for (j = i + 1; j < l; j++) {
2362 c = OPENSSL_VERSION_TEXT[j];
2363 if (c == ' ') break;
2371 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2375 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2378 READONLY_PROPERTY(process,
2380 OneByteString(node_isolate, PLATFORM));
2383 Local<Array> arguments = Array::New(argc);
2384 for (int i = 0; i < argc; ++i) {
2385 arguments->Set(i, String::NewFromUtf8(node_isolate, argv[i]));
2387 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2390 Local<Array> exec_arguments = Array::New(exec_argc);
2391 for (int i = 0; i < exec_argc; ++i) {
2392 exec_arguments->Set(i, String::NewFromUtf8(node_isolate, exec_argv[i]));
2394 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_arguments);
2396 // create process.env
2397 Local<ObjectTemplate> process_env_template = ObjectTemplate::New();
2398 process_env_template->SetNamedPropertyHandler(EnvGetter,
2404 Local<Object> process_env = process_env_template->NewInstance();
2405 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), process_env);
2407 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2408 READONLY_PROPERTY(process, "features", GetFeatures());
2409 process->SetAccessor(
2410 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2411 NeedImmediateCallbackGetter,
2412 NeedImmediateCallbackSetter);
2416 READONLY_PROPERTY(process,
2418 String::NewFromUtf8(node_isolate, eval_string));
2423 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2426 // -i, --interactive
2428 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2432 if (no_deprecation) {
2433 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2436 // --throw-deprecation
2437 if (throw_deprecation) {
2438 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2441 // --trace-deprecation
2442 if (trace_deprecation) {
2443 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2446 size_t exec_path_len = 2 * PATH_MAX;
2447 char* exec_path = new char[exec_path_len];
2448 Local<String> exec_path_value;
2449 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2450 exec_path_value = String::NewFromUtf8(node_isolate,
2452 String::kNormalString,
2455 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2457 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2461 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2465 // define various internal methods
2466 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2467 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2468 NODE_SET_METHOD(process, "reallyExit", Exit);
2469 NODE_SET_METHOD(process, "abort", Abort);
2470 NODE_SET_METHOD(process, "chdir", Chdir);
2471 NODE_SET_METHOD(process, "cwd", Cwd);
2473 NODE_SET_METHOD(process, "umask", Umask);
2475 #if defined(__POSIX__) && !defined(__ANDROID__)
2476 NODE_SET_METHOD(process, "getuid", GetUid);
2477 NODE_SET_METHOD(process, "setuid", SetUid);
2479 NODE_SET_METHOD(process, "setgid", SetGid);
2480 NODE_SET_METHOD(process, "getgid", GetGid);
2482 NODE_SET_METHOD(process, "getgroups", GetGroups);
2483 NODE_SET_METHOD(process, "setgroups", SetGroups);
2484 NODE_SET_METHOD(process, "initgroups", InitGroups);
2485 #endif // __POSIX__ && !defined(__ANDROID__)
2487 NODE_SET_METHOD(process, "_kill", Kill);
2489 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2490 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2491 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2493 NODE_SET_METHOD(process, "hrtime", Hrtime);
2495 NODE_SET_METHOD(process, "dlopen", DLOpen);
2497 NODE_SET_METHOD(process, "uptime", Uptime);
2498 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2500 NODE_SET_METHOD(process, "binding", Binding);
2502 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2504 // values use to cross communicate with processNextTick
2505 Local<Object> tick_info_obj = Object::New();
2506 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
2507 env->tick_info()->fields(),
2508 kExternalUnsignedIntArray,
2509 env->tick_info()->fields_count());
2510 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfo"), tick_info_obj);
2512 // pre-set _events object for faster emit checks
2513 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2517 #undef READONLY_PROPERTY
2520 static void AtExit() {
2521 uv_tty_reset_mode();
2525 static void SignalExit(int signal) {
2526 uv_tty_reset_mode();
2527 _exit(128 + signal);
2531 // Most of the time, it's best to use `console.error` to write
2532 // to the process.stderr stream. However, in some cases, such as
2533 // when debugging the stream.Writable class or the process.nextTick
2534 // function, it is useful to bypass JavaScript entirely.
2535 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2536 HandleScope scope(node_isolate);
2538 assert(args.Length() == 1 && args[0]->IsString() &&
2539 "must be called with a single string");
2541 String::Utf8Value message(args[0]);
2542 fprintf(stderr, "%s\n", *message);
2547 void Load(Environment* env) {
2548 HandleScope handle_scope(node_isolate);
2550 // Compile, execute the src/node.js file. (Which was included as static C
2551 // string in node_natives.h. 'natve_node' is the string containing that
2554 // The node.js file returns a function 'f'
2559 // Disable verbose mode to stop FatalException() handler from trying
2560 // to handle the exception. Errors this early in the start-up phase
2561 // are not safe to ignore.
2562 try_catch.SetVerbose(false);
2564 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2565 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2566 if (try_catch.HasCaught()) {
2567 ReportException(try_catch);
2570 assert(f_value->IsFunction());
2571 Local<Function> f = Local<Function>::Cast(f_value);
2573 // Now we call 'f' with the 'process' variable that we've built up with
2574 // all our bindings. Inside node.js we'll take care of assigning things to
2577 // We start the process this way in order to be more modular. Developers
2578 // who do not like how 'src/node.js' setups the module system but do like
2579 // Node's I/O bindings may want to replace 'f' with their own function.
2581 // Add a reference to the global object
2582 Local<Object> global = env->context()->Global();
2584 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2588 #if defined HAVE_PERFCTR
2589 InitPerfCounters(global);
2592 // Enable handling of uncaught exceptions
2593 // (FatalException(), break on uncaught exception in debugger)
2595 // This is not strictly necessary since it's almost impossible
2596 // to attach the debugger fast enought to break on exception
2597 // thrown during process startup.
2598 try_catch.SetVerbose(true);
2600 NODE_SET_METHOD(env->process_object(), "_rawDebug", RawDebug);
2602 Local<Value> arg = env->process_object();
2603 f->Call(global, 1, &arg);
2606 static void PrintHelp();
2608 static void ParseDebugOpt(const char* arg) {
2611 if (strstr(arg, "--debug-port=") == arg) {
2612 p = 1 + strchr(arg, '=');
2613 debug_port = atoi(p);
2615 use_debug_agent = true;
2616 if (!strcmp(arg, "--debug-brk")) {
2617 debug_wait_connect = true;
2619 } else if (!strcmp(arg, "--debug")) {
2621 } else if (strstr(arg, "--debug-brk=") == arg) {
2622 debug_wait_connect = true;
2623 p = 1 + strchr(arg, '=');
2624 debug_port = atoi(p);
2625 } else if (strstr(arg, "--debug=") == arg) {
2626 p = 1 + strchr(arg, '=');
2627 debug_port = atoi(p);
2630 if (p && debug_port > 1024 && debug_port < 65536)
2633 fprintf(stderr, "Bad debug option.\n");
2634 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2640 static void PrintHelp() {
2641 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2642 " node debug script.js [arguments] \n"
2645 " -v, --version print node's version\n"
2646 " -e, --eval script evaluate script\n"
2647 " -p, --print evaluate script and print result\n"
2648 " -i, --interactive always enter the REPL even if stdin\n"
2649 " does not appear to be a terminal\n"
2650 " --no-deprecation silence deprecation warnings\n"
2651 " --trace-deprecation show stack traces on deprecations\n"
2652 " --v8-options print v8 command line options\n"
2653 " --max-stack-size=val set max v8 stack size (bytes)\n"
2655 "Environment variables:\n"
2657 "NODE_PATH ';'-separated list of directories\n"
2659 "NODE_PATH ':'-separated list of directories\n"
2661 " prefixed to the module search path.\n"
2662 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2663 " global contexts.\n"
2664 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2666 "Documentation can be found at http://nodejs.org/\n");
2670 // Parse command line arguments.
2672 // argv is modified in place. exec_argv and v8_argv are out arguments that
2673 // ParseArgs() allocates memory for and stores a pointer to the output
2674 // vector in. The caller should free them with delete[].
2678 // * argv contains the arguments with node and V8 options filtered out.
2679 // * exec_argv contains both node and V8 options and nothing else.
2680 // * v8_argv contains argv[0] plus any V8 options
2681 static void ParseArgs(int* argc,
2684 const char*** exec_argv,
2686 const char*** v8_argv) {
2687 const unsigned int nargs = static_cast<unsigned int>(*argc);
2688 const char** new_exec_argv = new const char*[nargs];
2689 const char** new_v8_argv = new const char*[nargs];
2690 const char** new_argv = new const char*[nargs];
2692 for (unsigned int i = 0; i < nargs; ++i) {
2693 new_exec_argv[i] = NULL;
2694 new_v8_argv[i] = NULL;
2698 // exec_argv starts with the first option, the other two start with argv[0].
2699 unsigned int new_exec_argc = 0;
2700 unsigned int new_v8_argc = 1;
2701 unsigned int new_argc = 1;
2702 new_v8_argv[0] = argv[0];
2703 new_argv[0] = argv[0];
2705 unsigned int index = 1;
2706 while (index < nargs && argv[index][0] == '-') {
2707 const char* const arg = argv[index];
2708 unsigned int args_consumed = 1;
2710 if (strstr(arg, "--debug") == arg) {
2712 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2713 printf("%s\n", NODE_VERSION);
2715 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2718 } else if (strcmp(arg, "--eval") == 0 ||
2719 strcmp(arg, "-e") == 0 ||
2720 strcmp(arg, "--print") == 0 ||
2721 strcmp(arg, "-pe") == 0 ||
2722 strcmp(arg, "-p") == 0) {
2723 bool is_eval = strchr(arg, 'e') != NULL;
2724 bool is_print = strchr(arg, 'p') != NULL;
2725 print_eval = print_eval || is_print;
2726 // --eval, -e and -pe always require an argument.
2727 if (is_eval == true) {
2729 eval_string = argv[index + 1];
2730 if (eval_string == NULL) {
2731 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
2734 } else if (argv[index + 1] != NULL && argv[index + 1][0] != '-') {
2736 eval_string = argv[index + 1];
2737 if (strncmp(eval_string, "\\-", 2) == 0) {
2738 // Starts with "\\-": escaped expression, drop the backslash.
2742 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2744 } else if (strcmp(arg, "--no-deprecation") == 0) {
2745 no_deprecation = true;
2746 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2747 trace_deprecation = true;
2748 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2749 throw_deprecation = true;
2750 } else if (strcmp(arg, "--v8-options") == 0) {
2751 new_v8_argv[new_v8_argc] = "--help";
2754 // V8 option. Pass through as-is.
2755 new_v8_argv[new_v8_argc] = arg;
2759 memcpy(new_exec_argv + new_exec_argc,
2761 args_consumed * sizeof(*argv));
2763 new_exec_argc += args_consumed;
2764 index += args_consumed;
2767 // Copy remaining arguments.
2768 const unsigned int args_left = nargs - index;
2769 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
2770 new_argc += args_left;
2772 *exec_argc = new_exec_argc;
2773 *exec_argv = new_exec_argv;
2774 *v8_argc = new_v8_argc;
2775 *v8_argv = new_v8_argv;
2777 // Copy new_argv over argv and update argc.
2778 memcpy(argv, new_argv, new_argc * sizeof(*argv));
2780 *argc = static_cast<int>(new_argc);
2784 // Called from the main thread.
2785 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2786 v8::Debug::ProcessDebugMessages();
2790 // Called from V8 Debug Agent TCP thread.
2791 static void DispatchMessagesDebugAgentCallback() {
2792 uv_async_send(&dispatch_debug_messages_async);
2796 // Called from the main thread
2797 static void EmitDebugEnabledAsyncCallback(uv_async_t* handle, int status) {
2798 Environment* env = Environment::GetCurrent(node_isolate);
2799 Context::Scope context_scope(env->context());
2800 HandleScope handle_scope(env->isolate());
2801 Local<Object> message = Object::New();
2802 message->Set(FIXED_ONE_BYTE_STRING(node_isolate, "cmd"),
2803 FIXED_ONE_BYTE_STRING(node_isolate, "NODE_DEBUG_ENABLED"));
2804 Local<Value> args[] = {
2805 FIXED_ONE_BYTE_STRING(node_isolate, "internalMessage"),
2808 MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(args), args);
2812 // Called from the signal watcher callback
2813 static void EmitDebugEnabled() {
2814 uv_async_send(&emit_debug_enabled_async);
2818 static void EnableDebug(bool wait_connect) {
2819 // If we're called from another thread, make sure to enter the right
2821 node_isolate->Enter();
2823 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2826 // Start the debug thread and it's associated TCP server on port 5858.
2827 bool r = v8::Debug::EnableAgent("node " NODE_VERSION,
2831 // Crappy check that everything went well. FIXME
2834 // Print out some information.
2835 fprintf(stderr, "debugger listening on port %d\n", debug_port);
2838 debugger_running = true;
2840 if (Environment::GetCurrentChecked(node_isolate) != NULL) {
2844 node_isolate->Exit();
2849 static void EnableDebugSignalHandler(uv_signal_t* handle, int) {
2850 // Break once process will return execution to v8
2851 v8::Debug::DebugBreak(node_isolate);
2853 if (!debugger_running) {
2854 fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n");
2860 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2861 struct sigaction sa;
2863 memset(&sa, 0, sizeof(sa));
2864 sa.sa_handler = handler;
2865 sigfillset(&sa.sa_mask);
2866 sigaction(signal, &sa, NULL);
2870 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2871 HandleScope scope(node_isolate);
2873 if (args.Length() != 1) {
2874 return ThrowError("Invalid number of arguments.");
2880 pid = args[0]->IntegerValue();
2881 r = kill(pid, SIGUSR1);
2883 return ThrowErrnoException(errno, "kill");
2890 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2891 // Break once process will return execution to v8
2892 if (!debugger_running) {
2893 for (int i = 0; i < 1; i++) {
2894 fprintf(stderr, "Starting debugger agent.\r\n");
2900 v8::Debug::DebugBreak(node_isolate);
2906 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2908 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2912 static int RegisterDebugSignalHandler() {
2913 wchar_t mapping_name[32];
2914 HANDLE mapping_handle;
2916 LPTHREAD_START_ROUTINE* handler;
2918 pid = GetCurrentProcessId();
2920 if (GetDebugSignalHandlerMappingName(pid,
2922 ARRAY_SIZE(mapping_name)) < 0) {
2926 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2932 if (mapping_handle == NULL) {
2936 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2937 MapViewOfFile(mapping_handle,
2938 FILE_MAP_ALL_ACCESS,
2942 if (handler == NULL) {
2943 CloseHandle(mapping_handle);
2947 *handler = EnableDebugThreadProc;
2949 UnmapViewOfFile(static_cast<void*>(handler));
2955 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2956 HandleScope scope(node_isolate);
2958 HANDLE process = NULL;
2959 HANDLE thread = NULL;
2960 HANDLE mapping = NULL;
2961 wchar_t mapping_name[32];
2962 LPTHREAD_START_ROUTINE* handler = NULL;
2964 if (args.Length() != 1) {
2965 ThrowError("Invalid number of arguments.");
2969 pid = (DWORD) args[0]->IntegerValue();
2971 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2972 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2976 if (process == NULL) {
2977 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2981 if (GetDebugSignalHandlerMappingName(pid,
2983 ARRAY_SIZE(mapping_name)) < 0) {
2984 ThrowErrnoException(errno, "sprintf");
2988 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2989 if (mapping == NULL) {
2990 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
2994 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2995 MapViewOfFile(mapping,
3000 if (handler == NULL || *handler == NULL) {
3001 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
3005 thread = CreateRemoteThread(process,
3012 if (thread == NULL) {
3013 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
3017 // Wait for the thread to terminate
3018 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3019 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
3024 if (process != NULL)
3025 CloseHandle(process);
3027 CloseHandle(thread);
3028 if (handler != NULL)
3029 UnmapViewOfFile(handler);
3030 if (mapping != NULL)
3031 CloseHandle(mapping);
3036 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3037 v8::Debug::DebugBreak(node_isolate);
3041 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3042 if (debugger_running) {
3043 v8::Debug::DisableAgent();
3044 debugger_running = false;
3049 void Init(int* argc,
3052 const char*** exec_argv) {
3053 // Initialize prog_start_time to get relative uptime.
3054 uv_uptime(&prog_start_time);
3056 // Make inherited handles noninheritable.
3057 uv_disable_stdio_inheritance();
3059 // init async debug messages dispatching
3060 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3061 uv_async_init(uv_default_loop(),
3062 &dispatch_debug_messages_async,
3063 DispatchDebugMessagesAsyncCallback);
3064 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3066 // init async NODE_DEBUG_ENABLED emitter
3067 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3068 uv_async_init(uv_default_loop(),
3069 &emit_debug_enabled_async,
3070 EmitDebugEnabledAsyncCallback);
3071 uv_unref(reinterpret_cast<uv_handle_t*>(&emit_debug_enabled_async));
3073 // Parse a few arguments which are specific to Node.
3075 const char** v8_argv;
3076 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3078 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3079 // the argv array or the elements it points to.
3080 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3082 // Anything that's still in v8_argv is not a V8 or a node option.
3083 for (int i = 1; i < v8_argc; i++) {
3084 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3093 if (debug_wait_connect) {
3094 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3095 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3098 const char typed_arrays_flag[] = "--harmony_typed_arrays";
3099 V8::SetFlagsFromString(typed_arrays_flag, sizeof(typed_arrays_flag) - 1);
3100 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3102 // Fetch a reference to the main isolate, so we have a reference to it
3103 // even when we need it to access it from another (debugger) thread.
3104 node_isolate = Isolate::GetCurrent();
3107 // Raise the open file descriptor limit.
3110 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3111 // Do a binary search for the limit.
3112 rlim_t min = lim.rlim_cur;
3113 rlim_t max = 1 << 20;
3114 // But if there's a defined upper bound, don't search, just set it.
3115 if (lim.rlim_max != RLIM_INFINITY) {
3120 lim.rlim_cur = min + (max - min) / 2;
3121 if (setrlimit(RLIMIT_NOFILE, &lim)) {
3126 } while (min + 1 < max);
3130 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3131 RegisterSignalHandler(SIGINT, SignalExit);
3132 RegisterSignalHandler(SIGTERM, SignalExit);
3135 V8::SetFatalErrorHandler(node::OnFatalError);
3136 V8::AddMessageListener(OnMessage);
3138 // If the --debug flag was specified then initialize the debug thread.
3139 if (use_debug_agent) {
3140 EnableDebug(debug_wait_connect);
3143 RegisterDebugSignalHandler();
3145 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3146 static uv_signal_t signal_watcher;
3147 uv_signal_init(uv_default_loop(), &signal_watcher);
3148 uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1);
3149 uv_unref(reinterpret_cast<uv_handle_t*>(&signal_watcher));
3155 struct AtExitCallback {
3156 AtExitCallback* next_;
3157 void (*cb_)(void* arg);
3161 static AtExitCallback* at_exit_functions_;
3164 // TODO(bnoordhuis) Turn into per-context event.
3165 void RunAtExit(Environment* env) {
3166 AtExitCallback* p = at_exit_functions_;
3167 at_exit_functions_ = NULL;
3170 AtExitCallback* q = p->next_;
3178 void AtExit(void (*cb)(void* arg), void* arg) {
3179 AtExitCallback* p = new AtExitCallback;
3182 p->next_ = at_exit_functions_;
3183 at_exit_functions_ = p;
3187 void EmitExit(Environment* env) {
3188 // process.emit('exit')
3189 Context::Scope context_scope(env->context());
3190 HandleScope handle_scope(env->isolate());
3191 Local<Object> process_object = env->process_object();
3192 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3193 True(node_isolate));
3195 Handle<String> exitCode = FIXED_ONE_BYTE_STRING(node_isolate, "exitCode");
3196 int code = process_object->Get(exitCode)->IntegerValue();
3198 Local<Value> args[] = {
3199 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3200 Integer::New(code, node_isolate)
3203 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3208 Environment* CreateEnvironment(Isolate* isolate,
3210 const char* const* argv,
3212 const char* const* exec_argv) {
3213 HandleScope handle_scope(isolate);
3215 Local<Context> context = Context::New(isolate);
3216 Context::Scope context_scope(context);
3217 Environment* env = Environment::New(context);
3219 uv_check_init(env->event_loop(), env->immediate_check_handle());
3221 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3222 uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3224 Local<FunctionTemplate> process_template = FunctionTemplate::New();
3225 process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3227 Local<Object> process_object = process_template->GetFunction()->NewInstance();
3228 env->set_process_object(process_object);
3230 SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3237 int Start(int argc, char** argv) {
3240 // Hack around with the argv pointer. Used for process.title = "blah".
3241 argv = uv_setup_args(argc, argv);
3243 // This needs to run *before* V8::Initialize(). The const_cast is not
3244 // optional, in case you're wondering.
3246 const char** exec_argv;
3247 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3250 // V8 on Windows doesn't have a good source of entropy. Seed it from
3252 V8::SetEntropySource(crypto::EntropySource);
3257 Locker locker(node_isolate);
3259 CreateEnvironment(node_isolate, argc, argv, exec_argc, exec_argv);
3260 Context::Scope context_scope(env->context());
3261 HandleScope handle_scope(env->isolate());
3262 uv_run(env->event_loop(), UV_RUN_DEFAULT);
3270 // Clean up. Not strictly necessary.