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"));
913 if (!tdc_v->IsFunction()) {
914 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
917 Local<Function> tdc = tdc_v.As<Function>();
918 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"), tdc);
919 process_tickCallback.Reset(node_isolate, tdc);
924 MakeDomainCallback(const Handle<Object> object,
925 const Handle<Function> callback,
927 Handle<Value> argv[]) {
928 // TODO(trevnorris) Hook for long stack traces to be made here.
930 // lazy load domain specific symbols
931 if (enter_symbol.IsEmpty()) {
932 enter_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "enter");
933 exit_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "exit");
934 disposed_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "_disposed");
937 Local<Value> domain_v = object->Get(domain_symbol);
938 Local<Object> domain;
939 Local<Function> enter;
940 Local<Function> exit;
943 try_catch.SetVerbose(true);
945 bool has_domain = domain_v->IsObject();
947 domain = domain_v->ToObject();
948 assert(!domain.IsEmpty());
949 if (domain->Get(disposed_symbol)->IsTrue()) {
950 // domain has been disposed of.
951 return Undefined(node_isolate);
953 enter = Local<Function>::Cast(domain->Get(enter_symbol));
954 assert(!enter.IsEmpty());
955 enter->Call(domain, 0, NULL);
957 if (try_catch.HasCaught()) {
958 return Undefined(node_isolate);
962 Local<Value> ret = callback->Call(object, argc, argv);
964 if (try_catch.HasCaught()) {
965 return Undefined(node_isolate);
969 exit = Local<Function>::Cast(domain->Get(exit_symbol));
970 assert(!exit.IsEmpty());
971 exit->Call(domain, 0, NULL);
973 if (try_catch.HasCaught()) {
974 return Undefined(node_isolate);
978 if (tick_infobox.last_threw == 1) {
979 tick_infobox.last_threw = 0;
983 if (tick_infobox.in_tick == 1) {
987 if (tick_infobox.length == 0) {
988 tick_infobox.index = 0;
992 // process nextTicks after call
993 Local<Object> process = PersistentToLocal(node_isolate, process_p);
994 Local<Function> fn = PersistentToLocal(node_isolate, process_tickCallback);
995 fn->Call(process, 0, NULL);
997 if (try_catch.HasCaught()) {
998 return Undefined(node_isolate);
1006 MakeCallback(const Handle<Object> object,
1007 const Handle<Function> callback,
1009 Handle<Value> argv[]) {
1010 // TODO(trevnorris) Hook for long stack traces to be made here.
1011 Local<Object> process = PersistentToLocal(node_isolate, process_p);
1014 return MakeDomainCallback(object, callback, argc, argv);
1016 // lazy load no domain next tick callbacks
1017 if (process_tickCallback.IsEmpty()) {
1019 process->Get(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"));
1020 if (!cb_v->IsFunction()) {
1021 fprintf(stderr, "process._tickCallback assigned to non-function\n");
1024 process_tickCallback.Reset(node_isolate, cb_v.As<Function>());
1028 try_catch.SetVerbose(true);
1030 Local<Value> ret = callback->Call(object, argc, argv);
1032 if (try_catch.HasCaught()) {
1033 return Undefined(node_isolate);
1036 if (tick_infobox.in_tick == 1) {
1040 if (tick_infobox.length == 0) {
1041 tick_infobox.index = 0;
1045 // process nextTicks after call
1046 Local<Function> fn = PersistentToLocal(node_isolate, process_tickCallback);
1047 fn->Call(process, 0, NULL);
1049 if (try_catch.HasCaught()) {
1050 return Undefined(node_isolate);
1058 MakeCallback(const Handle<Object> object,
1059 const Handle<String> symbol,
1061 Handle<Value> argv[]) {
1062 HandleScope scope(node_isolate);
1064 Local<Function> callback = object->Get(symbol).As<Function>();
1065 assert(callback->IsFunction());
1068 return scope.Close(MakeDomainCallback(object, callback, argc, argv));
1069 return scope.Close(MakeCallback(object, callback, argc, argv));
1074 MakeCallback(const Handle<Object> object,
1077 Handle<Value> argv[]) {
1078 HandleScope scope(node_isolate);
1080 Local<String> method_string = OneByteString(node_isolate, method);
1081 Handle<Value> ret = MakeCallback(object, method_string, argc, argv);
1083 return scope.Close(ret);
1087 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1088 HandleScope scope(node_isolate);
1090 if (!encoding_v->IsString()) return _default;
1092 String::Utf8Value encoding(encoding_v);
1094 if (strcasecmp(*encoding, "utf8") == 0) {
1096 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1098 } else if (strcasecmp(*encoding, "ascii") == 0) {
1100 } else if (strcasecmp(*encoding, "base64") == 0) {
1102 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1104 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1106 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1108 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1110 } else if (strcasecmp(*encoding, "binary") == 0) {
1112 } else if (strcasecmp(*encoding, "buffer") == 0) {
1114 } else if (strcasecmp(*encoding, "hex") == 0) {
1116 } else if (strcasecmp(*encoding, "raw") == 0) {
1117 if (!no_deprecation) {
1118 fprintf(stderr, "'raw' (array of integers) has been removed. "
1122 } else if (strcasecmp(*encoding, "raws") == 0) {
1123 if (!no_deprecation) {
1124 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1125 "Please update your code.\n");
1133 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1134 return StringBytes::Encode(static_cast<const char*>(buf),
1139 // Returns -1 if the handle was not valid for decoding
1140 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1141 HandleScope scope(node_isolate);
1143 if (val->IsArray()) {
1144 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1150 return StringBytes::Size(val, encoding);
1154 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1157 // Returns number of bytes written.
1158 ssize_t DecodeWrite(char *buf,
1160 v8::Handle<v8::Value> val,
1161 enum encoding encoding) {
1162 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1165 void DisplayExceptionLine(Handle<Message> message) {
1166 // Prevent re-entry into this function. For example, if there is
1167 // a throw from a program in vm.runInThisContext(code, filename, true),
1168 // then we want to show the original failure, not the secondary one.
1169 static bool displayed_error = false;
1171 if (displayed_error) return;
1172 displayed_error = true;
1174 uv_tty_reset_mode();
1176 fprintf(stderr, "\n");
1178 if (!message.IsEmpty()) {
1179 // Print (filename):(line number): (message).
1180 String::Utf8Value filename(message->GetScriptResourceName());
1181 const char* filename_string = *filename;
1182 int linenum = message->GetLineNumber();
1183 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1184 // Print line of source code.
1185 String::Utf8Value sourceline(message->GetSourceLine());
1186 const char* sourceline_string = *sourceline;
1188 // Because of how node modules work, all scripts are wrapped with a
1189 // "function (module, exports, __filename, ...) {"
1190 // to provide script local variables.
1192 // When reporting errors on the first line of a script, this wrapper
1193 // function is leaked to the user. There used to be a hack here to
1194 // truncate off the first 62 characters, but it caused numerous other
1195 // problems when vm.runIn*Context() methods were used for non-module
1198 // If we ever decide to re-instate such a hack, the following steps
1201 // 1. Pass a flag around to say "this code was wrapped"
1202 // 2. Update the stack frame output so that it is also correct.
1204 // It would probably be simpler to add a line rather than add some
1205 // number of characters to the first line, since V8 truncates the
1206 // sourceline to 78 characters, and we end up not providing very much
1207 // useful debugging info to the user if we remove 62 characters.
1209 int start = message->GetStartColumn();
1210 int end = message->GetEndColumn();
1212 fprintf(stderr, "%s\n", sourceline_string);
1213 // Print wavy underline (GetUnderline is deprecated).
1214 for (int i = 0; i < start; i++) {
1215 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1217 for (int i = start; i < end; i++) {
1220 fputc('\n', stderr);
1225 static void ReportException(Handle<Value> er, Handle<Message> message) {
1226 HandleScope scope(node_isolate);
1228 DisplayExceptionLine(message);
1230 Local<Value> trace_value(
1231 er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack")));
1232 String::Utf8Value trace(trace_value);
1234 // range errors have a trace member set to undefined
1235 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1236 fprintf(stderr, "%s\n", *trace);
1238 // this really only happens for RangeErrors, since they're the only
1239 // kind that won't have all this info in the trace, or when non-Error
1240 // objects are thrown manually.
1241 Local<Value> message;
1244 if (er->IsObject()) {
1245 Local<Object> err_obj = er.As<Object>();
1246 message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1247 name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1250 if (message.IsEmpty() ||
1251 message->IsUndefined() ||
1253 name->IsUndefined()) {
1254 // Not an error object. Just print as-is.
1255 String::Utf8Value message(er);
1256 fprintf(stderr, "%s\n", *message);
1258 String::Utf8Value name_string(name);
1259 String::Utf8Value message_string(message);
1260 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1268 static void ReportException(const TryCatch& try_catch) {
1269 ReportException(try_catch.Exception(), try_catch.Message());
1273 // Executes a str within the current v8 context.
1274 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1275 HandleScope scope(node_isolate);
1278 // try_catch must be nonverbose to disable FatalException() handler,
1279 // we will handle exceptions ourself.
1280 try_catch.SetVerbose(false);
1282 Local<v8::Script> script = v8::Script::Compile(source, filename);
1283 if (script.IsEmpty()) {
1284 ReportException(try_catch);
1288 Local<Value> result = script->Run();
1289 if (result.IsEmpty()) {
1290 ReportException(try_catch);
1294 return scope.Close(result);
1298 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1299 HandleScope scope(node_isolate);
1301 Local<Array> ary = Array::New();
1305 QUEUE_FOREACH(q, &req_wrap_queue) {
1306 ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1307 if (w->persistent().IsEmpty()) continue;
1308 ary->Set(i++, w->object());
1311 args.GetReturnValue().Set(ary);
1315 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1316 // implemented here for consistency with GetActiveRequests().
1317 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1318 HandleScope scope(node_isolate);
1320 Local<Array> ary = Array::New();
1324 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1326 QUEUE_FOREACH(q, &handle_wrap_queue) {
1327 HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1328 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue;
1329 Local<Object> object = w->object();
1330 Local<Value> owner = object->Get(owner_sym);
1331 if (owner->IsUndefined()) owner = object;
1332 ary->Set(i++, owner);
1335 args.GetReturnValue().Set(ary);
1339 static void Abort(const FunctionCallbackInfo<Value>& args) {
1344 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1345 HandleScope scope(node_isolate);
1347 if (args.Length() != 1 || !args[0]->IsString()) {
1348 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1351 String::Utf8Value path(args[0]);
1352 int err = uv_chdir(*path);
1354 return ThrowUVException(err, "uv_chdir");
1359 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1360 HandleScope scope(node_isolate);
1362 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1363 char buf[MAX_PATH * 4 + 1];
1365 char buf[PATH_MAX + 1];
1368 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1370 return ThrowUVException(err, "uv_cwd");
1373 buf[ARRAY_SIZE(buf) - 1] = '\0';
1374 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1376 args.GetReturnValue().Set(cwd);
1380 static void Umask(const FunctionCallbackInfo<Value>& args) {
1381 HandleScope scope(node_isolate);
1384 if (args.Length() < 1 || args[0]->IsUndefined()) {
1386 umask(static_cast<mode_t>(old));
1387 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1388 return ThrowTypeError("argument must be an integer or octal string.");
1391 if (args[0]->IsInt32()) {
1392 oct = args[0]->Uint32Value();
1395 String::Utf8Value str(args[0]);
1397 // Parse the octal string.
1398 for (int i = 0; i < str.length(); i++) {
1400 if (c > '7' || c < '0') {
1401 return ThrowTypeError("invalid octal string");
1407 old = umask(static_cast<mode_t>(oct));
1410 args.GetReturnValue().Set(old);
1414 #if defined(__POSIX__) && !defined(__ANDROID__)
1416 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1417 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1420 static uid_t uid_by_name(const char* name) {
1428 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1432 return uid_not_found;
1436 static char* name_by_uid(uid_t uid) {
1445 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1446 return strdup(pp->pw_name);
1457 static gid_t gid_by_name(const char* name) {
1465 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1469 return gid_not_found;
1473 #if 0 // For future use.
1474 static const char* name_by_gid(gid_t gid) {
1483 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1484 return strdup(pp->gr_name);
1496 static uid_t uid_by_name(Handle<Value> value) {
1497 if (value->IsUint32()) {
1498 return static_cast<uid_t>(value->Uint32Value());
1500 String::Utf8Value name(value);
1501 return uid_by_name(*name);
1506 static gid_t gid_by_name(Handle<Value> value) {
1507 if (value->IsUint32()) {
1508 return static_cast<gid_t>(value->Uint32Value());
1510 String::Utf8Value name(value);
1511 return gid_by_name(*name);
1516 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1517 args.GetReturnValue().Set(getuid());
1521 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1522 args.GetReturnValue().Set(getgid());
1526 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1527 HandleScope scope(node_isolate);
1529 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1530 return ThrowTypeError("setgid argument must be a number or a string");
1533 gid_t gid = gid_by_name(args[0]);
1535 if (gid == gid_not_found) {
1536 return ThrowError("setgid group id does not exist");
1540 return ThrowErrnoException(errno, "setgid");
1545 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1546 HandleScope scope(node_isolate);
1548 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1549 return ThrowTypeError("setuid argument must be a number or a string");
1552 uid_t uid = uid_by_name(args[0]);
1554 if (uid == uid_not_found) {
1555 return ThrowError("setuid user id does not exist");
1559 return ThrowErrnoException(errno, "setuid");
1564 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1565 HandleScope scope(node_isolate);
1567 int ngroups = getgroups(0, NULL);
1569 if (ngroups == -1) {
1570 return ThrowErrnoException(errno, "getgroups");
1573 gid_t* groups = new gid_t[ngroups];
1575 ngroups = getgroups(ngroups, groups);
1577 if (ngroups == -1) {
1579 return ThrowErrnoException(errno, "getgroups");
1582 Local<Array> groups_list = Array::New(ngroups);
1583 bool seen_egid = false;
1584 gid_t egid = getegid();
1586 for (int i = 0; i < ngroups; i++) {
1587 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1588 if (groups[i] == egid) seen_egid = true;
1593 if (seen_egid == false) {
1594 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1597 args.GetReturnValue().Set(groups_list);
1601 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1602 HandleScope scope(node_isolate);
1604 if (!args[0]->IsArray()) {
1605 return ThrowTypeError("argument 1 must be an array");
1608 Local<Array> groups_list = args[0].As<Array>();
1609 size_t size = groups_list->Length();
1610 gid_t* groups = new gid_t[size];
1612 for (size_t i = 0; i < size; i++) {
1613 gid_t gid = gid_by_name(groups_list->Get(i));
1615 if (gid == gid_not_found) {
1617 return ThrowError("group name not found");
1623 int rc = setgroups(size, groups);
1627 return ThrowErrnoException(errno, "setgroups");
1632 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1633 HandleScope scope(node_isolate);
1635 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1636 return ThrowTypeError("argument 1 must be a number or a string");
1639 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1640 return ThrowTypeError("argument 2 must be a number or a string");
1643 String::Utf8Value arg0(args[0]);
1648 if (args[0]->IsUint32()) {
1649 user = name_by_uid(args[0]->Uint32Value());
1657 return ThrowError("initgroups user not found");
1660 extra_group = gid_by_name(args[1]);
1662 if (extra_group == gid_not_found) {
1663 if (must_free) free(user);
1664 return ThrowError("initgroups extra group not found");
1667 int rc = initgroups(user, extra_group);
1674 return ThrowErrnoException(errno, "initgroups");
1678 #endif // __POSIX__ && !defined(__ANDROID__)
1681 void Exit(const FunctionCallbackInfo<Value>& args) {
1682 HandleScope scope(node_isolate);
1683 exit(args[0]->IntegerValue());
1687 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1688 HandleScope scope(node_isolate);
1690 if (uv_uptime(&uptime)) return;
1691 args.GetReturnValue().Set(uptime - prog_start_time);
1695 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1696 HandleScope scope(node_isolate);
1700 int err = uv_resident_set_memory(&rss);
1702 return ThrowUVException(err, "uv_resident_set_memory");
1705 Local<Object> info = Object::New();
1707 if (rss_symbol.IsEmpty()) {
1708 rss_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "rss");
1709 heap_total_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "heapTotal");
1710 heap_used_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "heapUsed");
1713 info->Set(rss_symbol, Number::New(rss));
1716 HeapStatistics v8_heap_stats;
1717 node_isolate->GetHeapStatistics(&v8_heap_stats);
1718 info->Set(heap_total_symbol,
1719 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(),
1721 info->Set(heap_used_symbol,
1722 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(),
1725 args.GetReturnValue().Set(info);
1729 void Kill(const FunctionCallbackInfo<Value>& args) {
1730 HandleScope scope(node_isolate);
1732 if (args.Length() != 2) {
1733 return ThrowError("Bad argument.");
1736 int pid = args[0]->IntegerValue();
1737 int sig = args[1]->Int32Value();
1738 int err = uv_kill(pid, sig);
1739 args.GetReturnValue().Set(err);
1742 // used in Hrtime() below
1743 #define NANOS_PER_SEC 1000000000
1745 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1746 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1747 // so this function instead returns an Array with 2 entries representing seconds
1748 // and nanoseconds, to avoid any integer overflow possibility.
1749 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1750 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1751 HandleScope scope(node_isolate);
1753 uint64_t t = uv_hrtime();
1755 if (args.Length() > 0) {
1756 // return a time diff tuple
1757 if (!args[0]->IsArray()) {
1758 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1760 Local<Array> inArray = Local<Array>::Cast(args[0]);
1761 uint64_t seconds = inArray->Get(0)->Uint32Value();
1762 uint64_t nanos = inArray->Get(1)->Uint32Value();
1763 t -= (seconds * NANOS_PER_SEC) + nanos;
1766 Local<Array> tuple = Array::New(2);
1767 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1768 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1769 args.GetReturnValue().Set(tuple);
1773 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1775 // DLOpen is process.dlopen(module, filename).
1776 // Used to load 'module.node' dynamically shared objects.
1777 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1778 HandleScope scope(node_isolate);
1779 char symbol[1024], *base, *pos;
1783 if (args.Length() < 2) {
1784 return ThrowError("process.dlopen takes exactly 2 arguments.");
1787 Local<Object> module = args[0]->ToObject(); // Cast
1788 String::Utf8Value filename(args[1]); // Cast
1790 if (exports_symbol.IsEmpty()) {
1791 exports_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "exports");
1793 Local<Object> exports = module->Get(exports_symbol)->ToObject();
1795 if (uv_dlopen(*filename, &lib)) {
1796 Local<String> errmsg = OneByteString(node_isolate, uv_dlerror(&lib));
1798 // Windows needs to add the filename into the error message
1799 errmsg = String::Concat(errmsg, args[1]->ToString());
1801 ThrowException(Exception::Error(errmsg));
1805 String::Utf8Value path(args[1]);
1808 /* Find the shared library filename within the full path. */
1810 pos = strrchr(base, '/');
1816 pos = strpbrk(base, "\\/:");
1824 /* Strip the .node extension. */
1825 pos = strrchr(base, '.');
1830 /* Add the `_module` suffix to the extension name. */
1831 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1832 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1833 return ThrowError("Out of memory.");
1836 /* Replace dashes with underscores. When loading foo-bar.node,
1837 * look for foo_bar_module, not foo-bar_module.
1839 for (pos = symbol; *pos != '\0'; ++pos) {
1840 if (*pos == '-') *pos = '_';
1843 node_module_struct *mod;
1844 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1846 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1847 return ThrowError(errmsg);
1850 if (mod->version != NODE_MODULE_VERSION) {
1854 "Module version mismatch. Expected %d, got %d.",
1855 NODE_MODULE_VERSION, mod->version);
1856 return ThrowError(errmsg);
1859 // Execute the C++ module
1860 mod->register_func(exports, module);
1862 // Tell coverity that 'handle' should not be freed when we return.
1863 // coverity[leaked_storage]
1867 static void OnFatalError(const char* location, const char* message) {
1869 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1871 fprintf(stderr, "FATAL ERROR: %s\n", message);
1881 NO_RETURN void FatalError(const char* location, const char* message) {
1882 OnFatalError(location, message);
1883 // to supress compiler warning
1888 void FatalException(Handle<Value> error, Handle<Message> message) {
1889 HandleScope scope(node_isolate);
1891 if (fatal_exception_symbol.IsEmpty()) {
1892 fatal_exception_symbol =
1893 FIXED_ONE_BYTE_STRING(node_isolate, "_fatalException");
1896 Local<Object> process = PersistentToLocal(node_isolate, process_p);
1897 Local<Value> fatal_v = process->Get(fatal_exception_symbol);
1899 if (!fatal_v->IsFunction()) {
1900 // failed before the process._fatalException function was added!
1901 // this is probably pretty bad. Nothing to do but report and exit.
1902 ReportException(error, message);
1906 Local<Function> fatal_f = Local<Function>::Cast(fatal_v);
1908 TryCatch fatal_try_catch;
1910 // Do not call FatalException when _fatalException handler throws
1911 fatal_try_catch.SetVerbose(false);
1913 // this will return true if the JS layer handled it, false otherwise
1914 Local<Value> caught = fatal_f->Call(process, 1, &error);
1916 if (fatal_try_catch.HasCaught()) {
1917 // the fatal exception function threw, so we must exit
1918 ReportException(fatal_try_catch);
1922 if (false == caught->BooleanValue()) {
1923 ReportException(error, message);
1929 void FatalException(const TryCatch& try_catch) {
1930 HandleScope scope(node_isolate);
1931 // TODO(bajtos) do not call FatalException if try_catch is verbose
1932 // (requires V8 API to expose getter for try_catch.is_verbose_)
1933 FatalException(try_catch.Exception(), try_catch.Message());
1937 void OnMessage(Handle<Message> message, Handle<Value> error) {
1938 // The current version of V8 sends messages for errors only
1939 // (thus `error` is always set).
1940 FatalException(error, message);
1944 static void Binding(const FunctionCallbackInfo<Value>& args) {
1945 HandleScope scope(node_isolate);
1947 Local<String> module = args[0]->ToString();
1948 String::Utf8Value module_v(module);
1949 node_module_struct* modp;
1951 Local<Object> cache = PersistentToLocal(node_isolate, binding_cache);
1952 Local<Object> exports;
1954 if (cache->Has(module)) {
1955 exports = cache->Get(module)->ToObject();
1956 args.GetReturnValue().Set(exports);
1960 // Append a string to process.moduleLoadList
1962 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
1964 Local<Array> modules = PersistentToLocal(node_isolate, module_load_list);
1965 uint32_t l = modules->Length();
1966 modules->Set(l, OneByteString(node_isolate, buf));
1968 if ((modp = get_builtin_module(*module_v)) != NULL) {
1969 exports = Object::New();
1970 // Internal bindings don't have a "module" object,
1972 modp->register_func(exports, Undefined(node_isolate));
1973 cache->Set(module, exports);
1974 } else if (!strcmp(*module_v, "constants")) {
1975 exports = Object::New();
1976 DefineConstants(exports);
1977 cache->Set(module, exports);
1978 } else if (!strcmp(*module_v, "natives")) {
1979 exports = Object::New();
1980 DefineJavaScript(exports);
1981 cache->Set(module, exports);
1983 return ThrowError("No such module");
1986 args.GetReturnValue().Set(exports);
1990 static void ProcessTitleGetter(Local<String> property,
1991 const PropertyCallbackInfo<Value>& info) {
1992 HandleScope scope(node_isolate);
1994 uv_get_process_title(buffer, sizeof(buffer));
1995 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
1999 static void ProcessTitleSetter(Local<String> property,
2001 const PropertyCallbackInfo<void>& info) {
2002 HandleScope scope(node_isolate);
2003 String::Utf8Value title(value);
2004 // TODO(piscisaureus): protect with a lock
2005 uv_set_process_title(*title);
2009 static void EnvGetter(Local<String> property,
2010 const PropertyCallbackInfo<Value>& info) {
2011 HandleScope scope(node_isolate);
2013 String::Utf8Value key(property);
2014 const char* val = getenv(*key);
2016 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2019 String::Value key(property);
2020 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2021 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2023 ARRAY_SIZE(buffer));
2024 // If result >= sizeof buffer the buffer was too small. That should never
2025 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2027 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2028 result < ARRAY_SIZE(buffer)) {
2029 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2030 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2031 return info.GetReturnValue().Set(rc);
2034 // Not found. Fetch from prototype.
2035 info.GetReturnValue().Set(
2036 info.Data().As<Object>()->Get(property));
2040 static void EnvSetter(Local<String> property,
2042 const PropertyCallbackInfo<Value>& info) {
2043 HandleScope scope(node_isolate);
2045 String::Utf8Value key(property);
2046 String::Utf8Value val(value);
2047 setenv(*key, *val, 1);
2049 String::Value key(property);
2050 String::Value val(value);
2051 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2052 // Environment variables that start with '=' are read-only.
2053 if (key_ptr[0] != L'=') {
2054 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2057 // Whether it worked or not, always return rval.
2058 info.GetReturnValue().Set(value);
2062 static void EnvQuery(Local<String> property,
2063 const PropertyCallbackInfo<Integer>& info) {
2064 HandleScope scope(node_isolate);
2065 int32_t rc = -1; // Not found unless proven otherwise.
2067 String::Utf8Value key(property);
2068 if (getenv(*key)) rc = 0;
2070 String::Value key(property);
2071 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2072 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2073 GetLastError() == ERROR_SUCCESS) {
2075 if (key_ptr[0] == L'=') {
2076 // Environment variables that start with '=' are hidden and read-only.
2077 rc = static_cast<int32_t>(v8::ReadOnly) |
2078 static_cast<int32_t>(v8::DontDelete) |
2079 static_cast<int32_t>(v8::DontEnum);
2083 if (rc != -1) info.GetReturnValue().Set(rc);
2087 static void EnvDeleter(Local<String> property,
2088 const PropertyCallbackInfo<Boolean>& info) {
2089 HandleScope scope(node_isolate);
2092 String::Utf8Value key(property);
2093 rc = getenv(*key) != NULL;
2094 if (rc) unsetenv(*key);
2096 String::Value key(property);
2097 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2098 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2099 // Deletion failed. Return true if the key wasn't there in the first place,
2100 // false if it is still there.
2101 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2102 GetLastError() != ERROR_SUCCESS;
2105 info.GetReturnValue().Set(rc);
2109 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2110 HandleScope scope(node_isolate);
2113 while (environ[size]) size++;
2115 Local<Array> env = Array::New(size);
2117 for (int i = 0; i < size; ++i) {
2118 const char* var = environ[i];
2119 const char* s = strchr(var, '=');
2120 const int length = s ? s - var : strlen(var);
2121 Local<String> name = String::NewFromUtf8(node_isolate,
2123 String::kNormalString,
2128 WCHAR* environment = GetEnvironmentStringsW();
2129 if (environment == NULL) return; // This should not happen.
2130 Local<Array> env = Array::New();
2131 WCHAR* p = environment;
2133 while (*p != NULL) {
2136 // If the key starts with '=' it is a hidden environment variable.
2140 s = wcschr(p, L'=');
2145 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2146 const size_t two_byte_buffer_len = s - p;
2147 Local<String> value = String::NewFromTwoByte(node_isolate,
2149 String::kNormalString,
2150 two_byte_buffer_len);
2151 env->Set(i++, value);
2152 p = s + wcslen(s) + 1;
2154 FreeEnvironmentStringsW(environment);
2157 info.GetReturnValue().Set(env);
2161 static Handle<Object> GetFeatures() {
2162 HandleScope scope(node_isolate);
2164 Local<Object> obj = Object::New();
2165 #if defined(DEBUG) && DEBUG
2166 Local<Value> debug = True(node_isolate);
2168 Local<Value> debug = False(node_isolate);
2169 #endif // defined(DEBUG) && DEBUG
2171 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2173 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2174 // TODO(bnoordhuis) ping libuv
2175 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2177 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"),
2178 Boolean::New(use_npn));
2179 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"),
2180 Boolean::New(use_sni));
2181 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2182 Boolean::New(get_builtin_module("crypto") != NULL));
2184 return scope.Close(obj);
2188 static void DebugPortGetter(Local<String> property,
2189 const PropertyCallbackInfo<Value>& info) {
2190 HandleScope scope(node_isolate);
2191 info.GetReturnValue().Set(debug_port);
2195 static void DebugPortSetter(Local<String> property,
2197 const PropertyCallbackInfo<void>& info) {
2198 HandleScope scope(node_isolate);
2199 debug_port = value->NumberValue();
2203 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2204 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2205 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2208 void NeedImmediateCallbackGetter(Local<String> property,
2209 const PropertyCallbackInfo<Value>& info) {
2210 info.GetReturnValue().Set(need_immediate_cb);
2214 static void NeedImmediateCallbackSetter(Local<String> property,
2216 const PropertyCallbackInfo<void>&) {
2217 HandleScope scope(node_isolate);
2219 bool bool_value = value->BooleanValue();
2221 if (need_immediate_cb == bool_value) return;
2223 need_immediate_cb = bool_value;
2225 if (need_immediate_cb) {
2226 uv_check_start(&check_immediate_watcher, node::CheckImmediate);
2227 // idle handle is needed only to maintain event loop
2228 uv_idle_start(&idle_immediate_dummy, node::IdleImmediateDummy);
2230 uv_check_stop(&check_immediate_watcher);
2231 uv_idle_stop(&idle_immediate_dummy);
2236 #define READONLY_PROPERTY(obj, str, var) \
2238 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2242 Handle<Object> SetupProcessObject(int argc, char *argv[]) {
2243 HandleScope scope(node_isolate);
2247 Local<FunctionTemplate> process_template = FunctionTemplate::New();
2248 process_template->SetClassName(
2249 FIXED_ONE_BYTE_STRING(node_isolate, "process"));
2251 Local<Object> process = process_template->GetFunction()->NewInstance();
2252 assert(process.IsEmpty() == false);
2253 assert(process->IsObject() == true);
2255 process_p.Reset(node_isolate, process);
2257 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2259 ProcessTitleSetter);
2262 READONLY_PROPERTY(process,
2264 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2266 // process.moduleLoadList
2267 Local<Array> modules = Array::New();
2268 module_load_list.Reset(node_isolate, modules);
2269 READONLY_PROPERTY(process, "moduleLoadList", modules);
2272 Local<Object> versions = Object::New();
2273 READONLY_PROPERTY(process, "versions", versions);
2275 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2277 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2278 READONLY_PROPERTY(versions,
2280 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2282 // +1 to get rid of the leading 'v'
2283 READONLY_PROPERTY(versions,
2285 OneByteString(node_isolate, NODE_VERSION + 1));
2286 READONLY_PROPERTY(versions,
2288 OneByteString(node_isolate, V8::GetVersion()));
2289 READONLY_PROPERTY(versions,
2291 OneByteString(node_isolate, uv_version_string()));
2292 READONLY_PROPERTY(versions,
2294 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2296 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2297 READONLY_PROPERTY(versions,
2299 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2302 // Stupid code to slice out the version string.
2303 int c, l = strlen(OPENSSL_VERSION_TEXT);
2304 for (i = j = 0; i < l; i++) {
2305 c = OPENSSL_VERSION_TEXT[i];
2306 if ('0' <= c && c <= '9') {
2307 for (j = i + 1; j < l; j++) {
2308 c = OPENSSL_VERSION_TEXT[j];
2309 if (c == ' ') break;
2317 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2323 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2326 READONLY_PROPERTY(process,
2328 OneByteString(node_isolate, PLATFORM));
2331 Local<Array> arguments = Array::New(argc - option_end_index + 1);
2332 arguments->Set(0, String::NewFromUtf8(node_isolate, argv[0]));
2333 for (j = 1, i = option_end_index; i < argc; j++, i++) {
2334 arguments->Set(j, String::NewFromUtf8(node_isolate, argv[i]));
2336 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2339 Local<Array> exec_argv = Array::New(option_end_index - 1);
2340 for (j = 1, i = 0; j < option_end_index; j++, i++) {
2341 exec_argv->Set(i, String::NewFromUtf8(node_isolate, argv[j]));
2343 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_argv);
2345 // create process.env
2346 Local<ObjectTemplate> envTemplate = ObjectTemplate::New();
2347 envTemplate->SetNamedPropertyHandler(EnvGetter,
2353 Local<Object> env = envTemplate->NewInstance();
2354 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), env);
2356 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2357 READONLY_PROPERTY(process, "features", GetFeatures());
2358 process->SetAccessor(
2359 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2360 NeedImmediateCallbackGetter,
2361 NeedImmediateCallbackSetter);
2365 READONLY_PROPERTY(process,
2367 String::NewFromUtf8(node_isolate, eval_string));
2372 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2375 // -i, --interactive
2377 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2381 if (no_deprecation) {
2382 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2385 // --throw-deprecation
2386 if (throw_deprecation) {
2387 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2390 // --trace-deprecation
2391 if (trace_deprecation) {
2392 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2395 size_t exec_path_len = 2 * PATH_MAX;
2396 char* exec_path = new char[exec_path_len];
2397 Local<String> exec_path_value;
2398 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2399 exec_path_value = String::NewFromUtf8(node_isolate,
2401 String::kNormalString,
2404 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2406 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2410 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2414 // define various internal methods
2415 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2416 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2417 NODE_SET_METHOD(process, "reallyExit", Exit);
2418 NODE_SET_METHOD(process, "abort", Abort);
2419 NODE_SET_METHOD(process, "chdir", Chdir);
2420 NODE_SET_METHOD(process, "cwd", Cwd);
2422 NODE_SET_METHOD(process, "umask", Umask);
2424 #if defined(__POSIX__) && !defined(__ANDROID__)
2425 NODE_SET_METHOD(process, "getuid", GetUid);
2426 NODE_SET_METHOD(process, "setuid", SetUid);
2428 NODE_SET_METHOD(process, "setgid", SetGid);
2429 NODE_SET_METHOD(process, "getgid", GetGid);
2431 NODE_SET_METHOD(process, "getgroups", GetGroups);
2432 NODE_SET_METHOD(process, "setgroups", SetGroups);
2433 NODE_SET_METHOD(process, "initgroups", InitGroups);
2434 #endif // __POSIX__ && !defined(__ANDROID__)
2436 NODE_SET_METHOD(process, "_kill", Kill);
2438 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2439 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2440 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2442 NODE_SET_METHOD(process, "hrtime", Hrtime);
2444 NODE_SET_METHOD(process, "dlopen", DLOpen);
2446 NODE_SET_METHOD(process, "uptime", Uptime);
2447 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2449 NODE_SET_METHOD(process, "binding", Binding);
2451 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2453 // values use to cross communicate with processNextTick
2454 Local<Object> info_box = Object::New();
2455 info_box->SetIndexedPropertiesToExternalArrayData(&tick_infobox,
2456 kExternalUnsignedIntArray,
2458 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfoBox"), info_box);
2460 // pre-set _events object for faster emit checks
2461 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2463 return scope.Close(process);
2467 #undef READONLY_PROPERTY
2470 static void AtExit() {
2471 uv_tty_reset_mode();
2475 static void SignalExit(int signal) {
2476 uv_tty_reset_mode();
2477 _exit(128 + signal);
2481 void Load(Handle<Object> process_l) {
2482 HandleScope handle_scope(node_isolate);
2484 process_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "process");
2485 domain_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "domain");
2487 // Compile, execute the src/node.js file. (Which was included as static C
2488 // string in node_natives.h. 'natve_node' is the string containing that
2491 // The node.js file returns a function 'f'
2496 // Disable verbose mode to stop FatalException() handler from trying
2497 // to handle the exception. Errors this early in the start-up phase
2498 // are not safe to ignore.
2499 try_catch.SetVerbose(false);
2501 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2502 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2503 if (try_catch.HasCaught()) {
2504 ReportException(try_catch);
2507 assert(f_value->IsFunction());
2508 Local<Function> f = Local<Function>::Cast(f_value);
2510 // Now we call 'f' with the 'process' variable that we've built up with
2511 // all our bindings. Inside node.js we'll take care of assigning things to
2514 // We start the process this way in order to be more modular. Developers
2515 // who do not like how 'src/node.js' setups the module system but do like
2516 // Node's I/O bindings may want to replace 'f' with their own function.
2518 // Add a reference to the global object
2519 Local<Object> global = v8::Context::GetCurrent()->Global();
2521 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2525 #if defined HAVE_PERFCTR
2526 InitPerfCounters(global);
2529 // Enable handling of uncaught exceptions
2530 // (FatalException(), break on uncaught exception in debugger)
2532 // This is not strictly necessary since it's almost impossible
2533 // to attach the debugger fast enought to break on exception
2534 // thrown during process startup.
2535 try_catch.SetVerbose(true);
2537 Local<Value> arg = process_l;
2538 f->Call(global, 1, &arg);
2541 static void PrintHelp();
2543 static void ParseDebugOpt(const char* arg) {
2546 if (strstr(arg, "--debug-port=") == arg) {
2547 p = 1 + strchr(arg, '=');
2548 debug_port = atoi(p);
2550 use_debug_agent = true;
2551 if (!strcmp(arg, "--debug-brk")) {
2552 debug_wait_connect = true;
2554 } else if (!strcmp(arg, "--debug")) {
2556 } else if (strstr(arg, "--debug-brk=") == arg) {
2557 debug_wait_connect = true;
2558 p = 1 + strchr(arg, '=');
2559 debug_port = atoi(p);
2560 } else if (strstr(arg, "--debug=") == arg) {
2561 p = 1 + strchr(arg, '=');
2562 debug_port = atoi(p);
2565 if (p && debug_port > 1024 && debug_port < 65536)
2568 fprintf(stderr, "Bad debug option.\n");
2569 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2575 static void PrintHelp() {
2576 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2577 " node debug script.js [arguments] \n"
2580 " -v, --version print node's version\n"
2581 " -e, --eval script evaluate script\n"
2582 " -p, --print evaluate script and print result\n"
2583 " -i, --interactive always enter the REPL even if stdin\n"
2584 " does not appear to be a terminal\n"
2585 " --no-deprecation silence deprecation warnings\n"
2586 " --trace-deprecation show stack traces on deprecations\n"
2587 " --v8-options print v8 command line options\n"
2588 " --max-stack-size=val set max v8 stack size (bytes)\n"
2590 "Environment variables:\n"
2592 "NODE_PATH ';'-separated list of directories\n"
2594 "NODE_PATH ':'-separated list of directories\n"
2596 " prefixed to the module search path.\n"
2597 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2598 " global contexts.\n"
2599 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2601 "Documentation can be found at http://nodejs.org/\n");
2605 // Parse node command line arguments.
2606 static void ParseArgs(int argc, char **argv) {
2609 // TODO(bnoordhuis) use parse opts
2610 for (i = 1; i < argc; i++) {
2611 const char *arg = argv[i];
2612 if (strstr(arg, "--debug") == arg) {
2614 argv[i] = const_cast<char*>("");
2615 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2616 printf("%s\n", NODE_VERSION);
2618 } else if (strstr(arg, "--max-stack-size=") == arg) {
2620 p = 1 + strchr(arg, '=');
2621 max_stack_size = atoi(p);
2622 argv[i] = const_cast<char*>("");
2623 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2626 } else if (strcmp(arg, "--eval") == 0 ||
2627 strcmp(arg, "-e") == 0 ||
2628 strcmp(arg, "--print") == 0 ||
2629 strcmp(arg, "-pe") == 0 ||
2630 strcmp(arg, "-p") == 0) {
2631 bool is_eval = strchr(arg, 'e') != NULL;
2632 bool is_print = strchr(arg, 'p') != NULL;
2634 // argument to -p and --print is optional
2635 if (is_eval == true && i + 1 >= argc) {
2636 fprintf(stderr, "Error: %s requires an argument\n", arg);
2640 print_eval = print_eval || is_print;
2641 argv[i] = const_cast<char*>("");
2643 // --eval, -e and -pe always require an argument
2644 if (is_eval == true) {
2645 eval_string = argv[++i];
2649 // next arg is the expression to evaluate unless it starts with:
2650 // - a dash, then it's another switch
2651 // - "\\-", then it's an escaped expression, drop the backslash
2652 if (argv[i + 1] == NULL) continue;
2653 if (argv[i + 1][0] == '-') continue;
2654 eval_string = argv[++i];
2655 if (strncmp(eval_string, "\\-", 2) == 0) ++eval_string;
2656 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2658 argv[i] = const_cast<char*>("");
2659 } else if (strcmp(arg, "--v8-options") == 0) {
2660 argv[i] = const_cast<char*>("--help");
2661 } else if (strcmp(arg, "--no-deprecation") == 0) {
2662 argv[i] = const_cast<char*>("");
2663 no_deprecation = true;
2664 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2665 argv[i] = const_cast<char*>("");
2666 trace_deprecation = true;
2667 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2668 argv[i] = const_cast<char*>("");
2669 throw_deprecation = true;
2670 } else if (argv[i][0] != '-') {
2675 option_end_index = i;
2679 // Called from the main thread.
2680 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2681 v8::Debug::ProcessDebugMessages();
2685 // Called from V8 Debug Agent TCP thread.
2686 static void DispatchMessagesDebugAgentCallback() {
2687 uv_async_send(&dispatch_debug_messages_async);
2691 // Called from the main thread
2692 static void EmitDebugEnabledAsyncCallback(uv_async_t* handle, int status) {
2693 HandleScope handle_scope(node_isolate);
2694 Local<Object> obj = Object::New();
2695 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "cmd"),
2696 FIXED_ONE_BYTE_STRING(node_isolate, "NODE_DEBUG_ENABLED"));
2697 Local<Value> args[] = {
2698 FIXED_ONE_BYTE_STRING(node_isolate, "internalMessage"),
2701 MakeCallback(process_p, "emit", ARRAY_SIZE(args), args);
2705 // Called from the signal watcher callback
2706 static void EmitDebugEnabled() {
2707 uv_async_send(&emit_debug_enabled_async);
2711 static void EnableDebug(bool wait_connect) {
2712 // If we're called from another thread, make sure to enter the right
2714 node_isolate->Enter();
2716 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2719 // Start the debug thread and it's associated TCP server on port 5858.
2720 bool r = v8::Debug::EnableAgent("node " NODE_VERSION,
2724 // Crappy check that everything went well. FIXME
2727 // Print out some information.
2728 fprintf(stderr, "debugger listening on port %d\n", debug_port);
2731 debugger_running = true;
2733 // Do not emit NODE_DEBUG_ENABLED when debugger is enabled before starting
2734 // the main process (i.e. when called via `node --debug`)
2735 if (!process_p.IsEmpty())
2738 node_isolate->Exit();
2743 static void EnableDebugSignalHandler(uv_signal_t* handle, int) {
2744 // Break once process will return execution to v8
2745 v8::Debug::DebugBreak(node_isolate);
2747 if (!debugger_running) {
2748 fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n");
2754 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2755 struct sigaction sa;
2757 memset(&sa, 0, sizeof(sa));
2758 sa.sa_handler = handler;
2759 sigfillset(&sa.sa_mask);
2760 sigaction(signal, &sa, NULL);
2764 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2765 HandleScope scope(node_isolate);
2767 if (args.Length() != 1) {
2768 return ThrowError("Invalid number of arguments.");
2774 pid = args[0]->IntegerValue();
2775 r = kill(pid, SIGUSR1);
2777 return ThrowErrnoException(errno, "kill");
2784 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2785 // Break once process will return execution to v8
2786 if (!debugger_running) {
2787 for (int i = 0; i < 1; i++) {
2788 fprintf(stderr, "Starting debugger agent.\r\n");
2794 v8::Debug::DebugBreak(node_isolate);
2800 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2802 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2806 static int RegisterDebugSignalHandler() {
2807 wchar_t mapping_name[32];
2808 HANDLE mapping_handle;
2810 LPTHREAD_START_ROUTINE* handler;
2812 pid = GetCurrentProcessId();
2814 if (GetDebugSignalHandlerMappingName(pid,
2816 ARRAY_SIZE(mapping_name)) < 0) {
2820 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2826 if (mapping_handle == NULL) {
2830 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2831 MapViewOfFile(mapping_handle,
2832 FILE_MAP_ALL_ACCESS,
2836 if (handler == NULL) {
2837 CloseHandle(mapping_handle);
2841 *handler = EnableDebugThreadProc;
2843 UnmapViewOfFile(static_cast<void*>(handler));
2849 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2850 HandleScope scope(node_isolate);
2852 HANDLE process = NULL;
2853 HANDLE thread = NULL;
2854 HANDLE mapping = NULL;
2855 wchar_t mapping_name[32];
2856 LPTHREAD_START_ROUTINE* handler = NULL;
2858 if (args.Length() != 1) {
2859 ThrowError("Invalid number of arguments.");
2863 pid = (DWORD) args[0]->IntegerValue();
2865 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2866 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2870 if (process == NULL) {
2871 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2875 if (GetDebugSignalHandlerMappingName(pid,
2877 ARRAY_SIZE(mapping_name)) < 0) {
2878 ThrowErrnoException(errno, "sprintf");
2882 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2883 if (mapping == NULL) {
2884 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
2888 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2889 MapViewOfFile(mapping,
2894 if (handler == NULL || *handler == NULL) {
2895 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
2899 thread = CreateRemoteThread(process,
2906 if (thread == NULL) {
2907 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
2911 // Wait for the thread to terminate
2912 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
2913 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
2918 if (process != NULL)
2919 CloseHandle(process);
2921 CloseHandle(thread);
2922 if (handler != NULL)
2923 UnmapViewOfFile(handler);
2924 if (mapping != NULL)
2925 CloseHandle(mapping);
2930 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
2931 v8::Debug::DebugBreak(node_isolate);
2935 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
2936 if (debugger_running) {
2937 v8::Debug::DisableAgent();
2938 debugger_running = false;
2943 char** Init(int argc, char *argv[]) {
2944 // Initialize prog_start_time to get relative uptime.
2945 uv_uptime(&prog_start_time);
2947 // Make inherited handles noninheritable.
2948 uv_disable_stdio_inheritance();
2950 // init async debug messages dispatching
2951 uv_async_init(uv_default_loop(),
2952 &dispatch_debug_messages_async,
2953 DispatchDebugMessagesAsyncCallback);
2954 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
2956 // init async NODE_DEBUG_ENABLED emitter
2957 uv_async_init(uv_default_loop(),
2958 &emit_debug_enabled_async,
2959 EmitDebugEnabledAsyncCallback);
2960 uv_unref(reinterpret_cast<uv_handle_t*>(&emit_debug_enabled_async));
2962 // Parse a few arguments which are specific to Node.
2963 node::ParseArgs(argc, argv);
2964 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
2965 // in the command line))
2966 int v8argc = option_end_index;
2967 char **v8argv = argv;
2969 if (debug_wait_connect) {
2970 // v8argv is a copy of argv up to the script file argument +2 if --debug-brk
2971 // to expose the v8 debugger js object so that node.js can set
2972 // a breakpoint on the first line of the startup script
2974 v8argv = new char*[v8argc];
2975 memcpy(v8argv, argv, sizeof(*argv) * option_end_index);
2976 v8argv[option_end_index] = const_cast<char*>("--expose_debug_as");
2977 v8argv[option_end_index + 1] = const_cast<char*>("v8debug");
2980 // For the normal stack which moves from high to low addresses when frames
2981 // are pushed, we can compute the limit as stack_size bytes below the
2982 // the address of a stack variable (e.g. &stack_var) as an approximation
2983 // of the start of the stack (we're assuming that we haven't pushed a lot
2985 if (max_stack_size != 0) {
2987 ResourceConstraints constraints;
2989 uint32_t *stack_limit = &stack_var - (max_stack_size / sizeof(uint32_t));
2990 constraints.set_stack_limit(stack_limit);
2991 SetResourceConstraints(&constraints); // Must be done before V8::Initialize
2993 V8::SetFlagsFromCommandLine(&v8argc, v8argv, false);
2995 const char typed_arrays_flag[] = "--harmony_typed_arrays";
2996 V8::SetFlagsFromString(typed_arrays_flag, sizeof(typed_arrays_flag) - 1);
2997 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
2999 // Fetch a reference to the main isolate, so we have a reference to it
3000 // even when we need it to access it from another (debugger) thread.
3001 node_isolate = Isolate::GetCurrent();
3005 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3006 RegisterSignalHandler(SIGINT, SignalExit);
3007 RegisterSignalHandler(SIGTERM, SignalExit);
3010 uv_check_init(uv_default_loop(), &check_immediate_watcher);
3011 uv_unref(reinterpret_cast<uv_handle_t*>(&check_immediate_watcher));
3012 uv_idle_init(uv_default_loop(), &idle_immediate_dummy);
3014 V8::SetFatalErrorHandler(node::OnFatalError);
3015 V8::AddMessageListener(OnMessage);
3017 // If the --debug flag was specified then initialize the debug thread.
3018 if (use_debug_agent) {
3019 EnableDebug(debug_wait_connect);
3022 RegisterDebugSignalHandler();
3024 static uv_signal_t signal_watcher;
3025 uv_signal_init(uv_default_loop(), &signal_watcher);
3026 uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1);
3027 uv_unref(reinterpret_cast<uv_handle_t*>(&signal_watcher));
3035 struct AtExitCallback {
3036 AtExitCallback* next_;
3037 void (*cb_)(void* arg);
3041 static AtExitCallback* at_exit_functions_;
3045 AtExitCallback* p = at_exit_functions_;
3046 at_exit_functions_ = NULL;
3049 AtExitCallback* q = p->next_;
3057 void AtExit(void (*cb)(void* arg), void* arg) {
3058 AtExitCallback* p = new AtExitCallback;
3061 p->next_ = at_exit_functions_;
3062 at_exit_functions_ = p;
3066 void EmitExit(v8::Handle<v8::Object> process_l) {
3067 // process.emit('exit')
3068 process_l->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3069 True(node_isolate));
3070 Local<Value> args[] = {
3071 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3072 Integer::New(0, node_isolate)
3074 MakeCallback(process_l, "emit", ARRAY_SIZE(args), args);
3077 static char **copy_argv(int argc, char **argv) {
3085 for (i = 0; i < argc; i++) {
3086 strlen_sum += strlen(argv[i]) + 1;
3089 argv_copy = static_cast<char**>(
3090 malloc(sizeof(*argv_copy) * (argc + 1) + strlen_sum));
3095 argv_data = reinterpret_cast<char*>(argv_copy) +
3096 sizeof(*argv_copy) * (argc + 1);
3098 for (i = 0; i < argc; i++) {
3099 argv_copy[i] = argv_data;
3100 len = strlen(argv[i]) + 1;
3101 memcpy(argv_data, argv[i], len);
3105 argv_copy[argc] = NULL;
3110 int Start(int argc, char *argv[]) {
3111 // Hack aroung with the argv pointer. Used for process.title = "blah".
3112 argv = uv_setup_args(argc, argv);
3114 // Logic to duplicate argv as Init() modifies arguments
3115 // that are passed into it.
3116 char **argv_copy = copy_argv(argc, argv);
3118 // This needs to run *before* V8::Initialize()
3119 // Use copy here as to not modify the original argv:
3120 Init(argc, argv_copy);
3124 Locker locker(node_isolate);
3125 HandleScope handle_scope(node_isolate);
3127 // Create the one and only Context.
3128 Local<Context> context = Context::New(node_isolate);
3129 Context::Scope context_scope(context);
3131 binding_cache.Reset(node_isolate, Object::New());
3133 // Use original argv, as we're just copying values out of it.
3134 Local<Object> process_l = SetupProcessObject(argc, argv);
3136 // Create all the objects, load modules, do everything.
3137 // so your next reading stop should be node::Load()!
3140 // All our arguments are loaded. We've evaluated all of the scripts. We
3141 // might even have created TCP servers. Now we enter the main eventloop. If
3142 // there are no watchers on the loop (except for the ones that were
3143 // uv_unref'd) then this function exits. As long as there are active
3144 // watchers, it blocks.
3145 uv_run(uv_default_loop(), UV_RUN_DEFAULT);
3147 EmitExit(process_l);
3152 // Clean up. Not strictly necessary.
3156 // Clean up the copy: