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 static Persistent<Object> process;
103 static Persistent<Function> process_tickDomainCallback;
104 static Persistent<Function> process_tickFromSpinner;
105 static Persistent<Function> process_tickCallback;
107 static Persistent<String> exports_symbol;
109 static Persistent<String> errno_symbol;
110 static Persistent<String> syscall_symbol;
111 static Persistent<String> errpath_symbol;
112 static Persistent<String> code_symbol;
114 static Persistent<String> rss_symbol;
115 static Persistent<String> heap_total_symbol;
116 static Persistent<String> heap_used_symbol;
118 static Persistent<String> fatal_exception_symbol;
120 static Persistent<String> enter_symbol;
121 static Persistent<String> exit_symbol;
122 static Persistent<String> disposed_symbol;
125 static bool print_eval = false;
126 static bool force_repl = false;
127 static bool trace_deprecation = false;
128 static char *eval_string = NULL;
129 static int option_end_index = 0;
130 static bool use_debug_agent = false;
131 static bool debug_wait_connect = false;
132 static int debug_port=5858;
133 static int max_stack_size = 0;
135 // used by C++ modules as well
136 bool no_deprecation = false;
138 static uv_idle_t tick_spinner;
139 static bool need_tick_cb;
140 static Persistent<String> tick_callback_sym;
142 static uv_check_t check_immediate_watcher;
143 static uv_idle_t idle_immediate_dummy;
144 static bool need_immediate_cb;
145 static Persistent<String> immediate_callback_sym;
147 // for quick ref to tickCallback values
154 #ifdef OPENSSL_NPN_NEGOTIATED
155 static bool use_npn = true;
157 static bool use_npn = false;
160 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
161 static bool use_sni = true;
163 static bool use_sni = false;
166 // process-relative uptime base, initialized at start-up
167 static double prog_start_time;
169 static volatile bool debugger_running = false;
170 static uv_async_t dispatch_debug_messages_async;
172 // Declared in node_internals.h
173 Isolate* node_isolate = NULL;
176 static void Spin(uv_idle_t* handle, int status) {
177 assert((uv_idle_t*) handle == &tick_spinner);
180 // Avoid entering a V8 scope.
181 if (!need_tick_cb) return;
182 need_tick_cb = false;
184 uv_idle_stop(&tick_spinner);
188 if (process_tickFromSpinner.IsEmpty()) {
189 Local<Value> cb_v = process->Get(String::New("_tickFromSpinner"));
190 if (!cb_v->IsFunction()) {
191 fprintf(stderr, "process._tickFromSpinner assigned to non-function\n");
194 Local<Function> cb = cb_v.As<Function>();
195 process_tickFromSpinner = Persistent<Function>::New(cb);
200 process_tickFromSpinner->Call(process, 0, NULL);
202 if (try_catch.HasCaught()) {
203 FatalException(try_catch);
208 static Handle<Value> NeedTickCallback(const Arguments& args) {
210 uv_idle_start(&tick_spinner, Spin);
215 static void CheckImmediate(uv_check_t* handle, int status) {
216 assert(handle == &check_immediate_watcher);
221 if (immediate_callback_sym.IsEmpty()) {
222 immediate_callback_sym = NODE_PSYMBOL("_immediateCallback");
225 MakeCallback(process, immediate_callback_sym, 0, NULL);
229 static void IdleImmediateDummy(uv_idle_t* handle, int status) {
230 // Do nothing. Only for maintaining event loop
231 assert(handle == &idle_immediate_dummy);
236 static inline const char *errno_string(int errorno) {
237 #define ERRNO_CASE(e) case e: return #e;
245 ERRNO_CASE(EADDRINUSE);
249 ERRNO_CASE(EADDRNOTAVAIL);
253 ERRNO_CASE(EAFNOSUPPORT);
261 # if EAGAIN != EWOULDBLOCK
262 ERRNO_CASE(EWOULDBLOCK);
267 ERRNO_CASE(EALREADY);
283 ERRNO_CASE(ECANCELED);
291 ERRNO_CASE(ECONNABORTED);
295 ERRNO_CASE(ECONNREFUSED);
299 ERRNO_CASE(ECONNRESET);
307 ERRNO_CASE(EDESTADDRREQ);
331 ERRNO_CASE(EHOSTUNREACH);
343 ERRNO_CASE(EINPROGRESS);
379 ERRNO_CASE(EMSGSIZE);
383 ERRNO_CASE(EMULTIHOP);
387 ERRNO_CASE(ENAMETOOLONG);
391 ERRNO_CASE(ENETDOWN);
395 ERRNO_CASE(ENETRESET);
399 ERRNO_CASE(ENETUNREACH);
431 # if ENOLINK != ENOLCK
445 ERRNO_CASE(ENOPROTOOPT);
465 ERRNO_CASE(ENOTCONN);
473 ERRNO_CASE(ENOTEMPTY);
477 ERRNO_CASE(ENOTSOCK);
484 ERRNO_CASE(EOPNOTSUPP);
498 ERRNO_CASE(EOVERFLOW);
513 #ifdef EPROTONOSUPPORT
514 ERRNO_CASE(EPROTONOSUPPORT);
518 ERRNO_CASE(EPROTOTYPE);
546 ERRNO_CASE(ETIMEDOUT);
561 const char *signo_string(int signo) {
562 #define SIGNO_CASE(e) case e: return #e;
590 # if SIGABRT != SIGIOT
634 SIGNO_CASE(SIGSTKFLT);
651 SIGNO_CASE(SIGBREAK);
675 SIGNO_CASE(SIGVTALRM);
683 SIGNO_CASE(SIGWINCH);
691 # if SIGPOLL != SIGIO
701 # if SIGPWR != SIGLOST
715 Local<Value> ErrnoException(int errorno,
720 Local<String> estring = String::NewSymbol(errno_string(errorno));
722 msg = strerror(errorno);
724 Local<String> message = String::NewSymbol(msg);
726 Local<String> cons1 = String::Concat(estring, String::NewSymbol(", "));
727 Local<String> cons2 = String::Concat(cons1, message);
729 if (syscall_symbol.IsEmpty()) {
730 syscall_symbol = NODE_PSYMBOL("syscall");
731 errno_symbol = NODE_PSYMBOL("errno");
732 errpath_symbol = NODE_PSYMBOL("path");
733 code_symbol = NODE_PSYMBOL("code");
737 Local<String> cons3 = String::Concat(cons2, String::NewSymbol(" '"));
738 Local<String> cons4 = String::Concat(cons3, String::New(path));
739 Local<String> cons5 = String::Concat(cons4, String::NewSymbol("'"));
740 e = Exception::Error(cons5);
742 e = Exception::Error(cons2);
745 Local<Object> obj = e->ToObject();
747 obj->Set(errno_symbol, Integer::New(errorno));
748 obj->Set(code_symbol, estring);
749 if (path) obj->Set(errpath_symbol, String::New(path));
750 if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
755 static const char* get_uv_errno_string(int errorno) {
757 memset(&err, 0, sizeof err);
758 err.code = (uv_err_code)errorno;
759 return uv_err_name(err);
763 static const char* get_uv_errno_message(int errorno) {
765 memset(&err, 0, sizeof err);
766 err.code = (uv_err_code)errorno;
767 return uv_strerror(err);
771 // hack alert! copy of ErrnoException, tuned for uv errors
772 Local<Value> UVException(int errorno,
776 if (syscall_symbol.IsEmpty()) {
777 syscall_symbol = NODE_PSYMBOL("syscall");
778 errno_symbol = NODE_PSYMBOL("errno");
779 errpath_symbol = NODE_PSYMBOL("path");
780 code_symbol = NODE_PSYMBOL("code");
784 msg = get_uv_errno_message(errorno);
786 Local<String> estring = String::NewSymbol(get_uv_errno_string(errorno));
787 Local<String> message = String::NewSymbol(msg);
788 Local<String> cons1 = String::Concat(estring, String::NewSymbol(", "));
789 Local<String> cons2 = String::Concat(cons1, message);
793 Local<String> path_str;
797 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
798 path_str = String::Concat(String::New("\\\\"), String::New(path + 8));
799 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
800 path_str = String::New(path + 4);
802 path_str = String::New(path);
805 path_str = String::New(path);
808 Local<String> cons3 = String::Concat(cons2, String::NewSymbol(" '"));
809 Local<String> cons4 = String::Concat(cons3, path_str);
810 Local<String> cons5 = String::Concat(cons4, String::NewSymbol("'"));
811 e = Exception::Error(cons5);
813 e = Exception::Error(cons2);
816 Local<Object> obj = e->ToObject();
818 // TODO errno should probably go
819 obj->Set(errno_symbol, Integer::New(errorno));
820 obj->Set(code_symbol, estring);
821 if (path) obj->Set(errpath_symbol, path_str);
822 if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
828 // Does about the same as strerror(),
829 // but supports all windows error messages
830 static const char *winapi_strerror(const int errorno) {
833 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
834 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
835 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
838 // Remove trailing newlines
839 for (int i = strlen(errmsg) - 1;
840 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
846 // FormatMessage failed
847 return "Unknown error";
852 Local<Value> WinapiErrnoException(int errorno,
857 if (!msg || !msg[0]) {
858 msg = winapi_strerror(errorno);
860 Local<String> message = String::NewSymbol(msg);
862 if (syscall_symbol.IsEmpty()) {
863 syscall_symbol = NODE_PSYMBOL("syscall");
864 errno_symbol = NODE_PSYMBOL("errno");
865 errpath_symbol = NODE_PSYMBOL("path");
866 code_symbol = NODE_PSYMBOL("code");
870 Local<String> cons1 = String::Concat(message, String::NewSymbol(" '"));
871 Local<String> cons2 = String::Concat(cons1, String::New(path));
872 Local<String> cons3 = String::Concat(cons2, String::NewSymbol("'"));
873 e = Exception::Error(cons3);
875 e = Exception::Error(message);
878 Local<Object> obj = e->ToObject();
880 obj->Set(errno_symbol, Integer::New(errorno));
881 if (path) obj->Set(errpath_symbol, String::New(path));
882 if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
888 Handle<Value> FromConstructorTemplate(Persistent<FunctionTemplate> t,
889 const Arguments& args) {
891 Local<Value> argv[32];
892 unsigned argc = args.Length();
893 if (argc > ARRAY_SIZE(argv)) argc = ARRAY_SIZE(argv);
894 for (unsigned i = 0; i < argc; ++i) argv[i] = args[i];
895 return scope.Close(t->GetFunction()->NewInstance(argc, argv));
900 MakeDomainCallback(const Handle<Object> object,
901 const Handle<Function> callback,
903 Handle<Value> argv[]) {
904 // lazy load _tickDomainCallback
905 if (process_tickDomainCallback.IsEmpty()) {
906 Local<Value> cb_v = process->Get(String::New("_tickDomainCallback"));
907 if (!cb_v->IsFunction()) {
908 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
911 Local<Function> cb = cb_v.As<Function>();
912 process_tickDomainCallback = Persistent<Function>::New(cb);
915 // lazy load domain specific symbols
916 if (enter_symbol.IsEmpty()) {
917 enter_symbol = NODE_PSYMBOL("enter");
918 exit_symbol = NODE_PSYMBOL("exit");
919 disposed_symbol = NODE_PSYMBOL("_disposed");
922 Local<Value> domain_v = object->Get(domain_symbol);
923 Local<Object> domain;
924 Local<Function> enter;
925 Local<Function> exit;
929 domain = domain_v->ToObject();
930 assert(!domain.IsEmpty());
931 if (domain->Get(disposed_symbol)->IsTrue()) {
932 // domain has been disposed of.
935 enter = Local<Function>::Cast(domain->Get(enter_symbol));
936 assert(!enter.IsEmpty());
937 enter->Call(domain, 0, NULL);
939 if (try_catch.HasCaught()) {
940 FatalException(try_catch);
944 Local<Value> ret = callback->Call(object, argc, argv);
946 if (try_catch.HasCaught()) {
947 FatalException(try_catch);
951 exit = Local<Function>::Cast(domain->Get(exit_symbol));
952 assert(!exit.IsEmpty());
953 exit->Call(domain, 0, NULL);
955 if (try_catch.HasCaught()) {
956 FatalException(try_catch);
960 if (tick_infobox.length == 0) {
961 tick_infobox.index = 0;
962 tick_infobox.depth = 0;
966 // process nextTicks after call
967 process_tickDomainCallback->Call(process, 0, NULL);
969 if (try_catch.HasCaught()) {
970 FatalException(try_catch);
979 MakeCallback(const Handle<Object> object,
980 const Handle<String> symbol,
982 Handle<Value> argv[]) {
985 Local<Function> callback = object->Get(symbol).As<Function>();
986 Local<Value> domain = object->Get(domain_symbol);
988 // TODO Hook for long stack traces to be made here.
990 // has domain, off with you
991 if (!domain->IsNull() && !domain->IsUndefined())
992 return scope.Close(MakeDomainCallback(object, callback, argc, argv));
994 // lazy load no domain next tick callbacks
995 if (process_tickCallback.IsEmpty()) {
996 Local<Value> cb_v = process->Get(String::New("_tickCallback"));
997 if (!cb_v->IsFunction()) {
998 fprintf(stderr, "process._tickCallback assigned to non-function\n");
1001 Local<Function> cb = cb_v.As<Function>();
1002 process_tickCallback = Persistent<Function>::New(cb);
1007 Local<Value> ret = callback->Call(object, argc, argv);
1009 if (try_catch.HasCaught()) {
1010 FatalException(try_catch);
1014 if (tick_infobox.length == 0) {
1015 tick_infobox.index = 0;
1016 tick_infobox.depth = 0;
1017 return scope.Close(ret);
1020 // process nextTicks after call
1021 process_tickCallback->Call(process, 0, NULL);
1023 if (try_catch.HasCaught()) {
1024 FatalException(try_catch);
1028 return scope.Close(ret);
1033 MakeCallback(const Handle<Object> object,
1036 Handle<Value> argv[]) {
1040 MakeCallback(object, String::NewSymbol(method), argc, argv);
1042 return scope.Close(ret);
1046 void SetErrno(uv_err_t err) {
1049 if (errno_symbol.IsEmpty()) {
1050 errno_symbol = NODE_PSYMBOL("errno");
1053 if (err.code == UV_UNKNOWN) {
1054 char errno_buf[100];
1055 snprintf(errno_buf, 100, "Unknown system errno %d", err.sys_errno_);
1056 Context::GetCurrent()->Global()->Set(errno_symbol, String::New(errno_buf));
1058 Context::GetCurrent()->Global()->Set(errno_symbol,
1059 String::NewSymbol(uv_err_name(err)));
1064 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1067 if (!encoding_v->IsString()) return _default;
1069 String::Utf8Value encoding(encoding_v);
1071 if (strcasecmp(*encoding, "utf8") == 0) {
1073 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1075 } else if (strcasecmp(*encoding, "ascii") == 0) {
1077 } else if (strcasecmp(*encoding, "base64") == 0) {
1079 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1081 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1083 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1085 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1087 } else if (strcasecmp(*encoding, "binary") == 0) {
1089 } else if (strcasecmp(*encoding, "buffer") == 0) {
1091 } else if (strcasecmp(*encoding, "hex") == 0) {
1093 } else if (strcasecmp(*encoding, "raw") == 0) {
1094 if (!no_deprecation) {
1095 fprintf(stderr, "'raw' (array of integers) has been removed. "
1099 } else if (strcasecmp(*encoding, "raws") == 0) {
1100 if (!no_deprecation) {
1101 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1102 "Please update your code.\n");
1110 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1113 if (encoding == BUFFER) {
1115 Buffer::New(static_cast<const char*>(buf), len)->handle_);
1118 if (!len) return scope.Close(String::Empty());
1120 if (encoding == BINARY) {
1121 const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
1122 uint16_t * twobytebuf = new uint16_t[len];
1123 for (size_t i = 0; i < len; i++) {
1124 // XXX is the following line platform independent?
1125 twobytebuf[i] = cbuf[i];
1127 Local<String> chunk = String::New(twobytebuf, len);
1128 delete [] twobytebuf; // TODO use ExternalTwoByteString?
1129 return scope.Close(chunk);
1132 // utf8 or ascii encoding
1133 Local<String> chunk = String::New((const char*)buf, len);
1134 return scope.Close(chunk);
1137 // Returns -1 if the handle was not valid for decoding
1138 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1141 if (val->IsArray()) {
1142 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1148 if ((encoding == BUFFER || encoding == BINARY) && Buffer::HasInstance(val)) {
1149 return Buffer::Length(val->ToObject());
1152 Local<String> str = val->ToString();
1154 if (encoding == UTF8) return str->Utf8Length();
1155 else if (encoding == UCS2) return str->Length() * 2;
1156 else if (encoding == HEX) return str->Length() / 2;
1158 return str->Length();
1162 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1165 // Returns number of bytes written.
1166 ssize_t DecodeWrite(char *buf,
1168 v8::Handle<v8::Value> val,
1169 enum encoding encoding) {
1173 // A lot of improvement can be made here. See:
1174 // http://code.google.com/p/v8/issues/detail?id=270
1175 // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
1176 // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
1178 if (val->IsArray()) {
1179 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1185 bool is_buffer = Buffer::HasInstance(val);
1187 if (is_buffer && (encoding == BINARY || encoding == BUFFER)) {
1188 // fast path, copy buffer data
1189 const char* data = Buffer::Data(val.As<Object>());
1190 size_t size = Buffer::Length(val.As<Object>());
1191 size_t len = size < buflen ? size : buflen;
1192 memcpy(buf, data, len);
1198 if (is_buffer) { // slow path, convert to binary string
1199 Local<Value> arg = String::New("binary");
1200 str = MakeCallback(val.As<Object>(), "toString", 1, &arg)->ToString();
1203 str = val->ToString();
1206 if (encoding == UTF8) {
1207 str->WriteUtf8(buf, buflen, NULL, String::HINT_MANY_WRITES_EXPECTED);
1211 if (encoding == ASCII) {
1212 str->WriteAscii(buf, 0, buflen, String::HINT_MANY_WRITES_EXPECTED);
1216 // THIS IS AWFUL!!! FIXME
1218 assert(encoding == BINARY);
1220 uint16_t * twobytebuf = new uint16_t[buflen];
1222 str->Write(twobytebuf, 0, buflen, String::HINT_MANY_WRITES_EXPECTED);
1224 for (size_t i = 0; i < buflen; i++) {
1225 unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
1229 delete [] twobytebuf;
1234 void DisplayExceptionLine (TryCatch &try_catch) {
1235 // Prevent re-entry into this function. For example, if there is
1236 // a throw from a program in vm.runInThisContext(code, filename, true),
1237 // then we want to show the original failure, not the secondary one.
1238 static bool displayed_error = false;
1240 if (displayed_error) return;
1241 displayed_error = true;
1245 Handle<Message> message = try_catch.Message();
1247 uv_tty_reset_mode();
1249 fprintf(stderr, "\n");
1251 if (!message.IsEmpty()) {
1252 // Print (filename):(line number): (message).
1253 String::Utf8Value filename(message->GetScriptResourceName());
1254 const char* filename_string = *filename;
1255 int linenum = message->GetLineNumber();
1256 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1257 // Print line of source code.
1258 String::Utf8Value sourceline(message->GetSourceLine());
1259 const char* sourceline_string = *sourceline;
1261 // Because of how node modules work, all scripts are wrapped with a
1262 // "function (module, exports, __filename, ...) {"
1263 // to provide script local variables.
1265 // When reporting errors on the first line of a script, this wrapper
1266 // function is leaked to the user. There used to be a hack here to
1267 // truncate off the first 62 characters, but it caused numerous other
1268 // problems when vm.runIn*Context() methods were used for non-module
1271 // If we ever decide to re-instate such a hack, the following steps
1274 // 1. Pass a flag around to say "this code was wrapped"
1275 // 2. Update the stack frame output so that it is also correct.
1277 // It would probably be simpler to add a line rather than add some
1278 // number of characters to the first line, since V8 truncates the
1279 // sourceline to 78 characters, and we end up not providing very much
1280 // useful debugging info to the user if we remove 62 characters.
1282 int start = message->GetStartColumn();
1283 int end = message->GetEndColumn();
1285 // fprintf(stderr, "---\nsourceline:%s\noffset:%d\nstart:%d\nend:%d\n---\n", sourceline_string, start, end);
1287 fprintf(stderr, "%s\n", sourceline_string);
1288 // Print wavy underline (GetUnderline is deprecated).
1289 for (int i = 0; i < start; i++) {
1290 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1292 for (int i = start; i < end; i++) {
1295 fputc('\n', stderr);
1300 static void ReportException(TryCatch &try_catch, bool show_line) {
1303 if (show_line) DisplayExceptionLine(try_catch);
1305 String::Utf8Value trace(try_catch.StackTrace());
1307 // range errors have a trace member set to undefined
1308 if (trace.length() > 0 && !try_catch.StackTrace()->IsUndefined()) {
1309 fprintf(stderr, "%s\n", *trace);
1311 // this really only happens for RangeErrors, since they're the only
1312 // kind that won't have all this info in the trace, or when non-Error
1313 // objects are thrown manually.
1314 Local<Value> er = try_catch.Exception();
1315 bool isErrorObject = er->IsObject() &&
1316 !(er->ToObject()->Get(String::New("message"))->IsUndefined()) &&
1317 !(er->ToObject()->Get(String::New("name"))->IsUndefined());
1319 if (isErrorObject) {
1320 String::Utf8Value name(er->ToObject()->Get(String::New("name")));
1321 fprintf(stderr, "%s: ", *name);
1324 String::Utf8Value msg(!isErrorObject ? er
1325 : er->ToObject()->Get(String::New("message")));
1326 fprintf(stderr, "%s\n", *msg);
1332 // Executes a str within the current v8 context.
1333 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1337 Local<v8::Script> script = v8::Script::Compile(source, filename);
1338 if (script.IsEmpty()) {
1339 ReportException(try_catch, true);
1343 Local<Value> result = script->Run();
1344 if (result.IsEmpty()) {
1345 ReportException(try_catch, true);
1349 return scope.Close(result);
1353 static Handle<Value> GetActiveRequests(const Arguments& args) {
1356 Local<Array> ary = Array::New();
1357 ngx_queue_t* q = NULL;
1360 ngx_queue_foreach(q, &req_wrap_queue) {
1361 ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1362 if (w->object_.IsEmpty()) continue;
1363 ary->Set(i++, w->object_);
1366 return scope.Close(ary);
1370 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1371 // implemented here for consistency with GetActiveRequests().
1372 Handle<Value> GetActiveHandles(const Arguments& args) {
1375 Local<Array> ary = Array::New();
1376 ngx_queue_t* q = NULL;
1379 Local<String> owner_sym = String::New("owner");
1381 ngx_queue_foreach(q, &handle_wrap_queue) {
1382 HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1383 if (w->object_.IsEmpty() || w->unref_) continue;
1384 Local<Value> obj = w->object_->Get(owner_sym);
1385 if (obj->IsUndefined()) obj = *w->object_;
1389 return scope.Close(ary);
1393 static Handle<Value> Abort(const Arguments& args) {
1399 static Handle<Value> Chdir(const Arguments& args) {
1402 if (args.Length() != 1 || !args[0]->IsString()) {
1403 return ThrowException(Exception::Error(String::New("Bad argument.")));
1406 String::Utf8Value path(args[0]);
1408 uv_err_t r = uv_chdir(*path);
1410 if (r.code != UV_OK) {
1411 return ThrowException(UVException(r.code, "uv_chdir"));
1418 static Handle<Value> Cwd(const Arguments& args) {
1421 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1422 char buf[MAX_PATH * 4 + 1];
1424 char buf[PATH_MAX + 1];
1427 uv_err_t r = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1428 if (r.code != UV_OK) {
1429 return ThrowException(UVException(r.code, "uv_cwd"));
1432 buf[ARRAY_SIZE(buf) - 1] = '\0';
1433 Local<String> cwd = String::New(buf);
1435 return scope.Close(cwd);
1439 static Handle<Value> Umask(const Arguments& args) {
1443 if (args.Length() < 1 || args[0]->IsUndefined()) {
1447 } else if(!args[0]->IsInt32() && !args[0]->IsString()) {
1448 return ThrowException(Exception::TypeError(
1449 String::New("argument must be an integer or octal string.")));
1453 if(args[0]->IsInt32()) {
1454 oct = args[0]->Uint32Value();
1457 String::Utf8Value str(args[0]);
1459 // Parse the octal string.
1460 for (int i = 0; i < str.length(); i++) {
1462 if (c > '7' || c < '0') {
1463 return ThrowException(Exception::TypeError(
1464 String::New("invalid octal string")));
1470 old = umask(static_cast<mode_t>(oct));
1473 return scope.Close(Uint32::New(old));
1479 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1480 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1483 static uid_t uid_by_name(const char* name) {
1492 if ((rc = getpwnam_r(name, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1496 return uid_not_found;
1500 static char* name_by_uid(uid_t uid) {
1509 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1510 return strdup(pp->pw_name);
1521 static gid_t gid_by_name(const char* name) {
1530 if ((rc = getgrnam_r(name, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1534 return gid_not_found;
1538 #if 0 // For future use.
1539 static const char* name_by_gid(gid_t gid) {
1548 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1549 return strdup(pp->gr_name);
1561 static uid_t uid_by_name(Handle<Value> value) {
1562 if (value->IsUint32()) {
1563 return static_cast<uid_t>(value->Uint32Value());
1565 String::Utf8Value name(value);
1566 return uid_by_name(*name);
1571 static gid_t gid_by_name(Handle<Value> value) {
1572 if (value->IsUint32()) {
1573 return static_cast<gid_t>(value->Uint32Value());
1575 String::Utf8Value name(value);
1576 return gid_by_name(*name);
1581 static Handle<Value> GetUid(const Arguments& args) {
1584 return scope.Close(Integer::New(uid));
1588 static Handle<Value> GetGid(const Arguments& args) {
1591 return scope.Close(Integer::New(gid));
1595 static Handle<Value> SetGid(const Arguments& args) {
1598 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1599 return ThrowTypeError("setgid argument must be a number or a string");
1602 gid_t gid = gid_by_name(args[0]);
1604 if (gid == gid_not_found) {
1605 return ThrowError("setgid group id does not exist");
1609 return ThrowException(ErrnoException(errno, "setgid"));
1616 static Handle<Value> SetUid(const Arguments& args) {
1619 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1620 return ThrowTypeError("setuid argument must be a number or a string");
1623 uid_t uid = uid_by_name(args[0]);
1625 if (uid == uid_not_found) {
1626 return ThrowError("setuid user id does not exist");
1630 return ThrowException(ErrnoException(errno, "setuid"));
1637 static Handle<Value> GetGroups(const Arguments& args) {
1640 int ngroups = getgroups(0, NULL);
1642 if (ngroups == -1) {
1643 return ThrowException(ErrnoException(errno, "getgroups"));
1646 gid_t* groups = new gid_t[ngroups];
1648 ngroups = getgroups(ngroups, groups);
1650 if (ngroups == -1) {
1652 return ThrowException(ErrnoException(errno, "getgroups"));
1655 Local<Array> groups_list = Array::New(ngroups);
1656 bool seen_egid = false;
1657 gid_t egid = getegid();
1659 for (int i = 0; i < ngroups; i++) {
1660 groups_list->Set(i, Integer::New(groups[i]));
1661 if (groups[i] == egid) seen_egid = true;
1666 if (seen_egid == false) {
1667 groups_list->Set(ngroups, Integer::New(egid));
1670 return scope.Close(groups_list);
1674 static Handle<Value> SetGroups(const Arguments& args) {
1677 if (!args[0]->IsArray()) {
1678 return ThrowTypeError("argument 1 must be an array");
1681 Local<Array> groups_list = args[0].As<Array>();
1682 size_t size = groups_list->Length();
1683 gid_t* groups = new gid_t[size];
1685 for (size_t i = 0; i < size; i++) {
1686 gid_t gid = gid_by_name(groups_list->Get(i));
1688 if (gid == gid_not_found) {
1690 return ThrowError("group name not found");
1696 int rc = setgroups(size, groups);
1700 return ThrowException(ErrnoException(errno, "setgroups"));
1707 static Handle<Value> InitGroups(const Arguments& args) {
1710 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1711 return ThrowTypeError("argument 1 must be a number or a string");
1714 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1715 return ThrowTypeError("argument 2 must be a number or a string");
1718 String::Utf8Value arg0(args[0]);
1723 if (args[0]->IsUint32()) {
1724 user = name_by_uid(args[0]->Uint32Value());
1732 return ThrowError("initgroups user not found");
1735 extra_group = gid_by_name(args[1]);
1737 if (extra_group == gid_not_found) {
1738 if (must_free) free(user);
1739 return ThrowError("initgroups extra group not found");
1742 int rc = initgroups(user, extra_group);
1749 return ThrowException(ErrnoException(errno, "initgroups"));
1758 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
1760 exit(args[0]->IntegerValue());
1765 static Handle<Value> Uptime(const Arguments& args) {
1769 uv_err_t err = uv_uptime(&uptime);
1771 if (err.code != UV_OK) {
1775 return scope.Close(Number::New(uptime - prog_start_time));
1779 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
1784 uv_err_t err = uv_resident_set_memory(&rss);
1786 if (err.code != UV_OK) {
1787 return ThrowException(UVException(err.code, "uv_resident_set_memory"));
1790 Local<Object> info = Object::New();
1792 if (rss_symbol.IsEmpty()) {
1793 rss_symbol = NODE_PSYMBOL("rss");
1794 heap_total_symbol = NODE_PSYMBOL("heapTotal");
1795 heap_used_symbol = NODE_PSYMBOL("heapUsed");
1798 info->Set(rss_symbol, Number::New(rss));
1801 HeapStatistics v8_heap_stats;
1802 V8::GetHeapStatistics(&v8_heap_stats);
1803 info->Set(heap_total_symbol,
1804 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
1805 info->Set(heap_used_symbol,
1806 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
1808 return scope.Close(info);
1812 Handle<Value> Kill(const Arguments& args) {
1815 if (args.Length() != 2) {
1816 return ThrowException(Exception::Error(String::New("Bad argument.")));
1819 int pid = args[0]->IntegerValue();
1820 int sig = args[1]->Int32Value();
1821 uv_err_t err = uv_kill(pid, sig);
1823 if (err.code != UV_OK) {
1825 return scope.Close(Integer::New(-1));
1831 // used in Hrtime() below
1832 #define NANOS_PER_SEC 1000000000
1834 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1835 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1836 // so this function instead returns an Array with 2 entries representing seconds
1837 // and nanoseconds, to avoid any integer overflow possibility.
1838 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1839 Handle<Value> Hrtime(const v8::Arguments& args) {
1842 uint64_t t = uv_hrtime();
1844 if (args.Length() > 0) {
1845 // return a time diff tuple
1846 if (!args[0]->IsArray()) {
1847 Local<Value> exception = Exception::TypeError(
1848 String::New("process.hrtime() only accepts an Array tuple."));
1849 return ThrowException(exception);
1851 Local<Array> inArray = Local<Array>::Cast(args[0]);
1852 uint64_t seconds = inArray->Get(0)->Uint32Value();
1853 uint64_t nanos = inArray->Get(1)->Uint32Value();
1854 t -= (seconds * NANOS_PER_SEC) + nanos;
1857 Local<Array> tuple = Array::New(2);
1858 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC));
1859 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC));
1861 return scope.Close(tuple);
1865 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1867 // DLOpen is process.dlopen(module, filename).
1868 // Used to load 'module.node' dynamically shared objects.
1869 Handle<Value> DLOpen(const v8::Arguments& args) {
1871 char symbol[1024], *base, *pos;
1875 if (args.Length() < 2) {
1876 Local<Value> exception = Exception::Error(
1877 String::New("process.dlopen takes exactly 2 arguments."));
1878 return ThrowException(exception);
1881 Local<Object> module = args[0]->ToObject(); // Cast
1882 String::Utf8Value filename(args[1]); // Cast
1884 if (exports_symbol.IsEmpty()) {
1885 exports_symbol = NODE_PSYMBOL("exports");
1887 Local<Object> exports = module->Get(exports_symbol)->ToObject();
1889 if (uv_dlopen(*filename, &lib)) {
1890 Local<String> errmsg = String::New(uv_dlerror(&lib));
1892 // Windows needs to add the filename into the error message
1893 errmsg = String::Concat(errmsg, args[0]->ToString());
1895 return ThrowException(Exception::Error(errmsg));
1898 String::Utf8Value path(args[1]);
1901 /* Find the shared library filename within the full path. */
1903 pos = strrchr(base, '/');
1909 pos = strpbrk(base, "\\/:");
1917 /* Strip the .node extension. */
1918 pos = strrchr(base, '.');
1923 /* Add the `_module` suffix to the extension name. */
1924 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1925 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1926 Local<Value> exception =
1927 Exception::Error(String::New("Out of memory."));
1928 return ThrowException(exception);
1931 /* Replace dashes with underscores. When loading foo-bar.node,
1932 * look for foo_bar_module, not foo-bar_module.
1934 for (pos = symbol; *pos != '\0'; ++pos) {
1935 if (*pos == '-') *pos = '_';
1938 node_module_struct *mod;
1939 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1941 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1942 return ThrowError(errmsg);
1945 if (mod->version != NODE_MODULE_VERSION) {
1949 "Module version mismatch. Expected %d, got %d.",
1950 NODE_MODULE_VERSION, mod->version);
1951 return ThrowError(errmsg);
1954 // Execute the C++ module
1955 mod->register_func(exports, module);
1957 // Tell coverity that 'handle' should not be freed when we return.
1958 // coverity[leaked_storage]
1963 static void OnFatalError(const char* location, const char* message) {
1965 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1967 fprintf(stderr, "FATAL ERROR: %s\n", message);
1972 void FatalException(TryCatch &try_catch) {
1975 if (fatal_exception_symbol.IsEmpty())
1976 fatal_exception_symbol = NODE_PSYMBOL("_fatalException");
1978 Local<Value> fatal_v = process->Get(fatal_exception_symbol);
1980 if (!fatal_v->IsFunction()) {
1981 // failed before the process._fatalException function was added!
1982 // this is probably pretty bad. Nothing to do but report and exit.
1983 ReportException(try_catch, true);
1987 Local<Function> fatal_f = Local<Function>::Cast(fatal_v);
1989 Local<Value> error = try_catch.Exception();
1990 Local<Value> argv[] = { error };
1992 TryCatch fatal_try_catch;
1994 // this will return true if the JS layer handled it, false otherwise
1995 Local<Value> caught = fatal_f->Call(process, ARRAY_SIZE(argv), argv);
1997 if (fatal_try_catch.HasCaught()) {
1998 // the fatal exception function threw, so we must exit
1999 ReportException(fatal_try_catch, true);
2003 if (false == caught->BooleanValue()) {
2004 ReportException(try_catch, true);
2010 Persistent<Object> binding_cache;
2011 Persistent<Array> module_load_list;
2013 static Handle<Value> Binding(const Arguments& args) {
2016 Local<String> module = args[0]->ToString();
2017 String::Utf8Value module_v(module);
2018 node_module_struct* modp;
2020 if (binding_cache.IsEmpty()) {
2021 binding_cache = Persistent<Object>::New(Object::New());
2024 Local<Object> exports;
2026 if (binding_cache->Has(module)) {
2027 exports = binding_cache->Get(module)->ToObject();
2028 return scope.Close(exports);
2031 // Append a string to process.moduleLoadList
2033 snprintf(buf, 1024, "Binding %s", *module_v);
2034 uint32_t l = module_load_list->Length();
2035 module_load_list->Set(l, String::New(buf));
2037 if ((modp = get_builtin_module(*module_v)) != NULL) {
2038 exports = Object::New();
2039 // Internal bindings don't have a "module" object,
2041 modp->register_func(exports, Undefined());
2042 binding_cache->Set(module, exports);
2044 } else if (!strcmp(*module_v, "constants")) {
2045 exports = Object::New();
2046 DefineConstants(exports);
2047 binding_cache->Set(module, exports);
2049 } else if (!strcmp(*module_v, "natives")) {
2050 exports = Object::New();
2051 DefineJavaScript(exports);
2052 binding_cache->Set(module, exports);
2056 return ThrowException(Exception::Error(String::New("No such module")));
2059 return scope.Close(exports);
2063 static Handle<Value> ProcessTitleGetter(Local<String> property,
2064 const AccessorInfo& info) {
2067 uv_get_process_title(buffer, sizeof(buffer));
2068 return scope.Close(String::New(buffer));
2072 static void ProcessTitleSetter(Local<String> property,
2074 const AccessorInfo& info) {
2076 String::Utf8Value title(value);
2077 // TODO: protect with a lock
2078 uv_set_process_title(*title);
2082 static Handle<Value> EnvGetter(Local<String> property,
2083 const AccessorInfo& info) {
2086 String::Utf8Value key(property);
2087 const char* val = getenv(*key);
2089 return scope.Close(String::New(val));
2092 String::Value key(property);
2093 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2094 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2096 ARRAY_SIZE(buffer));
2097 // If result >= sizeof buffer the buffer was too small. That should never
2098 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2100 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2101 result < ARRAY_SIZE(buffer)) {
2102 return scope.Close(String::New(reinterpret_cast<uint16_t*>(buffer), result));
2105 // Not found. Fetch from prototype.
2106 return scope.Close(info.Data().As<Object>()->Get(property));
2110 static Handle<Value> EnvSetter(Local<String> property,
2112 const AccessorInfo& info) {
2115 String::Utf8Value key(property);
2116 String::Utf8Value val(value);
2117 setenv(*key, *val, 1);
2119 String::Value key(property);
2120 String::Value val(value);
2121 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2122 // Environment variables that start with '=' are read-only.
2123 if (key_ptr[0] != L'=') {
2124 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2127 // Whether it worked or not, always return rval.
2128 return scope.Close(value);
2132 static Handle<Integer> EnvQuery(Local<String> property,
2133 const AccessorInfo& info) {
2136 String::Utf8Value key(property);
2138 return scope.Close(Integer::New(0));
2141 String::Value key(property);
2142 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2143 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2144 GetLastError() == ERROR_SUCCESS) {
2145 if (key_ptr[0] == L'=') {
2146 // Environment variables that start with '=' are hidden and read-only.
2147 return scope.Close(Integer::New(v8::ReadOnly ||
2151 return scope.Close(Integer::New(0));
2156 return scope.Close(Handle<Integer>());
2160 static Handle<Boolean> EnvDeleter(Local<String> property,
2161 const AccessorInfo& info) {
2164 String::Utf8Value key(property);
2165 if (!getenv(*key)) return False();
2166 unsetenv(*key); // can't check return value, it's void on some platforms
2169 String::Value key(property);
2170 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2171 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2172 // Deletion failed. Return true if the key wasn't there in the first place,
2173 // false if it is still there.
2174 bool rv = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2175 GetLastError() != ERROR_SUCCESS;
2176 return scope.Close(Boolean::New(rv));
2183 static Handle<Array> EnvEnumerator(const AccessorInfo& info) {
2187 while (environ[size]) size++;
2189 Local<Array> env = Array::New(size);
2191 for (int i = 0; i < size; ++i) {
2192 const char* var = environ[i];
2193 const char* s = strchr(var, '=');
2194 const int length = s ? s - var : strlen(var);
2195 env->Set(i, String::New(var, length));
2198 WCHAR* environment = GetEnvironmentStringsW();
2199 if (environment == NULL) {
2200 // This should not happen.
2201 return scope.Close(Handle<Array>());
2203 Local<Array> env = Array::New();
2204 WCHAR* p = environment;
2206 while (*p != NULL) {
2209 // If the key starts with '=' it is a hidden environment variable.
2213 s = wcschr(p, L'=');
2218 env->Set(i++, String::New(reinterpret_cast<uint16_t*>(p), s - p));
2219 p = s + wcslen(s) + 1;
2221 FreeEnvironmentStringsW(environment);
2223 return scope.Close(env);
2227 static Handle<Object> GetFeatures() {
2230 Local<Object> obj = Object::New();
2231 obj->Set(String::NewSymbol("debug"),
2232 #if defined(DEBUG) && DEBUG
2239 obj->Set(String::NewSymbol("uv"), True());
2240 obj->Set(String::NewSymbol("ipv6"), True()); // TODO ping libuv
2241 obj->Set(String::NewSymbol("tls_npn"), Boolean::New(use_npn));
2242 obj->Set(String::NewSymbol("tls_sni"), Boolean::New(use_sni));
2243 obj->Set(String::NewSymbol("tls"),
2244 Boolean::New(get_builtin_module("crypto") != NULL));
2246 return scope.Close(obj);
2250 static Handle<Value> DebugPortGetter(Local<String> property,
2251 const AccessorInfo& info) {
2253 return scope.Close(Integer::NewFromUnsigned(debug_port));
2257 static void DebugPortSetter(Local<String> property,
2259 const AccessorInfo& info) {
2261 debug_port = value->NumberValue();
2265 static Handle<Value> DebugProcess(const Arguments& args);
2266 static Handle<Value> DebugPause(const Arguments& args);
2267 static Handle<Value> DebugEnd(const Arguments& args);
2270 Handle<Value> NeedImmediateCallbackGetter(Local<String> property,
2271 const AccessorInfo& info) {
2272 return Boolean::New(need_immediate_cb);
2276 static void NeedImmediateCallbackSetter(Local<String> property,
2278 const AccessorInfo& info) {
2281 bool bool_value = value->BooleanValue();
2283 if (need_immediate_cb == bool_value) return;
2285 need_immediate_cb = bool_value;
2287 if (need_immediate_cb) {
2288 uv_check_start(&check_immediate_watcher, node::CheckImmediate);
2289 // idle handle is needed only to maintain event loop
2290 uv_idle_start(&idle_immediate_dummy, node::IdleImmediateDummy);
2292 uv_check_stop(&check_immediate_watcher);
2293 uv_idle_stop(&idle_immediate_dummy);
2298 Handle<Object> SetupProcessObject(int argc, char *argv[]) {
2303 Local<FunctionTemplate> process_template = FunctionTemplate::New();
2305 process_template->SetClassName(String::NewSymbol("process"));
2307 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
2309 process->SetAccessor(String::New("title"),
2311 ProcessTitleSetter);
2314 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
2316 // process.moduleLoadList
2317 module_load_list = Persistent<Array>::New(Array::New());
2318 process->Set(String::NewSymbol("moduleLoadList"), module_load_list);
2321 Local<Object> versions = Object::New();
2322 process->Set(String::NewSymbol("versions"), versions);
2323 versions->Set(String::NewSymbol("http_parser"), String::New(
2324 NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR) "."
2325 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR)));
2326 // +1 to get rid of the leading 'v'
2327 versions->Set(String::NewSymbol("node"), String::New(NODE_VERSION+1));
2328 versions->Set(String::NewSymbol("v8"), String::New(V8::GetVersion()));
2329 versions->Set(String::NewSymbol("ares"), String::New(ARES_VERSION_STR));
2330 versions->Set(String::NewSymbol("uv"), String::New(
2331 NODE_STRINGIFY(UV_VERSION_MAJOR) "."
2332 NODE_STRINGIFY(UV_VERSION_MINOR)));
2333 versions->Set(String::NewSymbol("zlib"), String::New(ZLIB_VERSION));
2335 // Stupid code to slice out the version string.
2336 int c, l = strlen(OPENSSL_VERSION_TEXT);
2337 for (i = j = 0; i < l; i++) {
2338 c = OPENSSL_VERSION_TEXT[i];
2339 if ('0' <= c && c <= '9') {
2340 for (j = i + 1; j < l; j++) {
2341 c = OPENSSL_VERSION_TEXT[j];
2342 if (c == ' ') break;
2347 versions->Set(String::NewSymbol("openssl"),
2348 String::New(OPENSSL_VERSION_TEXT + i, j - i));
2354 process->Set(String::NewSymbol("arch"), String::New(ARCH));
2357 process->Set(String::NewSymbol("platform"), String::New(PLATFORM));
2360 Local<Array> arguments = Array::New(argc - option_end_index + 1);
2361 arguments->Set(Integer::New(0), String::New(argv[0]));
2362 for (j = 1, i = option_end_index; i < argc; j++, i++) {
2363 Local<String> arg = String::New(argv[i]);
2364 arguments->Set(Integer::New(j), arg);
2367 process->Set(String::NewSymbol("argv"), arguments);
2370 Local<Array> execArgv = Array::New(option_end_index - 1);
2371 for (j = 1, i = 0; j < option_end_index; j++, i++) {
2372 execArgv->Set(Integer::New(i), String::New(argv[j]));
2375 process->Set(String::NewSymbol("execArgv"), execArgv);
2378 // create process.env
2379 Local<ObjectTemplate> envTemplate = ObjectTemplate::New();
2380 envTemplate->SetNamedPropertyHandler(EnvGetter,
2386 Local<Object> env = envTemplate->NewInstance();
2387 process->Set(String::NewSymbol("env"), env);
2389 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
2390 process->Set(String::NewSymbol("features"), GetFeatures());
2391 process->SetAccessor(String::New("_needImmediateCallback"),
2392 NeedImmediateCallbackGetter,
2393 NeedImmediateCallbackSetter);
2397 process->Set(String::NewSymbol("_eval"), String::New(eval_string));
2402 process->Set(String::NewSymbol("_print_eval"), True());
2405 // -i, --interactive
2407 process->Set(String::NewSymbol("_forceRepl"), True());
2411 if (no_deprecation) {
2412 process->Set(String::NewSymbol("noDeprecation"), True());
2415 // --trace-deprecation
2416 if (trace_deprecation) {
2417 process->Set(String::NewSymbol("traceDeprecation"), True());
2420 size_t size = 2*PATH_MAX;
2421 char* execPath = new char[size];
2422 if (uv_exepath(execPath, &size) != 0) {
2423 // as a last ditch effort, fallback on argv[0] ?
2424 process->Set(String::NewSymbol("execPath"), String::New(argv[0]));
2426 process->Set(String::NewSymbol("execPath"), String::New(execPath, size));
2430 process->SetAccessor(String::New("debugPort"),
2435 // define various internal methods
2436 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2437 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2438 NODE_SET_METHOD(process, "_needTickCallback", NeedTickCallback);
2439 NODE_SET_METHOD(process, "reallyExit", Exit);
2440 NODE_SET_METHOD(process, "abort", Abort);
2441 NODE_SET_METHOD(process, "chdir", Chdir);
2442 NODE_SET_METHOD(process, "cwd", Cwd);
2444 NODE_SET_METHOD(process, "umask", Umask);
2447 NODE_SET_METHOD(process, "getuid", GetUid);
2448 NODE_SET_METHOD(process, "setuid", SetUid);
2450 NODE_SET_METHOD(process, "setgid", SetGid);
2451 NODE_SET_METHOD(process, "getgid", GetGid);
2453 NODE_SET_METHOD(process, "getgroups", GetGroups);
2454 NODE_SET_METHOD(process, "setgroups", SetGroups);
2455 NODE_SET_METHOD(process, "initgroups", InitGroups);
2458 NODE_SET_METHOD(process, "_kill", Kill);
2460 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2461 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2462 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2464 NODE_SET_METHOD(process, "hrtime", Hrtime);
2466 NODE_SET_METHOD(process, "dlopen", DLOpen);
2468 NODE_SET_METHOD(process, "uptime", Uptime);
2469 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2471 NODE_SET_METHOD(process, "binding", Binding);
2473 // values use to cross communicate with processNextTick
2474 Local<Object> info_box = Object::New();
2475 info_box->SetIndexedPropertiesToExternalArrayData(&tick_infobox,
2476 kExternalUnsignedIntArray,
2478 process->Set(String::NewSymbol("_tickInfoBox"), info_box);
2484 static void AtExit() {
2485 uv_tty_reset_mode();
2489 static void SignalExit(int signal) {
2490 uv_tty_reset_mode();
2491 _exit(128 + signal);
2495 void Load(Handle<Object> process_l) {
2496 process_symbol = NODE_PSYMBOL("process");
2497 domain_symbol = NODE_PSYMBOL("domain");
2499 // Compile, execute the src/node.js file. (Which was included as static C
2500 // string in node_natives.h. 'natve_node' is the string containing that
2503 // The node.js file returns a function 'f'
2508 Local<Value> f_value = ExecuteString(MainSource(),
2509 IMMUTABLE_STRING("node.js"));
2510 if (try_catch.HasCaught()) {
2511 ReportException(try_catch, true);
2514 assert(f_value->IsFunction());
2515 Local<Function> f = Local<Function>::Cast(f_value);
2517 // Now we call 'f' with the 'process' variable that we've built up with
2518 // all our bindings. Inside node.js we'll take care of assigning things to
2521 // We start the process this way in order to be more modular. Developers
2522 // who do not like how 'src/node.js' setups the module system but do like
2523 // Node's I/O bindings may want to replace 'f' with their own function.
2525 // Add a reference to the global object
2526 Local<Object> global = v8::Context::GetCurrent()->Global();
2527 Local<Value> args[1] = { Local<Value>::New(process_l) };
2529 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2533 #if defined HAVE_PERFCTR
2534 InitPerfCounters(global);
2537 f->Call(global, 1, args);
2539 if (try_catch.HasCaught()) {
2540 FatalException(try_catch);
2544 static void PrintHelp();
2546 static void ParseDebugOpt(const char* arg) {
2549 use_debug_agent = true;
2550 if (!strcmp (arg, "--debug-brk")) {
2551 debug_wait_connect = true;
2553 } else if (!strcmp(arg, "--debug")) {
2555 } else if (strstr(arg, "--debug-brk=") == arg) {
2556 debug_wait_connect = true;
2557 p = 1 + strchr(arg, '=');
2558 debug_port = atoi(p);
2559 } else if (strstr(arg, "--debug=") == arg) {
2560 p = 1 + strchr(arg, '=');
2561 debug_port = atoi(p);
2563 if (p && debug_port > 1024 && debug_port < 65536)
2566 fprintf(stderr, "Bad debug option.\n");
2567 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2573 static void PrintHelp() {
2574 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2575 " node debug script.js [arguments] \n"
2578 " -v, --version print node's version\n"
2579 " -e, --eval script evaluate script\n"
2580 " -p, --print evaluate script and print result\n"
2581 " -i, --interactive always enter the REPL even if stdin\n"
2582 " does not appear to be a terminal\n"
2583 " --no-deprecation silence deprecation warnings\n"
2584 " --trace-deprecation show stack traces on deprecations\n"
2585 " --v8-options print v8 command line options\n"
2586 " --max-stack-size=val set max v8 stack size (bytes)\n"
2588 "Environment variables:\n"
2590 "NODE_PATH ';'-separated list of directories\n"
2592 "NODE_PATH ':'-separated list of directories\n"
2594 " prefixed to the module search path.\n"
2595 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2596 " global contexts.\n"
2597 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2599 "Documentation can be found at http://nodejs.org/\n");
2602 // Parse node command line arguments.
2603 static void ParseArgs(int argc, char **argv) {
2606 // TODO use parse opts
2607 for (i = 1; i < argc; i++) {
2608 const char *arg = argv[i];
2609 if (strstr(arg, "--debug") == arg) {
2611 argv[i] = const_cast<char*>("");
2612 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2613 printf("%s\n", NODE_VERSION);
2615 } else if (strstr(arg, "--max-stack-size=") == arg) {
2617 p = 1 + strchr(arg, '=');
2618 max_stack_size = atoi(p);
2619 argv[i] = const_cast<char*>("");
2620 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2623 } else if (strcmp(arg, "--eval") == 0 ||
2624 strcmp(arg, "-e") == 0 ||
2625 strcmp(arg, "--print") == 0 ||
2626 strcmp(arg, "-pe") == 0 ||
2627 strcmp(arg, "-p") == 0) {
2628 bool is_eval = strchr(arg, 'e') != NULL;
2629 bool is_print = strchr(arg, 'p') != NULL;
2631 // argument to -p and --print is optional
2632 if (is_eval == true && i + 1 >= argc) {
2633 fprintf(stderr, "Error: %s requires an argument\n", arg);
2637 print_eval = print_eval || is_print;
2638 argv[i] = const_cast<char*>("");
2640 // --eval, -e and -pe always require an argument
2641 if (is_eval == true) {
2642 eval_string = argv[++i];
2646 // next arg is the expression to evaluate unless it starts with:
2647 // - a dash, then it's another switch
2648 // - "\\-", then it's an escaped expression, drop the backslash
2649 if (argv[i + 1] == NULL) continue;
2650 if (argv[i + 1][0] == '-') continue;
2651 eval_string = argv[++i];
2652 if (strncmp(eval_string, "\\-", 2) == 0) ++eval_string;
2653 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2655 argv[i] = const_cast<char*>("");
2656 } else if (strcmp(arg, "--v8-options") == 0) {
2657 argv[i] = const_cast<char*>("--help");
2658 } else if (strcmp(arg, "--no-deprecation") == 0) {
2659 argv[i] = const_cast<char*>("");
2660 no_deprecation = true;
2661 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2662 argv[i] = const_cast<char*>("");
2663 trace_deprecation = true;
2664 } else if (argv[i][0] != '-') {
2669 option_end_index = i;
2673 // Called from the main thread.
2674 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2675 v8::Debug::ProcessDebugMessages();
2679 // Called from V8 Debug Agent TCP thread.
2680 static void DispatchMessagesDebugAgentCallback() {
2681 uv_async_send(&dispatch_debug_messages_async);
2685 static void EnableDebug(bool wait_connect) {
2686 // If we're called from another thread, make sure to enter the right
2688 node_isolate->Enter();
2690 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2693 uv_async_init(uv_default_loop(),
2694 &dispatch_debug_messages_async,
2695 DispatchDebugMessagesAsyncCallback);
2696 uv_unref((uv_handle_t*) &dispatch_debug_messages_async);
2698 // Start the debug thread and it's associated TCP server on port 5858.
2699 bool r = v8::Debug::EnableAgent("node " NODE_VERSION,
2703 // Crappy check that everything went well. FIXME
2706 // Print out some information.
2707 fprintf(stderr, "debugger listening on port %d\n", debug_port);
2710 debugger_running = true;
2712 node_isolate->Exit();
2717 static void EnableDebugSignalHandler(uv_signal_t* handle, int) {
2718 // Break once process will return execution to v8
2719 v8::Debug::DebugBreak(node_isolate);
2721 if (!debugger_running) {
2722 fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n");
2728 static void RegisterSignalHandler(int signal, void (*handler)(int)) {
2729 struct sigaction sa;
2731 memset(&sa, 0, sizeof(sa));
2732 sa.sa_handler = handler;
2733 sigfillset(&sa.sa_mask);
2734 sigaction(signal, &sa, NULL);
2738 Handle<Value> DebugProcess(const Arguments& args) {
2741 if (args.Length() != 1) {
2742 return ThrowException(Exception::Error(
2743 String::New("Invalid number of arguments.")));
2749 pid = args[0]->IntegerValue();
2750 r = kill(pid, SIGUSR1);
2752 return ThrowException(ErrnoException(errno, "kill"));
2761 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2762 // Break once process will return execution to v8
2763 if (!debugger_running) {
2764 for (int i = 0; i < 1; i++) {
2765 fprintf(stderr, "Starting debugger agent.\r\n");
2771 v8::Debug::DebugBreak();
2777 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2779 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2783 static int RegisterDebugSignalHandler() {
2784 wchar_t mapping_name[32];
2785 HANDLE mapping_handle;
2787 LPTHREAD_START_ROUTINE* handler;
2789 pid = GetCurrentProcessId();
2791 if (GetDebugSignalHandlerMappingName(pid,
2793 ARRAY_SIZE(mapping_name)) < 0) {
2797 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2803 if (mapping_handle == NULL) {
2807 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2808 MapViewOfFile(mapping_handle,
2809 FILE_MAP_ALL_ACCESS,
2813 if (handler == NULL) {
2814 CloseHandle(mapping_handle);
2818 *handler = EnableDebugThreadProc;
2820 UnmapViewOfFile((void*) handler);
2826 static Handle<Value> DebugProcess(const Arguments& args) {
2828 Handle<Value> rv = Undefined();
2830 HANDLE process = NULL;
2831 HANDLE thread = NULL;
2832 HANDLE mapping = NULL;
2833 wchar_t mapping_name[32];
2834 LPTHREAD_START_ROUTINE* handler = NULL;
2836 if (args.Length() != 1) {
2837 rv = ThrowException(Exception::Error(String::New("Invalid number of arguments.")));
2841 pid = (DWORD) args[0]->IntegerValue();
2843 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2844 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2848 if (process == NULL) {
2849 rv = ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2853 if (GetDebugSignalHandlerMappingName(pid,
2855 ARRAY_SIZE(mapping_name)) < 0) {
2856 rv = ThrowException(ErrnoException(errno, "sprintf"));
2860 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2861 if (mapping == NULL) {
2862 rv = ThrowException(WinapiErrnoException(GetLastError(),
2863 "OpenFileMappingW"));
2867 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2868 MapViewOfFile(mapping,
2873 if (handler == NULL || *handler == NULL) {
2874 rv = ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
2878 thread = CreateRemoteThread(process,
2885 if (thread == NULL) {
2886 rv = ThrowException(WinapiErrnoException(GetLastError(),
2887 "CreateRemoteThread"));
2891 // Wait for the thread to terminate
2892 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
2893 rv = ThrowException(WinapiErrnoException(GetLastError(),
2894 "WaitForSingleObject"));
2899 if (process != NULL) {
2900 CloseHandle(process);
2902 if (thread != NULL) {
2903 CloseHandle(thread);
2905 if (handler != NULL) {
2906 UnmapViewOfFile(handler);
2908 if (mapping != NULL) {
2909 CloseHandle(mapping);
2917 static Handle<Value> DebugPause(const Arguments& args) {
2918 v8::Debug::DebugBreak(node_isolate);
2923 static Handle<Value> DebugEnd(const Arguments& args) {
2924 if (debugger_running) {
2925 v8::Debug::DisableAgent();
2926 debugger_running = false;
2933 char** Init(int argc, char *argv[]) {
2934 // Initialize prog_start_time to get relative uptime.
2935 uv_uptime(&prog_start_time);
2937 // Make inherited handles noninheritable.
2938 uv_disable_stdio_inheritance();
2940 // Parse a few arguments which are specific to Node.
2941 node::ParseArgs(argc, argv);
2942 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
2943 // in the command line))
2944 int v8argc = option_end_index;
2945 char **v8argv = argv;
2947 if (debug_wait_connect) {
2948 // v8argv is a copy of argv up to the script file argument +2 if --debug-brk
2949 // to expose the v8 debugger js object so that node.js can set
2950 // a breakpoint on the first line of the startup script
2952 v8argv = new char*[v8argc];
2953 memcpy(v8argv, argv, sizeof(*argv) * option_end_index);
2954 v8argv[option_end_index] = const_cast<char*>("--expose_debug_as");
2955 v8argv[option_end_index + 1] = const_cast<char*>("v8debug");
2958 // For the normal stack which moves from high to low addresses when frames
2959 // are pushed, we can compute the limit as stack_size bytes below the
2960 // the address of a stack variable (e.g. &stack_var) as an approximation
2961 // of the start of the stack (we're assuming that we haven't pushed a lot
2963 if (max_stack_size != 0) {
2965 ResourceConstraints constraints;
2967 uint32_t *stack_limit = &stack_var - (max_stack_size / sizeof(uint32_t));
2968 constraints.set_stack_limit(stack_limit);
2969 SetResourceConstraints(&constraints); // Must be done before V8::Initialize
2971 V8::SetFlagsFromCommandLine(&v8argc, v8argv, false);
2975 RegisterSignalHandler(SIGPIPE, SIG_IGN);
2976 RegisterSignalHandler(SIGINT, SignalExit);
2977 RegisterSignalHandler(SIGTERM, SignalExit);
2980 uv_idle_init(uv_default_loop(), &tick_spinner);
2982 uv_check_init(uv_default_loop(), &check_immediate_watcher);
2983 uv_unref((uv_handle_t*) &check_immediate_watcher);
2984 uv_idle_init(uv_default_loop(), &idle_immediate_dummy);
2986 V8::SetFatalErrorHandler(node::OnFatalError);
2988 // Fetch a reference to the main isolate, so we have a reference to it
2989 // even when we need it to access it from another (debugger) thread.
2990 node_isolate = Isolate::GetCurrent();
2992 // If the --debug flag was specified then initialize the debug thread.
2993 if (use_debug_agent) {
2994 EnableDebug(debug_wait_connect);
2997 RegisterDebugSignalHandler();
2999 static uv_signal_t signal_watcher;
3000 uv_signal_init(uv_default_loop(), &signal_watcher);
3001 uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1);
3002 uv_unref((uv_handle_t*)&signal_watcher);
3010 struct AtExitCallback {
3011 AtExitCallback* next_;
3012 void (*cb_)(void* arg);
3016 static AtExitCallback* at_exit_functions_;
3020 AtExitCallback* p = at_exit_functions_;
3021 at_exit_functions_ = NULL;
3024 AtExitCallback* q = p->next_;
3032 void AtExit(void (*cb)(void* arg), void* arg) {
3033 AtExitCallback* p = new AtExitCallback;
3036 p->next_ = at_exit_functions_;
3037 at_exit_functions_ = p;
3041 void EmitExit(v8::Handle<v8::Object> process_l) {
3042 // process.emit('exit')
3043 process_l->Set(String::NewSymbol("_exiting"), True());
3044 Local<Value> emit_v = process_l->Get(String::New("emit"));
3045 assert(emit_v->IsFunction());
3046 Local<Function> emit = Local<Function>::Cast(emit_v);
3047 Local<Value> args[] = { String::New("exit"), Integer::New(0) };
3049 emit->Call(process_l, 2, args);
3050 if (try_catch.HasCaught()) {
3051 FatalException(try_catch);
3055 static char **copy_argv(int argc, char **argv) {
3063 for(i = 0; i < argc; i++) {
3064 strlen_sum += strlen(argv[i]) + 1;
3067 argv_copy = (char **) malloc(sizeof(char *) * (argc + 1) + strlen_sum);
3072 argv_data = (char *) argv_copy + sizeof(char *) * (argc + 1);
3074 for(i = 0; i < argc; i++) {
3075 argv_copy[i] = argv_data;
3076 len = strlen(argv[i]) + 1;
3077 memcpy(argv_data, argv[i], len);
3081 argv_copy[argc] = NULL;
3086 int Start(int argc, char *argv[]) {
3087 // Hack aroung with the argv pointer. Used for process.title = "blah".
3088 argv = uv_setup_args(argc, argv);
3090 // Logic to duplicate argv as Init() modifies arguments
3091 // that are passed into it.
3092 char **argv_copy = copy_argv(argc, argv);
3094 // This needs to run *before* V8::Initialize()
3095 // Use copy here as to not modify the original argv:
3096 Init(argc, argv_copy);
3101 HandleScope handle_scope;
3103 // Create the one and only Context.
3104 Persistent<Context> context = Context::New();
3105 Context::Scope context_scope(context);
3107 // Use original argv, as we're just copying values out of it.
3108 Handle<Object> process_l = SetupProcessObject(argc, argv);
3109 v8_typed_array::AttachBindings(context->Global());
3111 // Create all the objects, load modules, do everything.
3112 // so your next reading stop should be node::Load()!
3115 // All our arguments are loaded. We've evaluated all of the scripts. We
3116 // might even have created TCP servers. Now we enter the main eventloop. If
3117 // there are no watchers on the loop (except for the ones that were
3118 // uv_unref'd) then this function exits. As long as there are active
3119 // watchers, it blocks.
3120 uv_run(uv_default_loop(), UV_RUN_DEFAULT);
3122 EmitExit(process_l);
3131 // Clean up. Not strictly necessary.
3135 // Clean up the copy: