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.
24 #include "handle_wrap.h"
25 #include "string_bytes.h"
31 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
32 # include "node_dtrace.h"
34 #if defined HAVE_PERFCTR
35 # include "node_counters.h"
43 #if !defined(_MSC_VER)
46 #define strcasecmp _stricmp
48 #include <limits.h> /* PATH_MAX */
50 #if !defined(_MSC_VER)
51 #include <unistd.h> /* setuid, getuid */
55 #define getpid _getpid
61 #include <sys/types.h>
65 # include <pwd.h> /* getpwnam() */
66 # include <grp.h> /* getgrnam() */
69 #include "node_buffer.h"
70 #include "node_file.h"
71 #include "node_http_parser.h"
72 #include "node_constants.h"
73 #include "node_javascript.h"
74 #include "node_version.h"
75 #include "node_string.h"
77 # include "node_crypto.h"
80 #include "node_systemtap.h"
82 #include "node_script.h"
83 #include "v8_typed_array.h"
88 # include <crt_externs.h>
89 # define environ (*_NSGetEnviron())
90 # elif !defined(_MSC_VER)
91 extern char **environ;
96 ngx_queue_t handle_wrap_queue = { &handle_wrap_queue, &handle_wrap_queue };
97 ngx_queue_t req_wrap_queue = { &req_wrap_queue, &req_wrap_queue };
99 // declared in req_wrap.h
100 Persistent<String> process_symbol;
101 Persistent<String> domain_symbol;
103 // declared in node_internals.h
104 Persistent<Object> process;
106 static Persistent<Function> process_tickFromSpinner;
107 static Persistent<Function> process_tickCallback;
109 static Persistent<String> exports_symbol;
111 static Persistent<String> errno_symbol;
112 static Persistent<String> syscall_symbol;
113 static Persistent<String> errpath_symbol;
114 static Persistent<String> code_symbol;
116 static Persistent<String> rss_symbol;
117 static Persistent<String> heap_total_symbol;
118 static Persistent<String> heap_used_symbol;
120 static Persistent<String> fatal_exception_symbol;
122 static Persistent<String> enter_symbol;
123 static Persistent<String> exit_symbol;
124 static Persistent<String> disposed_symbol;
127 static bool print_eval = false;
128 static bool force_repl = false;
129 static bool trace_deprecation = false;
130 static bool throw_deprecation = false;
131 static char *eval_string = NULL;
132 static int option_end_index = 0;
133 static bool use_debug_agent = false;
134 static bool debug_wait_connect = false;
135 static int debug_port=5858;
136 static int max_stack_size = 0;
137 static bool using_domains = false;
139 // used by C++ modules as well
140 bool no_deprecation = false;
142 static uv_idle_t tick_spinner;
143 static bool need_tick_cb;
144 static Persistent<String> tick_callback_sym;
146 static uv_check_t check_immediate_watcher;
147 static uv_idle_t idle_immediate_dummy;
148 static bool need_immediate_cb;
149 static Persistent<String> immediate_callback_sym;
151 // for quick ref to tickCallback values
158 #ifdef OPENSSL_NPN_NEGOTIATED
159 static bool use_npn = true;
161 static bool use_npn = false;
164 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
165 static bool use_sni = true;
167 static bool use_sni = false;
170 // process-relative uptime base, initialized at start-up
171 static double prog_start_time;
173 static volatile bool debugger_running = false;
174 static uv_async_t dispatch_debug_messages_async;
176 // Declared in node_internals.h
177 Isolate* node_isolate = NULL;
180 static void Spin(uv_idle_t* handle, int status) {
181 assert((uv_idle_t*) handle == &tick_spinner);
184 // Avoid entering a V8 scope.
185 if (!need_tick_cb) return;
186 need_tick_cb = false;
188 uv_idle_stop(&tick_spinner);
192 if (process_tickFromSpinner.IsEmpty()) {
193 Local<Value> cb_v = process->Get(String::New("_tickFromSpinner"));
194 if (!cb_v->IsFunction()) {
195 fprintf(stderr, "process._tickFromSpinner assigned to non-function\n");
198 Local<Function> cb = cb_v.As<Function>();
199 process_tickFromSpinner = Persistent<Function>::New(cb);
204 process_tickFromSpinner->Call(process, 0, NULL);
206 if (try_catch.HasCaught()) {
207 FatalException(try_catch);
212 static Handle<Value> NeedTickCallback(const Arguments& args) {
214 uv_idle_start(&tick_spinner, Spin);
219 static void CheckImmediate(uv_check_t* handle, int status) {
220 assert(handle == &check_immediate_watcher);
225 if (immediate_callback_sym.IsEmpty()) {
226 immediate_callback_sym = NODE_PSYMBOL("_immediateCallback");
229 MakeCallback(process, immediate_callback_sym, 0, NULL);
233 static void IdleImmediateDummy(uv_idle_t* handle, int status) {
234 // Do nothing. Only for maintaining event loop
235 assert(handle == &idle_immediate_dummy);
240 static inline const char *errno_string(int errorno) {
241 #define ERRNO_CASE(e) case e: return #e;
249 ERRNO_CASE(EADDRINUSE);
253 ERRNO_CASE(EADDRNOTAVAIL);
257 ERRNO_CASE(EAFNOSUPPORT);
265 # if EAGAIN != EWOULDBLOCK
266 ERRNO_CASE(EWOULDBLOCK);
271 ERRNO_CASE(EALREADY);
287 ERRNO_CASE(ECANCELED);
295 ERRNO_CASE(ECONNABORTED);
299 ERRNO_CASE(ECONNREFUSED);
303 ERRNO_CASE(ECONNRESET);
311 ERRNO_CASE(EDESTADDRREQ);
335 ERRNO_CASE(EHOSTUNREACH);
347 ERRNO_CASE(EINPROGRESS);
383 ERRNO_CASE(EMSGSIZE);
387 ERRNO_CASE(EMULTIHOP);
391 ERRNO_CASE(ENAMETOOLONG);
395 ERRNO_CASE(ENETDOWN);
399 ERRNO_CASE(ENETRESET);
403 ERRNO_CASE(ENETUNREACH);
435 # if ENOLINK != ENOLCK
449 ERRNO_CASE(ENOPROTOOPT);
469 ERRNO_CASE(ENOTCONN);
477 ERRNO_CASE(ENOTEMPTY);
481 ERRNO_CASE(ENOTSOCK);
488 ERRNO_CASE(EOPNOTSUPP);
502 ERRNO_CASE(EOVERFLOW);
517 #ifdef EPROTONOSUPPORT
518 ERRNO_CASE(EPROTONOSUPPORT);
522 ERRNO_CASE(EPROTOTYPE);
550 ERRNO_CASE(ETIMEDOUT);
565 const char *signo_string(int signo) {
566 #define SIGNO_CASE(e) case e: return #e;
594 # if SIGABRT != SIGIOT
638 SIGNO_CASE(SIGSTKFLT);
655 SIGNO_CASE(SIGBREAK);
679 SIGNO_CASE(SIGVTALRM);
687 SIGNO_CASE(SIGWINCH);
695 # if SIGPOLL != SIGIO
705 # if SIGPWR != SIGLOST
719 Local<Value> ErrnoException(int errorno,
724 Local<String> estring = String::NewSymbol(errno_string(errorno));
726 msg = strerror(errorno);
728 Local<String> message = String::NewSymbol(msg);
730 Local<String> cons1 = String::Concat(estring, String::NewSymbol(", "));
731 Local<String> cons2 = String::Concat(cons1, message);
733 if (syscall_symbol.IsEmpty()) {
734 syscall_symbol = NODE_PSYMBOL("syscall");
735 errno_symbol = NODE_PSYMBOL("errno");
736 errpath_symbol = NODE_PSYMBOL("path");
737 code_symbol = NODE_PSYMBOL("code");
741 Local<String> cons3 = String::Concat(cons2, String::NewSymbol(" '"));
742 Local<String> cons4 = String::Concat(cons3, String::New(path));
743 Local<String> cons5 = String::Concat(cons4, String::NewSymbol("'"));
744 e = Exception::Error(cons5);
746 e = Exception::Error(cons2);
749 Local<Object> obj = e->ToObject();
751 obj->Set(errno_symbol, Integer::New(errorno));
752 obj->Set(code_symbol, estring);
753 if (path) obj->Set(errpath_symbol, String::New(path));
754 if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
759 static const char* get_uv_errno_string(int errorno) {
761 memset(&err, 0, sizeof err);
762 err.code = (uv_err_code)errorno;
763 return uv_err_name(err);
767 static const char* get_uv_errno_message(int errorno) {
769 memset(&err, 0, sizeof err);
770 err.code = (uv_err_code)errorno;
771 return uv_strerror(err);
775 // hack alert! copy of ErrnoException, tuned for uv errors
776 Local<Value> UVException(int errorno,
780 if (syscall_symbol.IsEmpty()) {
781 syscall_symbol = NODE_PSYMBOL("syscall");
782 errno_symbol = NODE_PSYMBOL("errno");
783 errpath_symbol = NODE_PSYMBOL("path");
784 code_symbol = NODE_PSYMBOL("code");
788 msg = get_uv_errno_message(errorno);
790 Local<String> estring = String::NewSymbol(get_uv_errno_string(errorno));
791 Local<String> message = String::NewSymbol(msg);
792 Local<String> cons1 = String::Concat(estring, String::NewSymbol(", "));
793 Local<String> cons2 = String::Concat(cons1, message);
797 Local<String> path_str;
801 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
802 path_str = String::Concat(String::New("\\\\"), String::New(path + 8));
803 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
804 path_str = String::New(path + 4);
806 path_str = String::New(path);
809 path_str = String::New(path);
812 Local<String> cons3 = String::Concat(cons2, String::NewSymbol(" '"));
813 Local<String> cons4 = String::Concat(cons3, path_str);
814 Local<String> cons5 = String::Concat(cons4, String::NewSymbol("'"));
815 e = Exception::Error(cons5);
817 e = Exception::Error(cons2);
820 Local<Object> obj = e->ToObject();
822 // TODO errno should probably go
823 obj->Set(errno_symbol, Integer::New(errorno));
824 obj->Set(code_symbol, estring);
825 if (path) obj->Set(errpath_symbol, path_str);
826 if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
832 // Does about the same as strerror(),
833 // but supports all windows error messages
834 static const char *winapi_strerror(const int errorno) {
837 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
838 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
839 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
842 // Remove trailing newlines
843 for (int i = strlen(errmsg) - 1;
844 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
850 // FormatMessage failed
851 return "Unknown error";
856 Local<Value> WinapiErrnoException(int errorno,
861 if (!msg || !msg[0]) {
862 msg = winapi_strerror(errorno);
864 Local<String> message = String::NewSymbol(msg);
866 if (syscall_symbol.IsEmpty()) {
867 syscall_symbol = NODE_PSYMBOL("syscall");
868 errno_symbol = NODE_PSYMBOL("errno");
869 errpath_symbol = NODE_PSYMBOL("path");
870 code_symbol = NODE_PSYMBOL("code");
874 Local<String> cons1 = String::Concat(message, String::NewSymbol(" '"));
875 Local<String> cons2 = String::Concat(cons1, String::New(path));
876 Local<String> cons3 = String::Concat(cons2, String::NewSymbol("'"));
877 e = Exception::Error(cons3);
879 e = Exception::Error(message);
882 Local<Object> obj = e->ToObject();
884 obj->Set(errno_symbol, Integer::New(errorno));
885 if (path) obj->Set(errpath_symbol, String::New(path));
886 if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
892 Handle<Value> FromConstructorTemplate(Persistent<FunctionTemplate> t,
893 const Arguments& args) {
895 Local<Value> argv[32];
896 unsigned argc = args.Length();
897 if (argc > ARRAY_SIZE(argv)) argc = ARRAY_SIZE(argv);
898 for (unsigned i = 0; i < argc; ++i) argv[i] = args[i];
899 return scope.Close(t->GetFunction()->NewInstance(argc, argv));
903 Handle<Value> UsingDomains(const Arguments& args) {
906 return scope.Close(Undefined());
907 using_domains = true;
908 Local<Value> tdc_v = process->Get(String::New("_tickDomainCallback"));
909 Local<Value> ndt_v = process->Get(String::New("_nextDomainTick"));
910 if (!tdc_v->IsFunction()) {
911 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
914 if (!ndt_v->IsFunction()) {
915 fprintf(stderr, "process._nextDomainTick assigned to non-function\n");
918 Local<Function> tdc = tdc_v.As<Function>();
919 Local<Function> ndt = ndt_v.As<Function>();
920 process->Set(String::New("_tickCallback"), tdc);
921 process->Set(String::New("nextTick"), ndt);
922 process_tickCallback.Dispose(); // Possibly already set by MakeCallback().
923 process_tickCallback = Persistent<Function>::New(tdc);
929 MakeDomainCallback(const Handle<Object> object,
930 const Handle<Function> callback,
932 Handle<Value> argv[]) {
933 // TODO Hook for long stack traces to be made here.
935 // lazy load domain specific symbols
936 if (enter_symbol.IsEmpty()) {
937 enter_symbol = NODE_PSYMBOL("enter");
938 exit_symbol = NODE_PSYMBOL("exit");
939 disposed_symbol = NODE_PSYMBOL("_disposed");
942 Local<Value> domain_v = object->Get(domain_symbol);
943 Local<Object> domain;
944 Local<Function> enter;
945 Local<Function> exit;
949 bool has_domain = domain_v->IsObject();
951 domain = domain_v->ToObject();
952 assert(!domain.IsEmpty());
953 if (domain->Get(disposed_symbol)->IsTrue()) {
954 // domain has been disposed of.
957 enter = Local<Function>::Cast(domain->Get(enter_symbol));
958 assert(!enter.IsEmpty());
959 enter->Call(domain, 0, NULL);
961 if (try_catch.HasCaught()) {
962 FatalException(try_catch);
967 Local<Value> ret = callback->Call(object, argc, argv);
969 if (try_catch.HasCaught()) {
970 FatalException(try_catch);
975 exit = Local<Function>::Cast(domain->Get(exit_symbol));
976 assert(!exit.IsEmpty());
977 exit->Call(domain, 0, NULL);
979 if (try_catch.HasCaught()) {
980 FatalException(try_catch);
985 if (tick_infobox.length == 0) {
986 tick_infobox.index = 0;
987 tick_infobox.depth = 0;
991 // process nextTicks after call
992 process_tickCallback->Call(process, 0, NULL);
994 if (try_catch.HasCaught()) {
995 FatalException(try_catch);
1004 MakeCallback(const Handle<Object> object,
1005 const Handle<Function> callback,
1007 Handle<Value> argv[]) {
1008 // TODO Hook for long stack traces to be made here.
1011 return MakeDomainCallback(object, callback, argc, argv);
1013 // lazy load no domain next tick callbacks
1014 if (process_tickCallback.IsEmpty()) {
1015 Local<Value> cb_v = process->Get(String::New("_tickCallback"));
1016 if (!cb_v->IsFunction()) {
1017 fprintf(stderr, "process._tickCallback assigned to non-function\n");
1020 Local<Function> cb = cb_v.As<Function>();
1021 process_tickCallback = Persistent<Function>::New(cb);
1026 Local<Value> ret = callback->Call(object, argc, argv);
1028 if (try_catch.HasCaught()) {
1029 FatalException(try_catch);
1033 if (tick_infobox.length == 0) {
1034 tick_infobox.index = 0;
1035 tick_infobox.depth = 0;
1039 // process nextTicks after call
1040 process_tickCallback->Call(process, 0, NULL);
1042 if (try_catch.HasCaught()) {
1043 FatalException(try_catch);
1052 MakeCallback(const Handle<Object> object,
1053 const Handle<String> symbol,
1055 Handle<Value> argv[]) {
1058 Local<Function> callback = object->Get(symbol).As<Function>();
1061 return scope.Close(MakeDomainCallback(object, callback, argc, argv));
1062 return scope.Close(MakeCallback(object, callback, argc, argv));
1067 MakeCallback(const Handle<Object> object,
1070 Handle<Value> argv[]) {
1074 MakeCallback(object, String::NewSymbol(method), argc, argv);
1076 return scope.Close(ret);
1080 void SetErrno(uv_err_t err) {
1083 static Persistent<String> errno_symbol;
1084 if (errno_symbol.IsEmpty()) {
1085 errno_symbol = NODE_PSYMBOL("_errno");
1088 if (err.code == UV_UNKNOWN) {
1089 char errno_buf[100];
1090 snprintf(errno_buf, 100, "Unknown system errno %d", err.sys_errno_);
1091 process->Set(errno_symbol, String::New(errno_buf));
1093 process->Set(errno_symbol, String::NewSymbol(uv_err_name(err)));
1098 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1101 if (!encoding_v->IsString()) return _default;
1103 String::Utf8Value encoding(encoding_v);
1105 if (strcasecmp(*encoding, "utf8") == 0) {
1107 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1109 } else if (strcasecmp(*encoding, "ascii") == 0) {
1111 } else if (strcasecmp(*encoding, "base64") == 0) {
1113 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1115 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1117 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1119 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1121 } else if (strcasecmp(*encoding, "binary") == 0) {
1123 } else if (strcasecmp(*encoding, "buffer") == 0) {
1125 } else if (strcasecmp(*encoding, "hex") == 0) {
1127 } else if (strcasecmp(*encoding, "raw") == 0) {
1128 if (!no_deprecation) {
1129 fprintf(stderr, "'raw' (array of integers) has been removed. "
1133 } else if (strcasecmp(*encoding, "raws") == 0) {
1134 if (!no_deprecation) {
1135 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1136 "Please update your code.\n");
1144 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1145 return StringBytes::Encode(static_cast<const char*>(buf),
1150 // Returns -1 if the handle was not valid for decoding
1151 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1154 if (val->IsArray()) {
1155 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1161 return StringBytes::Size(val, encoding);
1165 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1168 // Returns number of bytes written.
1169 ssize_t DecodeWrite(char *buf,
1171 v8::Handle<v8::Value> val,
1172 enum encoding encoding) {
1175 if (val->IsArray()) {
1176 fprintf(stderr, "'raw' encoding (array of integers) has been removed.\n");
1181 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1184 void DisplayExceptionLine (TryCatch &try_catch) {
1185 // Prevent re-entry into this function. For example, if there is
1186 // a throw from a program in vm.runInThisContext(code, filename, true),
1187 // then we want to show the original failure, not the secondary one.
1188 static bool displayed_error = false;
1190 if (displayed_error) return;
1191 displayed_error = true;
1195 Handle<Message> message = try_catch.Message();
1197 uv_tty_reset_mode();
1199 fprintf(stderr, "\n");
1201 if (!message.IsEmpty()) {
1202 // Print (filename):(line number): (message).
1203 String::Utf8Value filename(message->GetScriptResourceName());
1204 const char* filename_string = *filename;
1205 int linenum = message->GetLineNumber();
1206 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1207 // Print line of source code.
1208 String::Utf8Value sourceline(message->GetSourceLine());
1209 const char* sourceline_string = *sourceline;
1211 // Because of how node modules work, all scripts are wrapped with a
1212 // "function (module, exports, __filename, ...) {"
1213 // to provide script local variables.
1215 // When reporting errors on the first line of a script, this wrapper
1216 // function is leaked to the user. There used to be a hack here to
1217 // truncate off the first 62 characters, but it caused numerous other
1218 // problems when vm.runIn*Context() methods were used for non-module
1221 // If we ever decide to re-instate such a hack, the following steps
1224 // 1. Pass a flag around to say "this code was wrapped"
1225 // 2. Update the stack frame output so that it is also correct.
1227 // It would probably be simpler to add a line rather than add some
1228 // number of characters to the first line, since V8 truncates the
1229 // sourceline to 78 characters, and we end up not providing very much
1230 // useful debugging info to the user if we remove 62 characters.
1232 int start = message->GetStartColumn();
1233 int end = message->GetEndColumn();
1235 // fprintf(stderr, "---\nsourceline:%s\noffset:%d\nstart:%d\nend:%d\n---\n", sourceline_string, start, end);
1237 fprintf(stderr, "%s\n", sourceline_string);
1238 // Print wavy underline (GetUnderline is deprecated).
1239 for (int i = 0; i < start; i++) {
1240 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1242 for (int i = start; i < end; i++) {
1245 fputc('\n', stderr);
1250 static void ReportException(TryCatch &try_catch, bool show_line) {
1253 if (show_line) DisplayExceptionLine(try_catch);
1255 String::Utf8Value trace(try_catch.StackTrace());
1257 // range errors have a trace member set to undefined
1258 if (trace.length() > 0 && !try_catch.StackTrace()->IsUndefined()) {
1259 fprintf(stderr, "%s\n", *trace);
1261 // this really only happens for RangeErrors, since they're the only
1262 // kind that won't have all this info in the trace, or when non-Error
1263 // objects are thrown manually.
1264 Local<Value> er = try_catch.Exception();
1265 bool isErrorObject = er->IsObject() &&
1266 !(er->ToObject()->Get(String::New("message"))->IsUndefined()) &&
1267 !(er->ToObject()->Get(String::New("name"))->IsUndefined());
1269 if (isErrorObject) {
1270 String::Utf8Value name(er->ToObject()->Get(String::New("name")));
1271 fprintf(stderr, "%s: ", *name);
1274 String::Utf8Value msg(!isErrorObject ? er
1275 : er->ToObject()->Get(String::New("message")));
1276 fprintf(stderr, "%s\n", *msg);
1282 // Executes a str within the current v8 context.
1283 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1287 Local<v8::Script> script = v8::Script::Compile(source, filename);
1288 if (script.IsEmpty()) {
1289 ReportException(try_catch, true);
1293 Local<Value> result = script->Run();
1294 if (result.IsEmpty()) {
1295 ReportException(try_catch, true);
1299 return scope.Close(result);
1303 static Handle<Value> GetActiveRequests(const Arguments& args) {
1306 Local<Array> ary = Array::New();
1307 ngx_queue_t* q = NULL;
1310 ngx_queue_foreach(q, &req_wrap_queue) {
1311 ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1312 if (w->object_.IsEmpty()) continue;
1313 ary->Set(i++, w->object_);
1316 return scope.Close(ary);
1320 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1321 // implemented here for consistency with GetActiveRequests().
1322 Handle<Value> GetActiveHandles(const Arguments& args) {
1325 Local<Array> ary = Array::New();
1326 ngx_queue_t* q = NULL;
1329 Local<String> owner_sym = String::New("owner");
1331 ngx_queue_foreach(q, &handle_wrap_queue) {
1332 HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1333 if (w->object_.IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue;
1334 Local<Value> obj = w->object_->Get(owner_sym);
1335 if (obj->IsUndefined()) obj = *w->object_;
1339 return scope.Close(ary);
1343 static Handle<Value> Abort(const Arguments& args) {
1349 static Handle<Value> Chdir(const Arguments& args) {
1352 if (args.Length() != 1 || !args[0]->IsString()) {
1353 return ThrowException(Exception::Error(String::New("Bad argument.")));
1356 String::Utf8Value path(args[0]);
1358 uv_err_t r = uv_chdir(*path);
1360 if (r.code != UV_OK) {
1361 return ThrowException(UVException(r.code, "uv_chdir"));
1368 static Handle<Value> Cwd(const Arguments& args) {
1371 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1372 char buf[MAX_PATH * 4 + 1];
1374 char buf[PATH_MAX + 1];
1377 uv_err_t r = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1378 if (r.code != UV_OK) {
1379 return ThrowException(UVException(r.code, "uv_cwd"));
1382 buf[ARRAY_SIZE(buf) - 1] = '\0';
1383 Local<String> cwd = String::New(buf);
1385 return scope.Close(cwd);
1389 static Handle<Value> Umask(const Arguments& args) {
1393 if (args.Length() < 1 || args[0]->IsUndefined()) {
1397 } else if(!args[0]->IsInt32() && !args[0]->IsString()) {
1398 return ThrowException(Exception::TypeError(
1399 String::New("argument must be an integer or octal string.")));
1403 if(args[0]->IsInt32()) {
1404 oct = args[0]->Uint32Value();
1407 String::Utf8Value str(args[0]);
1409 // Parse the octal string.
1410 for (int i = 0; i < str.length(); i++) {
1412 if (c > '7' || c < '0') {
1413 return ThrowException(Exception::TypeError(
1414 String::New("invalid octal string")));
1420 old = umask(static_cast<mode_t>(oct));
1423 return scope.Close(Uint32::New(old));
1429 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1430 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1433 static uid_t uid_by_name(const char* name) {
1441 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1445 return uid_not_found;
1449 static char* name_by_uid(uid_t uid) {
1458 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1459 return strdup(pp->pw_name);
1470 static gid_t gid_by_name(const char* name) {
1478 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1482 return gid_not_found;
1486 #if 0 // For future use.
1487 static const char* name_by_gid(gid_t gid) {
1496 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1497 return strdup(pp->gr_name);
1509 static uid_t uid_by_name(Handle<Value> value) {
1510 if (value->IsUint32()) {
1511 return static_cast<uid_t>(value->Uint32Value());
1513 String::Utf8Value name(value);
1514 return uid_by_name(*name);
1519 static gid_t gid_by_name(Handle<Value> value) {
1520 if (value->IsUint32()) {
1521 return static_cast<gid_t>(value->Uint32Value());
1523 String::Utf8Value name(value);
1524 return gid_by_name(*name);
1529 static Handle<Value> GetUid(const Arguments& args) {
1531 uid_t uid = getuid();
1532 return scope.Close(Integer::NewFromUnsigned(uid));
1536 static Handle<Value> GetGid(const Arguments& args) {
1538 gid_t gid = getgid();
1539 return scope.Close(Integer::NewFromUnsigned(gid));
1543 static Handle<Value> SetGid(const Arguments& args) {
1546 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1547 return ThrowTypeError("setgid argument must be a number or a string");
1550 gid_t gid = gid_by_name(args[0]);
1552 if (gid == gid_not_found) {
1553 return ThrowError("setgid group id does not exist");
1557 return ThrowException(ErrnoException(errno, "setgid"));
1564 static Handle<Value> SetUid(const Arguments& args) {
1567 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1568 return ThrowTypeError("setuid argument must be a number or a string");
1571 uid_t uid = uid_by_name(args[0]);
1573 if (uid == uid_not_found) {
1574 return ThrowError("setuid user id does not exist");
1578 return ThrowException(ErrnoException(errno, "setuid"));
1585 static Handle<Value> GetGroups(const Arguments& args) {
1588 int ngroups = getgroups(0, NULL);
1590 if (ngroups == -1) {
1591 return ThrowException(ErrnoException(errno, "getgroups"));
1594 gid_t* groups = new gid_t[ngroups];
1596 ngroups = getgroups(ngroups, groups);
1598 if (ngroups == -1) {
1600 return ThrowException(ErrnoException(errno, "getgroups"));
1603 Local<Array> groups_list = Array::New(ngroups);
1604 bool seen_egid = false;
1605 gid_t egid = getegid();
1607 for (int i = 0; i < ngroups; i++) {
1608 groups_list->Set(i, Integer::New(groups[i]));
1609 if (groups[i] == egid) seen_egid = true;
1614 if (seen_egid == false) {
1615 groups_list->Set(ngroups, Integer::New(egid));
1618 return scope.Close(groups_list);
1622 static Handle<Value> SetGroups(const Arguments& args) {
1625 if (!args[0]->IsArray()) {
1626 return ThrowTypeError("argument 1 must be an array");
1629 Local<Array> groups_list = args[0].As<Array>();
1630 size_t size = groups_list->Length();
1631 gid_t* groups = new gid_t[size];
1633 for (size_t i = 0; i < size; i++) {
1634 gid_t gid = gid_by_name(groups_list->Get(i));
1636 if (gid == gid_not_found) {
1638 return ThrowError("group name not found");
1644 int rc = setgroups(size, groups);
1648 return ThrowException(ErrnoException(errno, "setgroups"));
1655 static Handle<Value> InitGroups(const Arguments& args) {
1658 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1659 return ThrowTypeError("argument 1 must be a number or a string");
1662 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1663 return ThrowTypeError("argument 2 must be a number or a string");
1666 String::Utf8Value arg0(args[0]);
1671 if (args[0]->IsUint32()) {
1672 user = name_by_uid(args[0]->Uint32Value());
1680 return ThrowError("initgroups user not found");
1683 extra_group = gid_by_name(args[1]);
1685 if (extra_group == gid_not_found) {
1686 if (must_free) free(user);
1687 return ThrowError("initgroups extra group not found");
1690 int rc = initgroups(user, extra_group);
1697 return ThrowException(ErrnoException(errno, "initgroups"));
1706 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
1708 exit(args[0]->IntegerValue());
1713 static Handle<Value> Uptime(const Arguments& args) {
1717 uv_err_t err = uv_uptime(&uptime);
1719 if (err.code != UV_OK) {
1723 return scope.Close(Number::New(uptime - prog_start_time));
1727 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
1732 uv_err_t err = uv_resident_set_memory(&rss);
1734 if (err.code != UV_OK) {
1735 return ThrowException(UVException(err.code, "uv_resident_set_memory"));
1738 Local<Object> info = Object::New();
1740 if (rss_symbol.IsEmpty()) {
1741 rss_symbol = NODE_PSYMBOL("rss");
1742 heap_total_symbol = NODE_PSYMBOL("heapTotal");
1743 heap_used_symbol = NODE_PSYMBOL("heapUsed");
1746 info->Set(rss_symbol, Number::New(rss));
1749 HeapStatistics v8_heap_stats;
1750 V8::GetHeapStatistics(&v8_heap_stats);
1751 info->Set(heap_total_symbol,
1752 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
1753 info->Set(heap_used_symbol,
1754 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
1756 return scope.Close(info);
1760 Handle<Value> Kill(const Arguments& args) {
1763 if (args.Length() != 2) {
1764 return ThrowException(Exception::Error(String::New("Bad argument.")));
1767 int pid = args[0]->IntegerValue();
1768 int sig = args[1]->Int32Value();
1769 uv_err_t err = uv_kill(pid, sig);
1771 if (err.code != UV_OK) {
1773 return scope.Close(Integer::New(-1));
1779 // used in Hrtime() below
1780 #define NANOS_PER_SEC 1000000000
1782 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1783 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1784 // so this function instead returns an Array with 2 entries representing seconds
1785 // and nanoseconds, to avoid any integer overflow possibility.
1786 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1787 Handle<Value> Hrtime(const v8::Arguments& args) {
1790 uint64_t t = uv_hrtime();
1792 if (args.Length() > 0) {
1793 // return a time diff tuple
1794 if (!args[0]->IsArray()) {
1795 Local<Value> exception = Exception::TypeError(
1796 String::New("process.hrtime() only accepts an Array tuple."));
1797 return ThrowException(exception);
1799 Local<Array> inArray = Local<Array>::Cast(args[0]);
1800 uint64_t seconds = inArray->Get(0)->Uint32Value();
1801 uint64_t nanos = inArray->Get(1)->Uint32Value();
1802 t -= (seconds * NANOS_PER_SEC) + nanos;
1805 Local<Array> tuple = Array::New(2);
1806 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC));
1807 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC));
1809 return scope.Close(tuple);
1813 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1815 // DLOpen is process.dlopen(module, filename).
1816 // Used to load 'module.node' dynamically shared objects.
1817 Handle<Value> DLOpen(const v8::Arguments& args) {
1819 char symbol[1024], *base, *pos;
1823 if (args.Length() < 2) {
1824 Local<Value> exception = Exception::Error(
1825 String::New("process.dlopen takes exactly 2 arguments."));
1826 return ThrowException(exception);
1829 Local<Object> module = args[0]->ToObject(); // Cast
1830 String::Utf8Value filename(args[1]); // Cast
1832 if (exports_symbol.IsEmpty()) {
1833 exports_symbol = NODE_PSYMBOL("exports");
1835 Local<Object> exports = module->Get(exports_symbol)->ToObject();
1837 if (uv_dlopen(*filename, &lib)) {
1838 Local<String> errmsg = String::New(uv_dlerror(&lib));
1840 // Windows needs to add the filename into the error message
1841 errmsg = String::Concat(errmsg, args[1]->ToString());
1843 return ThrowException(Exception::Error(errmsg));
1846 String::Utf8Value path(args[1]);
1849 /* Find the shared library filename within the full path. */
1851 pos = strrchr(base, '/');
1857 pos = strpbrk(base, "\\/:");
1865 /* Strip the .node extension. */
1866 pos = strrchr(base, '.');
1871 /* Add the `_module` suffix to the extension name. */
1872 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1873 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1874 Local<Value> exception =
1875 Exception::Error(String::New("Out of memory."));
1876 return ThrowException(exception);
1879 /* Replace dashes with underscores. When loading foo-bar.node,
1880 * look for foo_bar_module, not foo-bar_module.
1882 for (pos = symbol; *pos != '\0'; ++pos) {
1883 if (*pos == '-') *pos = '_';
1886 node_module_struct *mod;
1887 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1889 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1890 return ThrowError(errmsg);
1893 if (mod->version != NODE_MODULE_VERSION) {
1897 "Module version mismatch. Expected %d, got %d.",
1898 NODE_MODULE_VERSION, mod->version);
1899 return ThrowError(errmsg);
1902 // Execute the C++ module
1903 mod->register_func(exports, module);
1905 // Tell coverity that 'handle' should not be freed when we return.
1906 // coverity[leaked_storage]
1911 static void OnFatalError(const char* location, const char* message) {
1913 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1915 fprintf(stderr, "FATAL ERROR: %s\n", message);
1920 void FatalException(TryCatch &try_catch) {
1923 if (fatal_exception_symbol.IsEmpty())
1924 fatal_exception_symbol = NODE_PSYMBOL("_fatalException");
1926 Local<Value> fatal_v = process->Get(fatal_exception_symbol);
1928 if (!fatal_v->IsFunction()) {
1929 // failed before the process._fatalException function was added!
1930 // this is probably pretty bad. Nothing to do but report and exit.
1931 ReportException(try_catch, true);
1935 Local<Function> fatal_f = Local<Function>::Cast(fatal_v);
1937 Local<Value> error = try_catch.Exception();
1938 Local<Value> argv[] = { error };
1940 TryCatch fatal_try_catch;
1942 // this will return true if the JS layer handled it, false otherwise
1943 Local<Value> caught = fatal_f->Call(process, ARRAY_SIZE(argv), argv);
1945 if (fatal_try_catch.HasCaught()) {
1946 // the fatal exception function threw, so we must exit
1947 ReportException(fatal_try_catch, true);
1951 if (false == caught->BooleanValue()) {
1952 ReportException(try_catch, true);
1958 Persistent<Object> binding_cache;
1959 Persistent<Array> module_load_list;
1961 static Handle<Value> Binding(const Arguments& args) {
1964 Local<String> module = args[0]->ToString();
1965 String::Utf8Value module_v(module);
1966 node_module_struct* modp;
1968 if (binding_cache.IsEmpty()) {
1969 binding_cache = Persistent<Object>::New(Object::New());
1972 Local<Object> exports;
1974 if (binding_cache->Has(module)) {
1975 exports = binding_cache->Get(module)->ToObject();
1976 return scope.Close(exports);
1979 // Append a string to process.moduleLoadList
1981 snprintf(buf, 1024, "Binding %s", *module_v);
1982 uint32_t l = module_load_list->Length();
1983 module_load_list->Set(l, String::New(buf));
1985 if ((modp = get_builtin_module(*module_v)) != NULL) {
1986 exports = Object::New();
1987 // Internal bindings don't have a "module" object,
1989 modp->register_func(exports, Undefined());
1990 binding_cache->Set(module, exports);
1992 } else if (!strcmp(*module_v, "constants")) {
1993 exports = Object::New();
1994 DefineConstants(exports);
1995 binding_cache->Set(module, exports);
1997 } else if (!strcmp(*module_v, "natives")) {
1998 exports = Object::New();
1999 DefineJavaScript(exports);
2000 binding_cache->Set(module, exports);
2004 return ThrowException(Exception::Error(String::New("No such module")));
2007 return scope.Close(exports);
2011 static Handle<Value> ProcessTitleGetter(Local<String> property,
2012 const AccessorInfo& info) {
2015 uv_get_process_title(buffer, sizeof(buffer));
2016 return scope.Close(String::New(buffer));
2020 static void ProcessTitleSetter(Local<String> property,
2022 const AccessorInfo& info) {
2024 String::Utf8Value title(value);
2025 // TODO: protect with a lock
2026 uv_set_process_title(*title);
2030 static Handle<Value> EnvGetter(Local<String> property,
2031 const AccessorInfo& info) {
2034 String::Utf8Value key(property);
2035 const char* val = getenv(*key);
2037 return scope.Close(String::New(val));
2040 String::Value key(property);
2041 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2042 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2044 ARRAY_SIZE(buffer));
2045 // If result >= sizeof buffer the buffer was too small. That should never
2046 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2048 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2049 result < ARRAY_SIZE(buffer)) {
2050 return scope.Close(String::New(reinterpret_cast<uint16_t*>(buffer), result));
2053 // Not found. Fetch from prototype.
2054 return scope.Close(info.Data().As<Object>()->Get(property));
2058 static Handle<Value> EnvSetter(Local<String> property,
2060 const AccessorInfo& info) {
2063 String::Utf8Value key(property);
2064 String::Utf8Value val(value);
2065 setenv(*key, *val, 1);
2067 String::Value key(property);
2068 String::Value val(value);
2069 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2070 // Environment variables that start with '=' are read-only.
2071 if (key_ptr[0] != L'=') {
2072 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2075 // Whether it worked or not, always return rval.
2076 return scope.Close(value);
2080 static Handle<Integer> EnvQuery(Local<String> property,
2081 const AccessorInfo& info) {
2084 String::Utf8Value key(property);
2086 return scope.Close(Integer::New(0));
2089 String::Value key(property);
2090 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2091 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2092 GetLastError() == ERROR_SUCCESS) {
2093 if (key_ptr[0] == L'=') {
2094 // Environment variables that start with '=' are hidden and read-only.
2095 return scope.Close(Integer::New(v8::ReadOnly ||
2099 return scope.Close(Integer::New(0));
2104 return scope.Close(Handle<Integer>());
2108 static Handle<Boolean> EnvDeleter(Local<String> property,
2109 const AccessorInfo& info) {
2112 String::Utf8Value key(property);
2113 if (!getenv(*key)) return False();
2114 unsetenv(*key); // can't check return value, it's void on some platforms
2117 String::Value key(property);
2118 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2119 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2120 // Deletion failed. Return true if the key wasn't there in the first place,
2121 // false if it is still there.
2122 bool rv = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2123 GetLastError() != ERROR_SUCCESS;
2124 return scope.Close(Boolean::New(rv));
2131 static Handle<Array> EnvEnumerator(const AccessorInfo& info) {
2135 while (environ[size]) size++;
2137 Local<Array> env = Array::New(size);
2139 for (int i = 0; i < size; ++i) {
2140 const char* var = environ[i];
2141 const char* s = strchr(var, '=');
2142 const int length = s ? s - var : strlen(var);
2143 env->Set(i, String::New(var, length));
2146 WCHAR* environment = GetEnvironmentStringsW();
2147 if (environment == NULL) {
2148 // This should not happen.
2149 return scope.Close(Handle<Array>());
2151 Local<Array> env = Array::New();
2152 WCHAR* p = environment;
2154 while (*p != NULL) {
2157 // If the key starts with '=' it is a hidden environment variable.
2161 s = wcschr(p, L'=');
2166 env->Set(i++, String::New(reinterpret_cast<uint16_t*>(p), s - p));
2167 p = s + wcslen(s) + 1;
2169 FreeEnvironmentStringsW(environment);
2171 return scope.Close(env);
2175 static Handle<Object> GetFeatures() {
2178 Local<Object> obj = Object::New();
2179 obj->Set(String::NewSymbol("debug"),
2180 #if defined(DEBUG) && DEBUG
2187 obj->Set(String::NewSymbol("uv"), True());
2188 obj->Set(String::NewSymbol("ipv6"), True()); // TODO ping libuv
2189 obj->Set(String::NewSymbol("tls_npn"), Boolean::New(use_npn));
2190 obj->Set(String::NewSymbol("tls_sni"), Boolean::New(use_sni));
2191 obj->Set(String::NewSymbol("tls"),
2192 Boolean::New(get_builtin_module("crypto") != NULL));
2194 return scope.Close(obj);
2198 static Handle<Value> DebugPortGetter(Local<String> property,
2199 const AccessorInfo& info) {
2201 return scope.Close(Integer::NewFromUnsigned(debug_port));
2205 static void DebugPortSetter(Local<String> property,
2207 const AccessorInfo& info) {
2209 debug_port = value->NumberValue();
2213 static Handle<Value> DebugProcess(const Arguments& args);
2214 static Handle<Value> DebugPause(const Arguments& args);
2215 static Handle<Value> DebugEnd(const Arguments& args);
2218 Handle<Value> NeedImmediateCallbackGetter(Local<String> property,
2219 const AccessorInfo& info) {
2220 return Boolean::New(need_immediate_cb);
2224 static void NeedImmediateCallbackSetter(Local<String> property,
2226 const AccessorInfo& info) {
2229 bool bool_value = value->BooleanValue();
2231 if (need_immediate_cb == bool_value) return;
2233 need_immediate_cb = bool_value;
2235 if (need_immediate_cb) {
2236 uv_check_start(&check_immediate_watcher, node::CheckImmediate);
2237 // idle handle is needed only to maintain event loop
2238 uv_idle_start(&idle_immediate_dummy, node::IdleImmediateDummy);
2240 uv_check_stop(&check_immediate_watcher);
2241 uv_idle_stop(&idle_immediate_dummy);
2246 Handle<Object> SetupProcessObject(int argc, char *argv[]) {
2251 Local<FunctionTemplate> process_template = FunctionTemplate::New();
2253 process_template->SetClassName(String::NewSymbol("process"));
2255 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
2257 process->SetAccessor(String::New("title"),
2259 ProcessTitleSetter);
2262 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
2264 // process.moduleLoadList
2265 module_load_list = Persistent<Array>::New(Array::New());
2266 process->Set(String::NewSymbol("moduleLoadList"), module_load_list);
2269 Local<Object> versions = Object::New();
2270 process->Set(String::NewSymbol("versions"), versions);
2271 versions->Set(String::NewSymbol("http_parser"), String::New(
2272 NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR) "."
2273 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR)));
2274 // +1 to get rid of the leading 'v'
2275 versions->Set(String::NewSymbol("node"), String::New(NODE_VERSION+1));
2276 versions->Set(String::NewSymbol("v8"), String::New(V8::GetVersion()));
2277 versions->Set(String::NewSymbol("ares"), String::New(ARES_VERSION_STR));
2278 versions->Set(String::NewSymbol("uv"), String::New(uv_version_string()));
2279 versions->Set(String::NewSymbol("zlib"), String::New(ZLIB_VERSION));
2280 versions->Set(String::NewSymbol("modules"),
2281 String::New(NODE_STRINGIFY(NODE_MODULE_VERSION)));
2283 // Stupid code to slice out the version string.
2284 int c, l = strlen(OPENSSL_VERSION_TEXT);
2285 for (i = j = 0; i < l; i++) {
2286 c = OPENSSL_VERSION_TEXT[i];
2287 if ('0' <= c && c <= '9') {
2288 for (j = i + 1; j < l; j++) {
2289 c = OPENSSL_VERSION_TEXT[j];
2290 if (c == ' ') break;
2295 versions->Set(String::NewSymbol("openssl"),
2296 String::New(OPENSSL_VERSION_TEXT + i, j - i));
2302 process->Set(String::NewSymbol("arch"), String::New(ARCH));
2305 process->Set(String::NewSymbol("platform"), String::New(PLATFORM));
2308 Local<Array> arguments = Array::New(argc - option_end_index + 1);
2309 arguments->Set(Integer::New(0), String::New(argv[0]));
2310 for (j = 1, i = option_end_index; i < argc; j++, i++) {
2311 Local<String> arg = String::New(argv[i]);
2312 arguments->Set(Integer::New(j), arg);
2315 process->Set(String::NewSymbol("argv"), arguments);
2318 Local<Array> execArgv = Array::New(option_end_index - 1);
2319 for (j = 1, i = 0; j < option_end_index; j++, i++) {
2320 execArgv->Set(Integer::New(i), String::New(argv[j]));
2323 process->Set(String::NewSymbol("execArgv"), execArgv);
2326 // create process.env
2327 Local<ObjectTemplate> envTemplate = ObjectTemplate::New();
2328 envTemplate->SetNamedPropertyHandler(EnvGetter,
2334 Local<Object> env = envTemplate->NewInstance();
2335 process->Set(String::NewSymbol("env"), env);
2337 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
2338 process->Set(String::NewSymbol("features"), GetFeatures());
2339 process->SetAccessor(String::New("_needImmediateCallback"),
2340 NeedImmediateCallbackGetter,
2341 NeedImmediateCallbackSetter);
2345 process->Set(String::NewSymbol("_eval"), String::New(eval_string));
2350 process->Set(String::NewSymbol("_print_eval"), True());
2353 // -i, --interactive
2355 process->Set(String::NewSymbol("_forceRepl"), True());
2359 if (no_deprecation) {
2360 process->Set(String::NewSymbol("noDeprecation"), True());
2363 // --throw-deprecation
2364 if (throw_deprecation) {
2365 process->Set(String::NewSymbol("throwDeprecation"), True());
2368 // --trace-deprecation
2369 if (trace_deprecation) {
2370 process->Set(String::NewSymbol("traceDeprecation"), True());
2373 size_t size = 2*PATH_MAX;
2374 char* execPath = new char[size];
2375 if (uv_exepath(execPath, &size) != 0) {
2376 // as a last ditch effort, fallback on argv[0] ?
2377 process->Set(String::NewSymbol("execPath"), String::New(argv[0]));
2379 process->Set(String::NewSymbol("execPath"), String::New(execPath, size));
2383 process->SetAccessor(String::New("debugPort"),
2388 // define various internal methods
2389 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2390 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2391 NODE_SET_METHOD(process, "_needTickCallback", NeedTickCallback);
2392 NODE_SET_METHOD(process, "reallyExit", Exit);
2393 NODE_SET_METHOD(process, "abort", Abort);
2394 NODE_SET_METHOD(process, "chdir", Chdir);
2395 NODE_SET_METHOD(process, "cwd", Cwd);
2397 NODE_SET_METHOD(process, "umask", Umask);
2400 NODE_SET_METHOD(process, "getuid", GetUid);
2401 NODE_SET_METHOD(process, "setuid", SetUid);
2403 NODE_SET_METHOD(process, "setgid", SetGid);
2404 NODE_SET_METHOD(process, "getgid", GetGid);
2406 NODE_SET_METHOD(process, "getgroups", GetGroups);
2407 NODE_SET_METHOD(process, "setgroups", SetGroups);
2408 NODE_SET_METHOD(process, "initgroups", InitGroups);
2411 NODE_SET_METHOD(process, "_kill", Kill);
2413 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2414 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2415 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2417 NODE_SET_METHOD(process, "hrtime", Hrtime);
2419 NODE_SET_METHOD(process, "dlopen", DLOpen);
2421 NODE_SET_METHOD(process, "uptime", Uptime);
2422 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2424 NODE_SET_METHOD(process, "binding", Binding);
2426 NODE_SET_METHOD(process, "_usingDomains", UsingDomains);
2428 // values use to cross communicate with processNextTick
2429 Local<Object> info_box = Object::New();
2430 info_box->SetIndexedPropertiesToExternalArrayData(&tick_infobox,
2431 kExternalUnsignedIntArray,
2433 process->Set(String::NewSymbol("_tickInfoBox"), info_box);
2435 // pre-set _events object for faster emit checks
2436 process->Set(String::NewSymbol("_events"), Object::New());
2442 static void AtExit() {
2443 uv_tty_reset_mode();
2447 static void SignalExit(int signal) {
2448 uv_tty_reset_mode();
2449 _exit(128 + signal);
2453 void Load(Handle<Object> process_l) {
2454 process_symbol = NODE_PSYMBOL("process");
2455 domain_symbol = NODE_PSYMBOL("domain");
2457 // Compile, execute the src/node.js file. (Which was included as static C
2458 // string in node_natives.h. 'natve_node' is the string containing that
2461 // The node.js file returns a function 'f'
2466 Local<Value> f_value = ExecuteString(MainSource(),
2467 IMMUTABLE_STRING("node.js"));
2468 if (try_catch.HasCaught()) {
2469 ReportException(try_catch, true);
2472 assert(f_value->IsFunction());
2473 Local<Function> f = Local<Function>::Cast(f_value);
2475 // Now we call 'f' with the 'process' variable that we've built up with
2476 // all our bindings. Inside node.js we'll take care of assigning things to
2479 // We start the process this way in order to be more modular. Developers
2480 // who do not like how 'src/node.js' setups the module system but do like
2481 // Node's I/O bindings may want to replace 'f' with their own function.
2483 // Add a reference to the global object
2484 Local<Object> global = v8::Context::GetCurrent()->Global();
2485 Local<Value> args[1] = { Local<Value>::New(process_l) };
2487 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2491 #if defined HAVE_PERFCTR
2492 InitPerfCounters(global);
2495 f->Call(global, 1, args);
2497 if (try_catch.HasCaught()) {
2498 FatalException(try_catch);
2502 static void PrintHelp();
2504 static void ParseDebugOpt(const char* arg) {
2507 use_debug_agent = true;
2508 if (!strcmp (arg, "--debug-brk")) {
2509 debug_wait_connect = true;
2511 } else if (!strcmp(arg, "--debug")) {
2513 } else if (strstr(arg, "--debug-brk=") == arg) {
2514 debug_wait_connect = true;
2515 p = 1 + strchr(arg, '=');
2516 debug_port = atoi(p);
2517 } else if (strstr(arg, "--debug=") == arg) {
2518 p = 1 + strchr(arg, '=');
2519 debug_port = atoi(p);
2521 if (p && debug_port > 1024 && debug_port < 65536)
2524 fprintf(stderr, "Bad debug option.\n");
2525 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2531 static void PrintHelp() {
2532 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2533 " node debug script.js [arguments] \n"
2536 " -v, --version print node's version\n"
2537 " -e, --eval script evaluate script\n"
2538 " -p, --print evaluate script and print result\n"
2539 " -i, --interactive always enter the REPL even if stdin\n"
2540 " does not appear to be a terminal\n"
2541 " --no-deprecation silence deprecation warnings\n"
2542 " --trace-deprecation show stack traces on deprecations\n"
2543 " --v8-options print v8 command line options\n"
2544 " --max-stack-size=val set max v8 stack size (bytes)\n"
2546 "Environment variables:\n"
2548 "NODE_PATH ';'-separated list of directories\n"
2550 "NODE_PATH ':'-separated list of directories\n"
2552 " prefixed to the module search path.\n"
2553 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2554 " global contexts.\n"
2555 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2557 "Documentation can be found at http://nodejs.org/\n");
2560 // Parse node command line arguments.
2561 static void ParseArgs(int argc, char **argv) {
2564 // TODO use parse opts
2565 for (i = 1; i < argc; i++) {
2566 const char *arg = argv[i];
2567 if (strstr(arg, "--debug") == arg) {
2569 argv[i] = const_cast<char*>("");
2570 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2571 printf("%s\n", NODE_VERSION);
2573 } else if (strstr(arg, "--max-stack-size=") == arg) {
2575 p = 1 + strchr(arg, '=');
2576 max_stack_size = atoi(p);
2577 argv[i] = const_cast<char*>("");
2578 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2581 } else if (strcmp(arg, "--eval") == 0 ||
2582 strcmp(arg, "-e") == 0 ||
2583 strcmp(arg, "--print") == 0 ||
2584 strcmp(arg, "-pe") == 0 ||
2585 strcmp(arg, "-p") == 0) {
2586 bool is_eval = strchr(arg, 'e') != NULL;
2587 bool is_print = strchr(arg, 'p') != NULL;
2589 // argument to -p and --print is optional
2590 if (is_eval == true && i + 1 >= argc) {
2591 fprintf(stderr, "Error: %s requires an argument\n", arg);
2595 print_eval = print_eval || is_print;
2596 argv[i] = const_cast<char*>("");
2598 // --eval, -e and -pe always require an argument
2599 if (is_eval == true) {
2600 eval_string = argv[++i];
2604 // next arg is the expression to evaluate unless it starts with:
2605 // - a dash, then it's another switch
2606 // - "\\-", then it's an escaped expression, drop the backslash
2607 if (argv[i + 1] == NULL) continue;
2608 if (argv[i + 1][0] == '-') continue;
2609 eval_string = argv[++i];
2610 if (strncmp(eval_string, "\\-", 2) == 0) ++eval_string;
2611 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2613 argv[i] = const_cast<char*>("");
2614 } else if (strcmp(arg, "--v8-options") == 0) {
2615 argv[i] = const_cast<char*>("--help");
2616 } else if (strcmp(arg, "--no-deprecation") == 0) {
2617 argv[i] = const_cast<char*>("");
2618 no_deprecation = true;
2619 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2620 argv[i] = const_cast<char*>("");
2621 trace_deprecation = true;
2622 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2623 argv[i] = const_cast<char*>("");
2624 throw_deprecation = true;
2625 } else if (argv[i][0] != '-') {
2630 option_end_index = i;
2634 // Called from the main thread.
2635 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2636 v8::Debug::ProcessDebugMessages();
2640 // Called from V8 Debug Agent TCP thread.
2641 static void DispatchMessagesDebugAgentCallback() {
2642 uv_async_send(&dispatch_debug_messages_async);
2646 static void EnableDebug(bool wait_connect) {
2647 // If we're called from another thread, make sure to enter the right
2649 node_isolate->Enter();
2651 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2654 uv_async_init(uv_default_loop(),
2655 &dispatch_debug_messages_async,
2656 DispatchDebugMessagesAsyncCallback);
2657 uv_unref((uv_handle_t*) &dispatch_debug_messages_async);
2659 // Start the debug thread and it's associated TCP server on port 5858.
2660 bool r = v8::Debug::EnableAgent("node " NODE_VERSION,
2664 // Crappy check that everything went well. FIXME
2667 // Print out some information.
2668 fprintf(stderr, "debugger listening on port %d\n", debug_port);
2671 debugger_running = true;
2673 node_isolate->Exit();
2678 static void EnableDebugSignalHandler(uv_signal_t* handle, int) {
2679 // Break once process will return execution to v8
2680 v8::Debug::DebugBreak(node_isolate);
2682 if (!debugger_running) {
2683 fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n");
2689 static void RegisterSignalHandler(int signal, void (*handler)(int)) {
2690 struct sigaction sa;
2692 memset(&sa, 0, sizeof(sa));
2693 sa.sa_handler = handler;
2694 sigfillset(&sa.sa_mask);
2695 sigaction(signal, &sa, NULL);
2699 Handle<Value> DebugProcess(const Arguments& args) {
2702 if (args.Length() != 1) {
2703 return ThrowException(Exception::Error(
2704 String::New("Invalid number of arguments.")));
2710 pid = args[0]->IntegerValue();
2711 r = kill(pid, SIGUSR1);
2713 return ThrowException(ErrnoException(errno, "kill"));
2722 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2723 // Break once process will return execution to v8
2724 if (!debugger_running) {
2725 for (int i = 0; i < 1; i++) {
2726 fprintf(stderr, "Starting debugger agent.\r\n");
2732 v8::Debug::DebugBreak();
2738 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2740 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2744 static int RegisterDebugSignalHandler() {
2745 wchar_t mapping_name[32];
2746 HANDLE mapping_handle;
2748 LPTHREAD_START_ROUTINE* handler;
2750 pid = GetCurrentProcessId();
2752 if (GetDebugSignalHandlerMappingName(pid,
2754 ARRAY_SIZE(mapping_name)) < 0) {
2758 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2764 if (mapping_handle == NULL) {
2768 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2769 MapViewOfFile(mapping_handle,
2770 FILE_MAP_ALL_ACCESS,
2774 if (handler == NULL) {
2775 CloseHandle(mapping_handle);
2779 *handler = EnableDebugThreadProc;
2781 UnmapViewOfFile((void*) handler);
2787 static Handle<Value> DebugProcess(const Arguments& args) {
2789 Handle<Value> rv = Undefined();
2791 HANDLE process = NULL;
2792 HANDLE thread = NULL;
2793 HANDLE mapping = NULL;
2794 wchar_t mapping_name[32];
2795 LPTHREAD_START_ROUTINE* handler = NULL;
2797 if (args.Length() != 1) {
2798 rv = ThrowException(Exception::Error(String::New("Invalid number of arguments.")));
2802 pid = (DWORD) args[0]->IntegerValue();
2804 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2805 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2809 if (process == NULL) {
2810 rv = ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2814 if (GetDebugSignalHandlerMappingName(pid,
2816 ARRAY_SIZE(mapping_name)) < 0) {
2817 rv = ThrowException(ErrnoException(errno, "sprintf"));
2821 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2822 if (mapping == NULL) {
2823 rv = ThrowException(WinapiErrnoException(GetLastError(),
2824 "OpenFileMappingW"));
2828 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2829 MapViewOfFile(mapping,
2834 if (handler == NULL || *handler == NULL) {
2835 rv = ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
2839 thread = CreateRemoteThread(process,
2846 if (thread == NULL) {
2847 rv = ThrowException(WinapiErrnoException(GetLastError(),
2848 "CreateRemoteThread"));
2852 // Wait for the thread to terminate
2853 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
2854 rv = ThrowException(WinapiErrnoException(GetLastError(),
2855 "WaitForSingleObject"));
2860 if (process != NULL) {
2861 CloseHandle(process);
2863 if (thread != NULL) {
2864 CloseHandle(thread);
2866 if (handler != NULL) {
2867 UnmapViewOfFile(handler);
2869 if (mapping != NULL) {
2870 CloseHandle(mapping);
2878 static Handle<Value> DebugPause(const Arguments& args) {
2879 v8::Debug::DebugBreak(node_isolate);
2884 static Handle<Value> DebugEnd(const Arguments& args) {
2885 if (debugger_running) {
2886 v8::Debug::DisableAgent();
2887 debugger_running = false;
2894 char** Init(int argc, char *argv[]) {
2895 // Initialize prog_start_time to get relative uptime.
2896 uv_uptime(&prog_start_time);
2898 // Make inherited handles noninheritable.
2899 uv_disable_stdio_inheritance();
2901 // Parse a few arguments which are specific to Node.
2902 node::ParseArgs(argc, argv);
2903 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
2904 // in the command line))
2905 int v8argc = option_end_index;
2906 char **v8argv = argv;
2908 if (debug_wait_connect) {
2909 // v8argv is a copy of argv up to the script file argument +2 if --debug-brk
2910 // to expose the v8 debugger js object so that node.js can set
2911 // a breakpoint on the first line of the startup script
2913 v8argv = new char*[v8argc];
2914 memcpy(v8argv, argv, sizeof(*argv) * option_end_index);
2915 v8argv[option_end_index] = const_cast<char*>("--expose_debug_as");
2916 v8argv[option_end_index + 1] = const_cast<char*>("v8debug");
2919 // For the normal stack which moves from high to low addresses when frames
2920 // are pushed, we can compute the limit as stack_size bytes below the
2921 // the address of a stack variable (e.g. &stack_var) as an approximation
2922 // of the start of the stack (we're assuming that we haven't pushed a lot
2924 if (max_stack_size != 0) {
2926 ResourceConstraints constraints;
2928 uint32_t *stack_limit = &stack_var - (max_stack_size / sizeof(uint32_t));
2929 constraints.set_stack_limit(stack_limit);
2930 SetResourceConstraints(&constraints); // Must be done before V8::Initialize
2932 V8::SetFlagsFromCommandLine(&v8argc, v8argv, false);
2936 RegisterSignalHandler(SIGPIPE, SIG_IGN);
2937 RegisterSignalHandler(SIGINT, SignalExit);
2938 RegisterSignalHandler(SIGTERM, SignalExit);
2941 uv_idle_init(uv_default_loop(), &tick_spinner);
2943 uv_check_init(uv_default_loop(), &check_immediate_watcher);
2944 uv_unref((uv_handle_t*) &check_immediate_watcher);
2945 uv_idle_init(uv_default_loop(), &idle_immediate_dummy);
2947 V8::SetFatalErrorHandler(node::OnFatalError);
2949 // Fetch a reference to the main isolate, so we have a reference to it
2950 // even when we need it to access it from another (debugger) thread.
2951 node_isolate = Isolate::GetCurrent();
2953 // If the --debug flag was specified then initialize the debug thread.
2954 if (use_debug_agent) {
2955 EnableDebug(debug_wait_connect);
2958 RegisterDebugSignalHandler();
2960 static uv_signal_t signal_watcher;
2961 uv_signal_init(uv_default_loop(), &signal_watcher);
2962 uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1);
2963 uv_unref((uv_handle_t*)&signal_watcher);
2971 struct AtExitCallback {
2972 AtExitCallback* next_;
2973 void (*cb_)(void* arg);
2977 static AtExitCallback* at_exit_functions_;
2981 AtExitCallback* p = at_exit_functions_;
2982 at_exit_functions_ = NULL;
2985 AtExitCallback* q = p->next_;
2993 void AtExit(void (*cb)(void* arg), void* arg) {
2994 AtExitCallback* p = new AtExitCallback;
2997 p->next_ = at_exit_functions_;
2998 at_exit_functions_ = p;
3002 void EmitExit(v8::Handle<v8::Object> process_l) {
3003 // process.emit('exit')
3004 process_l->Set(String::NewSymbol("_exiting"), True());
3005 Local<Value> emit_v = process_l->Get(String::New("emit"));
3006 assert(emit_v->IsFunction());
3007 Local<Function> emit = Local<Function>::Cast(emit_v);
3008 Local<Value> args[] = { String::New("exit"), Integer::New(0) };
3010 emit->Call(process_l, 2, args);
3011 if (try_catch.HasCaught()) {
3012 FatalException(try_catch);
3016 static char **copy_argv(int argc, char **argv) {
3024 for(i = 0; i < argc; i++) {
3025 strlen_sum += strlen(argv[i]) + 1;
3028 argv_copy = (char **) malloc(sizeof(char *) * (argc + 1) + strlen_sum);
3033 argv_data = (char *) argv_copy + sizeof(char *) * (argc + 1);
3035 for(i = 0; i < argc; i++) {
3036 argv_copy[i] = argv_data;
3037 len = strlen(argv[i]) + 1;
3038 memcpy(argv_data, argv[i], len);
3042 argv_copy[argc] = NULL;
3047 int Start(int argc, char *argv[]) {
3048 // Hack aroung with the argv pointer. Used for process.title = "blah".
3049 argv = uv_setup_args(argc, argv);
3051 // Logic to duplicate argv as Init() modifies arguments
3052 // that are passed into it.
3053 char **argv_copy = copy_argv(argc, argv);
3055 // This needs to run *before* V8::Initialize()
3056 // Use copy here as to not modify the original argv:
3057 Init(argc, argv_copy);
3062 HandleScope handle_scope;
3064 // Create the one and only Context.
3065 Persistent<Context> context = Context::New();
3066 Context::Scope context_scope(context);
3068 // Use original argv, as we're just copying values out of it.
3069 Handle<Object> process_l = SetupProcessObject(argc, argv);
3070 v8_typed_array::AttachBindings(context->Global());
3072 // Create all the objects, load modules, do everything.
3073 // so your next reading stop should be node::Load()!
3076 // All our arguments are loaded. We've evaluated all of the scripts. We
3077 // might even have created TCP servers. Now we enter the main eventloop. If
3078 // there are no watchers on the loop (except for the ones that were
3079 // uv_unref'd) then this function exits. As long as there are active
3080 // watchers, it blocks.
3081 uv_run(uv_default_loop(), UV_RUN_DEFAULT);
3083 EmitExit(process_l);
3092 // Clean up. Not strictly necessary.
3096 // Clean up the copy: