1 // Copyright Joyent, Inc. and other Node contributors.
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
23 #include "node_buffer.h"
24 #include "node_constants.h"
25 #include "node_file.h"
26 #include "node_http_parser.h"
27 #include "node_javascript.h"
28 #include "node_version.h"
30 #if defined HAVE_PERFCTR
31 #include "node_counters.h"
35 #include "node_crypto.h"
38 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
39 #include "node_dtrace.h"
43 #include "node_provider.h"
47 #include "handle_wrap.h"
49 #include "string_bytes.h"
56 #include <limits.h> // PATH_MAX
62 #include <sys/types.h>
68 #define strcasecmp _stricmp
69 #define getpid _getpid
73 #include <unistd.h> // setuid, getuid
76 #if defined(__POSIX__) && !defined(__ANDROID__)
77 #include <pwd.h> // getpwnam()
78 #include <grp.h> // getgrnam()
82 #include <crt_externs.h>
83 #define environ (*_NSGetEnviron())
84 #elif !defined(_MSC_VER)
85 extern char **environ;
91 using v8::ArrayBuffer;
96 using v8::FunctionCallbackInfo;
97 using v8::FunctionTemplate;
99 using v8::HandleScope;
100 using v8::HeapStatistics;
108 using v8::ObjectTemplate;
109 using v8::Persistent;
110 using v8::PropertyCallbackInfo;
111 using v8::ResourceConstraints;
112 using v8::SetResourceConstraints;
114 using v8::ThrowException;
119 using v8::kExternalUnsignedIntArray;
121 QUEUE handle_wrap_queue = { &handle_wrap_queue, &handle_wrap_queue };
122 QUEUE req_wrap_queue = { &req_wrap_queue, &req_wrap_queue };
124 // declared in req_wrap.h
125 Cached<String> process_symbol;
126 Cached<String> domain_symbol;
128 // declared in node_internals.h
129 Persistent<Object> process_p;
131 static Persistent<Function> process_tickCallback;
132 static Persistent<Object> binding_cache;
133 static Persistent<Array> module_load_list;
134 static Persistent<Array> p_domain_box;
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 // easily communicate domain depth
191 #ifdef OPENSSL_NPN_NEGOTIATED
192 static bool use_npn = true;
194 static bool use_npn = false;
197 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
198 static bool use_sni = true;
200 static bool use_sni = false;
203 // process-relative uptime base, initialized at start-up
204 static double prog_start_time;
206 static volatile bool debugger_running = false;
207 static uv_async_t dispatch_debug_messages_async;
208 static uv_async_t emit_debug_enabled_async;
210 // Declared in node_internals.h
211 Isolate* node_isolate = NULL;
214 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
216 // Impose an upper limit to avoid out of memory errors that bring down
218 static const size_t kMaxLength = 0x3fffffff;
219 static ArrayBufferAllocator the_singleton;
220 virtual ~ArrayBufferAllocator() {}
221 virtual void* Allocate(size_t length);
222 virtual void Free(void* data);
224 ArrayBufferAllocator() {}
225 ArrayBufferAllocator(const ArrayBufferAllocator&);
226 void operator=(const ArrayBufferAllocator&);
229 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
232 void* ArrayBufferAllocator::Allocate(size_t length) {
233 if (length > kMaxLength) return NULL;
234 return new char[length];
238 void ArrayBufferAllocator::Free(void* data) {
239 delete[] static_cast<char*>(data);
243 static void CheckImmediate(uv_check_t* handle, int status) {
244 assert(handle == &check_immediate_watcher);
247 HandleScope scope(node_isolate);
249 if (immediate_callback_sym.IsEmpty()) {
250 immediate_callback_sym =
251 FIXED_ONE_BYTE_STRING(node_isolate, "_immediateCallback");
254 MakeCallback(process_p, immediate_callback_sym, 0, NULL);
258 static void IdleImmediateDummy(uv_idle_t* handle, int status) {
259 // Do nothing. Only for maintaining event loop
260 assert(handle == &idle_immediate_dummy);
265 static inline const char *errno_string(int errorno) {
266 #define ERRNO_CASE(e) case e: return #e;
273 ERRNO_CASE(EADDRINUSE);
277 ERRNO_CASE(EADDRNOTAVAIL);
281 ERRNO_CASE(EAFNOSUPPORT);
289 # if EAGAIN != EWOULDBLOCK
290 ERRNO_CASE(EWOULDBLOCK);
295 ERRNO_CASE(EALREADY);
311 ERRNO_CASE(ECANCELED);
319 ERRNO_CASE(ECONNABORTED);
323 ERRNO_CASE(ECONNREFUSED);
327 ERRNO_CASE(ECONNRESET);
335 ERRNO_CASE(EDESTADDRREQ);
359 ERRNO_CASE(EHOSTUNREACH);
371 ERRNO_CASE(EINPROGRESS);
407 ERRNO_CASE(EMSGSIZE);
411 ERRNO_CASE(EMULTIHOP);
415 ERRNO_CASE(ENAMETOOLONG);
419 ERRNO_CASE(ENETDOWN);
423 ERRNO_CASE(ENETRESET);
427 ERRNO_CASE(ENETUNREACH);
459 # if ENOLINK != ENOLCK
473 ERRNO_CASE(ENOPROTOOPT);
493 ERRNO_CASE(ENOTCONN);
501 ERRNO_CASE(ENOTEMPTY);
505 ERRNO_CASE(ENOTSOCK);
512 ERRNO_CASE(EOPNOTSUPP);
526 ERRNO_CASE(EOVERFLOW);
541 #ifdef EPROTONOSUPPORT
542 ERRNO_CASE(EPROTONOSUPPORT);
546 ERRNO_CASE(EPROTOTYPE);
574 ERRNO_CASE(ETIMEDOUT);
589 const char *signo_string(int signo) {
590 #define SIGNO_CASE(e) case e: return #e;
617 # if SIGABRT != SIGIOT
661 SIGNO_CASE(SIGSTKFLT);
678 SIGNO_CASE(SIGBREAK);
702 SIGNO_CASE(SIGVTALRM);
710 SIGNO_CASE(SIGWINCH);
718 # if SIGPOLL != SIGIO
728 # if SIGPWR != SIGLOST
742 Local<Value> ErrnoException(int errorno,
747 Local<String> estring = OneByteString(node_isolate, errno_string(errorno));
748 if (msg == NULL || msg[0] == '\0') {
749 msg = strerror(errorno);
751 Local<String> message = OneByteString(node_isolate, msg);
753 Local<String> cons1 =
754 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
755 Local<String> cons2 = String::Concat(cons1, message);
757 if (syscall_symbol.IsEmpty()) {
758 syscall_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "syscall");
759 errno_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "errno");
760 errpath_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "path");
761 code_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "code");
765 Local<String> cons3 =
766 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
767 Local<String> cons4 =
768 String::Concat(cons3, String::NewFromUtf8(node_isolate, path));
769 Local<String> cons5 =
770 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
771 e = Exception::Error(cons5);
773 e = Exception::Error(cons2);
776 Local<Object> obj = e->ToObject();
778 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
779 obj->Set(code_symbol, estring);
780 if (path) obj->Set(errpath_symbol, String::NewFromUtf8(node_isolate, path));
781 if (syscall) obj->Set(syscall_symbol, OneByteString(node_isolate, syscall));
786 // hack alert! copy of ErrnoException, tuned for uv errors
787 Local<Value> UVException(int errorno,
791 if (syscall_symbol.IsEmpty()) {
792 syscall_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "syscall");
793 errno_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "errno");
794 errpath_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "path");
795 code_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "code");
799 msg = uv_strerror(errorno);
801 Local<String> estring = OneByteString(node_isolate, uv_err_name(errorno));
802 Local<String> message = OneByteString(node_isolate, msg);
803 Local<String> cons1 =
804 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
805 Local<String> cons2 = String::Concat(cons1, message);
809 Local<String> path_str;
813 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
814 path_str = String::Concat(FIXED_ONE_BYTE_STRING(node_isolate, "\\\\"),
815 String::NewFromUtf8(node_isolate, path + 8));
816 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
817 path_str = String::NewFromUtf8(node_isolate, path + 4);
819 path_str = String::NewFromUtf8(node_isolate, path);
822 path_str = String::NewFromUtf8(node_isolate, path);
825 Local<String> cons3 =
826 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
827 Local<String> cons4 =
828 String::Concat(cons3, path_str);
829 Local<String> cons5 =
830 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
831 e = Exception::Error(cons5);
833 e = Exception::Error(cons2);
836 Local<Object> obj = e->ToObject();
838 // TODO(piscisaureus) errno should probably go
839 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
840 obj->Set(code_symbol, estring);
841 if (path) obj->Set(errpath_symbol, path_str);
842 if (syscall) obj->Set(syscall_symbol, OneByteString(node_isolate, syscall));
848 // Does about the same as strerror(),
849 // but supports all windows error messages
850 static const char *winapi_strerror(const int errorno) {
853 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
854 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
855 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
858 // Remove trailing newlines
859 for (int i = strlen(errmsg) - 1;
860 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
866 // FormatMessage failed
867 return "Unknown error";
872 Local<Value> WinapiErrnoException(int errorno,
877 if (!msg || !msg[0]) {
878 msg = winapi_strerror(errorno);
880 Local<String> message = OneByteString(node_isolate, msg);
882 if (syscall_symbol.IsEmpty()) {
883 syscall_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "syscall");
884 errno_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "errno");
885 errpath_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "path");
886 code_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "code");
890 Local<String> cons1 =
891 String::Concat(message, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
892 Local<String> cons2 =
893 String::Concat(cons1, String::NewFromUtf8(node_isolate, path));
894 Local<String> cons3 =
895 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
896 e = Exception::Error(cons3);
898 e = Exception::Error(message);
901 Local<Object> obj = e->ToObject();
903 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
904 if (path) obj->Set(errpath_symbol, String::NewFromUtf8(node_isolate, path));
905 if (syscall) obj->Set(syscall_symbol, OneByteString(node_isolate, syscall));
911 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
912 if (using_domains) return;
913 HandleScope scope(node_isolate);
914 using_domains = true;
915 Local<Object> process = PersistentToLocal(node_isolate, process_p);
917 process->Get(FIXED_ONE_BYTE_STRING(node_isolate, "_tickDomainCallback"));
918 if (!tdc_v->IsFunction()) {
919 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
922 Local<Function> tdc = tdc_v.As<Function>();
923 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"), tdc);
924 process_tickCallback.Reset(node_isolate, tdc);
925 if (!args[0]->IsArray()) {
926 fprintf(stderr, "_setupDomainUse first argument must be an array\n");
929 p_domain_box.Reset(node_isolate, args[0].As<Array>());
930 if (!args[1]->IsObject()) {
931 fprintf(stderr, "_setupDomainUse second argument must be an object\n");
934 Local<Object> flag = args[1].As<Object>();
935 flag->SetIndexedPropertiesToExternalArrayData(&domain_flag,
936 kExternalUnsignedIntArray,
942 return using_domains && domain_flag.count > 0;
946 Handle<Value> GetDomain() {
947 // no domain can exist if no domain module has been loaded
948 if (!InDomain() || p_domain_box.IsEmpty())
949 return Null(node_isolate);
951 return PersistentToLocal(node_isolate, p_domain_box)->Get(0);
956 MakeDomainCallback(const Handle<Object> object,
957 const Handle<Function> callback,
959 Handle<Value> argv[]) {
960 // TODO(trevnorris) Hook for long stack traces to be made here.
962 // lazy load domain specific symbols
963 if (enter_symbol.IsEmpty()) {
964 enter_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "enter");
965 exit_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "exit");
966 disposed_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "_disposed");
969 Local<Value> domain_v = object->Get(domain_symbol);
970 Local<Object> domain;
971 Local<Function> enter;
972 Local<Function> exit;
975 try_catch.SetVerbose(true);
977 bool has_domain = domain_v->IsObject();
979 domain = domain_v->ToObject();
980 assert(!domain.IsEmpty());
981 if (domain->Get(disposed_symbol)->IsTrue()) {
982 // domain has been disposed of.
983 return Undefined(node_isolate);
985 enter = Local<Function>::Cast(domain->Get(enter_symbol));
986 assert(!enter.IsEmpty());
987 enter->Call(domain, 0, NULL);
989 if (try_catch.HasCaught()) {
990 return Undefined(node_isolate);
994 Local<Value> ret = callback->Call(object, argc, argv);
996 if (try_catch.HasCaught()) {
997 return Undefined(node_isolate);
1001 exit = Local<Function>::Cast(domain->Get(exit_symbol));
1002 assert(!exit.IsEmpty());
1003 exit->Call(domain, 0, NULL);
1005 if (try_catch.HasCaught()) {
1006 return Undefined(node_isolate);
1010 if (tick_infobox.last_threw == 1) {
1011 tick_infobox.last_threw = 0;
1015 if (tick_infobox.in_tick == 1) {
1019 if (tick_infobox.length == 0) {
1020 tick_infobox.index = 0;
1024 // process nextTicks after call
1025 Local<Object> process = PersistentToLocal(node_isolate, process_p);
1026 Local<Function> fn = PersistentToLocal(node_isolate, process_tickCallback);
1027 fn->Call(process, 0, NULL);
1029 if (try_catch.HasCaught()) {
1030 return Undefined(node_isolate);
1038 MakeCallback(const Handle<Object> object,
1039 const Handle<Function> callback,
1041 Handle<Value> argv[]) {
1042 // TODO(trevnorris) Hook for long stack traces to be made here.
1043 Local<Object> process = PersistentToLocal(node_isolate, process_p);
1046 return MakeDomainCallback(object, callback, argc, argv);
1048 // lazy load no domain next tick callbacks
1049 if (process_tickCallback.IsEmpty()) {
1051 process->Get(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"));
1052 if (!cb_v->IsFunction()) {
1053 fprintf(stderr, "process._tickCallback assigned to non-function\n");
1056 process_tickCallback.Reset(node_isolate, cb_v.As<Function>());
1060 try_catch.SetVerbose(true);
1062 Local<Value> ret = callback->Call(object, argc, argv);
1064 if (try_catch.HasCaught()) {
1065 return Undefined(node_isolate);
1068 if (tick_infobox.in_tick == 1) {
1072 if (tick_infobox.length == 0) {
1073 tick_infobox.index = 0;
1077 // process nextTicks after call
1078 Local<Function> fn = PersistentToLocal(node_isolate, process_tickCallback);
1079 fn->Call(process, 0, NULL);
1081 if (try_catch.HasCaught()) {
1082 return Undefined(node_isolate);
1091 MakeCallback(const Handle<Object> object,
1094 Handle<Value> argv[]) {
1095 HandleScope scope(node_isolate);
1097 Local<Function> callback = object->Get(index).As<Function>();
1098 assert(callback->IsFunction());
1101 return scope.Close(MakeDomainCallback(object, callback, argc, argv));
1102 return scope.Close(MakeCallback(object, callback, argc, argv));
1107 MakeCallback(const Handle<Object> object,
1108 const Handle<String> symbol,
1110 Handle<Value> argv[]) {
1111 HandleScope scope(node_isolate);
1113 Local<Function> callback = object->Get(symbol).As<Function>();
1114 assert(callback->IsFunction());
1117 return scope.Close(MakeDomainCallback(object, callback, argc, argv));
1118 return scope.Close(MakeCallback(object, callback, argc, argv));
1123 MakeCallback(const Handle<Object> object,
1126 Handle<Value> argv[]) {
1127 HandleScope scope(node_isolate);
1129 Local<String> method_string = OneByteString(node_isolate, method);
1130 Handle<Value> ret = MakeCallback(object, method_string, argc, argv);
1132 return scope.Close(ret);
1136 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1137 HandleScope scope(node_isolate);
1139 if (!encoding_v->IsString()) return _default;
1141 String::Utf8Value encoding(encoding_v);
1143 if (strcasecmp(*encoding, "utf8") == 0) {
1145 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1147 } else if (strcasecmp(*encoding, "ascii") == 0) {
1149 } else if (strcasecmp(*encoding, "base64") == 0) {
1151 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1153 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1155 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1157 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1159 } else if (strcasecmp(*encoding, "binary") == 0) {
1161 } else if (strcasecmp(*encoding, "buffer") == 0) {
1163 } else if (strcasecmp(*encoding, "hex") == 0) {
1165 } else if (strcasecmp(*encoding, "raw") == 0) {
1166 if (!no_deprecation) {
1167 fprintf(stderr, "'raw' (array of integers) has been removed. "
1171 } else if (strcasecmp(*encoding, "raws") == 0) {
1172 if (!no_deprecation) {
1173 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1174 "Please update your code.\n");
1182 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1183 return StringBytes::Encode(static_cast<const char*>(buf),
1188 // Returns -1 if the handle was not valid for decoding
1189 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1190 HandleScope scope(node_isolate);
1192 if (val->IsArray()) {
1193 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1199 return StringBytes::Size(val, encoding);
1203 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1206 // Returns number of bytes written.
1207 ssize_t DecodeWrite(char *buf,
1209 v8::Handle<v8::Value> val,
1210 enum encoding encoding) {
1211 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1214 void DisplayExceptionLine(Handle<Message> message) {
1215 // Prevent re-entry into this function. For example, if there is
1216 // a throw from a program in vm.runInThisContext(code, filename, true),
1217 // then we want to show the original failure, not the secondary one.
1218 static bool displayed_error = false;
1220 if (displayed_error) return;
1221 displayed_error = true;
1223 uv_tty_reset_mode();
1225 fprintf(stderr, "\n");
1227 if (!message.IsEmpty()) {
1228 // Print (filename):(line number): (message).
1229 String::Utf8Value filename(message->GetScriptResourceName());
1230 const char* filename_string = *filename;
1231 int linenum = message->GetLineNumber();
1232 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1233 // Print line of source code.
1234 String::Utf8Value sourceline(message->GetSourceLine());
1235 const char* sourceline_string = *sourceline;
1237 // Because of how node modules work, all scripts are wrapped with a
1238 // "function (module, exports, __filename, ...) {"
1239 // to provide script local variables.
1241 // When reporting errors on the first line of a script, this wrapper
1242 // function is leaked to the user. There used to be a hack here to
1243 // truncate off the first 62 characters, but it caused numerous other
1244 // problems when vm.runIn*Context() methods were used for non-module
1247 // If we ever decide to re-instate such a hack, the following steps
1250 // 1. Pass a flag around to say "this code was wrapped"
1251 // 2. Update the stack frame output so that it is also correct.
1253 // It would probably be simpler to add a line rather than add some
1254 // number of characters to the first line, since V8 truncates the
1255 // sourceline to 78 characters, and we end up not providing very much
1256 // useful debugging info to the user if we remove 62 characters.
1258 int start = message->GetStartColumn();
1259 int end = message->GetEndColumn();
1261 fprintf(stderr, "%s\n", sourceline_string);
1262 // Print wavy underline (GetUnderline is deprecated).
1263 for (int i = 0; i < start; i++) {
1264 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1266 for (int i = start; i < end; i++) {
1269 fputc('\n', stderr);
1274 static void ReportException(Handle<Value> er, Handle<Message> message) {
1275 HandleScope scope(node_isolate);
1277 DisplayExceptionLine(message);
1279 Local<Value> trace_value(
1280 er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack")));
1281 String::Utf8Value trace(trace_value);
1283 // range errors have a trace member set to undefined
1284 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1285 fprintf(stderr, "%s\n", *trace);
1287 // this really only happens for RangeErrors, since they're the only
1288 // kind that won't have all this info in the trace, or when non-Error
1289 // objects are thrown manually.
1290 Local<Value> message;
1293 if (er->IsObject()) {
1294 Local<Object> err_obj = er.As<Object>();
1295 message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1296 name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1299 if (message.IsEmpty() ||
1300 message->IsUndefined() ||
1302 name->IsUndefined()) {
1303 // Not an error object. Just print as-is.
1304 String::Utf8Value message(er);
1305 fprintf(stderr, "%s\n", *message);
1307 String::Utf8Value name_string(name);
1308 String::Utf8Value message_string(message);
1309 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1317 static void ReportException(const TryCatch& try_catch) {
1318 ReportException(try_catch.Exception(), try_catch.Message());
1322 // Executes a str within the current v8 context.
1323 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1324 HandleScope scope(node_isolate);
1327 // try_catch must be nonverbose to disable FatalException() handler,
1328 // we will handle exceptions ourself.
1329 try_catch.SetVerbose(false);
1331 Local<v8::Script> script = v8::Script::Compile(source, filename);
1332 if (script.IsEmpty()) {
1333 ReportException(try_catch);
1337 Local<Value> result = script->Run();
1338 if (result.IsEmpty()) {
1339 ReportException(try_catch);
1343 return scope.Close(result);
1347 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1348 HandleScope scope(node_isolate);
1350 Local<Array> ary = Array::New();
1354 QUEUE_FOREACH(q, &req_wrap_queue) {
1355 ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1356 if (w->persistent().IsEmpty()) continue;
1357 ary->Set(i++, w->object());
1360 args.GetReturnValue().Set(ary);
1364 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1365 // implemented here for consistency with GetActiveRequests().
1366 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1367 HandleScope scope(node_isolate);
1369 Local<Array> ary = Array::New();
1373 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1375 QUEUE_FOREACH(q, &handle_wrap_queue) {
1376 HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1377 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue;
1378 Local<Object> object = w->object();
1379 Local<Value> owner = object->Get(owner_sym);
1380 if (owner->IsUndefined()) owner = object;
1381 ary->Set(i++, owner);
1384 args.GetReturnValue().Set(ary);
1388 static void Abort(const FunctionCallbackInfo<Value>& args) {
1393 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1394 HandleScope scope(node_isolate);
1396 if (args.Length() != 1 || !args[0]->IsString()) {
1397 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1400 String::Utf8Value path(args[0]);
1401 int err = uv_chdir(*path);
1403 return ThrowUVException(err, "uv_chdir");
1408 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1409 HandleScope scope(node_isolate);
1411 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1412 char buf[MAX_PATH * 4 + 1];
1414 char buf[PATH_MAX + 1];
1417 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1419 return ThrowUVException(err, "uv_cwd");
1422 buf[ARRAY_SIZE(buf) - 1] = '\0';
1423 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1425 args.GetReturnValue().Set(cwd);
1429 static void Umask(const FunctionCallbackInfo<Value>& args) {
1430 HandleScope scope(node_isolate);
1433 if (args.Length() < 1 || args[0]->IsUndefined()) {
1435 umask(static_cast<mode_t>(old));
1436 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1437 return ThrowTypeError("argument must be an integer or octal string.");
1440 if (args[0]->IsInt32()) {
1441 oct = args[0]->Uint32Value();
1444 String::Utf8Value str(args[0]);
1446 // Parse the octal string.
1447 for (int i = 0; i < str.length(); i++) {
1449 if (c > '7' || c < '0') {
1450 return ThrowTypeError("invalid octal string");
1456 old = umask(static_cast<mode_t>(oct));
1459 args.GetReturnValue().Set(old);
1463 #if defined(__POSIX__) && !defined(__ANDROID__)
1465 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1466 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1469 static uid_t uid_by_name(const char* name) {
1477 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1481 return uid_not_found;
1485 static char* name_by_uid(uid_t uid) {
1494 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1495 return strdup(pp->pw_name);
1506 static gid_t gid_by_name(const char* name) {
1514 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1518 return gid_not_found;
1522 #if 0 // For future use.
1523 static const char* name_by_gid(gid_t gid) {
1532 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1533 return strdup(pp->gr_name);
1545 static uid_t uid_by_name(Handle<Value> value) {
1546 if (value->IsUint32()) {
1547 return static_cast<uid_t>(value->Uint32Value());
1549 String::Utf8Value name(value);
1550 return uid_by_name(*name);
1555 static gid_t gid_by_name(Handle<Value> value) {
1556 if (value->IsUint32()) {
1557 return static_cast<gid_t>(value->Uint32Value());
1559 String::Utf8Value name(value);
1560 return gid_by_name(*name);
1565 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1566 args.GetReturnValue().Set(getuid());
1570 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1571 args.GetReturnValue().Set(getgid());
1575 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1576 HandleScope scope(node_isolate);
1578 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1579 return ThrowTypeError("setgid argument must be a number or a string");
1582 gid_t gid = gid_by_name(args[0]);
1584 if (gid == gid_not_found) {
1585 return ThrowError("setgid group id does not exist");
1589 return ThrowErrnoException(errno, "setgid");
1594 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1595 HandleScope scope(node_isolate);
1597 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1598 return ThrowTypeError("setuid argument must be a number or a string");
1601 uid_t uid = uid_by_name(args[0]);
1603 if (uid == uid_not_found) {
1604 return ThrowError("setuid user id does not exist");
1608 return ThrowErrnoException(errno, "setuid");
1613 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1614 HandleScope scope(node_isolate);
1616 int ngroups = getgroups(0, NULL);
1618 if (ngroups == -1) {
1619 return ThrowErrnoException(errno, "getgroups");
1622 gid_t* groups = new gid_t[ngroups];
1624 ngroups = getgroups(ngroups, groups);
1626 if (ngroups == -1) {
1628 return ThrowErrnoException(errno, "getgroups");
1631 Local<Array> groups_list = Array::New(ngroups);
1632 bool seen_egid = false;
1633 gid_t egid = getegid();
1635 for (int i = 0; i < ngroups; i++) {
1636 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1637 if (groups[i] == egid) seen_egid = true;
1642 if (seen_egid == false) {
1643 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1646 args.GetReturnValue().Set(groups_list);
1650 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1651 HandleScope scope(node_isolate);
1653 if (!args[0]->IsArray()) {
1654 return ThrowTypeError("argument 1 must be an array");
1657 Local<Array> groups_list = args[0].As<Array>();
1658 size_t size = groups_list->Length();
1659 gid_t* groups = new gid_t[size];
1661 for (size_t i = 0; i < size; i++) {
1662 gid_t gid = gid_by_name(groups_list->Get(i));
1664 if (gid == gid_not_found) {
1666 return ThrowError("group name not found");
1672 int rc = setgroups(size, groups);
1676 return ThrowErrnoException(errno, "setgroups");
1681 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1682 HandleScope scope(node_isolate);
1684 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1685 return ThrowTypeError("argument 1 must be a number or a string");
1688 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1689 return ThrowTypeError("argument 2 must be a number or a string");
1692 String::Utf8Value arg0(args[0]);
1697 if (args[0]->IsUint32()) {
1698 user = name_by_uid(args[0]->Uint32Value());
1706 return ThrowError("initgroups user not found");
1709 extra_group = gid_by_name(args[1]);
1711 if (extra_group == gid_not_found) {
1712 if (must_free) free(user);
1713 return ThrowError("initgroups extra group not found");
1716 int rc = initgroups(user, extra_group);
1723 return ThrowErrnoException(errno, "initgroups");
1727 #endif // __POSIX__ && !defined(__ANDROID__)
1730 void Exit(const FunctionCallbackInfo<Value>& args) {
1731 HandleScope scope(node_isolate);
1732 exit(args[0]->IntegerValue());
1736 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1737 HandleScope scope(node_isolate);
1739 if (uv_uptime(&uptime)) return;
1740 args.GetReturnValue().Set(uptime - prog_start_time);
1744 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1745 HandleScope scope(node_isolate);
1749 int err = uv_resident_set_memory(&rss);
1751 return ThrowUVException(err, "uv_resident_set_memory");
1754 Local<Object> info = Object::New();
1756 if (rss_symbol.IsEmpty()) {
1757 rss_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "rss");
1758 heap_total_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "heapTotal");
1759 heap_used_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "heapUsed");
1762 info->Set(rss_symbol, Number::New(rss));
1765 HeapStatistics v8_heap_stats;
1766 node_isolate->GetHeapStatistics(&v8_heap_stats);
1767 info->Set(heap_total_symbol,
1768 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(),
1770 info->Set(heap_used_symbol,
1771 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(),
1774 args.GetReturnValue().Set(info);
1778 void Kill(const FunctionCallbackInfo<Value>& args) {
1779 HandleScope scope(node_isolate);
1781 if (args.Length() != 2) {
1782 return ThrowError("Bad argument.");
1785 int pid = args[0]->IntegerValue();
1786 int sig = args[1]->Int32Value();
1787 int err = uv_kill(pid, sig);
1788 args.GetReturnValue().Set(err);
1791 // used in Hrtime() below
1792 #define NANOS_PER_SEC 1000000000
1794 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1795 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1796 // so this function instead returns an Array with 2 entries representing seconds
1797 // and nanoseconds, to avoid any integer overflow possibility.
1798 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1799 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1800 HandleScope scope(node_isolate);
1802 uint64_t t = uv_hrtime();
1804 if (args.Length() > 0) {
1805 // return a time diff tuple
1806 if (!args[0]->IsArray()) {
1807 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1809 Local<Array> inArray = Local<Array>::Cast(args[0]);
1810 uint64_t seconds = inArray->Get(0)->Uint32Value();
1811 uint64_t nanos = inArray->Get(1)->Uint32Value();
1812 t -= (seconds * NANOS_PER_SEC) + nanos;
1815 Local<Array> tuple = Array::New(2);
1816 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1817 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1818 args.GetReturnValue().Set(tuple);
1822 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1824 // DLOpen is process.dlopen(module, filename).
1825 // Used to load 'module.node' dynamically shared objects.
1826 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1827 HandleScope scope(node_isolate);
1828 char symbol[1024], *base, *pos;
1832 if (args.Length() < 2) {
1833 return ThrowError("process.dlopen takes exactly 2 arguments.");
1836 Local<Object> module = args[0]->ToObject(); // Cast
1837 String::Utf8Value filename(args[1]); // Cast
1839 if (exports_symbol.IsEmpty()) {
1840 exports_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "exports");
1842 Local<Object> exports = module->Get(exports_symbol)->ToObject();
1844 if (uv_dlopen(*filename, &lib)) {
1845 Local<String> errmsg = OneByteString(node_isolate, uv_dlerror(&lib));
1847 // Windows needs to add the filename into the error message
1848 errmsg = String::Concat(errmsg, args[1]->ToString());
1850 ThrowException(Exception::Error(errmsg));
1854 String::Utf8Value path(args[1]);
1857 /* Find the shared library filename within the full path. */
1859 pos = strrchr(base, '/');
1865 pos = strpbrk(base, "\\/:");
1873 /* Strip the .node extension. */
1874 pos = strrchr(base, '.');
1879 /* Add the `_module` suffix to the extension name. */
1880 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1881 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1882 return ThrowError("Out of memory.");
1885 /* Replace dashes with underscores. When loading foo-bar.node,
1886 * look for foo_bar_module, not foo-bar_module.
1888 for (pos = symbol; *pos != '\0'; ++pos) {
1889 if (*pos == '-') *pos = '_';
1892 node_module_struct *mod;
1893 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1895 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1896 return ThrowError(errmsg);
1899 if (mod->version != NODE_MODULE_VERSION) {
1903 "Module version mismatch. Expected %d, got %d.",
1904 NODE_MODULE_VERSION, mod->version);
1905 return ThrowError(errmsg);
1908 // Execute the C++ module
1909 mod->register_func(exports, module);
1911 // Tell coverity that 'handle' should not be freed when we return.
1912 // coverity[leaked_storage]
1916 static void OnFatalError(const char* location, const char* message) {
1918 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1920 fprintf(stderr, "FATAL ERROR: %s\n", message);
1930 NO_RETURN void FatalError(const char* location, const char* message) {
1931 OnFatalError(location, message);
1932 // to supress compiler warning
1937 void FatalException(Handle<Value> error, Handle<Message> message) {
1938 HandleScope scope(node_isolate);
1940 if (fatal_exception_symbol.IsEmpty()) {
1941 fatal_exception_symbol =
1942 FIXED_ONE_BYTE_STRING(node_isolate, "_fatalException");
1945 Local<Object> process = PersistentToLocal(node_isolate, process_p);
1946 Local<Value> fatal_v = process->Get(fatal_exception_symbol);
1948 if (!fatal_v->IsFunction()) {
1949 // failed before the process._fatalException function was added!
1950 // this is probably pretty bad. Nothing to do but report and exit.
1951 ReportException(error, message);
1955 Local<Function> fatal_f = Local<Function>::Cast(fatal_v);
1957 TryCatch fatal_try_catch;
1959 // Do not call FatalException when _fatalException handler throws
1960 fatal_try_catch.SetVerbose(false);
1962 // this will return true if the JS layer handled it, false otherwise
1963 Local<Value> caught = fatal_f->Call(process, 1, &error);
1965 if (fatal_try_catch.HasCaught()) {
1966 // the fatal exception function threw, so we must exit
1967 ReportException(fatal_try_catch);
1971 if (false == caught->BooleanValue()) {
1972 ReportException(error, message);
1978 void FatalException(const TryCatch& try_catch) {
1979 HandleScope scope(node_isolate);
1980 // TODO(bajtos) do not call FatalException if try_catch is verbose
1981 // (requires V8 API to expose getter for try_catch.is_verbose_)
1982 FatalException(try_catch.Exception(), try_catch.Message());
1986 void OnMessage(Handle<Message> message, Handle<Value> error) {
1987 // The current version of V8 sends messages for errors only
1988 // (thus `error` is always set).
1989 FatalException(error, message);
1993 static void Binding(const FunctionCallbackInfo<Value>& args) {
1994 HandleScope scope(node_isolate);
1996 Local<String> module = args[0]->ToString();
1997 String::Utf8Value module_v(module);
1998 node_module_struct* modp;
2000 Local<Object> cache = PersistentToLocal(node_isolate, binding_cache);
2001 Local<Object> exports;
2003 if (cache->Has(module)) {
2004 exports = cache->Get(module)->ToObject();
2005 args.GetReturnValue().Set(exports);
2009 // Append a string to process.moduleLoadList
2011 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
2013 Local<Array> modules = PersistentToLocal(node_isolate, module_load_list);
2014 uint32_t l = modules->Length();
2015 modules->Set(l, OneByteString(node_isolate, buf));
2017 if ((modp = get_builtin_module(*module_v)) != NULL) {
2018 exports = Object::New();
2019 // Internal bindings don't have a "module" object,
2021 modp->register_func(exports, Undefined(node_isolate));
2022 cache->Set(module, exports);
2023 } else if (!strcmp(*module_v, "constants")) {
2024 exports = Object::New();
2025 DefineConstants(exports);
2026 cache->Set(module, exports);
2027 } else if (!strcmp(*module_v, "natives")) {
2028 exports = Object::New();
2029 DefineJavaScript(exports);
2030 cache->Set(module, exports);
2032 return ThrowError("No such module");
2035 args.GetReturnValue().Set(exports);
2039 static void ProcessTitleGetter(Local<String> property,
2040 const PropertyCallbackInfo<Value>& info) {
2041 HandleScope scope(node_isolate);
2043 uv_get_process_title(buffer, sizeof(buffer));
2044 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2048 static void ProcessTitleSetter(Local<String> property,
2050 const PropertyCallbackInfo<void>& info) {
2051 HandleScope scope(node_isolate);
2052 String::Utf8Value title(value);
2053 // TODO(piscisaureus): protect with a lock
2054 uv_set_process_title(*title);
2058 static void EnvGetter(Local<String> property,
2059 const PropertyCallbackInfo<Value>& info) {
2060 HandleScope scope(node_isolate);
2062 String::Utf8Value key(property);
2063 const char* val = getenv(*key);
2065 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2068 String::Value key(property);
2069 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2070 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2072 ARRAY_SIZE(buffer));
2073 // If result >= sizeof buffer the buffer was too small. That should never
2074 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2076 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2077 result < ARRAY_SIZE(buffer)) {
2078 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2079 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2080 return info.GetReturnValue().Set(rc);
2083 // Not found. Fetch from prototype.
2084 info.GetReturnValue().Set(
2085 info.Data().As<Object>()->Get(property));
2089 static void EnvSetter(Local<String> property,
2091 const PropertyCallbackInfo<Value>& info) {
2092 HandleScope scope(node_isolate);
2094 String::Utf8Value key(property);
2095 String::Utf8Value val(value);
2096 setenv(*key, *val, 1);
2098 String::Value key(property);
2099 String::Value val(value);
2100 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2101 // Environment variables that start with '=' are read-only.
2102 if (key_ptr[0] != L'=') {
2103 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2106 // Whether it worked or not, always return rval.
2107 info.GetReturnValue().Set(value);
2111 static void EnvQuery(Local<String> property,
2112 const PropertyCallbackInfo<Integer>& info) {
2113 HandleScope scope(node_isolate);
2114 int32_t rc = -1; // Not found unless proven otherwise.
2116 String::Utf8Value key(property);
2117 if (getenv(*key)) rc = 0;
2119 String::Value key(property);
2120 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2121 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2122 GetLastError() == ERROR_SUCCESS) {
2124 if (key_ptr[0] == L'=') {
2125 // Environment variables that start with '=' are hidden and read-only.
2126 rc = static_cast<int32_t>(v8::ReadOnly) |
2127 static_cast<int32_t>(v8::DontDelete) |
2128 static_cast<int32_t>(v8::DontEnum);
2132 if (rc != -1) info.GetReturnValue().Set(rc);
2136 static void EnvDeleter(Local<String> property,
2137 const PropertyCallbackInfo<Boolean>& info) {
2138 HandleScope scope(node_isolate);
2141 String::Utf8Value key(property);
2142 rc = getenv(*key) != NULL;
2143 if (rc) unsetenv(*key);
2145 String::Value key(property);
2146 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2147 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2148 // Deletion failed. Return true if the key wasn't there in the first place,
2149 // false if it is still there.
2150 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2151 GetLastError() != ERROR_SUCCESS;
2154 info.GetReturnValue().Set(rc);
2158 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2159 HandleScope scope(node_isolate);
2162 while (environ[size]) size++;
2164 Local<Array> env = Array::New(size);
2166 for (int i = 0; i < size; ++i) {
2167 const char* var = environ[i];
2168 const char* s = strchr(var, '=');
2169 const int length = s ? s - var : strlen(var);
2170 Local<String> name = String::NewFromUtf8(node_isolate,
2172 String::kNormalString,
2177 WCHAR* environment = GetEnvironmentStringsW();
2178 if (environment == NULL) return; // This should not happen.
2179 Local<Array> env = Array::New();
2180 WCHAR* p = environment;
2182 while (*p != NULL) {
2185 // If the key starts with '=' it is a hidden environment variable.
2189 s = wcschr(p, L'=');
2194 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2195 const size_t two_byte_buffer_len = s - p;
2196 Local<String> value = String::NewFromTwoByte(node_isolate,
2198 String::kNormalString,
2199 two_byte_buffer_len);
2200 env->Set(i++, value);
2201 p = s + wcslen(s) + 1;
2203 FreeEnvironmentStringsW(environment);
2206 info.GetReturnValue().Set(env);
2210 static Handle<Object> GetFeatures() {
2211 HandleScope scope(node_isolate);
2213 Local<Object> obj = Object::New();
2214 #if defined(DEBUG) && DEBUG
2215 Local<Value> debug = True(node_isolate);
2217 Local<Value> debug = False(node_isolate);
2218 #endif // defined(DEBUG) && DEBUG
2220 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2222 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2223 // TODO(bnoordhuis) ping libuv
2224 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2226 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"),
2227 Boolean::New(use_npn));
2228 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"),
2229 Boolean::New(use_sni));
2230 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2231 Boolean::New(get_builtin_module("crypto") != NULL));
2233 return scope.Close(obj);
2237 static void DebugPortGetter(Local<String> property,
2238 const PropertyCallbackInfo<Value>& info) {
2239 HandleScope scope(node_isolate);
2240 info.GetReturnValue().Set(debug_port);
2244 static void DebugPortSetter(Local<String> property,
2246 const PropertyCallbackInfo<void>& info) {
2247 HandleScope scope(node_isolate);
2248 debug_port = value->NumberValue();
2252 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2253 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2254 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2257 void NeedImmediateCallbackGetter(Local<String> property,
2258 const PropertyCallbackInfo<Value>& info) {
2259 info.GetReturnValue().Set(need_immediate_cb);
2263 static void NeedImmediateCallbackSetter(Local<String> property,
2265 const PropertyCallbackInfo<void>&) {
2266 HandleScope scope(node_isolate);
2268 bool bool_value = value->BooleanValue();
2270 if (need_immediate_cb == bool_value) return;
2272 need_immediate_cb = bool_value;
2274 if (need_immediate_cb) {
2275 uv_check_start(&check_immediate_watcher, node::CheckImmediate);
2276 // idle handle is needed only to maintain event loop
2277 uv_idle_start(&idle_immediate_dummy, node::IdleImmediateDummy);
2279 uv_check_stop(&check_immediate_watcher);
2280 uv_idle_stop(&idle_immediate_dummy);
2285 #define READONLY_PROPERTY(obj, str, var) \
2287 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2291 Handle<Object> SetupProcessObject(int argc, char *argv[]) {
2292 HandleScope scope(node_isolate);
2296 Local<FunctionTemplate> process_template = FunctionTemplate::New();
2297 process_template->SetClassName(
2298 FIXED_ONE_BYTE_STRING(node_isolate, "process"));
2300 Local<Object> process = process_template->GetFunction()->NewInstance();
2301 assert(process.IsEmpty() == false);
2302 assert(process->IsObject() == true);
2304 process_p.Reset(node_isolate, process);
2306 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2308 ProcessTitleSetter);
2311 READONLY_PROPERTY(process,
2313 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2315 // process.moduleLoadList
2316 Local<Array> modules = Array::New();
2317 module_load_list.Reset(node_isolate, modules);
2318 READONLY_PROPERTY(process, "moduleLoadList", modules);
2321 Local<Object> versions = Object::New();
2322 READONLY_PROPERTY(process, "versions", versions);
2324 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2326 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2327 READONLY_PROPERTY(versions,
2329 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2331 // +1 to get rid of the leading 'v'
2332 READONLY_PROPERTY(versions,
2334 OneByteString(node_isolate, NODE_VERSION + 1));
2335 READONLY_PROPERTY(versions,
2337 OneByteString(node_isolate, V8::GetVersion()));
2338 READONLY_PROPERTY(versions,
2340 OneByteString(node_isolate, uv_version_string()));
2341 READONLY_PROPERTY(versions,
2343 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2345 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2346 READONLY_PROPERTY(versions,
2348 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2351 // Stupid code to slice out the version string.
2352 int c, l = strlen(OPENSSL_VERSION_TEXT);
2353 for (i = j = 0; i < l; i++) {
2354 c = OPENSSL_VERSION_TEXT[i];
2355 if ('0' <= c && c <= '9') {
2356 for (j = i + 1; j < l; j++) {
2357 c = OPENSSL_VERSION_TEXT[j];
2358 if (c == ' ') break;
2366 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2372 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2375 READONLY_PROPERTY(process,
2377 OneByteString(node_isolate, PLATFORM));
2380 Local<Array> arguments = Array::New(argc - option_end_index + 1);
2381 arguments->Set(0, String::NewFromUtf8(node_isolate, argv[0]));
2382 for (j = 1, i = option_end_index; i < argc; j++, i++) {
2383 arguments->Set(j, String::NewFromUtf8(node_isolate, argv[i]));
2385 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2388 Local<Array> exec_argv = Array::New(option_end_index - 1);
2389 for (j = 1, i = 0; j < option_end_index; j++, i++) {
2390 exec_argv->Set(i, String::NewFromUtf8(node_isolate, argv[j]));
2392 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_argv);
2394 // create process.env
2395 Local<ObjectTemplate> envTemplate = ObjectTemplate::New();
2396 envTemplate->SetNamedPropertyHandler(EnvGetter,
2402 Local<Object> env = envTemplate->NewInstance();
2403 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), env);
2405 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2406 READONLY_PROPERTY(process, "features", GetFeatures());
2407 process->SetAccessor(
2408 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2409 NeedImmediateCallbackGetter,
2410 NeedImmediateCallbackSetter);
2414 READONLY_PROPERTY(process,
2416 String::NewFromUtf8(node_isolate, eval_string));
2421 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2424 // -i, --interactive
2426 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2430 if (no_deprecation) {
2431 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2434 // --throw-deprecation
2435 if (throw_deprecation) {
2436 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2439 // --trace-deprecation
2440 if (trace_deprecation) {
2441 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2444 size_t exec_path_len = 2 * PATH_MAX;
2445 char* exec_path = new char[exec_path_len];
2446 Local<String> exec_path_value;
2447 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2448 exec_path_value = String::NewFromUtf8(node_isolate,
2450 String::kNormalString,
2453 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2455 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2459 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2463 // define various internal methods
2464 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2465 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2466 NODE_SET_METHOD(process, "reallyExit", Exit);
2467 NODE_SET_METHOD(process, "abort", Abort);
2468 NODE_SET_METHOD(process, "chdir", Chdir);
2469 NODE_SET_METHOD(process, "cwd", Cwd);
2471 NODE_SET_METHOD(process, "umask", Umask);
2473 #if defined(__POSIX__) && !defined(__ANDROID__)
2474 NODE_SET_METHOD(process, "getuid", GetUid);
2475 NODE_SET_METHOD(process, "setuid", SetUid);
2477 NODE_SET_METHOD(process, "setgid", SetGid);
2478 NODE_SET_METHOD(process, "getgid", GetGid);
2480 NODE_SET_METHOD(process, "getgroups", GetGroups);
2481 NODE_SET_METHOD(process, "setgroups", SetGroups);
2482 NODE_SET_METHOD(process, "initgroups", InitGroups);
2483 #endif // __POSIX__ && !defined(__ANDROID__)
2485 NODE_SET_METHOD(process, "_kill", Kill);
2487 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2488 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2489 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2491 NODE_SET_METHOD(process, "hrtime", Hrtime);
2493 NODE_SET_METHOD(process, "dlopen", DLOpen);
2495 NODE_SET_METHOD(process, "uptime", Uptime);
2496 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2498 NODE_SET_METHOD(process, "binding", Binding);
2500 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2502 // values use to cross communicate with processNextTick
2503 Local<Object> info_box = Object::New();
2504 info_box->SetIndexedPropertiesToExternalArrayData(&tick_infobox,
2505 kExternalUnsignedIntArray,
2507 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfoBox"), info_box);
2509 // pre-set _events object for faster emit checks
2510 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2512 return scope.Close(process);
2516 #undef READONLY_PROPERTY
2519 static void AtExit() {
2520 uv_tty_reset_mode();
2524 static void SignalExit(int signal) {
2525 uv_tty_reset_mode();
2526 _exit(128 + signal);
2530 void Load(Handle<Object> process_l) {
2531 HandleScope handle_scope(node_isolate);
2533 process_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "process");
2534 domain_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "domain");
2536 // Compile, execute the src/node.js file. (Which was included as static C
2537 // string in node_natives.h. 'natve_node' is the string containing that
2540 // The node.js file returns a function 'f'
2545 // Disable verbose mode to stop FatalException() handler from trying
2546 // to handle the exception. Errors this early in the start-up phase
2547 // are not safe to ignore.
2548 try_catch.SetVerbose(false);
2550 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2551 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2552 if (try_catch.HasCaught()) {
2553 ReportException(try_catch);
2556 assert(f_value->IsFunction());
2557 Local<Function> f = Local<Function>::Cast(f_value);
2559 // Now we call 'f' with the 'process' variable that we've built up with
2560 // all our bindings. Inside node.js we'll take care of assigning things to
2563 // We start the process this way in order to be more modular. Developers
2564 // who do not like how 'src/node.js' setups the module system but do like
2565 // Node's I/O bindings may want to replace 'f' with their own function.
2567 // Add a reference to the global object
2568 Local<Object> global = v8::Context::GetCurrent()->Global();
2570 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2574 #if defined HAVE_PERFCTR
2575 InitPerfCounters(global);
2578 // Enable handling of uncaught exceptions
2579 // (FatalException(), break on uncaught exception in debugger)
2581 // This is not strictly necessary since it's almost impossible
2582 // to attach the debugger fast enought to break on exception
2583 // thrown during process startup.
2584 try_catch.SetVerbose(true);
2586 Local<Value> arg = process_l;
2587 f->Call(global, 1, &arg);
2590 static void PrintHelp();
2592 static void ParseDebugOpt(const char* arg) {
2595 if (strstr(arg, "--debug-port=") == arg) {
2596 p = 1 + strchr(arg, '=');
2597 debug_port = atoi(p);
2599 use_debug_agent = true;
2600 if (!strcmp(arg, "--debug-brk")) {
2601 debug_wait_connect = true;
2603 } else if (!strcmp(arg, "--debug")) {
2605 } else if (strstr(arg, "--debug-brk=") == arg) {
2606 debug_wait_connect = true;
2607 p = 1 + strchr(arg, '=');
2608 debug_port = atoi(p);
2609 } else if (strstr(arg, "--debug=") == arg) {
2610 p = 1 + strchr(arg, '=');
2611 debug_port = atoi(p);
2614 if (p && debug_port > 1024 && debug_port < 65536)
2617 fprintf(stderr, "Bad debug option.\n");
2618 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2624 static void PrintHelp() {
2625 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2626 " node debug script.js [arguments] \n"
2629 " -v, --version print node's version\n"
2630 " -e, --eval script evaluate script\n"
2631 " -p, --print evaluate script and print result\n"
2632 " -i, --interactive always enter the REPL even if stdin\n"
2633 " does not appear to be a terminal\n"
2634 " --no-deprecation silence deprecation warnings\n"
2635 " --trace-deprecation show stack traces on deprecations\n"
2636 " --v8-options print v8 command line options\n"
2637 " --max-stack-size=val set max v8 stack size (bytes)\n"
2639 "Environment variables:\n"
2641 "NODE_PATH ';'-separated list of directories\n"
2643 "NODE_PATH ':'-separated list of directories\n"
2645 " prefixed to the module search path.\n"
2646 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2647 " global contexts.\n"
2648 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2650 "Documentation can be found at http://nodejs.org/\n");
2654 // Parse node command line arguments.
2655 static void ParseArgs(int argc, char **argv) {
2658 // TODO(bnoordhuis) use parse opts
2659 for (i = 1; i < argc; i++) {
2660 const char *arg = argv[i];
2661 if (strstr(arg, "--debug") == arg) {
2663 argv[i] = const_cast<char*>("");
2664 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2665 printf("%s\n", NODE_VERSION);
2667 } else if (strstr(arg, "--max-stack-size=") == arg) {
2669 p = 1 + strchr(arg, '=');
2670 max_stack_size = atoi(p);
2671 argv[i] = const_cast<char*>("");
2672 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2675 } else if (strcmp(arg, "--eval") == 0 ||
2676 strcmp(arg, "-e") == 0 ||
2677 strcmp(arg, "--print") == 0 ||
2678 strcmp(arg, "-pe") == 0 ||
2679 strcmp(arg, "-p") == 0) {
2680 bool is_eval = strchr(arg, 'e') != NULL;
2681 bool is_print = strchr(arg, 'p') != NULL;
2683 // argument to -p and --print is optional
2684 if (is_eval == true && i + 1 >= argc) {
2685 fprintf(stderr, "Error: %s requires an argument\n", arg);
2689 print_eval = print_eval || is_print;
2690 argv[i] = const_cast<char*>("");
2692 // --eval, -e and -pe always require an argument
2693 if (is_eval == true) {
2694 eval_string = argv[++i];
2698 // next arg is the expression to evaluate unless it starts with:
2699 // - a dash, then it's another switch
2700 // - "\\-", then it's an escaped expression, drop the backslash
2701 if (argv[i + 1] == NULL) continue;
2702 if (argv[i + 1][0] == '-') continue;
2703 eval_string = argv[++i];
2704 if (strncmp(eval_string, "\\-", 2) == 0) ++eval_string;
2705 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2707 argv[i] = const_cast<char*>("");
2708 } else if (strcmp(arg, "--v8-options") == 0) {
2709 argv[i] = const_cast<char*>("--help");
2710 } else if (strcmp(arg, "--no-deprecation") == 0) {
2711 argv[i] = const_cast<char*>("");
2712 no_deprecation = true;
2713 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2714 argv[i] = const_cast<char*>("");
2715 trace_deprecation = true;
2716 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2717 argv[i] = const_cast<char*>("");
2718 throw_deprecation = true;
2719 } else if (argv[i][0] != '-') {
2724 option_end_index = i;
2728 // Called from the main thread.
2729 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2730 v8::Debug::ProcessDebugMessages();
2734 // Called from V8 Debug Agent TCP thread.
2735 static void DispatchMessagesDebugAgentCallback() {
2736 uv_async_send(&dispatch_debug_messages_async);
2740 // Called from the main thread
2741 static void EmitDebugEnabledAsyncCallback(uv_async_t* handle, int status) {
2742 HandleScope handle_scope(node_isolate);
2743 Local<Object> obj = Object::New();
2744 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "cmd"),
2745 FIXED_ONE_BYTE_STRING(node_isolate, "NODE_DEBUG_ENABLED"));
2746 Local<Value> args[] = {
2747 FIXED_ONE_BYTE_STRING(node_isolate, "internalMessage"),
2750 MakeCallback(process_p, "emit", ARRAY_SIZE(args), args);
2754 // Called from the signal watcher callback
2755 static void EmitDebugEnabled() {
2756 uv_async_send(&emit_debug_enabled_async);
2760 static void EnableDebug(bool wait_connect) {
2761 // If we're called from another thread, make sure to enter the right
2763 node_isolate->Enter();
2765 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2768 // Start the debug thread and it's associated TCP server on port 5858.
2769 bool r = v8::Debug::EnableAgent("node " NODE_VERSION,
2773 // Crappy check that everything went well. FIXME
2776 // Print out some information.
2777 fprintf(stderr, "debugger listening on port %d\n", debug_port);
2780 debugger_running = true;
2782 // Do not emit NODE_DEBUG_ENABLED when debugger is enabled before starting
2783 // the main process (i.e. when called via `node --debug`)
2784 if (!process_p.IsEmpty())
2787 node_isolate->Exit();
2792 static void EnableDebugSignalHandler(uv_signal_t* handle, int) {
2793 // Break once process will return execution to v8
2794 v8::Debug::DebugBreak(node_isolate);
2796 if (!debugger_running) {
2797 fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n");
2803 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2804 struct sigaction sa;
2806 memset(&sa, 0, sizeof(sa));
2807 sa.sa_handler = handler;
2808 sigfillset(&sa.sa_mask);
2809 sigaction(signal, &sa, NULL);
2813 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2814 HandleScope scope(node_isolate);
2816 if (args.Length() != 1) {
2817 return ThrowError("Invalid number of arguments.");
2823 pid = args[0]->IntegerValue();
2824 r = kill(pid, SIGUSR1);
2826 return ThrowErrnoException(errno, "kill");
2833 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2834 // Break once process will return execution to v8
2835 if (!debugger_running) {
2836 for (int i = 0; i < 1; i++) {
2837 fprintf(stderr, "Starting debugger agent.\r\n");
2843 v8::Debug::DebugBreak(node_isolate);
2849 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2851 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2855 static int RegisterDebugSignalHandler() {
2856 wchar_t mapping_name[32];
2857 HANDLE mapping_handle;
2859 LPTHREAD_START_ROUTINE* handler;
2861 pid = GetCurrentProcessId();
2863 if (GetDebugSignalHandlerMappingName(pid,
2865 ARRAY_SIZE(mapping_name)) < 0) {
2869 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2875 if (mapping_handle == NULL) {
2879 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2880 MapViewOfFile(mapping_handle,
2881 FILE_MAP_ALL_ACCESS,
2885 if (handler == NULL) {
2886 CloseHandle(mapping_handle);
2890 *handler = EnableDebugThreadProc;
2892 UnmapViewOfFile(static_cast<void*>(handler));
2898 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2899 HandleScope scope(node_isolate);
2901 HANDLE process = NULL;
2902 HANDLE thread = NULL;
2903 HANDLE mapping = NULL;
2904 wchar_t mapping_name[32];
2905 LPTHREAD_START_ROUTINE* handler = NULL;
2907 if (args.Length() != 1) {
2908 ThrowError("Invalid number of arguments.");
2912 pid = (DWORD) args[0]->IntegerValue();
2914 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2915 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2919 if (process == NULL) {
2920 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2924 if (GetDebugSignalHandlerMappingName(pid,
2926 ARRAY_SIZE(mapping_name)) < 0) {
2927 ThrowErrnoException(errno, "sprintf");
2931 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2932 if (mapping == NULL) {
2933 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
2937 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2938 MapViewOfFile(mapping,
2943 if (handler == NULL || *handler == NULL) {
2944 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
2948 thread = CreateRemoteThread(process,
2955 if (thread == NULL) {
2956 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
2960 // Wait for the thread to terminate
2961 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
2962 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
2967 if (process != NULL)
2968 CloseHandle(process);
2970 CloseHandle(thread);
2971 if (handler != NULL)
2972 UnmapViewOfFile(handler);
2973 if (mapping != NULL)
2974 CloseHandle(mapping);
2979 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
2980 v8::Debug::DebugBreak(node_isolate);
2984 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
2985 if (debugger_running) {
2986 v8::Debug::DisableAgent();
2987 debugger_running = false;
2992 char** Init(int argc, char *argv[]) {
2993 // Initialize prog_start_time to get relative uptime.
2994 uv_uptime(&prog_start_time);
2996 // Make inherited handles noninheritable.
2997 uv_disable_stdio_inheritance();
2999 // init async debug messages dispatching
3000 uv_async_init(uv_default_loop(),
3001 &dispatch_debug_messages_async,
3002 DispatchDebugMessagesAsyncCallback);
3003 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3005 // init async NODE_DEBUG_ENABLED emitter
3006 uv_async_init(uv_default_loop(),
3007 &emit_debug_enabled_async,
3008 EmitDebugEnabledAsyncCallback);
3009 uv_unref(reinterpret_cast<uv_handle_t*>(&emit_debug_enabled_async));
3011 // Parse a few arguments which are specific to Node.
3012 node::ParseArgs(argc, argv);
3013 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
3014 // in the command line))
3015 int v8argc = option_end_index;
3016 char **v8argv = argv;
3018 if (debug_wait_connect) {
3019 // v8argv is a copy of argv up to the script file argument +2 if --debug-brk
3020 // to expose the v8 debugger js object so that node.js can set
3021 // a breakpoint on the first line of the startup script
3023 v8argv = new char*[v8argc];
3024 memcpy(v8argv, argv, sizeof(*argv) * option_end_index);
3025 v8argv[option_end_index] = const_cast<char*>("--expose_debug_as");
3026 v8argv[option_end_index + 1] = const_cast<char*>("v8debug");
3029 // For the normal stack which moves from high to low addresses when frames
3030 // are pushed, we can compute the limit as stack_size bytes below the
3031 // the address of a stack variable (e.g. &stack_var) as an approximation
3032 // of the start of the stack (we're assuming that we haven't pushed a lot
3034 if (max_stack_size != 0) {
3036 ResourceConstraints constraints;
3038 uint32_t *stack_limit = &stack_var - (max_stack_size / sizeof(uint32_t));
3039 constraints.set_stack_limit(stack_limit);
3040 SetResourceConstraints(&constraints); // Must be done before V8::Initialize
3042 V8::SetFlagsFromCommandLine(&v8argc, v8argv, false);
3044 const char typed_arrays_flag[] = "--harmony_typed_arrays";
3045 V8::SetFlagsFromString(typed_arrays_flag, sizeof(typed_arrays_flag) - 1);
3046 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3048 // Fetch a reference to the main isolate, so we have a reference to it
3049 // even when we need it to access it from another (debugger) thread.
3050 node_isolate = Isolate::GetCurrent();
3054 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3055 RegisterSignalHandler(SIGINT, SignalExit);
3056 RegisterSignalHandler(SIGTERM, SignalExit);
3059 uv_check_init(uv_default_loop(), &check_immediate_watcher);
3060 uv_unref(reinterpret_cast<uv_handle_t*>(&check_immediate_watcher));
3061 uv_idle_init(uv_default_loop(), &idle_immediate_dummy);
3063 V8::SetFatalErrorHandler(node::OnFatalError);
3064 V8::AddMessageListener(OnMessage);
3066 // If the --debug flag was specified then initialize the debug thread.
3067 if (use_debug_agent) {
3068 EnableDebug(debug_wait_connect);
3071 RegisterDebugSignalHandler();
3073 static uv_signal_t signal_watcher;
3074 uv_signal_init(uv_default_loop(), &signal_watcher);
3075 uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1);
3076 uv_unref(reinterpret_cast<uv_handle_t*>(&signal_watcher));
3084 struct AtExitCallback {
3085 AtExitCallback* next_;
3086 void (*cb_)(void* arg);
3090 static AtExitCallback* at_exit_functions_;
3094 AtExitCallback* p = at_exit_functions_;
3095 at_exit_functions_ = NULL;
3098 AtExitCallback* q = p->next_;
3106 void AtExit(void (*cb)(void* arg), void* arg) {
3107 AtExitCallback* p = new AtExitCallback;
3110 p->next_ = at_exit_functions_;
3111 at_exit_functions_ = p;
3115 void EmitExit(v8::Handle<v8::Object> process_l) {
3116 // process.emit('exit')
3117 process_l->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3118 True(node_isolate));
3119 Local<Value> args[] = {
3120 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3121 Integer::New(0, node_isolate)
3123 MakeCallback(process_l, "emit", ARRAY_SIZE(args), args);
3126 static char **copy_argv(int argc, char **argv) {
3134 for (i = 0; i < argc; i++) {
3135 strlen_sum += strlen(argv[i]) + 1;
3138 argv_copy = static_cast<char**>(
3139 malloc(sizeof(*argv_copy) * (argc + 1) + strlen_sum));
3144 argv_data = reinterpret_cast<char*>(argv_copy) +
3145 sizeof(*argv_copy) * (argc + 1);
3147 for (i = 0; i < argc; i++) {
3148 argv_copy[i] = argv_data;
3149 len = strlen(argv[i]) + 1;
3150 memcpy(argv_data, argv[i], len);
3154 argv_copy[argc] = NULL;
3159 int Start(int argc, char *argv[]) {
3160 // Hack aroung with the argv pointer. Used for process.title = "blah".
3161 argv = uv_setup_args(argc, argv);
3163 // Logic to duplicate argv as Init() modifies arguments
3164 // that are passed into it.
3165 char **argv_copy = copy_argv(argc, argv);
3167 // This needs to run *before* V8::Initialize()
3168 // Use copy here as to not modify the original argv:
3169 Init(argc, argv_copy);
3173 Locker locker(node_isolate);
3174 HandleScope handle_scope(node_isolate);
3176 // Create the one and only Context.
3177 Local<Context> context = Context::New(node_isolate);
3178 Context::Scope context_scope(context);
3180 binding_cache.Reset(node_isolate, Object::New());
3182 // Use original argv, as we're just copying values out of it.
3183 Local<Object> process_l = SetupProcessObject(argc, argv);
3185 // Create all the objects, load modules, do everything.
3186 // so your next reading stop should be node::Load()!
3189 // All our arguments are loaded. We've evaluated all of the scripts. We
3190 // might even have created TCP servers. Now we enter the main eventloop. If
3191 // there are no watchers on the loop (except for the ones that were
3192 // uv_unref'd) then this function exits. As long as there are active
3193 // watchers, it blocks.
3194 uv_run(uv_default_loop(), UV_RUN_DEFAULT);
3196 EmitExit(process_l);
3201 // Clean up. Not strictly necessary.
3205 // Clean up the copy: