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;
135 static Persistent<Array> p_domain_box;
137 static Cached<String> exports_symbol;
139 static Cached<String> errno_symbol;
140 static Cached<String> syscall_symbol;
141 static Cached<String> errpath_symbol;
142 static Cached<String> code_symbol;
144 static Cached<String> rss_symbol;
145 static Cached<String> heap_total_symbol;
146 static Cached<String> heap_used_symbol;
148 static Cached<String> fatal_exception_symbol;
150 static Cached<String> enter_symbol;
151 static Cached<String> exit_symbol;
152 static Cached<String> disposed_symbol;
154 // Essential for node_wrap.h
155 Persistent<FunctionTemplate> pipeConstructorTmpl;
156 Persistent<FunctionTemplate> tcpConstructorTmpl;
157 Persistent<FunctionTemplate> ttyConstructorTmpl;
159 static bool print_eval = false;
160 static bool force_repl = false;
161 static bool trace_deprecation = false;
162 static bool throw_deprecation = false;
163 static char *eval_string = NULL;
164 static int option_end_index = 0;
165 static bool use_debug_agent = false;
166 static bool debug_wait_connect = false;
167 static int debug_port = 5858;
168 static int max_stack_size = 0;
169 bool using_domains = false;
171 // used by C++ modules as well
172 bool no_deprecation = false;
174 static uv_check_t check_immediate_watcher;
175 static uv_idle_t idle_immediate_dummy;
176 static bool need_immediate_cb;
177 static Cached<String> immediate_callback_sym;
179 // for quick ref to tickCallback values
187 // easily communicate domain depth
192 #ifdef OPENSSL_NPN_NEGOTIATED
193 static bool use_npn = true;
195 static bool use_npn = false;
198 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
199 static bool use_sni = true;
201 static bool use_sni = false;
204 // process-relative uptime base, initialized at start-up
205 static double prog_start_time;
207 static volatile bool debugger_running = false;
208 static uv_async_t dispatch_debug_messages_async;
209 static uv_async_t emit_debug_enabled_async;
211 // Declared in node_internals.h
212 Isolate* node_isolate = NULL;
215 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
217 // Impose an upper limit to avoid out of memory errors that bring down
219 static const size_t kMaxLength = 0x3fffffff;
220 static ArrayBufferAllocator the_singleton;
221 virtual ~ArrayBufferAllocator() {}
222 virtual void* Allocate(size_t length);
223 virtual void Free(void* data);
225 ArrayBufferAllocator() {}
226 ArrayBufferAllocator(const ArrayBufferAllocator&);
227 void operator=(const ArrayBufferAllocator&);
230 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
233 void* ArrayBufferAllocator::Allocate(size_t length) {
234 if (length > kMaxLength) return NULL;
235 return new char[length];
239 void ArrayBufferAllocator::Free(void* data) {
240 delete[] static_cast<char*>(data);
244 static void CheckImmediate(uv_check_t* handle, int status) {
245 assert(handle == &check_immediate_watcher);
248 HandleScope scope(node_isolate);
250 if (immediate_callback_sym.IsEmpty()) {
251 immediate_callback_sym =
252 FIXED_ONE_BYTE_STRING(node_isolate, "_immediateCallback");
255 MakeCallback(process_p, immediate_callback_sym, 0, NULL);
259 static void IdleImmediateDummy(uv_idle_t* handle, int status) {
260 // Do nothing. Only for maintaining event loop
261 assert(handle == &idle_immediate_dummy);
266 static inline const char *errno_string(int errorno) {
267 #define ERRNO_CASE(e) case e: return #e;
274 ERRNO_CASE(EADDRINUSE);
278 ERRNO_CASE(EADDRNOTAVAIL);
282 ERRNO_CASE(EAFNOSUPPORT);
290 # if EAGAIN != EWOULDBLOCK
291 ERRNO_CASE(EWOULDBLOCK);
296 ERRNO_CASE(EALREADY);
312 ERRNO_CASE(ECANCELED);
320 ERRNO_CASE(ECONNABORTED);
324 ERRNO_CASE(ECONNREFUSED);
328 ERRNO_CASE(ECONNRESET);
336 ERRNO_CASE(EDESTADDRREQ);
360 ERRNO_CASE(EHOSTUNREACH);
372 ERRNO_CASE(EINPROGRESS);
408 ERRNO_CASE(EMSGSIZE);
412 ERRNO_CASE(EMULTIHOP);
416 ERRNO_CASE(ENAMETOOLONG);
420 ERRNO_CASE(ENETDOWN);
424 ERRNO_CASE(ENETRESET);
428 ERRNO_CASE(ENETUNREACH);
460 # if ENOLINK != ENOLCK
474 ERRNO_CASE(ENOPROTOOPT);
494 ERRNO_CASE(ENOTCONN);
502 ERRNO_CASE(ENOTEMPTY);
506 ERRNO_CASE(ENOTSOCK);
513 ERRNO_CASE(EOPNOTSUPP);
527 ERRNO_CASE(EOVERFLOW);
542 #ifdef EPROTONOSUPPORT
543 ERRNO_CASE(EPROTONOSUPPORT);
547 ERRNO_CASE(EPROTOTYPE);
575 ERRNO_CASE(ETIMEDOUT);
590 const char *signo_string(int signo) {
591 #define SIGNO_CASE(e) case e: return #e;
618 # if SIGABRT != SIGIOT
662 SIGNO_CASE(SIGSTKFLT);
679 SIGNO_CASE(SIGBREAK);
703 SIGNO_CASE(SIGVTALRM);
711 SIGNO_CASE(SIGWINCH);
719 # if SIGPOLL != SIGIO
729 # if SIGPWR != SIGLOST
743 Local<Value> ErrnoException(int errorno,
748 Local<String> estring = OneByteString(node_isolate, errno_string(errorno));
749 if (msg == NULL || msg[0] == '\0') {
750 msg = strerror(errorno);
752 Local<String> message = OneByteString(node_isolate, msg);
754 Local<String> cons1 =
755 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
756 Local<String> cons2 = String::Concat(cons1, message);
758 if (syscall_symbol.IsEmpty()) {
759 syscall_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "syscall");
760 errno_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "errno");
761 errpath_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "path");
762 code_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "code");
766 Local<String> cons3 =
767 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
768 Local<String> cons4 =
769 String::Concat(cons3, String::NewFromUtf8(node_isolate, path));
770 Local<String> cons5 =
771 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
772 e = Exception::Error(cons5);
774 e = Exception::Error(cons2);
777 Local<Object> obj = e->ToObject();
779 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
780 obj->Set(code_symbol, estring);
781 if (path) obj->Set(errpath_symbol, String::NewFromUtf8(node_isolate, path));
782 if (syscall) obj->Set(syscall_symbol, OneByteString(node_isolate, syscall));
787 // hack alert! copy of ErrnoException, tuned for uv errors
788 Local<Value> UVException(int errorno,
792 if (syscall_symbol.IsEmpty()) {
793 syscall_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "syscall");
794 errno_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "errno");
795 errpath_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "path");
796 code_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "code");
800 msg = uv_strerror(errorno);
802 Local<String> estring = OneByteString(node_isolate, uv_err_name(errorno));
803 Local<String> message = OneByteString(node_isolate, msg);
804 Local<String> cons1 =
805 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
806 Local<String> cons2 = String::Concat(cons1, message);
810 Local<String> path_str;
814 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
815 path_str = String::Concat(FIXED_ONE_BYTE_STRING(node_isolate, "\\\\"),
816 String::NewFromUtf8(node_isolate, path + 8));
817 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
818 path_str = String::NewFromUtf8(node_isolate, path + 4);
820 path_str = String::NewFromUtf8(node_isolate, path);
823 path_str = String::NewFromUtf8(node_isolate, path);
826 Local<String> cons3 =
827 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
828 Local<String> cons4 =
829 String::Concat(cons3, path_str);
830 Local<String> cons5 =
831 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
832 e = Exception::Error(cons5);
834 e = Exception::Error(cons2);
837 Local<Object> obj = e->ToObject();
839 // TODO(piscisaureus) errno should probably go
840 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
841 obj->Set(code_symbol, estring);
842 if (path) obj->Set(errpath_symbol, path_str);
843 if (syscall) obj->Set(syscall_symbol, OneByteString(node_isolate, syscall));
849 // Does about the same as strerror(),
850 // but supports all windows error messages
851 static const char *winapi_strerror(const int errorno) {
854 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
855 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
856 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
859 // Remove trailing newlines
860 for (int i = strlen(errmsg) - 1;
861 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
867 // FormatMessage failed
868 return "Unknown error";
873 Local<Value> WinapiErrnoException(int errorno,
878 if (!msg || !msg[0]) {
879 msg = winapi_strerror(errorno);
881 Local<String> message = OneByteString(node_isolate, msg);
883 if (syscall_symbol.IsEmpty()) {
884 syscall_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "syscall");
885 errno_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "errno");
886 errpath_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "path");
887 code_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "code");
891 Local<String> cons1 =
892 String::Concat(message, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
893 Local<String> cons2 =
894 String::Concat(cons1, String::NewFromUtf8(node_isolate, path));
895 Local<String> cons3 =
896 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
897 e = Exception::Error(cons3);
899 e = Exception::Error(message);
902 Local<Object> obj = e->ToObject();
904 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
905 if (path) obj->Set(errpath_symbol, String::NewFromUtf8(node_isolate, path));
906 if (syscall) obj->Set(syscall_symbol, OneByteString(node_isolate, syscall));
912 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
913 if (using_domains) return;
914 HandleScope scope(node_isolate);
915 using_domains = true;
916 Local<Object> process = PersistentToLocal(node_isolate, process_p);
918 process->Get(FIXED_ONE_BYTE_STRING(node_isolate, "_tickDomainCallback"));
919 if (!tdc_v->IsFunction()) {
920 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
923 Local<Function> tdc = tdc_v.As<Function>();
924 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"), tdc);
925 process_tickCallback.Reset(node_isolate, tdc);
926 if (!args[0]->IsArray()) {
927 fprintf(stderr, "_setupDomainUse first argument must be an array\n");
930 p_domain_box.Reset(node_isolate, args[0].As<Array>());
931 if (!args[1]->IsObject()) {
932 fprintf(stderr, "_setupDomainUse second argument must be an object\n");
935 Local<Object> flag = args[1].As<Object>();
936 flag->SetIndexedPropertiesToExternalArrayData(&domain_flag,
937 kExternalUnsignedIntArray,
943 return using_domains && domain_flag.count > 0;
947 Handle<Value> GetDomain() {
948 // no domain can exist if no domain module has been loaded
949 if (!InDomain() || p_domain_box.IsEmpty())
950 return Null(node_isolate);
952 return PersistentToLocal(node_isolate, p_domain_box)->Get(0);
957 MakeDomainCallback(const Handle<Object> object,
958 const Handle<Function> callback,
960 Handle<Value> argv[]) {
961 // TODO(trevnorris) Hook for long stack traces to be made here.
963 // lazy load domain specific symbols
964 if (enter_symbol.IsEmpty()) {
965 enter_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "enter");
966 exit_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "exit");
967 disposed_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "_disposed");
970 Local<Value> domain_v = object->Get(domain_symbol);
971 Local<Object> domain;
972 Local<Function> enter;
973 Local<Function> exit;
976 try_catch.SetVerbose(true);
978 bool has_domain = domain_v->IsObject();
980 domain = domain_v->ToObject();
981 assert(!domain.IsEmpty());
982 if (domain->Get(disposed_symbol)->IsTrue()) {
983 // domain has been disposed of.
984 return Undefined(node_isolate);
986 enter = Local<Function>::Cast(domain->Get(enter_symbol));
987 assert(!enter.IsEmpty());
988 enter->Call(domain, 0, NULL);
990 if (try_catch.HasCaught()) {
991 return Undefined(node_isolate);
995 Local<Value> ret = callback->Call(object, argc, argv);
997 if (try_catch.HasCaught()) {
998 return Undefined(node_isolate);
1002 exit = Local<Function>::Cast(domain->Get(exit_symbol));
1003 assert(!exit.IsEmpty());
1004 exit->Call(domain, 0, NULL);
1006 if (try_catch.HasCaught()) {
1007 return Undefined(node_isolate);
1011 if (tick_infobox.last_threw == 1) {
1012 tick_infobox.last_threw = 0;
1016 if (tick_infobox.in_tick == 1) {
1020 if (tick_infobox.length == 0) {
1021 tick_infobox.index = 0;
1025 // process nextTicks after call
1026 Local<Object> process = PersistentToLocal(node_isolate, process_p);
1027 Local<Function> fn = PersistentToLocal(node_isolate, process_tickCallback);
1028 fn->Call(process, 0, NULL);
1030 if (try_catch.HasCaught()) {
1031 return Undefined(node_isolate);
1039 MakeCallback(const Handle<Object> object,
1040 const Handle<Function> callback,
1042 Handle<Value> argv[]) {
1043 // TODO(trevnorris) Hook for long stack traces to be made here.
1044 Local<Object> process = PersistentToLocal(node_isolate, process_p);
1047 return MakeDomainCallback(object, callback, argc, argv);
1049 // lazy load no domain next tick callbacks
1050 if (process_tickCallback.IsEmpty()) {
1052 process->Get(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"));
1053 if (!cb_v->IsFunction()) {
1054 fprintf(stderr, "process._tickCallback assigned to non-function\n");
1057 process_tickCallback.Reset(node_isolate, cb_v.As<Function>());
1061 try_catch.SetVerbose(true);
1063 Local<Value> ret = callback->Call(object, argc, argv);
1065 if (try_catch.HasCaught()) {
1066 return Undefined(node_isolate);
1069 if (tick_infobox.in_tick == 1) {
1073 if (tick_infobox.length == 0) {
1074 tick_infobox.index = 0;
1078 // process nextTicks after call
1079 Local<Function> fn = PersistentToLocal(node_isolate, process_tickCallback);
1080 fn->Call(process, 0, NULL);
1082 if (try_catch.HasCaught()) {
1083 return Undefined(node_isolate);
1091 MakeCallback(const Handle<Object> object,
1092 const Handle<String> symbol,
1094 Handle<Value> argv[]) {
1095 HandleScope scope(node_isolate);
1097 Local<Function> callback = object->Get(symbol).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,
1110 Handle<Value> argv[]) {
1111 HandleScope scope(node_isolate);
1113 Local<String> method_string = OneByteString(node_isolate, method);
1114 Handle<Value> ret = MakeCallback(object, method_string, argc, argv);
1116 return scope.Close(ret);
1120 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1121 HandleScope scope(node_isolate);
1123 if (!encoding_v->IsString()) return _default;
1125 String::Utf8Value encoding(encoding_v);
1127 if (strcasecmp(*encoding, "utf8") == 0) {
1129 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1131 } else if (strcasecmp(*encoding, "ascii") == 0) {
1133 } else if (strcasecmp(*encoding, "base64") == 0) {
1135 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1137 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1139 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1141 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1143 } else if (strcasecmp(*encoding, "binary") == 0) {
1145 } else if (strcasecmp(*encoding, "buffer") == 0) {
1147 } else if (strcasecmp(*encoding, "hex") == 0) {
1149 } else if (strcasecmp(*encoding, "raw") == 0) {
1150 if (!no_deprecation) {
1151 fprintf(stderr, "'raw' (array of integers) has been removed. "
1155 } else if (strcasecmp(*encoding, "raws") == 0) {
1156 if (!no_deprecation) {
1157 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1158 "Please update your code.\n");
1166 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1167 return StringBytes::Encode(static_cast<const char*>(buf),
1172 // Returns -1 if the handle was not valid for decoding
1173 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1174 HandleScope scope(node_isolate);
1176 if (val->IsArray()) {
1177 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1183 return StringBytes::Size(val, encoding);
1187 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1190 // Returns number of bytes written.
1191 ssize_t DecodeWrite(char *buf,
1193 v8::Handle<v8::Value> val,
1194 enum encoding encoding) {
1195 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1198 void DisplayExceptionLine(Handle<Message> message) {
1199 // Prevent re-entry into this function. For example, if there is
1200 // a throw from a program in vm.runInThisContext(code, filename, true),
1201 // then we want to show the original failure, not the secondary one.
1202 static bool displayed_error = false;
1204 if (displayed_error) return;
1205 displayed_error = true;
1207 uv_tty_reset_mode();
1209 fprintf(stderr, "\n");
1211 if (!message.IsEmpty()) {
1212 // Print (filename):(line number): (message).
1213 String::Utf8Value filename(message->GetScriptResourceName());
1214 const char* filename_string = *filename;
1215 int linenum = message->GetLineNumber();
1216 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1217 // Print line of source code.
1218 String::Utf8Value sourceline(message->GetSourceLine());
1219 const char* sourceline_string = *sourceline;
1221 // Because of how node modules work, all scripts are wrapped with a
1222 // "function (module, exports, __filename, ...) {"
1223 // to provide script local variables.
1225 // When reporting errors on the first line of a script, this wrapper
1226 // function is leaked to the user. There used to be a hack here to
1227 // truncate off the first 62 characters, but it caused numerous other
1228 // problems when vm.runIn*Context() methods were used for non-module
1231 // If we ever decide to re-instate such a hack, the following steps
1234 // 1. Pass a flag around to say "this code was wrapped"
1235 // 2. Update the stack frame output so that it is also correct.
1237 // It would probably be simpler to add a line rather than add some
1238 // number of characters to the first line, since V8 truncates the
1239 // sourceline to 78 characters, and we end up not providing very much
1240 // useful debugging info to the user if we remove 62 characters.
1242 int start = message->GetStartColumn();
1243 int end = message->GetEndColumn();
1245 fprintf(stderr, "%s\n", sourceline_string);
1246 // Print wavy underline (GetUnderline is deprecated).
1247 for (int i = 0; i < start; i++) {
1248 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1250 for (int i = start; i < end; i++) {
1253 fputc('\n', stderr);
1258 static void ReportException(Handle<Value> er, Handle<Message> message) {
1259 HandleScope scope(node_isolate);
1261 DisplayExceptionLine(message);
1263 Local<Value> trace_value(
1264 er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack")));
1265 String::Utf8Value trace(trace_value);
1267 // range errors have a trace member set to undefined
1268 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1269 fprintf(stderr, "%s\n", *trace);
1271 // this really only happens for RangeErrors, since they're the only
1272 // kind that won't have all this info in the trace, or when non-Error
1273 // objects are thrown manually.
1274 Local<Value> message;
1277 if (er->IsObject()) {
1278 Local<Object> err_obj = er.As<Object>();
1279 message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1280 name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1283 if (message.IsEmpty() ||
1284 message->IsUndefined() ||
1286 name->IsUndefined()) {
1287 // Not an error object. Just print as-is.
1288 String::Utf8Value message(er);
1289 fprintf(stderr, "%s\n", *message);
1291 String::Utf8Value name_string(name);
1292 String::Utf8Value message_string(message);
1293 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1301 static void ReportException(const TryCatch& try_catch) {
1302 ReportException(try_catch.Exception(), try_catch.Message());
1306 // Executes a str within the current v8 context.
1307 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1308 HandleScope scope(node_isolate);
1311 // try_catch must be nonverbose to disable FatalException() handler,
1312 // we will handle exceptions ourself.
1313 try_catch.SetVerbose(false);
1315 Local<v8::Script> script = v8::Script::Compile(source, filename);
1316 if (script.IsEmpty()) {
1317 ReportException(try_catch);
1321 Local<Value> result = script->Run();
1322 if (result.IsEmpty()) {
1323 ReportException(try_catch);
1327 return scope.Close(result);
1331 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1332 HandleScope scope(node_isolate);
1334 Local<Array> ary = Array::New();
1338 QUEUE_FOREACH(q, &req_wrap_queue) {
1339 ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1340 if (w->persistent().IsEmpty()) continue;
1341 ary->Set(i++, w->object());
1344 args.GetReturnValue().Set(ary);
1348 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1349 // implemented here for consistency with GetActiveRequests().
1350 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1351 HandleScope scope(node_isolate);
1353 Local<Array> ary = Array::New();
1357 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1359 QUEUE_FOREACH(q, &handle_wrap_queue) {
1360 HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1361 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue;
1362 Local<Object> object = w->object();
1363 Local<Value> owner = object->Get(owner_sym);
1364 if (owner->IsUndefined()) owner = object;
1365 ary->Set(i++, owner);
1368 args.GetReturnValue().Set(ary);
1372 static void Abort(const FunctionCallbackInfo<Value>& args) {
1377 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1378 HandleScope scope(node_isolate);
1380 if (args.Length() != 1 || !args[0]->IsString()) {
1381 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1384 String::Utf8Value path(args[0]);
1385 int err = uv_chdir(*path);
1387 return ThrowUVException(err, "uv_chdir");
1392 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1393 HandleScope scope(node_isolate);
1395 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1396 char buf[MAX_PATH * 4 + 1];
1398 char buf[PATH_MAX + 1];
1401 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1403 return ThrowUVException(err, "uv_cwd");
1406 buf[ARRAY_SIZE(buf) - 1] = '\0';
1407 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1409 args.GetReturnValue().Set(cwd);
1413 static void Umask(const FunctionCallbackInfo<Value>& args) {
1414 HandleScope scope(node_isolate);
1417 if (args.Length() < 1 || args[0]->IsUndefined()) {
1419 umask(static_cast<mode_t>(old));
1420 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1421 return ThrowTypeError("argument must be an integer or octal string.");
1424 if (args[0]->IsInt32()) {
1425 oct = args[0]->Uint32Value();
1428 String::Utf8Value str(args[0]);
1430 // Parse the octal string.
1431 for (int i = 0; i < str.length(); i++) {
1433 if (c > '7' || c < '0') {
1434 return ThrowTypeError("invalid octal string");
1440 old = umask(static_cast<mode_t>(oct));
1443 args.GetReturnValue().Set(old);
1447 #if defined(__POSIX__) && !defined(__ANDROID__)
1449 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1450 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1453 static uid_t uid_by_name(const char* name) {
1461 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1465 return uid_not_found;
1469 static char* name_by_uid(uid_t uid) {
1478 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1479 return strdup(pp->pw_name);
1490 static gid_t gid_by_name(const char* name) {
1498 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1502 return gid_not_found;
1506 #if 0 // For future use.
1507 static const char* name_by_gid(gid_t gid) {
1516 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1517 return strdup(pp->gr_name);
1529 static uid_t uid_by_name(Handle<Value> value) {
1530 if (value->IsUint32()) {
1531 return static_cast<uid_t>(value->Uint32Value());
1533 String::Utf8Value name(value);
1534 return uid_by_name(*name);
1539 static gid_t gid_by_name(Handle<Value> value) {
1540 if (value->IsUint32()) {
1541 return static_cast<gid_t>(value->Uint32Value());
1543 String::Utf8Value name(value);
1544 return gid_by_name(*name);
1549 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1550 args.GetReturnValue().Set(getuid());
1554 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1555 args.GetReturnValue().Set(getgid());
1559 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1560 HandleScope scope(node_isolate);
1562 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1563 return ThrowTypeError("setgid argument must be a number or a string");
1566 gid_t gid = gid_by_name(args[0]);
1568 if (gid == gid_not_found) {
1569 return ThrowError("setgid group id does not exist");
1573 return ThrowErrnoException(errno, "setgid");
1578 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1579 HandleScope scope(node_isolate);
1581 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1582 return ThrowTypeError("setuid argument must be a number or a string");
1585 uid_t uid = uid_by_name(args[0]);
1587 if (uid == uid_not_found) {
1588 return ThrowError("setuid user id does not exist");
1592 return ThrowErrnoException(errno, "setuid");
1597 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1598 HandleScope scope(node_isolate);
1600 int ngroups = getgroups(0, NULL);
1602 if (ngroups == -1) {
1603 return ThrowErrnoException(errno, "getgroups");
1606 gid_t* groups = new gid_t[ngroups];
1608 ngroups = getgroups(ngroups, groups);
1610 if (ngroups == -1) {
1612 return ThrowErrnoException(errno, "getgroups");
1615 Local<Array> groups_list = Array::New(ngroups);
1616 bool seen_egid = false;
1617 gid_t egid = getegid();
1619 for (int i = 0; i < ngroups; i++) {
1620 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1621 if (groups[i] == egid) seen_egid = true;
1626 if (seen_egid == false) {
1627 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1630 args.GetReturnValue().Set(groups_list);
1634 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1635 HandleScope scope(node_isolate);
1637 if (!args[0]->IsArray()) {
1638 return ThrowTypeError("argument 1 must be an array");
1641 Local<Array> groups_list = args[0].As<Array>();
1642 size_t size = groups_list->Length();
1643 gid_t* groups = new gid_t[size];
1645 for (size_t i = 0; i < size; i++) {
1646 gid_t gid = gid_by_name(groups_list->Get(i));
1648 if (gid == gid_not_found) {
1650 return ThrowError("group name not found");
1656 int rc = setgroups(size, groups);
1660 return ThrowErrnoException(errno, "setgroups");
1665 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1666 HandleScope scope(node_isolate);
1668 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1669 return ThrowTypeError("argument 1 must be a number or a string");
1672 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1673 return ThrowTypeError("argument 2 must be a number or a string");
1676 String::Utf8Value arg0(args[0]);
1681 if (args[0]->IsUint32()) {
1682 user = name_by_uid(args[0]->Uint32Value());
1690 return ThrowError("initgroups user not found");
1693 extra_group = gid_by_name(args[1]);
1695 if (extra_group == gid_not_found) {
1696 if (must_free) free(user);
1697 return ThrowError("initgroups extra group not found");
1700 int rc = initgroups(user, extra_group);
1707 return ThrowErrnoException(errno, "initgroups");
1711 #endif // __POSIX__ && !defined(__ANDROID__)
1714 void Exit(const FunctionCallbackInfo<Value>& args) {
1715 HandleScope scope(node_isolate);
1716 exit(args[0]->IntegerValue());
1720 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1721 HandleScope scope(node_isolate);
1723 if (uv_uptime(&uptime)) return;
1724 args.GetReturnValue().Set(uptime - prog_start_time);
1728 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1729 HandleScope scope(node_isolate);
1733 int err = uv_resident_set_memory(&rss);
1735 return ThrowUVException(err, "uv_resident_set_memory");
1738 Local<Object> info = Object::New();
1740 if (rss_symbol.IsEmpty()) {
1741 rss_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "rss");
1742 heap_total_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "heapTotal");
1743 heap_used_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "heapUsed");
1746 info->Set(rss_symbol, Number::New(rss));
1749 HeapStatistics v8_heap_stats;
1750 node_isolate->GetHeapStatistics(&v8_heap_stats);
1751 info->Set(heap_total_symbol,
1752 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(),
1754 info->Set(heap_used_symbol,
1755 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(),
1758 args.GetReturnValue().Set(info);
1762 void Kill(const FunctionCallbackInfo<Value>& args) {
1763 HandleScope scope(node_isolate);
1765 if (args.Length() != 2) {
1766 return ThrowError("Bad argument.");
1769 int pid = args[0]->IntegerValue();
1770 int sig = args[1]->Int32Value();
1771 int err = uv_kill(pid, sig);
1772 args.GetReturnValue().Set(err);
1775 // used in Hrtime() below
1776 #define NANOS_PER_SEC 1000000000
1778 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1779 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1780 // so this function instead returns an Array with 2 entries representing seconds
1781 // and nanoseconds, to avoid any integer overflow possibility.
1782 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1783 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1784 HandleScope scope(node_isolate);
1786 uint64_t t = uv_hrtime();
1788 if (args.Length() > 0) {
1789 // return a time diff tuple
1790 if (!args[0]->IsArray()) {
1791 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1793 Local<Array> inArray = Local<Array>::Cast(args[0]);
1794 uint64_t seconds = inArray->Get(0)->Uint32Value();
1795 uint64_t nanos = inArray->Get(1)->Uint32Value();
1796 t -= (seconds * NANOS_PER_SEC) + nanos;
1799 Local<Array> tuple = Array::New(2);
1800 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1801 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1802 args.GetReturnValue().Set(tuple);
1806 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1808 // DLOpen is process.dlopen(module, filename).
1809 // Used to load 'module.node' dynamically shared objects.
1810 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1811 HandleScope scope(node_isolate);
1812 char symbol[1024], *base, *pos;
1816 if (args.Length() < 2) {
1817 return ThrowError("process.dlopen takes exactly 2 arguments.");
1820 Local<Object> module = args[0]->ToObject(); // Cast
1821 String::Utf8Value filename(args[1]); // Cast
1823 if (exports_symbol.IsEmpty()) {
1824 exports_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "exports");
1826 Local<Object> exports = module->Get(exports_symbol)->ToObject();
1828 if (uv_dlopen(*filename, &lib)) {
1829 Local<String> errmsg = OneByteString(node_isolate, uv_dlerror(&lib));
1831 // Windows needs to add the filename into the error message
1832 errmsg = String::Concat(errmsg, args[1]->ToString());
1834 ThrowException(Exception::Error(errmsg));
1838 String::Utf8Value path(args[1]);
1841 /* Find the shared library filename within the full path. */
1843 pos = strrchr(base, '/');
1849 pos = strpbrk(base, "\\/:");
1857 /* Strip the .node extension. */
1858 pos = strrchr(base, '.');
1863 /* Add the `_module` suffix to the extension name. */
1864 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1865 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1866 return ThrowError("Out of memory.");
1869 /* Replace dashes with underscores. When loading foo-bar.node,
1870 * look for foo_bar_module, not foo-bar_module.
1872 for (pos = symbol; *pos != '\0'; ++pos) {
1873 if (*pos == '-') *pos = '_';
1876 node_module_struct *mod;
1877 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1879 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1880 return ThrowError(errmsg);
1883 if (mod->version != NODE_MODULE_VERSION) {
1887 "Module version mismatch. Expected %d, got %d.",
1888 NODE_MODULE_VERSION, mod->version);
1889 return ThrowError(errmsg);
1892 // Execute the C++ module
1893 mod->register_func(exports, module);
1895 // Tell coverity that 'handle' should not be freed when we return.
1896 // coverity[leaked_storage]
1900 static void OnFatalError(const char* location, const char* message) {
1902 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1904 fprintf(stderr, "FATAL ERROR: %s\n", message);
1914 NO_RETURN void FatalError(const char* location, const char* message) {
1915 OnFatalError(location, message);
1916 // to supress compiler warning
1921 void FatalException(Handle<Value> error, Handle<Message> message) {
1922 HandleScope scope(node_isolate);
1924 if (fatal_exception_symbol.IsEmpty()) {
1925 fatal_exception_symbol =
1926 FIXED_ONE_BYTE_STRING(node_isolate, "_fatalException");
1929 Local<Object> process = PersistentToLocal(node_isolate, process_p);
1930 Local<Value> fatal_v = process->Get(fatal_exception_symbol);
1932 if (!fatal_v->IsFunction()) {
1933 // failed before the process._fatalException function was added!
1934 // this is probably pretty bad. Nothing to do but report and exit.
1935 ReportException(error, message);
1939 Local<Function> fatal_f = Local<Function>::Cast(fatal_v);
1941 TryCatch fatal_try_catch;
1943 // Do not call FatalException when _fatalException handler throws
1944 fatal_try_catch.SetVerbose(false);
1946 // this will return true if the JS layer handled it, false otherwise
1947 Local<Value> caught = fatal_f->Call(process, 1, &error);
1949 if (fatal_try_catch.HasCaught()) {
1950 // the fatal exception function threw, so we must exit
1951 ReportException(fatal_try_catch);
1955 if (false == caught->BooleanValue()) {
1956 ReportException(error, message);
1962 void FatalException(const TryCatch& try_catch) {
1963 HandleScope scope(node_isolate);
1964 // TODO(bajtos) do not call FatalException if try_catch is verbose
1965 // (requires V8 API to expose getter for try_catch.is_verbose_)
1966 FatalException(try_catch.Exception(), try_catch.Message());
1970 void OnMessage(Handle<Message> message, Handle<Value> error) {
1971 // The current version of V8 sends messages for errors only
1972 // (thus `error` is always set).
1973 FatalException(error, message);
1977 static void Binding(const FunctionCallbackInfo<Value>& args) {
1978 HandleScope scope(node_isolate);
1980 Local<String> module = args[0]->ToString();
1981 String::Utf8Value module_v(module);
1982 node_module_struct* modp;
1984 Local<Object> cache = PersistentToLocal(node_isolate, binding_cache);
1985 Local<Object> exports;
1987 if (cache->Has(module)) {
1988 exports = cache->Get(module)->ToObject();
1989 args.GetReturnValue().Set(exports);
1993 // Append a string to process.moduleLoadList
1995 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
1997 Local<Array> modules = PersistentToLocal(node_isolate, module_load_list);
1998 uint32_t l = modules->Length();
1999 modules->Set(l, OneByteString(node_isolate, buf));
2001 if ((modp = get_builtin_module(*module_v)) != NULL) {
2002 exports = Object::New();
2003 // Internal bindings don't have a "module" object,
2005 modp->register_func(exports, Undefined(node_isolate));
2006 cache->Set(module, exports);
2007 } else if (!strcmp(*module_v, "constants")) {
2008 exports = Object::New();
2009 DefineConstants(exports);
2010 cache->Set(module, exports);
2011 } else if (!strcmp(*module_v, "natives")) {
2012 exports = Object::New();
2013 DefineJavaScript(exports);
2014 cache->Set(module, exports);
2016 return ThrowError("No such module");
2019 args.GetReturnValue().Set(exports);
2023 static void ProcessTitleGetter(Local<String> property,
2024 const PropertyCallbackInfo<Value>& info) {
2025 HandleScope scope(node_isolate);
2027 uv_get_process_title(buffer, sizeof(buffer));
2028 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2032 static void ProcessTitleSetter(Local<String> property,
2034 const PropertyCallbackInfo<void>& info) {
2035 HandleScope scope(node_isolate);
2036 String::Utf8Value title(value);
2037 // TODO(piscisaureus): protect with a lock
2038 uv_set_process_title(*title);
2042 static void EnvGetter(Local<String> property,
2043 const PropertyCallbackInfo<Value>& info) {
2044 HandleScope scope(node_isolate);
2046 String::Utf8Value key(property);
2047 const char* val = getenv(*key);
2049 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2052 String::Value key(property);
2053 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2054 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2056 ARRAY_SIZE(buffer));
2057 // If result >= sizeof buffer the buffer was too small. That should never
2058 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2060 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2061 result < ARRAY_SIZE(buffer)) {
2062 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2063 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2064 return info.GetReturnValue().Set(rc);
2067 // Not found. Fetch from prototype.
2068 info.GetReturnValue().Set(
2069 info.Data().As<Object>()->Get(property));
2073 static void EnvSetter(Local<String> property,
2075 const PropertyCallbackInfo<Value>& info) {
2076 HandleScope scope(node_isolate);
2078 String::Utf8Value key(property);
2079 String::Utf8Value val(value);
2080 setenv(*key, *val, 1);
2082 String::Value key(property);
2083 String::Value val(value);
2084 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2085 // Environment variables that start with '=' are read-only.
2086 if (key_ptr[0] != L'=') {
2087 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2090 // Whether it worked or not, always return rval.
2091 info.GetReturnValue().Set(value);
2095 static void EnvQuery(Local<String> property,
2096 const PropertyCallbackInfo<Integer>& info) {
2097 HandleScope scope(node_isolate);
2098 int32_t rc = -1; // Not found unless proven otherwise.
2100 String::Utf8Value key(property);
2101 if (getenv(*key)) rc = 0;
2103 String::Value key(property);
2104 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2105 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2106 GetLastError() == ERROR_SUCCESS) {
2108 if (key_ptr[0] == L'=') {
2109 // Environment variables that start with '=' are hidden and read-only.
2110 rc = static_cast<int32_t>(v8::ReadOnly) |
2111 static_cast<int32_t>(v8::DontDelete) |
2112 static_cast<int32_t>(v8::DontEnum);
2116 if (rc != -1) info.GetReturnValue().Set(rc);
2120 static void EnvDeleter(Local<String> property,
2121 const PropertyCallbackInfo<Boolean>& info) {
2122 HandleScope scope(node_isolate);
2125 String::Utf8Value key(property);
2126 rc = getenv(*key) != NULL;
2127 if (rc) unsetenv(*key);
2129 String::Value key(property);
2130 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2131 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2132 // Deletion failed. Return true if the key wasn't there in the first place,
2133 // false if it is still there.
2134 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2135 GetLastError() != ERROR_SUCCESS;
2138 info.GetReturnValue().Set(rc);
2142 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2143 HandleScope scope(node_isolate);
2146 while (environ[size]) size++;
2148 Local<Array> env = Array::New(size);
2150 for (int i = 0; i < size; ++i) {
2151 const char* var = environ[i];
2152 const char* s = strchr(var, '=');
2153 const int length = s ? s - var : strlen(var);
2154 Local<String> name = String::NewFromUtf8(node_isolate,
2156 String::kNormalString,
2161 WCHAR* environment = GetEnvironmentStringsW();
2162 if (environment == NULL) return; // This should not happen.
2163 Local<Array> env = Array::New();
2164 WCHAR* p = environment;
2166 while (*p != NULL) {
2169 // If the key starts with '=' it is a hidden environment variable.
2173 s = wcschr(p, L'=');
2178 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2179 const size_t two_byte_buffer_len = s - p;
2180 Local<String> value = String::NewFromTwoByte(node_isolate,
2182 String::kNormalString,
2183 two_byte_buffer_len);
2184 env->Set(i++, value);
2185 p = s + wcslen(s) + 1;
2187 FreeEnvironmentStringsW(environment);
2190 info.GetReturnValue().Set(env);
2194 static Handle<Object> GetFeatures() {
2195 HandleScope scope(node_isolate);
2197 Local<Object> obj = Object::New();
2198 #if defined(DEBUG) && DEBUG
2199 Local<Value> debug = True(node_isolate);
2201 Local<Value> debug = False(node_isolate);
2202 #endif // defined(DEBUG) && DEBUG
2204 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2206 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2207 // TODO(bnoordhuis) ping libuv
2208 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2210 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"),
2211 Boolean::New(use_npn));
2212 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"),
2213 Boolean::New(use_sni));
2214 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2215 Boolean::New(get_builtin_module("crypto") != NULL));
2217 return scope.Close(obj);
2221 static void DebugPortGetter(Local<String> property,
2222 const PropertyCallbackInfo<Value>& info) {
2223 HandleScope scope(node_isolate);
2224 info.GetReturnValue().Set(debug_port);
2228 static void DebugPortSetter(Local<String> property,
2230 const PropertyCallbackInfo<void>& info) {
2231 HandleScope scope(node_isolate);
2232 debug_port = value->NumberValue();
2236 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2237 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2238 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2241 void NeedImmediateCallbackGetter(Local<String> property,
2242 const PropertyCallbackInfo<Value>& info) {
2243 info.GetReturnValue().Set(need_immediate_cb);
2247 static void NeedImmediateCallbackSetter(Local<String> property,
2249 const PropertyCallbackInfo<void>&) {
2250 HandleScope scope(node_isolate);
2252 bool bool_value = value->BooleanValue();
2254 if (need_immediate_cb == bool_value) return;
2256 need_immediate_cb = bool_value;
2258 if (need_immediate_cb) {
2259 uv_check_start(&check_immediate_watcher, node::CheckImmediate);
2260 // idle handle is needed only to maintain event loop
2261 uv_idle_start(&idle_immediate_dummy, node::IdleImmediateDummy);
2263 uv_check_stop(&check_immediate_watcher);
2264 uv_idle_stop(&idle_immediate_dummy);
2269 #define READONLY_PROPERTY(obj, str, var) \
2271 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2275 Handle<Object> SetupProcessObject(int argc, char *argv[]) {
2276 HandleScope scope(node_isolate);
2280 Local<FunctionTemplate> process_template = FunctionTemplate::New();
2281 process_template->SetClassName(
2282 FIXED_ONE_BYTE_STRING(node_isolate, "process"));
2284 Local<Object> process = process_template->GetFunction()->NewInstance();
2285 assert(process.IsEmpty() == false);
2286 assert(process->IsObject() == true);
2288 process_p.Reset(node_isolate, process);
2290 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2292 ProcessTitleSetter);
2295 READONLY_PROPERTY(process,
2297 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2299 // process.moduleLoadList
2300 Local<Array> modules = Array::New();
2301 module_load_list.Reset(node_isolate, modules);
2302 READONLY_PROPERTY(process, "moduleLoadList", modules);
2305 Local<Object> versions = Object::New();
2306 READONLY_PROPERTY(process, "versions", versions);
2308 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2310 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2311 READONLY_PROPERTY(versions,
2313 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2315 // +1 to get rid of the leading 'v'
2316 READONLY_PROPERTY(versions,
2318 OneByteString(node_isolate, NODE_VERSION + 1));
2319 READONLY_PROPERTY(versions,
2321 OneByteString(node_isolate, V8::GetVersion()));
2322 READONLY_PROPERTY(versions,
2324 OneByteString(node_isolate, uv_version_string()));
2325 READONLY_PROPERTY(versions,
2327 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2329 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2330 READONLY_PROPERTY(versions,
2332 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2335 // Stupid code to slice out the version string.
2336 int c, l = strlen(OPENSSL_VERSION_TEXT);
2337 for (i = j = 0; i < l; i++) {
2338 c = OPENSSL_VERSION_TEXT[i];
2339 if ('0' <= c && c <= '9') {
2340 for (j = i + 1; j < l; j++) {
2341 c = OPENSSL_VERSION_TEXT[j];
2342 if (c == ' ') break;
2350 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2356 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2359 READONLY_PROPERTY(process,
2361 OneByteString(node_isolate, PLATFORM));
2364 Local<Array> arguments = Array::New(argc - option_end_index + 1);
2365 arguments->Set(0, String::NewFromUtf8(node_isolate, argv[0]));
2366 for (j = 1, i = option_end_index; i < argc; j++, i++) {
2367 arguments->Set(j, String::NewFromUtf8(node_isolate, argv[i]));
2369 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2372 Local<Array> exec_argv = Array::New(option_end_index - 1);
2373 for (j = 1, i = 0; j < option_end_index; j++, i++) {
2374 exec_argv->Set(i, String::NewFromUtf8(node_isolate, argv[j]));
2376 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_argv);
2378 // create process.env
2379 Local<ObjectTemplate> envTemplate = ObjectTemplate::New();
2380 envTemplate->SetNamedPropertyHandler(EnvGetter,
2386 Local<Object> env = envTemplate->NewInstance();
2387 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), env);
2389 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2390 READONLY_PROPERTY(process, "features", GetFeatures());
2391 process->SetAccessor(
2392 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2393 NeedImmediateCallbackGetter,
2394 NeedImmediateCallbackSetter);
2398 READONLY_PROPERTY(process,
2400 String::NewFromUtf8(node_isolate, eval_string));
2405 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2408 // -i, --interactive
2410 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2414 if (no_deprecation) {
2415 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2418 // --throw-deprecation
2419 if (throw_deprecation) {
2420 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2423 // --trace-deprecation
2424 if (trace_deprecation) {
2425 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2428 size_t exec_path_len = 2 * PATH_MAX;
2429 char* exec_path = new char[exec_path_len];
2430 Local<String> exec_path_value;
2431 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2432 exec_path_value = String::NewFromUtf8(node_isolate,
2434 String::kNormalString,
2437 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2439 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2443 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2447 // define various internal methods
2448 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2449 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2450 NODE_SET_METHOD(process, "reallyExit", Exit);
2451 NODE_SET_METHOD(process, "abort", Abort);
2452 NODE_SET_METHOD(process, "chdir", Chdir);
2453 NODE_SET_METHOD(process, "cwd", Cwd);
2455 NODE_SET_METHOD(process, "umask", Umask);
2457 #if defined(__POSIX__) && !defined(__ANDROID__)
2458 NODE_SET_METHOD(process, "getuid", GetUid);
2459 NODE_SET_METHOD(process, "setuid", SetUid);
2461 NODE_SET_METHOD(process, "setgid", SetGid);
2462 NODE_SET_METHOD(process, "getgid", GetGid);
2464 NODE_SET_METHOD(process, "getgroups", GetGroups);
2465 NODE_SET_METHOD(process, "setgroups", SetGroups);
2466 NODE_SET_METHOD(process, "initgroups", InitGroups);
2467 #endif // __POSIX__ && !defined(__ANDROID__)
2469 NODE_SET_METHOD(process, "_kill", Kill);
2471 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2472 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2473 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2475 NODE_SET_METHOD(process, "hrtime", Hrtime);
2477 NODE_SET_METHOD(process, "dlopen", DLOpen);
2479 NODE_SET_METHOD(process, "uptime", Uptime);
2480 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2482 NODE_SET_METHOD(process, "binding", Binding);
2484 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2486 // values use to cross communicate with processNextTick
2487 Local<Object> info_box = Object::New();
2488 info_box->SetIndexedPropertiesToExternalArrayData(&tick_infobox,
2489 kExternalUnsignedIntArray,
2491 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfoBox"), info_box);
2493 // pre-set _events object for faster emit checks
2494 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2496 return scope.Close(process);
2500 #undef READONLY_PROPERTY
2503 static void AtExit() {
2504 uv_tty_reset_mode();
2508 static void SignalExit(int signal) {
2509 uv_tty_reset_mode();
2510 _exit(128 + signal);
2514 void Load(Handle<Object> process_l) {
2515 HandleScope handle_scope(node_isolate);
2517 process_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "process");
2518 domain_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "domain");
2520 // Compile, execute the src/node.js file. (Which was included as static C
2521 // string in node_natives.h. 'natve_node' is the string containing that
2524 // The node.js file returns a function 'f'
2529 // Disable verbose mode to stop FatalException() handler from trying
2530 // to handle the exception. Errors this early in the start-up phase
2531 // are not safe to ignore.
2532 try_catch.SetVerbose(false);
2534 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2535 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2536 if (try_catch.HasCaught()) {
2537 ReportException(try_catch);
2540 assert(f_value->IsFunction());
2541 Local<Function> f = Local<Function>::Cast(f_value);
2543 // Now we call 'f' with the 'process' variable that we've built up with
2544 // all our bindings. Inside node.js we'll take care of assigning things to
2547 // We start the process this way in order to be more modular. Developers
2548 // who do not like how 'src/node.js' setups the module system but do like
2549 // Node's I/O bindings may want to replace 'f' with their own function.
2551 // Add a reference to the global object
2552 Local<Object> global = v8::Context::GetCurrent()->Global();
2554 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2558 #if defined HAVE_PERFCTR
2559 InitPerfCounters(global);
2562 // Enable handling of uncaught exceptions
2563 // (FatalException(), break on uncaught exception in debugger)
2565 // This is not strictly necessary since it's almost impossible
2566 // to attach the debugger fast enought to break on exception
2567 // thrown during process startup.
2568 try_catch.SetVerbose(true);
2570 Local<Value> arg = process_l;
2571 f->Call(global, 1, &arg);
2574 static void PrintHelp();
2576 static void ParseDebugOpt(const char* arg) {
2579 if (strstr(arg, "--debug-port=") == arg) {
2580 p = 1 + strchr(arg, '=');
2581 debug_port = atoi(p);
2583 use_debug_agent = true;
2584 if (!strcmp(arg, "--debug-brk")) {
2585 debug_wait_connect = true;
2587 } else if (!strcmp(arg, "--debug")) {
2589 } else if (strstr(arg, "--debug-brk=") == arg) {
2590 debug_wait_connect = true;
2591 p = 1 + strchr(arg, '=');
2592 debug_port = atoi(p);
2593 } else if (strstr(arg, "--debug=") == arg) {
2594 p = 1 + strchr(arg, '=');
2595 debug_port = atoi(p);
2598 if (p && debug_port > 1024 && debug_port < 65536)
2601 fprintf(stderr, "Bad debug option.\n");
2602 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2608 static void PrintHelp() {
2609 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2610 " node debug script.js [arguments] \n"
2613 " -v, --version print node's version\n"
2614 " -e, --eval script evaluate script\n"
2615 " -p, --print evaluate script and print result\n"
2616 " -i, --interactive always enter the REPL even if stdin\n"
2617 " does not appear to be a terminal\n"
2618 " --no-deprecation silence deprecation warnings\n"
2619 " --trace-deprecation show stack traces on deprecations\n"
2620 " --v8-options print v8 command line options\n"
2621 " --max-stack-size=val set max v8 stack size (bytes)\n"
2623 "Environment variables:\n"
2625 "NODE_PATH ';'-separated list of directories\n"
2627 "NODE_PATH ':'-separated list of directories\n"
2629 " prefixed to the module search path.\n"
2630 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2631 " global contexts.\n"
2632 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2634 "Documentation can be found at http://nodejs.org/\n");
2638 // Parse node command line arguments.
2639 static void ParseArgs(int argc, char **argv) {
2642 // TODO(bnoordhuis) use parse opts
2643 for (i = 1; i < argc; i++) {
2644 const char *arg = argv[i];
2645 if (strstr(arg, "--debug") == arg) {
2647 argv[i] = const_cast<char*>("");
2648 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2649 printf("%s\n", NODE_VERSION);
2651 } else if (strstr(arg, "--max-stack-size=") == arg) {
2653 p = 1 + strchr(arg, '=');
2654 max_stack_size = atoi(p);
2655 argv[i] = const_cast<char*>("");
2656 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2659 } else if (strcmp(arg, "--eval") == 0 ||
2660 strcmp(arg, "-e") == 0 ||
2661 strcmp(arg, "--print") == 0 ||
2662 strcmp(arg, "-pe") == 0 ||
2663 strcmp(arg, "-p") == 0) {
2664 bool is_eval = strchr(arg, 'e') != NULL;
2665 bool is_print = strchr(arg, 'p') != NULL;
2667 // argument to -p and --print is optional
2668 if (is_eval == true && i + 1 >= argc) {
2669 fprintf(stderr, "Error: %s requires an argument\n", arg);
2673 print_eval = print_eval || is_print;
2674 argv[i] = const_cast<char*>("");
2676 // --eval, -e and -pe always require an argument
2677 if (is_eval == true) {
2678 eval_string = argv[++i];
2682 // next arg is the expression to evaluate unless it starts with:
2683 // - a dash, then it's another switch
2684 // - "\\-", then it's an escaped expression, drop the backslash
2685 if (argv[i + 1] == NULL) continue;
2686 if (argv[i + 1][0] == '-') continue;
2687 eval_string = argv[++i];
2688 if (strncmp(eval_string, "\\-", 2) == 0) ++eval_string;
2689 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2691 argv[i] = const_cast<char*>("");
2692 } else if (strcmp(arg, "--v8-options") == 0) {
2693 argv[i] = const_cast<char*>("--help");
2694 } else if (strcmp(arg, "--no-deprecation") == 0) {
2695 argv[i] = const_cast<char*>("");
2696 no_deprecation = true;
2697 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2698 argv[i] = const_cast<char*>("");
2699 trace_deprecation = true;
2700 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2701 argv[i] = const_cast<char*>("");
2702 throw_deprecation = true;
2703 } else if (argv[i][0] != '-') {
2708 option_end_index = i;
2712 // Called from the main thread.
2713 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2714 v8::Debug::ProcessDebugMessages();
2718 // Called from V8 Debug Agent TCP thread.
2719 static void DispatchMessagesDebugAgentCallback() {
2720 uv_async_send(&dispatch_debug_messages_async);
2724 // Called from the main thread
2725 static void EmitDebugEnabledAsyncCallback(uv_async_t* handle, int status) {
2726 HandleScope handle_scope(node_isolate);
2727 Local<Object> obj = Object::New();
2728 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "cmd"),
2729 FIXED_ONE_BYTE_STRING(node_isolate, "NODE_DEBUG_ENABLED"));
2730 Local<Value> args[] = {
2731 FIXED_ONE_BYTE_STRING(node_isolate, "internalMessage"),
2734 MakeCallback(process_p, "emit", ARRAY_SIZE(args), args);
2738 // Called from the signal watcher callback
2739 static void EmitDebugEnabled() {
2740 uv_async_send(&emit_debug_enabled_async);
2744 static void EnableDebug(bool wait_connect) {
2745 // If we're called from another thread, make sure to enter the right
2747 node_isolate->Enter();
2749 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2752 // Start the debug thread and it's associated TCP server on port 5858.
2753 bool r = v8::Debug::EnableAgent("node " NODE_VERSION,
2757 // Crappy check that everything went well. FIXME
2760 // Print out some information.
2761 fprintf(stderr, "debugger listening on port %d\n", debug_port);
2764 debugger_running = true;
2766 // Do not emit NODE_DEBUG_ENABLED when debugger is enabled before starting
2767 // the main process (i.e. when called via `node --debug`)
2768 if (!process_p.IsEmpty())
2771 node_isolate->Exit();
2776 static void EnableDebugSignalHandler(uv_signal_t* handle, int) {
2777 // Break once process will return execution to v8
2778 v8::Debug::DebugBreak(node_isolate);
2780 if (!debugger_running) {
2781 fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n");
2787 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2788 struct sigaction sa;
2790 memset(&sa, 0, sizeof(sa));
2791 sa.sa_handler = handler;
2792 sigfillset(&sa.sa_mask);
2793 sigaction(signal, &sa, NULL);
2797 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2798 HandleScope scope(node_isolate);
2800 if (args.Length() != 1) {
2801 return ThrowError("Invalid number of arguments.");
2807 pid = args[0]->IntegerValue();
2808 r = kill(pid, SIGUSR1);
2810 return ThrowErrnoException(errno, "kill");
2817 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2818 // Break once process will return execution to v8
2819 if (!debugger_running) {
2820 for (int i = 0; i < 1; i++) {
2821 fprintf(stderr, "Starting debugger agent.\r\n");
2827 v8::Debug::DebugBreak(node_isolate);
2833 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2835 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2839 static int RegisterDebugSignalHandler() {
2840 wchar_t mapping_name[32];
2841 HANDLE mapping_handle;
2843 LPTHREAD_START_ROUTINE* handler;
2845 pid = GetCurrentProcessId();
2847 if (GetDebugSignalHandlerMappingName(pid,
2849 ARRAY_SIZE(mapping_name)) < 0) {
2853 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2859 if (mapping_handle == NULL) {
2863 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2864 MapViewOfFile(mapping_handle,
2865 FILE_MAP_ALL_ACCESS,
2869 if (handler == NULL) {
2870 CloseHandle(mapping_handle);
2874 *handler = EnableDebugThreadProc;
2876 UnmapViewOfFile(static_cast<void*>(handler));
2882 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2883 HandleScope scope(node_isolate);
2885 HANDLE process = NULL;
2886 HANDLE thread = NULL;
2887 HANDLE mapping = NULL;
2888 wchar_t mapping_name[32];
2889 LPTHREAD_START_ROUTINE* handler = NULL;
2891 if (args.Length() != 1) {
2892 ThrowError("Invalid number of arguments.");
2896 pid = (DWORD) args[0]->IntegerValue();
2898 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2899 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2903 if (process == NULL) {
2904 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2908 if (GetDebugSignalHandlerMappingName(pid,
2910 ARRAY_SIZE(mapping_name)) < 0) {
2911 ThrowErrnoException(errno, "sprintf");
2915 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2916 if (mapping == NULL) {
2917 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
2921 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2922 MapViewOfFile(mapping,
2927 if (handler == NULL || *handler == NULL) {
2928 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
2932 thread = CreateRemoteThread(process,
2939 if (thread == NULL) {
2940 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
2944 // Wait for the thread to terminate
2945 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
2946 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
2951 if (process != NULL)
2952 CloseHandle(process);
2954 CloseHandle(thread);
2955 if (handler != NULL)
2956 UnmapViewOfFile(handler);
2957 if (mapping != NULL)
2958 CloseHandle(mapping);
2963 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
2964 v8::Debug::DebugBreak(node_isolate);
2968 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
2969 if (debugger_running) {
2970 v8::Debug::DisableAgent();
2971 debugger_running = false;
2976 char** Init(int argc, char *argv[]) {
2977 // Initialize prog_start_time to get relative uptime.
2978 uv_uptime(&prog_start_time);
2980 // Make inherited handles noninheritable.
2981 uv_disable_stdio_inheritance();
2983 // init async debug messages dispatching
2984 uv_async_init(uv_default_loop(),
2985 &dispatch_debug_messages_async,
2986 DispatchDebugMessagesAsyncCallback);
2987 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
2989 // init async NODE_DEBUG_ENABLED emitter
2990 uv_async_init(uv_default_loop(),
2991 &emit_debug_enabled_async,
2992 EmitDebugEnabledAsyncCallback);
2993 uv_unref(reinterpret_cast<uv_handle_t*>(&emit_debug_enabled_async));
2995 // Parse a few arguments which are specific to Node.
2996 node::ParseArgs(argc, argv);
2997 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
2998 // in the command line))
2999 int v8argc = option_end_index;
3000 char **v8argv = argv;
3002 if (debug_wait_connect) {
3003 // v8argv is a copy of argv up to the script file argument +2 if --debug-brk
3004 // to expose the v8 debugger js object so that node.js can set
3005 // a breakpoint on the first line of the startup script
3007 v8argv = new char*[v8argc];
3008 memcpy(v8argv, argv, sizeof(*argv) * option_end_index);
3009 v8argv[option_end_index] = const_cast<char*>("--expose_debug_as");
3010 v8argv[option_end_index + 1] = const_cast<char*>("v8debug");
3013 // For the normal stack which moves from high to low addresses when frames
3014 // are pushed, we can compute the limit as stack_size bytes below the
3015 // the address of a stack variable (e.g. &stack_var) as an approximation
3016 // of the start of the stack (we're assuming that we haven't pushed a lot
3018 if (max_stack_size != 0) {
3020 ResourceConstraints constraints;
3022 uint32_t *stack_limit = &stack_var - (max_stack_size / sizeof(uint32_t));
3023 constraints.set_stack_limit(stack_limit);
3024 SetResourceConstraints(&constraints); // Must be done before V8::Initialize
3026 V8::SetFlagsFromCommandLine(&v8argc, v8argv, false);
3028 const char typed_arrays_flag[] = "--harmony_typed_arrays";
3029 V8::SetFlagsFromString(typed_arrays_flag, sizeof(typed_arrays_flag) - 1);
3030 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3032 // Fetch a reference to the main isolate, so we have a reference to it
3033 // even when we need it to access it from another (debugger) thread.
3034 node_isolate = Isolate::GetCurrent();
3038 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3039 RegisterSignalHandler(SIGINT, SignalExit);
3040 RegisterSignalHandler(SIGTERM, SignalExit);
3043 uv_check_init(uv_default_loop(), &check_immediate_watcher);
3044 uv_unref(reinterpret_cast<uv_handle_t*>(&check_immediate_watcher));
3045 uv_idle_init(uv_default_loop(), &idle_immediate_dummy);
3047 V8::SetFatalErrorHandler(node::OnFatalError);
3048 V8::AddMessageListener(OnMessage);
3050 // If the --debug flag was specified then initialize the debug thread.
3051 if (use_debug_agent) {
3052 EnableDebug(debug_wait_connect);
3055 RegisterDebugSignalHandler();
3057 static uv_signal_t signal_watcher;
3058 uv_signal_init(uv_default_loop(), &signal_watcher);
3059 uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1);
3060 uv_unref(reinterpret_cast<uv_handle_t*>(&signal_watcher));
3068 struct AtExitCallback {
3069 AtExitCallback* next_;
3070 void (*cb_)(void* arg);
3074 static AtExitCallback* at_exit_functions_;
3078 AtExitCallback* p = at_exit_functions_;
3079 at_exit_functions_ = NULL;
3082 AtExitCallback* q = p->next_;
3090 void AtExit(void (*cb)(void* arg), void* arg) {
3091 AtExitCallback* p = new AtExitCallback;
3094 p->next_ = at_exit_functions_;
3095 at_exit_functions_ = p;
3099 void EmitExit(v8::Handle<v8::Object> process_l) {
3100 // process.emit('exit')
3101 process_l->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3102 True(node_isolate));
3103 Local<Value> args[] = {
3104 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3105 Integer::New(0, node_isolate)
3107 MakeCallback(process_l, "emit", ARRAY_SIZE(args), args);
3110 static char **copy_argv(int argc, char **argv) {
3118 for (i = 0; i < argc; i++) {
3119 strlen_sum += strlen(argv[i]) + 1;
3122 argv_copy = static_cast<char**>(
3123 malloc(sizeof(*argv_copy) * (argc + 1) + strlen_sum));
3128 argv_data = reinterpret_cast<char*>(argv_copy) +
3129 sizeof(*argv_copy) * (argc + 1);
3131 for (i = 0; i < argc; i++) {
3132 argv_copy[i] = argv_data;
3133 len = strlen(argv[i]) + 1;
3134 memcpy(argv_data, argv[i], len);
3138 argv_copy[argc] = NULL;
3143 int Start(int argc, char *argv[]) {
3144 // Hack aroung with the argv pointer. Used for process.title = "blah".
3145 argv = uv_setup_args(argc, argv);
3147 // Logic to duplicate argv as Init() modifies arguments
3148 // that are passed into it.
3149 char **argv_copy = copy_argv(argc, argv);
3151 // This needs to run *before* V8::Initialize()
3152 // Use copy here as to not modify the original argv:
3153 Init(argc, argv_copy);
3157 Locker locker(node_isolate);
3158 HandleScope handle_scope(node_isolate);
3160 // Create the one and only Context.
3161 Local<Context> context = Context::New(node_isolate);
3162 Context::Scope context_scope(context);
3164 binding_cache.Reset(node_isolate, Object::New());
3166 // Use original argv, as we're just copying values out of it.
3167 Local<Object> process_l = SetupProcessObject(argc, argv);
3169 // Create all the objects, load modules, do everything.
3170 // so your next reading stop should be node::Load()!
3173 // All our arguments are loaded. We've evaluated all of the scripts. We
3174 // might even have created TCP servers. Now we enter the main eventloop. If
3175 // there are no watchers on the loop (except for the ones that were
3176 // uv_unref'd) then this function exits. As long as there are active
3177 // watchers, it blocks.
3178 uv_run(uv_default_loop(), UV_RUN_DEFAULT);
3180 EmitExit(process_l);
3185 // Clean up. Not strictly necessary.
3189 // Clean up the copy: