1 // Copyright Joyent, Inc. and other Node contributors.
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
23 #include "node_buffer.h"
24 #include "node_constants.h"
25 #include "node_file.h"
26 #include "node_http_parser.h"
27 #include "node_javascript.h"
28 #include "node_version.h"
30 #if defined HAVE_PERFCTR
31 #include "node_counters.h"
35 #include "node_crypto.h"
38 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
39 #include "node_dtrace.h"
43 #include "node_provider.h"
49 #include "handle_wrap.h"
51 #include "string_bytes.h"
54 #include "v8-profiler.h"
59 #include <limits.h> // PATH_MAX
65 #include <sys/types.h>
71 #define strcasecmp _stricmp
72 #define getpid _getpid
76 #include <sys/resource.h> // getrlimit, setrlimit
77 #include <unistd.h> // setuid, getuid
80 #if defined(__POSIX__) && !defined(__ANDROID__)
81 #include <pwd.h> // getpwnam()
82 #include <grp.h> // getgrnam()
86 #include <crt_externs.h>
87 #define environ (*_NSGetEnviron())
88 #elif !defined(_MSC_VER)
89 extern char **environ;
95 using v8::ArrayBuffer;
100 using v8::FunctionCallbackInfo;
101 using v8::FunctionTemplate;
103 using v8::HandleScope;
104 using v8::HeapStatistics;
112 using v8::ObjectTemplate;
113 using v8::PropertyCallbackInfo;
115 using v8::ThrowException;
120 using v8::kExternalUnsignedIntArray;
122 // FIXME(bnoordhuis) Make these per-context?
123 QUEUE handle_wrap_queue = { &handle_wrap_queue, &handle_wrap_queue };
124 QUEUE req_wrap_queue = { &req_wrap_queue, &req_wrap_queue };
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 const char* eval_string = NULL;
131 static bool use_debug_agent = false;
132 static bool debug_wait_connect = false;
133 static int debug_port = 5858;
134 static bool v8_is_profiling = false;
136 // used by C++ modules as well
137 bool no_deprecation = false;
139 // process-relative uptime base, initialized at start-up
140 static double prog_start_time;
141 static bool debugger_running;
142 static uv_async_t dispatch_debug_messages_async;
144 // Declared in node_internals.h
145 Isolate* node_isolate = NULL;
148 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
150 // Impose an upper limit to avoid out of memory errors that bring down
152 static const size_t kMaxLength = 0x3fffffff;
153 static ArrayBufferAllocator the_singleton;
154 virtual ~ArrayBufferAllocator() {}
155 virtual void* Allocate(size_t length);
156 virtual void Free(void* data);
158 ArrayBufferAllocator() {}
159 ArrayBufferAllocator(const ArrayBufferAllocator&);
160 void operator=(const ArrayBufferAllocator&);
163 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
166 void* ArrayBufferAllocator::Allocate(size_t length) {
167 if (length > kMaxLength)
169 return new char[length];
173 void ArrayBufferAllocator::Free(void* data) {
174 delete[] static_cast<char*>(data);
178 static void CheckImmediate(uv_check_t* handle, int status) {
179 Environment* env = Environment::from_immediate_check_handle(handle);
180 Context::Scope context_scope(env->context());
181 MakeCallback(env, env->process_object(), env->immediate_callback_string());
185 static void IdleImmediateDummy(uv_idle_t*, int) {
186 // Do nothing. Only for maintaining event loop.
187 // TODO(bnoordhuis) Maybe make libuv accept NULL idle callbacks.
191 static inline const char *errno_string(int errorno) {
192 #define ERRNO_CASE(e) case e: return #e;
199 ERRNO_CASE(EADDRINUSE);
203 ERRNO_CASE(EADDRNOTAVAIL);
207 ERRNO_CASE(EAFNOSUPPORT);
215 # if EAGAIN != EWOULDBLOCK
216 ERRNO_CASE(EWOULDBLOCK);
221 ERRNO_CASE(EALREADY);
237 ERRNO_CASE(ECANCELED);
245 ERRNO_CASE(ECONNABORTED);
249 ERRNO_CASE(ECONNREFUSED);
253 ERRNO_CASE(ECONNRESET);
261 ERRNO_CASE(EDESTADDRREQ);
285 ERRNO_CASE(EHOSTUNREACH);
297 ERRNO_CASE(EINPROGRESS);
333 ERRNO_CASE(EMSGSIZE);
337 ERRNO_CASE(EMULTIHOP);
341 ERRNO_CASE(ENAMETOOLONG);
345 ERRNO_CASE(ENETDOWN);
349 ERRNO_CASE(ENETRESET);
353 ERRNO_CASE(ENETUNREACH);
385 # if ENOLINK != ENOLCK
399 ERRNO_CASE(ENOPROTOOPT);
419 ERRNO_CASE(ENOTCONN);
427 ERRNO_CASE(ENOTEMPTY);
431 ERRNO_CASE(ENOTSOCK);
438 ERRNO_CASE(EOPNOTSUPP);
452 ERRNO_CASE(EOVERFLOW);
467 #ifdef EPROTONOSUPPORT
468 ERRNO_CASE(EPROTONOSUPPORT);
472 ERRNO_CASE(EPROTOTYPE);
500 ERRNO_CASE(ETIMEDOUT);
515 const char *signo_string(int signo) {
516 #define SIGNO_CASE(e) case e: return #e;
543 # if SIGABRT != SIGIOT
587 SIGNO_CASE(SIGSTKFLT);
604 SIGNO_CASE(SIGBREAK);
628 SIGNO_CASE(SIGVTALRM);
636 SIGNO_CASE(SIGWINCH);
644 # if SIGPOLL != SIGIO
654 # if SIGPWR != SIGLOST
668 Local<Value> ErrnoException(int errorno,
672 Environment* env = Environment::GetCurrent(node_isolate);
675 Local<String> estring = OneByteString(node_isolate, errno_string(errorno));
676 if (msg == NULL || msg[0] == '\0') {
677 msg = strerror(errorno);
679 Local<String> message = OneByteString(node_isolate, msg);
681 Local<String> cons1 =
682 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
683 Local<String> cons2 = String::Concat(cons1, message);
686 Local<String> cons3 =
687 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
688 Local<String> cons4 =
689 String::Concat(cons3, String::NewFromUtf8(node_isolate, path));
690 Local<String> cons5 =
691 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
692 e = Exception::Error(cons5);
694 e = Exception::Error(cons2);
697 Local<Object> obj = e->ToObject();
698 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
699 obj->Set(env->code_string(), estring);
702 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
705 if (syscall != NULL) {
706 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
713 // hack alert! copy of ErrnoException, tuned for uv errors
714 Local<Value> UVException(int errorno,
718 Environment* env = Environment::GetCurrent(node_isolate);
721 msg = uv_strerror(errorno);
723 Local<String> estring = OneByteString(node_isolate, uv_err_name(errorno));
724 Local<String> message = OneByteString(node_isolate, msg);
725 Local<String> cons1 =
726 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
727 Local<String> cons2 = String::Concat(cons1, message);
731 Local<String> path_str;
735 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
736 path_str = String::Concat(FIXED_ONE_BYTE_STRING(node_isolate, "\\\\"),
737 String::NewFromUtf8(node_isolate, path + 8));
738 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
739 path_str = String::NewFromUtf8(node_isolate, path + 4);
741 path_str = String::NewFromUtf8(node_isolate, path);
744 path_str = String::NewFromUtf8(node_isolate, path);
747 Local<String> cons3 =
748 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
749 Local<String> cons4 =
750 String::Concat(cons3, path_str);
751 Local<String> cons5 =
752 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
753 e = Exception::Error(cons5);
755 e = Exception::Error(cons2);
758 Local<Object> obj = e->ToObject();
759 // TODO(piscisaureus) errno should probably go
760 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
761 obj->Set(env->code_string(), estring);
764 obj->Set(env->path_string(), path_str);
767 if (syscall != NULL) {
768 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
776 // Does about the same as strerror(),
777 // but supports all windows error messages
778 static const char *winapi_strerror(const int errorno) {
781 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
782 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
783 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
786 // Remove trailing newlines
787 for (int i = strlen(errmsg) - 1;
788 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
794 // FormatMessage failed
795 return "Unknown error";
800 Local<Value> WinapiErrnoException(int errorno,
804 Environment* env = Environment::GetCurrent(node_isolate);
807 if (!msg || !msg[0]) {
808 msg = winapi_strerror(errorno);
810 Local<String> message = OneByteString(node_isolate, msg);
813 Local<String> cons1 =
814 String::Concat(message, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
815 Local<String> cons2 =
816 String::Concat(cons1, String::NewFromUtf8(node_isolate, path));
817 Local<String> cons3 =
818 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
819 e = Exception::Error(cons3);
821 e = Exception::Error(message);
824 Local<Object> obj = e->ToObject();
825 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
828 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
831 if (syscall != NULL) {
832 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
840 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
841 Environment* env = Environment::GetCurrent(args.GetIsolate());
843 if (env->using_domains())
845 env->set_using_domains(true);
847 HandleScope scope(node_isolate);
848 Local<Object> process_object = env->process_object();
850 Local<String> tick_callback_function_key =
851 FIXED_ONE_BYTE_STRING(node_isolate, "_tickDomainCallback");
852 Local<Function> tick_callback_function =
853 process_object->Get(tick_callback_function_key).As<Function>();
855 if (!tick_callback_function->IsFunction()) {
856 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
860 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"),
861 tick_callback_function);
862 env->set_tick_callback_function(tick_callback_function);
864 if (!args[0]->IsArray()) {
865 fprintf(stderr, "_setupDomainUse first argument must be an array\n");
868 env->set_domain_array(args[0].As<Array>());
870 if (!args[1]->IsObject()) {
871 fprintf(stderr, "_setupDomainUse second argument must be an object\n");
875 Local<Object> domain_flag_obj = args[1].As<Object>();
876 Environment::DomainFlag* domain_flag = env->domain_flag();
877 domain_flag_obj->SetIndexedPropertiesToExternalArrayData(
878 domain_flag->fields(),
879 kExternalUnsignedIntArray,
880 domain_flag->fields_count());
884 Handle<Value> MakeDomainCallback(Environment* env,
885 const Handle<Object> object,
886 const Handle<Function> callback,
888 Handle<Value> argv[]) {
889 // If you hit this assertion, you forgot to enter the v8::Context first.
890 assert(env->context() == env->isolate()->GetCurrentContext());
892 // TODO(trevnorris) Hook for long stack traces to be made here.
894 Local<Value> domain_v = object->Get(env->domain_string());
895 Local<Object> domain;
898 try_catch.SetVerbose(true);
900 bool has_domain = domain_v->IsObject();
902 domain = domain_v.As<Object>();
904 if (domain->Get(env->disposed_string())->IsTrue()) {
905 // domain has been disposed of.
906 return Undefined(node_isolate);
909 Local<Function> enter =
910 domain->Get(env->enter_string()).As<Function>();
911 assert(enter->IsFunction());
912 enter->Call(domain, 0, NULL);
914 if (try_catch.HasCaught()) {
915 return Undefined(node_isolate);
919 Local<Value> ret = callback->Call(object, argc, argv);
921 if (try_catch.HasCaught()) {
922 return Undefined(node_isolate);
926 Local<Function> exit =
927 domain->Get(env->exit_string()).As<Function>();
928 assert(exit->IsFunction());
929 exit->Call(domain, 0, NULL);
931 if (try_catch.HasCaught()) {
932 return Undefined(node_isolate);
936 Environment::TickInfo* tick_info = env->tick_info();
938 if (tick_info->last_threw() == 1) {
939 tick_info->set_last_threw(0);
943 if (tick_info->in_tick() == 1) {
947 if (tick_info->length() == 0) {
948 tick_info->set_index(0);
952 // process nextTicks after call
953 Local<Object> process_object = env->process_object();
954 Local<Function> tick_callback_function = env->tick_callback_function();
955 tick_callback_function->Call(process_object, 0, NULL);
957 if (try_catch.HasCaught()) {
958 return Undefined(node_isolate);
965 Handle<Value> MakeCallback(Environment* env,
966 const Handle<Object> object,
967 const Handle<Function> callback,
969 Handle<Value> argv[]) {
970 // If you hit this assertion, you forgot to enter the v8::Context first.
971 assert(env->context() == env->isolate()->GetCurrentContext());
973 // TODO(trevnorris) Hook for long stack traces to be made here.
974 Local<Object> process_object = env->process_object();
976 if (env->using_domains())
977 return MakeDomainCallback(env, object, callback, argc, argv);
980 try_catch.SetVerbose(true);
982 Local<Value> ret = callback->Call(object, argc, argv);
984 if (try_catch.HasCaught()) {
985 return Undefined(node_isolate);
988 Environment::TickInfo* tick_info = env->tick_info();
990 if (tick_info->in_tick() == 1) {
994 if (tick_info->length() == 0) {
995 tick_info->set_index(0);
999 // lazy load no domain next tick callbacks
1000 Local<Function> tick_callback_function = env->tick_callback_function();
1001 if (tick_callback_function.IsEmpty()) {
1002 Local<String> tick_callback_function_key =
1003 FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback");
1004 tick_callback_function =
1005 process_object->Get(tick_callback_function_key).As<Function>();
1006 if (!tick_callback_function->IsFunction()) {
1007 fprintf(stderr, "process._tickCallback assigned to non-function\n");
1010 env->set_tick_callback_function(tick_callback_function);
1013 // process nextTicks after call
1014 tick_callback_function->Call(process_object, 0, NULL);
1016 if (try_catch.HasCaught()) {
1017 return Undefined(node_isolate);
1025 Handle<Value> MakeCallback(Environment* env,
1026 const Handle<Object> object,
1029 Handle<Value> argv[]) {
1030 // If you hit this assertion, you forgot to enter the v8::Context first.
1031 assert(env->context() == env->isolate()->GetCurrentContext());
1033 Local<Function> callback = object->Get(index).As<Function>();
1034 assert(callback->IsFunction());
1036 if (env->using_domains()) {
1037 return MakeDomainCallback(env, object, callback, argc, argv);
1040 return MakeCallback(env, object, callback, argc, argv);
1044 Handle<Value> MakeCallback(Environment* env,
1045 const Handle<Object> object,
1046 const Handle<String> symbol,
1048 Handle<Value> argv[]) {
1049 // If you hit this assertion, you forgot to enter the v8::Context first.
1050 assert(env->context() == env->isolate()->GetCurrentContext());
1052 Local<Function> callback = object->Get(symbol).As<Function>();
1053 assert(callback->IsFunction());
1055 if (env->using_domains()) {
1056 return MakeDomainCallback(env, object, callback, argc, argv);
1059 return MakeCallback(env, object, callback, argc, argv);
1063 Handle<Value> MakeCallback(Environment* env,
1064 const Handle<Object> object,
1067 Handle<Value> argv[]) {
1068 // If you hit this assertion, you forgot to enter the v8::Context first.
1069 assert(env->context() == env->isolate()->GetCurrentContext());
1070 Local<String> method_string = OneByteString(node_isolate, method);
1071 return MakeCallback(env, object, method_string, argc, argv);
1075 Handle<Value> MakeCallback(const Handle<Object> object,
1078 Handle<Value> argv[]) {
1079 Local<Context> context = object->CreationContext();
1080 Environment* env = Environment::GetCurrent(context);
1081 Context::Scope context_scope(context);
1082 HandleScope handle_scope(env->isolate());
1083 return handle_scope.Close(MakeCallback(env, object, method, argc, argv));
1087 Handle<Value> MakeCallback(const Handle<Object> object,
1088 const Handle<String> symbol,
1090 Handle<Value> argv[]) {
1091 Local<Context> context = object->CreationContext();
1092 Environment* env = Environment::GetCurrent(context);
1093 Context::Scope context_scope(context);
1094 HandleScope handle_scope(env->isolate());
1095 return handle_scope.Close(MakeCallback(env, object, symbol, argc, argv));
1099 Handle<Value> MakeCallback(const Handle<Object> object,
1100 const Handle<Function> callback,
1102 Handle<Value> argv[]) {
1103 Local<Context> context = object->CreationContext();
1104 Environment* env = Environment::GetCurrent(context);
1105 Context::Scope context_scope(context);
1106 HandleScope handle_scope(env->isolate());
1107 return handle_scope.Close(MakeCallback(env, object, callback, argc, argv));
1111 Handle<Value> MakeDomainCallback(const Handle<Object> object,
1112 const Handle<Function> callback,
1114 Handle<Value> argv[]) {
1115 Local<Context> context = object->CreationContext();
1116 Environment* env = Environment::GetCurrent(context);
1117 Context::Scope context_scope(context);
1118 HandleScope handle_scope(env->isolate());
1119 return handle_scope.Close(
1120 MakeDomainCallback(env, object, callback, argc, argv));
1124 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1125 HandleScope scope(node_isolate);
1127 if (!encoding_v->IsString())
1130 String::Utf8Value encoding(encoding_v);
1132 if (strcasecmp(*encoding, "utf8") == 0) {
1134 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1136 } else if (strcasecmp(*encoding, "ascii") == 0) {
1138 } else if (strcasecmp(*encoding, "base64") == 0) {
1140 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1142 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1144 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1146 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1148 } else if (strcasecmp(*encoding, "binary") == 0) {
1150 } else if (strcasecmp(*encoding, "buffer") == 0) {
1152 } else if (strcasecmp(*encoding, "hex") == 0) {
1154 } else if (strcasecmp(*encoding, "raw") == 0) {
1155 if (!no_deprecation) {
1156 fprintf(stderr, "'raw' (array of integers) has been removed. "
1160 } else if (strcasecmp(*encoding, "raws") == 0) {
1161 if (!no_deprecation) {
1162 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1163 "Please update your code.\n");
1171 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1172 return StringBytes::Encode(static_cast<const char*>(buf),
1177 // Returns -1 if the handle was not valid for decoding
1178 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1179 HandleScope scope(node_isolate);
1181 if (val->IsArray()) {
1182 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1188 return StringBytes::Size(val, encoding);
1192 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1195 // Returns number of bytes written.
1196 ssize_t DecodeWrite(char *buf,
1198 v8::Handle<v8::Value> val,
1199 enum encoding encoding) {
1200 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1203 void DisplayExceptionLine(Handle<Message> message) {
1204 // Prevent re-entry into this function. For example, if there is
1205 // a throw from a program in vm.runInThisContext(code, filename, true),
1206 // then we want to show the original failure, not the secondary one.
1207 static bool displayed_error = false;
1209 if (displayed_error)
1211 displayed_error = true;
1213 uv_tty_reset_mode();
1215 fprintf(stderr, "\n");
1217 if (!message.IsEmpty()) {
1218 // Print (filename):(line number): (message).
1219 String::Utf8Value filename(message->GetScriptResourceName());
1220 const char* filename_string = *filename;
1221 int linenum = message->GetLineNumber();
1222 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1223 // Print line of source code.
1224 String::Utf8Value sourceline(message->GetSourceLine());
1225 const char* sourceline_string = *sourceline;
1227 // Because of how node modules work, all scripts are wrapped with a
1228 // "function (module, exports, __filename, ...) {"
1229 // to provide script local variables.
1231 // When reporting errors on the first line of a script, this wrapper
1232 // function is leaked to the user. There used to be a hack here to
1233 // truncate off the first 62 characters, but it caused numerous other
1234 // problems when vm.runIn*Context() methods were used for non-module
1237 // If we ever decide to re-instate such a hack, the following steps
1240 // 1. Pass a flag around to say "this code was wrapped"
1241 // 2. Update the stack frame output so that it is also correct.
1243 // It would probably be simpler to add a line rather than add some
1244 // number of characters to the first line, since V8 truncates the
1245 // sourceline to 78 characters, and we end up not providing very much
1246 // useful debugging info to the user if we remove 62 characters.
1248 int start = message->GetStartColumn();
1249 int end = message->GetEndColumn();
1251 fprintf(stderr, "%s\n", sourceline_string);
1252 // Print wavy underline (GetUnderline is deprecated).
1253 for (int i = 0; i < start; i++) {
1254 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1256 for (int i = start; i < end; i++) {
1259 fputc('\n', stderr);
1264 static void ReportException(Handle<Value> er, Handle<Message> message) {
1265 HandleScope scope(node_isolate);
1267 DisplayExceptionLine(message);
1269 Local<Value> trace_value(
1270 er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack")));
1271 String::Utf8Value trace(trace_value);
1273 // range errors have a trace member set to undefined
1274 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1275 fprintf(stderr, "%s\n", *trace);
1277 // this really only happens for RangeErrors, since they're the only
1278 // kind that won't have all this info in the trace, or when non-Error
1279 // objects are thrown manually.
1280 Local<Value> message;
1283 if (er->IsObject()) {
1284 Local<Object> err_obj = er.As<Object>();
1285 message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1286 name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1289 if (message.IsEmpty() ||
1290 message->IsUndefined() ||
1292 name->IsUndefined()) {
1293 // Not an error object. Just print as-is.
1294 String::Utf8Value message(er);
1295 fprintf(stderr, "%s\n", *message);
1297 String::Utf8Value name_string(name);
1298 String::Utf8Value message_string(message);
1299 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1307 static void ReportException(const TryCatch& try_catch) {
1308 ReportException(try_catch.Exception(), try_catch.Message());
1312 // Executes a str within the current v8 context.
1313 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1314 HandleScope scope(node_isolate);
1317 // try_catch must be nonverbose to disable FatalException() handler,
1318 // we will handle exceptions ourself.
1319 try_catch.SetVerbose(false);
1321 Local<v8::Script> script = v8::Script::Compile(source, filename);
1322 if (script.IsEmpty()) {
1323 ReportException(try_catch);
1327 Local<Value> result = script->Run();
1328 if (result.IsEmpty()) {
1329 ReportException(try_catch);
1333 return scope.Close(result);
1337 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1338 HandleScope scope(node_isolate);
1340 Local<Array> ary = Array::New();
1344 QUEUE_FOREACH(q, &req_wrap_queue) {
1345 ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1346 if (w->persistent().IsEmpty())
1348 ary->Set(i++, w->object());
1351 args.GetReturnValue().Set(ary);
1355 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1356 // implemented here for consistency with GetActiveRequests().
1357 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1358 HandleScope scope(node_isolate);
1360 Local<Array> ary = Array::New();
1364 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1366 QUEUE_FOREACH(q, &handle_wrap_queue) {
1367 HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1368 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref))
1370 Local<Object> object = w->object();
1371 Local<Value> owner = object->Get(owner_sym);
1372 if (owner->IsUndefined())
1374 ary->Set(i++, owner);
1377 args.GetReturnValue().Set(ary);
1381 static void Abort(const FunctionCallbackInfo<Value>& args) {
1386 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1387 HandleScope scope(node_isolate);
1389 if (args.Length() != 1 || !args[0]->IsString()) {
1390 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1393 String::Utf8Value path(args[0]);
1394 int err = uv_chdir(*path);
1396 return ThrowUVException(err, "uv_chdir");
1401 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1402 HandleScope scope(node_isolate);
1404 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1405 char buf[MAX_PATH * 4 + 1];
1407 char buf[PATH_MAX + 1];
1410 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1412 return ThrowUVException(err, "uv_cwd");
1415 buf[ARRAY_SIZE(buf) - 1] = '\0';
1416 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1418 args.GetReturnValue().Set(cwd);
1422 static void Umask(const FunctionCallbackInfo<Value>& args) {
1423 HandleScope scope(node_isolate);
1426 if (args.Length() < 1 || args[0]->IsUndefined()) {
1428 umask(static_cast<mode_t>(old));
1429 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1430 return ThrowTypeError("argument must be an integer or octal string.");
1433 if (args[0]->IsInt32()) {
1434 oct = args[0]->Uint32Value();
1437 String::Utf8Value str(args[0]);
1439 // Parse the octal string.
1440 for (int i = 0; i < str.length(); i++) {
1442 if (c > '7' || c < '0') {
1443 return ThrowTypeError("invalid octal string");
1449 old = umask(static_cast<mode_t>(oct));
1452 args.GetReturnValue().Set(old);
1456 #if defined(__POSIX__) && !defined(__ANDROID__)
1458 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1459 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1462 static uid_t uid_by_name(const char* name) {
1470 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1474 return uid_not_found;
1478 static char* name_by_uid(uid_t uid) {
1487 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1488 return strdup(pp->pw_name);
1499 static gid_t gid_by_name(const char* name) {
1507 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1511 return gid_not_found;
1515 #if 0 // For future use.
1516 static const char* name_by_gid(gid_t gid) {
1525 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1526 return strdup(pp->gr_name);
1538 static uid_t uid_by_name(Handle<Value> value) {
1539 if (value->IsUint32()) {
1540 return static_cast<uid_t>(value->Uint32Value());
1542 String::Utf8Value name(value);
1543 return uid_by_name(*name);
1548 static gid_t gid_by_name(Handle<Value> value) {
1549 if (value->IsUint32()) {
1550 return static_cast<gid_t>(value->Uint32Value());
1552 String::Utf8Value name(value);
1553 return gid_by_name(*name);
1558 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1559 // uid_t is an uint32_t on all supported platforms.
1560 args.GetReturnValue().Set(static_cast<uint32_t>(getuid()));
1564 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1565 // gid_t is an uint32_t on all supported platforms.
1566 args.GetReturnValue().Set(static_cast<uint32_t>(getgid()));
1570 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1571 HandleScope scope(node_isolate);
1573 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1574 return ThrowTypeError("setgid argument must be a number or a string");
1577 gid_t gid = gid_by_name(args[0]);
1579 if (gid == gid_not_found) {
1580 return ThrowError("setgid group id does not exist");
1584 return ThrowErrnoException(errno, "setgid");
1589 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1590 HandleScope scope(node_isolate);
1592 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1593 return ThrowTypeError("setuid argument must be a number or a string");
1596 uid_t uid = uid_by_name(args[0]);
1598 if (uid == uid_not_found) {
1599 return ThrowError("setuid user id does not exist");
1603 return ThrowErrnoException(errno, "setuid");
1608 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1609 HandleScope scope(node_isolate);
1611 int ngroups = getgroups(0, NULL);
1613 if (ngroups == -1) {
1614 return ThrowErrnoException(errno, "getgroups");
1617 gid_t* groups = new gid_t[ngroups];
1619 ngroups = getgroups(ngroups, groups);
1621 if (ngroups == -1) {
1623 return ThrowErrnoException(errno, "getgroups");
1626 Local<Array> groups_list = Array::New(ngroups);
1627 bool seen_egid = false;
1628 gid_t egid = getegid();
1630 for (int i = 0; i < ngroups; i++) {
1631 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1632 if (groups[i] == egid)
1638 if (seen_egid == false) {
1639 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1642 args.GetReturnValue().Set(groups_list);
1646 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1647 HandleScope scope(node_isolate);
1649 if (!args[0]->IsArray()) {
1650 return ThrowTypeError("argument 1 must be an array");
1653 Local<Array> groups_list = args[0].As<Array>();
1654 size_t size = groups_list->Length();
1655 gid_t* groups = new gid_t[size];
1657 for (size_t i = 0; i < size; i++) {
1658 gid_t gid = gid_by_name(groups_list->Get(i));
1660 if (gid == gid_not_found) {
1662 return ThrowError("group name not found");
1668 int rc = setgroups(size, groups);
1672 return ThrowErrnoException(errno, "setgroups");
1677 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1678 HandleScope scope(node_isolate);
1680 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1681 return ThrowTypeError("argument 1 must be a number or a string");
1684 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1685 return ThrowTypeError("argument 2 must be a number or a string");
1688 String::Utf8Value arg0(args[0]);
1693 if (args[0]->IsUint32()) {
1694 user = name_by_uid(args[0]->Uint32Value());
1702 return ThrowError("initgroups user not found");
1705 extra_group = gid_by_name(args[1]);
1707 if (extra_group == gid_not_found) {
1710 return ThrowError("initgroups extra group not found");
1713 int rc = initgroups(user, extra_group);
1720 return ThrowErrnoException(errno, "initgroups");
1724 #endif // __POSIX__ && !defined(__ANDROID__)
1727 void Exit(const FunctionCallbackInfo<Value>& args) {
1728 HandleScope scope(node_isolate);
1729 exit(args[0]->IntegerValue());
1733 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1734 HandleScope scope(node_isolate);
1736 if (uv_uptime(&uptime))
1738 args.GetReturnValue().Set(uptime - prog_start_time);
1742 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1743 Environment* env = Environment::GetCurrent(args.GetIsolate());
1744 HandleScope handle_scope(args.GetIsolate());
1747 int err = uv_resident_set_memory(&rss);
1749 return ThrowUVException(err, "uv_resident_set_memory");
1753 HeapStatistics v8_heap_stats;
1754 node_isolate->GetHeapStatistics(&v8_heap_stats);
1756 Local<Integer> heap_total =
1757 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(), node_isolate);
1758 Local<Integer> heap_used =
1759 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(), node_isolate);
1761 Local<Object> info = Object::New();
1762 info->Set(env->rss_string(), Number::New(node_isolate, rss));
1763 info->Set(env->heap_total_string(), heap_total);
1764 info->Set(env->heap_used_string(), heap_used);
1766 args.GetReturnValue().Set(info);
1770 void Kill(const FunctionCallbackInfo<Value>& args) {
1771 HandleScope scope(node_isolate);
1773 if (args.Length() != 2) {
1774 return ThrowError("Bad argument.");
1777 int pid = args[0]->IntegerValue();
1778 int sig = args[1]->Int32Value();
1779 int err = uv_kill(pid, sig);
1780 args.GetReturnValue().Set(err);
1783 // used in Hrtime() below
1784 #define NANOS_PER_SEC 1000000000
1786 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1787 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1788 // so this function instead returns an Array with 2 entries representing seconds
1789 // and nanoseconds, to avoid any integer overflow possibility.
1790 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1791 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1792 HandleScope scope(node_isolate);
1794 uint64_t t = uv_hrtime();
1796 if (args.Length() > 0) {
1797 // return a time diff tuple
1798 if (!args[0]->IsArray()) {
1799 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1801 Local<Array> inArray = Local<Array>::Cast(args[0]);
1802 uint64_t seconds = inArray->Get(0)->Uint32Value();
1803 uint64_t nanos = inArray->Get(1)->Uint32Value();
1804 t -= (seconds * NANOS_PER_SEC) + nanos;
1807 Local<Array> tuple = Array::New(2);
1808 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1809 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1810 args.GetReturnValue().Set(tuple);
1814 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1816 // DLOpen is process.dlopen(module, filename).
1817 // Used to load 'module.node' dynamically shared objects.
1819 // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
1820 // when two contexts try to load the same shared object. Maybe have a shadow
1821 // cache that's a plain C list or hash table that's shared across contexts?
1822 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1823 Environment* env = Environment::GetCurrent(args.GetIsolate());
1824 HandleScope handle_scope(args.GetIsolate());
1825 char symbol[1024], *base, *pos;
1829 if (args.Length() < 2) {
1830 return ThrowError("process.dlopen takes exactly 2 arguments.");
1833 Local<Object> module = args[0]->ToObject(); // Cast
1834 String::Utf8Value filename(args[1]); // Cast
1836 Local<String> exports_string = env->exports_string();
1837 Local<Object> exports = module->Get(exports_string)->ToObject();
1839 if (uv_dlopen(*filename, &lib)) {
1840 Local<String> errmsg = OneByteString(env->isolate(), uv_dlerror(&lib));
1842 // Windows needs to add the filename into the error message
1843 errmsg = String::Concat(errmsg, args[1]->ToString());
1845 ThrowException(Exception::Error(errmsg));
1849 String::Utf8Value path(args[1]);
1852 /* Find the shared library filename within the full path. */
1854 pos = strrchr(base, '/');
1860 pos = strpbrk(base, "\\/:");
1868 /* Strip the .node extension. */
1869 pos = strrchr(base, '.');
1874 /* Add the `_module` suffix to the extension name. */
1875 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1876 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1877 return ThrowError("Out of memory.");
1880 /* Replace dashes with underscores. When loading foo-bar.node,
1881 * look for foo_bar_module, not foo-bar_module.
1883 for (pos = symbol; *pos != '\0'; ++pos) {
1888 node_module_struct *mod;
1889 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1891 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1892 return ThrowError(errmsg);
1895 if (mod->version != NODE_MODULE_VERSION) {
1899 "Module version mismatch. Expected %d, got %d.",
1900 NODE_MODULE_VERSION, mod->version);
1901 return ThrowError(errmsg);
1904 // Execute the C++ module
1905 if (mod->register_context_func != NULL) {
1906 mod->register_context_func(exports, module, env->context());
1907 } else if (mod->register_func != NULL) {
1908 mod->register_func(exports, module);
1910 return ThrowError("Module has no declared entry point.");
1913 // Tell coverity that 'handle' should not be freed when we return.
1914 // coverity[leaked_storage]
1918 static void OnFatalError(const char* location, const char* message) {
1920 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1922 fprintf(stderr, "FATAL ERROR: %s\n", message);
1932 NO_RETURN void FatalError(const char* location, const char* message) {
1933 OnFatalError(location, message);
1934 // to supress compiler warning
1939 void FatalException(Handle<Value> error, Handle<Message> message) {
1940 HandleScope scope(node_isolate);
1942 Environment* env = Environment::GetCurrent(node_isolate);
1943 Local<Object> process_object = env->process_object();
1944 Local<String> fatal_exception_string = env->fatal_exception_string();
1945 Local<Function> fatal_exception_function =
1946 process_object->Get(fatal_exception_string).As<Function>();
1948 if (!fatal_exception_function->IsFunction()) {
1949 // failed before the process._fatalException function was added!
1950 // this is probably pretty bad. Nothing to do but report and exit.
1951 ReportException(error, message);
1955 TryCatch fatal_try_catch;
1957 // Do not call FatalException when _fatalException handler throws
1958 fatal_try_catch.SetVerbose(false);
1960 // this will return true if the JS layer handled it, false otherwise
1961 Local<Value> caught =
1962 fatal_exception_function->Call(process_object, 1, &error);
1964 if (fatal_try_catch.HasCaught()) {
1965 // the fatal exception function threw, so we must exit
1966 ReportException(fatal_try_catch);
1970 if (false == caught->BooleanValue()) {
1971 ReportException(error, message);
1977 void FatalException(const TryCatch& try_catch) {
1978 HandleScope scope(node_isolate);
1979 // TODO(bajtos) do not call FatalException if try_catch is verbose
1980 // (requires V8 API to expose getter for try_catch.is_verbose_)
1981 FatalException(try_catch.Exception(), try_catch.Message());
1985 void OnMessage(Handle<Message> message, Handle<Value> error) {
1986 // The current version of V8 sends messages for errors only
1987 // (thus `error` is always set).
1988 FatalException(error, message);
1992 static void Binding(const FunctionCallbackInfo<Value>& args) {
1993 Environment* env = Environment::GetCurrent(args.GetIsolate());
1994 HandleScope handle_scope(args.GetIsolate());
1996 Local<String> module = args[0]->ToString();
1997 String::Utf8Value module_v(module);
1999 Local<Object> cache = env->binding_cache_object();
2000 Local<Object> exports;
2002 if (cache->Has(module)) {
2003 exports = cache->Get(module)->ToObject();
2004 args.GetReturnValue().Set(exports);
2008 // Append a string to process.moduleLoadList
2010 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
2012 Local<Array> modules = env->module_load_list_array();
2013 uint32_t l = modules->Length();
2014 modules->Set(l, OneByteString(node_isolate, buf));
2016 node_module_struct* mod = get_builtin_module(*module_v);
2018 exports = Object::New();
2019 // Internal bindings don't have a "module" object, only exports.
2020 assert(mod->register_func == NULL);
2021 assert(mod->register_context_func != NULL);
2022 Local<Value> unused = Undefined(env->isolate());
2023 mod->register_context_func(exports, unused, env->context());
2024 cache->Set(module, exports);
2025 } else if (!strcmp(*module_v, "constants")) {
2026 exports = Object::New();
2027 DefineConstants(exports);
2028 cache->Set(module, exports);
2029 } else if (!strcmp(*module_v, "natives")) {
2030 exports = Object::New();
2031 DefineJavaScript(exports);
2032 cache->Set(module, exports);
2034 return ThrowError("No such module");
2037 args.GetReturnValue().Set(exports);
2041 static void ProcessTitleGetter(Local<String> property,
2042 const PropertyCallbackInfo<Value>& info) {
2043 HandleScope scope(node_isolate);
2045 uv_get_process_title(buffer, sizeof(buffer));
2046 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2050 static void ProcessTitleSetter(Local<String> property,
2052 const PropertyCallbackInfo<void>& info) {
2053 HandleScope scope(node_isolate);
2054 String::Utf8Value title(value);
2055 // TODO(piscisaureus): protect with a lock
2056 uv_set_process_title(*title);
2060 static void EnvGetter(Local<String> property,
2061 const PropertyCallbackInfo<Value>& info) {
2062 HandleScope scope(node_isolate);
2064 String::Utf8Value key(property);
2065 const char* val = getenv(*key);
2067 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2070 String::Value key(property);
2071 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2072 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2074 ARRAY_SIZE(buffer));
2075 // If result >= sizeof buffer the buffer was too small. That should never
2076 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2078 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2079 result < ARRAY_SIZE(buffer)) {
2080 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2081 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2082 return info.GetReturnValue().Set(rc);
2085 // Not found. Fetch from prototype.
2086 info.GetReturnValue().Set(
2087 info.Data().As<Object>()->Get(property));
2091 static void EnvSetter(Local<String> property,
2093 const PropertyCallbackInfo<Value>& info) {
2094 HandleScope scope(node_isolate);
2096 String::Utf8Value key(property);
2097 String::Utf8Value val(value);
2098 setenv(*key, *val, 1);
2100 String::Value key(property);
2101 String::Value val(value);
2102 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2103 // Environment variables that start with '=' are read-only.
2104 if (key_ptr[0] != L'=') {
2105 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2108 // Whether it worked or not, always return rval.
2109 info.GetReturnValue().Set(value);
2113 static void EnvQuery(Local<String> property,
2114 const PropertyCallbackInfo<Integer>& info) {
2115 HandleScope scope(node_isolate);
2116 int32_t rc = -1; // Not found unless proven otherwise.
2118 String::Utf8Value key(property);
2122 String::Value key(property);
2123 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2124 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2125 GetLastError() == ERROR_SUCCESS) {
2127 if (key_ptr[0] == L'=') {
2128 // Environment variables that start with '=' are hidden and read-only.
2129 rc = static_cast<int32_t>(v8::ReadOnly) |
2130 static_cast<int32_t>(v8::DontDelete) |
2131 static_cast<int32_t>(v8::DontEnum);
2136 info.GetReturnValue().Set(rc);
2140 static void EnvDeleter(Local<String> property,
2141 const PropertyCallbackInfo<Boolean>& info) {
2142 HandleScope scope(node_isolate);
2145 String::Utf8Value key(property);
2146 rc = getenv(*key) != NULL;
2150 String::Value key(property);
2151 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2152 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2153 // Deletion failed. Return true if the key wasn't there in the first place,
2154 // false if it is still there.
2155 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2156 GetLastError() != ERROR_SUCCESS;
2159 info.GetReturnValue().Set(rc);
2163 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2164 HandleScope scope(node_isolate);
2167 while (environ[size])
2170 Local<Array> env = Array::New(size);
2172 for (int i = 0; i < size; ++i) {
2173 const char* var = environ[i];
2174 const char* s = strchr(var, '=');
2175 const int length = s ? s - var : strlen(var);
2176 Local<String> name = String::NewFromUtf8(node_isolate,
2178 String::kNormalString,
2183 WCHAR* environment = GetEnvironmentStringsW();
2184 if (environment == NULL)
2185 return; // This should not happen.
2186 Local<Array> env = Array::New();
2187 WCHAR* p = environment;
2189 while (*p != NULL) {
2192 // If the key starts with '=' it is a hidden environment variable.
2196 s = wcschr(p, L'=');
2201 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2202 const size_t two_byte_buffer_len = s - p;
2203 Local<String> value = String::NewFromTwoByte(node_isolate,
2205 String::kNormalString,
2206 two_byte_buffer_len);
2207 env->Set(i++, value);
2208 p = s + wcslen(s) + 1;
2210 FreeEnvironmentStringsW(environment);
2213 info.GetReturnValue().Set(env);
2217 static Handle<Object> GetFeatures() {
2218 HandleScope scope(node_isolate);
2220 Local<Object> obj = Object::New();
2221 #if defined(DEBUG) && DEBUG
2222 Local<Value> debug = True(node_isolate);
2224 Local<Value> debug = False(node_isolate);
2225 #endif // defined(DEBUG) && DEBUG
2227 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2229 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2230 // TODO(bnoordhuis) ping libuv
2231 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2233 #ifdef OPENSSL_NPN_NEGOTIATED
2234 Local<Boolean> tls_npn = True(node_isolate);
2236 Local<Boolean> tls_npn = False(node_isolate);
2238 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"), tls_npn);
2240 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2241 Local<Boolean> tls_sni = True(node_isolate);
2243 Local<Boolean> tls_sni = False(node_isolate);
2245 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"), tls_sni);
2247 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2248 Boolean::New(get_builtin_module("crypto") != NULL));
2250 return scope.Close(obj);
2254 static void DebugPortGetter(Local<String> property,
2255 const PropertyCallbackInfo<Value>& info) {
2256 HandleScope scope(node_isolate);
2257 info.GetReturnValue().Set(debug_port);
2261 static void DebugPortSetter(Local<String> property,
2263 const PropertyCallbackInfo<void>& info) {
2264 HandleScope scope(node_isolate);
2265 debug_port = value->NumberValue();
2269 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2270 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2271 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2274 void NeedImmediateCallbackGetter(Local<String> property,
2275 const PropertyCallbackInfo<Value>& info) {
2276 Environment* env = Environment::GetCurrent(info.GetIsolate());
2277 const uv_check_t* immediate_check_handle = env->immediate_check_handle();
2278 bool active = uv_is_active(
2279 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2280 info.GetReturnValue().Set(active);
2284 static void NeedImmediateCallbackSetter(
2285 Local<String> property,
2287 const PropertyCallbackInfo<void>& info) {
2288 Environment* env = Environment::GetCurrent(info.GetIsolate());
2289 HandleScope handle_scope(info.GetIsolate());
2291 uv_check_t* immediate_check_handle = env->immediate_check_handle();
2292 bool active = uv_is_active(
2293 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2295 if (active == value->BooleanValue())
2298 uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
2301 uv_check_stop(immediate_check_handle);
2302 uv_idle_stop(immediate_idle_handle);
2304 uv_check_start(immediate_check_handle, CheckImmediate);
2305 // Idle handle is needed only to stop the event loop from blocking in poll.
2306 uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
2311 void SetIdle(uv_prepare_t* handle, int) {
2312 Environment* env = Environment::from_idle_prepare_handle(handle);
2313 env->isolate()->GetCpuProfiler()->SetIdle(true);
2317 void ClearIdle(uv_check_t* handle, int) {
2318 Environment* env = Environment::from_idle_check_handle(handle);
2319 env->isolate()->GetCpuProfiler()->SetIdle(false);
2323 void StartProfilerIdleNotifier(Environment* env) {
2324 uv_prepare_start(env->idle_prepare_handle(), SetIdle);
2325 uv_check_start(env->idle_check_handle(), ClearIdle);
2329 void StopProfilerIdleNotifier(Environment* env) {
2330 uv_prepare_stop(env->idle_prepare_handle());
2331 uv_check_stop(env->idle_check_handle());
2335 void StartProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2336 StartProfilerIdleNotifier(Environment::GetCurrent(args.GetIsolate()));
2340 void StopProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2341 StopProfilerIdleNotifier(Environment::GetCurrent(args.GetIsolate()));
2345 #define READONLY_PROPERTY(obj, str, var) \
2347 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2351 void SetupProcessObject(Environment* env,
2353 const char* const* argv,
2355 const char* const* exec_argv) {
2356 HandleScope scope(node_isolate);
2359 Local<Object> process = env->process_object();
2361 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2363 ProcessTitleSetter);
2366 READONLY_PROPERTY(process,
2368 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2370 // process.moduleLoadList
2371 READONLY_PROPERTY(process,
2373 env->module_load_list_array());
2376 Local<Object> versions = Object::New();
2377 READONLY_PROPERTY(process, "versions", versions);
2379 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2381 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2382 READONLY_PROPERTY(versions,
2384 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2386 // +1 to get rid of the leading 'v'
2387 READONLY_PROPERTY(versions,
2389 OneByteString(node_isolate, NODE_VERSION + 1));
2390 READONLY_PROPERTY(versions,
2392 OneByteString(node_isolate, V8::GetVersion()));
2393 READONLY_PROPERTY(versions,
2395 OneByteString(node_isolate, uv_version_string()));
2396 READONLY_PROPERTY(versions,
2398 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2400 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2401 READONLY_PROPERTY(versions,
2403 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2406 // Stupid code to slice out the version string.
2407 int c, l = strlen(OPENSSL_VERSION_TEXT);
2408 for (i = j = 0; i < l; i++) {
2409 c = OPENSSL_VERSION_TEXT[i];
2410 if ('0' <= c && c <= '9') {
2411 for (j = i + 1; j < l; j++) {
2412 c = OPENSSL_VERSION_TEXT[j];
2422 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2426 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2429 READONLY_PROPERTY(process,
2431 OneByteString(node_isolate, PLATFORM));
2434 Local<Array> arguments = Array::New(argc);
2435 for (int i = 0; i < argc; ++i) {
2436 arguments->Set(i, String::NewFromUtf8(node_isolate, argv[i]));
2438 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2441 Local<Array> exec_arguments = Array::New(exec_argc);
2442 for (int i = 0; i < exec_argc; ++i) {
2443 exec_arguments->Set(i, String::NewFromUtf8(node_isolate, exec_argv[i]));
2445 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_arguments);
2447 // create process.env
2448 Local<ObjectTemplate> process_env_template = ObjectTemplate::New();
2449 process_env_template->SetNamedPropertyHandler(EnvGetter,
2455 Local<Object> process_env = process_env_template->NewInstance();
2456 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), process_env);
2458 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2459 READONLY_PROPERTY(process, "features", GetFeatures());
2460 process->SetAccessor(
2461 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2462 NeedImmediateCallbackGetter,
2463 NeedImmediateCallbackSetter);
2467 READONLY_PROPERTY(process,
2469 String::NewFromUtf8(node_isolate, eval_string));
2474 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2477 // -i, --interactive
2479 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2483 if (no_deprecation) {
2484 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2487 // --throw-deprecation
2488 if (throw_deprecation) {
2489 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2492 // --trace-deprecation
2493 if (trace_deprecation) {
2494 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2497 size_t exec_path_len = 2 * PATH_MAX;
2498 char* exec_path = new char[exec_path_len];
2499 Local<String> exec_path_value;
2500 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2501 exec_path_value = String::NewFromUtf8(node_isolate,
2503 String::kNormalString,
2506 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2508 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2512 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2516 // define various internal methods
2517 NODE_SET_METHOD(process,
2518 "_startProfilerIdleNotifier",
2519 StartProfilerIdleNotifier);
2520 NODE_SET_METHOD(process,
2521 "_stopProfilerIdleNotifier",
2522 StopProfilerIdleNotifier);
2523 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2524 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2525 NODE_SET_METHOD(process, "reallyExit", Exit);
2526 NODE_SET_METHOD(process, "abort", Abort);
2527 NODE_SET_METHOD(process, "chdir", Chdir);
2528 NODE_SET_METHOD(process, "cwd", Cwd);
2530 NODE_SET_METHOD(process, "umask", Umask);
2532 #if defined(__POSIX__) && !defined(__ANDROID__)
2533 NODE_SET_METHOD(process, "getuid", GetUid);
2534 NODE_SET_METHOD(process, "setuid", SetUid);
2536 NODE_SET_METHOD(process, "setgid", SetGid);
2537 NODE_SET_METHOD(process, "getgid", GetGid);
2539 NODE_SET_METHOD(process, "getgroups", GetGroups);
2540 NODE_SET_METHOD(process, "setgroups", SetGroups);
2541 NODE_SET_METHOD(process, "initgroups", InitGroups);
2542 #endif // __POSIX__ && !defined(__ANDROID__)
2544 NODE_SET_METHOD(process, "_kill", Kill);
2546 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2547 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2548 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2550 NODE_SET_METHOD(process, "hrtime", Hrtime);
2552 NODE_SET_METHOD(process, "dlopen", DLOpen);
2554 NODE_SET_METHOD(process, "uptime", Uptime);
2555 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2557 NODE_SET_METHOD(process, "binding", Binding);
2559 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2561 // values use to cross communicate with processNextTick
2562 Local<Object> tick_info_obj = Object::New();
2563 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
2564 env->tick_info()->fields(),
2565 kExternalUnsignedIntArray,
2566 env->tick_info()->fields_count());
2567 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfo"), tick_info_obj);
2569 // pre-set _events object for faster emit checks
2570 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2574 #undef READONLY_PROPERTY
2577 static void AtExit() {
2578 uv_tty_reset_mode();
2582 static void SignalExit(int signal) {
2583 uv_tty_reset_mode();
2584 _exit(128 + signal);
2588 // Most of the time, it's best to use `console.error` to write
2589 // to the process.stderr stream. However, in some cases, such as
2590 // when debugging the stream.Writable class or the process.nextTick
2591 // function, it is useful to bypass JavaScript entirely.
2592 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2593 HandleScope scope(node_isolate);
2595 assert(args.Length() == 1 && args[0]->IsString() &&
2596 "must be called with a single string");
2598 String::Utf8Value message(args[0]);
2599 fprintf(stderr, "%s\n", *message);
2604 void Load(Environment* env) {
2605 HandleScope handle_scope(node_isolate);
2607 // Compile, execute the src/node.js file. (Which was included as static C
2608 // string in node_natives.h. 'natve_node' is the string containing that
2611 // The node.js file returns a function 'f'
2616 // Disable verbose mode to stop FatalException() handler from trying
2617 // to handle the exception. Errors this early in the start-up phase
2618 // are not safe to ignore.
2619 try_catch.SetVerbose(false);
2621 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2622 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2623 if (try_catch.HasCaught()) {
2624 ReportException(try_catch);
2627 assert(f_value->IsFunction());
2628 Local<Function> f = Local<Function>::Cast(f_value);
2630 // Now we call 'f' with the 'process' variable that we've built up with
2631 // all our bindings. Inside node.js we'll take care of assigning things to
2634 // We start the process this way in order to be more modular. Developers
2635 // who do not like how 'src/node.js' setups the module system but do like
2636 // Node's I/O bindings may want to replace 'f' with their own function.
2638 // Add a reference to the global object
2639 Local<Object> global = env->context()->Global();
2641 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2645 #if defined HAVE_PERFCTR
2646 InitPerfCounters(global);
2649 // Enable handling of uncaught exceptions
2650 // (FatalException(), break on uncaught exception in debugger)
2652 // This is not strictly necessary since it's almost impossible
2653 // to attach the debugger fast enought to break on exception
2654 // thrown during process startup.
2655 try_catch.SetVerbose(true);
2657 NODE_SET_METHOD(env->process_object(), "_rawDebug", RawDebug);
2659 Local<Value> arg = env->process_object();
2660 f->Call(global, 1, &arg);
2663 static void PrintHelp();
2665 static void ParseDebugOpt(const char* arg) {
2668 if (strstr(arg, "--debug-port=") == arg) {
2669 p = 1 + strchr(arg, '=');
2670 debug_port = atoi(p);
2672 use_debug_agent = true;
2673 if (!strcmp(arg, "--debug-brk")) {
2674 debug_wait_connect = true;
2676 } else if (!strcmp(arg, "--debug")) {
2678 } else if (strstr(arg, "--debug-brk=") == arg) {
2679 debug_wait_connect = true;
2680 p = 1 + strchr(arg, '=');
2681 debug_port = atoi(p);
2682 } else if (strstr(arg, "--debug=") == arg) {
2683 p = 1 + strchr(arg, '=');
2684 debug_port = atoi(p);
2687 if (p && debug_port > 1024 && debug_port < 65536)
2690 fprintf(stderr, "Bad debug option.\n");
2692 fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2698 static void PrintHelp() {
2699 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2700 " node debug script.js [arguments] \n"
2703 " -v, --version print node's version\n"
2704 " -e, --eval script evaluate script\n"
2705 " -p, --print evaluate script and print result\n"
2706 " -i, --interactive always enter the REPL even if stdin\n"
2707 " does not appear to be a terminal\n"
2708 " --no-deprecation silence deprecation warnings\n"
2709 " --trace-deprecation show stack traces on deprecations\n"
2710 " --v8-options print v8 command line options\n"
2711 " --max-stack-size=val set max v8 stack size (bytes)\n"
2713 "Environment variables:\n"
2715 "NODE_PATH ';'-separated list of directories\n"
2717 "NODE_PATH ':'-separated list of directories\n"
2719 " prefixed to the module search path.\n"
2720 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2721 " global contexts.\n"
2722 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2724 "Documentation can be found at http://nodejs.org/\n");
2728 // Parse command line arguments.
2730 // argv is modified in place. exec_argv and v8_argv are out arguments that
2731 // ParseArgs() allocates memory for and stores a pointer to the output
2732 // vector in. The caller should free them with delete[].
2736 // * argv contains the arguments with node and V8 options filtered out.
2737 // * exec_argv contains both node and V8 options and nothing else.
2738 // * v8_argv contains argv[0] plus any V8 options
2739 static void ParseArgs(int* argc,
2742 const char*** exec_argv,
2744 const char*** v8_argv) {
2745 const unsigned int nargs = static_cast<unsigned int>(*argc);
2746 const char** new_exec_argv = new const char*[nargs];
2747 const char** new_v8_argv = new const char*[nargs];
2748 const char** new_argv = new const char*[nargs];
2750 for (unsigned int i = 0; i < nargs; ++i) {
2751 new_exec_argv[i] = NULL;
2752 new_v8_argv[i] = NULL;
2756 // exec_argv starts with the first option, the other two start with argv[0].
2757 unsigned int new_exec_argc = 0;
2758 unsigned int new_v8_argc = 1;
2759 unsigned int new_argc = 1;
2760 new_v8_argv[0] = argv[0];
2761 new_argv[0] = argv[0];
2763 unsigned int index = 1;
2764 while (index < nargs && argv[index][0] == '-') {
2765 const char* const arg = argv[index];
2766 unsigned int args_consumed = 1;
2768 if (strstr(arg, "--debug") == arg) {
2770 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2771 printf("%s\n", NODE_VERSION);
2773 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2776 } else if (strcmp(arg, "--eval") == 0 ||
2777 strcmp(arg, "-e") == 0 ||
2778 strcmp(arg, "--print") == 0 ||
2779 strcmp(arg, "-pe") == 0 ||
2780 strcmp(arg, "-p") == 0) {
2781 bool is_eval = strchr(arg, 'e') != NULL;
2782 bool is_print = strchr(arg, 'p') != NULL;
2783 print_eval = print_eval || is_print;
2784 // --eval, -e and -pe always require an argument.
2785 if (is_eval == true) {
2787 eval_string = argv[index + 1];
2788 if (eval_string == NULL) {
2789 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
2792 } else if (argv[index + 1] != NULL && argv[index + 1][0] != '-') {
2794 eval_string = argv[index + 1];
2795 if (strncmp(eval_string, "\\-", 2) == 0) {
2796 // Starts with "\\-": escaped expression, drop the backslash.
2800 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2802 } else if (strcmp(arg, "--no-deprecation") == 0) {
2803 no_deprecation = true;
2804 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2805 trace_deprecation = true;
2806 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2807 throw_deprecation = true;
2808 } else if (strcmp(arg, "--v8-options") == 0) {
2809 new_v8_argv[new_v8_argc] = "--help";
2812 // V8 option. Pass through as-is.
2813 new_v8_argv[new_v8_argc] = arg;
2817 memcpy(new_exec_argv + new_exec_argc,
2819 args_consumed * sizeof(*argv));
2821 new_exec_argc += args_consumed;
2822 index += args_consumed;
2825 // Copy remaining arguments.
2826 const unsigned int args_left = nargs - index;
2827 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
2828 new_argc += args_left;
2830 *exec_argc = new_exec_argc;
2831 *exec_argv = new_exec_argv;
2832 *v8_argc = new_v8_argc;
2833 *v8_argv = new_v8_argv;
2835 // Copy new_argv over argv and update argc.
2836 memcpy(argv, new_argv, new_argc * sizeof(*argv));
2838 *argc = static_cast<int>(new_argc);
2842 // Called from V8 Debug Agent TCP thread.
2843 static void DispatchMessagesDebugAgentCallback() {
2844 uv_async_send(&dispatch_debug_messages_async);
2848 // Called from the main thread.
2849 static void EnableDebug(bool wait_connect) {
2850 assert(debugger_running == false);
2851 Isolate* isolate = node_isolate; // TODO(bnoordhuis) Multi-isolate support.
2852 Isolate::Scope isolate_scope(isolate);
2853 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2855 debugger_running = v8::Debug::EnableAgent("node " NODE_VERSION,
2858 if (debugger_running == false) {
2859 fprintf(stderr, "Starting debugger on port %d failed\n", debug_port);
2863 fprintf(stderr, "Debugger listening on port %d\n", debug_port);
2866 Environment* env = Environment::GetCurrentChecked(isolate);
2868 return; // Still starting up.
2870 Context::Scope context_scope(env->context());
2871 HandleScope handle_scope(env->isolate());
2872 Local<Object> message = Object::New();
2873 message->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "cmd"),
2874 FIXED_ONE_BYTE_STRING(env->isolate(), "NODE_DEBUG_ENABLED"));
2875 Local<Value> argv[] = {
2876 FIXED_ONE_BYTE_STRING(env->isolate(), "internalMessage"),
2879 MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(argv), argv);
2883 // Called from the main thread.
2884 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2885 if (debugger_running == false) {
2886 fprintf(stderr, "Starting debugger agent.\n");
2889 Isolate::Scope isolate_scope(node_isolate);
2890 v8::Debug::ProcessDebugMessages();
2895 static volatile sig_atomic_t caught_early_debug_signal;
2898 static void EarlyDebugSignalHandler(int signo) {
2899 caught_early_debug_signal = 1;
2903 static void InstallEarlyDebugSignalHandler() {
2904 struct sigaction sa;
2905 memset(&sa, 0, sizeof(sa));
2906 sa.sa_handler = EarlyDebugSignalHandler;
2907 sigaction(SIGUSR1, &sa, NULL);
2911 static void EnableDebugSignalHandler(int signo) {
2912 // Call only async signal-safe functions here!
2913 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
2914 uv_async_send(&dispatch_debug_messages_async);
2918 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2919 struct sigaction sa;
2920 memset(&sa, 0, sizeof(sa));
2921 sa.sa_handler = handler;
2922 sigfillset(&sa.sa_mask);
2923 sigaction(signal, &sa, NULL);
2927 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2928 HandleScope scope(node_isolate);
2930 if (args.Length() != 1) {
2931 return ThrowError("Invalid number of arguments.");
2937 pid = args[0]->IntegerValue();
2938 r = kill(pid, SIGUSR1);
2940 return ThrowErrnoException(errno, "kill");
2945 static int RegisterDebugSignalHandler() {
2946 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
2947 RegisterSignalHandler(SIGUSR1, EnableDebugSignalHandler);
2948 // If we caught a SIGUSR1 during the bootstrap process, re-raise it
2949 // now that the debugger infrastructure is in place.
2950 if (caught_early_debug_signal)
2958 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2959 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
2960 uv_async_send(&dispatch_debug_messages_async);
2965 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2967 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2971 static int RegisterDebugSignalHandler() {
2972 wchar_t mapping_name[32];
2973 HANDLE mapping_handle;
2975 LPTHREAD_START_ROUTINE* handler;
2977 pid = GetCurrentProcessId();
2979 if (GetDebugSignalHandlerMappingName(pid,
2981 ARRAY_SIZE(mapping_name)) < 0) {
2985 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2991 if (mapping_handle == NULL) {
2995 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2996 MapViewOfFile(mapping_handle,
2997 FILE_MAP_ALL_ACCESS,
3001 if (handler == NULL) {
3002 CloseHandle(mapping_handle);
3006 *handler = EnableDebugThreadProc;
3008 UnmapViewOfFile(static_cast<void*>(handler));
3014 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3015 HandleScope scope(node_isolate);
3017 HANDLE process = NULL;
3018 HANDLE thread = NULL;
3019 HANDLE mapping = NULL;
3020 wchar_t mapping_name[32];
3021 LPTHREAD_START_ROUTINE* handler = NULL;
3023 if (args.Length() != 1) {
3024 ThrowError("Invalid number of arguments.");
3028 pid = (DWORD) args[0]->IntegerValue();
3030 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
3031 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
3035 if (process == NULL) {
3036 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
3040 if (GetDebugSignalHandlerMappingName(pid,
3042 ARRAY_SIZE(mapping_name)) < 0) {
3043 ThrowErrnoException(errno, "sprintf");
3047 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
3048 if (mapping == NULL) {
3049 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
3053 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3054 MapViewOfFile(mapping,
3059 if (handler == NULL || *handler == NULL) {
3060 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
3064 thread = CreateRemoteThread(process,
3071 if (thread == NULL) {
3072 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
3076 // Wait for the thread to terminate
3077 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3078 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
3083 if (process != NULL)
3084 CloseHandle(process);
3086 CloseHandle(thread);
3087 if (handler != NULL)
3088 UnmapViewOfFile(handler);
3089 if (mapping != NULL)
3090 CloseHandle(mapping);
3095 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3096 v8::Debug::DebugBreak(node_isolate);
3100 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3101 if (debugger_running) {
3102 v8::Debug::DisableAgent();
3103 debugger_running = false;
3108 void Init(int* argc,
3111 const char*** exec_argv) {
3112 // Initialize prog_start_time to get relative uptime.
3113 uv_uptime(&prog_start_time);
3115 // Make inherited handles noninheritable.
3116 uv_disable_stdio_inheritance();
3118 // init async debug messages dispatching
3119 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3120 uv_async_init(uv_default_loop(),
3121 &dispatch_debug_messages_async,
3122 DispatchDebugMessagesAsyncCallback);
3123 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3125 // Parse a few arguments which are specific to Node.
3127 const char** v8_argv;
3128 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3130 // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
3131 // manually? That would give us a little more control over its runtime
3132 // behavior but it could also interfere with the user's intentions in ways
3133 // we fail to anticipate. Dillema.
3134 for (int i = 1; i < v8_argc; ++i) {
3135 if (strncmp(v8_argv[i], "--prof", sizeof("--prof") - 1) == 0) {
3136 v8_is_profiling = true;
3141 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3142 // the argv array or the elements it points to.
3143 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3145 // Anything that's still in v8_argv is not a V8 or a node option.
3146 for (int i = 1; i < v8_argc; i++) {
3147 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3156 if (debug_wait_connect) {
3157 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3158 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3161 const char typed_arrays_flag[] = "--harmony_typed_arrays";
3162 V8::SetFlagsFromString(typed_arrays_flag, sizeof(typed_arrays_flag) - 1);
3163 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3165 // Fetch a reference to the main isolate, so we have a reference to it
3166 // even when we need it to access it from another (debugger) thread.
3167 node_isolate = Isolate::GetCurrent();
3170 // Raise the open file descriptor limit.
3171 { // NOLINT (whitespace/braces)
3173 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3174 // Do a binary search for the limit.
3175 rlim_t min = lim.rlim_cur;
3176 rlim_t max = 1 << 20;
3177 // But if there's a defined upper bound, don't search, just set it.
3178 if (lim.rlim_max != RLIM_INFINITY) {
3183 lim.rlim_cur = min + (max - min) / 2;
3184 if (setrlimit(RLIMIT_NOFILE, &lim)) {
3189 } while (min + 1 < max);
3193 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3194 RegisterSignalHandler(SIGINT, SignalExit);
3195 RegisterSignalHandler(SIGTERM, SignalExit);
3198 V8::SetFatalErrorHandler(node::OnFatalError);
3199 V8::AddMessageListener(OnMessage);
3201 // If the --debug flag was specified then initialize the debug thread.
3202 if (use_debug_agent) {
3203 EnableDebug(debug_wait_connect);
3205 RegisterDebugSignalHandler();
3210 struct AtExitCallback {
3211 AtExitCallback* next_;
3212 void (*cb_)(void* arg);
3216 static AtExitCallback* at_exit_functions_;
3219 // TODO(bnoordhuis) Turn into per-context event.
3220 void RunAtExit(Environment* env) {
3221 AtExitCallback* p = at_exit_functions_;
3222 at_exit_functions_ = NULL;
3225 AtExitCallback* q = p->next_;
3233 void AtExit(void (*cb)(void* arg), void* arg) {
3234 AtExitCallback* p = new AtExitCallback;
3237 p->next_ = at_exit_functions_;
3238 at_exit_functions_ = p;
3242 void EmitExit(Environment* env) {
3243 // process.emit('exit')
3244 Context::Scope context_scope(env->context());
3245 HandleScope handle_scope(env->isolate());
3246 Local<Object> process_object = env->process_object();
3247 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3248 True(node_isolate));
3250 Handle<String> exitCode = FIXED_ONE_BYTE_STRING(node_isolate, "exitCode");
3251 int code = process_object->Get(exitCode)->IntegerValue();
3253 Local<Value> args[] = {
3254 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3255 Integer::New(code, node_isolate)
3258 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3263 Environment* CreateEnvironment(Isolate* isolate,
3265 const char* const* argv,
3267 const char* const* exec_argv) {
3268 HandleScope handle_scope(isolate);
3270 Local<Context> context = Context::New(isolate);
3271 Context::Scope context_scope(context);
3272 Environment* env = Environment::New(context);
3274 uv_check_init(env->event_loop(), env->immediate_check_handle());
3276 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3277 uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3279 // Inform V8's CPU profiler when we're idle. The profiler is sampling-based
3280 // but not all samples are created equal; mark the wall clock time spent in
3281 // epoll_wait() and friends so profiling tools can filter it out. The samples
3282 // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
3283 // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
3284 // probably fortify in the API contract, namely that the last started prepare
3285 // or check watcher runs first. It's not 100% foolproof; if an add-on starts
3286 // a prepare or check watcher after us, any samples attributed to its callback
3287 // will be recorded with state=IDLE.
3288 uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
3289 uv_check_init(env->event_loop(), env->idle_check_handle());
3290 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
3291 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
3293 if (v8_is_profiling) {
3294 StartProfilerIdleNotifier(env);
3297 Local<FunctionTemplate> process_template = FunctionTemplate::New();
3298 process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3300 Local<Object> process_object = process_template->GetFunction()->NewInstance();
3301 env->set_process_object(process_object);
3303 SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3310 int Start(int argc, char** argv) {
3311 #if !defined(_WIN32)
3312 // Try hard not to lose SIGUSR1 signals during the bootstrap process.
3313 InstallEarlyDebugSignalHandler();
3318 // Hack around with the argv pointer. Used for process.title = "blah".
3319 argv = uv_setup_args(argc, argv);
3321 // This needs to run *before* V8::Initialize(). The const_cast is not
3322 // optional, in case you're wondering.
3324 const char** exec_argv;
3325 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3328 // V8 on Windows doesn't have a good source of entropy. Seed it from
3330 V8::SetEntropySource(crypto::EntropySource);
3335 Locker locker(node_isolate);
3337 CreateEnvironment(node_isolate, argc, argv, exec_argc, exec_argv);
3338 Context::Scope context_scope(env->context());
3339 HandleScope handle_scope(env->isolate());
3340 uv_run(env->event_loop(), UV_RUN_DEFAULT);
3348 // Clean up. Not strictly necessary.