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 bool using_domains = false;
169 // used by C++ modules as well
170 bool no_deprecation = false;
172 static uv_check_t check_immediate_watcher;
173 static uv_idle_t idle_immediate_dummy;
174 static bool need_immediate_cb;
175 static Cached<String> immediate_callback_sym;
177 // for quick ref to tickCallback values
185 // easily communicate domain depth
190 // process-relative uptime base, initialized at start-up
191 static double prog_start_time;
193 static volatile bool debugger_running = false;
194 static uv_async_t dispatch_debug_messages_async;
195 static uv_async_t emit_debug_enabled_async;
197 // Declared in node_internals.h
198 Isolate* node_isolate = NULL;
206 static ProcessState process_state = INITIALIZING;
209 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
211 // Impose an upper limit to avoid out of memory errors that bring down
213 static const size_t kMaxLength = 0x3fffffff;
214 static ArrayBufferAllocator the_singleton;
215 virtual ~ArrayBufferAllocator() {}
216 virtual void* Allocate(size_t length);
217 virtual void Free(void* data);
219 ArrayBufferAllocator() {}
220 ArrayBufferAllocator(const ArrayBufferAllocator&);
221 void operator=(const ArrayBufferAllocator&);
224 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
227 void* ArrayBufferAllocator::Allocate(size_t length) {
228 if (length > kMaxLength) return NULL;
229 return new char[length];
233 void ArrayBufferAllocator::Free(void* data) {
234 delete[] static_cast<char*>(data);
238 static void CheckImmediate(uv_check_t* handle, int status) {
239 assert(handle == &check_immediate_watcher);
242 HandleScope scope(node_isolate);
244 if (immediate_callback_sym.IsEmpty()) {
245 immediate_callback_sym =
246 FIXED_ONE_BYTE_STRING(node_isolate, "_immediateCallback");
249 MakeCallback(process_p, immediate_callback_sym, 0, NULL);
253 static void IdleImmediateDummy(uv_idle_t* handle, int status) {
254 // Do nothing. Only for maintaining event loop
255 assert(handle == &idle_immediate_dummy);
260 static inline const char *errno_string(int errorno) {
261 #define ERRNO_CASE(e) case e: return #e;
268 ERRNO_CASE(EADDRINUSE);
272 ERRNO_CASE(EADDRNOTAVAIL);
276 ERRNO_CASE(EAFNOSUPPORT);
284 # if EAGAIN != EWOULDBLOCK
285 ERRNO_CASE(EWOULDBLOCK);
290 ERRNO_CASE(EALREADY);
306 ERRNO_CASE(ECANCELED);
314 ERRNO_CASE(ECONNABORTED);
318 ERRNO_CASE(ECONNREFUSED);
322 ERRNO_CASE(ECONNRESET);
330 ERRNO_CASE(EDESTADDRREQ);
354 ERRNO_CASE(EHOSTUNREACH);
366 ERRNO_CASE(EINPROGRESS);
402 ERRNO_CASE(EMSGSIZE);
406 ERRNO_CASE(EMULTIHOP);
410 ERRNO_CASE(ENAMETOOLONG);
414 ERRNO_CASE(ENETDOWN);
418 ERRNO_CASE(ENETRESET);
422 ERRNO_CASE(ENETUNREACH);
454 # if ENOLINK != ENOLCK
468 ERRNO_CASE(ENOPROTOOPT);
488 ERRNO_CASE(ENOTCONN);
496 ERRNO_CASE(ENOTEMPTY);
500 ERRNO_CASE(ENOTSOCK);
507 ERRNO_CASE(EOPNOTSUPP);
521 ERRNO_CASE(EOVERFLOW);
536 #ifdef EPROTONOSUPPORT
537 ERRNO_CASE(EPROTONOSUPPORT);
541 ERRNO_CASE(EPROTOTYPE);
569 ERRNO_CASE(ETIMEDOUT);
584 const char *signo_string(int signo) {
585 #define SIGNO_CASE(e) case e: return #e;
612 # if SIGABRT != SIGIOT
656 SIGNO_CASE(SIGSTKFLT);
673 SIGNO_CASE(SIGBREAK);
697 SIGNO_CASE(SIGVTALRM);
705 SIGNO_CASE(SIGWINCH);
713 # if SIGPOLL != SIGIO
723 # if SIGPWR != SIGLOST
737 Local<Value> ErrnoException(int errorno,
742 Local<String> estring = OneByteString(node_isolate, errno_string(errorno));
743 if (msg == NULL || msg[0] == '\0') {
744 msg = strerror(errorno);
746 Local<String> message = OneByteString(node_isolate, msg);
748 Local<String> cons1 =
749 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
750 Local<String> cons2 = String::Concat(cons1, message);
752 if (syscall_symbol.IsEmpty()) {
753 syscall_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "syscall");
754 errno_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "errno");
755 errpath_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "path");
756 code_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "code");
760 Local<String> cons3 =
761 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
762 Local<String> cons4 =
763 String::Concat(cons3, String::NewFromUtf8(node_isolate, path));
764 Local<String> cons5 =
765 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
766 e = Exception::Error(cons5);
768 e = Exception::Error(cons2);
771 Local<Object> obj = e->ToObject();
773 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
774 obj->Set(code_symbol, estring);
775 if (path) obj->Set(errpath_symbol, String::NewFromUtf8(node_isolate, path));
776 if (syscall) obj->Set(syscall_symbol, OneByteString(node_isolate, syscall));
781 // hack alert! copy of ErrnoException, tuned for uv errors
782 Local<Value> UVException(int errorno,
786 if (syscall_symbol.IsEmpty()) {
787 syscall_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "syscall");
788 errno_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "errno");
789 errpath_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "path");
790 code_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "code");
794 msg = uv_strerror(errorno);
796 Local<String> estring = OneByteString(node_isolate, uv_err_name(errorno));
797 Local<String> message = OneByteString(node_isolate, msg);
798 Local<String> cons1 =
799 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
800 Local<String> cons2 = String::Concat(cons1, message);
804 Local<String> path_str;
808 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
809 path_str = String::Concat(FIXED_ONE_BYTE_STRING(node_isolate, "\\\\"),
810 String::NewFromUtf8(node_isolate, path + 8));
811 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
812 path_str = String::NewFromUtf8(node_isolate, path + 4);
814 path_str = String::NewFromUtf8(node_isolate, path);
817 path_str = String::NewFromUtf8(node_isolate, path);
820 Local<String> cons3 =
821 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
822 Local<String> cons4 =
823 String::Concat(cons3, path_str);
824 Local<String> cons5 =
825 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
826 e = Exception::Error(cons5);
828 e = Exception::Error(cons2);
831 Local<Object> obj = e->ToObject();
833 // TODO(piscisaureus) errno should probably go
834 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
835 obj->Set(code_symbol, estring);
836 if (path) obj->Set(errpath_symbol, path_str);
837 if (syscall) obj->Set(syscall_symbol, OneByteString(node_isolate, syscall));
843 // Does about the same as strerror(),
844 // but supports all windows error messages
845 static const char *winapi_strerror(const int errorno) {
848 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
849 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
850 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
853 // Remove trailing newlines
854 for (int i = strlen(errmsg) - 1;
855 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
861 // FormatMessage failed
862 return "Unknown error";
867 Local<Value> WinapiErrnoException(int errorno,
872 if (!msg || !msg[0]) {
873 msg = winapi_strerror(errorno);
875 Local<String> message = OneByteString(node_isolate, msg);
877 if (syscall_symbol.IsEmpty()) {
878 syscall_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "syscall");
879 errno_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "errno");
880 errpath_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "path");
881 code_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "code");
885 Local<String> cons1 =
886 String::Concat(message, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
887 Local<String> cons2 =
888 String::Concat(cons1, String::NewFromUtf8(node_isolate, path));
889 Local<String> cons3 =
890 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
891 e = Exception::Error(cons3);
893 e = Exception::Error(message);
896 Local<Object> obj = e->ToObject();
898 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
899 if (path) obj->Set(errpath_symbol, String::NewFromUtf8(node_isolate, path));
900 if (syscall) obj->Set(syscall_symbol, OneByteString(node_isolate, syscall));
906 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
907 if (using_domains) return;
908 HandleScope scope(node_isolate);
909 using_domains = true;
910 Local<Object> process = PersistentToLocal(node_isolate, process_p);
912 process->Get(FIXED_ONE_BYTE_STRING(node_isolate, "_tickDomainCallback"));
913 if (!tdc_v->IsFunction()) {
914 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
917 Local<Function> tdc = tdc_v.As<Function>();
918 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"), tdc);
919 process_tickCallback.Reset(node_isolate, tdc);
920 if (!args[0]->IsArray()) {
921 fprintf(stderr, "_setupDomainUse first argument must be an array\n");
924 p_domain_box.Reset(node_isolate, args[0].As<Array>());
925 if (!args[1]->IsObject()) {
926 fprintf(stderr, "_setupDomainUse second argument must be an object\n");
929 Local<Object> flag = args[1].As<Object>();
930 flag->SetIndexedPropertiesToExternalArrayData(&domain_flag,
931 kExternalUnsignedIntArray,
937 return using_domains && domain_flag.count > 0;
941 Handle<Value> GetDomain() {
942 // no domain can exist if no domain module has been loaded
943 if (!InDomain() || p_domain_box.IsEmpty())
944 return Null(node_isolate);
946 return PersistentToLocal(node_isolate, p_domain_box)->Get(0);
951 MakeDomainCallback(const Handle<Object> object,
952 const Handle<Function> callback,
954 Handle<Value> argv[]) {
955 // TODO(trevnorris) Hook for long stack traces to be made here.
957 // lazy load domain specific symbols
958 if (enter_symbol.IsEmpty()) {
959 enter_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "enter");
960 exit_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "exit");
961 disposed_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "_disposed");
964 Local<Value> domain_v = object->Get(domain_symbol);
965 Local<Object> domain;
966 Local<Function> enter;
967 Local<Function> exit;
970 try_catch.SetVerbose(true);
972 bool has_domain = domain_v->IsObject();
974 domain = domain_v->ToObject();
975 assert(!domain.IsEmpty());
976 if (domain->Get(disposed_symbol)->IsTrue()) {
977 // domain has been disposed of.
978 return Undefined(node_isolate);
980 enter = Local<Function>::Cast(domain->Get(enter_symbol));
981 assert(!enter.IsEmpty());
982 enter->Call(domain, 0, NULL);
984 if (try_catch.HasCaught()) {
985 return Undefined(node_isolate);
989 Local<Value> ret = callback->Call(object, argc, argv);
991 if (try_catch.HasCaught()) {
992 return Undefined(node_isolate);
996 exit = Local<Function>::Cast(domain->Get(exit_symbol));
997 assert(!exit.IsEmpty());
998 exit->Call(domain, 0, NULL);
1000 if (try_catch.HasCaught()) {
1001 return Undefined(node_isolate);
1005 if (tick_infobox.last_threw == 1) {
1006 tick_infobox.last_threw = 0;
1010 if (tick_infobox.in_tick == 1) {
1014 if (tick_infobox.length == 0) {
1015 tick_infobox.index = 0;
1019 // process nextTicks after call
1020 Local<Object> process = PersistentToLocal(node_isolate, process_p);
1021 Local<Function> fn = PersistentToLocal(node_isolate, process_tickCallback);
1022 fn->Call(process, 0, NULL);
1024 if (try_catch.HasCaught()) {
1025 return Undefined(node_isolate);
1033 MakeCallback(const Handle<Object> object,
1034 const Handle<Function> callback,
1036 Handle<Value> argv[]) {
1037 if (process_state == SHUTTING_DOWN)
1038 return Undefined(node_isolate);
1040 // TODO(trevnorris) Hook for long stack traces to be made here.
1041 Local<Object> process = PersistentToLocal(node_isolate, process_p);
1044 return MakeDomainCallback(object, callback, argc, argv);
1046 // lazy load no domain next tick callbacks
1047 if (process_tickCallback.IsEmpty()) {
1049 process->Get(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"));
1050 if (!cb_v->IsFunction()) {
1051 fprintf(stderr, "process._tickCallback assigned to non-function\n");
1054 process_tickCallback.Reset(node_isolate, cb_v.As<Function>());
1058 try_catch.SetVerbose(true);
1060 Local<Value> ret = callback->Call(object, argc, argv);
1062 if (try_catch.HasCaught()) {
1063 return Undefined(node_isolate);
1066 if (tick_infobox.in_tick == 1) {
1070 if (tick_infobox.length == 0) {
1071 tick_infobox.index = 0;
1075 // process nextTicks after call
1076 Local<Function> fn = PersistentToLocal(node_isolate, process_tickCallback);
1077 fn->Call(process, 0, NULL);
1079 if (try_catch.HasCaught()) {
1080 return Undefined(node_isolate);
1089 MakeCallback(const Handle<Object> object,
1092 Handle<Value> argv[]) {
1093 HandleScope scope(node_isolate);
1095 Local<Function> callback = object->Get(index).As<Function>();
1096 assert(callback->IsFunction());
1099 return scope.Close(MakeDomainCallback(object, callback, argc, argv));
1100 return scope.Close(MakeCallback(object, callback, argc, argv));
1105 MakeCallback(const Handle<Object> object,
1106 const Handle<String> symbol,
1108 Handle<Value> argv[]) {
1109 HandleScope scope(node_isolate);
1111 Local<Function> callback = object->Get(symbol).As<Function>();
1112 assert(callback->IsFunction());
1115 return scope.Close(MakeDomainCallback(object, callback, argc, argv));
1116 return scope.Close(MakeCallback(object, callback, argc, argv));
1121 MakeCallback(const Handle<Object> object,
1124 Handle<Value> argv[]) {
1125 HandleScope scope(node_isolate);
1127 Local<String> method_string = OneByteString(node_isolate, method);
1128 Handle<Value> ret = MakeCallback(object, method_string, argc, argv);
1130 return scope.Close(ret);
1134 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1135 HandleScope scope(node_isolate);
1137 if (!encoding_v->IsString()) return _default;
1139 String::Utf8Value encoding(encoding_v);
1141 if (strcasecmp(*encoding, "utf8") == 0) {
1143 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1145 } else if (strcasecmp(*encoding, "ascii") == 0) {
1147 } else if (strcasecmp(*encoding, "base64") == 0) {
1149 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1151 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1153 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1155 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1157 } else if (strcasecmp(*encoding, "binary") == 0) {
1159 } else if (strcasecmp(*encoding, "buffer") == 0) {
1161 } else if (strcasecmp(*encoding, "hex") == 0) {
1163 } else if (strcasecmp(*encoding, "raw") == 0) {
1164 if (!no_deprecation) {
1165 fprintf(stderr, "'raw' (array of integers) has been removed. "
1169 } else if (strcasecmp(*encoding, "raws") == 0) {
1170 if (!no_deprecation) {
1171 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1172 "Please update your code.\n");
1180 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1181 return StringBytes::Encode(static_cast<const char*>(buf),
1186 // Returns -1 if the handle was not valid for decoding
1187 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1188 HandleScope scope(node_isolate);
1190 if (val->IsArray()) {
1191 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1197 return StringBytes::Size(val, encoding);
1201 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1204 // Returns number of bytes written.
1205 ssize_t DecodeWrite(char *buf,
1207 v8::Handle<v8::Value> val,
1208 enum encoding encoding) {
1209 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1212 void DisplayExceptionLine(Handle<Message> message) {
1213 // Prevent re-entry into this function. For example, if there is
1214 // a throw from a program in vm.runInThisContext(code, filename, true),
1215 // then we want to show the original failure, not the secondary one.
1216 static bool displayed_error = false;
1218 if (displayed_error) return;
1219 displayed_error = true;
1221 uv_tty_reset_mode();
1223 fprintf(stderr, "\n");
1225 if (!message.IsEmpty()) {
1226 // Print (filename):(line number): (message).
1227 String::Utf8Value filename(message->GetScriptResourceName());
1228 const char* filename_string = *filename;
1229 int linenum = message->GetLineNumber();
1230 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1231 // Print line of source code.
1232 String::Utf8Value sourceline(message->GetSourceLine());
1233 const char* sourceline_string = *sourceline;
1235 // Because of how node modules work, all scripts are wrapped with a
1236 // "function (module, exports, __filename, ...) {"
1237 // to provide script local variables.
1239 // When reporting errors on the first line of a script, this wrapper
1240 // function is leaked to the user. There used to be a hack here to
1241 // truncate off the first 62 characters, but it caused numerous other
1242 // problems when vm.runIn*Context() methods were used for non-module
1245 // If we ever decide to re-instate such a hack, the following steps
1248 // 1. Pass a flag around to say "this code was wrapped"
1249 // 2. Update the stack frame output so that it is also correct.
1251 // It would probably be simpler to add a line rather than add some
1252 // number of characters to the first line, since V8 truncates the
1253 // sourceline to 78 characters, and we end up not providing very much
1254 // useful debugging info to the user if we remove 62 characters.
1256 int start = message->GetStartColumn();
1257 int end = message->GetEndColumn();
1259 fprintf(stderr, "%s\n", sourceline_string);
1260 // Print wavy underline (GetUnderline is deprecated).
1261 for (int i = 0; i < start; i++) {
1262 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1264 for (int i = start; i < end; i++) {
1267 fputc('\n', stderr);
1272 static void ReportException(Handle<Value> er, Handle<Message> message) {
1273 HandleScope scope(node_isolate);
1275 DisplayExceptionLine(message);
1277 Local<Value> trace_value(
1278 er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack")));
1279 String::Utf8Value trace(trace_value);
1281 // range errors have a trace member set to undefined
1282 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1283 fprintf(stderr, "%s\n", *trace);
1285 // this really only happens for RangeErrors, since they're the only
1286 // kind that won't have all this info in the trace, or when non-Error
1287 // objects are thrown manually.
1288 Local<Value> message;
1291 if (er->IsObject()) {
1292 Local<Object> err_obj = er.As<Object>();
1293 message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1294 name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1297 if (message.IsEmpty() ||
1298 message->IsUndefined() ||
1300 name->IsUndefined()) {
1301 // Not an error object. Just print as-is.
1302 String::Utf8Value message(er);
1303 fprintf(stderr, "%s\n", *message);
1305 String::Utf8Value name_string(name);
1306 String::Utf8Value message_string(message);
1307 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1315 static void ReportException(const TryCatch& try_catch) {
1316 ReportException(try_catch.Exception(), try_catch.Message());
1320 // Executes a str within the current v8 context.
1321 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1322 HandleScope scope(node_isolate);
1325 // try_catch must be nonverbose to disable FatalException() handler,
1326 // we will handle exceptions ourself.
1327 try_catch.SetVerbose(false);
1329 Local<v8::Script> script = v8::Script::Compile(source, filename);
1330 if (script.IsEmpty()) {
1331 ReportException(try_catch);
1335 Local<Value> result = script->Run();
1336 if (result.IsEmpty()) {
1337 ReportException(try_catch);
1341 return scope.Close(result);
1345 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1346 HandleScope scope(node_isolate);
1348 Local<Array> ary = Array::New();
1352 QUEUE_FOREACH(q, &req_wrap_queue) {
1353 ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1354 if (w->persistent().IsEmpty()) continue;
1355 ary->Set(i++, w->object());
1358 args.GetReturnValue().Set(ary);
1362 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1363 // implemented here for consistency with GetActiveRequests().
1364 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1365 HandleScope scope(node_isolate);
1367 Local<Array> ary = Array::New();
1371 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1373 QUEUE_FOREACH(q, &handle_wrap_queue) {
1374 HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1375 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue;
1376 Local<Object> object = w->object();
1377 Local<Value> owner = object->Get(owner_sym);
1378 if (owner->IsUndefined()) owner = object;
1379 ary->Set(i++, owner);
1382 args.GetReturnValue().Set(ary);
1386 static void Abort(const FunctionCallbackInfo<Value>& args) {
1391 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1392 HandleScope scope(node_isolate);
1394 if (args.Length() != 1 || !args[0]->IsString()) {
1395 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1398 String::Utf8Value path(args[0]);
1399 int err = uv_chdir(*path);
1401 return ThrowUVException(err, "uv_chdir");
1406 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1407 HandleScope scope(node_isolate);
1409 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1410 char buf[MAX_PATH * 4 + 1];
1412 char buf[PATH_MAX + 1];
1415 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1417 return ThrowUVException(err, "uv_cwd");
1420 buf[ARRAY_SIZE(buf) - 1] = '\0';
1421 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1423 args.GetReturnValue().Set(cwd);
1427 static void Umask(const FunctionCallbackInfo<Value>& args) {
1428 HandleScope scope(node_isolate);
1431 if (args.Length() < 1 || args[0]->IsUndefined()) {
1433 umask(static_cast<mode_t>(old));
1434 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1435 return ThrowTypeError("argument must be an integer or octal string.");
1438 if (args[0]->IsInt32()) {
1439 oct = args[0]->Uint32Value();
1442 String::Utf8Value str(args[0]);
1444 // Parse the octal string.
1445 for (int i = 0; i < str.length(); i++) {
1447 if (c > '7' || c < '0') {
1448 return ThrowTypeError("invalid octal string");
1454 old = umask(static_cast<mode_t>(oct));
1457 args.GetReturnValue().Set(old);
1461 #if defined(__POSIX__) && !defined(__ANDROID__)
1463 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1464 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1467 static uid_t uid_by_name(const char* name) {
1475 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1479 return uid_not_found;
1483 static char* name_by_uid(uid_t uid) {
1492 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1493 return strdup(pp->pw_name);
1504 static gid_t gid_by_name(const char* name) {
1512 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1516 return gid_not_found;
1520 #if 0 // For future use.
1521 static const char* name_by_gid(gid_t gid) {
1530 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1531 return strdup(pp->gr_name);
1543 static uid_t uid_by_name(Handle<Value> value) {
1544 if (value->IsUint32()) {
1545 return static_cast<uid_t>(value->Uint32Value());
1547 String::Utf8Value name(value);
1548 return uid_by_name(*name);
1553 static gid_t gid_by_name(Handle<Value> value) {
1554 if (value->IsUint32()) {
1555 return static_cast<gid_t>(value->Uint32Value());
1557 String::Utf8Value name(value);
1558 return gid_by_name(*name);
1563 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1564 args.GetReturnValue().Set(getuid());
1568 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1569 args.GetReturnValue().Set(getgid());
1573 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1574 HandleScope scope(node_isolate);
1576 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1577 return ThrowTypeError("setgid argument must be a number or a string");
1580 gid_t gid = gid_by_name(args[0]);
1582 if (gid == gid_not_found) {
1583 return ThrowError("setgid group id does not exist");
1587 return ThrowErrnoException(errno, "setgid");
1592 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1593 HandleScope scope(node_isolate);
1595 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1596 return ThrowTypeError("setuid argument must be a number or a string");
1599 uid_t uid = uid_by_name(args[0]);
1601 if (uid == uid_not_found) {
1602 return ThrowError("setuid user id does not exist");
1606 return ThrowErrnoException(errno, "setuid");
1611 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1612 HandleScope scope(node_isolate);
1614 int ngroups = getgroups(0, NULL);
1616 if (ngroups == -1) {
1617 return ThrowErrnoException(errno, "getgroups");
1620 gid_t* groups = new gid_t[ngroups];
1622 ngroups = getgroups(ngroups, groups);
1624 if (ngroups == -1) {
1626 return ThrowErrnoException(errno, "getgroups");
1629 Local<Array> groups_list = Array::New(ngroups);
1630 bool seen_egid = false;
1631 gid_t egid = getegid();
1633 for (int i = 0; i < ngroups; i++) {
1634 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1635 if (groups[i] == egid) seen_egid = true;
1640 if (seen_egid == false) {
1641 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1644 args.GetReturnValue().Set(groups_list);
1648 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1649 HandleScope scope(node_isolate);
1651 if (!args[0]->IsArray()) {
1652 return ThrowTypeError("argument 1 must be an array");
1655 Local<Array> groups_list = args[0].As<Array>();
1656 size_t size = groups_list->Length();
1657 gid_t* groups = new gid_t[size];
1659 for (size_t i = 0; i < size; i++) {
1660 gid_t gid = gid_by_name(groups_list->Get(i));
1662 if (gid == gid_not_found) {
1664 return ThrowError("group name not found");
1670 int rc = setgroups(size, groups);
1674 return ThrowErrnoException(errno, "setgroups");
1679 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1680 HandleScope scope(node_isolate);
1682 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1683 return ThrowTypeError("argument 1 must be a number or a string");
1686 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1687 return ThrowTypeError("argument 2 must be a number or a string");
1690 String::Utf8Value arg0(args[0]);
1695 if (args[0]->IsUint32()) {
1696 user = name_by_uid(args[0]->Uint32Value());
1704 return ThrowError("initgroups user not found");
1707 extra_group = gid_by_name(args[1]);
1709 if (extra_group == gid_not_found) {
1710 if (must_free) free(user);
1711 return ThrowError("initgroups extra group not found");
1714 int rc = initgroups(user, extra_group);
1721 return ThrowErrnoException(errno, "initgroups");
1725 #endif // __POSIX__ && !defined(__ANDROID__)
1728 void MaybeCloseNamedPipe(uv_shutdown_t* req, int status) {
1729 uv_handle_t* handle = reinterpret_cast<uv_handle_t*>(req->handle);
1732 if (status == UV_ECANCELED) {
1733 return; // Already closing.
1735 if (status == UV_EPIPE) {
1736 return; // Read end went away before shutdown completed.
1738 assert(status == 0);
1740 if (uv_is_closing(handle)) {
1744 uv_close(handle, NULL);
1748 void MaybeCloseHandle(uv_handle_t* handle, void* unused) {
1749 if (uv_is_closing(handle)) {
1753 // Named pipes get special treatment: we do a shutdown first to flush
1754 // pending writes. Avoids truncated stdout/stderr output on Windows.
1755 bool do_shutdown = handle->type == UV_NAMED_PIPE &&
1756 uv_is_writable(reinterpret_cast<uv_stream_t*>(handle));
1758 if (do_shutdown == false) {
1759 uv_close(handle, NULL);
1763 uv_shutdown_t* req = new uv_shutdown_t;
1764 uv_stream_t* stream = reinterpret_cast<uv_stream_t*>(handle);
1765 int err = uv_shutdown(req, stream, MaybeCloseNamedPipe);
1767 assert(err == UV_ENOTCONN);
1773 void DisposeEventLoop(uv_loop_t* loop) {
1774 // Don't call into JS land from now on.
1775 process_state = SHUTTING_DOWN;
1776 // Force-close open handles.
1777 uv_walk(loop, MaybeCloseHandle, NULL);
1778 uv_run(loop, UV_RUN_DEFAULT);
1779 uv_loop_delete(loop);
1783 void Exit(const FunctionCallbackInfo<Value>& args) {
1784 HandleScope scope(node_isolate);
1785 int32_t exit_code = args[0]->Int32Value();
1786 DisposeEventLoop(uv_default_loop());
1791 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1792 HandleScope scope(node_isolate);
1794 if (uv_uptime(&uptime)) return;
1795 args.GetReturnValue().Set(uptime - prog_start_time);
1799 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1800 HandleScope scope(node_isolate);
1804 int err = uv_resident_set_memory(&rss);
1806 return ThrowUVException(err, "uv_resident_set_memory");
1809 Local<Object> info = Object::New();
1811 if (rss_symbol.IsEmpty()) {
1812 rss_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "rss");
1813 heap_total_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "heapTotal");
1814 heap_used_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "heapUsed");
1817 info->Set(rss_symbol, Number::New(rss));
1820 HeapStatistics v8_heap_stats;
1821 node_isolate->GetHeapStatistics(&v8_heap_stats);
1822 info->Set(heap_total_symbol,
1823 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(),
1825 info->Set(heap_used_symbol,
1826 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(),
1829 args.GetReturnValue().Set(info);
1833 void Kill(const FunctionCallbackInfo<Value>& args) {
1834 HandleScope scope(node_isolate);
1836 if (args.Length() != 2) {
1837 return ThrowError("Bad argument.");
1840 int pid = args[0]->IntegerValue();
1841 int sig = args[1]->Int32Value();
1842 int err = uv_kill(pid, sig);
1843 args.GetReturnValue().Set(err);
1846 // used in Hrtime() below
1847 #define NANOS_PER_SEC 1000000000
1849 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1850 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1851 // so this function instead returns an Array with 2 entries representing seconds
1852 // and nanoseconds, to avoid any integer overflow possibility.
1853 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1854 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1855 HandleScope scope(node_isolate);
1857 uint64_t t = uv_hrtime();
1859 if (args.Length() > 0) {
1860 // return a time diff tuple
1861 if (!args[0]->IsArray()) {
1862 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1864 Local<Array> inArray = Local<Array>::Cast(args[0]);
1865 uint64_t seconds = inArray->Get(0)->Uint32Value();
1866 uint64_t nanos = inArray->Get(1)->Uint32Value();
1867 t -= (seconds * NANOS_PER_SEC) + nanos;
1870 Local<Array> tuple = Array::New(2);
1871 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1872 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1873 args.GetReturnValue().Set(tuple);
1877 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1879 // DLOpen is process.dlopen(module, filename).
1880 // Used to load 'module.node' dynamically shared objects.
1881 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1882 HandleScope scope(node_isolate);
1883 char symbol[1024], *base, *pos;
1887 if (args.Length() < 2) {
1888 return ThrowError("process.dlopen takes exactly 2 arguments.");
1891 Local<Object> module = args[0]->ToObject(); // Cast
1892 String::Utf8Value filename(args[1]); // Cast
1894 if (exports_symbol.IsEmpty()) {
1895 exports_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "exports");
1897 Local<Object> exports = module->Get(exports_symbol)->ToObject();
1899 if (uv_dlopen(*filename, &lib)) {
1900 Local<String> errmsg = OneByteString(node_isolate, uv_dlerror(&lib));
1902 // Windows needs to add the filename into the error message
1903 errmsg = String::Concat(errmsg, args[1]->ToString());
1905 ThrowException(Exception::Error(errmsg));
1909 String::Utf8Value path(args[1]);
1912 /* Find the shared library filename within the full path. */
1914 pos = strrchr(base, '/');
1920 pos = strpbrk(base, "\\/:");
1928 /* Strip the .node extension. */
1929 pos = strrchr(base, '.');
1934 /* Add the `_module` suffix to the extension name. */
1935 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1936 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1937 return ThrowError("Out of memory.");
1940 /* Replace dashes with underscores. When loading foo-bar.node,
1941 * look for foo_bar_module, not foo-bar_module.
1943 for (pos = symbol; *pos != '\0'; ++pos) {
1944 if (*pos == '-') *pos = '_';
1947 node_module_struct *mod;
1948 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1950 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1951 return ThrowError(errmsg);
1954 if (mod->version != NODE_MODULE_VERSION) {
1958 "Module version mismatch. Expected %d, got %d.",
1959 NODE_MODULE_VERSION, mod->version);
1960 return ThrowError(errmsg);
1963 // Execute the C++ module
1964 mod->register_func(exports, module);
1966 // Tell coverity that 'handle' should not be freed when we return.
1967 // coverity[leaked_storage]
1971 static void OnFatalError(const char* location, const char* message) {
1973 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1975 fprintf(stderr, "FATAL ERROR: %s\n", message);
1985 NO_RETURN void FatalError(const char* location, const char* message) {
1986 OnFatalError(location, message);
1987 // to supress compiler warning
1992 void FatalException(Handle<Value> error, Handle<Message> message) {
1993 HandleScope scope(node_isolate);
1995 if (fatal_exception_symbol.IsEmpty()) {
1996 fatal_exception_symbol =
1997 FIXED_ONE_BYTE_STRING(node_isolate, "_fatalException");
2000 Local<Object> process = PersistentToLocal(node_isolate, process_p);
2001 Local<Value> fatal_v = process->Get(fatal_exception_symbol);
2003 if (!fatal_v->IsFunction()) {
2004 // failed before the process._fatalException function was added!
2005 // this is probably pretty bad. Nothing to do but report and exit.
2006 ReportException(error, message);
2010 Local<Function> fatal_f = Local<Function>::Cast(fatal_v);
2012 TryCatch fatal_try_catch;
2014 // Do not call FatalException when _fatalException handler throws
2015 fatal_try_catch.SetVerbose(false);
2017 // this will return true if the JS layer handled it, false otherwise
2018 Local<Value> caught = fatal_f->Call(process, 1, &error);
2020 if (fatal_try_catch.HasCaught()) {
2021 // the fatal exception function threw, so we must exit
2022 ReportException(fatal_try_catch);
2026 if (false == caught->BooleanValue()) {
2027 ReportException(error, message);
2033 void FatalException(const TryCatch& try_catch) {
2034 HandleScope scope(node_isolate);
2035 // TODO(bajtos) do not call FatalException if try_catch is verbose
2036 // (requires V8 API to expose getter for try_catch.is_verbose_)
2037 FatalException(try_catch.Exception(), try_catch.Message());
2041 void OnMessage(Handle<Message> message, Handle<Value> error) {
2042 // The current version of V8 sends messages for errors only
2043 // (thus `error` is always set).
2044 FatalException(error, message);
2048 static void Binding(const FunctionCallbackInfo<Value>& args) {
2049 HandleScope scope(node_isolate);
2051 Local<String> module = args[0]->ToString();
2052 String::Utf8Value module_v(module);
2053 node_module_struct* modp;
2055 Local<Object> cache = PersistentToLocal(node_isolate, binding_cache);
2056 Local<Object> exports;
2058 if (cache->Has(module)) {
2059 exports = cache->Get(module)->ToObject();
2060 args.GetReturnValue().Set(exports);
2064 // Append a string to process.moduleLoadList
2066 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
2068 Local<Array> modules = PersistentToLocal(node_isolate, module_load_list);
2069 uint32_t l = modules->Length();
2070 modules->Set(l, OneByteString(node_isolate, buf));
2072 if ((modp = get_builtin_module(*module_v)) != NULL) {
2073 exports = Object::New();
2074 // Internal bindings don't have a "module" object,
2076 modp->register_func(exports, Undefined(node_isolate));
2077 cache->Set(module, exports);
2078 } else if (!strcmp(*module_v, "constants")) {
2079 exports = Object::New();
2080 DefineConstants(exports);
2081 cache->Set(module, exports);
2082 } else if (!strcmp(*module_v, "natives")) {
2083 exports = Object::New();
2084 DefineJavaScript(exports);
2085 cache->Set(module, exports);
2087 return ThrowError("No such module");
2090 args.GetReturnValue().Set(exports);
2094 static void ProcessTitleGetter(Local<String> property,
2095 const PropertyCallbackInfo<Value>& info) {
2096 HandleScope scope(node_isolate);
2098 uv_get_process_title(buffer, sizeof(buffer));
2099 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2103 static void ProcessTitleSetter(Local<String> property,
2105 const PropertyCallbackInfo<void>& info) {
2106 HandleScope scope(node_isolate);
2107 String::Utf8Value title(value);
2108 // TODO(piscisaureus): protect with a lock
2109 uv_set_process_title(*title);
2113 static void EnvGetter(Local<String> property,
2114 const PropertyCallbackInfo<Value>& info) {
2115 HandleScope scope(node_isolate);
2117 String::Utf8Value key(property);
2118 const char* val = getenv(*key);
2120 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2123 String::Value key(property);
2124 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2125 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2127 ARRAY_SIZE(buffer));
2128 // If result >= sizeof buffer the buffer was too small. That should never
2129 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2131 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2132 result < ARRAY_SIZE(buffer)) {
2133 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2134 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2135 return info.GetReturnValue().Set(rc);
2138 // Not found. Fetch from prototype.
2139 info.GetReturnValue().Set(
2140 info.Data().As<Object>()->Get(property));
2144 static void EnvSetter(Local<String> property,
2146 const PropertyCallbackInfo<Value>& info) {
2147 HandleScope scope(node_isolate);
2149 String::Utf8Value key(property);
2150 String::Utf8Value val(value);
2151 setenv(*key, *val, 1);
2153 String::Value key(property);
2154 String::Value val(value);
2155 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2156 // Environment variables that start with '=' are read-only.
2157 if (key_ptr[0] != L'=') {
2158 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2161 // Whether it worked or not, always return rval.
2162 info.GetReturnValue().Set(value);
2166 static void EnvQuery(Local<String> property,
2167 const PropertyCallbackInfo<Integer>& info) {
2168 HandleScope scope(node_isolate);
2169 int32_t rc = -1; // Not found unless proven otherwise.
2171 String::Utf8Value key(property);
2172 if (getenv(*key)) rc = 0;
2174 String::Value key(property);
2175 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2176 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2177 GetLastError() == ERROR_SUCCESS) {
2179 if (key_ptr[0] == L'=') {
2180 // Environment variables that start with '=' are hidden and read-only.
2181 rc = static_cast<int32_t>(v8::ReadOnly) |
2182 static_cast<int32_t>(v8::DontDelete) |
2183 static_cast<int32_t>(v8::DontEnum);
2187 if (rc != -1) info.GetReturnValue().Set(rc);
2191 static void EnvDeleter(Local<String> property,
2192 const PropertyCallbackInfo<Boolean>& info) {
2193 HandleScope scope(node_isolate);
2196 String::Utf8Value key(property);
2197 rc = getenv(*key) != NULL;
2198 if (rc) unsetenv(*key);
2200 String::Value key(property);
2201 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2202 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2203 // Deletion failed. Return true if the key wasn't there in the first place,
2204 // false if it is still there.
2205 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2206 GetLastError() != ERROR_SUCCESS;
2209 info.GetReturnValue().Set(rc);
2213 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2214 HandleScope scope(node_isolate);
2217 while (environ[size]) size++;
2219 Local<Array> env = Array::New(size);
2221 for (int i = 0; i < size; ++i) {
2222 const char* var = environ[i];
2223 const char* s = strchr(var, '=');
2224 const int length = s ? s - var : strlen(var);
2225 Local<String> name = String::NewFromUtf8(node_isolate,
2227 String::kNormalString,
2232 WCHAR* environment = GetEnvironmentStringsW();
2233 if (environment == NULL) return; // This should not happen.
2234 Local<Array> env = Array::New();
2235 WCHAR* p = environment;
2237 while (*p != NULL) {
2240 // If the key starts with '=' it is a hidden environment variable.
2244 s = wcschr(p, L'=');
2249 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2250 const size_t two_byte_buffer_len = s - p;
2251 Local<String> value = String::NewFromTwoByte(node_isolate,
2253 String::kNormalString,
2254 two_byte_buffer_len);
2255 env->Set(i++, value);
2256 p = s + wcslen(s) + 1;
2258 FreeEnvironmentStringsW(environment);
2261 info.GetReturnValue().Set(env);
2265 static Handle<Object> GetFeatures() {
2266 HandleScope scope(node_isolate);
2268 Local<Object> obj = Object::New();
2269 #if defined(DEBUG) && DEBUG
2270 Local<Value> debug = True(node_isolate);
2272 Local<Value> debug = False(node_isolate);
2273 #endif // defined(DEBUG) && DEBUG
2275 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2277 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2278 // TODO(bnoordhuis) ping libuv
2279 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2281 #ifdef OPENSSL_NPN_NEGOTIATED
2282 Local<Boolean> tls_npn = True(node_isolate);
2284 Local<Boolean> tls_npn = False(node_isolate);
2286 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"), tls_npn);
2288 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2289 Local<Boolean> tls_sni = True(node_isolate);
2291 Local<Boolean> tls_sni = False(node_isolate);
2293 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"), tls_sni);
2295 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2296 Boolean::New(get_builtin_module("crypto") != NULL));
2298 return scope.Close(obj);
2302 static void DebugPortGetter(Local<String> property,
2303 const PropertyCallbackInfo<Value>& info) {
2304 HandleScope scope(node_isolate);
2305 info.GetReturnValue().Set(debug_port);
2309 static void DebugPortSetter(Local<String> property,
2311 const PropertyCallbackInfo<void>& info) {
2312 HandleScope scope(node_isolate);
2313 debug_port = value->NumberValue();
2317 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2318 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2319 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2322 void NeedImmediateCallbackGetter(Local<String> property,
2323 const PropertyCallbackInfo<Value>& info) {
2324 info.GetReturnValue().Set(need_immediate_cb);
2328 static void NeedImmediateCallbackSetter(Local<String> property,
2330 const PropertyCallbackInfo<void>&) {
2331 HandleScope scope(node_isolate);
2333 bool bool_value = value->BooleanValue();
2335 if (need_immediate_cb == bool_value) return;
2337 need_immediate_cb = bool_value;
2339 if (need_immediate_cb) {
2340 uv_check_start(&check_immediate_watcher, node::CheckImmediate);
2341 // idle handle is needed only to maintain event loop
2342 uv_idle_start(&idle_immediate_dummy, node::IdleImmediateDummy);
2344 uv_check_stop(&check_immediate_watcher);
2345 uv_idle_stop(&idle_immediate_dummy);
2350 #define READONLY_PROPERTY(obj, str, var) \
2352 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2356 Handle<Object> SetupProcessObject(int argc, char *argv[]) {
2357 HandleScope scope(node_isolate);
2361 Local<FunctionTemplate> process_template = FunctionTemplate::New();
2362 process_template->SetClassName(
2363 FIXED_ONE_BYTE_STRING(node_isolate, "process"));
2365 Local<Object> process = process_template->GetFunction()->NewInstance();
2366 assert(process.IsEmpty() == false);
2367 assert(process->IsObject() == true);
2369 process_p.Reset(node_isolate, process);
2371 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2373 ProcessTitleSetter);
2376 READONLY_PROPERTY(process,
2378 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2380 // process.moduleLoadList
2381 Local<Array> modules = Array::New();
2382 module_load_list.Reset(node_isolate, modules);
2383 READONLY_PROPERTY(process, "moduleLoadList", modules);
2386 Local<Object> versions = Object::New();
2387 READONLY_PROPERTY(process, "versions", versions);
2389 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2391 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2392 READONLY_PROPERTY(versions,
2394 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2396 // +1 to get rid of the leading 'v'
2397 READONLY_PROPERTY(versions,
2399 OneByteString(node_isolate, NODE_VERSION + 1));
2400 READONLY_PROPERTY(versions,
2402 OneByteString(node_isolate, V8::GetVersion()));
2403 READONLY_PROPERTY(versions,
2405 OneByteString(node_isolate, uv_version_string()));
2406 READONLY_PROPERTY(versions,
2408 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2410 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2411 READONLY_PROPERTY(versions,
2413 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2416 // Stupid code to slice out the version string.
2417 int c, l = strlen(OPENSSL_VERSION_TEXT);
2418 for (i = j = 0; i < l; i++) {
2419 c = OPENSSL_VERSION_TEXT[i];
2420 if ('0' <= c && c <= '9') {
2421 for (j = i + 1; j < l; j++) {
2422 c = OPENSSL_VERSION_TEXT[j];
2423 if (c == ' ') break;
2431 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2437 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2440 READONLY_PROPERTY(process,
2442 OneByteString(node_isolate, PLATFORM));
2445 Local<Array> arguments = Array::New(argc - option_end_index + 1);
2446 arguments->Set(0, String::NewFromUtf8(node_isolate, argv[0]));
2447 for (j = 1, i = option_end_index; i < argc; j++, i++) {
2448 arguments->Set(j, String::NewFromUtf8(node_isolate, argv[i]));
2450 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2453 Local<Array> exec_argv = Array::New(option_end_index - 1);
2454 for (j = 1, i = 0; j < option_end_index; j++, i++) {
2455 exec_argv->Set(i, String::NewFromUtf8(node_isolate, argv[j]));
2457 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_argv);
2459 // create process.env
2460 Local<ObjectTemplate> envTemplate = ObjectTemplate::New();
2461 envTemplate->SetNamedPropertyHandler(EnvGetter,
2467 Local<Object> env = envTemplate->NewInstance();
2468 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), env);
2470 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2471 READONLY_PROPERTY(process, "features", GetFeatures());
2472 process->SetAccessor(
2473 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2474 NeedImmediateCallbackGetter,
2475 NeedImmediateCallbackSetter);
2479 READONLY_PROPERTY(process,
2481 String::NewFromUtf8(node_isolate, eval_string));
2486 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2489 // -i, --interactive
2491 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2495 if (no_deprecation) {
2496 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2499 // --throw-deprecation
2500 if (throw_deprecation) {
2501 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2504 // --trace-deprecation
2505 if (trace_deprecation) {
2506 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2509 size_t exec_path_len = 2 * PATH_MAX;
2510 char* exec_path = new char[exec_path_len];
2511 Local<String> exec_path_value;
2512 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2513 exec_path_value = String::NewFromUtf8(node_isolate,
2515 String::kNormalString,
2518 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2520 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2524 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2528 // define various internal methods
2529 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2530 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2531 NODE_SET_METHOD(process, "reallyExit", Exit);
2532 NODE_SET_METHOD(process, "abort", Abort);
2533 NODE_SET_METHOD(process, "chdir", Chdir);
2534 NODE_SET_METHOD(process, "cwd", Cwd);
2536 NODE_SET_METHOD(process, "umask", Umask);
2538 #if defined(__POSIX__) && !defined(__ANDROID__)
2539 NODE_SET_METHOD(process, "getuid", GetUid);
2540 NODE_SET_METHOD(process, "setuid", SetUid);
2542 NODE_SET_METHOD(process, "setgid", SetGid);
2543 NODE_SET_METHOD(process, "getgid", GetGid);
2545 NODE_SET_METHOD(process, "getgroups", GetGroups);
2546 NODE_SET_METHOD(process, "setgroups", SetGroups);
2547 NODE_SET_METHOD(process, "initgroups", InitGroups);
2548 #endif // __POSIX__ && !defined(__ANDROID__)
2550 NODE_SET_METHOD(process, "_kill", Kill);
2552 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2553 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2554 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2556 NODE_SET_METHOD(process, "hrtime", Hrtime);
2558 NODE_SET_METHOD(process, "dlopen", DLOpen);
2560 NODE_SET_METHOD(process, "uptime", Uptime);
2561 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2563 NODE_SET_METHOD(process, "binding", Binding);
2565 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2567 // values use to cross communicate with processNextTick
2568 Local<Object> info_box = Object::New();
2569 info_box->SetIndexedPropertiesToExternalArrayData(&tick_infobox,
2570 kExternalUnsignedIntArray,
2572 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfoBox"), info_box);
2574 // pre-set _events object for faster emit checks
2575 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2577 return scope.Close(process);
2581 #undef READONLY_PROPERTY
2584 static void AtExit() {
2585 uv_tty_reset_mode();
2589 static void SignalExit(int signal) {
2590 uv_tty_reset_mode();
2591 _exit(128 + signal);
2595 void Load(Handle<Object> process_l) {
2596 HandleScope handle_scope(node_isolate);
2598 process_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "process");
2599 domain_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "domain");
2601 // Compile, execute the src/node.js file. (Which was included as static C
2602 // string in node_natives.h. 'natve_node' is the string containing that
2605 // The node.js file returns a function 'f'
2610 // Disable verbose mode to stop FatalException() handler from trying
2611 // to handle the exception. Errors this early in the start-up phase
2612 // are not safe to ignore.
2613 try_catch.SetVerbose(false);
2615 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2616 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2617 if (try_catch.HasCaught()) {
2618 ReportException(try_catch);
2621 assert(f_value->IsFunction());
2622 Local<Function> f = Local<Function>::Cast(f_value);
2624 // Now we call 'f' with the 'process' variable that we've built up with
2625 // all our bindings. Inside node.js we'll take care of assigning things to
2628 // We start the process this way in order to be more modular. Developers
2629 // who do not like how 'src/node.js' setups the module system but do like
2630 // Node's I/O bindings may want to replace 'f' with their own function.
2632 // Add a reference to the global object
2633 Local<Object> global = v8::Context::GetCurrent()->Global();
2635 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2639 #if defined HAVE_PERFCTR
2640 InitPerfCounters(global);
2643 // Enable handling of uncaught exceptions
2644 // (FatalException(), break on uncaught exception in debugger)
2646 // This is not strictly necessary since it's almost impossible
2647 // to attach the debugger fast enought to break on exception
2648 // thrown during process startup.
2649 try_catch.SetVerbose(true);
2651 Local<Value> arg = process_l;
2652 f->Call(global, 1, &arg);
2655 static void PrintHelp();
2657 static void ParseDebugOpt(const char* arg) {
2660 if (strstr(arg, "--debug-port=") == arg) {
2661 p = 1 + strchr(arg, '=');
2662 debug_port = atoi(p);
2664 use_debug_agent = true;
2665 if (!strcmp(arg, "--debug-brk")) {
2666 debug_wait_connect = true;
2668 } else if (!strcmp(arg, "--debug")) {
2670 } else if (strstr(arg, "--debug-brk=") == arg) {
2671 debug_wait_connect = true;
2672 p = 1 + strchr(arg, '=');
2673 debug_port = atoi(p);
2674 } else if (strstr(arg, "--debug=") == arg) {
2675 p = 1 + strchr(arg, '=');
2676 debug_port = atoi(p);
2679 if (p && debug_port > 1024 && debug_port < 65536)
2682 fprintf(stderr, "Bad debug option.\n");
2683 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2689 static void PrintHelp() {
2690 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2691 " node debug script.js [arguments] \n"
2694 " -v, --version print node's version\n"
2695 " -e, --eval script evaluate script\n"
2696 " -p, --print evaluate script and print result\n"
2697 " -i, --interactive always enter the REPL even if stdin\n"
2698 " does not appear to be a terminal\n"
2699 " --no-deprecation silence deprecation warnings\n"
2700 " --trace-deprecation show stack traces on deprecations\n"
2701 " --v8-options print v8 command line options\n"
2702 " --max-stack-size=val set max v8 stack size (bytes)\n"
2704 "Environment variables:\n"
2706 "NODE_PATH ';'-separated list of directories\n"
2708 "NODE_PATH ':'-separated list of directories\n"
2710 " prefixed to the module search path.\n"
2711 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2712 " global contexts.\n"
2713 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2715 "Documentation can be found at http://nodejs.org/\n");
2719 // Parse node command line arguments.
2720 static void ParseArgs(int argc, char **argv) {
2723 // TODO(bnoordhuis) use parse opts
2724 for (i = 1; i < argc; i++) {
2725 const char *arg = argv[i];
2726 if (strstr(arg, "--debug") == arg) {
2728 argv[i] = const_cast<char*>("");
2729 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2730 printf("%s\n", NODE_VERSION);
2732 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2735 } else if (strcmp(arg, "--eval") == 0 ||
2736 strcmp(arg, "-e") == 0 ||
2737 strcmp(arg, "--print") == 0 ||
2738 strcmp(arg, "-pe") == 0 ||
2739 strcmp(arg, "-p") == 0) {
2740 bool is_eval = strchr(arg, 'e') != NULL;
2741 bool is_print = strchr(arg, 'p') != NULL;
2743 // argument to -p and --print is optional
2744 if (is_eval == true && i + 1 >= argc) {
2745 fprintf(stderr, "Error: %s requires an argument\n", arg);
2749 print_eval = print_eval || is_print;
2750 argv[i] = const_cast<char*>("");
2752 // --eval, -e and -pe always require an argument
2753 if (is_eval == true) {
2754 eval_string = argv[++i];
2758 // next arg is the expression to evaluate unless it starts with:
2759 // - a dash, then it's another switch
2760 // - "\\-", then it's an escaped expression, drop the backslash
2761 if (argv[i + 1] == NULL) continue;
2762 if (argv[i + 1][0] == '-') continue;
2763 eval_string = argv[++i];
2764 if (strncmp(eval_string, "\\-", 2) == 0) ++eval_string;
2765 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2767 argv[i] = const_cast<char*>("");
2768 } else if (strcmp(arg, "--v8-options") == 0) {
2769 argv[i] = const_cast<char*>("--help");
2770 } else if (strcmp(arg, "--no-deprecation") == 0) {
2771 argv[i] = const_cast<char*>("");
2772 no_deprecation = true;
2773 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2774 argv[i] = const_cast<char*>("");
2775 trace_deprecation = true;
2776 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2777 argv[i] = const_cast<char*>("");
2778 throw_deprecation = true;
2779 } else if (argv[i][0] != '-') {
2784 option_end_index = i;
2788 // Called from the main thread.
2789 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2790 v8::Debug::ProcessDebugMessages();
2794 // Called from V8 Debug Agent TCP thread.
2795 static void DispatchMessagesDebugAgentCallback() {
2796 uv_async_send(&dispatch_debug_messages_async);
2800 // Called from the main thread
2801 static void EmitDebugEnabledAsyncCallback(uv_async_t* handle, int status) {
2802 HandleScope handle_scope(node_isolate);
2803 Local<Object> obj = Object::New();
2804 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "cmd"),
2805 FIXED_ONE_BYTE_STRING(node_isolate, "NODE_DEBUG_ENABLED"));
2806 Local<Value> args[] = {
2807 FIXED_ONE_BYTE_STRING(node_isolate, "internalMessage"),
2810 MakeCallback(process_p, "emit", ARRAY_SIZE(args), args);
2814 // Called from the signal watcher callback
2815 static void EmitDebugEnabled() {
2816 uv_async_send(&emit_debug_enabled_async);
2820 static void EnableDebug(bool wait_connect) {
2821 // If we're called from another thread, make sure to enter the right
2823 node_isolate->Enter();
2825 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2828 // Start the debug thread and it's associated TCP server on port 5858.
2829 bool r = v8::Debug::EnableAgent("node " NODE_VERSION,
2833 // Crappy check that everything went well. FIXME
2836 // Print out some information.
2837 fprintf(stderr, "debugger listening on port %d\n", debug_port);
2840 debugger_running = true;
2842 // Do not emit NODE_DEBUG_ENABLED when debugger is enabled before starting
2843 // the main process (i.e. when called via `node --debug`)
2844 if (!process_p.IsEmpty())
2847 node_isolate->Exit();
2852 static void EnableDebugSignalHandler(uv_signal_t* handle, int) {
2853 // Break once process will return execution to v8
2854 v8::Debug::DebugBreak(node_isolate);
2856 if (!debugger_running) {
2857 fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n");
2863 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2864 struct sigaction sa;
2866 memset(&sa, 0, sizeof(sa));
2867 sa.sa_handler = handler;
2868 sigfillset(&sa.sa_mask);
2869 sigaction(signal, &sa, NULL);
2873 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2874 HandleScope scope(node_isolate);
2876 if (args.Length() != 1) {
2877 return ThrowError("Invalid number of arguments.");
2883 pid = args[0]->IntegerValue();
2884 r = kill(pid, SIGUSR1);
2886 return ThrowErrnoException(errno, "kill");
2893 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2894 // Break once process will return execution to v8
2895 if (!debugger_running) {
2896 for (int i = 0; i < 1; i++) {
2897 fprintf(stderr, "Starting debugger agent.\r\n");
2903 v8::Debug::DebugBreak(node_isolate);
2909 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2911 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2915 static int RegisterDebugSignalHandler() {
2916 wchar_t mapping_name[32];
2917 HANDLE mapping_handle;
2919 LPTHREAD_START_ROUTINE* handler;
2921 pid = GetCurrentProcessId();
2923 if (GetDebugSignalHandlerMappingName(pid,
2925 ARRAY_SIZE(mapping_name)) < 0) {
2929 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2935 if (mapping_handle == NULL) {
2939 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2940 MapViewOfFile(mapping_handle,
2941 FILE_MAP_ALL_ACCESS,
2945 if (handler == NULL) {
2946 CloseHandle(mapping_handle);
2950 *handler = EnableDebugThreadProc;
2952 UnmapViewOfFile(static_cast<void*>(handler));
2958 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2959 HandleScope scope(node_isolate);
2961 HANDLE process = NULL;
2962 HANDLE thread = NULL;
2963 HANDLE mapping = NULL;
2964 wchar_t mapping_name[32];
2965 LPTHREAD_START_ROUTINE* handler = NULL;
2967 if (args.Length() != 1) {
2968 ThrowError("Invalid number of arguments.");
2972 pid = (DWORD) args[0]->IntegerValue();
2974 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2975 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2979 if (process == NULL) {
2980 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2984 if (GetDebugSignalHandlerMappingName(pid,
2986 ARRAY_SIZE(mapping_name)) < 0) {
2987 ThrowErrnoException(errno, "sprintf");
2991 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2992 if (mapping == NULL) {
2993 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
2997 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2998 MapViewOfFile(mapping,
3003 if (handler == NULL || *handler == NULL) {
3004 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
3008 thread = CreateRemoteThread(process,
3015 if (thread == NULL) {
3016 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
3020 // Wait for the thread to terminate
3021 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3022 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
3027 if (process != NULL)
3028 CloseHandle(process);
3030 CloseHandle(thread);
3031 if (handler != NULL)
3032 UnmapViewOfFile(handler);
3033 if (mapping != NULL)
3034 CloseHandle(mapping);
3039 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3040 v8::Debug::DebugBreak(node_isolate);
3044 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3045 if (debugger_running) {
3046 v8::Debug::DisableAgent();
3047 debugger_running = false;
3052 char** Init(int argc, char *argv[]) {
3053 // Initialize prog_start_time to get relative uptime.
3054 uv_uptime(&prog_start_time);
3056 // Make inherited handles noninheritable.
3057 uv_disable_stdio_inheritance();
3059 // init async debug messages dispatching
3060 uv_async_init(uv_default_loop(),
3061 &dispatch_debug_messages_async,
3062 DispatchDebugMessagesAsyncCallback);
3063 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3065 // init async NODE_DEBUG_ENABLED emitter
3066 uv_async_init(uv_default_loop(),
3067 &emit_debug_enabled_async,
3068 EmitDebugEnabledAsyncCallback);
3069 uv_unref(reinterpret_cast<uv_handle_t*>(&emit_debug_enabled_async));
3071 // Parse a few arguments which are specific to Node.
3072 node::ParseArgs(argc, argv);
3073 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
3074 // in the command line))
3075 int v8argc = option_end_index;
3076 char **v8argv = argv;
3078 if (debug_wait_connect) {
3079 // v8argv is a copy of argv up to the script file argument +2 if --debug-brk
3080 // to expose the v8 debugger js object so that node.js can set
3081 // a breakpoint on the first line of the startup script
3083 v8argv = new char*[v8argc];
3084 memcpy(v8argv, argv, sizeof(*argv) * option_end_index);
3085 v8argv[option_end_index] = const_cast<char*>("--expose_debug_as");
3086 v8argv[option_end_index + 1] = const_cast<char*>("v8debug");
3089 V8::SetFlagsFromCommandLine(&v8argc, v8argv, false);
3091 const char typed_arrays_flag[] = "--harmony_typed_arrays";
3092 V8::SetFlagsFromString(typed_arrays_flag, sizeof(typed_arrays_flag) - 1);
3093 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3095 // Fetch a reference to the main isolate, so we have a reference to it
3096 // even when we need it to access it from another (debugger) thread.
3097 node_isolate = Isolate::GetCurrent();
3101 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3102 RegisterSignalHandler(SIGINT, SignalExit);
3103 RegisterSignalHandler(SIGTERM, SignalExit);
3106 uv_check_init(uv_default_loop(), &check_immediate_watcher);
3107 uv_unref(reinterpret_cast<uv_handle_t*>(&check_immediate_watcher));
3108 uv_idle_init(uv_default_loop(), &idle_immediate_dummy);
3110 V8::SetFatalErrorHandler(node::OnFatalError);
3111 V8::AddMessageListener(OnMessage);
3113 // If the --debug flag was specified then initialize the debug thread.
3114 if (use_debug_agent) {
3115 EnableDebug(debug_wait_connect);
3118 RegisterDebugSignalHandler();
3120 static uv_signal_t signal_watcher;
3121 uv_signal_init(uv_default_loop(), &signal_watcher);
3122 uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1);
3123 uv_unref(reinterpret_cast<uv_handle_t*>(&signal_watcher));
3131 struct AtExitCallback {
3132 AtExitCallback* next_;
3133 void (*cb_)(void* arg);
3137 static AtExitCallback* at_exit_functions_;
3141 AtExitCallback* p = at_exit_functions_;
3142 at_exit_functions_ = NULL;
3145 AtExitCallback* q = p->next_;
3153 void AtExit(void (*cb)(void* arg), void* arg) {
3154 AtExitCallback* p = new AtExitCallback;
3157 p->next_ = at_exit_functions_;
3158 at_exit_functions_ = p;
3162 void EmitExit(v8::Handle<v8::Object> process_l) {
3163 // process.emit('exit')
3164 process_l->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3165 True(node_isolate));
3166 Local<Value> args[] = {
3167 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3168 Integer::New(0, node_isolate)
3170 MakeCallback(process_l, "emit", ARRAY_SIZE(args), args);
3173 static char **copy_argv(int argc, char **argv) {
3181 for (i = 0; i < argc; i++) {
3182 strlen_sum += strlen(argv[i]) + 1;
3185 argv_copy = static_cast<char**>(
3186 malloc(sizeof(*argv_copy) * (argc + 1) + strlen_sum));
3191 argv_data = reinterpret_cast<char*>(argv_copy) +
3192 sizeof(*argv_copy) * (argc + 1);
3194 for (i = 0; i < argc; i++) {
3195 argv_copy[i] = argv_data;
3196 len = strlen(argv[i]) + 1;
3197 memcpy(argv_data, argv[i], len);
3201 argv_copy[argc] = NULL;
3206 int Start(int argc, char *argv[]) {
3207 // Hack aroung with the argv pointer. Used for process.title = "blah".
3208 argv = uv_setup_args(argc, argv);
3210 // Logic to duplicate argv as Init() modifies arguments
3211 // that are passed into it.
3212 char **argv_copy = copy_argv(argc, argv);
3214 // This needs to run *before* V8::Initialize()
3215 // Use copy here as to not modify the original argv:
3216 Init(argc, argv_copy);
3220 Locker locker(node_isolate);
3221 HandleScope handle_scope(node_isolate);
3223 // Create the one and only Context.
3224 Local<Context> context = Context::New(node_isolate);
3225 Context::Scope context_scope(context);
3227 binding_cache.Reset(node_isolate, Object::New());
3229 // Use original argv, as we're just copying values out of it.
3230 Local<Object> process_l = SetupProcessObject(argc, argv);
3232 // Create all the objects, load modules, do everything.
3233 // so your next reading stop should be node::Load()!
3236 // All our arguments are loaded. We've evaluated all of the scripts. We
3237 // might even have created TCP servers. Now we enter the main eventloop. If
3238 // there are no watchers on the loop (except for the ones that were
3239 // uv_unref'd) then this function exits. As long as there are active
3240 // watchers, it blocks.
3241 process_state = RUNNING;
3242 uv_run(uv_default_loop(), UV_RUN_DEFAULT);
3244 EmitExit(process_l);
3248 DisposeEventLoop(uv_default_loop());
3251 // Clean up the copy: