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 const char* eval_string = NULL;
163 static bool use_debug_agent = false;
164 static bool debug_wait_connect = false;
165 static int debug_port = 5858;
166 bool using_domains = false;
168 // used by C++ modules as well
169 bool no_deprecation = false;
171 static uv_check_t check_immediate_watcher;
172 static uv_idle_t idle_immediate_dummy;
173 static bool need_immediate_cb;
174 static Cached<String> immediate_callback_sym;
176 // for quick ref to tickCallback values
184 // easily communicate domain depth
189 // process-relative uptime base, initialized at start-up
190 static double prog_start_time;
192 static volatile bool debugger_running = false;
193 static uv_async_t dispatch_debug_messages_async;
194 static uv_async_t emit_debug_enabled_async;
196 // Declared in node_internals.h
197 Isolate* node_isolate = NULL;
200 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
202 // Impose an upper limit to avoid out of memory errors that bring down
204 static const size_t kMaxLength = 0x3fffffff;
205 static ArrayBufferAllocator the_singleton;
206 virtual ~ArrayBufferAllocator() {}
207 virtual void* Allocate(size_t length);
208 virtual void Free(void* data);
210 ArrayBufferAllocator() {}
211 ArrayBufferAllocator(const ArrayBufferAllocator&);
212 void operator=(const ArrayBufferAllocator&);
215 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
218 void* ArrayBufferAllocator::Allocate(size_t length) {
219 if (length > kMaxLength) return NULL;
220 return new char[length];
224 void ArrayBufferAllocator::Free(void* data) {
225 delete[] static_cast<char*>(data);
229 static void CheckImmediate(uv_check_t* handle, int status) {
230 assert(handle == &check_immediate_watcher);
233 HandleScope scope(node_isolate);
235 if (immediate_callback_sym.IsEmpty()) {
236 immediate_callback_sym =
237 FIXED_ONE_BYTE_STRING(node_isolate, "_immediateCallback");
240 MakeCallback(process_p, immediate_callback_sym, 0, NULL);
244 static void IdleImmediateDummy(uv_idle_t* handle, int status) {
245 // Do nothing. Only for maintaining event loop
246 assert(handle == &idle_immediate_dummy);
251 static inline const char *errno_string(int errorno) {
252 #define ERRNO_CASE(e) case e: return #e;
259 ERRNO_CASE(EADDRINUSE);
263 ERRNO_CASE(EADDRNOTAVAIL);
267 ERRNO_CASE(EAFNOSUPPORT);
275 # if EAGAIN != EWOULDBLOCK
276 ERRNO_CASE(EWOULDBLOCK);
281 ERRNO_CASE(EALREADY);
297 ERRNO_CASE(ECANCELED);
305 ERRNO_CASE(ECONNABORTED);
309 ERRNO_CASE(ECONNREFUSED);
313 ERRNO_CASE(ECONNRESET);
321 ERRNO_CASE(EDESTADDRREQ);
345 ERRNO_CASE(EHOSTUNREACH);
357 ERRNO_CASE(EINPROGRESS);
393 ERRNO_CASE(EMSGSIZE);
397 ERRNO_CASE(EMULTIHOP);
401 ERRNO_CASE(ENAMETOOLONG);
405 ERRNO_CASE(ENETDOWN);
409 ERRNO_CASE(ENETRESET);
413 ERRNO_CASE(ENETUNREACH);
445 # if ENOLINK != ENOLCK
459 ERRNO_CASE(ENOPROTOOPT);
479 ERRNO_CASE(ENOTCONN);
487 ERRNO_CASE(ENOTEMPTY);
491 ERRNO_CASE(ENOTSOCK);
498 ERRNO_CASE(EOPNOTSUPP);
512 ERRNO_CASE(EOVERFLOW);
527 #ifdef EPROTONOSUPPORT
528 ERRNO_CASE(EPROTONOSUPPORT);
532 ERRNO_CASE(EPROTOTYPE);
560 ERRNO_CASE(ETIMEDOUT);
575 const char *signo_string(int signo) {
576 #define SIGNO_CASE(e) case e: return #e;
603 # if SIGABRT != SIGIOT
647 SIGNO_CASE(SIGSTKFLT);
664 SIGNO_CASE(SIGBREAK);
688 SIGNO_CASE(SIGVTALRM);
696 SIGNO_CASE(SIGWINCH);
704 # if SIGPOLL != SIGIO
714 # if SIGPWR != SIGLOST
728 Local<Value> ErrnoException(int errorno,
733 Local<String> estring = OneByteString(node_isolate, errno_string(errorno));
734 if (msg == NULL || msg[0] == '\0') {
735 msg = strerror(errorno);
737 Local<String> message = OneByteString(node_isolate, msg);
739 Local<String> cons1 =
740 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
741 Local<String> cons2 = String::Concat(cons1, message);
743 if (syscall_symbol.IsEmpty()) {
744 syscall_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "syscall");
745 errno_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "errno");
746 errpath_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "path");
747 code_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "code");
751 Local<String> cons3 =
752 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
753 Local<String> cons4 =
754 String::Concat(cons3, String::NewFromUtf8(node_isolate, path));
755 Local<String> cons5 =
756 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
757 e = Exception::Error(cons5);
759 e = Exception::Error(cons2);
762 Local<Object> obj = e->ToObject();
764 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
765 obj->Set(code_symbol, estring);
766 if (path) obj->Set(errpath_symbol, String::NewFromUtf8(node_isolate, path));
767 if (syscall) obj->Set(syscall_symbol, OneByteString(node_isolate, syscall));
772 // hack alert! copy of ErrnoException, tuned for uv errors
773 Local<Value> UVException(int errorno,
777 if (syscall_symbol.IsEmpty()) {
778 syscall_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "syscall");
779 errno_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "errno");
780 errpath_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "path");
781 code_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "code");
785 msg = uv_strerror(errorno);
787 Local<String> estring = OneByteString(node_isolate, uv_err_name(errorno));
788 Local<String> message = OneByteString(node_isolate, msg);
789 Local<String> cons1 =
790 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
791 Local<String> cons2 = String::Concat(cons1, message);
795 Local<String> path_str;
799 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
800 path_str = String::Concat(FIXED_ONE_BYTE_STRING(node_isolate, "\\\\"),
801 String::NewFromUtf8(node_isolate, path + 8));
802 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
803 path_str = String::NewFromUtf8(node_isolate, path + 4);
805 path_str = String::NewFromUtf8(node_isolate, path);
808 path_str = String::NewFromUtf8(node_isolate, path);
811 Local<String> cons3 =
812 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
813 Local<String> cons4 =
814 String::Concat(cons3, path_str);
815 Local<String> cons5 =
816 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
817 e = Exception::Error(cons5);
819 e = Exception::Error(cons2);
822 Local<Object> obj = e->ToObject();
824 // TODO(piscisaureus) errno should probably go
825 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
826 obj->Set(code_symbol, estring);
827 if (path) obj->Set(errpath_symbol, path_str);
828 if (syscall) obj->Set(syscall_symbol, OneByteString(node_isolate, syscall));
834 // Does about the same as strerror(),
835 // but supports all windows error messages
836 static const char *winapi_strerror(const int errorno) {
839 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
840 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
841 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
844 // Remove trailing newlines
845 for (int i = strlen(errmsg) - 1;
846 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
852 // FormatMessage failed
853 return "Unknown error";
858 Local<Value> WinapiErrnoException(int errorno,
863 if (!msg || !msg[0]) {
864 msg = winapi_strerror(errorno);
866 Local<String> message = OneByteString(node_isolate, msg);
868 if (syscall_symbol.IsEmpty()) {
869 syscall_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "syscall");
870 errno_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "errno");
871 errpath_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "path");
872 code_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "code");
876 Local<String> cons1 =
877 String::Concat(message, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
878 Local<String> cons2 =
879 String::Concat(cons1, String::NewFromUtf8(node_isolate, path));
880 Local<String> cons3 =
881 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
882 e = Exception::Error(cons3);
884 e = Exception::Error(message);
887 Local<Object> obj = e->ToObject();
889 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
890 if (path) obj->Set(errpath_symbol, String::NewFromUtf8(node_isolate, path));
891 if (syscall) obj->Set(syscall_symbol, OneByteString(node_isolate, syscall));
897 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
898 if (using_domains) return;
899 HandleScope scope(node_isolate);
900 using_domains = true;
901 Local<Object> process = PersistentToLocal(node_isolate, process_p);
903 process->Get(FIXED_ONE_BYTE_STRING(node_isolate, "_tickDomainCallback"));
904 if (!tdc_v->IsFunction()) {
905 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
908 Local<Function> tdc = tdc_v.As<Function>();
909 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"), tdc);
910 process_tickCallback.Reset(node_isolate, tdc);
911 if (!args[0]->IsArray()) {
912 fprintf(stderr, "_setupDomainUse first argument must be an array\n");
915 p_domain_box.Reset(node_isolate, args[0].As<Array>());
916 if (!args[1]->IsObject()) {
917 fprintf(stderr, "_setupDomainUse second argument must be an object\n");
920 Local<Object> flag = args[1].As<Object>();
921 flag->SetIndexedPropertiesToExternalArrayData(&domain_flag,
922 kExternalUnsignedIntArray,
928 return using_domains && domain_flag.count > 0;
932 Handle<Value> GetDomain() {
933 // no domain can exist if no domain module has been loaded
934 if (!InDomain() || p_domain_box.IsEmpty())
935 return Null(node_isolate);
937 return PersistentToLocal(node_isolate, p_domain_box)->Get(0);
942 MakeDomainCallback(const Handle<Object> object,
943 const Handle<Function> callback,
945 Handle<Value> argv[]) {
946 // TODO(trevnorris) Hook for long stack traces to be made here.
948 // lazy load domain specific symbols
949 if (enter_symbol.IsEmpty()) {
950 enter_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "enter");
951 exit_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "exit");
952 disposed_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "_disposed");
955 Local<Value> domain_v = object->Get(domain_symbol);
956 Local<Object> domain;
957 Local<Function> enter;
958 Local<Function> exit;
961 try_catch.SetVerbose(true);
963 bool has_domain = domain_v->IsObject();
965 domain = domain_v->ToObject();
966 assert(!domain.IsEmpty());
967 if (domain->Get(disposed_symbol)->IsTrue()) {
968 // domain has been disposed of.
969 return Undefined(node_isolate);
971 enter = Local<Function>::Cast(domain->Get(enter_symbol));
972 assert(!enter.IsEmpty());
973 enter->Call(domain, 0, NULL);
975 if (try_catch.HasCaught()) {
976 return Undefined(node_isolate);
980 Local<Value> ret = callback->Call(object, argc, argv);
982 if (try_catch.HasCaught()) {
983 return Undefined(node_isolate);
987 exit = Local<Function>::Cast(domain->Get(exit_symbol));
988 assert(!exit.IsEmpty());
989 exit->Call(domain, 0, NULL);
991 if (try_catch.HasCaught()) {
992 return Undefined(node_isolate);
996 if (tick_infobox.last_threw == 1) {
997 tick_infobox.last_threw = 0;
1001 if (tick_infobox.in_tick == 1) {
1005 if (tick_infobox.length == 0) {
1006 tick_infobox.index = 0;
1010 // process nextTicks after call
1011 Local<Object> process = PersistentToLocal(node_isolate, process_p);
1012 Local<Function> fn = PersistentToLocal(node_isolate, process_tickCallback);
1013 fn->Call(process, 0, NULL);
1015 if (try_catch.HasCaught()) {
1016 return Undefined(node_isolate);
1024 MakeCallback(const Handle<Object> object,
1025 const Handle<Function> callback,
1027 Handle<Value> argv[]) {
1028 // TODO(trevnorris) Hook for long stack traces to be made here.
1029 Local<Object> process = PersistentToLocal(node_isolate, process_p);
1032 return MakeDomainCallback(object, callback, argc, argv);
1034 // lazy load no domain next tick callbacks
1035 if (process_tickCallback.IsEmpty()) {
1037 process->Get(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"));
1038 if (!cb_v->IsFunction()) {
1039 fprintf(stderr, "process._tickCallback assigned to non-function\n");
1042 process_tickCallback.Reset(node_isolate, cb_v.As<Function>());
1046 try_catch.SetVerbose(true);
1048 Local<Value> ret = callback->Call(object, argc, argv);
1050 if (try_catch.HasCaught()) {
1051 return Undefined(node_isolate);
1054 if (tick_infobox.in_tick == 1) {
1058 if (tick_infobox.length == 0) {
1059 tick_infobox.index = 0;
1063 // process nextTicks after call
1064 Local<Function> fn = PersistentToLocal(node_isolate, process_tickCallback);
1065 fn->Call(process, 0, NULL);
1067 if (try_catch.HasCaught()) {
1068 return Undefined(node_isolate);
1077 MakeCallback(const Handle<Object> object,
1080 Handle<Value> argv[]) {
1081 HandleScope scope(node_isolate);
1083 Local<Function> callback = object->Get(index).As<Function>();
1084 assert(callback->IsFunction());
1087 return scope.Close(MakeDomainCallback(object, callback, argc, argv));
1088 return scope.Close(MakeCallback(object, callback, argc, argv));
1093 MakeCallback(const Handle<Object> object,
1094 const Handle<String> symbol,
1096 Handle<Value> argv[]) {
1097 HandleScope scope(node_isolate);
1099 Local<Function> callback = object->Get(symbol).As<Function>();
1100 assert(callback->IsFunction());
1103 return scope.Close(MakeDomainCallback(object, callback, argc, argv));
1104 return scope.Close(MakeCallback(object, callback, argc, argv));
1109 MakeCallback(const Handle<Object> object,
1112 Handle<Value> argv[]) {
1113 HandleScope scope(node_isolate);
1115 Local<String> method_string = OneByteString(node_isolate, method);
1116 Handle<Value> ret = MakeCallback(object, method_string, argc, argv);
1118 return scope.Close(ret);
1122 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1123 HandleScope scope(node_isolate);
1125 if (!encoding_v->IsString()) return _default;
1127 String::Utf8Value encoding(encoding_v);
1129 if (strcasecmp(*encoding, "utf8") == 0) {
1131 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1133 } else if (strcasecmp(*encoding, "ascii") == 0) {
1135 } else if (strcasecmp(*encoding, "base64") == 0) {
1137 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1139 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1141 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1143 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1145 } else if (strcasecmp(*encoding, "binary") == 0) {
1147 } else if (strcasecmp(*encoding, "buffer") == 0) {
1149 } else if (strcasecmp(*encoding, "hex") == 0) {
1151 } else if (strcasecmp(*encoding, "raw") == 0) {
1152 if (!no_deprecation) {
1153 fprintf(stderr, "'raw' (array of integers) has been removed. "
1157 } else if (strcasecmp(*encoding, "raws") == 0) {
1158 if (!no_deprecation) {
1159 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1160 "Please update your code.\n");
1168 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1169 return StringBytes::Encode(static_cast<const char*>(buf),
1174 // Returns -1 if the handle was not valid for decoding
1175 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1176 HandleScope scope(node_isolate);
1178 if (val->IsArray()) {
1179 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1185 return StringBytes::Size(val, encoding);
1189 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1192 // Returns number of bytes written.
1193 ssize_t DecodeWrite(char *buf,
1195 v8::Handle<v8::Value> val,
1196 enum encoding encoding) {
1197 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1200 void DisplayExceptionLine(Handle<Message> message) {
1201 // Prevent re-entry into this function. For example, if there is
1202 // a throw from a program in vm.runInThisContext(code, filename, true),
1203 // then we want to show the original failure, not the secondary one.
1204 static bool displayed_error = false;
1206 if (displayed_error) return;
1207 displayed_error = true;
1209 uv_tty_reset_mode();
1211 fprintf(stderr, "\n");
1213 if (!message.IsEmpty()) {
1214 // Print (filename):(line number): (message).
1215 String::Utf8Value filename(message->GetScriptResourceName());
1216 const char* filename_string = *filename;
1217 int linenum = message->GetLineNumber();
1218 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1219 // Print line of source code.
1220 String::Utf8Value sourceline(message->GetSourceLine());
1221 const char* sourceline_string = *sourceline;
1223 // Because of how node modules work, all scripts are wrapped with a
1224 // "function (module, exports, __filename, ...) {"
1225 // to provide script local variables.
1227 // When reporting errors on the first line of a script, this wrapper
1228 // function is leaked to the user. There used to be a hack here to
1229 // truncate off the first 62 characters, but it caused numerous other
1230 // problems when vm.runIn*Context() methods were used for non-module
1233 // If we ever decide to re-instate such a hack, the following steps
1236 // 1. Pass a flag around to say "this code was wrapped"
1237 // 2. Update the stack frame output so that it is also correct.
1239 // It would probably be simpler to add a line rather than add some
1240 // number of characters to the first line, since V8 truncates the
1241 // sourceline to 78 characters, and we end up not providing very much
1242 // useful debugging info to the user if we remove 62 characters.
1244 int start = message->GetStartColumn();
1245 int end = message->GetEndColumn();
1247 fprintf(stderr, "%s\n", sourceline_string);
1248 // Print wavy underline (GetUnderline is deprecated).
1249 for (int i = 0; i < start; i++) {
1250 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1252 for (int i = start; i < end; i++) {
1255 fputc('\n', stderr);
1260 static void ReportException(Handle<Value> er, Handle<Message> message) {
1261 HandleScope scope(node_isolate);
1263 DisplayExceptionLine(message);
1265 Local<Value> trace_value(
1266 er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack")));
1267 String::Utf8Value trace(trace_value);
1269 // range errors have a trace member set to undefined
1270 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1271 fprintf(stderr, "%s\n", *trace);
1273 // this really only happens for RangeErrors, since they're the only
1274 // kind that won't have all this info in the trace, or when non-Error
1275 // objects are thrown manually.
1276 Local<Value> message;
1279 if (er->IsObject()) {
1280 Local<Object> err_obj = er.As<Object>();
1281 message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1282 name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1285 if (message.IsEmpty() ||
1286 message->IsUndefined() ||
1288 name->IsUndefined()) {
1289 // Not an error object. Just print as-is.
1290 String::Utf8Value message(er);
1291 fprintf(stderr, "%s\n", *message);
1293 String::Utf8Value name_string(name);
1294 String::Utf8Value message_string(message);
1295 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1303 static void ReportException(const TryCatch& try_catch) {
1304 ReportException(try_catch.Exception(), try_catch.Message());
1308 // Executes a str within the current v8 context.
1309 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1310 HandleScope scope(node_isolate);
1313 // try_catch must be nonverbose to disable FatalException() handler,
1314 // we will handle exceptions ourself.
1315 try_catch.SetVerbose(false);
1317 Local<v8::Script> script = v8::Script::Compile(source, filename);
1318 if (script.IsEmpty()) {
1319 ReportException(try_catch);
1323 Local<Value> result = script->Run();
1324 if (result.IsEmpty()) {
1325 ReportException(try_catch);
1329 return scope.Close(result);
1333 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1334 HandleScope scope(node_isolate);
1336 Local<Array> ary = Array::New();
1340 QUEUE_FOREACH(q, &req_wrap_queue) {
1341 ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1342 if (w->persistent().IsEmpty()) continue;
1343 ary->Set(i++, w->object());
1346 args.GetReturnValue().Set(ary);
1350 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1351 // implemented here for consistency with GetActiveRequests().
1352 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1353 HandleScope scope(node_isolate);
1355 Local<Array> ary = Array::New();
1359 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1361 QUEUE_FOREACH(q, &handle_wrap_queue) {
1362 HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1363 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue;
1364 Local<Object> object = w->object();
1365 Local<Value> owner = object->Get(owner_sym);
1366 if (owner->IsUndefined()) owner = object;
1367 ary->Set(i++, owner);
1370 args.GetReturnValue().Set(ary);
1374 static void Abort(const FunctionCallbackInfo<Value>& args) {
1379 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1380 HandleScope scope(node_isolate);
1382 if (args.Length() != 1 || !args[0]->IsString()) {
1383 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1386 String::Utf8Value path(args[0]);
1387 int err = uv_chdir(*path);
1389 return ThrowUVException(err, "uv_chdir");
1394 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1395 HandleScope scope(node_isolate);
1397 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1398 char buf[MAX_PATH * 4 + 1];
1400 char buf[PATH_MAX + 1];
1403 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1405 return ThrowUVException(err, "uv_cwd");
1408 buf[ARRAY_SIZE(buf) - 1] = '\0';
1409 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1411 args.GetReturnValue().Set(cwd);
1415 static void Umask(const FunctionCallbackInfo<Value>& args) {
1416 HandleScope scope(node_isolate);
1419 if (args.Length() < 1 || args[0]->IsUndefined()) {
1421 umask(static_cast<mode_t>(old));
1422 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1423 return ThrowTypeError("argument must be an integer or octal string.");
1426 if (args[0]->IsInt32()) {
1427 oct = args[0]->Uint32Value();
1430 String::Utf8Value str(args[0]);
1432 // Parse the octal string.
1433 for (int i = 0; i < str.length(); i++) {
1435 if (c > '7' || c < '0') {
1436 return ThrowTypeError("invalid octal string");
1442 old = umask(static_cast<mode_t>(oct));
1445 args.GetReturnValue().Set(old);
1449 #if defined(__POSIX__) && !defined(__ANDROID__)
1451 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1452 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1455 static uid_t uid_by_name(const char* name) {
1463 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1467 return uid_not_found;
1471 static char* name_by_uid(uid_t uid) {
1480 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1481 return strdup(pp->pw_name);
1492 static gid_t gid_by_name(const char* name) {
1500 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1504 return gid_not_found;
1508 #if 0 // For future use.
1509 static const char* name_by_gid(gid_t gid) {
1518 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1519 return strdup(pp->gr_name);
1531 static uid_t uid_by_name(Handle<Value> value) {
1532 if (value->IsUint32()) {
1533 return static_cast<uid_t>(value->Uint32Value());
1535 String::Utf8Value name(value);
1536 return uid_by_name(*name);
1541 static gid_t gid_by_name(Handle<Value> value) {
1542 if (value->IsUint32()) {
1543 return static_cast<gid_t>(value->Uint32Value());
1545 String::Utf8Value name(value);
1546 return gid_by_name(*name);
1551 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1552 args.GetReturnValue().Set(getuid());
1556 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1557 args.GetReturnValue().Set(getgid());
1561 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1562 HandleScope scope(node_isolate);
1564 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1565 return ThrowTypeError("setgid argument must be a number or a string");
1568 gid_t gid = gid_by_name(args[0]);
1570 if (gid == gid_not_found) {
1571 return ThrowError("setgid group id does not exist");
1575 return ThrowErrnoException(errno, "setgid");
1580 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1581 HandleScope scope(node_isolate);
1583 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1584 return ThrowTypeError("setuid argument must be a number or a string");
1587 uid_t uid = uid_by_name(args[0]);
1589 if (uid == uid_not_found) {
1590 return ThrowError("setuid user id does not exist");
1594 return ThrowErrnoException(errno, "setuid");
1599 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1600 HandleScope scope(node_isolate);
1602 int ngroups = getgroups(0, NULL);
1604 if (ngroups == -1) {
1605 return ThrowErrnoException(errno, "getgroups");
1608 gid_t* groups = new gid_t[ngroups];
1610 ngroups = getgroups(ngroups, groups);
1612 if (ngroups == -1) {
1614 return ThrowErrnoException(errno, "getgroups");
1617 Local<Array> groups_list = Array::New(ngroups);
1618 bool seen_egid = false;
1619 gid_t egid = getegid();
1621 for (int i = 0; i < ngroups; i++) {
1622 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1623 if (groups[i] == egid) seen_egid = true;
1628 if (seen_egid == false) {
1629 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1632 args.GetReturnValue().Set(groups_list);
1636 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1637 HandleScope scope(node_isolate);
1639 if (!args[0]->IsArray()) {
1640 return ThrowTypeError("argument 1 must be an array");
1643 Local<Array> groups_list = args[0].As<Array>();
1644 size_t size = groups_list->Length();
1645 gid_t* groups = new gid_t[size];
1647 for (size_t i = 0; i < size; i++) {
1648 gid_t gid = gid_by_name(groups_list->Get(i));
1650 if (gid == gid_not_found) {
1652 return ThrowError("group name not found");
1658 int rc = setgroups(size, groups);
1662 return ThrowErrnoException(errno, "setgroups");
1667 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1668 HandleScope scope(node_isolate);
1670 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1671 return ThrowTypeError("argument 1 must be a number or a string");
1674 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1675 return ThrowTypeError("argument 2 must be a number or a string");
1678 String::Utf8Value arg0(args[0]);
1683 if (args[0]->IsUint32()) {
1684 user = name_by_uid(args[0]->Uint32Value());
1692 return ThrowError("initgroups user not found");
1695 extra_group = gid_by_name(args[1]);
1697 if (extra_group == gid_not_found) {
1698 if (must_free) free(user);
1699 return ThrowError("initgroups extra group not found");
1702 int rc = initgroups(user, extra_group);
1709 return ThrowErrnoException(errno, "initgroups");
1713 #endif // __POSIX__ && !defined(__ANDROID__)
1716 void Exit(const FunctionCallbackInfo<Value>& args) {
1717 HandleScope scope(node_isolate);
1718 exit(args[0]->IntegerValue());
1722 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1723 HandleScope scope(node_isolate);
1725 if (uv_uptime(&uptime)) return;
1726 args.GetReturnValue().Set(uptime - prog_start_time);
1730 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1731 HandleScope scope(node_isolate);
1735 int err = uv_resident_set_memory(&rss);
1737 return ThrowUVException(err, "uv_resident_set_memory");
1740 Local<Object> info = Object::New();
1742 if (rss_symbol.IsEmpty()) {
1743 rss_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "rss");
1744 heap_total_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "heapTotal");
1745 heap_used_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "heapUsed");
1748 info->Set(rss_symbol, Number::New(rss));
1751 HeapStatistics v8_heap_stats;
1752 node_isolate->GetHeapStatistics(&v8_heap_stats);
1753 info->Set(heap_total_symbol,
1754 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(),
1756 info->Set(heap_used_symbol,
1757 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(),
1760 args.GetReturnValue().Set(info);
1764 void Kill(const FunctionCallbackInfo<Value>& args) {
1765 HandleScope scope(node_isolate);
1767 if (args.Length() != 2) {
1768 return ThrowError("Bad argument.");
1771 int pid = args[0]->IntegerValue();
1772 int sig = args[1]->Int32Value();
1773 int err = uv_kill(pid, sig);
1774 args.GetReturnValue().Set(err);
1777 // used in Hrtime() below
1778 #define NANOS_PER_SEC 1000000000
1780 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1781 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1782 // so this function instead returns an Array with 2 entries representing seconds
1783 // and nanoseconds, to avoid any integer overflow possibility.
1784 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1785 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1786 HandleScope scope(node_isolate);
1788 uint64_t t = uv_hrtime();
1790 if (args.Length() > 0) {
1791 // return a time diff tuple
1792 if (!args[0]->IsArray()) {
1793 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1795 Local<Array> inArray = Local<Array>::Cast(args[0]);
1796 uint64_t seconds = inArray->Get(0)->Uint32Value();
1797 uint64_t nanos = inArray->Get(1)->Uint32Value();
1798 t -= (seconds * NANOS_PER_SEC) + nanos;
1801 Local<Array> tuple = Array::New(2);
1802 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1803 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1804 args.GetReturnValue().Set(tuple);
1808 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1810 // DLOpen is process.dlopen(module, filename).
1811 // Used to load 'module.node' dynamically shared objects.
1812 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1813 HandleScope scope(node_isolate);
1814 char symbol[1024], *base, *pos;
1818 if (args.Length() < 2) {
1819 return ThrowError("process.dlopen takes exactly 2 arguments.");
1822 Local<Object> module = args[0]->ToObject(); // Cast
1823 String::Utf8Value filename(args[1]); // Cast
1825 if (exports_symbol.IsEmpty()) {
1826 exports_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "exports");
1828 Local<Object> exports = module->Get(exports_symbol)->ToObject();
1830 if (uv_dlopen(*filename, &lib)) {
1831 Local<String> errmsg = OneByteString(node_isolate, uv_dlerror(&lib));
1833 // Windows needs to add the filename into the error message
1834 errmsg = String::Concat(errmsg, args[1]->ToString());
1836 ThrowException(Exception::Error(errmsg));
1840 String::Utf8Value path(args[1]);
1843 /* Find the shared library filename within the full path. */
1845 pos = strrchr(base, '/');
1851 pos = strpbrk(base, "\\/:");
1859 /* Strip the .node extension. */
1860 pos = strrchr(base, '.');
1865 /* Add the `_module` suffix to the extension name. */
1866 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1867 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1868 return ThrowError("Out of memory.");
1871 /* Replace dashes with underscores. When loading foo-bar.node,
1872 * look for foo_bar_module, not foo-bar_module.
1874 for (pos = symbol; *pos != '\0'; ++pos) {
1875 if (*pos == '-') *pos = '_';
1878 node_module_struct *mod;
1879 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1881 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1882 return ThrowError(errmsg);
1885 if (mod->version != NODE_MODULE_VERSION) {
1889 "Module version mismatch. Expected %d, got %d.",
1890 NODE_MODULE_VERSION, mod->version);
1891 return ThrowError(errmsg);
1894 // Execute the C++ module
1895 mod->register_func(exports, module);
1897 // Tell coverity that 'handle' should not be freed when we return.
1898 // coverity[leaked_storage]
1902 static void OnFatalError(const char* location, const char* message) {
1904 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1906 fprintf(stderr, "FATAL ERROR: %s\n", message);
1916 NO_RETURN void FatalError(const char* location, const char* message) {
1917 OnFatalError(location, message);
1918 // to supress compiler warning
1923 void FatalException(Handle<Value> error, Handle<Message> message) {
1924 HandleScope scope(node_isolate);
1926 if (fatal_exception_symbol.IsEmpty()) {
1927 fatal_exception_symbol =
1928 FIXED_ONE_BYTE_STRING(node_isolate, "_fatalException");
1931 Local<Object> process = PersistentToLocal(node_isolate, process_p);
1932 Local<Value> fatal_v = process->Get(fatal_exception_symbol);
1934 if (!fatal_v->IsFunction()) {
1935 // failed before the process._fatalException function was added!
1936 // this is probably pretty bad. Nothing to do but report and exit.
1937 ReportException(error, message);
1941 Local<Function> fatal_f = Local<Function>::Cast(fatal_v);
1943 TryCatch fatal_try_catch;
1945 // Do not call FatalException when _fatalException handler throws
1946 fatal_try_catch.SetVerbose(false);
1948 // this will return true if the JS layer handled it, false otherwise
1949 Local<Value> caught = fatal_f->Call(process, 1, &error);
1951 if (fatal_try_catch.HasCaught()) {
1952 // the fatal exception function threw, so we must exit
1953 ReportException(fatal_try_catch);
1957 if (false == caught->BooleanValue()) {
1958 ReportException(error, message);
1964 void FatalException(const TryCatch& try_catch) {
1965 HandleScope scope(node_isolate);
1966 // TODO(bajtos) do not call FatalException if try_catch is verbose
1967 // (requires V8 API to expose getter for try_catch.is_verbose_)
1968 FatalException(try_catch.Exception(), try_catch.Message());
1972 void OnMessage(Handle<Message> message, Handle<Value> error) {
1973 // The current version of V8 sends messages for errors only
1974 // (thus `error` is always set).
1975 FatalException(error, message);
1979 static void Binding(const FunctionCallbackInfo<Value>& args) {
1980 HandleScope scope(node_isolate);
1982 Local<String> module = args[0]->ToString();
1983 String::Utf8Value module_v(module);
1984 node_module_struct* modp;
1986 Local<Object> cache = PersistentToLocal(node_isolate, binding_cache);
1987 Local<Object> exports;
1989 if (cache->Has(module)) {
1990 exports = cache->Get(module)->ToObject();
1991 args.GetReturnValue().Set(exports);
1995 // Append a string to process.moduleLoadList
1997 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
1999 Local<Array> modules = PersistentToLocal(node_isolate, module_load_list);
2000 uint32_t l = modules->Length();
2001 modules->Set(l, OneByteString(node_isolate, buf));
2003 if ((modp = get_builtin_module(*module_v)) != NULL) {
2004 exports = Object::New();
2005 // Internal bindings don't have a "module" object,
2007 modp->register_func(exports, Undefined(node_isolate));
2008 cache->Set(module, exports);
2009 } else if (!strcmp(*module_v, "constants")) {
2010 exports = Object::New();
2011 DefineConstants(exports);
2012 cache->Set(module, exports);
2013 } else if (!strcmp(*module_v, "natives")) {
2014 exports = Object::New();
2015 DefineJavaScript(exports);
2016 cache->Set(module, exports);
2018 return ThrowError("No such module");
2021 args.GetReturnValue().Set(exports);
2025 static void ProcessTitleGetter(Local<String> property,
2026 const PropertyCallbackInfo<Value>& info) {
2027 HandleScope scope(node_isolate);
2029 uv_get_process_title(buffer, sizeof(buffer));
2030 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2034 static void ProcessTitleSetter(Local<String> property,
2036 const PropertyCallbackInfo<void>& info) {
2037 HandleScope scope(node_isolate);
2038 String::Utf8Value title(value);
2039 // TODO(piscisaureus): protect with a lock
2040 uv_set_process_title(*title);
2044 static void EnvGetter(Local<String> property,
2045 const PropertyCallbackInfo<Value>& info) {
2046 HandleScope scope(node_isolate);
2048 String::Utf8Value key(property);
2049 const char* val = getenv(*key);
2051 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2054 String::Value key(property);
2055 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2056 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2058 ARRAY_SIZE(buffer));
2059 // If result >= sizeof buffer the buffer was too small. That should never
2060 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2062 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2063 result < ARRAY_SIZE(buffer)) {
2064 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2065 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2066 return info.GetReturnValue().Set(rc);
2069 // Not found. Fetch from prototype.
2070 info.GetReturnValue().Set(
2071 info.Data().As<Object>()->Get(property));
2075 static void EnvSetter(Local<String> property,
2077 const PropertyCallbackInfo<Value>& info) {
2078 HandleScope scope(node_isolate);
2080 String::Utf8Value key(property);
2081 String::Utf8Value val(value);
2082 setenv(*key, *val, 1);
2084 String::Value key(property);
2085 String::Value val(value);
2086 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2087 // Environment variables that start with '=' are read-only.
2088 if (key_ptr[0] != L'=') {
2089 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2092 // Whether it worked or not, always return rval.
2093 info.GetReturnValue().Set(value);
2097 static void EnvQuery(Local<String> property,
2098 const PropertyCallbackInfo<Integer>& info) {
2099 HandleScope scope(node_isolate);
2100 int32_t rc = -1; // Not found unless proven otherwise.
2102 String::Utf8Value key(property);
2103 if (getenv(*key)) rc = 0;
2105 String::Value key(property);
2106 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2107 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2108 GetLastError() == ERROR_SUCCESS) {
2110 if (key_ptr[0] == L'=') {
2111 // Environment variables that start with '=' are hidden and read-only.
2112 rc = static_cast<int32_t>(v8::ReadOnly) |
2113 static_cast<int32_t>(v8::DontDelete) |
2114 static_cast<int32_t>(v8::DontEnum);
2118 if (rc != -1) info.GetReturnValue().Set(rc);
2122 static void EnvDeleter(Local<String> property,
2123 const PropertyCallbackInfo<Boolean>& info) {
2124 HandleScope scope(node_isolate);
2127 String::Utf8Value key(property);
2128 rc = getenv(*key) != NULL;
2129 if (rc) unsetenv(*key);
2131 String::Value key(property);
2132 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2133 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2134 // Deletion failed. Return true if the key wasn't there in the first place,
2135 // false if it is still there.
2136 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2137 GetLastError() != ERROR_SUCCESS;
2140 info.GetReturnValue().Set(rc);
2144 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2145 HandleScope scope(node_isolate);
2148 while (environ[size]) size++;
2150 Local<Array> env = Array::New(size);
2152 for (int i = 0; i < size; ++i) {
2153 const char* var = environ[i];
2154 const char* s = strchr(var, '=');
2155 const int length = s ? s - var : strlen(var);
2156 Local<String> name = String::NewFromUtf8(node_isolate,
2158 String::kNormalString,
2163 WCHAR* environment = GetEnvironmentStringsW();
2164 if (environment == NULL) return; // This should not happen.
2165 Local<Array> env = Array::New();
2166 WCHAR* p = environment;
2168 while (*p != NULL) {
2171 // If the key starts with '=' it is a hidden environment variable.
2175 s = wcschr(p, L'=');
2180 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2181 const size_t two_byte_buffer_len = s - p;
2182 Local<String> value = String::NewFromTwoByte(node_isolate,
2184 String::kNormalString,
2185 two_byte_buffer_len);
2186 env->Set(i++, value);
2187 p = s + wcslen(s) + 1;
2189 FreeEnvironmentStringsW(environment);
2192 info.GetReturnValue().Set(env);
2196 static Handle<Object> GetFeatures() {
2197 HandleScope scope(node_isolate);
2199 Local<Object> obj = Object::New();
2200 #if defined(DEBUG) && DEBUG
2201 Local<Value> debug = True(node_isolate);
2203 Local<Value> debug = False(node_isolate);
2204 #endif // defined(DEBUG) && DEBUG
2206 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2208 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2209 // TODO(bnoordhuis) ping libuv
2210 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2212 #ifdef OPENSSL_NPN_NEGOTIATED
2213 Local<Boolean> tls_npn = True(node_isolate);
2215 Local<Boolean> tls_npn = False(node_isolate);
2217 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"), tls_npn);
2219 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2220 Local<Boolean> tls_sni = True(node_isolate);
2222 Local<Boolean> tls_sni = False(node_isolate);
2224 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"), tls_sni);
2226 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2227 Boolean::New(get_builtin_module("crypto") != NULL));
2229 return scope.Close(obj);
2233 static void DebugPortGetter(Local<String> property,
2234 const PropertyCallbackInfo<Value>& info) {
2235 HandleScope scope(node_isolate);
2236 info.GetReturnValue().Set(debug_port);
2240 static void DebugPortSetter(Local<String> property,
2242 const PropertyCallbackInfo<void>& info) {
2243 HandleScope scope(node_isolate);
2244 debug_port = value->NumberValue();
2248 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2249 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2250 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2253 void NeedImmediateCallbackGetter(Local<String> property,
2254 const PropertyCallbackInfo<Value>& info) {
2255 info.GetReturnValue().Set(need_immediate_cb);
2259 static void NeedImmediateCallbackSetter(Local<String> property,
2261 const PropertyCallbackInfo<void>&) {
2262 HandleScope scope(node_isolate);
2264 bool bool_value = value->BooleanValue();
2266 if (need_immediate_cb == bool_value) return;
2268 need_immediate_cb = bool_value;
2270 if (need_immediate_cb) {
2271 uv_check_start(&check_immediate_watcher, node::CheckImmediate);
2272 // idle handle is needed only to maintain event loop
2273 uv_idle_start(&idle_immediate_dummy, node::IdleImmediateDummy);
2275 uv_check_stop(&check_immediate_watcher);
2276 uv_idle_stop(&idle_immediate_dummy);
2281 #define READONLY_PROPERTY(obj, str, var) \
2283 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2287 Handle<Object> SetupProcessObject(int argc,
2288 const char* const* argv,
2290 const char* const* exec_argv) {
2291 HandleScope scope(node_isolate);
2295 Local<FunctionTemplate> process_template = FunctionTemplate::New();
2296 process_template->SetClassName(
2297 FIXED_ONE_BYTE_STRING(node_isolate, "process"));
2299 Local<Object> process = process_template->GetFunction()->NewInstance();
2300 assert(process.IsEmpty() == false);
2301 assert(process->IsObject() == true);
2303 process_p.Reset(node_isolate, process);
2305 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2307 ProcessTitleSetter);
2310 READONLY_PROPERTY(process,
2312 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2314 // process.moduleLoadList
2315 Local<Array> modules = Array::New();
2316 module_load_list.Reset(node_isolate, modules);
2317 READONLY_PROPERTY(process, "moduleLoadList", modules);
2320 Local<Object> versions = Object::New();
2321 READONLY_PROPERTY(process, "versions", versions);
2323 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2325 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2326 READONLY_PROPERTY(versions,
2328 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2330 // +1 to get rid of the leading 'v'
2331 READONLY_PROPERTY(versions,
2333 OneByteString(node_isolate, NODE_VERSION + 1));
2334 READONLY_PROPERTY(versions,
2336 OneByteString(node_isolate, V8::GetVersion()));
2337 READONLY_PROPERTY(versions,
2339 OneByteString(node_isolate, uv_version_string()));
2340 READONLY_PROPERTY(versions,
2342 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2344 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2345 READONLY_PROPERTY(versions,
2347 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2350 // Stupid code to slice out the version string.
2351 int c, l = strlen(OPENSSL_VERSION_TEXT);
2352 for (i = j = 0; i < l; i++) {
2353 c = OPENSSL_VERSION_TEXT[i];
2354 if ('0' <= c && c <= '9') {
2355 for (j = i + 1; j < l; j++) {
2356 c = OPENSSL_VERSION_TEXT[j];
2357 if (c == ' ') break;
2365 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2371 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2374 READONLY_PROPERTY(process,
2376 OneByteString(node_isolate, PLATFORM));
2379 Local<Array> arguments = Array::New(argc);
2380 for (int i = 0; i < argc; ++i) {
2381 arguments->Set(i, String::NewFromUtf8(node_isolate, argv[i]));
2383 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2386 Local<Array> exec_arguments = Array::New(exec_argc);
2387 for (int i = 0; i < exec_argc; ++i) {
2388 exec_arguments->Set(i, String::NewFromUtf8(node_isolate, exec_argv[i]));
2390 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_arguments);
2392 // create process.env
2393 Local<ObjectTemplate> envTemplate = ObjectTemplate::New();
2394 envTemplate->SetNamedPropertyHandler(EnvGetter,
2400 Local<Object> env = envTemplate->NewInstance();
2401 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), env);
2403 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2404 READONLY_PROPERTY(process, "features", GetFeatures());
2405 process->SetAccessor(
2406 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2407 NeedImmediateCallbackGetter,
2408 NeedImmediateCallbackSetter);
2412 READONLY_PROPERTY(process,
2414 String::NewFromUtf8(node_isolate, eval_string));
2419 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2422 // -i, --interactive
2424 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2428 if (no_deprecation) {
2429 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2432 // --throw-deprecation
2433 if (throw_deprecation) {
2434 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2437 // --trace-deprecation
2438 if (trace_deprecation) {
2439 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2442 size_t exec_path_len = 2 * PATH_MAX;
2443 char* exec_path = new char[exec_path_len];
2444 Local<String> exec_path_value;
2445 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2446 exec_path_value = String::NewFromUtf8(node_isolate,
2448 String::kNormalString,
2451 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2453 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2457 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2461 // define various internal methods
2462 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2463 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2464 NODE_SET_METHOD(process, "reallyExit", Exit);
2465 NODE_SET_METHOD(process, "abort", Abort);
2466 NODE_SET_METHOD(process, "chdir", Chdir);
2467 NODE_SET_METHOD(process, "cwd", Cwd);
2469 NODE_SET_METHOD(process, "umask", Umask);
2471 #if defined(__POSIX__) && !defined(__ANDROID__)
2472 NODE_SET_METHOD(process, "getuid", GetUid);
2473 NODE_SET_METHOD(process, "setuid", SetUid);
2475 NODE_SET_METHOD(process, "setgid", SetGid);
2476 NODE_SET_METHOD(process, "getgid", GetGid);
2478 NODE_SET_METHOD(process, "getgroups", GetGroups);
2479 NODE_SET_METHOD(process, "setgroups", SetGroups);
2480 NODE_SET_METHOD(process, "initgroups", InitGroups);
2481 #endif // __POSIX__ && !defined(__ANDROID__)
2483 NODE_SET_METHOD(process, "_kill", Kill);
2485 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2486 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2487 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2489 NODE_SET_METHOD(process, "hrtime", Hrtime);
2491 NODE_SET_METHOD(process, "dlopen", DLOpen);
2493 NODE_SET_METHOD(process, "uptime", Uptime);
2494 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2496 NODE_SET_METHOD(process, "binding", Binding);
2498 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2500 // values use to cross communicate with processNextTick
2501 Local<Object> info_box = Object::New();
2502 info_box->SetIndexedPropertiesToExternalArrayData(&tick_infobox,
2503 kExternalUnsignedIntArray,
2505 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfoBox"), info_box);
2507 // pre-set _events object for faster emit checks
2508 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2510 return scope.Close(process);
2514 #undef READONLY_PROPERTY
2517 static void AtExit() {
2518 uv_tty_reset_mode();
2522 static void SignalExit(int signal) {
2523 uv_tty_reset_mode();
2524 _exit(128 + signal);
2528 void Load(Handle<Object> process_l) {
2529 HandleScope handle_scope(node_isolate);
2531 process_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "process");
2532 domain_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "domain");
2534 // Compile, execute the src/node.js file. (Which was included as static C
2535 // string in node_natives.h. 'natve_node' is the string containing that
2538 // The node.js file returns a function 'f'
2543 // Disable verbose mode to stop FatalException() handler from trying
2544 // to handle the exception. Errors this early in the start-up phase
2545 // are not safe to ignore.
2546 try_catch.SetVerbose(false);
2548 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2549 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2550 if (try_catch.HasCaught()) {
2551 ReportException(try_catch);
2554 assert(f_value->IsFunction());
2555 Local<Function> f = Local<Function>::Cast(f_value);
2557 // Now we call 'f' with the 'process' variable that we've built up with
2558 // all our bindings. Inside node.js we'll take care of assigning things to
2561 // We start the process this way in order to be more modular. Developers
2562 // who do not like how 'src/node.js' setups the module system but do like
2563 // Node's I/O bindings may want to replace 'f' with their own function.
2565 // Add a reference to the global object
2566 Local<Object> global = v8::Context::GetCurrent()->Global();
2568 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2572 #if defined HAVE_PERFCTR
2573 InitPerfCounters(global);
2576 // Enable handling of uncaught exceptions
2577 // (FatalException(), break on uncaught exception in debugger)
2579 // This is not strictly necessary since it's almost impossible
2580 // to attach the debugger fast enought to break on exception
2581 // thrown during process startup.
2582 try_catch.SetVerbose(true);
2584 Local<Value> arg = process_l;
2585 f->Call(global, 1, &arg);
2588 static void PrintHelp();
2590 static void ParseDebugOpt(const char* arg) {
2593 if (strstr(arg, "--debug-port=") == arg) {
2594 p = 1 + strchr(arg, '=');
2595 debug_port = atoi(p);
2597 use_debug_agent = true;
2598 if (!strcmp(arg, "--debug-brk")) {
2599 debug_wait_connect = true;
2601 } else if (!strcmp(arg, "--debug")) {
2603 } else if (strstr(arg, "--debug-brk=") == arg) {
2604 debug_wait_connect = true;
2605 p = 1 + strchr(arg, '=');
2606 debug_port = atoi(p);
2607 } else if (strstr(arg, "--debug=") == arg) {
2608 p = 1 + strchr(arg, '=');
2609 debug_port = atoi(p);
2612 if (p && debug_port > 1024 && debug_port < 65536)
2615 fprintf(stderr, "Bad debug option.\n");
2616 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2622 static void PrintHelp() {
2623 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2624 " node debug script.js [arguments] \n"
2627 " -v, --version print node's version\n"
2628 " -e, --eval script evaluate script\n"
2629 " -p, --print evaluate script and print result\n"
2630 " -i, --interactive always enter the REPL even if stdin\n"
2631 " does not appear to be a terminal\n"
2632 " --no-deprecation silence deprecation warnings\n"
2633 " --trace-deprecation show stack traces on deprecations\n"
2634 " --v8-options print v8 command line options\n"
2635 " --max-stack-size=val set max v8 stack size (bytes)\n"
2637 "Environment variables:\n"
2639 "NODE_PATH ';'-separated list of directories\n"
2641 "NODE_PATH ':'-separated list of directories\n"
2643 " prefixed to the module search path.\n"
2644 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2645 " global contexts.\n"
2646 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2648 "Documentation can be found at http://nodejs.org/\n");
2652 // Parse command line arguments.
2654 // argv is modified in place. exec_argv and v8_argv are out arguments that
2655 // ParseArgs() allocates memory for and stores a pointer to the output
2656 // vector in. The caller should free them with delete[].
2660 // * argv contains the arguments with node and V8 options filtered out.
2661 // * exec_argv contains both node and V8 options and nothing else.
2662 // * v8_argv contains argv[0] plus any V8 options
2663 static void ParseArgs(int* argc,
2666 const char*** exec_argv,
2668 const char*** v8_argv) {
2669 const unsigned int nargs = static_cast<unsigned int>(*argc);
2670 const char** new_exec_argv = new const char*[nargs];
2671 const char** new_v8_argv = new const char*[nargs];
2672 const char** new_argv = new const char*[nargs];
2674 for (unsigned int i = 0; i < nargs; ++i) {
2675 new_exec_argv[i] = NULL;
2676 new_v8_argv[i] = NULL;
2680 // exec_argv starts with the first option, the other two start with argv[0].
2681 unsigned int new_exec_argc = 0;
2682 unsigned int new_v8_argc = 1;
2683 unsigned int new_argc = 1;
2684 new_v8_argv[0] = argv[0];
2685 new_argv[0] = argv[0];
2687 unsigned int index = 1;
2688 while (index < nargs && argv[index][0] == '-') {
2689 const char* const arg = argv[index];
2690 unsigned int args_consumed = 1;
2692 if (strstr(arg, "--debug") == arg) {
2694 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2695 printf("%s\n", NODE_VERSION);
2697 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2700 } else if (strcmp(arg, "--eval") == 0 ||
2701 strcmp(arg, "-e") == 0 ||
2702 strcmp(arg, "--print") == 0 ||
2703 strcmp(arg, "-pe") == 0 ||
2704 strcmp(arg, "-p") == 0) {
2705 bool is_eval = strchr(arg, 'e') != NULL;
2706 bool is_print = strchr(arg, 'p') != NULL;
2707 print_eval = print_eval || is_print;
2708 // --eval, -e and -pe always require an argument.
2709 if (is_eval == true) {
2711 eval_string = argv[index + 1];
2712 if (eval_string == NULL) {
2713 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
2716 } else if (argv[index + 1] != NULL && argv[index + 1][0] != '-') {
2718 eval_string = argv[index + 1];
2719 if (strncmp(eval_string, "\\-", 2) == 0) {
2720 // Starts with "\\-": escaped expression, drop the backslash.
2724 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2726 } else if (strcmp(arg, "--no-deprecation") == 0) {
2727 no_deprecation = true;
2728 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2729 trace_deprecation = true;
2730 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2731 throw_deprecation = true;
2732 } else if (strcmp(arg, "--v8-options") == 0) {
2733 new_v8_argv[new_v8_argc] = "--help";
2736 // V8 option. Pass through as-is.
2737 new_v8_argv[new_v8_argc] = arg;
2741 memcpy(new_exec_argv + new_exec_argc,
2743 args_consumed * sizeof(*argv));
2745 new_exec_argc += args_consumed;
2746 index += args_consumed;
2749 // Copy remaining arguments.
2750 const unsigned int args_left = nargs - index;
2751 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
2752 new_argc += args_left;
2754 *exec_argc = new_exec_argc;
2755 *exec_argv = new_exec_argv;
2756 *v8_argc = new_v8_argc;
2757 *v8_argv = new_v8_argv;
2759 // Copy new_argv over argv and update argc.
2760 memcpy(argv, new_argv, new_argc * sizeof(*argv));
2762 *argc = static_cast<int>(new_argc);
2766 // Called from the main thread.
2767 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2768 v8::Debug::ProcessDebugMessages();
2772 // Called from V8 Debug Agent TCP thread.
2773 static void DispatchMessagesDebugAgentCallback() {
2774 uv_async_send(&dispatch_debug_messages_async);
2778 // Called from the main thread
2779 static void EmitDebugEnabledAsyncCallback(uv_async_t* handle, int status) {
2780 HandleScope handle_scope(node_isolate);
2781 Local<Object> obj = Object::New();
2782 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "cmd"),
2783 FIXED_ONE_BYTE_STRING(node_isolate, "NODE_DEBUG_ENABLED"));
2784 Local<Value> args[] = {
2785 FIXED_ONE_BYTE_STRING(node_isolate, "internalMessage"),
2788 MakeCallback(process_p, "emit", ARRAY_SIZE(args), args);
2792 // Called from the signal watcher callback
2793 static void EmitDebugEnabled() {
2794 uv_async_send(&emit_debug_enabled_async);
2798 static void EnableDebug(bool wait_connect) {
2799 // If we're called from another thread, make sure to enter the right
2801 node_isolate->Enter();
2803 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2806 // Start the debug thread and it's associated TCP server on port 5858.
2807 bool r = v8::Debug::EnableAgent("node " NODE_VERSION,
2811 // Crappy check that everything went well. FIXME
2814 // Print out some information.
2815 fprintf(stderr, "debugger listening on port %d\n", debug_port);
2818 debugger_running = true;
2820 // Do not emit NODE_DEBUG_ENABLED when debugger is enabled before starting
2821 // the main process (i.e. when called via `node --debug`)
2822 if (!process_p.IsEmpty())
2825 node_isolate->Exit();
2830 static void EnableDebugSignalHandler(uv_signal_t* handle, int) {
2831 // Break once process will return execution to v8
2832 v8::Debug::DebugBreak(node_isolate);
2834 if (!debugger_running) {
2835 fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n");
2841 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2842 struct sigaction sa;
2844 memset(&sa, 0, sizeof(sa));
2845 sa.sa_handler = handler;
2846 sigfillset(&sa.sa_mask);
2847 sigaction(signal, &sa, NULL);
2851 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2852 HandleScope scope(node_isolate);
2854 if (args.Length() != 1) {
2855 return ThrowError("Invalid number of arguments.");
2861 pid = args[0]->IntegerValue();
2862 r = kill(pid, SIGUSR1);
2864 return ThrowErrnoException(errno, "kill");
2871 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2872 // Break once process will return execution to v8
2873 if (!debugger_running) {
2874 for (int i = 0; i < 1; i++) {
2875 fprintf(stderr, "Starting debugger agent.\r\n");
2881 v8::Debug::DebugBreak(node_isolate);
2887 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2889 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2893 static int RegisterDebugSignalHandler() {
2894 wchar_t mapping_name[32];
2895 HANDLE mapping_handle;
2897 LPTHREAD_START_ROUTINE* handler;
2899 pid = GetCurrentProcessId();
2901 if (GetDebugSignalHandlerMappingName(pid,
2903 ARRAY_SIZE(mapping_name)) < 0) {
2907 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2913 if (mapping_handle == NULL) {
2917 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2918 MapViewOfFile(mapping_handle,
2919 FILE_MAP_ALL_ACCESS,
2923 if (handler == NULL) {
2924 CloseHandle(mapping_handle);
2928 *handler = EnableDebugThreadProc;
2930 UnmapViewOfFile(static_cast<void*>(handler));
2936 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2937 HandleScope scope(node_isolate);
2939 HANDLE process = NULL;
2940 HANDLE thread = NULL;
2941 HANDLE mapping = NULL;
2942 wchar_t mapping_name[32];
2943 LPTHREAD_START_ROUTINE* handler = NULL;
2945 if (args.Length() != 1) {
2946 ThrowError("Invalid number of arguments.");
2950 pid = (DWORD) args[0]->IntegerValue();
2952 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2953 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2957 if (process == NULL) {
2958 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2962 if (GetDebugSignalHandlerMappingName(pid,
2964 ARRAY_SIZE(mapping_name)) < 0) {
2965 ThrowErrnoException(errno, "sprintf");
2969 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2970 if (mapping == NULL) {
2971 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
2975 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2976 MapViewOfFile(mapping,
2981 if (handler == NULL || *handler == NULL) {
2982 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
2986 thread = CreateRemoteThread(process,
2993 if (thread == NULL) {
2994 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
2998 // Wait for the thread to terminate
2999 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3000 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
3005 if (process != NULL)
3006 CloseHandle(process);
3008 CloseHandle(thread);
3009 if (handler != NULL)
3010 UnmapViewOfFile(handler);
3011 if (mapping != NULL)
3012 CloseHandle(mapping);
3017 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3018 v8::Debug::DebugBreak(node_isolate);
3022 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3023 if (debugger_running) {
3024 v8::Debug::DisableAgent();
3025 debugger_running = false;
3030 void Init(int* argc,
3033 const char*** exec_argv) {
3034 // Initialize prog_start_time to get relative uptime.
3035 uv_uptime(&prog_start_time);
3037 // Make inherited handles noninheritable.
3038 uv_disable_stdio_inheritance();
3040 // init async debug messages dispatching
3041 uv_async_init(uv_default_loop(),
3042 &dispatch_debug_messages_async,
3043 DispatchDebugMessagesAsyncCallback);
3044 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3046 // init async NODE_DEBUG_ENABLED emitter
3047 uv_async_init(uv_default_loop(),
3048 &emit_debug_enabled_async,
3049 EmitDebugEnabledAsyncCallback);
3050 uv_unref(reinterpret_cast<uv_handle_t*>(&emit_debug_enabled_async));
3052 // Parse a few arguments which are specific to Node.
3054 const char** v8_argv;
3055 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3057 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3058 // the argv array or the elements it points to.
3059 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3061 // Anything that's still in v8_argv is not a V8 or a node option.
3062 for (int i = 1; i < v8_argc; i++) {
3063 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3072 if (debug_wait_connect) {
3073 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3074 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3077 const char typed_arrays_flag[] = "--harmony_typed_arrays";
3078 V8::SetFlagsFromString(typed_arrays_flag, sizeof(typed_arrays_flag) - 1);
3079 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3081 // Fetch a reference to the main isolate, so we have a reference to it
3082 // even when we need it to access it from another (debugger) thread.
3083 node_isolate = Isolate::GetCurrent();
3087 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3088 RegisterSignalHandler(SIGINT, SignalExit);
3089 RegisterSignalHandler(SIGTERM, SignalExit);
3092 uv_check_init(uv_default_loop(), &check_immediate_watcher);
3093 uv_unref(reinterpret_cast<uv_handle_t*>(&check_immediate_watcher));
3094 uv_idle_init(uv_default_loop(), &idle_immediate_dummy);
3096 V8::SetFatalErrorHandler(node::OnFatalError);
3097 V8::AddMessageListener(OnMessage);
3099 // If the --debug flag was specified then initialize the debug thread.
3100 if (use_debug_agent) {
3101 EnableDebug(debug_wait_connect);
3104 RegisterDebugSignalHandler();
3106 static uv_signal_t signal_watcher;
3107 uv_signal_init(uv_default_loop(), &signal_watcher);
3108 uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1);
3109 uv_unref(reinterpret_cast<uv_handle_t*>(&signal_watcher));
3115 struct AtExitCallback {
3116 AtExitCallback* next_;
3117 void (*cb_)(void* arg);
3121 static AtExitCallback* at_exit_functions_;
3125 AtExitCallback* p = at_exit_functions_;
3126 at_exit_functions_ = NULL;
3129 AtExitCallback* q = p->next_;
3137 void AtExit(void (*cb)(void* arg), void* arg) {
3138 AtExitCallback* p = new AtExitCallback;
3141 p->next_ = at_exit_functions_;
3142 at_exit_functions_ = p;
3146 void EmitExit(v8::Handle<v8::Object> process_l) {
3147 // process.emit('exit')
3148 process_l->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3149 True(node_isolate));
3150 Local<Value> args[] = {
3151 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3152 Integer::New(0, node_isolate)
3154 MakeCallback(process_l, "emit", ARRAY_SIZE(args), args);
3158 int Start(int argc, char** argv) {
3161 // Hack around with the argv pointer. Used for process.title = "blah".
3162 argv = uv_setup_args(argc, argv);
3164 // This needs to run *before* V8::Initialize(). The const_cast is not
3165 // optional, in case you're wondering.
3167 const char** exec_argv;
3168 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3172 Locker locker(node_isolate);
3173 HandleScope handle_scope(node_isolate);
3175 // Create the one and only Context.
3176 Local<Context> context = Context::New(node_isolate);
3177 Context::Scope context_scope(context);
3179 binding_cache.Reset(node_isolate, Object::New());
3181 // Use original argv, as we're just copying values out of it.
3182 Local<Object> process_l =
3183 SetupProcessObject(argc, argv, exec_argc, exec_argv);
3185 // Create all the objects, load modules, do everything.
3186 // so your next reading stop should be node::Load()!
3189 // All our arguments are loaded. We've evaluated all of the scripts. We
3190 // might even have created TCP servers. Now we enter the main eventloop. If
3191 // there are no watchers on the loop (except for the ones that were
3192 // uv_unref'd) then this function exits. As long as there are active
3193 // watchers, it blocks.
3194 uv_run(uv_default_loop(), UV_RUN_DEFAULT);
3196 EmitExit(process_l);
3201 // Clean up. Not strictly necessary.