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_script.h"
29 #include "node_version.h"
31 #if defined HAVE_PERFCTR
32 #include "node_counters.h"
36 #include "node_crypto.h"
39 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
40 #include "node_dtrace.h"
44 #include "node_provider.h"
48 #include "handle_wrap.h"
50 #include "string_bytes.h"
57 #include <limits.h> // PATH_MAX
63 #include <sys/types.h>
69 #define strcasecmp _stricmp
70 #define getpid _getpid
74 #include <unistd.h> // setuid, getuid
77 #if defined(__POSIX__) && !defined(__ANDROID__)
78 #include <pwd.h> // getpwnam()
79 #include <grp.h> // getgrnam()
83 #include <crt_externs.h>
84 #define environ (*_NSGetEnviron())
85 #elif !defined(_MSC_VER)
86 extern char **environ;
92 using v8::ArrayBuffer;
97 using v8::FunctionCallbackInfo;
98 using v8::FunctionTemplate;
100 using v8::HandleScope;
101 using v8::HeapStatistics;
109 using v8::ObjectTemplate;
110 using v8::Persistent;
111 using v8::PropertyCallbackInfo;
112 using v8::ResourceConstraints;
113 using v8::SetResourceConstraints;
115 using v8::ThrowException;
120 using v8::kExternalUnsignedIntArray;
122 QUEUE handle_wrap_queue = { &handle_wrap_queue, &handle_wrap_queue };
123 QUEUE req_wrap_queue = { &req_wrap_queue, &req_wrap_queue };
125 // declared in req_wrap.h
126 Cached<String> process_symbol;
127 Cached<String> domain_symbol;
129 // declared in node_internals.h
130 Persistent<Object> process_p;
132 static Persistent<Function> process_tickCallback;
133 static Persistent<Object> binding_cache;
134 static Persistent<Array> module_load_list;
136 static Cached<String> exports_symbol;
138 static Cached<String> errno_symbol;
139 static Cached<String> syscall_symbol;
140 static Cached<String> errpath_symbol;
141 static Cached<String> code_symbol;
143 static Cached<String> rss_symbol;
144 static Cached<String> heap_total_symbol;
145 static Cached<String> heap_used_symbol;
147 static Cached<String> fatal_exception_symbol;
149 static Cached<String> enter_symbol;
150 static Cached<String> exit_symbol;
151 static Cached<String> disposed_symbol;
153 // Essential for node_wrap.h
154 Persistent<FunctionTemplate> pipeConstructorTmpl;
155 Persistent<FunctionTemplate> tcpConstructorTmpl;
156 Persistent<FunctionTemplate> ttyConstructorTmpl;
158 static bool print_eval = false;
159 static bool force_repl = false;
160 static bool trace_deprecation = false;
161 static bool throw_deprecation = false;
162 static char *eval_string = NULL;
163 static int option_end_index = 0;
164 static bool use_debug_agent = false;
165 static bool debug_wait_connect = false;
166 static int debug_port = 5858;
167 static int max_stack_size = 0;
168 bool using_domains = false;
170 // used by C++ modules as well
171 bool no_deprecation = false;
173 static uv_check_t check_immediate_watcher;
174 static uv_idle_t idle_immediate_dummy;
175 static bool need_immediate_cb;
176 static Cached<String> immediate_callback_sym;
178 // for quick ref to tickCallback values
186 #ifdef OPENSSL_NPN_NEGOTIATED
187 static bool use_npn = true;
189 static bool use_npn = false;
192 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
193 static bool use_sni = true;
195 static bool use_sni = false;
198 // process-relative uptime base, initialized at start-up
199 static double prog_start_time;
201 static volatile bool debugger_running = false;
202 static uv_async_t dispatch_debug_messages_async;
203 static uv_async_t emit_debug_enabled_async;
205 // Declared in node_internals.h
206 Isolate* node_isolate = NULL;
209 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
211 // Impose an upper limit to avoid out of memory errors that bring down
213 static const size_t kMaxLength = 0x3fffffff;
214 static ArrayBufferAllocator the_singleton;
215 virtual ~ArrayBufferAllocator() {}
216 virtual void* Allocate(size_t length);
217 virtual void Free(void* data);
219 ArrayBufferAllocator() {}
220 ArrayBufferAllocator(const ArrayBufferAllocator&);
221 void operator=(const ArrayBufferAllocator&);
224 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
227 void* ArrayBufferAllocator::Allocate(size_t length) {
228 if (length > kMaxLength) return NULL;
229 return new char[length];
233 void ArrayBufferAllocator::Free(void* data) {
234 delete[] static_cast<char*>(data);
238 static void CheckImmediate(uv_check_t* handle, int status) {
239 assert(handle == &check_immediate_watcher);
242 HandleScope scope(node_isolate);
244 if (immediate_callback_sym.IsEmpty()) {
245 immediate_callback_sym =
246 FIXED_ONE_BYTE_STRING(node_isolate, "_immediateCallback");
249 MakeCallback(process_p, immediate_callback_sym, 0, NULL);
253 static void IdleImmediateDummy(uv_idle_t* handle, int status) {
254 // Do nothing. Only for maintaining event loop
255 assert(handle == &idle_immediate_dummy);
260 static inline const char *errno_string(int errorno) {
261 #define ERRNO_CASE(e) case e: return #e;
268 ERRNO_CASE(EADDRINUSE);
272 ERRNO_CASE(EADDRNOTAVAIL);
276 ERRNO_CASE(EAFNOSUPPORT);
284 # if EAGAIN != EWOULDBLOCK
285 ERRNO_CASE(EWOULDBLOCK);
290 ERRNO_CASE(EALREADY);
306 ERRNO_CASE(ECANCELED);
314 ERRNO_CASE(ECONNABORTED);
318 ERRNO_CASE(ECONNREFUSED);
322 ERRNO_CASE(ECONNRESET);
330 ERRNO_CASE(EDESTADDRREQ);
354 ERRNO_CASE(EHOSTUNREACH);
366 ERRNO_CASE(EINPROGRESS);
402 ERRNO_CASE(EMSGSIZE);
406 ERRNO_CASE(EMULTIHOP);
410 ERRNO_CASE(ENAMETOOLONG);
414 ERRNO_CASE(ENETDOWN);
418 ERRNO_CASE(ENETRESET);
422 ERRNO_CASE(ENETUNREACH);
454 # if ENOLINK != ENOLCK
468 ERRNO_CASE(ENOPROTOOPT);
488 ERRNO_CASE(ENOTCONN);
496 ERRNO_CASE(ENOTEMPTY);
500 ERRNO_CASE(ENOTSOCK);
507 ERRNO_CASE(EOPNOTSUPP);
521 ERRNO_CASE(EOVERFLOW);
536 #ifdef EPROTONOSUPPORT
537 ERRNO_CASE(EPROTONOSUPPORT);
541 ERRNO_CASE(EPROTOTYPE);
569 ERRNO_CASE(ETIMEDOUT);
584 const char *signo_string(int signo) {
585 #define SIGNO_CASE(e) case e: return #e;
612 # if SIGABRT != SIGIOT
656 SIGNO_CASE(SIGSTKFLT);
673 SIGNO_CASE(SIGBREAK);
697 SIGNO_CASE(SIGVTALRM);
705 SIGNO_CASE(SIGWINCH);
713 # if SIGPOLL != SIGIO
723 # if SIGPWR != SIGLOST
737 Local<Value> ErrnoException(int errorno,
742 Local<String> estring = OneByteString(node_isolate, errno_string(errorno));
743 if (msg == NULL || msg[0] == '\0') {
744 msg = strerror(errorno);
746 Local<String> message = OneByteString(node_isolate, msg);
748 Local<String> cons1 =
749 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
750 Local<String> cons2 = String::Concat(cons1, message);
752 if (syscall_symbol.IsEmpty()) {
753 syscall_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "syscall");
754 errno_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "errno");
755 errpath_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "path");
756 code_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "code");
760 Local<String> cons3 =
761 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
762 Local<String> cons4 =
763 String::Concat(cons3, String::NewFromUtf8(node_isolate, path));
764 Local<String> cons5 =
765 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
766 e = Exception::Error(cons5);
768 e = Exception::Error(cons2);
771 Local<Object> obj = e->ToObject();
773 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
774 obj->Set(code_symbol, estring);
775 if (path) obj->Set(errpath_symbol, String::NewFromUtf8(node_isolate, path));
776 if (syscall) obj->Set(syscall_symbol, OneByteString(node_isolate, syscall));
781 // hack alert! copy of ErrnoException, tuned for uv errors
782 Local<Value> UVException(int errorno,
786 if (syscall_symbol.IsEmpty()) {
787 syscall_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "syscall");
788 errno_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "errno");
789 errpath_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "path");
790 code_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "code");
794 msg = uv_strerror(errorno);
796 Local<String> estring = OneByteString(node_isolate, uv_err_name(errorno));
797 Local<String> message = OneByteString(node_isolate, msg);
798 Local<String> cons1 =
799 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
800 Local<String> cons2 = String::Concat(cons1, message);
804 Local<String> path_str;
808 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
809 path_str = String::Concat(FIXED_ONE_BYTE_STRING(node_isolate, "\\\\"),
810 String::NewFromUtf8(node_isolate, path + 8));
811 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
812 path_str = String::NewFromUtf8(node_isolate, path + 4);
814 path_str = String::NewFromUtf8(node_isolate, path);
817 path_str = String::NewFromUtf8(node_isolate, path);
820 Local<String> cons3 =
821 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
822 Local<String> cons4 =
823 String::Concat(cons3, path_str);
824 Local<String> cons5 =
825 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
826 e = Exception::Error(cons5);
828 e = Exception::Error(cons2);
831 Local<Object> obj = e->ToObject();
833 // TODO(piscisaureus) errno should probably go
834 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
835 obj->Set(code_symbol, estring);
836 if (path) obj->Set(errpath_symbol, path_str);
837 if (syscall) obj->Set(syscall_symbol, OneByteString(node_isolate, syscall));
843 // Does about the same as strerror(),
844 // but supports all windows error messages
845 static const char *winapi_strerror(const int errorno) {
848 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
849 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
850 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
853 // Remove trailing newlines
854 for (int i = strlen(errmsg) - 1;
855 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
861 // FormatMessage failed
862 return "Unknown error";
867 Local<Value> WinapiErrnoException(int errorno,
872 if (!msg || !msg[0]) {
873 msg = winapi_strerror(errorno);
875 Local<String> message = OneByteString(node_isolate, msg);
877 if (syscall_symbol.IsEmpty()) {
878 syscall_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "syscall");
879 errno_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "errno");
880 errpath_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "path");
881 code_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "code");
885 Local<String> cons1 =
886 String::Concat(message, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
887 Local<String> cons2 =
888 String::Concat(cons1, String::NewFromUtf8(node_isolate, path));
889 Local<String> cons3 =
890 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
891 e = Exception::Error(cons3);
893 e = Exception::Error(message);
896 Local<Object> obj = e->ToObject();
898 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
899 if (path) obj->Set(errpath_symbol, String::NewFromUtf8(node_isolate, path));
900 if (syscall) obj->Set(syscall_symbol, OneByteString(node_isolate, syscall));
906 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
907 if (using_domains) return;
908 HandleScope scope(node_isolate);
909 using_domains = true;
910 Local<Object> process = PersistentToLocal(node_isolate, process_p);
912 process->Get(FIXED_ONE_BYTE_STRING(node_isolate, "_tickDomainCallback"));
914 process->Get(FIXED_ONE_BYTE_STRING(node_isolate, "_nextDomainTick"));
915 if (!tdc_v->IsFunction()) {
916 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
919 if (!ndt_v->IsFunction()) {
920 fprintf(stderr, "process._nextDomainTick assigned to non-function\n");
923 Local<Function> tdc = tdc_v.As<Function>();
924 Local<Function> ndt = ndt_v.As<Function>();
925 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"), tdc);
926 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "nextTick"), ndt);
927 process_tickCallback.Reset(node_isolate, tdc);
932 MakeDomainCallback(const Handle<Object> object,
933 const Handle<Function> callback,
935 Handle<Value> argv[]) {
936 // TODO(trevnorris) Hook for long stack traces to be made here.
938 // lazy load domain specific symbols
939 if (enter_symbol.IsEmpty()) {
940 enter_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "enter");
941 exit_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "exit");
942 disposed_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "_disposed");
945 Local<Value> domain_v = object->Get(domain_symbol);
946 Local<Object> domain;
947 Local<Function> enter;
948 Local<Function> exit;
951 try_catch.SetVerbose(true);
953 bool has_domain = domain_v->IsObject();
955 domain = domain_v->ToObject();
956 assert(!domain.IsEmpty());
957 if (domain->Get(disposed_symbol)->IsTrue()) {
958 // domain has been disposed of.
959 return Undefined(node_isolate);
961 enter = Local<Function>::Cast(domain->Get(enter_symbol));
962 assert(!enter.IsEmpty());
963 enter->Call(domain, 0, NULL);
965 if (try_catch.HasCaught()) {
966 return Undefined(node_isolate);
970 Local<Value> ret = callback->Call(object, argc, argv);
972 if (try_catch.HasCaught()) {
973 return Undefined(node_isolate);
977 exit = Local<Function>::Cast(domain->Get(exit_symbol));
978 assert(!exit.IsEmpty());
979 exit->Call(domain, 0, NULL);
981 if (try_catch.HasCaught()) {
982 return Undefined(node_isolate);
986 if (tick_infobox.last_threw == 1) {
987 tick_infobox.last_threw = 0;
991 if (tick_infobox.in_tick == 1) {
995 if (tick_infobox.length == 0) {
996 tick_infobox.index = 0;
1000 // process nextTicks after call
1001 Local<Object> process = PersistentToLocal(node_isolate, process_p);
1002 Local<Function> fn = PersistentToLocal(node_isolate, process_tickCallback);
1003 fn->Call(process, 0, NULL);
1005 if (try_catch.HasCaught()) {
1006 return Undefined(node_isolate);
1014 MakeCallback(const Handle<Object> object,
1015 const Handle<Function> callback,
1017 Handle<Value> argv[]) {
1018 // TODO(trevnorris) Hook for long stack traces to be made here.
1019 Local<Object> process = PersistentToLocal(node_isolate, process_p);
1022 return MakeDomainCallback(object, callback, argc, argv);
1024 // lazy load no domain next tick callbacks
1025 if (process_tickCallback.IsEmpty()) {
1027 process->Get(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"));
1028 if (!cb_v->IsFunction()) {
1029 fprintf(stderr, "process._tickCallback assigned to non-function\n");
1032 process_tickCallback.Reset(node_isolate, cb_v.As<Function>());
1036 try_catch.SetVerbose(true);
1038 Local<Value> ret = callback->Call(object, argc, argv);
1040 if (try_catch.HasCaught()) {
1041 return Undefined(node_isolate);
1044 if (tick_infobox.in_tick == 1) {
1048 if (tick_infobox.length == 0) {
1049 tick_infobox.index = 0;
1053 // process nextTicks after call
1054 Local<Function> fn = PersistentToLocal(node_isolate, process_tickCallback);
1055 fn->Call(process, 0, NULL);
1057 if (try_catch.HasCaught()) {
1058 return Undefined(node_isolate);
1066 MakeCallback(const Handle<Object> object,
1067 const Handle<String> symbol,
1069 Handle<Value> argv[]) {
1070 HandleScope scope(node_isolate);
1072 Local<Function> callback = object->Get(symbol).As<Function>();
1073 assert(callback->IsFunction());
1076 return scope.Close(MakeDomainCallback(object, callback, argc, argv));
1077 return scope.Close(MakeCallback(object, callback, argc, argv));
1082 MakeCallback(const Handle<Object> object,
1085 Handle<Value> argv[]) {
1086 HandleScope scope(node_isolate);
1088 Local<String> method_string = OneByteString(node_isolate, method);
1089 Handle<Value> ret = MakeCallback(object, method_string, argc, argv);
1091 return scope.Close(ret);
1095 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1096 HandleScope scope(node_isolate);
1098 if (!encoding_v->IsString()) return _default;
1100 String::Utf8Value encoding(encoding_v);
1102 if (strcasecmp(*encoding, "utf8") == 0) {
1104 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1106 } else if (strcasecmp(*encoding, "ascii") == 0) {
1108 } else if (strcasecmp(*encoding, "base64") == 0) {
1110 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1112 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1114 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1116 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1118 } else if (strcasecmp(*encoding, "binary") == 0) {
1120 } else if (strcasecmp(*encoding, "buffer") == 0) {
1122 } else if (strcasecmp(*encoding, "hex") == 0) {
1124 } else if (strcasecmp(*encoding, "raw") == 0) {
1125 if (!no_deprecation) {
1126 fprintf(stderr, "'raw' (array of integers) has been removed. "
1130 } else if (strcasecmp(*encoding, "raws") == 0) {
1131 if (!no_deprecation) {
1132 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1133 "Please update your code.\n");
1141 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1142 return StringBytes::Encode(static_cast<const char*>(buf),
1147 // Returns -1 if the handle was not valid for decoding
1148 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1149 HandleScope scope(node_isolate);
1151 if (val->IsArray()) {
1152 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1158 return StringBytes::Size(val, encoding);
1162 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1165 // Returns number of bytes written.
1166 ssize_t DecodeWrite(char *buf,
1168 v8::Handle<v8::Value> val,
1169 enum encoding encoding) {
1170 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1173 void DisplayExceptionLine(Handle<Message> message) {
1174 // Prevent re-entry into this function. For example, if there is
1175 // a throw from a program in vm.runInThisContext(code, filename, true),
1176 // then we want to show the original failure, not the secondary one.
1177 static bool displayed_error = false;
1179 if (displayed_error) return;
1180 displayed_error = true;
1182 uv_tty_reset_mode();
1184 fprintf(stderr, "\n");
1186 if (!message.IsEmpty()) {
1187 // Print (filename):(line number): (message).
1188 String::Utf8Value filename(message->GetScriptResourceName());
1189 const char* filename_string = *filename;
1190 int linenum = message->GetLineNumber();
1191 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1192 // Print line of source code.
1193 String::Utf8Value sourceline(message->GetSourceLine());
1194 const char* sourceline_string = *sourceline;
1196 // Because of how node modules work, all scripts are wrapped with a
1197 // "function (module, exports, __filename, ...) {"
1198 // to provide script local variables.
1200 // When reporting errors on the first line of a script, this wrapper
1201 // function is leaked to the user. There used to be a hack here to
1202 // truncate off the first 62 characters, but it caused numerous other
1203 // problems when vm.runIn*Context() methods were used for non-module
1206 // If we ever decide to re-instate such a hack, the following steps
1209 // 1. Pass a flag around to say "this code was wrapped"
1210 // 2. Update the stack frame output so that it is also correct.
1212 // It would probably be simpler to add a line rather than add some
1213 // number of characters to the first line, since V8 truncates the
1214 // sourceline to 78 characters, and we end up not providing very much
1215 // useful debugging info to the user if we remove 62 characters.
1217 int start = message->GetStartColumn();
1218 int end = message->GetEndColumn();
1220 fprintf(stderr, "%s\n", sourceline_string);
1221 // Print wavy underline (GetUnderline is deprecated).
1222 for (int i = 0; i < start; i++) {
1223 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1225 for (int i = start; i < end; i++) {
1228 fputc('\n', stderr);
1233 static void ReportException(Handle<Value> er, Handle<Message> message) {
1234 HandleScope scope(node_isolate);
1236 DisplayExceptionLine(message);
1238 Local<Value> trace_value(
1239 er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack")));
1240 String::Utf8Value trace(trace_value);
1242 // range errors have a trace member set to undefined
1243 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1244 fprintf(stderr, "%s\n", *trace);
1246 // this really only happens for RangeErrors, since they're the only
1247 // kind that won't have all this info in the trace, or when non-Error
1248 // objects are thrown manually.
1249 Local<Value> message;
1252 if (er->IsObject()) {
1253 Local<Object> err_obj = er.As<Object>();
1254 message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1255 name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1258 if (message.IsEmpty() ||
1259 message->IsUndefined() ||
1261 name->IsUndefined()) {
1262 // Not an error object. Just print as-is.
1263 String::Utf8Value message(er);
1264 fprintf(stderr, "%s\n", *message);
1266 String::Utf8Value name_string(name);
1267 String::Utf8Value message_string(message);
1268 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1276 static void ReportException(const TryCatch& try_catch) {
1277 ReportException(try_catch.Exception(), try_catch.Message());
1281 // Executes a str within the current v8 context.
1282 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1283 HandleScope scope(node_isolate);
1286 // try_catch must be nonverbose to disable FatalException() handler,
1287 // we will handle exceptions ourself.
1288 try_catch.SetVerbose(false);
1290 Local<v8::Script> script = v8::Script::Compile(source, filename);
1291 if (script.IsEmpty()) {
1292 ReportException(try_catch);
1296 Local<Value> result = script->Run();
1297 if (result.IsEmpty()) {
1298 ReportException(try_catch);
1302 return scope.Close(result);
1306 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1307 HandleScope scope(node_isolate);
1309 Local<Array> ary = Array::New();
1313 QUEUE_FOREACH(q, &req_wrap_queue) {
1314 ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1315 if (w->persistent().IsEmpty()) continue;
1316 ary->Set(i++, w->object());
1319 args.GetReturnValue().Set(ary);
1323 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1324 // implemented here for consistency with GetActiveRequests().
1325 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1326 HandleScope scope(node_isolate);
1328 Local<Array> ary = Array::New();
1332 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1334 QUEUE_FOREACH(q, &handle_wrap_queue) {
1335 HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1336 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue;
1337 Local<Object> object = w->object();
1338 Local<Value> owner = object->Get(owner_sym);
1339 if (owner->IsUndefined()) owner = object;
1340 ary->Set(i++, owner);
1343 args.GetReturnValue().Set(ary);
1347 static void Abort(const FunctionCallbackInfo<Value>& args) {
1352 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1353 HandleScope scope(node_isolate);
1355 if (args.Length() != 1 || !args[0]->IsString()) {
1356 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1359 String::Utf8Value path(args[0]);
1360 int err = uv_chdir(*path);
1362 return ThrowUVException(err, "uv_chdir");
1367 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1368 HandleScope scope(node_isolate);
1370 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1371 char buf[MAX_PATH * 4 + 1];
1373 char buf[PATH_MAX + 1];
1376 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1378 return ThrowUVException(err, "uv_cwd");
1381 buf[ARRAY_SIZE(buf) - 1] = '\0';
1382 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1384 args.GetReturnValue().Set(cwd);
1388 static void Umask(const FunctionCallbackInfo<Value>& args) {
1389 HandleScope scope(node_isolate);
1392 if (args.Length() < 1 || args[0]->IsUndefined()) {
1394 umask(static_cast<mode_t>(old));
1395 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1396 return ThrowTypeError("argument must be an integer or octal string.");
1399 if (args[0]->IsInt32()) {
1400 oct = args[0]->Uint32Value();
1403 String::Utf8Value str(args[0]);
1405 // Parse the octal string.
1406 for (int i = 0; i < str.length(); i++) {
1408 if (c > '7' || c < '0') {
1409 return ThrowTypeError("invalid octal string");
1415 old = umask(static_cast<mode_t>(oct));
1418 args.GetReturnValue().Set(old);
1422 #if defined(__POSIX__) && !defined(__ANDROID__)
1424 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1425 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1428 static uid_t uid_by_name(const char* name) {
1436 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1440 return uid_not_found;
1444 static char* name_by_uid(uid_t uid) {
1453 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1454 return strdup(pp->pw_name);
1465 static gid_t gid_by_name(const char* name) {
1473 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1477 return gid_not_found;
1481 #if 0 // For future use.
1482 static const char* name_by_gid(gid_t gid) {
1491 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1492 return strdup(pp->gr_name);
1504 static uid_t uid_by_name(Handle<Value> value) {
1505 if (value->IsUint32()) {
1506 return static_cast<uid_t>(value->Uint32Value());
1508 String::Utf8Value name(value);
1509 return uid_by_name(*name);
1514 static gid_t gid_by_name(Handle<Value> value) {
1515 if (value->IsUint32()) {
1516 return static_cast<gid_t>(value->Uint32Value());
1518 String::Utf8Value name(value);
1519 return gid_by_name(*name);
1524 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1525 args.GetReturnValue().Set(getuid());
1529 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1530 args.GetReturnValue().Set(getgid());
1534 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1535 HandleScope scope(node_isolate);
1537 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1538 return ThrowTypeError("setgid argument must be a number or a string");
1541 gid_t gid = gid_by_name(args[0]);
1543 if (gid == gid_not_found) {
1544 return ThrowError("setgid group id does not exist");
1548 return ThrowErrnoException(errno, "setgid");
1553 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1554 HandleScope scope(node_isolate);
1556 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1557 return ThrowTypeError("setuid argument must be a number or a string");
1560 uid_t uid = uid_by_name(args[0]);
1562 if (uid == uid_not_found) {
1563 return ThrowError("setuid user id does not exist");
1567 return ThrowErrnoException(errno, "setuid");
1572 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1573 HandleScope scope(node_isolate);
1575 int ngroups = getgroups(0, NULL);
1577 if (ngroups == -1) {
1578 return ThrowErrnoException(errno, "getgroups");
1581 gid_t* groups = new gid_t[ngroups];
1583 ngroups = getgroups(ngroups, groups);
1585 if (ngroups == -1) {
1587 return ThrowErrnoException(errno, "getgroups");
1590 Local<Array> groups_list = Array::New(ngroups);
1591 bool seen_egid = false;
1592 gid_t egid = getegid();
1594 for (int i = 0; i < ngroups; i++) {
1595 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1596 if (groups[i] == egid) seen_egid = true;
1601 if (seen_egid == false) {
1602 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1605 args.GetReturnValue().Set(groups_list);
1609 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1610 HandleScope scope(node_isolate);
1612 if (!args[0]->IsArray()) {
1613 return ThrowTypeError("argument 1 must be an array");
1616 Local<Array> groups_list = args[0].As<Array>();
1617 size_t size = groups_list->Length();
1618 gid_t* groups = new gid_t[size];
1620 for (size_t i = 0; i < size; i++) {
1621 gid_t gid = gid_by_name(groups_list->Get(i));
1623 if (gid == gid_not_found) {
1625 return ThrowError("group name not found");
1631 int rc = setgroups(size, groups);
1635 return ThrowErrnoException(errno, "setgroups");
1640 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1641 HandleScope scope(node_isolate);
1643 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1644 return ThrowTypeError("argument 1 must be a number or a string");
1647 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1648 return ThrowTypeError("argument 2 must be a number or a string");
1651 String::Utf8Value arg0(args[0]);
1656 if (args[0]->IsUint32()) {
1657 user = name_by_uid(args[0]->Uint32Value());
1665 return ThrowError("initgroups user not found");
1668 extra_group = gid_by_name(args[1]);
1670 if (extra_group == gid_not_found) {
1671 if (must_free) free(user);
1672 return ThrowError("initgroups extra group not found");
1675 int rc = initgroups(user, extra_group);
1682 return ThrowErrnoException(errno, "initgroups");
1686 #endif // __POSIX__ && !defined(__ANDROID__)
1689 void Exit(const FunctionCallbackInfo<Value>& args) {
1690 HandleScope scope(node_isolate);
1691 exit(args[0]->IntegerValue());
1695 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1696 HandleScope scope(node_isolate);
1698 if (uv_uptime(&uptime)) return;
1699 args.GetReturnValue().Set(uptime - prog_start_time);
1703 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1704 HandleScope scope(node_isolate);
1708 int err = uv_resident_set_memory(&rss);
1710 return ThrowUVException(err, "uv_resident_set_memory");
1713 Local<Object> info = Object::New();
1715 if (rss_symbol.IsEmpty()) {
1716 rss_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "rss");
1717 heap_total_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "heapTotal");
1718 heap_used_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "heapUsed");
1721 info->Set(rss_symbol, Number::New(rss));
1724 HeapStatistics v8_heap_stats;
1725 node_isolate->GetHeapStatistics(&v8_heap_stats);
1726 info->Set(heap_total_symbol,
1727 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(),
1729 info->Set(heap_used_symbol,
1730 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(),
1733 args.GetReturnValue().Set(info);
1737 void Kill(const FunctionCallbackInfo<Value>& args) {
1738 HandleScope scope(node_isolate);
1740 if (args.Length() != 2) {
1741 return ThrowError("Bad argument.");
1744 int pid = args[0]->IntegerValue();
1745 int sig = args[1]->Int32Value();
1746 int err = uv_kill(pid, sig);
1747 args.GetReturnValue().Set(err);
1750 // used in Hrtime() below
1751 #define NANOS_PER_SEC 1000000000
1753 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1754 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1755 // so this function instead returns an Array with 2 entries representing seconds
1756 // and nanoseconds, to avoid any integer overflow possibility.
1757 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1758 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1759 HandleScope scope(node_isolate);
1761 uint64_t t = uv_hrtime();
1763 if (args.Length() > 0) {
1764 // return a time diff tuple
1765 if (!args[0]->IsArray()) {
1766 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1768 Local<Array> inArray = Local<Array>::Cast(args[0]);
1769 uint64_t seconds = inArray->Get(0)->Uint32Value();
1770 uint64_t nanos = inArray->Get(1)->Uint32Value();
1771 t -= (seconds * NANOS_PER_SEC) + nanos;
1774 Local<Array> tuple = Array::New(2);
1775 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1776 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1777 args.GetReturnValue().Set(tuple);
1781 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1783 // DLOpen is process.dlopen(module, filename).
1784 // Used to load 'module.node' dynamically shared objects.
1785 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1786 HandleScope scope(node_isolate);
1787 char symbol[1024], *base, *pos;
1791 if (args.Length() < 2) {
1792 return ThrowError("process.dlopen takes exactly 2 arguments.");
1795 Local<Object> module = args[0]->ToObject(); // Cast
1796 String::Utf8Value filename(args[1]); // Cast
1798 if (exports_symbol.IsEmpty()) {
1799 exports_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "exports");
1801 Local<Object> exports = module->Get(exports_symbol)->ToObject();
1803 if (uv_dlopen(*filename, &lib)) {
1804 Local<String> errmsg = OneByteString(node_isolate, uv_dlerror(&lib));
1806 // Windows needs to add the filename into the error message
1807 errmsg = String::Concat(errmsg, args[1]->ToString());
1809 ThrowException(Exception::Error(errmsg));
1813 String::Utf8Value path(args[1]);
1816 /* Find the shared library filename within the full path. */
1818 pos = strrchr(base, '/');
1824 pos = strpbrk(base, "\\/:");
1832 /* Strip the .node extension. */
1833 pos = strrchr(base, '.');
1838 /* Add the `_module` suffix to the extension name. */
1839 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1840 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1841 return ThrowError("Out of memory.");
1844 /* Replace dashes with underscores. When loading foo-bar.node,
1845 * look for foo_bar_module, not foo-bar_module.
1847 for (pos = symbol; *pos != '\0'; ++pos) {
1848 if (*pos == '-') *pos = '_';
1851 node_module_struct *mod;
1852 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1854 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1855 return ThrowError(errmsg);
1858 if (mod->version != NODE_MODULE_VERSION) {
1862 "Module version mismatch. Expected %d, got %d.",
1863 NODE_MODULE_VERSION, mod->version);
1864 return ThrowError(errmsg);
1867 // Execute the C++ module
1868 mod->register_func(exports, module);
1870 // Tell coverity that 'handle' should not be freed when we return.
1871 // coverity[leaked_storage]
1875 static void OnFatalError(const char* location, const char* message) {
1877 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1879 fprintf(stderr, "FATAL ERROR: %s\n", message);
1889 NO_RETURN void FatalError(const char* location, const char* message) {
1890 OnFatalError(location, message);
1891 // to supress compiler warning
1896 void FatalException(Handle<Value> error, Handle<Message> message) {
1897 HandleScope scope(node_isolate);
1899 if (fatal_exception_symbol.IsEmpty()) {
1900 fatal_exception_symbol =
1901 FIXED_ONE_BYTE_STRING(node_isolate, "_fatalException");
1904 Local<Object> process = PersistentToLocal(node_isolate, process_p);
1905 Local<Value> fatal_v = process->Get(fatal_exception_symbol);
1907 if (!fatal_v->IsFunction()) {
1908 // failed before the process._fatalException function was added!
1909 // this is probably pretty bad. Nothing to do but report and exit.
1910 ReportException(error, message);
1914 Local<Function> fatal_f = Local<Function>::Cast(fatal_v);
1916 TryCatch fatal_try_catch;
1918 // Do not call FatalException when _fatalException handler throws
1919 fatal_try_catch.SetVerbose(false);
1921 // this will return true if the JS layer handled it, false otherwise
1922 Local<Value> caught = fatal_f->Call(process, 1, &error);
1924 if (fatal_try_catch.HasCaught()) {
1925 // the fatal exception function threw, so we must exit
1926 ReportException(fatal_try_catch);
1930 if (false == caught->BooleanValue()) {
1931 ReportException(error, message);
1937 void FatalException(const TryCatch& try_catch) {
1938 HandleScope scope(node_isolate);
1939 // TODO(bajtos) do not call FatalException if try_catch is verbose
1940 // (requires V8 API to expose getter for try_catch.is_verbose_)
1941 FatalException(try_catch.Exception(), try_catch.Message());
1945 void OnMessage(Handle<Message> message, Handle<Value> error) {
1946 // The current version of V8 sends messages for errors only
1947 // (thus `error` is always set).
1948 FatalException(error, message);
1952 static void Binding(const FunctionCallbackInfo<Value>& args) {
1953 HandleScope scope(node_isolate);
1955 Local<String> module = args[0]->ToString();
1956 String::Utf8Value module_v(module);
1957 node_module_struct* modp;
1959 Local<Object> cache = PersistentToLocal(node_isolate, binding_cache);
1960 Local<Object> exports;
1962 if (cache->Has(module)) {
1963 exports = cache->Get(module)->ToObject();
1964 args.GetReturnValue().Set(exports);
1968 // Append a string to process.moduleLoadList
1970 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
1972 Local<Array> modules = PersistentToLocal(node_isolate, module_load_list);
1973 uint32_t l = modules->Length();
1974 modules->Set(l, OneByteString(node_isolate, buf));
1976 if ((modp = get_builtin_module(*module_v)) != NULL) {
1977 exports = Object::New();
1978 // Internal bindings don't have a "module" object,
1980 modp->register_func(exports, Undefined(node_isolate));
1981 cache->Set(module, exports);
1982 } else if (!strcmp(*module_v, "constants")) {
1983 exports = Object::New();
1984 DefineConstants(exports);
1985 cache->Set(module, exports);
1986 } else if (!strcmp(*module_v, "natives")) {
1987 exports = Object::New();
1988 DefineJavaScript(exports);
1989 cache->Set(module, exports);
1991 return ThrowError("No such module");
1994 args.GetReturnValue().Set(exports);
1998 static void ProcessTitleGetter(Local<String> property,
1999 const PropertyCallbackInfo<Value>& info) {
2000 HandleScope scope(node_isolate);
2002 uv_get_process_title(buffer, sizeof(buffer));
2003 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2007 static void ProcessTitleSetter(Local<String> property,
2009 const PropertyCallbackInfo<void>& info) {
2010 HandleScope scope(node_isolate);
2011 String::Utf8Value title(value);
2012 // TODO(piscisaureus): protect with a lock
2013 uv_set_process_title(*title);
2017 static void EnvGetter(Local<String> property,
2018 const PropertyCallbackInfo<Value>& info) {
2019 HandleScope scope(node_isolate);
2021 String::Utf8Value key(property);
2022 const char* val = getenv(*key);
2024 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2027 String::Value key(property);
2028 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2029 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2031 ARRAY_SIZE(buffer));
2032 // If result >= sizeof buffer the buffer was too small. That should never
2033 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2035 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2036 result < ARRAY_SIZE(buffer)) {
2037 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2038 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2039 return info.GetReturnValue().Set(rc);
2042 // Not found. Fetch from prototype.
2043 info.GetReturnValue().Set(
2044 info.Data().As<Object>()->Get(property));
2048 static void EnvSetter(Local<String> property,
2050 const PropertyCallbackInfo<Value>& info) {
2051 HandleScope scope(node_isolate);
2053 String::Utf8Value key(property);
2054 String::Utf8Value val(value);
2055 setenv(*key, *val, 1);
2057 String::Value key(property);
2058 String::Value val(value);
2059 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2060 // Environment variables that start with '=' are read-only.
2061 if (key_ptr[0] != L'=') {
2062 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2065 // Whether it worked or not, always return rval.
2066 info.GetReturnValue().Set(value);
2070 static void EnvQuery(Local<String> property,
2071 const PropertyCallbackInfo<Integer>& info) {
2072 HandleScope scope(node_isolate);
2073 int32_t rc = -1; // Not found unless proven otherwise.
2075 String::Utf8Value key(property);
2076 if (getenv(*key)) rc = 0;
2078 String::Value key(property);
2079 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2080 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2081 GetLastError() == ERROR_SUCCESS) {
2083 if (key_ptr[0] == L'=') {
2084 // Environment variables that start with '=' are hidden and read-only.
2085 rc = static_cast<int32_t>(v8::ReadOnly) |
2086 static_cast<int32_t>(v8::DontDelete) |
2087 static_cast<int32_t>(v8::DontEnum);
2091 if (rc != -1) info.GetReturnValue().Set(rc);
2095 static void EnvDeleter(Local<String> property,
2096 const PropertyCallbackInfo<Boolean>& info) {
2097 HandleScope scope(node_isolate);
2100 String::Utf8Value key(property);
2101 rc = getenv(*key) != NULL;
2102 if (rc) unsetenv(*key);
2104 String::Value key(property);
2105 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2106 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2107 // Deletion failed. Return true if the key wasn't there in the first place,
2108 // false if it is still there.
2109 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2110 GetLastError() != ERROR_SUCCESS;
2113 info.GetReturnValue().Set(rc);
2117 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2118 HandleScope scope(node_isolate);
2121 while (environ[size]) size++;
2123 Local<Array> env = Array::New(size);
2125 for (int i = 0; i < size; ++i) {
2126 const char* var = environ[i];
2127 const char* s = strchr(var, '=');
2128 const int length = s ? s - var : strlen(var);
2129 Local<String> name = String::NewFromUtf8(node_isolate,
2131 String::kNormalString,
2136 WCHAR* environment = GetEnvironmentStringsW();
2137 if (environment == NULL) return; // This should not happen.
2138 Local<Array> env = Array::New();
2139 WCHAR* p = environment;
2141 while (*p != NULL) {
2144 // If the key starts with '=' it is a hidden environment variable.
2148 s = wcschr(p, L'=');
2153 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2154 const size_t two_byte_buffer_len = s - p;
2155 Local<String> value = String::NewFromTwoByte(node_isolate,
2157 String::kNormalString,
2158 two_byte_buffer_len);
2159 env->Set(i++, value);
2160 p = s + wcslen(s) + 1;
2162 FreeEnvironmentStringsW(environment);
2165 info.GetReturnValue().Set(env);
2169 static Handle<Object> GetFeatures() {
2170 HandleScope scope(node_isolate);
2172 Local<Object> obj = Object::New();
2173 #if defined(DEBUG) && DEBUG
2174 Local<Value> debug = True(node_isolate);
2176 Local<Value> debug = False(node_isolate);
2177 #endif // defined(DEBUG) && DEBUG
2179 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2181 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2182 // TODO(bnoordhuis) ping libuv
2183 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2185 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"),
2186 Boolean::New(use_npn));
2187 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"),
2188 Boolean::New(use_sni));
2189 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2190 Boolean::New(get_builtin_module("crypto") != NULL));
2192 return scope.Close(obj);
2196 static void DebugPortGetter(Local<String> property,
2197 const PropertyCallbackInfo<Value>& info) {
2198 HandleScope scope(node_isolate);
2199 info.GetReturnValue().Set(debug_port);
2203 static void DebugPortSetter(Local<String> property,
2205 const PropertyCallbackInfo<void>& info) {
2206 HandleScope scope(node_isolate);
2207 debug_port = value->NumberValue();
2211 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2212 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2213 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2216 void NeedImmediateCallbackGetter(Local<String> property,
2217 const PropertyCallbackInfo<Value>& info) {
2218 info.GetReturnValue().Set(need_immediate_cb);
2222 static void NeedImmediateCallbackSetter(Local<String> property,
2224 const PropertyCallbackInfo<void>&) {
2225 HandleScope scope(node_isolate);
2227 bool bool_value = value->BooleanValue();
2229 if (need_immediate_cb == bool_value) return;
2231 need_immediate_cb = bool_value;
2233 if (need_immediate_cb) {
2234 uv_check_start(&check_immediate_watcher, node::CheckImmediate);
2235 // idle handle is needed only to maintain event loop
2236 uv_idle_start(&idle_immediate_dummy, node::IdleImmediateDummy);
2238 uv_check_stop(&check_immediate_watcher);
2239 uv_idle_stop(&idle_immediate_dummy);
2244 #define READONLY_PROPERTY(obj, str, var) \
2246 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2250 Handle<Object> SetupProcessObject(int argc, char *argv[]) {
2251 HandleScope scope(node_isolate);
2255 Local<FunctionTemplate> process_template = FunctionTemplate::New();
2256 process_template->SetClassName(
2257 FIXED_ONE_BYTE_STRING(node_isolate, "process"));
2259 Local<Object> process = process_template->GetFunction()->NewInstance();
2260 assert(process.IsEmpty() == false);
2261 assert(process->IsObject() == true);
2263 process_p.Reset(node_isolate, process);
2265 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2267 ProcessTitleSetter);
2270 READONLY_PROPERTY(process,
2272 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2274 // process.moduleLoadList
2275 Local<Array> modules = Array::New();
2276 module_load_list.Reset(node_isolate, modules);
2277 READONLY_PROPERTY(process, "moduleLoadList", modules);
2280 Local<Object> versions = Object::New();
2281 READONLY_PROPERTY(process, "versions", versions);
2283 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2285 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2286 READONLY_PROPERTY(versions,
2288 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2290 // +1 to get rid of the leading 'v'
2291 READONLY_PROPERTY(versions,
2293 OneByteString(node_isolate, NODE_VERSION + 1));
2294 READONLY_PROPERTY(versions,
2296 OneByteString(node_isolate, V8::GetVersion()));
2297 READONLY_PROPERTY(versions,
2299 OneByteString(node_isolate, uv_version_string()));
2300 READONLY_PROPERTY(versions,
2302 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2304 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2305 READONLY_PROPERTY(versions,
2307 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2310 // Stupid code to slice out the version string.
2311 int c, l = strlen(OPENSSL_VERSION_TEXT);
2312 for (i = j = 0; i < l; i++) {
2313 c = OPENSSL_VERSION_TEXT[i];
2314 if ('0' <= c && c <= '9') {
2315 for (j = i + 1; j < l; j++) {
2316 c = OPENSSL_VERSION_TEXT[j];
2317 if (c == ' ') break;
2325 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2331 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2334 READONLY_PROPERTY(process,
2336 OneByteString(node_isolate, PLATFORM));
2339 Local<Array> arguments = Array::New(argc - option_end_index + 1);
2340 arguments->Set(0, String::NewFromUtf8(node_isolate, argv[0]));
2341 for (j = 1, i = option_end_index; i < argc; j++, i++) {
2342 arguments->Set(j, String::NewFromUtf8(node_isolate, argv[i]));
2344 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2347 Local<Array> exec_argv = Array::New(option_end_index - 1);
2348 for (j = 1, i = 0; j < option_end_index; j++, i++) {
2349 exec_argv->Set(i, String::NewFromUtf8(node_isolate, argv[j]));
2351 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_argv);
2353 // create process.env
2354 Local<ObjectTemplate> envTemplate = ObjectTemplate::New();
2355 envTemplate->SetNamedPropertyHandler(EnvGetter,
2361 Local<Object> env = envTemplate->NewInstance();
2362 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), env);
2364 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2365 READONLY_PROPERTY(process, "features", GetFeatures());
2366 process->SetAccessor(
2367 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2368 NeedImmediateCallbackGetter,
2369 NeedImmediateCallbackSetter);
2373 READONLY_PROPERTY(process,
2375 String::NewFromUtf8(node_isolate, eval_string));
2380 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2383 // -i, --interactive
2385 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2389 if (no_deprecation) {
2390 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2393 // --throw-deprecation
2394 if (throw_deprecation) {
2395 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2398 // --trace-deprecation
2399 if (trace_deprecation) {
2400 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2403 size_t exec_path_len = 2 * PATH_MAX;
2404 char* exec_path = new char[exec_path_len];
2405 Local<String> exec_path_value;
2406 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2407 exec_path_value = String::NewFromUtf8(node_isolate,
2409 String::kNormalString,
2412 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2414 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2418 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2422 // define various internal methods
2423 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2424 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2425 NODE_SET_METHOD(process, "reallyExit", Exit);
2426 NODE_SET_METHOD(process, "abort", Abort);
2427 NODE_SET_METHOD(process, "chdir", Chdir);
2428 NODE_SET_METHOD(process, "cwd", Cwd);
2430 NODE_SET_METHOD(process, "umask", Umask);
2432 #if defined(__POSIX__) && !defined(__ANDROID__)
2433 NODE_SET_METHOD(process, "getuid", GetUid);
2434 NODE_SET_METHOD(process, "setuid", SetUid);
2436 NODE_SET_METHOD(process, "setgid", SetGid);
2437 NODE_SET_METHOD(process, "getgid", GetGid);
2439 NODE_SET_METHOD(process, "getgroups", GetGroups);
2440 NODE_SET_METHOD(process, "setgroups", SetGroups);
2441 NODE_SET_METHOD(process, "initgroups", InitGroups);
2442 #endif // __POSIX__ && !defined(__ANDROID__)
2444 NODE_SET_METHOD(process, "_kill", Kill);
2446 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2447 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2448 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2450 NODE_SET_METHOD(process, "hrtime", Hrtime);
2452 NODE_SET_METHOD(process, "dlopen", DLOpen);
2454 NODE_SET_METHOD(process, "uptime", Uptime);
2455 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2457 NODE_SET_METHOD(process, "binding", Binding);
2459 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2461 // values use to cross communicate with processNextTick
2462 Local<Object> info_box = Object::New();
2463 info_box->SetIndexedPropertiesToExternalArrayData(&tick_infobox,
2464 kExternalUnsignedIntArray,
2466 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfoBox"), info_box);
2468 // pre-set _events object for faster emit checks
2469 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2471 return scope.Close(process);
2475 #undef READONLY_PROPERTY
2478 static void AtExit() {
2479 uv_tty_reset_mode();
2483 static void SignalExit(int signal) {
2484 uv_tty_reset_mode();
2485 _exit(128 + signal);
2489 void Load(Handle<Object> process_l) {
2490 HandleScope handle_scope(node_isolate);
2492 process_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "process");
2493 domain_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "domain");
2495 // Compile, execute the src/node.js file. (Which was included as static C
2496 // string in node_natives.h. 'natve_node' is the string containing that
2499 // The node.js file returns a function 'f'
2504 // Disable verbose mode to stop FatalException() handler from trying
2505 // to handle the exception. Errors this early in the start-up phase
2506 // are not safe to ignore.
2507 try_catch.SetVerbose(false);
2509 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2510 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2511 if (try_catch.HasCaught()) {
2512 ReportException(try_catch);
2515 assert(f_value->IsFunction());
2516 Local<Function> f = Local<Function>::Cast(f_value);
2518 // Now we call 'f' with the 'process' variable that we've built up with
2519 // all our bindings. Inside node.js we'll take care of assigning things to
2522 // We start the process this way in order to be more modular. Developers
2523 // who do not like how 'src/node.js' setups the module system but do like
2524 // Node's I/O bindings may want to replace 'f' with their own function.
2526 // Add a reference to the global object
2527 Local<Object> global = v8::Context::GetCurrent()->Global();
2529 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2533 #if defined HAVE_PERFCTR
2534 InitPerfCounters(global);
2537 // Enable handling of uncaught exceptions
2538 // (FatalException(), break on uncaught exception in debugger)
2540 // This is not strictly necessary since it's almost impossible
2541 // to attach the debugger fast enought to break on exception
2542 // thrown during process startup.
2543 try_catch.SetVerbose(true);
2545 Local<Value> arg = process_l;
2546 f->Call(global, 1, &arg);
2549 static void PrintHelp();
2551 static void ParseDebugOpt(const char* arg) {
2554 if (strstr(arg, "--debug-port=") == arg) {
2555 p = 1 + strchr(arg, '=');
2556 debug_port = atoi(p);
2558 use_debug_agent = true;
2559 if (!strcmp(arg, "--debug-brk")) {
2560 debug_wait_connect = true;
2562 } else if (!strcmp(arg, "--debug")) {
2564 } else if (strstr(arg, "--debug-brk=") == arg) {
2565 debug_wait_connect = true;
2566 p = 1 + strchr(arg, '=');
2567 debug_port = atoi(p);
2568 } else if (strstr(arg, "--debug=") == arg) {
2569 p = 1 + strchr(arg, '=');
2570 debug_port = atoi(p);
2573 if (p && debug_port > 1024 && debug_port < 65536)
2576 fprintf(stderr, "Bad debug option.\n");
2577 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2583 static void PrintHelp() {
2584 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2585 " node debug script.js [arguments] \n"
2588 " -v, --version print node's version\n"
2589 " -e, --eval script evaluate script\n"
2590 " -p, --print evaluate script and print result\n"
2591 " -i, --interactive always enter the REPL even if stdin\n"
2592 " does not appear to be a terminal\n"
2593 " --no-deprecation silence deprecation warnings\n"
2594 " --trace-deprecation show stack traces on deprecations\n"
2595 " --v8-options print v8 command line options\n"
2596 " --max-stack-size=val set max v8 stack size (bytes)\n"
2598 "Environment variables:\n"
2600 "NODE_PATH ';'-separated list of directories\n"
2602 "NODE_PATH ':'-separated list of directories\n"
2604 " prefixed to the module search path.\n"
2605 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2606 " global contexts.\n"
2607 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2609 "Documentation can be found at http://nodejs.org/\n");
2613 // Parse node command line arguments.
2614 static void ParseArgs(int argc, char **argv) {
2617 // TODO(bnoordhuis) use parse opts
2618 for (i = 1; i < argc; i++) {
2619 const char *arg = argv[i];
2620 if (strstr(arg, "--debug") == arg) {
2622 argv[i] = const_cast<char*>("");
2623 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2624 printf("%s\n", NODE_VERSION);
2626 } else if (strstr(arg, "--max-stack-size=") == arg) {
2628 p = 1 + strchr(arg, '=');
2629 max_stack_size = atoi(p);
2630 argv[i] = const_cast<char*>("");
2631 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2634 } else if (strcmp(arg, "--eval") == 0 ||
2635 strcmp(arg, "-e") == 0 ||
2636 strcmp(arg, "--print") == 0 ||
2637 strcmp(arg, "-pe") == 0 ||
2638 strcmp(arg, "-p") == 0) {
2639 bool is_eval = strchr(arg, 'e') != NULL;
2640 bool is_print = strchr(arg, 'p') != NULL;
2642 // argument to -p and --print is optional
2643 if (is_eval == true && i + 1 >= argc) {
2644 fprintf(stderr, "Error: %s requires an argument\n", arg);
2648 print_eval = print_eval || is_print;
2649 argv[i] = const_cast<char*>("");
2651 // --eval, -e and -pe always require an argument
2652 if (is_eval == true) {
2653 eval_string = argv[++i];
2657 // next arg is the expression to evaluate unless it starts with:
2658 // - a dash, then it's another switch
2659 // - "\\-", then it's an escaped expression, drop the backslash
2660 if (argv[i + 1] == NULL) continue;
2661 if (argv[i + 1][0] == '-') continue;
2662 eval_string = argv[++i];
2663 if (strncmp(eval_string, "\\-", 2) == 0) ++eval_string;
2664 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2666 argv[i] = const_cast<char*>("");
2667 } else if (strcmp(arg, "--v8-options") == 0) {
2668 argv[i] = const_cast<char*>("--help");
2669 } else if (strcmp(arg, "--no-deprecation") == 0) {
2670 argv[i] = const_cast<char*>("");
2671 no_deprecation = true;
2672 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2673 argv[i] = const_cast<char*>("");
2674 trace_deprecation = true;
2675 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2676 argv[i] = const_cast<char*>("");
2677 throw_deprecation = true;
2678 } else if (argv[i][0] != '-') {
2683 option_end_index = i;
2687 // Called from the main thread.
2688 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2689 v8::Debug::ProcessDebugMessages();
2693 // Called from V8 Debug Agent TCP thread.
2694 static void DispatchMessagesDebugAgentCallback() {
2695 uv_async_send(&dispatch_debug_messages_async);
2699 // Called from the main thread
2700 static void EmitDebugEnabledAsyncCallback(uv_async_t* handle, int status) {
2701 HandleScope handle_scope(node_isolate);
2702 Local<Object> obj = Object::New();
2703 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "cmd"),
2704 FIXED_ONE_BYTE_STRING(node_isolate, "NODE_DEBUG_ENABLED"));
2705 Local<Value> args[] = {
2706 FIXED_ONE_BYTE_STRING(node_isolate, "internalMessage"),
2709 MakeCallback(process_p, "emit", ARRAY_SIZE(args), args);
2713 // Called from the signal watcher callback
2714 static void EmitDebugEnabled() {
2715 uv_async_send(&emit_debug_enabled_async);
2719 static void EnableDebug(bool wait_connect) {
2720 // If we're called from another thread, make sure to enter the right
2722 node_isolate->Enter();
2724 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2727 // Start the debug thread and it's associated TCP server on port 5858.
2728 bool r = v8::Debug::EnableAgent("node " NODE_VERSION,
2732 // Crappy check that everything went well. FIXME
2735 // Print out some information.
2736 fprintf(stderr, "debugger listening on port %d\n", debug_port);
2739 debugger_running = true;
2741 // Do not emit NODE_DEBUG_ENABLED when debugger is enabled before starting
2742 // the main process (i.e. when called via `node --debug`)
2743 if (!process_p.IsEmpty())
2746 node_isolate->Exit();
2751 static void EnableDebugSignalHandler(uv_signal_t* handle, int) {
2752 // Break once process will return execution to v8
2753 v8::Debug::DebugBreak(node_isolate);
2755 if (!debugger_running) {
2756 fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n");
2762 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2763 struct sigaction sa;
2765 memset(&sa, 0, sizeof(sa));
2766 sa.sa_handler = handler;
2767 sigfillset(&sa.sa_mask);
2768 sigaction(signal, &sa, NULL);
2772 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2773 HandleScope scope(node_isolate);
2775 if (args.Length() != 1) {
2776 return ThrowError("Invalid number of arguments.");
2782 pid = args[0]->IntegerValue();
2783 r = kill(pid, SIGUSR1);
2785 return ThrowErrnoException(errno, "kill");
2792 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2793 // Break once process will return execution to v8
2794 if (!debugger_running) {
2795 for (int i = 0; i < 1; i++) {
2796 fprintf(stderr, "Starting debugger agent.\r\n");
2802 v8::Debug::DebugBreak(node_isolate);
2808 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2810 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2814 static int RegisterDebugSignalHandler() {
2815 wchar_t mapping_name[32];
2816 HANDLE mapping_handle;
2818 LPTHREAD_START_ROUTINE* handler;
2820 pid = GetCurrentProcessId();
2822 if (GetDebugSignalHandlerMappingName(pid,
2824 ARRAY_SIZE(mapping_name)) < 0) {
2828 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2834 if (mapping_handle == NULL) {
2838 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2839 MapViewOfFile(mapping_handle,
2840 FILE_MAP_ALL_ACCESS,
2844 if (handler == NULL) {
2845 CloseHandle(mapping_handle);
2849 *handler = EnableDebugThreadProc;
2851 UnmapViewOfFile(static_cast<void*>(handler));
2857 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2858 HandleScope scope(node_isolate);
2860 HANDLE process = NULL;
2861 HANDLE thread = NULL;
2862 HANDLE mapping = NULL;
2863 wchar_t mapping_name[32];
2864 LPTHREAD_START_ROUTINE* handler = NULL;
2866 if (args.Length() != 1) {
2867 ThrowError("Invalid number of arguments.");
2871 pid = (DWORD) args[0]->IntegerValue();
2873 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2874 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2878 if (process == NULL) {
2879 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2883 if (GetDebugSignalHandlerMappingName(pid,
2885 ARRAY_SIZE(mapping_name)) < 0) {
2886 ThrowErrnoException(errno, "sprintf");
2890 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2891 if (mapping == NULL) {
2892 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
2896 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2897 MapViewOfFile(mapping,
2902 if (handler == NULL || *handler == NULL) {
2903 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
2907 thread = CreateRemoteThread(process,
2914 if (thread == NULL) {
2915 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
2919 // Wait for the thread to terminate
2920 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
2921 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
2926 if (process != NULL)
2927 CloseHandle(process);
2929 CloseHandle(thread);
2930 if (handler != NULL)
2931 UnmapViewOfFile(handler);
2932 if (mapping != NULL)
2933 CloseHandle(mapping);
2938 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
2939 v8::Debug::DebugBreak(node_isolate);
2943 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
2944 if (debugger_running) {
2945 v8::Debug::DisableAgent();
2946 debugger_running = false;
2951 char** Init(int argc, char *argv[]) {
2952 // Initialize prog_start_time to get relative uptime.
2953 uv_uptime(&prog_start_time);
2955 // Make inherited handles noninheritable.
2956 uv_disable_stdio_inheritance();
2958 // init async debug messages dispatching
2959 uv_async_init(uv_default_loop(),
2960 &dispatch_debug_messages_async,
2961 DispatchDebugMessagesAsyncCallback);
2962 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
2964 // init async NODE_DEBUG_ENABLED emitter
2965 uv_async_init(uv_default_loop(),
2966 &emit_debug_enabled_async,
2967 EmitDebugEnabledAsyncCallback);
2968 uv_unref(reinterpret_cast<uv_handle_t*>(&emit_debug_enabled_async));
2970 // Parse a few arguments which are specific to Node.
2971 node::ParseArgs(argc, argv);
2972 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
2973 // in the command line))
2974 int v8argc = option_end_index;
2975 char **v8argv = argv;
2977 if (debug_wait_connect) {
2978 // v8argv is a copy of argv up to the script file argument +2 if --debug-brk
2979 // to expose the v8 debugger js object so that node.js can set
2980 // a breakpoint on the first line of the startup script
2982 v8argv = new char*[v8argc];
2983 memcpy(v8argv, argv, sizeof(*argv) * option_end_index);
2984 v8argv[option_end_index] = const_cast<char*>("--expose_debug_as");
2985 v8argv[option_end_index + 1] = const_cast<char*>("v8debug");
2988 // For the normal stack which moves from high to low addresses when frames
2989 // are pushed, we can compute the limit as stack_size bytes below the
2990 // the address of a stack variable (e.g. &stack_var) as an approximation
2991 // of the start of the stack (we're assuming that we haven't pushed a lot
2993 if (max_stack_size != 0) {
2995 ResourceConstraints constraints;
2997 uint32_t *stack_limit = &stack_var - (max_stack_size / sizeof(uint32_t));
2998 constraints.set_stack_limit(stack_limit);
2999 SetResourceConstraints(&constraints); // Must be done before V8::Initialize
3001 V8::SetFlagsFromCommandLine(&v8argc, v8argv, false);
3003 const char typed_arrays_flag[] = "--harmony_typed_arrays";
3004 V8::SetFlagsFromString(typed_arrays_flag, sizeof(typed_arrays_flag) - 1);
3005 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3007 // Fetch a reference to the main isolate, so we have a reference to it
3008 // even when we need it to access it from another (debugger) thread.
3009 node_isolate = Isolate::GetCurrent();
3013 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3014 RegisterSignalHandler(SIGINT, SignalExit);
3015 RegisterSignalHandler(SIGTERM, SignalExit);
3018 uv_check_init(uv_default_loop(), &check_immediate_watcher);
3019 uv_unref(reinterpret_cast<uv_handle_t*>(&check_immediate_watcher));
3020 uv_idle_init(uv_default_loop(), &idle_immediate_dummy);
3022 V8::SetFatalErrorHandler(node::OnFatalError);
3023 V8::AddMessageListener(OnMessage);
3025 // If the --debug flag was specified then initialize the debug thread.
3026 if (use_debug_agent) {
3027 EnableDebug(debug_wait_connect);
3030 RegisterDebugSignalHandler();
3032 static uv_signal_t signal_watcher;
3033 uv_signal_init(uv_default_loop(), &signal_watcher);
3034 uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1);
3035 uv_unref(reinterpret_cast<uv_handle_t*>(&signal_watcher));
3043 struct AtExitCallback {
3044 AtExitCallback* next_;
3045 void (*cb_)(void* arg);
3049 static AtExitCallback* at_exit_functions_;
3053 AtExitCallback* p = at_exit_functions_;
3054 at_exit_functions_ = NULL;
3057 AtExitCallback* q = p->next_;
3065 void AtExit(void (*cb)(void* arg), void* arg) {
3066 AtExitCallback* p = new AtExitCallback;
3069 p->next_ = at_exit_functions_;
3070 at_exit_functions_ = p;
3074 void EmitExit(v8::Handle<v8::Object> process_l) {
3075 // process.emit('exit')
3076 process_l->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3077 True(node_isolate));
3078 Local<Value> args[] = {
3079 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3080 Integer::New(0, node_isolate)
3082 MakeCallback(process_l, "emit", ARRAY_SIZE(args), args);
3085 static char **copy_argv(int argc, char **argv) {
3093 for (i = 0; i < argc; i++) {
3094 strlen_sum += strlen(argv[i]) + 1;
3097 argv_copy = static_cast<char**>(
3098 malloc(sizeof(*argv_copy) * (argc + 1) + strlen_sum));
3103 argv_data = reinterpret_cast<char*>(argv_copy) +
3104 sizeof(*argv_copy) * (argc + 1);
3106 for (i = 0; i < argc; i++) {
3107 argv_copy[i] = argv_data;
3108 len = strlen(argv[i]) + 1;
3109 memcpy(argv_data, argv[i], len);
3113 argv_copy[argc] = NULL;
3118 int Start(int argc, char *argv[]) {
3119 // Hack aroung with the argv pointer. Used for process.title = "blah".
3120 argv = uv_setup_args(argc, argv);
3122 // Logic to duplicate argv as Init() modifies arguments
3123 // that are passed into it.
3124 char **argv_copy = copy_argv(argc, argv);
3126 // This needs to run *before* V8::Initialize()
3127 // Use copy here as to not modify the original argv:
3128 Init(argc, argv_copy);
3132 Locker locker(node_isolate);
3133 HandleScope handle_scope(node_isolate);
3135 // Create the one and only Context.
3136 Local<Context> context = Context::New(node_isolate);
3137 Context::Scope context_scope(context);
3139 binding_cache.Reset(node_isolate, Object::New());
3141 // Use original argv, as we're just copying values out of it.
3142 Local<Object> process_l = SetupProcessObject(argc, argv);
3144 // Create all the objects, load modules, do everything.
3145 // so your next reading stop should be node::Load()!
3148 // All our arguments are loaded. We've evaluated all of the scripts. We
3149 // might even have created TCP servers. Now we enter the main eventloop. If
3150 // there are no watchers on the loop (except for the ones that were
3151 // uv_unref'd) then this function exits. As long as there are active
3152 // watchers, it blocks.
3153 uv_run(uv_default_loop(), UV_RUN_DEFAULT);
3155 EmitExit(process_l);
3160 // Clean up. Not strictly necessary.
3164 // Clean up the copy: