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 = String::New("_immediateCallback");
248 MakeCallback(process_p, immediate_callback_sym, 0, NULL);
252 static void IdleImmediateDummy(uv_idle_t* handle, int status) {
253 // Do nothing. Only for maintaining event loop
254 assert(handle == &idle_immediate_dummy);
259 static inline const char *errno_string(int errorno) {
260 #define ERRNO_CASE(e) case e: return #e;
267 ERRNO_CASE(EADDRINUSE);
271 ERRNO_CASE(EADDRNOTAVAIL);
275 ERRNO_CASE(EAFNOSUPPORT);
283 # if EAGAIN != EWOULDBLOCK
284 ERRNO_CASE(EWOULDBLOCK);
289 ERRNO_CASE(EALREADY);
305 ERRNO_CASE(ECANCELED);
313 ERRNO_CASE(ECONNABORTED);
317 ERRNO_CASE(ECONNREFUSED);
321 ERRNO_CASE(ECONNRESET);
329 ERRNO_CASE(EDESTADDRREQ);
353 ERRNO_CASE(EHOSTUNREACH);
365 ERRNO_CASE(EINPROGRESS);
401 ERRNO_CASE(EMSGSIZE);
405 ERRNO_CASE(EMULTIHOP);
409 ERRNO_CASE(ENAMETOOLONG);
413 ERRNO_CASE(ENETDOWN);
417 ERRNO_CASE(ENETRESET);
421 ERRNO_CASE(ENETUNREACH);
453 # if ENOLINK != ENOLCK
467 ERRNO_CASE(ENOPROTOOPT);
487 ERRNO_CASE(ENOTCONN);
495 ERRNO_CASE(ENOTEMPTY);
499 ERRNO_CASE(ENOTSOCK);
506 ERRNO_CASE(EOPNOTSUPP);
520 ERRNO_CASE(EOVERFLOW);
535 #ifdef EPROTONOSUPPORT
536 ERRNO_CASE(EPROTONOSUPPORT);
540 ERRNO_CASE(EPROTOTYPE);
568 ERRNO_CASE(ETIMEDOUT);
583 const char *signo_string(int signo) {
584 #define SIGNO_CASE(e) case e: return #e;
611 # if SIGABRT != SIGIOT
655 SIGNO_CASE(SIGSTKFLT);
672 SIGNO_CASE(SIGBREAK);
696 SIGNO_CASE(SIGVTALRM);
704 SIGNO_CASE(SIGWINCH);
712 # if SIGPOLL != SIGIO
722 # if SIGPWR != SIGLOST
736 Local<Value> ErrnoException(int errorno,
741 Local<String> estring = String::NewSymbol(errno_string(errorno));
742 if (msg == NULL || msg[0] == '\0') {
743 msg = strerror(errorno);
745 Local<String> message = String::NewSymbol(msg);
747 Local<String> cons1 = String::Concat(estring, String::NewSymbol(", "));
748 Local<String> cons2 = String::Concat(cons1, message);
750 if (syscall_symbol.IsEmpty()) {
751 syscall_symbol = String::New("syscall");
752 errno_symbol = String::New("errno");
753 errpath_symbol = String::New("path");
754 code_symbol = String::New("code");
758 Local<String> cons3 = String::Concat(cons2, String::NewSymbol(" '"));
759 Local<String> cons4 = String::Concat(cons3, String::New(path));
760 Local<String> cons5 = String::Concat(cons4, String::NewSymbol("'"));
761 e = Exception::Error(cons5);
763 e = Exception::Error(cons2);
766 Local<Object> obj = e->ToObject();
768 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
769 obj->Set(code_symbol, estring);
770 if (path) obj->Set(errpath_symbol, String::New(path));
771 if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
776 // hack alert! copy of ErrnoException, tuned for uv errors
777 Local<Value> UVException(int errorno,
781 if (syscall_symbol.IsEmpty()) {
782 syscall_symbol = String::New("syscall");
783 errno_symbol = String::New("errno");
784 errpath_symbol = String::New("path");
785 code_symbol = String::New("code");
789 msg = uv_strerror(errorno);
791 Local<String> estring = String::NewSymbol(uv_err_name(errorno));
792 Local<String> message = String::NewSymbol(msg);
793 Local<String> cons1 = String::Concat(estring, String::NewSymbol(", "));
794 Local<String> cons2 = String::Concat(cons1, message);
798 Local<String> path_str;
802 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
803 path_str = String::Concat(String::New("\\\\"), String::New(path + 8));
804 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
805 path_str = String::New(path + 4);
807 path_str = String::New(path);
810 path_str = String::New(path);
813 Local<String> cons3 = String::Concat(cons2, String::NewSymbol(" '"));
814 Local<String> cons4 = String::Concat(cons3, path_str);
815 Local<String> cons5 = String::Concat(cons4, String::NewSymbol("'"));
816 e = Exception::Error(cons5);
818 e = Exception::Error(cons2);
821 Local<Object> obj = e->ToObject();
823 // TODO(piscisaureus) errno should probably go
824 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
825 obj->Set(code_symbol, estring);
826 if (path) obj->Set(errpath_symbol, path_str);
827 if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
833 // Does about the same as strerror(),
834 // but supports all windows error messages
835 static const char *winapi_strerror(const int errorno) {
838 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
839 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
840 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
843 // Remove trailing newlines
844 for (int i = strlen(errmsg) - 1;
845 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
851 // FormatMessage failed
852 return "Unknown error";
857 Local<Value> WinapiErrnoException(int errorno,
862 if (!msg || !msg[0]) {
863 msg = winapi_strerror(errorno);
865 Local<String> message = String::NewSymbol(msg);
867 if (syscall_symbol.IsEmpty()) {
868 syscall_symbol = String::New("syscall");
869 errno_symbol = String::New("errno");
870 errpath_symbol = String::New("path");
871 code_symbol = String::New("code");
875 Local<String> cons1 = String::Concat(message, String::NewSymbol(" '"));
876 Local<String> cons2 = String::Concat(cons1, String::New(path));
877 Local<String> cons3 = String::Concat(cons2, String::NewSymbol("'"));
878 e = Exception::Error(cons3);
880 e = Exception::Error(message);
883 Local<Object> obj = e->ToObject();
885 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
886 if (path) obj->Set(errpath_symbol, String::New(path));
887 if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
893 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
894 if (using_domains) return;
895 HandleScope scope(node_isolate);
896 using_domains = true;
897 Local<Object> process = PersistentToLocal(process_p);
898 Local<Value> tdc_v = process->Get(String::New("_tickDomainCallback"));
899 Local<Value> ndt_v = process->Get(String::New("_nextDomainTick"));
900 if (!tdc_v->IsFunction()) {
901 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
904 if (!ndt_v->IsFunction()) {
905 fprintf(stderr, "process._nextDomainTick assigned to non-function\n");
908 Local<Function> tdc = tdc_v.As<Function>();
909 Local<Function> ndt = ndt_v.As<Function>();
910 process->Set(String::New("_tickCallback"), tdc);
911 process->Set(String::New("nextTick"), ndt);
912 process_tickCallback.Reset(node_isolate, tdc);
917 MakeDomainCallback(const Handle<Object> object,
918 const Handle<Function> callback,
920 Handle<Value> argv[]) {
921 // TODO(trevnorris) Hook for long stack traces to be made here.
923 // lazy load domain specific symbols
924 if (enter_symbol.IsEmpty()) {
925 enter_symbol = String::New("enter");
926 exit_symbol = String::New("exit");
927 disposed_symbol = String::New("_disposed");
930 Local<Value> domain_v = object->Get(domain_symbol);
931 Local<Object> domain;
932 Local<Function> enter;
933 Local<Function> exit;
936 try_catch.SetVerbose(true);
938 bool has_domain = domain_v->IsObject();
940 domain = domain_v->ToObject();
941 assert(!domain.IsEmpty());
942 if (domain->Get(disposed_symbol)->IsTrue()) {
943 // domain has been disposed of.
944 return Undefined(node_isolate);
946 enter = Local<Function>::Cast(domain->Get(enter_symbol));
947 assert(!enter.IsEmpty());
948 enter->Call(domain, 0, NULL);
950 if (try_catch.HasCaught()) {
951 return Undefined(node_isolate);
955 Local<Value> ret = callback->Call(object, argc, argv);
957 if (try_catch.HasCaught()) {
958 return Undefined(node_isolate);
962 exit = Local<Function>::Cast(domain->Get(exit_symbol));
963 assert(!exit.IsEmpty());
964 exit->Call(domain, 0, NULL);
966 if (try_catch.HasCaught()) {
967 return Undefined(node_isolate);
971 if (tick_infobox.last_threw == 1) {
972 tick_infobox.last_threw = 0;
976 if (tick_infobox.in_tick == 1) {
980 if (tick_infobox.length == 0) {
981 tick_infobox.index = 0;
985 // process nextTicks after call
986 Local<Object> process = PersistentToLocal(process_p);
987 Local<Function> fn = PersistentToLocal(process_tickCallback);
988 fn->Call(process, 0, NULL);
990 if (try_catch.HasCaught()) {
991 return Undefined(node_isolate);
999 MakeCallback(const Handle<Object> object,
1000 const Handle<Function> callback,
1002 Handle<Value> argv[]) {
1003 // TODO(trevnorris) Hook for long stack traces to be made here.
1004 Local<Object> process = PersistentToLocal(process_p);
1007 return MakeDomainCallback(object, callback, argc, argv);
1009 // lazy load no domain next tick callbacks
1010 if (process_tickCallback.IsEmpty()) {
1011 Local<Value> cb_v = process->Get(String::New("_tickCallback"));
1012 if (!cb_v->IsFunction()) {
1013 fprintf(stderr, "process._tickCallback assigned to non-function\n");
1016 process_tickCallback.Reset(node_isolate, cb_v.As<Function>());
1020 try_catch.SetVerbose(true);
1022 Local<Value> ret = callback->Call(object, argc, argv);
1024 if (try_catch.HasCaught()) {
1025 return Undefined(node_isolate);
1028 if (tick_infobox.in_tick == 1) {
1032 if (tick_infobox.length == 0) {
1033 tick_infobox.index = 0;
1037 // process nextTicks after call
1038 Local<Function> fn = PersistentToLocal(process_tickCallback);
1039 fn->Call(process, 0, NULL);
1041 if (try_catch.HasCaught()) {
1042 return Undefined(node_isolate);
1050 MakeCallback(const Handle<Object> object,
1051 const Handle<String> symbol,
1053 Handle<Value> argv[]) {
1054 HandleScope scope(node_isolate);
1056 Local<Function> callback = object->Get(symbol).As<Function>();
1057 assert(callback->IsFunction());
1060 return scope.Close(MakeDomainCallback(object, callback, argc, argv));
1061 return scope.Close(MakeCallback(object, callback, argc, argv));
1066 MakeCallback(const Handle<Object> object,
1069 Handle<Value> argv[]) {
1070 HandleScope scope(node_isolate);
1073 MakeCallback(object, String::NewSymbol(method), argc, argv);
1075 return scope.Close(ret);
1079 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1080 HandleScope scope(node_isolate);
1082 if (!encoding_v->IsString()) return _default;
1084 String::Utf8Value encoding(encoding_v);
1086 if (strcasecmp(*encoding, "utf8") == 0) {
1088 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1090 } else if (strcasecmp(*encoding, "ascii") == 0) {
1092 } else if (strcasecmp(*encoding, "base64") == 0) {
1094 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1096 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1098 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1100 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1102 } else if (strcasecmp(*encoding, "binary") == 0) {
1104 } else if (strcasecmp(*encoding, "buffer") == 0) {
1106 } else if (strcasecmp(*encoding, "hex") == 0) {
1108 } else if (strcasecmp(*encoding, "raw") == 0) {
1109 if (!no_deprecation) {
1110 fprintf(stderr, "'raw' (array of integers) has been removed. "
1114 } else if (strcasecmp(*encoding, "raws") == 0) {
1115 if (!no_deprecation) {
1116 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1117 "Please update your code.\n");
1125 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1126 return StringBytes::Encode(static_cast<const char*>(buf),
1131 // Returns -1 if the handle was not valid for decoding
1132 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1133 HandleScope scope(node_isolate);
1135 if (val->IsArray()) {
1136 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1142 return StringBytes::Size(val, encoding);
1146 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1149 // Returns number of bytes written.
1150 ssize_t DecodeWrite(char *buf,
1152 v8::Handle<v8::Value> val,
1153 enum encoding encoding) {
1154 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1157 void DisplayExceptionLine(Handle<Message> message) {
1158 // Prevent re-entry into this function. For example, if there is
1159 // a throw from a program in vm.runInThisContext(code, filename, true),
1160 // then we want to show the original failure, not the secondary one.
1161 static bool displayed_error = false;
1163 if (displayed_error) return;
1164 displayed_error = true;
1166 uv_tty_reset_mode();
1168 fprintf(stderr, "\n");
1170 if (!message.IsEmpty()) {
1171 // Print (filename):(line number): (message).
1172 String::Utf8Value filename(message->GetScriptResourceName());
1173 const char* filename_string = *filename;
1174 int linenum = message->GetLineNumber();
1175 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1176 // Print line of source code.
1177 String::Utf8Value sourceline(message->GetSourceLine());
1178 const char* sourceline_string = *sourceline;
1180 // Because of how node modules work, all scripts are wrapped with a
1181 // "function (module, exports, __filename, ...) {"
1182 // to provide script local variables.
1184 // When reporting errors on the first line of a script, this wrapper
1185 // function is leaked to the user. There used to be a hack here to
1186 // truncate off the first 62 characters, but it caused numerous other
1187 // problems when vm.runIn*Context() methods were used for non-module
1190 // If we ever decide to re-instate such a hack, the following steps
1193 // 1. Pass a flag around to say "this code was wrapped"
1194 // 2. Update the stack frame output so that it is also correct.
1196 // It would probably be simpler to add a line rather than add some
1197 // number of characters to the first line, since V8 truncates the
1198 // sourceline to 78 characters, and we end up not providing very much
1199 // useful debugging info to the user if we remove 62 characters.
1201 int start = message->GetStartColumn();
1202 int end = message->GetEndColumn();
1204 fprintf(stderr, "%s\n", sourceline_string);
1205 // Print wavy underline (GetUnderline is deprecated).
1206 for (int i = 0; i < start; i++) {
1207 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1209 for (int i = start; i < end; i++) {
1212 fputc('\n', stderr);
1217 static void ReportException(Handle<Value> er, Handle<Message> message) {
1218 HandleScope scope(node_isolate);
1220 DisplayExceptionLine(message);
1222 Local<Value> trace_value(er->ToObject()->Get(String::New("stack")));
1223 String::Utf8Value trace(trace_value);
1225 // range errors have a trace member set to undefined
1226 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1227 fprintf(stderr, "%s\n", *trace);
1229 // this really only happens for RangeErrors, since they're the only
1230 // kind that won't have all this info in the trace, or when non-Error
1231 // objects are thrown manually.
1232 bool isErrorObject = er->IsObject() &&
1233 !(er->ToObject()->Get(String::New("message"))->IsUndefined()) &&
1234 !(er->ToObject()->Get(String::New("name"))->IsUndefined());
1236 if (isErrorObject) {
1237 String::Utf8Value name(er->ToObject()->Get(String::New("name")));
1238 fprintf(stderr, "%s: ", *name);
1241 String::Utf8Value msg(!isErrorObject ? er
1242 : er->ToObject()->Get(String::New("message")));
1243 fprintf(stderr, "%s\n", *msg);
1250 static void ReportException(const TryCatch& try_catch) {
1251 ReportException(try_catch.Exception(), try_catch.Message());
1255 // Executes a str within the current v8 context.
1256 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1257 HandleScope scope(node_isolate);
1260 // try_catch must be nonverbose to disable FatalException() handler,
1261 // we will handle exceptions ourself.
1262 try_catch.SetVerbose(false);
1264 Local<v8::Script> script = v8::Script::Compile(source, filename);
1265 if (script.IsEmpty()) {
1266 ReportException(try_catch);
1270 Local<Value> result = script->Run();
1271 if (result.IsEmpty()) {
1272 ReportException(try_catch);
1276 return scope.Close(result);
1280 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1281 HandleScope scope(node_isolate);
1283 Local<Array> ary = Array::New();
1287 QUEUE_FOREACH(q, &req_wrap_queue) {
1288 ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1289 if (w->persistent().IsEmpty()) continue;
1290 ary->Set(i++, w->object());
1293 args.GetReturnValue().Set(ary);
1297 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1298 // implemented here for consistency with GetActiveRequests().
1299 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1300 HandleScope scope(node_isolate);
1302 Local<Array> ary = Array::New();
1306 Local<String> owner_sym = String::New("owner");
1308 QUEUE_FOREACH(q, &handle_wrap_queue) {
1309 HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1310 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue;
1311 Local<Object> object = w->object();
1312 Local<Value> owner = object->Get(owner_sym);
1313 if (owner->IsUndefined()) owner = object;
1314 ary->Set(i++, owner);
1317 args.GetReturnValue().Set(ary);
1321 static void Abort(const FunctionCallbackInfo<Value>& args) {
1326 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1327 HandleScope scope(node_isolate);
1329 if (args.Length() != 1 || !args[0]->IsString()) {
1330 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1333 String::Utf8Value path(args[0]);
1334 int err = uv_chdir(*path);
1336 return ThrowUVException(err, "uv_chdir");
1341 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1342 HandleScope scope(node_isolate);
1344 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1345 char buf[MAX_PATH * 4 + 1];
1347 char buf[PATH_MAX + 1];
1350 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1352 return ThrowUVException(err, "uv_cwd");
1355 buf[ARRAY_SIZE(buf) - 1] = '\0';
1356 Local<String> cwd = String::New(buf);
1358 args.GetReturnValue().Set(cwd);
1362 static void Umask(const FunctionCallbackInfo<Value>& args) {
1363 HandleScope scope(node_isolate);
1366 if (args.Length() < 1 || args[0]->IsUndefined()) {
1368 umask(static_cast<mode_t>(old));
1369 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1370 return ThrowTypeError("argument must be an integer or octal string.");
1373 if (args[0]->IsInt32()) {
1374 oct = args[0]->Uint32Value();
1377 String::Utf8Value str(args[0]);
1379 // Parse the octal string.
1380 for (int i = 0; i < str.length(); i++) {
1382 if (c > '7' || c < '0') {
1383 return ThrowTypeError("invalid octal string");
1389 old = umask(static_cast<mode_t>(oct));
1392 args.GetReturnValue().Set(old);
1396 #if defined(__POSIX__) && !defined(__ANDROID__)
1398 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1399 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1402 static uid_t uid_by_name(const char* name) {
1410 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1414 return uid_not_found;
1418 static char* name_by_uid(uid_t uid) {
1427 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1428 return strdup(pp->pw_name);
1439 static gid_t gid_by_name(const char* name) {
1447 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1451 return gid_not_found;
1455 #if 0 // For future use.
1456 static const char* name_by_gid(gid_t gid) {
1465 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1466 return strdup(pp->gr_name);
1478 static uid_t uid_by_name(Handle<Value> value) {
1479 if (value->IsUint32()) {
1480 return static_cast<uid_t>(value->Uint32Value());
1482 String::Utf8Value name(value);
1483 return uid_by_name(*name);
1488 static gid_t gid_by_name(Handle<Value> value) {
1489 if (value->IsUint32()) {
1490 return static_cast<gid_t>(value->Uint32Value());
1492 String::Utf8Value name(value);
1493 return gid_by_name(*name);
1498 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1499 args.GetReturnValue().Set(getuid());
1503 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1504 args.GetReturnValue().Set(getgid());
1508 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1509 HandleScope scope(node_isolate);
1511 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1512 return ThrowTypeError("setgid argument must be a number or a string");
1515 gid_t gid = gid_by_name(args[0]);
1517 if (gid == gid_not_found) {
1518 return ThrowError("setgid group id does not exist");
1522 return ThrowErrnoException(errno, "setgid");
1527 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1528 HandleScope scope(node_isolate);
1530 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1531 return ThrowTypeError("setuid argument must be a number or a string");
1534 uid_t uid = uid_by_name(args[0]);
1536 if (uid == uid_not_found) {
1537 return ThrowError("setuid user id does not exist");
1541 return ThrowErrnoException(errno, "setuid");
1546 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1547 HandleScope scope(node_isolate);
1549 int ngroups = getgroups(0, NULL);
1551 if (ngroups == -1) {
1552 return ThrowErrnoException(errno, "getgroups");
1555 gid_t* groups = new gid_t[ngroups];
1557 ngroups = getgroups(ngroups, groups);
1559 if (ngroups == -1) {
1561 return ThrowErrnoException(errno, "getgroups");
1564 Local<Array> groups_list = Array::New(ngroups);
1565 bool seen_egid = false;
1566 gid_t egid = getegid();
1568 for (int i = 0; i < ngroups; i++) {
1569 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1570 if (groups[i] == egid) seen_egid = true;
1575 if (seen_egid == false) {
1576 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1579 args.GetReturnValue().Set(groups_list);
1583 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1584 HandleScope scope(node_isolate);
1586 if (!args[0]->IsArray()) {
1587 return ThrowTypeError("argument 1 must be an array");
1590 Local<Array> groups_list = args[0].As<Array>();
1591 size_t size = groups_list->Length();
1592 gid_t* groups = new gid_t[size];
1594 for (size_t i = 0; i < size; i++) {
1595 gid_t gid = gid_by_name(groups_list->Get(i));
1597 if (gid == gid_not_found) {
1599 return ThrowError("group name not found");
1605 int rc = setgroups(size, groups);
1609 return ThrowErrnoException(errno, "setgroups");
1614 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1615 HandleScope scope(node_isolate);
1617 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1618 return ThrowTypeError("argument 1 must be a number or a string");
1621 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1622 return ThrowTypeError("argument 2 must be a number or a string");
1625 String::Utf8Value arg0(args[0]);
1630 if (args[0]->IsUint32()) {
1631 user = name_by_uid(args[0]->Uint32Value());
1639 return ThrowError("initgroups user not found");
1642 extra_group = gid_by_name(args[1]);
1644 if (extra_group == gid_not_found) {
1645 if (must_free) free(user);
1646 return ThrowError("initgroups extra group not found");
1649 int rc = initgroups(user, extra_group);
1656 return ThrowErrnoException(errno, "initgroups");
1660 #endif // __POSIX__ && !defined(__ANDROID__)
1663 void Exit(const FunctionCallbackInfo<Value>& args) {
1664 HandleScope scope(node_isolate);
1665 exit(args[0]->IntegerValue());
1669 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1670 HandleScope scope(node_isolate);
1672 if (uv_uptime(&uptime)) return;
1673 args.GetReturnValue().Set(uptime - prog_start_time);
1677 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1678 HandleScope scope(node_isolate);
1682 int err = uv_resident_set_memory(&rss);
1684 return ThrowUVException(err, "uv_resident_set_memory");
1687 Local<Object> info = Object::New();
1689 if (rss_symbol.IsEmpty()) {
1690 rss_symbol = String::New("rss");
1691 heap_total_symbol = String::New("heapTotal");
1692 heap_used_symbol = String::New("heapUsed");
1695 info->Set(rss_symbol, Number::New(rss));
1698 HeapStatistics v8_heap_stats;
1699 node_isolate->GetHeapStatistics(&v8_heap_stats);
1700 info->Set(heap_total_symbol,
1701 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(),
1703 info->Set(heap_used_symbol,
1704 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(),
1707 args.GetReturnValue().Set(info);
1711 void Kill(const FunctionCallbackInfo<Value>& args) {
1712 HandleScope scope(node_isolate);
1714 if (args.Length() != 2) {
1715 return ThrowError("Bad argument.");
1718 int pid = args[0]->IntegerValue();
1719 int sig = args[1]->Int32Value();
1720 int err = uv_kill(pid, sig);
1721 args.GetReturnValue().Set(err);
1724 // used in Hrtime() below
1725 #define NANOS_PER_SEC 1000000000
1727 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1728 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1729 // so this function instead returns an Array with 2 entries representing seconds
1730 // and nanoseconds, to avoid any integer overflow possibility.
1731 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1732 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1733 HandleScope scope(node_isolate);
1735 uint64_t t = uv_hrtime();
1737 if (args.Length() > 0) {
1738 // return a time diff tuple
1739 if (!args[0]->IsArray()) {
1740 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1742 Local<Array> inArray = Local<Array>::Cast(args[0]);
1743 uint64_t seconds = inArray->Get(0)->Uint32Value();
1744 uint64_t nanos = inArray->Get(1)->Uint32Value();
1745 t -= (seconds * NANOS_PER_SEC) + nanos;
1748 Local<Array> tuple = Array::New(2);
1749 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1750 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1751 args.GetReturnValue().Set(tuple);
1755 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1757 // DLOpen is process.dlopen(module, filename).
1758 // Used to load 'module.node' dynamically shared objects.
1759 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1760 HandleScope scope(node_isolate);
1761 char symbol[1024], *base, *pos;
1765 if (args.Length() < 2) {
1766 return ThrowError("process.dlopen takes exactly 2 arguments.");
1769 Local<Object> module = args[0]->ToObject(); // Cast
1770 String::Utf8Value filename(args[1]); // Cast
1772 if (exports_symbol.IsEmpty()) {
1773 exports_symbol = String::New("exports");
1775 Local<Object> exports = module->Get(exports_symbol)->ToObject();
1777 if (uv_dlopen(*filename, &lib)) {
1778 Local<String> errmsg = String::New(uv_dlerror(&lib));
1780 // Windows needs to add the filename into the error message
1781 errmsg = String::Concat(errmsg, args[1]->ToString());
1783 ThrowException(Exception::Error(errmsg));
1787 String::Utf8Value path(args[1]);
1790 /* Find the shared library filename within the full path. */
1792 pos = strrchr(base, '/');
1798 pos = strpbrk(base, "\\/:");
1806 /* Strip the .node extension. */
1807 pos = strrchr(base, '.');
1812 /* Add the `_module` suffix to the extension name. */
1813 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1814 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1815 return ThrowError("Out of memory.");
1818 /* Replace dashes with underscores. When loading foo-bar.node,
1819 * look for foo_bar_module, not foo-bar_module.
1821 for (pos = symbol; *pos != '\0'; ++pos) {
1822 if (*pos == '-') *pos = '_';
1825 node_module_struct *mod;
1826 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1828 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1829 return ThrowError(errmsg);
1832 if (mod->version != NODE_MODULE_VERSION) {
1836 "Module version mismatch. Expected %d, got %d.",
1837 NODE_MODULE_VERSION, mod->version);
1838 return ThrowError(errmsg);
1841 // Execute the C++ module
1842 mod->register_func(exports, module);
1844 // Tell coverity that 'handle' should not be freed when we return.
1845 // coverity[leaked_storage]
1849 static void OnFatalError(const char* location, const char* message) {
1851 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1853 fprintf(stderr, "FATAL ERROR: %s\n", message);
1863 NO_RETURN void FatalError(const char* location, const char* message) {
1864 OnFatalError(location, message);
1865 // to supress compiler warning
1870 void FatalException(Handle<Value> error, Handle<Message> message) {
1871 HandleScope scope(node_isolate);
1873 if (fatal_exception_symbol.IsEmpty())
1874 fatal_exception_symbol = String::New("_fatalException");
1876 Local<Object> process = PersistentToLocal(process_p);
1877 Local<Value> fatal_v = process->Get(fatal_exception_symbol);
1879 if (!fatal_v->IsFunction()) {
1880 // failed before the process._fatalException function was added!
1881 // this is probably pretty bad. Nothing to do but report and exit.
1882 ReportException(error, message);
1886 Local<Function> fatal_f = Local<Function>::Cast(fatal_v);
1888 TryCatch fatal_try_catch;
1890 // Do not call FatalException when _fatalException handler throws
1891 fatal_try_catch.SetVerbose(false);
1893 // this will return true if the JS layer handled it, false otherwise
1894 Local<Value> caught = fatal_f->Call(process, 1, &error);
1896 if (fatal_try_catch.HasCaught()) {
1897 // the fatal exception function threw, so we must exit
1898 ReportException(fatal_try_catch);
1902 if (false == caught->BooleanValue()) {
1903 ReportException(error, message);
1909 void FatalException(const TryCatch& try_catch) {
1910 HandleScope scope(node_isolate);
1911 // TODO(bajtos) do not call FatalException if try_catch is verbose
1912 // (requires V8 API to expose getter for try_catch.is_verbose_)
1913 FatalException(try_catch.Exception(), try_catch.Message());
1917 void OnMessage(Handle<Message> message, Handle<Value> error) {
1918 // The current version of V8 sends messages for errors only
1919 // (thus `error` is always set).
1920 FatalException(error, message);
1924 static void Binding(const FunctionCallbackInfo<Value>& args) {
1925 HandleScope scope(node_isolate);
1927 Local<String> module = args[0]->ToString();
1928 String::Utf8Value module_v(module);
1929 node_module_struct* modp;
1931 Local<Object> cache = PersistentToLocal(binding_cache);
1932 Local<Object> exports;
1934 if (cache->Has(module)) {
1935 exports = cache->Get(module)->ToObject();
1936 args.GetReturnValue().Set(exports);
1940 // Append a string to process.moduleLoadList
1942 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
1944 Local<Array> modules = PersistentToLocal(module_load_list);
1945 uint32_t l = modules->Length();
1946 modules->Set(l, String::New(buf));
1948 if ((modp = get_builtin_module(*module_v)) != NULL) {
1949 exports = Object::New();
1950 // Internal bindings don't have a "module" object,
1952 modp->register_func(exports, Undefined(node_isolate));
1953 cache->Set(module, exports);
1954 } else if (!strcmp(*module_v, "constants")) {
1955 exports = Object::New();
1956 DefineConstants(exports);
1957 cache->Set(module, exports);
1958 } else if (!strcmp(*module_v, "natives")) {
1959 exports = Object::New();
1960 DefineJavaScript(exports);
1961 cache->Set(module, exports);
1963 return ThrowError("No such module");
1966 args.GetReturnValue().Set(exports);
1970 static void ProcessTitleGetter(Local<String> property,
1971 const PropertyCallbackInfo<Value>& info) {
1972 HandleScope scope(node_isolate);
1974 uv_get_process_title(buffer, sizeof(buffer));
1975 info.GetReturnValue().Set(String::New(buffer));
1979 static void ProcessTitleSetter(Local<String> property,
1981 const PropertyCallbackInfo<void>& info) {
1982 HandleScope scope(node_isolate);
1983 String::Utf8Value title(value);
1984 // TODO(piscisaureus): protect with a lock
1985 uv_set_process_title(*title);
1989 static void EnvGetter(Local<String> property,
1990 const PropertyCallbackInfo<Value>& info) {
1991 HandleScope scope(node_isolate);
1993 String::Utf8Value key(property);
1994 const char* val = getenv(*key);
1996 return info.GetReturnValue().Set(String::New(val));
1999 String::Value key(property);
2000 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2001 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2003 ARRAY_SIZE(buffer));
2004 // If result >= sizeof buffer the buffer was too small. That should never
2005 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2007 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2008 result < ARRAY_SIZE(buffer)) {
2009 return info.GetReturnValue().Set(
2010 String::New(reinterpret_cast<uint16_t*>(buffer), result));
2013 // Not found. Fetch from prototype.
2014 info.GetReturnValue().Set(
2015 info.Data().As<Object>()->Get(property));
2019 static void EnvSetter(Local<String> property,
2021 const PropertyCallbackInfo<Value>& info) {
2022 HandleScope scope(node_isolate);
2024 String::Utf8Value key(property);
2025 String::Utf8Value val(value);
2026 setenv(*key, *val, 1);
2028 String::Value key(property);
2029 String::Value val(value);
2030 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2031 // Environment variables that start with '=' are read-only.
2032 if (key_ptr[0] != L'=') {
2033 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2036 // Whether it worked or not, always return rval.
2037 info.GetReturnValue().Set(value);
2041 static void EnvQuery(Local<String> property,
2042 const PropertyCallbackInfo<Integer>& info) {
2043 HandleScope scope(node_isolate);
2044 int32_t rc = -1; // Not found unless proven otherwise.
2046 String::Utf8Value key(property);
2047 if (getenv(*key)) rc = 0;
2049 String::Value key(property);
2050 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2051 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2052 GetLastError() == ERROR_SUCCESS) {
2054 if (key_ptr[0] == L'=') {
2055 // Environment variables that start with '=' are hidden and read-only.
2056 rc = static_cast<int32_t>(v8::ReadOnly) |
2057 static_cast<int32_t>(v8::DontDelete) |
2058 static_cast<int32_t>(v8::DontEnum);
2062 if (rc != -1) info.GetReturnValue().Set(rc);
2066 static void EnvDeleter(Local<String> property,
2067 const PropertyCallbackInfo<Boolean>& info) {
2068 HandleScope scope(node_isolate);
2071 String::Utf8Value key(property);
2072 rc = getenv(*key) != NULL;
2073 if (rc) unsetenv(*key);
2075 String::Value key(property);
2076 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2077 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2078 // Deletion failed. Return true if the key wasn't there in the first place,
2079 // false if it is still there.
2080 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2081 GetLastError() != ERROR_SUCCESS;
2084 info.GetReturnValue().Set(rc);
2088 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2089 HandleScope scope(node_isolate);
2092 while (environ[size]) size++;
2094 Local<Array> env = Array::New(size);
2096 for (int i = 0; i < size; ++i) {
2097 const char* var = environ[i];
2098 const char* s = strchr(var, '=');
2099 const int length = s ? s - var : strlen(var);
2100 env->Set(i, String::New(var, length));
2103 WCHAR* environment = GetEnvironmentStringsW();
2104 if (environment == NULL) return; // This should not happen.
2105 Local<Array> env = Array::New();
2106 WCHAR* p = environment;
2108 while (*p != NULL) {
2111 // If the key starts with '=' it is a hidden environment variable.
2115 s = wcschr(p, L'=');
2120 env->Set(i++, String::New(reinterpret_cast<uint16_t*>(p), s - p));
2121 p = s + wcslen(s) + 1;
2123 FreeEnvironmentStringsW(environment);
2126 info.GetReturnValue().Set(env);
2130 static Handle<Object> GetFeatures() {
2131 HandleScope scope(node_isolate);
2133 Local<Object> obj = Object::New();
2134 #if defined(DEBUG) && DEBUG
2135 Local<Value> debug = True(node_isolate);
2137 Local<Value> debug = False(node_isolate);
2138 #endif // defined(DEBUG) && DEBUG
2140 obj->Set(String::NewSymbol("debug"), debug);
2142 obj->Set(String::NewSymbol("uv"), True(node_isolate));
2143 // TODO(bnoordhuis) ping libuv
2144 obj->Set(String::NewSymbol("ipv6"), True(node_isolate));
2145 obj->Set(String::NewSymbol("tls_npn"), Boolean::New(use_npn));
2146 obj->Set(String::NewSymbol("tls_sni"), Boolean::New(use_sni));
2147 obj->Set(String::NewSymbol("tls"),
2148 Boolean::New(get_builtin_module("crypto") != NULL));
2150 return scope.Close(obj);
2154 static void DebugPortGetter(Local<String> property,
2155 const PropertyCallbackInfo<Value>& info) {
2156 HandleScope scope(node_isolate);
2157 info.GetReturnValue().Set(debug_port);
2161 static void DebugPortSetter(Local<String> property,
2163 const PropertyCallbackInfo<void>& info) {
2164 HandleScope scope(node_isolate);
2165 debug_port = value->NumberValue();
2169 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2170 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2171 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2174 void NeedImmediateCallbackGetter(Local<String> property,
2175 const PropertyCallbackInfo<Value>& info) {
2176 info.GetReturnValue().Set(need_immediate_cb);
2180 static void NeedImmediateCallbackSetter(Local<String> property,
2182 const PropertyCallbackInfo<void>&) {
2183 HandleScope scope(node_isolate);
2185 bool bool_value = value->BooleanValue();
2187 if (need_immediate_cb == bool_value) return;
2189 need_immediate_cb = bool_value;
2191 if (need_immediate_cb) {
2192 uv_check_start(&check_immediate_watcher, node::CheckImmediate);
2193 // idle handle is needed only to maintain event loop
2194 uv_idle_start(&idle_immediate_dummy, node::IdleImmediateDummy);
2196 uv_check_stop(&check_immediate_watcher);
2197 uv_idle_stop(&idle_immediate_dummy);
2202 Handle<Object> SetupProcessObject(int argc, char *argv[]) {
2203 HandleScope scope(node_isolate);
2207 Local<FunctionTemplate> process_template = FunctionTemplate::New();
2208 process_template->SetClassName(String::New("process"));
2210 Local<Object> process = process_template->GetFunction()->NewInstance();
2211 assert(process.IsEmpty() == false);
2212 assert(process->IsObject() == true);
2214 process_p.Reset(node_isolate, process);
2216 process->SetAccessor(String::New("title"),
2218 ProcessTitleSetter);
2221 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
2223 // process.moduleLoadList
2224 Local<Array> modules = Array::New();
2225 module_load_list.Reset(node_isolate, modules);
2226 process->Set(String::NewSymbol("moduleLoadList"), modules);
2229 Local<Object> versions = Object::New();
2230 process->Set(String::NewSymbol("versions"), versions);
2231 versions->Set(String::NewSymbol("http_parser"), String::New(
2232 NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR) "."
2233 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR)));
2234 // +1 to get rid of the leading 'v'
2235 versions->Set(String::NewSymbol("node"), String::New(NODE_VERSION+1));
2236 versions->Set(String::NewSymbol("v8"), String::New(V8::GetVersion()));
2237 versions->Set(String::NewSymbol("ares"), String::New(ARES_VERSION_STR));
2238 versions->Set(String::NewSymbol("uv"), String::New(uv_version_string()));
2239 versions->Set(String::NewSymbol("zlib"), String::New(ZLIB_VERSION));
2240 versions->Set(String::NewSymbol("modules"),
2241 String::New(NODE_STRINGIFY(NODE_MODULE_VERSION)));
2243 // Stupid code to slice out the version string.
2244 int c, l = strlen(OPENSSL_VERSION_TEXT);
2245 for (i = j = 0; i < l; i++) {
2246 c = OPENSSL_VERSION_TEXT[i];
2247 if ('0' <= c && c <= '9') {
2248 for (j = i + 1; j < l; j++) {
2249 c = OPENSSL_VERSION_TEXT[j];
2250 if (c == ' ') break;
2255 versions->Set(String::NewSymbol("openssl"),
2256 String::New(&OPENSSL_VERSION_TEXT[i], j - i));
2262 process->Set(String::NewSymbol("arch"), String::New(ARCH));
2265 process->Set(String::NewSymbol("platform"), String::New(PLATFORM));
2268 Local<Array> arguments = Array::New(argc - option_end_index + 1);
2269 arguments->Set(Integer::New(0, node_isolate), String::New(argv[0]));
2270 for (j = 1, i = option_end_index; i < argc; j++, i++) {
2271 Local<String> arg = String::New(argv[i]);
2272 arguments->Set(Integer::New(j, node_isolate), arg);
2275 process->Set(String::NewSymbol("argv"), arguments);
2278 Local<Array> execArgv = Array::New(option_end_index - 1);
2279 for (j = 1, i = 0; j < option_end_index; j++, i++) {
2280 execArgv->Set(Integer::New(i, node_isolate), String::New(argv[j]));
2283 process->Set(String::NewSymbol("execArgv"), execArgv);
2286 // create process.env
2287 Local<ObjectTemplate> envTemplate = ObjectTemplate::New();
2288 envTemplate->SetNamedPropertyHandler(EnvGetter,
2294 Local<Object> env = envTemplate->NewInstance();
2295 process->Set(String::NewSymbol("env"), env);
2297 process->Set(String::NewSymbol("pid"), Integer::New(getpid(), node_isolate));
2298 process->Set(String::NewSymbol("features"), GetFeatures());
2299 process->SetAccessor(String::New("_needImmediateCallback"),
2300 NeedImmediateCallbackGetter,
2301 NeedImmediateCallbackSetter);
2305 process->Set(String::NewSymbol("_eval"), String::New(eval_string));
2310 process->Set(String::NewSymbol("_print_eval"), True(node_isolate));
2313 // -i, --interactive
2315 process->Set(String::NewSymbol("_forceRepl"), True(node_isolate));
2319 if (no_deprecation) {
2320 process->Set(String::NewSymbol("noDeprecation"), True(node_isolate));
2323 // --throw-deprecation
2324 if (throw_deprecation) {
2325 process->Set(String::NewSymbol("throwDeprecation"), True(node_isolate));
2328 // --trace-deprecation
2329 if (trace_deprecation) {
2330 process->Set(String::NewSymbol("traceDeprecation"), True(node_isolate));
2333 size_t size = 2*PATH_MAX;
2334 char* execPath = new char[size];
2335 if (uv_exepath(execPath, &size) != 0) {
2336 // as a last ditch effort, fallback on argv[0] ?
2337 process->Set(String::NewSymbol("execPath"), String::New(argv[0]));
2339 process->Set(String::NewSymbol("execPath"), String::New(execPath, size));
2343 process->SetAccessor(String::New("debugPort"),
2348 // define various internal methods
2349 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2350 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2351 NODE_SET_METHOD(process, "reallyExit", Exit);
2352 NODE_SET_METHOD(process, "abort", Abort);
2353 NODE_SET_METHOD(process, "chdir", Chdir);
2354 NODE_SET_METHOD(process, "cwd", Cwd);
2356 NODE_SET_METHOD(process, "umask", Umask);
2358 #if defined(__POSIX__) && !defined(__ANDROID__)
2359 NODE_SET_METHOD(process, "getuid", GetUid);
2360 NODE_SET_METHOD(process, "setuid", SetUid);
2362 NODE_SET_METHOD(process, "setgid", SetGid);
2363 NODE_SET_METHOD(process, "getgid", GetGid);
2365 NODE_SET_METHOD(process, "getgroups", GetGroups);
2366 NODE_SET_METHOD(process, "setgroups", SetGroups);
2367 NODE_SET_METHOD(process, "initgroups", InitGroups);
2368 #endif // __POSIX__ && !defined(__ANDROID__)
2370 NODE_SET_METHOD(process, "_kill", Kill);
2372 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2373 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2374 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2376 NODE_SET_METHOD(process, "hrtime", Hrtime);
2378 NODE_SET_METHOD(process, "dlopen", DLOpen);
2380 NODE_SET_METHOD(process, "uptime", Uptime);
2381 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2383 NODE_SET_METHOD(process, "binding", Binding);
2385 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2387 // values use to cross communicate with processNextTick
2388 Local<Object> info_box = Object::New();
2389 info_box->SetIndexedPropertiesToExternalArrayData(&tick_infobox,
2390 kExternalUnsignedIntArray,
2392 process->Set(String::NewSymbol("_tickInfoBox"), info_box);
2394 // pre-set _events object for faster emit checks
2395 process->Set(String::NewSymbol("_events"), Object::New());
2397 return scope.Close(process);
2401 static void AtExit() {
2402 uv_tty_reset_mode();
2406 static void SignalExit(int signal) {
2407 uv_tty_reset_mode();
2408 _exit(128 + signal);
2412 void Load(Handle<Object> process_l) {
2413 HandleScope handle_scope(node_isolate);
2415 process_symbol = String::New("process");
2416 domain_symbol = String::New("domain");
2418 // Compile, execute the src/node.js file. (Which was included as static C
2419 // string in node_natives.h. 'natve_node' is the string containing that
2422 // The node.js file returns a function 'f'
2427 // Disable verbose mode to stop FatalException() handler from trying
2428 // to handle the exception. Errors this early in the start-up phase
2429 // are not safe to ignore.
2430 try_catch.SetVerbose(false);
2432 Local<Value> f_value = ExecuteString(MainSource(), String::New("node.js"));
2433 if (try_catch.HasCaught()) {
2434 ReportException(try_catch);
2437 assert(f_value->IsFunction());
2438 Local<Function> f = Local<Function>::Cast(f_value);
2440 // Now we call 'f' with the 'process' variable that we've built up with
2441 // all our bindings. Inside node.js we'll take care of assigning things to
2444 // We start the process this way in order to be more modular. Developers
2445 // who do not like how 'src/node.js' setups the module system but do like
2446 // Node's I/O bindings may want to replace 'f' with their own function.
2448 // Add a reference to the global object
2449 Local<Object> global = v8::Context::GetCurrent()->Global();
2451 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2455 #if defined HAVE_PERFCTR
2456 InitPerfCounters(global);
2459 // Enable handling of uncaught exceptions
2460 // (FatalException(), break on uncaught exception in debugger)
2462 // This is not strictly necessary since it's almost impossible
2463 // to attach the debugger fast enought to break on exception
2464 // thrown during process startup.
2465 try_catch.SetVerbose(true);
2467 Local<Value> arg = process_l;
2468 f->Call(global, 1, &arg);
2471 static void PrintHelp();
2473 static void ParseDebugOpt(const char* arg) {
2476 if (strstr(arg, "--debug-port=") == arg) {
2477 p = 1 + strchr(arg, '=');
2478 debug_port = atoi(p);
2480 use_debug_agent = true;
2481 if (!strcmp(arg, "--debug-brk")) {
2482 debug_wait_connect = true;
2484 } else if (!strcmp(arg, "--debug")) {
2486 } else if (strstr(arg, "--debug-brk=") == arg) {
2487 debug_wait_connect = true;
2488 p = 1 + strchr(arg, '=');
2489 debug_port = atoi(p);
2490 } else if (strstr(arg, "--debug=") == arg) {
2491 p = 1 + strchr(arg, '=');
2492 debug_port = atoi(p);
2495 if (p && debug_port > 1024 && debug_port < 65536)
2498 fprintf(stderr, "Bad debug option.\n");
2499 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2505 static void PrintHelp() {
2506 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2507 " node debug script.js [arguments] \n"
2510 " -v, --version print node's version\n"
2511 " -e, --eval script evaluate script\n"
2512 " -p, --print evaluate script and print result\n"
2513 " -i, --interactive always enter the REPL even if stdin\n"
2514 " does not appear to be a terminal\n"
2515 " --no-deprecation silence deprecation warnings\n"
2516 " --trace-deprecation show stack traces on deprecations\n"
2517 " --v8-options print v8 command line options\n"
2518 " --max-stack-size=val set max v8 stack size (bytes)\n"
2520 "Environment variables:\n"
2522 "NODE_PATH ';'-separated list of directories\n"
2524 "NODE_PATH ':'-separated list of directories\n"
2526 " prefixed to the module search path.\n"
2527 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2528 " global contexts.\n"
2529 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2531 "Documentation can be found at http://nodejs.org/\n");
2535 // Parse node command line arguments.
2536 static void ParseArgs(int argc, char **argv) {
2539 // TODO(bnoordhuis) use parse opts
2540 for (i = 1; i < argc; i++) {
2541 const char *arg = argv[i];
2542 if (strstr(arg, "--debug") == arg) {
2544 argv[i] = const_cast<char*>("");
2545 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2546 printf("%s\n", NODE_VERSION);
2548 } else if (strstr(arg, "--max-stack-size=") == arg) {
2550 p = 1 + strchr(arg, '=');
2551 max_stack_size = atoi(p);
2552 argv[i] = const_cast<char*>("");
2553 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2556 } else if (strcmp(arg, "--eval") == 0 ||
2557 strcmp(arg, "-e") == 0 ||
2558 strcmp(arg, "--print") == 0 ||
2559 strcmp(arg, "-pe") == 0 ||
2560 strcmp(arg, "-p") == 0) {
2561 bool is_eval = strchr(arg, 'e') != NULL;
2562 bool is_print = strchr(arg, 'p') != NULL;
2564 // argument to -p and --print is optional
2565 if (is_eval == true && i + 1 >= argc) {
2566 fprintf(stderr, "Error: %s requires an argument\n", arg);
2570 print_eval = print_eval || is_print;
2571 argv[i] = const_cast<char*>("");
2573 // --eval, -e and -pe always require an argument
2574 if (is_eval == true) {
2575 eval_string = argv[++i];
2579 // next arg is the expression to evaluate unless it starts with:
2580 // - a dash, then it's another switch
2581 // - "\\-", then it's an escaped expression, drop the backslash
2582 if (argv[i + 1] == NULL) continue;
2583 if (argv[i + 1][0] == '-') continue;
2584 eval_string = argv[++i];
2585 if (strncmp(eval_string, "\\-", 2) == 0) ++eval_string;
2586 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2588 argv[i] = const_cast<char*>("");
2589 } else if (strcmp(arg, "--v8-options") == 0) {
2590 argv[i] = const_cast<char*>("--help");
2591 } else if (strcmp(arg, "--no-deprecation") == 0) {
2592 argv[i] = const_cast<char*>("");
2593 no_deprecation = true;
2594 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2595 argv[i] = const_cast<char*>("");
2596 trace_deprecation = true;
2597 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2598 argv[i] = const_cast<char*>("");
2599 throw_deprecation = true;
2600 } else if (argv[i][0] != '-') {
2605 option_end_index = i;
2609 // Called from the main thread.
2610 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2611 v8::Debug::ProcessDebugMessages();
2615 // Called from V8 Debug Agent TCP thread.
2616 static void DispatchMessagesDebugAgentCallback() {
2617 uv_async_send(&dispatch_debug_messages_async);
2621 // Called from the main thread
2622 static void EmitDebugEnabledAsyncCallback(uv_async_t* handle, int status) {
2623 HandleScope handle_scope(node_isolate);
2624 Local<Object> obj = Object::New();
2625 obj->Set(String::New("cmd"), String::New("NODE_DEBUG_ENABLED"));
2626 Local<Value> args[] = { String::New("internalMessage"), obj };
2627 MakeCallback(process_p, "emit", ARRAY_SIZE(args), args);
2631 // Called from the signal watcher callback
2632 static void EmitDebugEnabled() {
2633 uv_async_send(&emit_debug_enabled_async);
2637 static void EnableDebug(bool wait_connect) {
2638 // If we're called from another thread, make sure to enter the right
2640 node_isolate->Enter();
2642 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2645 // Start the debug thread and it's associated TCP server on port 5858.
2646 bool r = v8::Debug::EnableAgent("node " NODE_VERSION,
2650 // Crappy check that everything went well. FIXME
2653 // Print out some information.
2654 fprintf(stderr, "debugger listening on port %d\n", debug_port);
2657 debugger_running = true;
2659 // Do not emit NODE_DEBUG_ENABLED when debugger is enabled before starting
2660 // the main process (i.e. when called via `node --debug`)
2661 if (!process_p.IsEmpty())
2664 node_isolate->Exit();
2669 static void EnableDebugSignalHandler(uv_signal_t* handle, int) {
2670 // Break once process will return execution to v8
2671 v8::Debug::DebugBreak(node_isolate);
2673 if (!debugger_running) {
2674 fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n");
2680 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2681 struct sigaction sa;
2683 memset(&sa, 0, sizeof(sa));
2684 sa.sa_handler = handler;
2685 sigfillset(&sa.sa_mask);
2686 sigaction(signal, &sa, NULL);
2690 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2691 HandleScope scope(node_isolate);
2693 if (args.Length() != 1) {
2694 return ThrowError("Invalid number of arguments.");
2700 pid = args[0]->IntegerValue();
2701 r = kill(pid, SIGUSR1);
2703 return ThrowErrnoException(errno, "kill");
2710 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2711 // Break once process will return execution to v8
2712 if (!debugger_running) {
2713 for (int i = 0; i < 1; i++) {
2714 fprintf(stderr, "Starting debugger agent.\r\n");
2720 v8::Debug::DebugBreak(node_isolate);
2726 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2728 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2732 static int RegisterDebugSignalHandler() {
2733 wchar_t mapping_name[32];
2734 HANDLE mapping_handle;
2736 LPTHREAD_START_ROUTINE* handler;
2738 pid = GetCurrentProcessId();
2740 if (GetDebugSignalHandlerMappingName(pid,
2742 ARRAY_SIZE(mapping_name)) < 0) {
2746 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2752 if (mapping_handle == NULL) {
2756 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2757 MapViewOfFile(mapping_handle,
2758 FILE_MAP_ALL_ACCESS,
2762 if (handler == NULL) {
2763 CloseHandle(mapping_handle);
2767 *handler = EnableDebugThreadProc;
2769 UnmapViewOfFile(static_cast<void*>(handler));
2775 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2776 HandleScope scope(node_isolate);
2778 HANDLE process = NULL;
2779 HANDLE thread = NULL;
2780 HANDLE mapping = NULL;
2781 wchar_t mapping_name[32];
2782 LPTHREAD_START_ROUTINE* handler = NULL;
2784 if (args.Length() != 1) {
2785 ThrowError("Invalid number of arguments.");
2789 pid = (DWORD) args[0]->IntegerValue();
2791 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2792 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2796 if (process == NULL) {
2797 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2801 if (GetDebugSignalHandlerMappingName(pid,
2803 ARRAY_SIZE(mapping_name)) < 0) {
2804 ThrowErrnoException(errno, "sprintf");
2808 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2809 if (mapping == NULL) {
2810 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
2814 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2815 MapViewOfFile(mapping,
2820 if (handler == NULL || *handler == NULL) {
2821 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
2825 thread = CreateRemoteThread(process,
2832 if (thread == NULL) {
2833 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
2837 // Wait for the thread to terminate
2838 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
2839 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
2844 if (process != NULL)
2845 CloseHandle(process);
2847 CloseHandle(thread);
2848 if (handler != NULL)
2849 UnmapViewOfFile(handler);
2850 if (mapping != NULL)
2851 CloseHandle(mapping);
2856 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
2857 v8::Debug::DebugBreak(node_isolate);
2861 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
2862 if (debugger_running) {
2863 v8::Debug::DisableAgent();
2864 debugger_running = false;
2869 char** Init(int argc, char *argv[]) {
2870 // Initialize prog_start_time to get relative uptime.
2871 uv_uptime(&prog_start_time);
2873 // Make inherited handles noninheritable.
2874 uv_disable_stdio_inheritance();
2876 // init async debug messages dispatching
2877 uv_async_init(uv_default_loop(),
2878 &dispatch_debug_messages_async,
2879 DispatchDebugMessagesAsyncCallback);
2880 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
2882 // init async NODE_DEBUG_ENABLED emitter
2883 uv_async_init(uv_default_loop(),
2884 &emit_debug_enabled_async,
2885 EmitDebugEnabledAsyncCallback);
2886 uv_unref(reinterpret_cast<uv_handle_t*>(&emit_debug_enabled_async));
2888 // Parse a few arguments which are specific to Node.
2889 node::ParseArgs(argc, argv);
2890 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
2891 // in the command line))
2892 int v8argc = option_end_index;
2893 char **v8argv = argv;
2895 if (debug_wait_connect) {
2896 // v8argv is a copy of argv up to the script file argument +2 if --debug-brk
2897 // to expose the v8 debugger js object so that node.js can set
2898 // a breakpoint on the first line of the startup script
2900 v8argv = new char*[v8argc];
2901 memcpy(v8argv, argv, sizeof(*argv) * option_end_index);
2902 v8argv[option_end_index] = const_cast<char*>("--expose_debug_as");
2903 v8argv[option_end_index + 1] = const_cast<char*>("v8debug");
2906 // For the normal stack which moves from high to low addresses when frames
2907 // are pushed, we can compute the limit as stack_size bytes below the
2908 // the address of a stack variable (e.g. &stack_var) as an approximation
2909 // of the start of the stack (we're assuming that we haven't pushed a lot
2911 if (max_stack_size != 0) {
2913 ResourceConstraints constraints;
2915 uint32_t *stack_limit = &stack_var - (max_stack_size / sizeof(uint32_t));
2916 constraints.set_stack_limit(stack_limit);
2917 SetResourceConstraints(&constraints); // Must be done before V8::Initialize
2919 V8::SetFlagsFromCommandLine(&v8argc, v8argv, false);
2921 const char typed_arrays_flag[] = "--harmony_typed_arrays";
2922 V8::SetFlagsFromString(typed_arrays_flag, sizeof(typed_arrays_flag) - 1);
2923 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
2925 // Fetch a reference to the main isolate, so we have a reference to it
2926 // even when we need it to access it from another (debugger) thread.
2927 node_isolate = Isolate::GetCurrent();
2931 RegisterSignalHandler(SIGPIPE, SIG_IGN);
2932 RegisterSignalHandler(SIGINT, SignalExit);
2933 RegisterSignalHandler(SIGTERM, SignalExit);
2936 uv_check_init(uv_default_loop(), &check_immediate_watcher);
2937 uv_unref(reinterpret_cast<uv_handle_t*>(&check_immediate_watcher));
2938 uv_idle_init(uv_default_loop(), &idle_immediate_dummy);
2940 V8::SetFatalErrorHandler(node::OnFatalError);
2941 V8::AddMessageListener(OnMessage);
2943 // If the --debug flag was specified then initialize the debug thread.
2944 if (use_debug_agent) {
2945 EnableDebug(debug_wait_connect);
2948 RegisterDebugSignalHandler();
2950 static uv_signal_t signal_watcher;
2951 uv_signal_init(uv_default_loop(), &signal_watcher);
2952 uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1);
2953 uv_unref(reinterpret_cast<uv_handle_t*>(&signal_watcher));
2961 struct AtExitCallback {
2962 AtExitCallback* next_;
2963 void (*cb_)(void* arg);
2967 static AtExitCallback* at_exit_functions_;
2971 AtExitCallback* p = at_exit_functions_;
2972 at_exit_functions_ = NULL;
2975 AtExitCallback* q = p->next_;
2983 void AtExit(void (*cb)(void* arg), void* arg) {
2984 AtExitCallback* p = new AtExitCallback;
2987 p->next_ = at_exit_functions_;
2988 at_exit_functions_ = p;
2992 void EmitExit(v8::Handle<v8::Object> process_l) {
2993 // process.emit('exit')
2994 process_l->Set(String::NewSymbol("_exiting"), True(node_isolate));
2995 Local<Value> args[] = { String::New("exit"), Integer::New(0, node_isolate) };
2996 MakeCallback(process_l, "emit", ARRAY_SIZE(args), args);
2999 static char **copy_argv(int argc, char **argv) {
3007 for (i = 0; i < argc; i++) {
3008 strlen_sum += strlen(argv[i]) + 1;
3011 argv_copy = static_cast<char**>(
3012 malloc(sizeof(*argv_copy) * (argc + 1) + strlen_sum));
3017 argv_data = reinterpret_cast<char*>(argv_copy) +
3018 sizeof(*argv_copy) * (argc + 1);
3020 for (i = 0; i < argc; i++) {
3021 argv_copy[i] = argv_data;
3022 len = strlen(argv[i]) + 1;
3023 memcpy(argv_data, argv[i], len);
3027 argv_copy[argc] = NULL;
3032 int Start(int argc, char *argv[]) {
3033 // Hack aroung with the argv pointer. Used for process.title = "blah".
3034 argv = uv_setup_args(argc, argv);
3036 // Logic to duplicate argv as Init() modifies arguments
3037 // that are passed into it.
3038 char **argv_copy = copy_argv(argc, argv);
3040 // This needs to run *before* V8::Initialize()
3041 // Use copy here as to not modify the original argv:
3042 Init(argc, argv_copy);
3046 Locker locker(node_isolate);
3047 HandleScope handle_scope(node_isolate);
3049 // Create the one and only Context.
3050 Local<Context> context = Context::New(node_isolate);
3051 Context::Scope context_scope(context);
3053 binding_cache.Reset(node_isolate, Object::New());
3055 // Use original argv, as we're just copying values out of it.
3056 Local<Object> process_l = SetupProcessObject(argc, argv);
3058 // Create all the objects, load modules, do everything.
3059 // so your next reading stop should be node::Load()!
3062 // All our arguments are loaded. We've evaluated all of the scripts. We
3063 // might even have created TCP servers. Now we enter the main eventloop. If
3064 // there are no watchers on the loop (except for the ones that were
3065 // uv_unref'd) then this function exits. As long as there are active
3066 // watchers, it blocks.
3067 uv_run(uv_default_loop(), UV_RUN_DEFAULT);
3069 EmitExit(process_l);
3074 // Clean up. Not strictly necessary.
3078 // Clean up the copy: