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"
30 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
31 # include "node_dtrace.h"
33 #if defined HAVE_PERFCTR
34 # include "node_counters.h"
42 #if !defined(_MSC_VER)
45 #define strcasecmp _stricmp
47 #include <limits.h> /* PATH_MAX */
49 #if !defined(_MSC_VER)
50 #include <unistd.h> /* setuid, getuid */
54 #define getpid _getpid
60 #include <sys/types.h>
64 # include <pwd.h> /* getpwnam() */
65 # include <grp.h> /* getgrnam() */
68 #include "node_buffer.h"
69 #include "node_file.h"
70 #include "node_http_parser.h"
71 #include "node_constants.h"
72 #include "node_javascript.h"
73 #include "node_version.h"
74 #include "node_string.h"
76 # include "node_crypto.h"
79 #include "node_systemtap.h"
81 #include "node_script.h"
82 #include "v8_typed_array.h"
87 # include <crt_externs.h>
88 # define environ (*_NSGetEnviron())
89 # elif !defined(_MSC_VER)
90 extern char **environ;
95 ngx_queue_t handle_wrap_queue = { &handle_wrap_queue, &handle_wrap_queue };
96 ngx_queue_t req_wrap_queue = { &req_wrap_queue, &req_wrap_queue };
98 // declared in req_wrap.h
99 Persistent<String> process_symbol;
100 Persistent<String> domain_symbol;
102 // declared in node_internals.h
103 Persistent<Object> process;
105 static Persistent<Function> process_tickFromSpinner;
106 static Persistent<Function> process_tickCallback;
108 static Persistent<String> exports_symbol;
110 static Persistent<String> errno_symbol;
111 static Persistent<String> syscall_symbol;
112 static Persistent<String> errpath_symbol;
113 static Persistent<String> code_symbol;
115 static Persistent<String> rss_symbol;
116 static Persistent<String> heap_total_symbol;
117 static Persistent<String> heap_used_symbol;
119 static Persistent<String> fatal_exception_symbol;
121 static Persistent<String> enter_symbol;
122 static Persistent<String> exit_symbol;
123 static Persistent<String> disposed_symbol;
126 static bool print_eval = false;
127 static bool force_repl = false;
128 static bool trace_deprecation = false;
129 static bool throw_deprecation = false;
130 static char *eval_string = NULL;
131 static int option_end_index = 0;
132 static bool use_debug_agent = false;
133 static bool debug_wait_connect = false;
134 static int debug_port=5858;
135 static int max_stack_size = 0;
136 bool using_domains = false;
138 // used by C++ modules as well
139 bool no_deprecation = false;
141 static uv_idle_t tick_spinner;
142 static bool need_tick_cb;
143 static Persistent<String> tick_callback_sym;
145 static uv_check_t check_immediate_watcher;
146 static uv_idle_t idle_immediate_dummy;
147 static bool need_immediate_cb;
148 static Persistent<String> immediate_callback_sym;
150 // for quick ref to tickCallback values
157 #ifdef OPENSSL_NPN_NEGOTIATED
158 static bool use_npn = true;
160 static bool use_npn = false;
163 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
164 static bool use_sni = true;
166 static bool use_sni = false;
169 // process-relative uptime base, initialized at start-up
170 static double prog_start_time;
172 static volatile bool debugger_running = false;
173 static uv_async_t dispatch_debug_messages_async;
175 // Declared in node_internals.h
176 Isolate* node_isolate = NULL;
179 static void Spin(uv_idle_t* handle, int status) {
180 assert((uv_idle_t*) handle == &tick_spinner);
183 // Avoid entering a V8 scope.
184 if (!need_tick_cb) return;
185 need_tick_cb = false;
187 uv_idle_stop(&tick_spinner);
189 HandleScope scope(node_isolate);
191 if (process_tickFromSpinner.IsEmpty()) {
192 Local<Value> cb_v = process->Get(String::New("_tickFromSpinner"));
193 if (!cb_v->IsFunction()) {
194 fprintf(stderr, "process._tickFromSpinner assigned to non-function\n");
197 Local<Function> cb = cb_v.As<Function>();
198 process_tickFromSpinner = Persistent<Function>::New(node_isolate, cb);
203 process_tickFromSpinner->Call(process, 0, NULL);
205 if (try_catch.HasCaught()) {
206 FatalException(try_catch);
211 static Handle<Value> NeedTickCallback(const Arguments& args) {
213 uv_idle_start(&tick_spinner, Spin);
214 return Undefined(node_isolate);
218 static void CheckImmediate(uv_check_t* handle, int status) {
219 assert(handle == &check_immediate_watcher);
222 HandleScope scope(node_isolate);
224 if (immediate_callback_sym.IsEmpty()) {
225 immediate_callback_sym = NODE_PSYMBOL("_immediateCallback");
228 MakeCallback(process, immediate_callback_sym, 0, NULL);
232 static void IdleImmediateDummy(uv_idle_t* handle, int status) {
233 // Do nothing. Only for maintaining event loop
234 assert(handle == &idle_immediate_dummy);
239 static inline const char *errno_string(int errorno) {
240 #define ERRNO_CASE(e) case e: return #e;
248 ERRNO_CASE(EADDRINUSE);
252 ERRNO_CASE(EADDRNOTAVAIL);
256 ERRNO_CASE(EAFNOSUPPORT);
264 # if EAGAIN != EWOULDBLOCK
265 ERRNO_CASE(EWOULDBLOCK);
270 ERRNO_CASE(EALREADY);
286 ERRNO_CASE(ECANCELED);
294 ERRNO_CASE(ECONNABORTED);
298 ERRNO_CASE(ECONNREFUSED);
302 ERRNO_CASE(ECONNRESET);
310 ERRNO_CASE(EDESTADDRREQ);
334 ERRNO_CASE(EHOSTUNREACH);
346 ERRNO_CASE(EINPROGRESS);
382 ERRNO_CASE(EMSGSIZE);
386 ERRNO_CASE(EMULTIHOP);
390 ERRNO_CASE(ENAMETOOLONG);
394 ERRNO_CASE(ENETDOWN);
398 ERRNO_CASE(ENETRESET);
402 ERRNO_CASE(ENETUNREACH);
434 # if ENOLINK != ENOLCK
448 ERRNO_CASE(ENOPROTOOPT);
468 ERRNO_CASE(ENOTCONN);
476 ERRNO_CASE(ENOTEMPTY);
480 ERRNO_CASE(ENOTSOCK);
487 ERRNO_CASE(EOPNOTSUPP);
501 ERRNO_CASE(EOVERFLOW);
516 #ifdef EPROTONOSUPPORT
517 ERRNO_CASE(EPROTONOSUPPORT);
521 ERRNO_CASE(EPROTOTYPE);
549 ERRNO_CASE(ETIMEDOUT);
564 const char *signo_string(int signo) {
565 #define SIGNO_CASE(e) case e: return #e;
593 # if SIGABRT != SIGIOT
637 SIGNO_CASE(SIGSTKFLT);
654 SIGNO_CASE(SIGBREAK);
678 SIGNO_CASE(SIGVTALRM);
686 SIGNO_CASE(SIGWINCH);
694 # if SIGPOLL != SIGIO
704 # if SIGPWR != SIGLOST
718 Local<Value> ErrnoException(int errorno,
723 Local<String> estring = String::NewSymbol(errno_string(errorno));
725 msg = strerror(errorno);
727 Local<String> message = String::NewSymbol(msg);
729 Local<String> cons1 = String::Concat(estring, String::NewSymbol(", "));
730 Local<String> cons2 = String::Concat(cons1, message);
732 if (syscall_symbol.IsEmpty()) {
733 syscall_symbol = NODE_PSYMBOL("syscall");
734 errno_symbol = NODE_PSYMBOL("errno");
735 errpath_symbol = NODE_PSYMBOL("path");
736 code_symbol = NODE_PSYMBOL("code");
740 Local<String> cons3 = String::Concat(cons2, String::NewSymbol(" '"));
741 Local<String> cons4 = String::Concat(cons3, String::New(path));
742 Local<String> cons5 = String::Concat(cons4, String::NewSymbol("'"));
743 e = Exception::Error(cons5);
745 e = Exception::Error(cons2);
748 Local<Object> obj = e->ToObject();
750 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
751 obj->Set(code_symbol, estring);
752 if (path) obj->Set(errpath_symbol, String::New(path));
753 if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
758 static const char* get_uv_errno_string(int errorno) {
760 memset(&err, 0, sizeof err);
761 err.code = (uv_err_code)errorno;
762 return uv_err_name(err);
766 static const char* get_uv_errno_message(int errorno) {
768 memset(&err, 0, sizeof err);
769 err.code = (uv_err_code)errorno;
770 return uv_strerror(err);
774 // hack alert! copy of ErrnoException, tuned for uv errors
775 Local<Value> UVException(int errorno,
779 if (syscall_symbol.IsEmpty()) {
780 syscall_symbol = NODE_PSYMBOL("syscall");
781 errno_symbol = NODE_PSYMBOL("errno");
782 errpath_symbol = NODE_PSYMBOL("path");
783 code_symbol = NODE_PSYMBOL("code");
787 msg = get_uv_errno_message(errorno);
789 Local<String> estring = String::NewSymbol(get_uv_errno_string(errorno));
790 Local<String> message = String::NewSymbol(msg);
791 Local<String> cons1 = String::Concat(estring, String::NewSymbol(", "));
792 Local<String> cons2 = String::Concat(cons1, message);
796 Local<String> path_str;
800 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
801 path_str = String::Concat(String::New("\\\\"), String::New(path + 8));
802 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
803 path_str = String::New(path + 4);
805 path_str = String::New(path);
808 path_str = String::New(path);
811 Local<String> cons3 = String::Concat(cons2, String::NewSymbol(" '"));
812 Local<String> cons4 = String::Concat(cons3, path_str);
813 Local<String> cons5 = String::Concat(cons4, String::NewSymbol("'"));
814 e = Exception::Error(cons5);
816 e = Exception::Error(cons2);
819 Local<Object> obj = e->ToObject();
821 // TODO errno should probably go
822 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
823 obj->Set(code_symbol, estring);
824 if (path) obj->Set(errpath_symbol, path_str);
825 if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
831 // Does about the same as strerror(),
832 // but supports all windows error messages
833 static const char *winapi_strerror(const int errorno) {
836 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
837 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
838 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
841 // Remove trailing newlines
842 for (int i = strlen(errmsg) - 1;
843 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
849 // FormatMessage failed
850 return "Unknown error";
855 Local<Value> WinapiErrnoException(int errorno,
860 if (!msg || !msg[0]) {
861 msg = winapi_strerror(errorno);
863 Local<String> message = String::NewSymbol(msg);
865 if (syscall_symbol.IsEmpty()) {
866 syscall_symbol = NODE_PSYMBOL("syscall");
867 errno_symbol = NODE_PSYMBOL("errno");
868 errpath_symbol = NODE_PSYMBOL("path");
869 code_symbol = NODE_PSYMBOL("code");
873 Local<String> cons1 = String::Concat(message, String::NewSymbol(" '"));
874 Local<String> cons2 = String::Concat(cons1, String::New(path));
875 Local<String> cons3 = String::Concat(cons2, String::NewSymbol("'"));
876 e = Exception::Error(cons3);
878 e = Exception::Error(message);
881 Local<Object> obj = e->ToObject();
883 obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
884 if (path) obj->Set(errpath_symbol, String::New(path));
885 if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
891 Handle<Value> FromConstructorTemplate(Persistent<FunctionTemplate> t,
892 const Arguments& args) {
893 HandleScope scope(node_isolate);
894 Local<Value> argv[32];
895 unsigned argc = args.Length();
896 if (argc > ARRAY_SIZE(argv)) argc = ARRAY_SIZE(argv);
897 for (unsigned i = 0; i < argc; ++i) argv[i] = args[i];
898 return scope.Close(t->GetFunction()->NewInstance(argc, argv));
902 Handle<Value> SetupDomainUse(const Arguments& args) {
903 HandleScope scope(node_isolate);
906 using_domains = true;
907 Local<Value> tdc_v = process->Get(String::New("_tickDomainCallback"));
908 Local<Value> ndt_v = process->Get(String::New("_nextDomainTick"));
909 if (!tdc_v->IsFunction()) {
910 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
913 if (!ndt_v->IsFunction()) {
914 fprintf(stderr, "process._nextDomainTick assigned to non-function\n");
917 Local<Function> tdc = tdc_v.As<Function>();
918 Local<Function> ndt = ndt_v.As<Function>();
919 process->Set(String::New("_tickCallback"), tdc);
920 process->Set(String::New("nextTick"), ndt);
921 process_tickCallback = Persistent<Function>::New(node_isolate, tdc);
927 MakeDomainCallback(const Handle<Object> object,
928 const Handle<Function> callback,
930 Handle<Value> argv[]) {
931 // TODO Hook for long stack traces to be made here.
933 // lazy load domain specific symbols
934 if (enter_symbol.IsEmpty()) {
935 enter_symbol = NODE_PSYMBOL("enter");
936 exit_symbol = NODE_PSYMBOL("exit");
937 disposed_symbol = NODE_PSYMBOL("_disposed");
940 Local<Value> domain_v = object->Get(domain_symbol);
941 Local<Object> domain;
942 Local<Function> enter;
943 Local<Function> exit;
947 bool has_domain = domain_v->IsObject();
949 domain = domain_v->ToObject();
950 assert(!domain.IsEmpty());
951 if (domain->Get(disposed_symbol)->IsTrue()) {
952 // domain has been disposed of.
953 return Undefined(node_isolate);
955 enter = Local<Function>::Cast(domain->Get(enter_symbol));
956 assert(!enter.IsEmpty());
957 enter->Call(domain, 0, NULL);
959 if (try_catch.HasCaught()) {
960 FatalException(try_catch);
961 return Undefined(node_isolate);
965 Local<Value> ret = callback->Call(object, argc, argv);
967 if (try_catch.HasCaught()) {
968 FatalException(try_catch);
969 return Undefined(node_isolate);
973 exit = Local<Function>::Cast(domain->Get(exit_symbol));
974 assert(!exit.IsEmpty());
975 exit->Call(domain, 0, NULL);
977 if (try_catch.HasCaught()) {
978 FatalException(try_catch);
979 return Undefined(node_isolate);
983 if (tick_infobox.length == 0) {
984 tick_infobox.index = 0;
985 tick_infobox.depth = 0;
989 // process nextTicks after call
990 process_tickCallback->Call(process, 0, NULL);
992 if (try_catch.HasCaught()) {
993 FatalException(try_catch);
994 return Undefined(node_isolate);
1002 MakeCallback(const Handle<Object> object,
1003 const Handle<Function> callback,
1005 Handle<Value> argv[]) {
1006 // TODO Hook for long stack traces to be made here.
1008 // lazy load no domain next tick callbacks
1009 if (process_tickCallback.IsEmpty()) {
1010 Local<Value> cb_v = process->Get(String::New("_tickCallback"));
1011 if (!cb_v->IsFunction()) {
1012 fprintf(stderr, "process._tickCallback assigned to non-function\n");
1015 Local<Function> cb = cb_v.As<Function>();
1016 process_tickCallback = Persistent<Function>::New(node_isolate, cb);
1021 Local<Value> ret = callback->Call(object, argc, argv);
1023 if (try_catch.HasCaught()) {
1024 FatalException(try_catch);
1025 return Undefined(node_isolate);
1028 if (tick_infobox.length == 0) {
1029 tick_infobox.index = 0;
1030 tick_infobox.depth = 0;
1034 // process nextTicks after call
1035 process_tickCallback->Call(process, 0, NULL);
1037 if (try_catch.HasCaught()) {
1038 FatalException(try_catch);
1039 return Undefined(node_isolate);
1047 MakeCallback(const Handle<Object> object,
1048 const Handle<String> symbol,
1050 Handle<Value> argv[]) {
1051 HandleScope scope(node_isolate);
1053 Local<Function> callback = object->Get(symbol).As<Function>();
1056 return scope.Close(MakeDomainCallback(object, callback, argc, argv));
1057 return scope.Close(MakeCallback(object, callback, argc, argv));
1062 MakeCallback(const Handle<Object> object,
1065 Handle<Value> argv[]) {
1066 HandleScope scope(node_isolate);
1069 MakeCallback(object, String::NewSymbol(method), argc, argv);
1071 return scope.Close(ret);
1075 void SetErrno(uv_err_t err) {
1076 HandleScope scope(node_isolate);
1078 static Persistent<String> errno_symbol;
1079 if (errno_symbol.IsEmpty()) {
1080 errno_symbol = NODE_PSYMBOL("_errno");
1083 if (err.code == UV_UNKNOWN) {
1084 char errno_buf[100];
1085 snprintf(errno_buf, 100, "Unknown system errno %d", err.sys_errno_);
1086 process->Set(errno_symbol, String::New(errno_buf));
1088 process->Set(errno_symbol, String::NewSymbol(uv_err_name(err)));
1093 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1094 HandleScope scope(node_isolate);
1096 if (!encoding_v->IsString()) return _default;
1098 String::Utf8Value encoding(encoding_v);
1100 if (strcasecmp(*encoding, "utf8") == 0) {
1102 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1104 } else if (strcasecmp(*encoding, "ascii") == 0) {
1106 } else if (strcasecmp(*encoding, "base64") == 0) {
1108 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1110 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1112 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1114 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1116 } else if (strcasecmp(*encoding, "binary") == 0) {
1118 } else if (strcasecmp(*encoding, "buffer") == 0) {
1120 } else if (strcasecmp(*encoding, "hex") == 0) {
1122 } else if (strcasecmp(*encoding, "raw") == 0) {
1123 if (!no_deprecation) {
1124 fprintf(stderr, "'raw' (array of integers) has been removed. "
1128 } else if (strcasecmp(*encoding, "raws") == 0) {
1129 if (!no_deprecation) {
1130 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1131 "Please update your code.\n");
1139 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1140 HandleScope scope(node_isolate);
1142 if (encoding == BUFFER) {
1144 Buffer::New(static_cast<const char*>(buf), len)->handle_);
1147 if (!len) return scope.Close(String::Empty(node_isolate));
1149 if (encoding == BINARY) {
1150 const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
1151 uint16_t * twobytebuf = new uint16_t[len];
1152 for (size_t i = 0; i < len; i++) {
1153 // XXX is the following line platform independent?
1154 twobytebuf[i] = cbuf[i];
1156 Local<String> chunk = String::New(twobytebuf, len);
1157 delete [] twobytebuf; // TODO use ExternalTwoByteString?
1158 return scope.Close(chunk);
1161 // utf8 or ascii encoding
1162 Local<String> chunk = String::New((const char*)buf, len);
1163 return scope.Close(chunk);
1166 // Returns -1 if the handle was not valid for decoding
1167 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1168 HandleScope scope(node_isolate);
1170 if (val->IsArray()) {
1171 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1177 if ((encoding == BUFFER || encoding == BINARY) && Buffer::HasInstance(val)) {
1178 return Buffer::Length(val->ToObject());
1181 Local<String> str = val->ToString();
1183 if (encoding == UTF8) return str->Utf8Length();
1184 else if (encoding == UCS2) return str->Length() * 2;
1185 else if (encoding == HEX) return str->Length() / 2;
1187 return str->Length();
1191 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1194 // Returns number of bytes written.
1195 ssize_t DecodeWrite(char *buf,
1197 v8::Handle<v8::Value> val,
1198 enum encoding encoding) {
1199 HandleScope scope(node_isolate);
1202 // A lot of improvement can be made here. See:
1203 // http://code.google.com/p/v8/issues/detail?id=270
1204 // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
1205 // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
1207 if (val->IsArray()) {
1208 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1214 bool is_buffer = Buffer::HasInstance(val);
1216 if (is_buffer && (encoding == BINARY || encoding == BUFFER)) {
1217 // fast path, copy buffer data
1218 const char* data = Buffer::Data(val.As<Object>());
1219 size_t size = Buffer::Length(val.As<Object>());
1220 size_t len = size < buflen ? size : buflen;
1221 memcpy(buf, data, len);
1227 if (is_buffer) { // slow path, convert to binary string
1228 Local<Value> arg = String::New("binary");
1229 str = MakeCallback(val.As<Object>(), "toString", 1, &arg)->ToString();
1232 str = val->ToString();
1235 if (encoding == UTF8) {
1236 str->WriteUtf8(buf, buflen, NULL, String::HINT_MANY_WRITES_EXPECTED);
1240 if (encoding == ASCII) {
1241 str->WriteOneByte(reinterpret_cast<uint8_t*>(buf),
1244 String::HINT_MANY_WRITES_EXPECTED);
1248 // THIS IS AWFUL!!! FIXME
1250 assert(encoding == BINARY);
1252 uint16_t * twobytebuf = new uint16_t[buflen];
1254 str->Write(twobytebuf, 0, buflen, String::HINT_MANY_WRITES_EXPECTED);
1256 for (size_t i = 0; i < buflen; i++) {
1257 unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
1261 delete [] twobytebuf;
1266 void DisplayExceptionLine (TryCatch &try_catch) {
1267 // Prevent re-entry into this function. For example, if there is
1268 // a throw from a program in vm.runInThisContext(code, filename, true),
1269 // then we want to show the original failure, not the secondary one.
1270 static bool displayed_error = false;
1272 if (displayed_error) return;
1273 displayed_error = true;
1275 HandleScope scope(node_isolate);
1277 Handle<Message> message = try_catch.Message();
1279 uv_tty_reset_mode();
1281 fprintf(stderr, "\n");
1283 if (!message.IsEmpty()) {
1284 // Print (filename):(line number): (message).
1285 String::Utf8Value filename(message->GetScriptResourceName());
1286 const char* filename_string = *filename;
1287 int linenum = message->GetLineNumber();
1288 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1289 // Print line of source code.
1290 String::Utf8Value sourceline(message->GetSourceLine());
1291 const char* sourceline_string = *sourceline;
1293 // Because of how node modules work, all scripts are wrapped with a
1294 // "function (module, exports, __filename, ...) {"
1295 // to provide script local variables.
1297 // When reporting errors on the first line of a script, this wrapper
1298 // function is leaked to the user. There used to be a hack here to
1299 // truncate off the first 62 characters, but it caused numerous other
1300 // problems when vm.runIn*Context() methods were used for non-module
1303 // If we ever decide to re-instate such a hack, the following steps
1306 // 1. Pass a flag around to say "this code was wrapped"
1307 // 2. Update the stack frame output so that it is also correct.
1309 // It would probably be simpler to add a line rather than add some
1310 // number of characters to the first line, since V8 truncates the
1311 // sourceline to 78 characters, and we end up not providing very much
1312 // useful debugging info to the user if we remove 62 characters.
1314 int start = message->GetStartColumn();
1315 int end = message->GetEndColumn();
1317 // fprintf(stderr, "---\nsourceline:%s\noffset:%d\nstart:%d\nend:%d\n---\n", sourceline_string, start, end);
1319 fprintf(stderr, "%s\n", sourceline_string);
1320 // Print wavy underline (GetUnderline is deprecated).
1321 for (int i = 0; i < start; i++) {
1322 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1324 for (int i = start; i < end; i++) {
1327 fputc('\n', stderr);
1332 static void ReportException(TryCatch &try_catch, bool show_line) {
1333 HandleScope scope(node_isolate);
1335 if (show_line) DisplayExceptionLine(try_catch);
1337 String::Utf8Value trace(try_catch.StackTrace());
1339 // range errors have a trace member set to undefined
1340 if (trace.length() > 0 && !try_catch.StackTrace()->IsUndefined()) {
1341 fprintf(stderr, "%s\n", *trace);
1343 // this really only happens for RangeErrors, since they're the only
1344 // kind that won't have all this info in the trace, or when non-Error
1345 // objects are thrown manually.
1346 Local<Value> er = try_catch.Exception();
1347 bool isErrorObject = er->IsObject() &&
1348 !(er->ToObject()->Get(String::New("message"))->IsUndefined()) &&
1349 !(er->ToObject()->Get(String::New("name"))->IsUndefined());
1351 if (isErrorObject) {
1352 String::Utf8Value name(er->ToObject()->Get(String::New("name")));
1353 fprintf(stderr, "%s: ", *name);
1356 String::Utf8Value msg(!isErrorObject ? er
1357 : er->ToObject()->Get(String::New("message")));
1358 fprintf(stderr, "%s\n", *msg);
1364 // Executes a str within the current v8 context.
1365 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1366 HandleScope scope(node_isolate);
1369 Local<v8::Script> script = v8::Script::Compile(source, filename);
1370 if (script.IsEmpty()) {
1371 ReportException(try_catch, true);
1375 Local<Value> result = script->Run();
1376 if (result.IsEmpty()) {
1377 ReportException(try_catch, true);
1381 return scope.Close(result);
1385 static Handle<Value> GetActiveRequests(const Arguments& args) {
1386 HandleScope scope(node_isolate);
1388 Local<Array> ary = Array::New();
1389 ngx_queue_t* q = NULL;
1392 ngx_queue_foreach(q, &req_wrap_queue) {
1393 ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1394 if (w->object_.IsEmpty()) continue;
1395 ary->Set(i++, w->object_);
1398 return scope.Close(ary);
1402 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1403 // implemented here for consistency with GetActiveRequests().
1404 Handle<Value> GetActiveHandles(const Arguments& args) {
1405 HandleScope scope(node_isolate);
1407 Local<Array> ary = Array::New();
1408 ngx_queue_t* q = NULL;
1411 Local<String> owner_sym = String::New("owner");
1413 ngx_queue_foreach(q, &handle_wrap_queue) {
1414 HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1415 if (w->object_.IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue;
1416 Local<Value> obj = w->object_->Get(owner_sym);
1417 if (obj->IsUndefined()) obj = *w->object_;
1421 return scope.Close(ary);
1425 static Handle<Value> Abort(const Arguments& args) {
1427 return Undefined(node_isolate);
1431 static Handle<Value> Chdir(const Arguments& args) {
1432 HandleScope scope(node_isolate);
1434 if (args.Length() != 1 || !args[0]->IsString()) {
1435 return ThrowException(Exception::Error(String::New("Bad argument.")));
1438 String::Utf8Value path(args[0]);
1440 uv_err_t r = uv_chdir(*path);
1442 if (r.code != UV_OK) {
1443 return ThrowException(UVException(r.code, "uv_chdir"));
1446 return Undefined(node_isolate);
1450 static Handle<Value> Cwd(const Arguments& args) {
1451 HandleScope scope(node_isolate);
1453 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1454 char buf[MAX_PATH * 4 + 1];
1456 char buf[PATH_MAX + 1];
1459 uv_err_t r = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1460 if (r.code != UV_OK) {
1461 return ThrowException(UVException(r.code, "uv_cwd"));
1464 buf[ARRAY_SIZE(buf) - 1] = '\0';
1465 Local<String> cwd = String::New(buf);
1467 return scope.Close(cwd);
1471 static Handle<Value> Umask(const Arguments& args) {
1472 HandleScope scope(node_isolate);
1475 if (args.Length() < 1 || args[0]->IsUndefined()) {
1479 } else if(!args[0]->IsInt32() && !args[0]->IsString()) {
1480 return ThrowException(Exception::TypeError(
1481 String::New("argument must be an integer or octal string.")));
1485 if(args[0]->IsInt32()) {
1486 oct = args[0]->Uint32Value();
1489 String::Utf8Value str(args[0]);
1491 // Parse the octal string.
1492 for (int i = 0; i < str.length(); i++) {
1494 if (c > '7' || c < '0') {
1495 return ThrowException(Exception::TypeError(
1496 String::New("invalid octal string")));
1502 old = umask(static_cast<mode_t>(oct));
1505 return scope.Close(Uint32::New(old, node_isolate));
1511 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1512 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1515 static uid_t uid_by_name(const char* name) {
1523 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1527 return uid_not_found;
1531 static char* name_by_uid(uid_t uid) {
1540 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1541 return strdup(pp->pw_name);
1552 static gid_t gid_by_name(const char* name) {
1560 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1564 return gid_not_found;
1568 #if 0 // For future use.
1569 static const char* name_by_gid(gid_t gid) {
1578 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1579 return strdup(pp->gr_name);
1591 static uid_t uid_by_name(Handle<Value> value) {
1592 if (value->IsUint32()) {
1593 return static_cast<uid_t>(value->Uint32Value());
1595 String::Utf8Value name(value);
1596 return uid_by_name(*name);
1601 static gid_t gid_by_name(Handle<Value> value) {
1602 if (value->IsUint32()) {
1603 return static_cast<gid_t>(value->Uint32Value());
1605 String::Utf8Value name(value);
1606 return gid_by_name(*name);
1611 static Handle<Value> GetUid(const Arguments& args) {
1612 HandleScope scope(node_isolate);
1614 return scope.Close(Integer::New(uid, node_isolate));
1618 static Handle<Value> GetGid(const Arguments& args) {
1619 HandleScope scope(node_isolate);
1621 return scope.Close(Integer::New(gid, node_isolate));
1625 static Handle<Value> SetGid(const Arguments& args) {
1626 HandleScope scope(node_isolate);
1628 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1629 return ThrowTypeError("setgid argument must be a number or a string");
1632 gid_t gid = gid_by_name(args[0]);
1634 if (gid == gid_not_found) {
1635 return ThrowError("setgid group id does not exist");
1639 return ThrowException(ErrnoException(errno, "setgid"));
1642 return Undefined(node_isolate);
1646 static Handle<Value> SetUid(const Arguments& args) {
1647 HandleScope scope(node_isolate);
1649 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1650 return ThrowTypeError("setuid argument must be a number or a string");
1653 uid_t uid = uid_by_name(args[0]);
1655 if (uid == uid_not_found) {
1656 return ThrowError("setuid user id does not exist");
1660 return ThrowException(ErrnoException(errno, "setuid"));
1663 return Undefined(node_isolate);
1667 static Handle<Value> GetGroups(const Arguments& args) {
1668 HandleScope scope(node_isolate);
1670 int ngroups = getgroups(0, NULL);
1672 if (ngroups == -1) {
1673 return ThrowException(ErrnoException(errno, "getgroups"));
1676 gid_t* groups = new gid_t[ngroups];
1678 ngroups = getgroups(ngroups, groups);
1680 if (ngroups == -1) {
1682 return ThrowException(ErrnoException(errno, "getgroups"));
1685 Local<Array> groups_list = Array::New(ngroups);
1686 bool seen_egid = false;
1687 gid_t egid = getegid();
1689 for (int i = 0; i < ngroups; i++) {
1690 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1691 if (groups[i] == egid) seen_egid = true;
1696 if (seen_egid == false) {
1697 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1700 return scope.Close(groups_list);
1704 static Handle<Value> SetGroups(const Arguments& args) {
1705 HandleScope scope(node_isolate);
1707 if (!args[0]->IsArray()) {
1708 return ThrowTypeError("argument 1 must be an array");
1711 Local<Array> groups_list = args[0].As<Array>();
1712 size_t size = groups_list->Length();
1713 gid_t* groups = new gid_t[size];
1715 for (size_t i = 0; i < size; i++) {
1716 gid_t gid = gid_by_name(groups_list->Get(i));
1718 if (gid == gid_not_found) {
1720 return ThrowError("group name not found");
1726 int rc = setgroups(size, groups);
1730 return ThrowException(ErrnoException(errno, "setgroups"));
1733 return Undefined(node_isolate);
1737 static Handle<Value> InitGroups(const Arguments& args) {
1738 HandleScope scope(node_isolate);
1740 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1741 return ThrowTypeError("argument 1 must be a number or a string");
1744 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1745 return ThrowTypeError("argument 2 must be a number or a string");
1748 String::Utf8Value arg0(args[0]);
1753 if (args[0]->IsUint32()) {
1754 user = name_by_uid(args[0]->Uint32Value());
1762 return ThrowError("initgroups user not found");
1765 extra_group = gid_by_name(args[1]);
1767 if (extra_group == gid_not_found) {
1768 if (must_free) free(user);
1769 return ThrowError("initgroups extra group not found");
1772 int rc = initgroups(user, extra_group);
1779 return ThrowException(ErrnoException(errno, "initgroups"));
1782 return Undefined(node_isolate);
1788 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
1789 HandleScope scope(node_isolate);
1790 exit(args[0]->IntegerValue());
1791 return Undefined(node_isolate);
1795 static Handle<Value> Uptime(const Arguments& args) {
1796 HandleScope scope(node_isolate);
1799 uv_err_t err = uv_uptime(&uptime);
1801 if (err.code != UV_OK) {
1802 return Undefined(node_isolate);
1805 return scope.Close(Number::New(uptime - prog_start_time));
1809 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
1810 HandleScope scope(node_isolate);
1814 uv_err_t err = uv_resident_set_memory(&rss);
1816 if (err.code != UV_OK) {
1817 return ThrowException(UVException(err.code, "uv_resident_set_memory"));
1820 Local<Object> info = Object::New();
1822 if (rss_symbol.IsEmpty()) {
1823 rss_symbol = NODE_PSYMBOL("rss");
1824 heap_total_symbol = NODE_PSYMBOL("heapTotal");
1825 heap_used_symbol = NODE_PSYMBOL("heapUsed");
1828 info->Set(rss_symbol, Number::New(rss));
1831 HeapStatistics v8_heap_stats;
1832 node_isolate->GetHeapStatistics(&v8_heap_stats);
1833 info->Set(heap_total_symbol,
1834 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(),
1836 info->Set(heap_used_symbol,
1837 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(),
1840 return scope.Close(info);
1844 Handle<Value> Kill(const Arguments& args) {
1845 HandleScope scope(node_isolate);
1847 if (args.Length() != 2) {
1848 return ThrowException(Exception::Error(String::New("Bad argument.")));
1851 int pid = args[0]->IntegerValue();
1852 int sig = args[1]->Int32Value();
1853 uv_err_t err = uv_kill(pid, sig);
1855 if (err.code != UV_OK) {
1857 return scope.Close(Integer::New(-1, node_isolate));
1860 return Undefined(node_isolate);
1863 // used in Hrtime() below
1864 #define NANOS_PER_SEC 1000000000
1866 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1867 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1868 // so this function instead returns an Array with 2 entries representing seconds
1869 // and nanoseconds, to avoid any integer overflow possibility.
1870 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1871 Handle<Value> Hrtime(const v8::Arguments& args) {
1872 HandleScope scope(node_isolate);
1874 uint64_t t = uv_hrtime();
1876 if (args.Length() > 0) {
1877 // return a time diff tuple
1878 if (!args[0]->IsArray()) {
1879 Local<Value> exception = Exception::TypeError(
1880 String::New("process.hrtime() only accepts an Array tuple."));
1881 return ThrowException(exception);
1883 Local<Array> inArray = Local<Array>::Cast(args[0]);
1884 uint64_t seconds = inArray->Get(0)->Uint32Value();
1885 uint64_t nanos = inArray->Get(1)->Uint32Value();
1886 t -= (seconds * NANOS_PER_SEC) + nanos;
1889 Local<Array> tuple = Array::New(2);
1890 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1891 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1893 return scope.Close(tuple);
1897 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1899 // DLOpen is process.dlopen(module, filename).
1900 // Used to load 'module.node' dynamically shared objects.
1901 Handle<Value> DLOpen(const v8::Arguments& args) {
1902 HandleScope scope(node_isolate);
1903 char symbol[1024], *base, *pos;
1907 if (args.Length() < 2) {
1908 Local<Value> exception = Exception::Error(
1909 String::New("process.dlopen takes exactly 2 arguments."));
1910 return ThrowException(exception);
1913 Local<Object> module = args[0]->ToObject(); // Cast
1914 String::Utf8Value filename(args[1]); // Cast
1916 if (exports_symbol.IsEmpty()) {
1917 exports_symbol = NODE_PSYMBOL("exports");
1919 Local<Object> exports = module->Get(exports_symbol)->ToObject();
1921 if (uv_dlopen(*filename, &lib)) {
1922 Local<String> errmsg = String::New(uv_dlerror(&lib));
1924 // Windows needs to add the filename into the error message
1925 errmsg = String::Concat(errmsg, args[1]->ToString());
1927 return ThrowException(Exception::Error(errmsg));
1930 String::Utf8Value path(args[1]);
1933 /* Find the shared library filename within the full path. */
1935 pos = strrchr(base, '/');
1941 pos = strpbrk(base, "\\/:");
1949 /* Strip the .node extension. */
1950 pos = strrchr(base, '.');
1955 /* Add the `_module` suffix to the extension name. */
1956 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1957 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1958 Local<Value> exception =
1959 Exception::Error(String::New("Out of memory."));
1960 return ThrowException(exception);
1963 /* Replace dashes with underscores. When loading foo-bar.node,
1964 * look for foo_bar_module, not foo-bar_module.
1966 for (pos = symbol; *pos != '\0'; ++pos) {
1967 if (*pos == '-') *pos = '_';
1970 node_module_struct *mod;
1971 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1973 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1974 return ThrowError(errmsg);
1977 if (mod->version != NODE_MODULE_VERSION) {
1981 "Module version mismatch. Expected %d, got %d.",
1982 NODE_MODULE_VERSION, mod->version);
1983 return ThrowError(errmsg);
1986 // Execute the C++ module
1987 mod->register_func(exports, module);
1989 // Tell coverity that 'handle' should not be freed when we return.
1990 // coverity[leaked_storage]
1991 return Undefined(node_isolate);
1995 static void OnFatalError(const char* location, const char* message) {
1997 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1999 fprintf(stderr, "FATAL ERROR: %s\n", message);
2004 void FatalException(TryCatch &try_catch) {
2005 HandleScope scope(node_isolate);
2007 if (fatal_exception_symbol.IsEmpty())
2008 fatal_exception_symbol = NODE_PSYMBOL("_fatalException");
2010 Local<Value> fatal_v = process->Get(fatal_exception_symbol);
2012 if (!fatal_v->IsFunction()) {
2013 // failed before the process._fatalException function was added!
2014 // this is probably pretty bad. Nothing to do but report and exit.
2015 ReportException(try_catch, true);
2019 Local<Function> fatal_f = Local<Function>::Cast(fatal_v);
2021 Local<Value> error = try_catch.Exception();
2022 Local<Value> argv[] = { error };
2024 TryCatch fatal_try_catch;
2026 // this will return true if the JS layer handled it, false otherwise
2027 Local<Value> caught = fatal_f->Call(process, ARRAY_SIZE(argv), argv);
2029 if (fatal_try_catch.HasCaught()) {
2030 // the fatal exception function threw, so we must exit
2031 ReportException(fatal_try_catch, true);
2035 if (false == caught->BooleanValue()) {
2036 ReportException(try_catch, true);
2042 Persistent<Object> binding_cache;
2043 Persistent<Array> module_load_list;
2045 static Handle<Value> Binding(const Arguments& args) {
2046 HandleScope scope(node_isolate);
2048 Local<String> module = args[0]->ToString();
2049 String::Utf8Value module_v(module);
2050 node_module_struct* modp;
2052 if (binding_cache.IsEmpty()) {
2053 binding_cache = Persistent<Object>::New(node_isolate, Object::New());
2056 Local<Object> exports;
2058 if (binding_cache->Has(module)) {
2059 exports = binding_cache->Get(module)->ToObject();
2060 return scope.Close(exports);
2063 // Append a string to process.moduleLoadList
2065 snprintf(buf, 1024, "Binding %s", *module_v);
2066 uint32_t l = module_load_list->Length();
2067 module_load_list->Set(l, String::New(buf));
2069 if ((modp = get_builtin_module(*module_v)) != NULL) {
2070 exports = Object::New();
2071 // Internal bindings don't have a "module" object,
2073 modp->register_func(exports, Undefined(node_isolate));
2074 binding_cache->Set(module, exports);
2076 } else if (!strcmp(*module_v, "constants")) {
2077 exports = Object::New();
2078 DefineConstants(exports);
2079 binding_cache->Set(module, exports);
2081 } else if (!strcmp(*module_v, "natives")) {
2082 exports = Object::New();
2083 DefineJavaScript(exports);
2084 binding_cache->Set(module, exports);
2088 return ThrowException(Exception::Error(String::New("No such module")));
2091 return scope.Close(exports);
2095 static Handle<Value> ProcessTitleGetter(Local<String> property,
2096 const AccessorInfo& info) {
2097 HandleScope scope(node_isolate);
2099 uv_get_process_title(buffer, sizeof(buffer));
2100 return scope.Close(String::New(buffer));
2104 static void ProcessTitleSetter(Local<String> property,
2106 const AccessorInfo& info) {
2107 HandleScope scope(node_isolate);
2108 String::Utf8Value title(value);
2109 // TODO: protect with a lock
2110 uv_set_process_title(*title);
2114 static Handle<Value> EnvGetter(Local<String> property,
2115 const AccessorInfo& info) {
2116 HandleScope scope(node_isolate);
2118 String::Utf8Value key(property);
2119 const char* val = getenv(*key);
2121 return scope.Close(String::New(val));
2124 String::Value key(property);
2125 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2126 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2128 ARRAY_SIZE(buffer));
2129 // If result >= sizeof buffer the buffer was too small. That should never
2130 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2132 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2133 result < ARRAY_SIZE(buffer)) {
2134 return scope.Close(String::New(reinterpret_cast<uint16_t*>(buffer), result));
2137 // Not found. Fetch from prototype.
2138 return scope.Close(info.Data().As<Object>()->Get(property));
2142 static Handle<Value> EnvSetter(Local<String> property,
2144 const AccessorInfo& info) {
2145 HandleScope scope(node_isolate);
2147 String::Utf8Value key(property);
2148 String::Utf8Value val(value);
2149 setenv(*key, *val, 1);
2151 String::Value key(property);
2152 String::Value val(value);
2153 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2154 // Environment variables that start with '=' are read-only.
2155 if (key_ptr[0] != L'=') {
2156 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2159 // Whether it worked or not, always return rval.
2160 return scope.Close(value);
2164 static Handle<Integer> EnvQuery(Local<String> property,
2165 const AccessorInfo& info) {
2166 HandleScope scope(node_isolate);
2168 String::Utf8Value key(property);
2170 return scope.Close(Integer::New(0, node_isolate));
2173 String::Value key(property);
2174 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2175 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2176 GetLastError() == ERROR_SUCCESS) {
2177 if (key_ptr[0] == L'=') {
2178 // Environment variables that start with '=' are hidden and read-only.
2179 return scope.Close(Integer::New(v8::ReadOnly ||
2184 return scope.Close(Integer::New(0, node_isolate));
2189 return scope.Close(Handle<Integer>());
2193 static Handle<Boolean> EnvDeleter(Local<String> property,
2194 const AccessorInfo& info) {
2195 HandleScope scope(node_isolate);
2197 String::Utf8Value key(property);
2198 if (!getenv(*key)) return False(node_isolate);
2199 unsetenv(*key); // can't check return value, it's void on some platforms
2200 return True(node_isolate);
2202 String::Value key(property);
2203 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2204 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2205 // Deletion failed. Return true if the key wasn't there in the first place,
2206 // false if it is still there.
2207 bool rv = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2208 GetLastError() != ERROR_SUCCESS;
2209 return scope.Close(Boolean::New(rv));
2211 return True(node_isolate);
2216 static Handle<Array> EnvEnumerator(const AccessorInfo& info) {
2217 HandleScope scope(node_isolate);
2220 while (environ[size]) size++;
2222 Local<Array> env = Array::New(size);
2224 for (int i = 0; i < size; ++i) {
2225 const char* var = environ[i];
2226 const char* s = strchr(var, '=');
2227 const int length = s ? s - var : strlen(var);
2228 env->Set(i, String::New(var, length));
2231 WCHAR* environment = GetEnvironmentStringsW();
2232 if (environment == NULL) {
2233 // This should not happen.
2234 return scope.Close(Handle<Array>());
2236 Local<Array> env = Array::New();
2237 WCHAR* p = environment;
2239 while (*p != NULL) {
2242 // If the key starts with '=' it is a hidden environment variable.
2246 s = wcschr(p, L'=');
2251 env->Set(i++, String::New(reinterpret_cast<uint16_t*>(p), s - p));
2252 p = s + wcslen(s) + 1;
2254 FreeEnvironmentStringsW(environment);
2256 return scope.Close(env);
2260 static Handle<Object> GetFeatures() {
2261 HandleScope scope(node_isolate);
2263 Local<Object> obj = Object::New();
2264 obj->Set(String::NewSymbol("debug"),
2265 #if defined(DEBUG) && DEBUG
2272 obj->Set(String::NewSymbol("uv"), True(node_isolate));
2273 obj->Set(String::NewSymbol("ipv6"), True(node_isolate)); // TODO ping libuv
2274 obj->Set(String::NewSymbol("tls_npn"), Boolean::New(use_npn));
2275 obj->Set(String::NewSymbol("tls_sni"), Boolean::New(use_sni));
2276 obj->Set(String::NewSymbol("tls"),
2277 Boolean::New(get_builtin_module("crypto") != NULL));
2279 return scope.Close(obj);
2283 static Handle<Value> DebugPortGetter(Local<String> property,
2284 const AccessorInfo& info) {
2285 HandleScope scope(node_isolate);
2286 return scope.Close(Integer::NewFromUnsigned(debug_port, node_isolate));
2290 static void DebugPortSetter(Local<String> property,
2292 const AccessorInfo& info) {
2293 HandleScope scope(node_isolate);
2294 debug_port = value->NumberValue();
2298 static Handle<Value> DebugProcess(const Arguments& args);
2299 static Handle<Value> DebugPause(const Arguments& args);
2300 static Handle<Value> DebugEnd(const Arguments& args);
2303 Handle<Value> NeedImmediateCallbackGetter(Local<String> property,
2304 const AccessorInfo& info) {
2305 return Boolean::New(need_immediate_cb);
2309 static void NeedImmediateCallbackSetter(Local<String> property,
2311 const AccessorInfo& info) {
2312 HandleScope scope(node_isolate);
2314 bool bool_value = value->BooleanValue();
2316 if (need_immediate_cb == bool_value) return;
2318 need_immediate_cb = bool_value;
2320 if (need_immediate_cb) {
2321 uv_check_start(&check_immediate_watcher, node::CheckImmediate);
2322 // idle handle is needed only to maintain event loop
2323 uv_idle_start(&idle_immediate_dummy, node::IdleImmediateDummy);
2325 uv_check_stop(&check_immediate_watcher);
2326 uv_idle_stop(&idle_immediate_dummy);
2331 Handle<Object> SetupProcessObject(int argc, char *argv[]) {
2332 HandleScope scope(node_isolate);
2336 Local<FunctionTemplate> process_template = FunctionTemplate::New();
2338 process_template->SetClassName(String::NewSymbol("process"));
2340 process = Persistent<Object>::New(node_isolate,
2341 process_template->GetFunction()->NewInstance());
2343 process->SetAccessor(String::New("title"),
2345 ProcessTitleSetter);
2348 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
2350 // process.moduleLoadList
2351 module_load_list = Persistent<Array>::New(node_isolate, Array::New());
2352 process->Set(String::NewSymbol("moduleLoadList"), module_load_list);
2355 Local<Object> versions = Object::New();
2356 process->Set(String::NewSymbol("versions"), versions);
2357 versions->Set(String::NewSymbol("http_parser"), String::New(
2358 NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR) "."
2359 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR)));
2360 // +1 to get rid of the leading 'v'
2361 versions->Set(String::NewSymbol("node"), String::New(NODE_VERSION+1));
2362 versions->Set(String::NewSymbol("v8"), String::New(V8::GetVersion()));
2363 versions->Set(String::NewSymbol("ares"), String::New(ARES_VERSION_STR));
2364 versions->Set(String::NewSymbol("uv"), String::New(uv_version_string()));
2365 versions->Set(String::NewSymbol("zlib"), String::New(ZLIB_VERSION));
2366 versions->Set(String::NewSymbol("modules"),
2367 String::New(NODE_STRINGIFY(NODE_MODULE_VERSION)));
2369 // Stupid code to slice out the version string.
2370 int c, l = strlen(OPENSSL_VERSION_TEXT);
2371 for (i = j = 0; i < l; i++) {
2372 c = OPENSSL_VERSION_TEXT[i];
2373 if ('0' <= c && c <= '9') {
2374 for (j = i + 1; j < l; j++) {
2375 c = OPENSSL_VERSION_TEXT[j];
2376 if (c == ' ') break;
2381 versions->Set(String::NewSymbol("openssl"),
2382 String::New(&OPENSSL_VERSION_TEXT[i], j - i));
2388 process->Set(String::NewSymbol("arch"), String::New(ARCH));
2391 process->Set(String::NewSymbol("platform"), String::New(PLATFORM));
2394 Local<Array> arguments = Array::New(argc - option_end_index + 1);
2395 arguments->Set(Integer::New(0, node_isolate), String::New(argv[0]));
2396 for (j = 1, i = option_end_index; i < argc; j++, i++) {
2397 Local<String> arg = String::New(argv[i]);
2398 arguments->Set(Integer::New(j, node_isolate), arg);
2401 process->Set(String::NewSymbol("argv"), arguments);
2404 Local<Array> execArgv = Array::New(option_end_index - 1);
2405 for (j = 1, i = 0; j < option_end_index; j++, i++) {
2406 execArgv->Set(Integer::New(i, node_isolate), String::New(argv[j]));
2409 process->Set(String::NewSymbol("execArgv"), execArgv);
2412 // create process.env
2413 Local<ObjectTemplate> envTemplate = ObjectTemplate::New();
2414 envTemplate->SetNamedPropertyHandler(EnvGetter,
2420 Local<Object> env = envTemplate->NewInstance();
2421 process->Set(String::NewSymbol("env"), env);
2423 process->Set(String::NewSymbol("pid"), Integer::New(getpid(), node_isolate));
2424 process->Set(String::NewSymbol("features"), GetFeatures());
2425 process->SetAccessor(String::New("_needImmediateCallback"),
2426 NeedImmediateCallbackGetter,
2427 NeedImmediateCallbackSetter);
2431 process->Set(String::NewSymbol("_eval"), String::New(eval_string));
2436 process->Set(String::NewSymbol("_print_eval"), True(node_isolate));
2439 // -i, --interactive
2441 process->Set(String::NewSymbol("_forceRepl"), True(node_isolate));
2445 if (no_deprecation) {
2446 process->Set(String::NewSymbol("noDeprecation"), True(node_isolate));
2449 // --throw-deprecation
2450 if (throw_deprecation) {
2451 process->Set(String::NewSymbol("throwDeprecation"), True());
2454 // --trace-deprecation
2455 if (trace_deprecation) {
2456 process->Set(String::NewSymbol("traceDeprecation"), True(node_isolate));
2459 size_t size = 2*PATH_MAX;
2460 char* execPath = new char[size];
2461 if (uv_exepath(execPath, &size) != 0) {
2462 // as a last ditch effort, fallback on argv[0] ?
2463 process->Set(String::NewSymbol("execPath"), String::New(argv[0]));
2465 process->Set(String::NewSymbol("execPath"), String::New(execPath, size));
2469 process->SetAccessor(String::New("debugPort"),
2474 // define various internal methods
2475 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2476 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2477 NODE_SET_METHOD(process, "_needTickCallback", NeedTickCallback);
2478 NODE_SET_METHOD(process, "reallyExit", Exit);
2479 NODE_SET_METHOD(process, "abort", Abort);
2480 NODE_SET_METHOD(process, "chdir", Chdir);
2481 NODE_SET_METHOD(process, "cwd", Cwd);
2483 NODE_SET_METHOD(process, "umask", Umask);
2486 NODE_SET_METHOD(process, "getuid", GetUid);
2487 NODE_SET_METHOD(process, "setuid", SetUid);
2489 NODE_SET_METHOD(process, "setgid", SetGid);
2490 NODE_SET_METHOD(process, "getgid", GetGid);
2492 NODE_SET_METHOD(process, "getgroups", GetGroups);
2493 NODE_SET_METHOD(process, "setgroups", SetGroups);
2494 NODE_SET_METHOD(process, "initgroups", InitGroups);
2497 NODE_SET_METHOD(process, "_kill", Kill);
2499 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2500 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2501 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2503 NODE_SET_METHOD(process, "hrtime", Hrtime);
2505 NODE_SET_METHOD(process, "dlopen", DLOpen);
2507 NODE_SET_METHOD(process, "uptime", Uptime);
2508 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2510 NODE_SET_METHOD(process, "binding", Binding);
2512 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2514 // values use to cross communicate with processNextTick
2515 Local<Object> info_box = Object::New();
2516 info_box->SetIndexedPropertiesToExternalArrayData(&tick_infobox,
2517 kExternalUnsignedIntArray,
2519 process->Set(String::NewSymbol("_tickInfoBox"), info_box);
2521 // pre-set _events object for faster emit checks
2522 process->Set(String::NewSymbol("_events"), Object::New());
2528 static void AtExit() {
2529 uv_tty_reset_mode();
2533 static void SignalExit(int signal) {
2534 uv_tty_reset_mode();
2535 _exit(128 + signal);
2539 void Load(Handle<Object> process_l) {
2540 process_symbol = NODE_PSYMBOL("process");
2541 domain_symbol = NODE_PSYMBOL("domain");
2543 // Compile, execute the src/node.js file. (Which was included as static C
2544 // string in node_natives.h. 'natve_node' is the string containing that
2547 // The node.js file returns a function 'f'
2552 Local<Value> f_value = ExecuteString(MainSource(),
2553 IMMUTABLE_STRING("node.js"));
2554 if (try_catch.HasCaught()) {
2555 ReportException(try_catch, true);
2558 assert(f_value->IsFunction());
2559 Local<Function> f = Local<Function>::Cast(f_value);
2561 // Now we call 'f' with the 'process' variable that we've built up with
2562 // all our bindings. Inside node.js we'll take care of assigning things to
2565 // We start the process this way in order to be more modular. Developers
2566 // who do not like how 'src/node.js' setups the module system but do like
2567 // Node's I/O bindings may want to replace 'f' with their own function.
2569 // Add a reference to the global object
2570 Local<Object> global = v8::Context::GetCurrent()->Global();
2571 Local<Value> args[1] = { Local<Value>::New(node_isolate, process_l) };
2573 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2577 #if defined HAVE_PERFCTR
2578 InitPerfCounters(global);
2581 f->Call(global, 1, args);
2583 if (try_catch.HasCaught()) {
2584 FatalException(try_catch);
2588 static void PrintHelp();
2590 static void ParseDebugOpt(const char* arg) {
2593 use_debug_agent = true;
2594 if (!strcmp (arg, "--debug-brk")) {
2595 debug_wait_connect = true;
2597 } else if (!strcmp(arg, "--debug")) {
2599 } else if (strstr(arg, "--debug-brk=") == arg) {
2600 debug_wait_connect = true;
2601 p = 1 + strchr(arg, '=');
2602 debug_port = atoi(p);
2603 } else if (strstr(arg, "--debug=") == arg) {
2604 p = 1 + strchr(arg, '=');
2605 debug_port = atoi(p);
2607 if (p && debug_port > 1024 && debug_port < 65536)
2610 fprintf(stderr, "Bad debug option.\n");
2611 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2617 static void PrintHelp() {
2618 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2619 " node debug script.js [arguments] \n"
2622 " -v, --version print node's version\n"
2623 " -e, --eval script evaluate script\n"
2624 " -p, --print evaluate script and print result\n"
2625 " -i, --interactive always enter the REPL even if stdin\n"
2626 " does not appear to be a terminal\n"
2627 " --no-deprecation silence deprecation warnings\n"
2628 " --trace-deprecation show stack traces on deprecations\n"
2629 " --v8-options print v8 command line options\n"
2630 " --max-stack-size=val set max v8 stack size (bytes)\n"
2632 "Environment variables:\n"
2634 "NODE_PATH ';'-separated list of directories\n"
2636 "NODE_PATH ':'-separated list of directories\n"
2638 " prefixed to the module search path.\n"
2639 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2640 " global contexts.\n"
2641 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2643 "Documentation can be found at http://nodejs.org/\n");
2646 // Parse node command line arguments.
2647 static void ParseArgs(int argc, char **argv) {
2650 // TODO use parse opts
2651 for (i = 1; i < argc; i++) {
2652 const char *arg = argv[i];
2653 if (strstr(arg, "--debug") == arg) {
2655 argv[i] = const_cast<char*>("");
2656 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2657 printf("%s\n", NODE_VERSION);
2659 } else if (strstr(arg, "--max-stack-size=") == arg) {
2661 p = 1 + strchr(arg, '=');
2662 max_stack_size = atoi(p);
2663 argv[i] = const_cast<char*>("");
2664 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2667 } else if (strcmp(arg, "--eval") == 0 ||
2668 strcmp(arg, "-e") == 0 ||
2669 strcmp(arg, "--print") == 0 ||
2670 strcmp(arg, "-pe") == 0 ||
2671 strcmp(arg, "-p") == 0) {
2672 bool is_eval = strchr(arg, 'e') != NULL;
2673 bool is_print = strchr(arg, 'p') != NULL;
2675 // argument to -p and --print is optional
2676 if (is_eval == true && i + 1 >= argc) {
2677 fprintf(stderr, "Error: %s requires an argument\n", arg);
2681 print_eval = print_eval || is_print;
2682 argv[i] = const_cast<char*>("");
2684 // --eval, -e and -pe always require an argument
2685 if (is_eval == true) {
2686 eval_string = argv[++i];
2690 // next arg is the expression to evaluate unless it starts with:
2691 // - a dash, then it's another switch
2692 // - "\\-", then it's an escaped expression, drop the backslash
2693 if (argv[i + 1] == NULL) continue;
2694 if (argv[i + 1][0] == '-') continue;
2695 eval_string = argv[++i];
2696 if (strncmp(eval_string, "\\-", 2) == 0) ++eval_string;
2697 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2699 argv[i] = const_cast<char*>("");
2700 } else if (strcmp(arg, "--v8-options") == 0) {
2701 argv[i] = const_cast<char*>("--help");
2702 } else if (strcmp(arg, "--no-deprecation") == 0) {
2703 argv[i] = const_cast<char*>("");
2704 no_deprecation = true;
2705 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2706 argv[i] = const_cast<char*>("");
2707 trace_deprecation = true;
2708 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2709 argv[i] = const_cast<char*>("");
2710 throw_deprecation = true;
2711 } else if (argv[i][0] != '-') {
2716 option_end_index = i;
2720 // Called from the main thread.
2721 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2722 v8::Debug::ProcessDebugMessages();
2726 // Called from V8 Debug Agent TCP thread.
2727 static void DispatchMessagesDebugAgentCallback() {
2728 uv_async_send(&dispatch_debug_messages_async);
2732 static void EnableDebug(bool wait_connect) {
2733 // If we're called from another thread, make sure to enter the right
2735 node_isolate->Enter();
2737 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2740 uv_async_init(uv_default_loop(),
2741 &dispatch_debug_messages_async,
2742 DispatchDebugMessagesAsyncCallback);
2743 uv_unref((uv_handle_t*) &dispatch_debug_messages_async);
2745 // Start the debug thread and it's associated TCP server on port 5858.
2746 bool r = v8::Debug::EnableAgent("node " NODE_VERSION,
2750 // Crappy check that everything went well. FIXME
2753 // Print out some information.
2754 fprintf(stderr, "debugger listening on port %d\n", debug_port);
2757 debugger_running = true;
2759 node_isolate->Exit();
2764 static void EnableDebugSignalHandler(uv_signal_t* handle, int) {
2765 // Break once process will return execution to v8
2766 v8::Debug::DebugBreak(node_isolate);
2768 if (!debugger_running) {
2769 fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n");
2775 static void RegisterSignalHandler(int signal, void (*handler)(int)) {
2776 struct sigaction sa;
2778 memset(&sa, 0, sizeof(sa));
2779 sa.sa_handler = handler;
2780 sigfillset(&sa.sa_mask);
2781 sigaction(signal, &sa, NULL);
2785 Handle<Value> DebugProcess(const Arguments& args) {
2786 HandleScope scope(node_isolate);
2788 if (args.Length() != 1) {
2789 return ThrowException(Exception::Error(
2790 String::New("Invalid number of arguments.")));
2796 pid = args[0]->IntegerValue();
2797 r = kill(pid, SIGUSR1);
2799 return ThrowException(ErrnoException(errno, "kill"));
2802 return Undefined(node_isolate);
2808 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2809 // Break once process will return execution to v8
2810 if (!debugger_running) {
2811 for (int i = 0; i < 1; i++) {
2812 fprintf(stderr, "Starting debugger agent.\r\n");
2818 v8::Debug::DebugBreak(node_isolate);
2824 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2826 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2830 static int RegisterDebugSignalHandler() {
2831 wchar_t mapping_name[32];
2832 HANDLE mapping_handle;
2834 LPTHREAD_START_ROUTINE* handler;
2836 pid = GetCurrentProcessId();
2838 if (GetDebugSignalHandlerMappingName(pid,
2840 ARRAY_SIZE(mapping_name)) < 0) {
2844 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2850 if (mapping_handle == NULL) {
2854 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2855 MapViewOfFile(mapping_handle,
2856 FILE_MAP_ALL_ACCESS,
2860 if (handler == NULL) {
2861 CloseHandle(mapping_handle);
2865 *handler = EnableDebugThreadProc;
2867 UnmapViewOfFile((void*) handler);
2873 static Handle<Value> DebugProcess(const Arguments& args) {
2874 HandleScope scope(node_isolate);
2875 Handle<Value> rv = Undefined(node_isolate);
2877 HANDLE process = NULL;
2878 HANDLE thread = NULL;
2879 HANDLE mapping = NULL;
2880 wchar_t mapping_name[32];
2881 LPTHREAD_START_ROUTINE* handler = NULL;
2883 if (args.Length() != 1) {
2884 rv = ThrowException(Exception::Error(String::New("Invalid number of arguments.")));
2888 pid = (DWORD) args[0]->IntegerValue();
2890 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2891 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2895 if (process == NULL) {
2896 rv = ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2900 if (GetDebugSignalHandlerMappingName(pid,
2902 ARRAY_SIZE(mapping_name)) < 0) {
2903 rv = ThrowException(ErrnoException(errno, "sprintf"));
2907 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2908 if (mapping == NULL) {
2909 rv = ThrowException(WinapiErrnoException(GetLastError(),
2910 "OpenFileMappingW"));
2914 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2915 MapViewOfFile(mapping,
2920 if (handler == NULL || *handler == NULL) {
2921 rv = ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
2925 thread = CreateRemoteThread(process,
2932 if (thread == NULL) {
2933 rv = ThrowException(WinapiErrnoException(GetLastError(),
2934 "CreateRemoteThread"));
2938 // Wait for the thread to terminate
2939 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
2940 rv = ThrowException(WinapiErrnoException(GetLastError(),
2941 "WaitForSingleObject"));
2946 if (process != NULL) {
2947 CloseHandle(process);
2949 if (thread != NULL) {
2950 CloseHandle(thread);
2952 if (handler != NULL) {
2953 UnmapViewOfFile(handler);
2955 if (mapping != NULL) {
2956 CloseHandle(mapping);
2959 return Undefined(node_isolate);
2964 static Handle<Value> DebugPause(const Arguments& args) {
2965 v8::Debug::DebugBreak(node_isolate);
2966 return Undefined(node_isolate);
2970 static Handle<Value> DebugEnd(const Arguments& args) {
2971 if (debugger_running) {
2972 v8::Debug::DisableAgent();
2973 debugger_running = false;
2976 return Undefined(node_isolate);
2980 char** Init(int argc, char *argv[]) {
2981 // Initialize prog_start_time to get relative uptime.
2982 uv_uptime(&prog_start_time);
2984 // Make inherited handles noninheritable.
2985 uv_disable_stdio_inheritance();
2987 // Parse a few arguments which are specific to Node.
2988 node::ParseArgs(argc, argv);
2989 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
2990 // in the command line))
2991 int v8argc = option_end_index;
2992 char **v8argv = argv;
2994 if (debug_wait_connect) {
2995 // v8argv is a copy of argv up to the script file argument +2 if --debug-brk
2996 // to expose the v8 debugger js object so that node.js can set
2997 // a breakpoint on the first line of the startup script
2999 v8argv = new char*[v8argc];
3000 memcpy(v8argv, argv, sizeof(*argv) * option_end_index);
3001 v8argv[option_end_index] = const_cast<char*>("--expose_debug_as");
3002 v8argv[option_end_index + 1] = const_cast<char*>("v8debug");
3005 // For the normal stack which moves from high to low addresses when frames
3006 // are pushed, we can compute the limit as stack_size bytes below the
3007 // the address of a stack variable (e.g. &stack_var) as an approximation
3008 // of the start of the stack (we're assuming that we haven't pushed a lot
3010 if (max_stack_size != 0) {
3012 ResourceConstraints constraints;
3014 uint32_t *stack_limit = &stack_var - (max_stack_size / sizeof(uint32_t));
3015 constraints.set_stack_limit(stack_limit);
3016 SetResourceConstraints(&constraints); // Must be done before V8::Initialize
3018 V8::SetFlagsFromCommandLine(&v8argc, v8argv, false);
3020 // Fetch a reference to the main isolate, so we have a reference to it
3021 // even when we need it to access it from another (debugger) thread.
3022 node_isolate = Isolate::GetCurrent();
3026 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3027 RegisterSignalHandler(SIGINT, SignalExit);
3028 RegisterSignalHandler(SIGTERM, SignalExit);
3031 uv_idle_init(uv_default_loop(), &tick_spinner);
3033 uv_check_init(uv_default_loop(), &check_immediate_watcher);
3034 uv_unref((uv_handle_t*) &check_immediate_watcher);
3035 uv_idle_init(uv_default_loop(), &idle_immediate_dummy);
3037 V8::SetFatalErrorHandler(node::OnFatalError);
3039 // If the --debug flag was specified then initialize the debug thread.
3040 if (use_debug_agent) {
3041 EnableDebug(debug_wait_connect);
3044 RegisterDebugSignalHandler();
3046 static uv_signal_t signal_watcher;
3047 uv_signal_init(uv_default_loop(), &signal_watcher);
3048 uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1);
3049 uv_unref((uv_handle_t*)&signal_watcher);
3057 struct AtExitCallback {
3058 AtExitCallback* next_;
3059 void (*cb_)(void* arg);
3063 static AtExitCallback* at_exit_functions_;
3067 AtExitCallback* p = at_exit_functions_;
3068 at_exit_functions_ = NULL;
3071 AtExitCallback* q = p->next_;
3079 void AtExit(void (*cb)(void* arg), void* arg) {
3080 AtExitCallback* p = new AtExitCallback;
3083 p->next_ = at_exit_functions_;
3084 at_exit_functions_ = p;
3088 void EmitExit(v8::Handle<v8::Object> process_l) {
3089 // process.emit('exit')
3090 process_l->Set(String::NewSymbol("_exiting"), True(node_isolate));
3091 Local<Value> emit_v = process_l->Get(String::New("emit"));
3092 assert(emit_v->IsFunction());
3093 Local<Function> emit = Local<Function>::Cast(emit_v);
3094 Local<Value> args[] = { String::New("exit"), Integer::New(0, node_isolate) };
3096 emit->Call(process_l, 2, args);
3097 if (try_catch.HasCaught()) {
3098 FatalException(try_catch);
3102 static char **copy_argv(int argc, char **argv) {
3110 for(i = 0; i < argc; i++) {
3111 strlen_sum += strlen(argv[i]) + 1;
3114 argv_copy = (char **) malloc(sizeof(char *) * (argc + 1) + strlen_sum);
3119 argv_data = (char *) argv_copy + sizeof(char *) * (argc + 1);
3121 for(i = 0; i < argc; i++) {
3122 argv_copy[i] = argv_data;
3123 len = strlen(argv[i]) + 1;
3124 memcpy(argv_data, argv[i], len);
3128 argv_copy[argc] = NULL;
3133 int Start(int argc, char *argv[]) {
3134 // Hack aroung with the argv pointer. Used for process.title = "blah".
3135 argv = uv_setup_args(argc, argv);
3137 // Logic to duplicate argv as Init() modifies arguments
3138 // that are passed into it.
3139 char **argv_copy = copy_argv(argc, argv);
3141 // This needs to run *before* V8::Initialize()
3142 // Use copy here as to not modify the original argv:
3143 Init(argc, argv_copy);
3147 Locker locker(node_isolate);
3148 HandleScope handle_scope(node_isolate);
3150 // Create the one and only Context.
3151 Persistent<Context> context = Context::New();
3152 Context::Scope context_scope(context);
3154 // Use original argv, as we're just copying values out of it.
3155 Handle<Object> process_l = SetupProcessObject(argc, argv);
3156 v8_typed_array::AttachBindings(context->Global());
3158 // Create all the objects, load modules, do everything.
3159 // so your next reading stop should be node::Load()!
3162 // All our arguments are loaded. We've evaluated all of the scripts. We
3163 // might even have created TCP servers. Now we enter the main eventloop. If
3164 // there are no watchers on the loop (except for the ones that were
3165 // uv_unref'd) then this function exits. As long as there are active
3166 // watchers, it blocks.
3167 uv_run(uv_default_loop(), UV_RUN_DEFAULT);
3169 EmitExit(process_l);
3173 context.Dispose(node_isolate);
3178 // Clean up. Not strictly necessary.
3182 // Clean up the copy: