2 #include "node_buffer.h"
3 #include "node_constants.h"
5 #include "node_http_parser.h"
6 #include "node_javascript.h"
7 #include "node_version.h"
8 #include "node_v8_platform.h"
10 #if defined HAVE_PERFCTR
11 #include "node_counters.h"
15 #include "node_crypto.h"
18 #if defined(NODE_HAVE_I18N_SUPPORT)
19 #include "node_i18n.h"
22 #if defined HAVE_DTRACE || defined HAVE_ETW
23 #include "node_dtrace.h"
26 #if defined HAVE_LTTNG
27 #include "node_lttng.h"
31 #include "async-wrap.h"
32 #include "async-wrap-inl.h"
35 #include "handle_wrap.h"
37 #include "req-wrap-inl.h"
38 #include "string_bytes.h"
42 #include "v8-profiler.h"
46 #include <limits.h> // PATH_MAX
52 #include <sys/types.h>
58 #define strcasecmp _stricmp
59 #define getpid _getpid
63 #include <sys/resource.h> // getrlimit, setrlimit
64 #include <unistd.h> // setuid, getuid
67 #if defined(__POSIX__) && !defined(__ANDROID__)
68 #include <pwd.h> // getpwnam()
69 #include <grp.h> // getgrnam()
73 #include <crt_externs.h>
74 #define environ (*_NSGetEnviron())
75 #elif !defined(_MSC_VER)
76 extern char **environ;
82 using v8::ArrayBuffer;
85 using v8::EscapableHandleScope;
88 using v8::FunctionCallbackInfo;
89 using v8::FunctionTemplate;
91 using v8::HandleScope;
92 using v8::HeapStatistics;
100 using v8::ObjectTemplate;
102 using v8::PromiseRejectMessage;
103 using v8::PropertyCallbackInfo;
109 using v8::kExternalUint32Array;
111 static bool print_eval = false;
112 static bool force_repl = false;
113 static bool trace_deprecation = false;
114 static bool throw_deprecation = false;
115 static bool abort_on_uncaught_exception = false;
116 static const char* eval_string = nullptr;
117 static unsigned int preload_module_count = 0;
118 static const char** preload_modules = nullptr;
119 static bool use_debug_agent = false;
120 static bool debug_wait_connect = false;
121 static int debug_port = 5858;
122 static bool v8_is_profiling = false;
123 static bool node_is_initialized = false;
124 static node_module* modpending;
125 static node_module* modlist_builtin;
126 static node_module* modlist_linked;
127 static node_module* modlist_addon;
129 #if defined(NODE_HAVE_I18N_SUPPORT)
130 // Path to ICU data (for i18n / Intl)
131 static const char* icu_data_dir = nullptr;
134 // used by C++ modules as well
135 bool no_deprecation = false;
137 // process-relative uptime base, initialized at start-up
138 static double prog_start_time;
139 static bool debugger_running;
140 static uv_async_t dispatch_debug_messages_async;
142 static Isolate* node_isolate = nullptr;
144 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
146 // Impose an upper limit to avoid out of memory errors that bring down
148 static const size_t kMaxLength = 0x3fffffff;
149 static ArrayBufferAllocator the_singleton;
150 virtual ~ArrayBufferAllocator() = default;
151 virtual void* Allocate(size_t length) override;
152 virtual void* AllocateUninitialized(size_t length) override;
153 virtual void Free(void* data, size_t length) override;
155 ArrayBufferAllocator() = default;
156 DISALLOW_COPY_AND_ASSIGN(ArrayBufferAllocator);
159 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
162 void* ArrayBufferAllocator::Allocate(size_t length) {
163 if (length > kMaxLength)
165 char* data = new char[length];
166 memset(data, 0, length);
171 void* ArrayBufferAllocator::AllocateUninitialized(size_t length) {
172 if (length > kMaxLength)
174 return new char[length];
178 void ArrayBufferAllocator::Free(void* data, size_t length) {
179 delete[] static_cast<char*>(data);
183 static void CheckImmediate(uv_check_t* handle) {
184 Environment* env = Environment::from_immediate_check_handle(handle);
185 HandleScope scope(env->isolate());
186 Context::Scope context_scope(env->context());
187 MakeCallback(env, env->process_object(), env->immediate_callback_string());
191 static void IdleImmediateDummy(uv_idle_t* handle) {
192 // Do nothing. Only for maintaining event loop.
193 // TODO(bnoordhuis) Maybe make libuv accept nullptr idle callbacks.
197 static inline const char *errno_string(int errorno) {
198 #define ERRNO_CASE(e) case e: return #e;
205 ERRNO_CASE(EADDRINUSE);
209 ERRNO_CASE(EADDRNOTAVAIL);
213 ERRNO_CASE(EAFNOSUPPORT);
221 # if EAGAIN != EWOULDBLOCK
222 ERRNO_CASE(EWOULDBLOCK);
227 ERRNO_CASE(EALREADY);
243 ERRNO_CASE(ECANCELED);
251 ERRNO_CASE(ECONNABORTED);
255 ERRNO_CASE(ECONNREFUSED);
259 ERRNO_CASE(ECONNRESET);
267 ERRNO_CASE(EDESTADDRREQ);
291 ERRNO_CASE(EHOSTUNREACH);
303 ERRNO_CASE(EINPROGRESS);
339 ERRNO_CASE(EMSGSIZE);
343 ERRNO_CASE(EMULTIHOP);
347 ERRNO_CASE(ENAMETOOLONG);
351 ERRNO_CASE(ENETDOWN);
355 ERRNO_CASE(ENETRESET);
359 ERRNO_CASE(ENETUNREACH);
391 # if ENOLINK != ENOLCK
405 ERRNO_CASE(ENOPROTOOPT);
425 ERRNO_CASE(ENOTCONN);
433 ERRNO_CASE(ENOTEMPTY);
437 ERRNO_CASE(ENOTSOCK);
444 ERRNO_CASE(EOPNOTSUPP);
458 ERRNO_CASE(EOVERFLOW);
473 #ifdef EPROTONOSUPPORT
474 ERRNO_CASE(EPROTONOSUPPORT);
478 ERRNO_CASE(EPROTOTYPE);
506 ERRNO_CASE(ETIMEDOUT);
521 const char *signo_string(int signo) {
522 #define SIGNO_CASE(e) case e: return #e;
549 # if SIGABRT != SIGIOT
593 SIGNO_CASE(SIGSTKFLT);
610 SIGNO_CASE(SIGBREAK);
634 SIGNO_CASE(SIGVTALRM);
642 SIGNO_CASE(SIGWINCH);
650 # if SIGPOLL != SIGIO
660 # if SIGPWR != SIGLOST
674 // Convenience methods
677 void ThrowError(v8::Isolate* isolate, const char* errmsg) {
678 Environment::GetCurrent(isolate)->ThrowError(errmsg);
682 void ThrowTypeError(v8::Isolate* isolate, const char* errmsg) {
683 Environment::GetCurrent(isolate)->ThrowTypeError(errmsg);
687 void ThrowRangeError(v8::Isolate* isolate, const char* errmsg) {
688 Environment::GetCurrent(isolate)->ThrowRangeError(errmsg);
692 void ThrowErrnoException(v8::Isolate* isolate,
697 Environment::GetCurrent(isolate)->ThrowErrnoException(errorno,
704 void ThrowUVException(v8::Isolate* isolate,
710 Environment::GetCurrent(isolate)
711 ->ThrowUVException(errorno, syscall, message, path, dest);
715 Local<Value> ErrnoException(Isolate* isolate,
720 Environment* env = Environment::GetCurrent(isolate);
723 Local<String> estring = OneByteString(env->isolate(), errno_string(errorno));
724 if (msg == nullptr || msg[0] == '\0') {
725 msg = strerror(errorno);
727 Local<String> message = OneByteString(env->isolate(), msg);
730 String::Concat(estring, FIXED_ONE_BYTE_STRING(env->isolate(), ", "));
731 cons = String::Concat(cons, message);
733 Local<String> path_string;
734 if (path != nullptr) {
735 // FIXME(bnoordhuis) It's questionable to interpret the file path as UTF-8.
736 path_string = String::NewFromUtf8(env->isolate(), path);
739 if (path_string.IsEmpty() == false) {
740 cons = String::Concat(cons, FIXED_ONE_BYTE_STRING(env->isolate(), " '"));
741 cons = String::Concat(cons, path_string);
742 cons = String::Concat(cons, FIXED_ONE_BYTE_STRING(env->isolate(), "'"));
744 e = Exception::Error(cons);
746 Local<Object> obj = e->ToObject(env->isolate());
747 obj->Set(env->errno_string(), Integer::New(env->isolate(), errorno));
748 obj->Set(env->code_string(), estring);
750 if (path_string.IsEmpty() == false) {
751 obj->Set(env->path_string(), path_string);
754 if (syscall != nullptr) {
755 obj->Set(env->syscall_string(), OneByteString(env->isolate(), syscall));
762 static Local<String> StringFromPath(Isolate* isolate, const char* path) {
764 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
765 return String::Concat(FIXED_ONE_BYTE_STRING(isolate, "\\\\"),
766 String::NewFromUtf8(isolate, path + 8));
767 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
768 return String::NewFromUtf8(isolate, path + 4);
772 return String::NewFromUtf8(isolate, path);
776 Local<Value> UVException(Isolate* isolate,
781 return UVException(isolate, errorno, syscall, msg, path, nullptr);
785 Local<Value> UVException(Isolate* isolate,
791 Environment* env = Environment::GetCurrent(isolate);
794 msg = uv_strerror(errorno);
796 Local<String> js_code = OneByteString(isolate, uv_err_name(errorno));
797 Local<String> js_syscall = OneByteString(isolate, syscall);
798 Local<String> js_path;
799 Local<String> js_dest;
801 Local<String> js_msg = js_code;
802 js_msg = String::Concat(js_msg, FIXED_ONE_BYTE_STRING(isolate, ": "));
803 js_msg = String::Concat(js_msg, OneByteString(isolate, msg));
804 js_msg = String::Concat(js_msg, FIXED_ONE_BYTE_STRING(isolate, ", "));
805 js_msg = String::Concat(js_msg, js_syscall);
807 if (path != nullptr) {
808 js_path = StringFromPath(isolate, path);
810 js_msg = String::Concat(js_msg, FIXED_ONE_BYTE_STRING(isolate, " '"));
811 js_msg = String::Concat(js_msg, js_path);
812 js_msg = String::Concat(js_msg, FIXED_ONE_BYTE_STRING(isolate, "'"));
815 if (dest != nullptr) {
816 js_dest = StringFromPath(isolate, dest);
818 js_msg = String::Concat(js_msg, FIXED_ONE_BYTE_STRING(isolate, " -> '"));
819 js_msg = String::Concat(js_msg, js_dest);
820 js_msg = String::Concat(js_msg, FIXED_ONE_BYTE_STRING(isolate, "'"));
823 Local<Object> e = Exception::Error(js_msg)->ToObject(isolate);
825 // TODO(piscisaureus) errno should probably go; the user has no way of
826 // knowing which uv errno value maps to which error.
827 e->Set(env->errno_string(), Integer::New(isolate, errorno));
828 e->Set(env->code_string(), js_code);
829 e->Set(env->syscall_string(), js_syscall);
830 if (!js_path.IsEmpty())
831 e->Set(env->path_string(), js_path);
832 if (!js_dest.IsEmpty())
833 e->Set(env->dest_string(), js_dest);
839 // Look up environment variable unless running as setuid root.
840 inline const char* secure_getenv(const char* key) {
842 if (getuid() != geteuid() || getgid() != getegid())
850 // Does about the same as strerror(),
851 // but supports all windows error messages
852 static const char *winapi_strerror(const int errorno, bool* must_free) {
853 char *errmsg = nullptr;
855 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
856 FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorno,
857 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, nullptr);
862 // Remove trailing newlines
863 for (int i = strlen(errmsg) - 1;
864 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
870 // FormatMessage failed
872 return "Unknown error";
877 Local<Value> WinapiErrnoException(Isolate* isolate,
882 Environment* env = Environment::GetCurrent(isolate);
884 bool must_free = false;
885 if (!msg || !msg[0]) {
886 msg = winapi_strerror(errorno, &must_free);
888 Local<String> message = OneByteString(env->isolate(), msg);
891 Local<String> cons1 =
892 String::Concat(message, FIXED_ONE_BYTE_STRING(isolate, " '"));
893 Local<String> cons2 =
894 String::Concat(cons1, String::NewFromUtf8(isolate, path));
895 Local<String> cons3 =
896 String::Concat(cons2, FIXED_ONE_BYTE_STRING(isolate, "'"));
897 e = Exception::Error(cons3);
899 e = Exception::Error(message);
902 Local<Object> obj = e->ToObject(env->isolate());
903 obj->Set(env->errno_string(), Integer::New(isolate, errorno));
905 if (path != nullptr) {
906 obj->Set(env->path_string(), String::NewFromUtf8(isolate, path));
909 if (syscall != nullptr) {
910 obj->Set(env->syscall_string(), OneByteString(isolate, syscall));
914 LocalFree((HLOCAL)msg);
921 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
922 Environment* env = Environment::GetCurrent(args);
924 if (env->using_domains())
926 env->set_using_domains(true);
928 HandleScope scope(env->isolate());
929 Local<Object> process_object = env->process_object();
931 Local<String> tick_callback_function_key = env->tick_domain_cb_string();
932 Local<Function> tick_callback_function =
933 process_object->Get(tick_callback_function_key).As<Function>();
935 if (!tick_callback_function->IsFunction()) {
936 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
940 process_object->Set(env->tick_callback_string(), tick_callback_function);
941 env->set_tick_callback_function(tick_callback_function);
943 CHECK(args[0]->IsArray());
944 CHECK(args[1]->IsObject());
946 env->set_domain_array(args[0].As<Array>());
948 Local<Object> domain_flag_obj = args[1].As<Object>();
949 Environment::DomainFlag* domain_flag = env->domain_flag();
950 domain_flag_obj->SetIndexedPropertiesToExternalArrayData(
951 domain_flag->fields(),
952 kExternalUint32Array,
953 domain_flag->fields_count());
955 // Do a little housekeeping.
956 env->process_object()->Delete(
957 FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupDomainUse"));
960 void RunMicrotasks(const FunctionCallbackInfo<Value>& args) {
961 args.GetIsolate()->RunMicrotasks();
965 void SetupNextTick(const FunctionCallbackInfo<Value>& args) {
966 Environment* env = Environment::GetCurrent(args);
968 CHECK(args[0]->IsObject());
969 CHECK(args[1]->IsFunction());
970 CHECK(args[2]->IsObject());
972 // Values use to cross communicate with processNextTick.
973 Local<Object> tick_info_obj = args[0].As<Object>();
974 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
975 env->tick_info()->fields(),
976 kExternalUint32Array,
977 env->tick_info()->fields_count());
979 env->set_tick_callback_function(args[1].As<Function>());
981 env->SetMethod(args[2].As<Object>(), "runMicrotasks", RunMicrotasks);
983 // Do a little housekeeping.
984 env->process_object()->Delete(
985 FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupNextTick"));
988 void PromiseRejectCallback(PromiseRejectMessage message) {
989 Local<Promise> promise = message.GetPromise();
990 Isolate* isolate = promise->GetIsolate();
991 Local<Value> value = message.GetValue();
992 Local<Integer> event = Integer::New(isolate, message.GetEvent());
994 Environment* env = Environment::GetCurrent(isolate);
995 Local<Function> callback = env->promise_reject_function();
998 value = Undefined(isolate);
1000 Local<Value> args[] = { event, promise, value };
1001 Local<Object> process = env->process_object();
1003 callback->Call(process, ARRAY_SIZE(args), args);
1006 void SetupPromises(const FunctionCallbackInfo<Value>& args) {
1007 Environment* env = Environment::GetCurrent(args);
1008 Isolate* isolate = env->isolate();
1010 CHECK(args[0]->IsFunction());
1012 isolate->SetPromiseRejectCallback(PromiseRejectCallback);
1013 env->set_promise_reject_function(args[0].As<Function>());
1015 env->process_object()->Delete(
1016 FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupPromises"));
1020 Handle<Value> MakeCallback(Environment* env,
1022 const Handle<Function> callback,
1024 Handle<Value> argv[]) {
1025 // If you hit this assertion, you forgot to enter the v8::Context first.
1026 CHECK_EQ(env->context(), env->isolate()->GetCurrentContext());
1028 Local<Object> process = env->process_object();
1029 Local<Object> object, domain;
1030 bool has_async_queue = false;
1031 bool has_domain = false;
1033 if (recv->IsObject()) {
1034 object = recv.As<Object>();
1035 Local<Value> async_queue_v = object->Get(env->async_queue_string());
1036 if (async_queue_v->IsObject())
1037 has_async_queue = true;
1040 if (env->using_domains()) {
1041 CHECK(recv->IsObject());
1042 Local<Value> domain_v = object->Get(env->domain_string());
1043 has_domain = domain_v->IsObject();
1045 domain = domain_v.As<Object>();
1046 if (domain->Get(env->disposed_string())->IsTrue())
1047 return Undefined(env->isolate());
1052 try_catch.SetVerbose(true);
1055 Local<Value> enter_v = domain->Get(env->enter_string());
1056 if (enter_v->IsFunction()) {
1057 enter_v.As<Function>()->Call(domain, 0, nullptr);
1058 if (try_catch.HasCaught())
1059 return Undefined(env->isolate());
1063 if (has_async_queue) {
1064 try_catch.SetVerbose(false);
1065 env->async_hooks_pre_function()->Call(object, 0, nullptr);
1066 if (try_catch.HasCaught())
1067 FatalError("node::MakeCallback", "pre hook threw");
1068 try_catch.SetVerbose(true);
1071 Local<Value> ret = callback->Call(recv, argc, argv);
1073 if (has_async_queue) {
1074 try_catch.SetVerbose(false);
1075 env->async_hooks_post_function()->Call(object, 0, nullptr);
1076 if (try_catch.HasCaught())
1077 FatalError("node::MakeCallback", "post hook threw");
1078 try_catch.SetVerbose(true);
1082 Local<Value> exit_v = domain->Get(env->exit_string());
1083 if (exit_v->IsFunction()) {
1084 exit_v.As<Function>()->Call(domain, 0, nullptr);
1085 if (try_catch.HasCaught())
1086 return Undefined(env->isolate());
1089 env->tick_callback_function()->Call(process, 0, nullptr);
1090 CHECK_EQ(env->context(), env->isolate()->GetCurrentContext());
1092 if (try_catch.HasCaught()) {
1093 return Undefined(env->isolate());
1096 Environment::TickInfo* tick_info = env->tick_info();
1098 if (tick_info->in_tick()) {
1102 if (tick_info->length() == 0) {
1103 env->isolate()->RunMicrotasks();
1106 if (tick_info->length() == 0) {
1107 tick_info->set_index(0);
1111 tick_info->set_in_tick(true);
1113 // process nextTicks after call
1114 env->tick_callback_function()->Call(process, 0, nullptr);
1116 tick_info->set_in_tick(false);
1118 if (try_catch.HasCaught()) {
1119 tick_info->set_last_threw(true);
1120 return Undefined(env->isolate());
1128 Handle<Value> MakeCallback(Environment* env,
1129 Handle<Object> recv,
1132 Handle<Value> argv[]) {
1133 Local<Value> cb_v = recv->Get(index);
1134 CHECK(cb_v->IsFunction());
1135 return MakeCallback(env, recv.As<Value>(), cb_v.As<Function>(), argc, argv);
1139 Handle<Value> MakeCallback(Environment* env,
1140 Handle<Object> recv,
1141 Handle<String> symbol,
1143 Handle<Value> argv[]) {
1144 Local<Value> cb_v = recv->Get(symbol);
1145 CHECK(cb_v->IsFunction());
1146 return MakeCallback(env, recv.As<Value>(), cb_v.As<Function>(), argc, argv);
1150 Handle<Value> MakeCallback(Environment* env,
1151 Handle<Object> recv,
1154 Handle<Value> argv[]) {
1155 Local<String> method_string = OneByteString(env->isolate(), method);
1156 return MakeCallback(env, recv, method_string, argc, argv);
1160 Handle<Value> MakeCallback(Isolate* isolate,
1161 Handle<Object> recv,
1164 Handle<Value> argv[]) {
1165 EscapableHandleScope handle_scope(isolate);
1166 Local<Context> context = recv->CreationContext();
1167 Environment* env = Environment::GetCurrent(context);
1168 Context::Scope context_scope(context);
1169 return handle_scope.Escape(
1170 Local<Value>::New(isolate, MakeCallback(env, recv, method, argc, argv)));
1174 Handle<Value> MakeCallback(Isolate* isolate,
1175 Handle<Object> recv,
1176 Handle<String> symbol,
1178 Handle<Value> argv[]) {
1179 EscapableHandleScope handle_scope(isolate);
1180 Local<Context> context = recv->CreationContext();
1181 Environment* env = Environment::GetCurrent(context);
1182 Context::Scope context_scope(context);
1183 return handle_scope.Escape(
1184 Local<Value>::New(isolate, MakeCallback(env, recv, symbol, argc, argv)));
1188 Handle<Value> MakeCallback(Isolate* isolate,
1189 Handle<Object> recv,
1190 Handle<Function> callback,
1192 Handle<Value> argv[]) {
1193 EscapableHandleScope handle_scope(isolate);
1194 Local<Context> context = recv->CreationContext();
1195 Environment* env = Environment::GetCurrent(context);
1196 Context::Scope context_scope(context);
1197 return handle_scope.Escape(Local<Value>::New(
1199 MakeCallback(env, recv.As<Value>(), callback, argc, argv)));
1203 enum encoding ParseEncoding(const char* encoding,
1204 enum encoding default_encoding) {
1205 switch (encoding[0]) {
1208 if (encoding[1] == 't' && encoding[2] == 'f') {
1210 encoding += encoding[3] == '-' ? 4 : 3;
1211 if (encoding[0] == '8' && encoding[1] == '\0')
1213 if (strncmp(encoding, "16le", 4) == 0)
1217 } else if (encoding[1] == 'c' && encoding[2] == 's') {
1218 encoding += encoding[3] == '-' ? 4 : 3;
1219 if (encoding[0] == '2' && encoding[1] == '\0')
1225 if (encoding[1] == 'i') {
1226 if (strncmp(encoding + 2, "nary", 4) == 0)
1230 } else if (encoding[1] == 'u') {
1231 if (strncmp(encoding + 2, "ffer", 4) == 0)
1236 return default_encoding;
1241 if (strcasecmp(encoding, "utf8") == 0) {
1243 } else if (strcasecmp(encoding, "utf-8") == 0) {
1245 } else if (strcasecmp(encoding, "ascii") == 0) {
1247 } else if (strcasecmp(encoding, "base64") == 0) {
1249 } else if (strcasecmp(encoding, "ucs2") == 0) {
1251 } else if (strcasecmp(encoding, "ucs-2") == 0) {
1253 } else if (strcasecmp(encoding, "utf16le") == 0) {
1255 } else if (strcasecmp(encoding, "utf-16le") == 0) {
1257 } else if (strcasecmp(encoding, "binary") == 0) {
1259 } else if (strcasecmp(encoding, "buffer") == 0) {
1261 } else if (strcasecmp(encoding, "hex") == 0) {
1263 } else if (strcasecmp(encoding, "raw") == 0) {
1264 if (!no_deprecation) {
1265 fprintf(stderr, "'raw' (array of integers) has been removed. "
1269 } else if (strcasecmp(encoding, "raws") == 0) {
1270 if (!no_deprecation) {
1271 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1272 "Please update your code.\n");
1276 return default_encoding;
1281 enum encoding ParseEncoding(Isolate* isolate,
1282 Handle<Value> encoding_v,
1283 enum encoding default_encoding) {
1284 if (!encoding_v->IsString())
1285 return default_encoding;
1287 node::Utf8Value encoding(isolate, encoding_v);
1289 return ParseEncoding(*encoding, default_encoding);
1292 Local<Value> Encode(Isolate* isolate,
1295 enum encoding encoding) {
1296 CHECK_NE(encoding, UCS2);
1297 return StringBytes::Encode(isolate, buf, len, encoding);
1300 Local<Value> Encode(Isolate* isolate, const uint16_t* buf, size_t len) {
1301 return StringBytes::Encode(isolate, buf, len);
1304 // Returns -1 if the handle was not valid for decoding
1305 ssize_t DecodeBytes(Isolate* isolate,
1307 enum encoding encoding) {
1308 HandleScope scope(isolate);
1310 if (val->IsArray()) {
1311 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1317 return StringBytes::Size(isolate, val, encoding);
1320 // Returns number of bytes written.
1321 ssize_t DecodeWrite(Isolate* isolate,
1325 enum encoding encoding) {
1326 return StringBytes::Write(isolate, buf, buflen, val, encoding, nullptr);
1329 void AppendExceptionLine(Environment* env,
1331 Handle<Message> message) {
1332 if (message.IsEmpty())
1335 HandleScope scope(env->isolate());
1336 Local<Object> err_obj;
1337 if (!er.IsEmpty() && er->IsObject()) {
1338 err_obj = er.As<Object>();
1340 // Do it only once per message
1341 if (!err_obj->GetHiddenValue(env->processed_string()).IsEmpty())
1343 err_obj->SetHiddenValue(env->processed_string(), True(env->isolate()));
1348 // Print (filename):(line number): (message).
1349 node::Utf8Value filename(env->isolate(), message->GetScriptResourceName());
1350 const char* filename_string = *filename;
1351 int linenum = message->GetLineNumber();
1352 // Print line of source code.
1353 node::Utf8Value sourceline(env->isolate(), message->GetSourceLine());
1354 const char* sourceline_string = *sourceline;
1356 // Because of how node modules work, all scripts are wrapped with a
1357 // "function (module, exports, __filename, ...) {"
1358 // to provide script local variables.
1360 // When reporting errors on the first line of a script, this wrapper
1361 // function is leaked to the user. There used to be a hack here to
1362 // truncate off the first 62 characters, but it caused numerous other
1363 // problems when vm.runIn*Context() methods were used for non-module
1366 // If we ever decide to re-instate such a hack, the following steps
1369 // 1. Pass a flag around to say "this code was wrapped"
1370 // 2. Update the stack frame output so that it is also correct.
1372 // It would probably be simpler to add a line rather than add some
1373 // number of characters to the first line, since V8 truncates the
1374 // sourceline to 78 characters, and we end up not providing very much
1375 // useful debugging info to the user if we remove 62 characters.
1377 int start = message->GetStartColumn();
1378 int end = message->GetEndColumn();
1380 int off = snprintf(arrow,
1388 // Print wavy underline (GetUnderline is deprecated).
1389 for (int i = 0; i < start; i++) {
1390 if (sourceline_string[i] == '\0' ||
1391 static_cast<size_t>(off) >= sizeof(arrow)) {
1394 CHECK_LT(static_cast<size_t>(off), sizeof(arrow));
1395 arrow[off++] = (sourceline_string[i] == '\t') ? '\t' : ' ';
1397 for (int i = start; i < end; i++) {
1398 if (sourceline_string[i] == '\0' ||
1399 static_cast<size_t>(off) >= sizeof(arrow)) {
1402 CHECK_LT(static_cast<size_t>(off), sizeof(arrow));
1405 CHECK_LE(static_cast<size_t>(off - 1), sizeof(arrow) - 1);
1406 arrow[off++] = '\n';
1409 Local<String> arrow_str = String::NewFromUtf8(env->isolate(), arrow);
1413 // Allocation failed, just print it out
1414 if (arrow_str.IsEmpty() || err_obj.IsEmpty() || !err_obj->IsNativeError())
1417 msg = err_obj->Get(env->message_string());
1418 stack = err_obj->Get(env->stack_string());
1420 if (msg.IsEmpty() || stack.IsEmpty())
1423 err_obj->Set(env->message_string(),
1424 String::Concat(arrow_str, msg->ToString(env->isolate())));
1425 err_obj->Set(env->stack_string(),
1426 String::Concat(arrow_str, stack->ToString(env->isolate())));
1430 if (env->printed_error())
1432 env->set_printed_error(true);
1433 uv_tty_reset_mode();
1434 fprintf(stderr, "\n%s", arrow);
1438 static void ReportException(Environment* env,
1440 Handle<Message> message) {
1441 HandleScope scope(env->isolate());
1443 AppendExceptionLine(env, er, message);
1445 Local<Value> trace_value;
1447 if (er->IsUndefined() || er->IsNull())
1448 trace_value = Undefined(env->isolate());
1450 trace_value = er->ToObject(env->isolate())->Get(env->stack_string());
1452 node::Utf8Value trace(env->isolate(), trace_value);
1454 // range errors have a trace member set to undefined
1455 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1456 fprintf(stderr, "%s\n", *trace);
1458 // this really only happens for RangeErrors, since they're the only
1459 // kind that won't have all this info in the trace, or when non-Error
1460 // objects are thrown manually.
1461 Local<Value> message;
1464 if (er->IsObject()) {
1465 Local<Object> err_obj = er.As<Object>();
1466 message = err_obj->Get(env->message_string());
1467 name = err_obj->Get(FIXED_ONE_BYTE_STRING(env->isolate(), "name"));
1470 if (message.IsEmpty() ||
1471 message->IsUndefined() ||
1473 name->IsUndefined()) {
1474 // Not an error object. Just print as-is.
1475 node::Utf8Value message(env->isolate(), er);
1476 fprintf(stderr, "%s\n", *message);
1478 node::Utf8Value name_string(env->isolate(), name);
1479 node::Utf8Value message_string(env->isolate(), message);
1480 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1488 static void ReportException(Environment* env, const TryCatch& try_catch) {
1489 ReportException(env, try_catch.Exception(), try_catch.Message());
1493 // Executes a str within the current v8 context.
1494 static Local<Value> ExecuteString(Environment* env,
1495 Handle<String> source,
1496 Handle<String> filename) {
1497 EscapableHandleScope scope(env->isolate());
1500 // try_catch must be nonverbose to disable FatalException() handler,
1501 // we will handle exceptions ourself.
1502 try_catch.SetVerbose(false);
1504 Local<v8::Script> script = v8::Script::Compile(source, filename);
1505 if (script.IsEmpty()) {
1506 ReportException(env, try_catch);
1510 Local<Value> result = script->Run();
1511 if (result.IsEmpty()) {
1512 ReportException(env, try_catch);
1516 return scope.Escape(result);
1520 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1521 Environment* env = Environment::GetCurrent(args);
1523 Local<Array> ary = Array::New(args.GetIsolate());
1526 for (auto w : *env->req_wrap_queue())
1527 if (w->persistent().IsEmpty() == false)
1528 ary->Set(i++, w->object());
1530 args.GetReturnValue().Set(ary);
1534 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1535 // implemented here for consistency with GetActiveRequests().
1536 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1537 Environment* env = Environment::GetCurrent(args);
1539 Local<Array> ary = Array::New(env->isolate());
1542 Local<String> owner_sym = env->owner_string();
1544 for (auto w : *env->handle_wrap_queue()) {
1545 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref))
1547 Local<Object> object = w->object();
1548 Local<Value> owner = object->Get(owner_sym);
1549 if (owner->IsUndefined())
1551 ary->Set(i++, owner);
1554 args.GetReturnValue().Set(ary);
1558 static void Abort(const FunctionCallbackInfo<Value>& args) {
1563 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1564 Environment* env = Environment::GetCurrent(args);
1566 if (args.Length() != 1 || !args[0]->IsString()) {
1567 return env->ThrowTypeError("Bad argument.");
1570 node::Utf8Value path(args.GetIsolate(), args[0]);
1571 int err = uv_chdir(*path);
1573 return env->ThrowUVException(err, "uv_chdir");
1578 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1579 Environment* env = Environment::GetCurrent(args);
1581 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1582 char buf[MAX_PATH * 4];
1587 size_t cwd_len = sizeof(buf);
1588 int err = uv_cwd(buf, &cwd_len);
1590 return env->ThrowUVException(err, "uv_cwd");
1593 Local<String> cwd = String::NewFromUtf8(env->isolate(),
1595 String::kNormalString,
1597 args.GetReturnValue().Set(cwd);
1601 static void Umask(const FunctionCallbackInfo<Value>& args) {
1602 Environment* env = Environment::GetCurrent(args);
1605 if (args.Length() < 1 || args[0]->IsUndefined()) {
1607 umask(static_cast<mode_t>(old));
1608 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1609 return env->ThrowTypeError("argument must be an integer or octal string.");
1612 if (args[0]->IsInt32()) {
1613 oct = args[0]->Uint32Value();
1616 node::Utf8Value str(env->isolate(), args[0]);
1618 // Parse the octal string.
1619 for (size_t i = 0; i < str.length(); i++) {
1621 if (c > '7' || c < '0') {
1622 return env->ThrowTypeError("invalid octal string");
1628 old = umask(static_cast<mode_t>(oct));
1631 args.GetReturnValue().Set(old);
1635 #if defined(__POSIX__) && !defined(__ANDROID__)
1637 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1638 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1641 static uid_t uid_by_name(const char* name) {
1649 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != nullptr) {
1653 return uid_not_found;
1657 static char* name_by_uid(uid_t uid) {
1666 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 &&
1668 return strdup(pp->pw_name);
1679 static gid_t gid_by_name(const char* name) {
1687 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != nullptr) {
1691 return gid_not_found;
1695 #if 0 // For future use.
1696 static const char* name_by_gid(gid_t gid) {
1705 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 &&
1707 return strdup(pp->gr_name);
1719 static uid_t uid_by_name(Isolate* isolate, Handle<Value> value) {
1720 if (value->IsUint32()) {
1721 return static_cast<uid_t>(value->Uint32Value());
1723 node::Utf8Value name(isolate, value);
1724 return uid_by_name(*name);
1729 static gid_t gid_by_name(Isolate* isolate, Handle<Value> value) {
1730 if (value->IsUint32()) {
1731 return static_cast<gid_t>(value->Uint32Value());
1733 node::Utf8Value name(isolate, value);
1734 return gid_by_name(*name);
1739 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1740 // uid_t is an uint32_t on all supported platforms.
1741 args.GetReturnValue().Set(static_cast<uint32_t>(getuid()));
1745 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1746 // gid_t is an uint32_t on all supported platforms.
1747 args.GetReturnValue().Set(static_cast<uint32_t>(getgid()));
1751 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1752 Environment* env = Environment::GetCurrent(args);
1754 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1755 return env->ThrowTypeError("setgid argument must be a number or a string");
1758 gid_t gid = gid_by_name(env->isolate(), args[0]);
1760 if (gid == gid_not_found) {
1761 return env->ThrowError("setgid group id does not exist");
1765 return env->ThrowErrnoException(errno, "setgid");
1770 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1771 Environment* env = Environment::GetCurrent(args);
1773 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1774 return env->ThrowTypeError("setuid argument must be a number or a string");
1777 uid_t uid = uid_by_name(env->isolate(), args[0]);
1779 if (uid == uid_not_found) {
1780 return env->ThrowError("setuid user id does not exist");
1784 return env->ThrowErrnoException(errno, "setuid");
1789 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1790 Environment* env = Environment::GetCurrent(args);
1792 int ngroups = getgroups(0, nullptr);
1794 if (ngroups == -1) {
1795 return env->ThrowErrnoException(errno, "getgroups");
1798 gid_t* groups = new gid_t[ngroups];
1800 ngroups = getgroups(ngroups, groups);
1802 if (ngroups == -1) {
1804 return env->ThrowErrnoException(errno, "getgroups");
1807 Local<Array> groups_list = Array::New(env->isolate(), ngroups);
1808 bool seen_egid = false;
1809 gid_t egid = getegid();
1811 for (int i = 0; i < ngroups; i++) {
1812 groups_list->Set(i, Integer::New(env->isolate(), groups[i]));
1813 if (groups[i] == egid)
1819 if (seen_egid == false) {
1820 groups_list->Set(ngroups, Integer::New(env->isolate(), egid));
1823 args.GetReturnValue().Set(groups_list);
1827 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1828 Environment* env = Environment::GetCurrent(args);
1830 if (!args[0]->IsArray()) {
1831 return env->ThrowTypeError("argument 1 must be an array");
1834 Local<Array> groups_list = args[0].As<Array>();
1835 size_t size = groups_list->Length();
1836 gid_t* groups = new gid_t[size];
1838 for (size_t i = 0; i < size; i++) {
1839 gid_t gid = gid_by_name(env->isolate(), groups_list->Get(i));
1841 if (gid == gid_not_found) {
1843 return env->ThrowError("group name not found");
1849 int rc = setgroups(size, groups);
1853 return env->ThrowErrnoException(errno, "setgroups");
1858 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1859 Environment* env = Environment::GetCurrent(args);
1861 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1862 return env->ThrowTypeError("argument 1 must be a number or a string");
1865 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1866 return env->ThrowTypeError("argument 2 must be a number or a string");
1869 node::Utf8Value arg0(env->isolate(), args[0]);
1874 if (args[0]->IsUint32()) {
1875 user = name_by_uid(args[0]->Uint32Value());
1882 if (user == nullptr) {
1883 return env->ThrowError("initgroups user not found");
1886 extra_group = gid_by_name(env->isolate(), args[1]);
1888 if (extra_group == gid_not_found) {
1891 return env->ThrowError("initgroups extra group not found");
1894 int rc = initgroups(user, extra_group);
1901 return env->ThrowErrnoException(errno, "initgroups");
1905 #endif // __POSIX__ && !defined(__ANDROID__)
1908 void Exit(const FunctionCallbackInfo<Value>& args) {
1909 exit(args[0]->Int32Value());
1913 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1914 Environment* env = Environment::GetCurrent(args);
1917 uv_update_time(env->event_loop());
1918 uptime = uv_now(env->event_loop()) - prog_start_time;
1920 args.GetReturnValue().Set(Number::New(env->isolate(), uptime / 1000));
1924 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1925 Environment* env = Environment::GetCurrent(args);
1928 int err = uv_resident_set_memory(&rss);
1930 return env->ThrowUVException(err, "uv_resident_set_memory");
1934 HeapStatistics v8_heap_stats;
1935 env->isolate()->GetHeapStatistics(&v8_heap_stats);
1937 Local<Number> heap_total =
1938 Number::New(env->isolate(), v8_heap_stats.total_heap_size());
1939 Local<Number> heap_used =
1940 Number::New(env->isolate(), v8_heap_stats.used_heap_size());
1942 Local<Object> info = Object::New(env->isolate());
1943 info->Set(env->rss_string(), Number::New(env->isolate(), rss));
1944 info->Set(env->heap_total_string(), heap_total);
1945 info->Set(env->heap_used_string(), heap_used);
1947 args.GetReturnValue().Set(info);
1951 void Kill(const FunctionCallbackInfo<Value>& args) {
1952 Environment* env = Environment::GetCurrent(args);
1954 if (args.Length() != 2) {
1955 return env->ThrowError("Bad argument.");
1958 int pid = args[0]->Int32Value();
1959 int sig = args[1]->Int32Value();
1960 int err = uv_kill(pid, sig);
1961 args.GetReturnValue().Set(err);
1964 // used in Hrtime() below
1965 #define NANOS_PER_SEC 1000000000
1967 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1968 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1969 // so this function instead returns an Array with 2 entries representing seconds
1970 // and nanoseconds, to avoid any integer overflow possibility.
1971 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1972 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1973 Environment* env = Environment::GetCurrent(args);
1975 uint64_t t = uv_hrtime();
1977 if (args.Length() > 0) {
1978 // return a time diff tuple
1979 if (!args[0]->IsArray()) {
1980 return env->ThrowTypeError(
1981 "process.hrtime() only accepts an Array tuple.");
1983 Local<Array> inArray = Local<Array>::Cast(args[0]);
1984 uint64_t seconds = inArray->Get(0)->Uint32Value();
1985 uint64_t nanos = inArray->Get(1)->Uint32Value();
1986 t -= (seconds * NANOS_PER_SEC) + nanos;
1989 Local<Array> tuple = Array::New(env->isolate(), 2);
1990 tuple->Set(0, Integer::NewFromUnsigned(env->isolate(), t / NANOS_PER_SEC));
1991 tuple->Set(1, Integer::NewFromUnsigned(env->isolate(), t % NANOS_PER_SEC));
1992 args.GetReturnValue().Set(tuple);
1995 extern "C" void node_module_register(void* m) {
1996 struct node_module* mp = reinterpret_cast<struct node_module*>(m);
1998 if (mp->nm_flags & NM_F_BUILTIN) {
1999 mp->nm_link = modlist_builtin;
2000 modlist_builtin = mp;
2001 } else if (!node_is_initialized) {
2002 // "Linked" modules are included as part of the node project.
2003 // Like builtins they are registered *before* node::Init runs.
2004 mp->nm_flags = NM_F_LINKED;
2005 mp->nm_link = modlist_linked;
2006 modlist_linked = mp;
2012 struct node_module* get_builtin_module(const char* name) {
2013 struct node_module* mp;
2015 for (mp = modlist_builtin; mp != nullptr; mp = mp->nm_link) {
2016 if (strcmp(mp->nm_modname, name) == 0)
2020 CHECK(mp == nullptr || (mp->nm_flags & NM_F_BUILTIN) != 0);
2024 struct node_module* get_linked_module(const char* name) {
2025 struct node_module* mp;
2027 for (mp = modlist_linked; mp != nullptr; mp = mp->nm_link) {
2028 if (strcmp(mp->nm_modname, name) == 0)
2032 CHECK(mp == nullptr || (mp->nm_flags & NM_F_LINKED) != 0);
2036 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
2038 // DLOpen is process.dlopen(module, filename).
2039 // Used to load 'module.node' dynamically shared objects.
2041 // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
2042 // when two contexts try to load the same shared object. Maybe have a shadow
2043 // cache that's a plain C list or hash table that's shared across contexts?
2044 void DLOpen(const FunctionCallbackInfo<Value>& args) {
2045 Environment* env = Environment::GetCurrent(args);
2048 CHECK_EQ(modpending, nullptr);
2050 if (args.Length() != 2) {
2051 env->ThrowError("process.dlopen takes exactly 2 arguments.");
2055 Local<Object> module = args[0]->ToObject(env->isolate()); // Cast
2056 node::Utf8Value filename(env->isolate(), args[1]); // Cast
2057 const bool is_dlopen_error = uv_dlopen(*filename, &lib);
2059 // Objects containing v14 or later modules will have registered themselves
2060 // on the pending list. Activate all of them now. At present, only one
2061 // module per object is supported.
2062 node_module* const mp = modpending;
2063 modpending = nullptr;
2065 if (is_dlopen_error) {
2066 Local<String> errmsg = OneByteString(env->isolate(), uv_dlerror(&lib));
2068 // Windows needs to add the filename into the error message
2069 errmsg = String::Concat(errmsg, args[1]->ToString(env->isolate()));
2071 env->isolate()->ThrowException(Exception::Error(errmsg));
2075 if (mp == nullptr) {
2076 env->ThrowError("Module did not self-register.");
2079 if (mp->nm_version != NODE_MODULE_VERSION) {
2083 "Module version mismatch. Expected %d, got %d.",
2084 NODE_MODULE_VERSION, mp->nm_version);
2085 env->ThrowError(errmsg);
2088 if (mp->nm_flags & NM_F_BUILTIN) {
2089 env->ThrowError("Built-in module self-registered.");
2093 mp->nm_dso_handle = lib.handle;
2094 mp->nm_link = modlist_addon;
2097 Local<String> exports_string = env->exports_string();
2098 Local<Object> exports = module->Get(exports_string)->ToObject(env->isolate());
2100 if (mp->nm_context_register_func != nullptr) {
2101 mp->nm_context_register_func(exports, module, env->context(), mp->nm_priv);
2102 } else if (mp->nm_register_func != nullptr) {
2103 mp->nm_register_func(exports, module, mp->nm_priv);
2105 env->ThrowError("Module has no declared entry point.");
2109 // Tell coverity that 'handle' should not be freed when we return.
2110 // coverity[leaked_storage]
2114 static void OnFatalError(const char* location, const char* message) {
2116 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
2118 fprintf(stderr, "FATAL ERROR: %s\n", message);
2125 NO_RETURN void FatalError(const char* location, const char* message) {
2126 OnFatalError(location, message);
2127 // to supress compiler warning
2132 void FatalException(Isolate* isolate,
2133 Handle<Value> error,
2134 Handle<Message> message) {
2135 HandleScope scope(isolate);
2137 Environment* env = Environment::GetCurrent(isolate);
2138 Local<Object> process_object = env->process_object();
2139 Local<String> fatal_exception_string = env->fatal_exception_string();
2140 Local<Function> fatal_exception_function =
2141 process_object->Get(fatal_exception_string).As<Function>();
2143 if (!fatal_exception_function->IsFunction()) {
2144 // failed before the process._fatalException function was added!
2145 // this is probably pretty bad. Nothing to do but report and exit.
2146 ReportException(env, error, message);
2150 TryCatch fatal_try_catch;
2152 // Do not call FatalException when _fatalException handler throws
2153 fatal_try_catch.SetVerbose(false);
2155 // this will return true if the JS layer handled it, false otherwise
2156 Local<Value> caught =
2157 fatal_exception_function->Call(process_object, 1, &error);
2159 if (fatal_try_catch.HasCaught()) {
2160 // the fatal exception function threw, so we must exit
2161 ReportException(env, fatal_try_catch);
2165 if (false == caught->BooleanValue()) {
2166 ReportException(env, error, message);
2172 void FatalException(Isolate* isolate, const TryCatch& try_catch) {
2173 HandleScope scope(isolate);
2174 // TODO(bajtos) do not call FatalException if try_catch is verbose
2175 // (requires V8 API to expose getter for try_catch.is_verbose_)
2176 FatalException(isolate, try_catch.Exception(), try_catch.Message());
2180 void OnMessage(Handle<Message> message, Handle<Value> error) {
2181 // The current version of V8 sends messages for errors only
2182 // (thus `error` is always set).
2183 FatalException(Isolate::GetCurrent(), error, message);
2187 static void Binding(const FunctionCallbackInfo<Value>& args) {
2188 Environment* env = Environment::GetCurrent(args);
2190 Local<String> module = args[0]->ToString(env->isolate());
2191 node::Utf8Value module_v(env->isolate(), module);
2193 Local<Object> cache = env->binding_cache_object();
2194 Local<Object> exports;
2196 if (cache->Has(module)) {
2197 exports = cache->Get(module)->ToObject(env->isolate());
2198 args.GetReturnValue().Set(exports);
2202 // Append a string to process.moduleLoadList
2204 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
2206 Local<Array> modules = env->module_load_list_array();
2207 uint32_t l = modules->Length();
2208 modules->Set(l, OneByteString(env->isolate(), buf));
2210 node_module* mod = get_builtin_module(*module_v);
2211 if (mod != nullptr) {
2212 exports = Object::New(env->isolate());
2213 // Internal bindings don't have a "module" object, only exports.
2214 CHECK_EQ(mod->nm_register_func, nullptr);
2215 CHECK_NE(mod->nm_context_register_func, nullptr);
2216 Local<Value> unused = Undefined(env->isolate());
2217 mod->nm_context_register_func(exports, unused,
2218 env->context(), mod->nm_priv);
2219 cache->Set(module, exports);
2220 } else if (!strcmp(*module_v, "constants")) {
2221 exports = Object::New(env->isolate());
2222 DefineConstants(exports);
2223 cache->Set(module, exports);
2224 } else if (!strcmp(*module_v, "natives")) {
2225 exports = Object::New(env->isolate());
2226 DefineJavaScript(env, exports);
2227 cache->Set(module, exports);
2232 "No such module: %s",
2234 return env->ThrowError(errmsg);
2237 args.GetReturnValue().Set(exports);
2240 static void LinkedBinding(const FunctionCallbackInfo<Value>& args) {
2241 Environment* env = Environment::GetCurrent(args.GetIsolate());
2243 Local<String> module = args[0]->ToString(env->isolate());
2245 Local<Object> cache = env->binding_cache_object();
2246 Local<Value> exports_v = cache->Get(module);
2248 if (exports_v->IsObject())
2249 return args.GetReturnValue().Set(exports_v.As<Object>());
2251 node::Utf8Value module_v(env->isolate(), module);
2252 node_module* mod = get_linked_module(*module_v);
2254 if (mod == nullptr) {
2258 "No such module was linked: %s",
2260 return env->ThrowError(errmsg);
2263 Local<Object> exports = Object::New(env->isolate());
2265 if (mod->nm_context_register_func != nullptr) {
2266 mod->nm_context_register_func(exports,
2270 } else if (mod->nm_register_func != nullptr) {
2271 mod->nm_register_func(exports, module, mod->nm_priv);
2273 return env->ThrowError("Linked module has no declared entry point.");
2276 cache->Set(module, exports);
2278 args.GetReturnValue().Set(exports);
2281 static void ProcessTitleGetter(Local<String> property,
2282 const PropertyCallbackInfo<Value>& info) {
2283 Environment* env = Environment::GetCurrent(info.GetIsolate());
2284 HandleScope scope(env->isolate());
2286 uv_get_process_title(buffer, sizeof(buffer));
2287 info.GetReturnValue().Set(String::NewFromUtf8(env->isolate(), buffer));
2291 static void ProcessTitleSetter(Local<String> property,
2293 const PropertyCallbackInfo<void>& info) {
2294 Environment* env = Environment::GetCurrent(info.GetIsolate());
2295 HandleScope scope(env->isolate());
2296 node::Utf8Value title(env->isolate(), value);
2297 // TODO(piscisaureus): protect with a lock
2298 uv_set_process_title(*title);
2302 static void EnvGetter(Local<String> property,
2303 const PropertyCallbackInfo<Value>& info) {
2304 Environment* env = Environment::GetCurrent(info.GetIsolate());
2305 HandleScope scope(env->isolate());
2307 node::Utf8Value key(env->isolate(), property);
2308 const char* val = getenv(*key);
2310 return info.GetReturnValue().Set(String::NewFromUtf8(env->isolate(), val));
2313 String::Value key(property);
2314 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2315 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2317 ARRAY_SIZE(buffer));
2318 // If result >= sizeof buffer the buffer was too small. That should never
2319 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2321 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2322 result < ARRAY_SIZE(buffer)) {
2323 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2324 Local<String> rc = String::NewFromTwoByte(env->isolate(), two_byte_buffer);
2325 return info.GetReturnValue().Set(rc);
2328 // Not found. Fetch from prototype.
2329 info.GetReturnValue().Set(
2330 info.Data().As<Object>()->Get(property));
2334 static void EnvSetter(Local<String> property,
2336 const PropertyCallbackInfo<Value>& info) {
2337 Environment* env = Environment::GetCurrent(info.GetIsolate());
2338 HandleScope scope(env->isolate());
2340 node::Utf8Value key(env->isolate(), property);
2341 node::Utf8Value val(env->isolate(), value);
2342 setenv(*key, *val, 1);
2344 String::Value key(property);
2345 String::Value val(value);
2346 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2347 // Environment variables that start with '=' are read-only.
2348 if (key_ptr[0] != L'=') {
2349 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2352 // Whether it worked or not, always return rval.
2353 info.GetReturnValue().Set(value);
2357 static void EnvQuery(Local<String> property,
2358 const PropertyCallbackInfo<Integer>& info) {
2359 Environment* env = Environment::GetCurrent(info.GetIsolate());
2360 HandleScope scope(env->isolate());
2361 int32_t rc = -1; // Not found unless proven otherwise.
2363 node::Utf8Value key(env->isolate(), property);
2367 String::Value key(property);
2368 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2369 if (GetEnvironmentVariableW(key_ptr, nullptr, 0) > 0 ||
2370 GetLastError() == ERROR_SUCCESS) {
2372 if (key_ptr[0] == L'=') {
2373 // Environment variables that start with '=' are hidden and read-only.
2374 rc = static_cast<int32_t>(v8::ReadOnly) |
2375 static_cast<int32_t>(v8::DontDelete) |
2376 static_cast<int32_t>(v8::DontEnum);
2381 info.GetReturnValue().Set(rc);
2385 static void EnvDeleter(Local<String> property,
2386 const PropertyCallbackInfo<Boolean>& info) {
2387 Environment* env = Environment::GetCurrent(info.GetIsolate());
2388 HandleScope scope(env->isolate());
2391 node::Utf8Value key(env->isolate(), property);
2392 rc = getenv(*key) != nullptr;
2396 String::Value key(property);
2397 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2398 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, nullptr)) {
2399 // Deletion failed. Return true if the key wasn't there in the first place,
2400 // false if it is still there.
2401 rc = GetEnvironmentVariableW(key_ptr, nullptr, 0) == 0 &&
2402 GetLastError() != ERROR_SUCCESS;
2405 info.GetReturnValue().Set(rc);
2409 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2410 Environment* env = Environment::GetCurrent(info.GetIsolate());
2411 HandleScope scope(env->isolate());
2414 while (environ[size])
2417 Local<Array> envarr = Array::New(env->isolate(), size);
2419 for (int i = 0; i < size; ++i) {
2420 const char* var = environ[i];
2421 const char* s = strchr(var, '=');
2422 const int length = s ? s - var : strlen(var);
2423 Local<String> name = String::NewFromUtf8(env->isolate(),
2425 String::kNormalString,
2427 envarr->Set(i, name);
2430 WCHAR* environment = GetEnvironmentStringsW();
2431 if (environment == nullptr)
2432 return; // This should not happen.
2433 Local<Array> envarr = Array::New(env->isolate());
2434 WCHAR* p = environment;
2439 // If the key starts with '=' it is a hidden environment variable.
2443 s = wcschr(p, L'=');
2448 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2449 const size_t two_byte_buffer_len = s - p;
2450 Local<String> value = String::NewFromTwoByte(env->isolate(),
2452 String::kNormalString,
2453 two_byte_buffer_len);
2454 envarr->Set(i++, value);
2455 p = s + wcslen(s) + 1;
2457 FreeEnvironmentStringsW(environment);
2460 info.GetReturnValue().Set(envarr);
2464 static Handle<Object> GetFeatures(Environment* env) {
2465 EscapableHandleScope scope(env->isolate());
2467 Local<Object> obj = Object::New(env->isolate());
2468 #if defined(DEBUG) && DEBUG
2469 Local<Value> debug = True(env->isolate());
2471 Local<Value> debug = False(env->isolate());
2472 #endif // defined(DEBUG) && DEBUG
2474 obj->Set(env->debug_string(), debug);
2476 obj->Set(env->uv_string(), True(env->isolate()));
2477 // TODO(bnoordhuis) ping libuv
2478 obj->Set(env->ipv6_lc_string(), True(env->isolate()));
2480 #ifdef OPENSSL_NPN_NEGOTIATED
2481 Local<Boolean> tls_npn = True(env->isolate());
2483 Local<Boolean> tls_npn = False(env->isolate());
2485 obj->Set(env->tls_npn_string(), tls_npn);
2487 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2488 Local<Boolean> tls_sni = True(env->isolate());
2490 Local<Boolean> tls_sni = False(env->isolate());
2492 obj->Set(env->tls_sni_string(), tls_sni);
2494 #if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_set_tlsext_status_cb)
2495 Local<Boolean> tls_ocsp = True(env->isolate());
2497 Local<Boolean> tls_ocsp = False(env->isolate());
2498 #endif // !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_set_tlsext_status_cb)
2499 obj->Set(env->tls_ocsp_string(), tls_ocsp);
2501 obj->Set(env->tls_string(),
2502 Boolean::New(env->isolate(),
2503 get_builtin_module("crypto") != nullptr));
2505 return scope.Escape(obj);
2509 static void DebugPortGetter(Local<String> property,
2510 const PropertyCallbackInfo<Value>& info) {
2511 Environment* env = Environment::GetCurrent(info.GetIsolate());
2512 HandleScope scope(env->isolate());
2513 info.GetReturnValue().Set(debug_port);
2517 static void DebugPortSetter(Local<String> property,
2519 const PropertyCallbackInfo<void>& info) {
2520 Environment* env = Environment::GetCurrent(info.GetIsolate());
2521 HandleScope scope(env->isolate());
2522 debug_port = value->Int32Value();
2526 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2527 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2528 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2531 void NeedImmediateCallbackGetter(Local<String> property,
2532 const PropertyCallbackInfo<Value>& info) {
2533 Environment* env = Environment::GetCurrent(info.GetIsolate());
2534 const uv_check_t* immediate_check_handle = env->immediate_check_handle();
2535 bool active = uv_is_active(
2536 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2537 info.GetReturnValue().Set(active);
2541 static void NeedImmediateCallbackSetter(
2542 Local<String> property,
2544 const PropertyCallbackInfo<void>& info) {
2545 HandleScope handle_scope(info.GetIsolate());
2546 Environment* env = Environment::GetCurrent(info.GetIsolate());
2548 uv_check_t* immediate_check_handle = env->immediate_check_handle();
2549 bool active = uv_is_active(
2550 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2552 if (active == value->BooleanValue())
2555 uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
2558 uv_check_stop(immediate_check_handle);
2559 uv_idle_stop(immediate_idle_handle);
2561 uv_check_start(immediate_check_handle, CheckImmediate);
2562 // Idle handle is needed only to stop the event loop from blocking in poll.
2563 uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
2568 void SetIdle(uv_prepare_t* handle) {
2569 Environment* env = Environment::from_idle_prepare_handle(handle);
2570 env->isolate()->GetCpuProfiler()->SetIdle(true);
2574 void ClearIdle(uv_check_t* handle) {
2575 Environment* env = Environment::from_idle_check_handle(handle);
2576 env->isolate()->GetCpuProfiler()->SetIdle(false);
2580 void StartProfilerIdleNotifier(Environment* env) {
2581 uv_prepare_start(env->idle_prepare_handle(), SetIdle);
2582 uv_check_start(env->idle_check_handle(), ClearIdle);
2586 void StopProfilerIdleNotifier(Environment* env) {
2587 uv_prepare_stop(env->idle_prepare_handle());
2588 uv_check_stop(env->idle_check_handle());
2592 void StartProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2593 Environment* env = Environment::GetCurrent(args);
2594 StartProfilerIdleNotifier(env);
2598 void StopProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2599 Environment* env = Environment::GetCurrent(args);
2600 StopProfilerIdleNotifier(env);
2604 #define READONLY_PROPERTY(obj, str, var) \
2606 obj->ForceSet(OneByteString(env->isolate(), str), var, v8::ReadOnly); \
2609 #define READONLY_DONT_ENUM_PROPERTY(obj, str, var) \
2611 obj->ForceSet(OneByteString(env->isolate(), str), \
2613 static_cast<v8::PropertyAttribute>(v8::ReadOnly | \
2618 void SetupProcessObject(Environment* env,
2620 const char* const* argv,
2622 const char* const* exec_argv) {
2623 HandleScope scope(env->isolate());
2625 Local<Object> process = env->process_object();
2627 process->SetAccessor(env->title_string(),
2629 ProcessTitleSetter);
2632 READONLY_PROPERTY(process,
2634 FIXED_ONE_BYTE_STRING(env->isolate(), NODE_VERSION));
2636 // process.moduleLoadList
2637 READONLY_PROPERTY(process,
2639 env->module_load_list_array());
2642 Local<Object> versions = Object::New(env->isolate());
2643 READONLY_PROPERTY(process, "versions", versions);
2645 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2647 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR)
2649 NODE_STRINGIFY(HTTP_PARSER_VERSION_PATCH);
2650 READONLY_PROPERTY(versions,
2652 FIXED_ONE_BYTE_STRING(env->isolate(), http_parser_version));
2654 // +1 to get rid of the leading 'v'
2655 READONLY_PROPERTY(versions,
2657 OneByteString(env->isolate(), NODE_VERSION + 1));
2658 READONLY_PROPERTY(versions,
2660 OneByteString(env->isolate(), V8::GetVersion()));
2661 READONLY_PROPERTY(versions,
2663 OneByteString(env->isolate(), uv_version_string()));
2664 READONLY_PROPERTY(versions,
2666 FIXED_ONE_BYTE_STRING(env->isolate(), ZLIB_VERSION));
2667 READONLY_PROPERTY(versions,
2669 FIXED_ONE_BYTE_STRING(env->isolate(), ARES_VERSION_STR));
2671 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2675 FIXED_ONE_BYTE_STRING(env->isolate(), node_modules_version));
2677 // process._promiseRejectEvent
2678 Local<Object> promiseRejectEvent = Object::New(env->isolate());
2679 READONLY_DONT_ENUM_PROPERTY(process,
2680 "_promiseRejectEvent",
2681 promiseRejectEvent);
2682 READONLY_PROPERTY(promiseRejectEvent,
2684 Integer::New(env->isolate(),
2685 v8::kPromiseRejectWithNoHandler));
2686 READONLY_PROPERTY(promiseRejectEvent,
2688 Integer::New(env->isolate(),
2689 v8::kPromiseHandlerAddedAfterReject));
2692 // Stupid code to slice out the version string.
2693 { // NOLINT(whitespace/braces)
2696 for (i = j = 0, k = sizeof(OPENSSL_VERSION_TEXT) - 1; i < k; ++i) {
2697 c = OPENSSL_VERSION_TEXT[i];
2698 if ('0' <= c && c <= '9') {
2699 for (j = i + 1; j < k; ++j) {
2700 c = OPENSSL_VERSION_TEXT[j];
2710 OneByteString(env->isolate(), &OPENSSL_VERSION_TEXT[i], j - i));
2715 READONLY_PROPERTY(process, "arch", OneByteString(env->isolate(), NODE_ARCH));
2718 READONLY_PROPERTY(process,
2720 OneByteString(env->isolate(), NODE_PLATFORM));
2723 Local<Array> arguments = Array::New(env->isolate(), argc);
2724 for (int i = 0; i < argc; ++i) {
2725 arguments->Set(i, String::NewFromUtf8(env->isolate(), argv[i]));
2727 process->Set(env->argv_string(), arguments);
2730 Local<Array> exec_arguments = Array::New(env->isolate(), exec_argc);
2731 for (int i = 0; i < exec_argc; ++i) {
2732 exec_arguments->Set(i, String::NewFromUtf8(env->isolate(), exec_argv[i]));
2734 process->Set(env->exec_argv_string(), exec_arguments);
2736 // create process.env
2737 Local<ObjectTemplate> process_env_template =
2738 ObjectTemplate::New(env->isolate());
2739 process_env_template->SetNamedPropertyHandler(EnvGetter,
2744 Object::New(env->isolate()));
2745 Local<Object> process_env = process_env_template->NewInstance();
2746 process->Set(env->env_string(), process_env);
2748 READONLY_PROPERTY(process, "pid", Integer::New(env->isolate(), getpid()));
2749 READONLY_PROPERTY(process, "features", GetFeatures(env));
2750 process->SetAccessor(env->need_imm_cb_string(),
2751 NeedImmediateCallbackGetter,
2752 NeedImmediateCallbackSetter);
2756 READONLY_PROPERTY(process,
2758 String::NewFromUtf8(env->isolate(), eval_string));
2763 READONLY_PROPERTY(process, "_print_eval", True(env->isolate()));
2766 // -i, --interactive
2768 READONLY_PROPERTY(process, "_forceRepl", True(env->isolate()));
2771 if (preload_module_count) {
2772 CHECK(preload_modules);
2773 Local<Array> array = Array::New(env->isolate());
2774 for (unsigned int i = 0; i < preload_module_count; ++i) {
2775 Local<String> module = String::NewFromUtf8(env->isolate(),
2776 preload_modules[i]);
2777 array->Set(i, module);
2779 READONLY_PROPERTY(process,
2785 if (no_deprecation) {
2786 READONLY_PROPERTY(process, "noDeprecation", True(env->isolate()));
2789 // --throw-deprecation
2790 if (throw_deprecation) {
2791 READONLY_PROPERTY(process, "throwDeprecation", True(env->isolate()));
2794 // --trace-deprecation
2795 if (trace_deprecation) {
2796 READONLY_PROPERTY(process, "traceDeprecation", True(env->isolate()));
2799 size_t exec_path_len = 2 * PATH_MAX;
2800 char* exec_path = new char[exec_path_len];
2801 Local<String> exec_path_value;
2802 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2803 exec_path_value = String::NewFromUtf8(env->isolate(),
2805 String::kNormalString,
2808 exec_path_value = String::NewFromUtf8(env->isolate(), argv[0]);
2810 process->Set(env->exec_path_string(), exec_path_value);
2813 process->SetAccessor(env->debug_port_string(),
2817 // define various internal methods
2818 env->SetMethod(process,
2819 "_startProfilerIdleNotifier",
2820 StartProfilerIdleNotifier);
2821 env->SetMethod(process,
2822 "_stopProfilerIdleNotifier",
2823 StopProfilerIdleNotifier);
2824 env->SetMethod(process, "_getActiveRequests", GetActiveRequests);
2825 env->SetMethod(process, "_getActiveHandles", GetActiveHandles);
2826 env->SetMethod(process, "reallyExit", Exit);
2827 env->SetMethod(process, "abort", Abort);
2828 env->SetMethod(process, "chdir", Chdir);
2829 env->SetMethod(process, "cwd", Cwd);
2831 env->SetMethod(process, "umask", Umask);
2833 #if defined(__POSIX__) && !defined(__ANDROID__)
2834 env->SetMethod(process, "getuid", GetUid);
2835 env->SetMethod(process, "setuid", SetUid);
2837 env->SetMethod(process, "setgid", SetGid);
2838 env->SetMethod(process, "getgid", GetGid);
2840 env->SetMethod(process, "getgroups", GetGroups);
2841 env->SetMethod(process, "setgroups", SetGroups);
2842 env->SetMethod(process, "initgroups", InitGroups);
2843 #endif // __POSIX__ && !defined(__ANDROID__)
2845 env->SetMethod(process, "_kill", Kill);
2847 env->SetMethod(process, "_debugProcess", DebugProcess);
2848 env->SetMethod(process, "_debugPause", DebugPause);
2849 env->SetMethod(process, "_debugEnd", DebugEnd);
2851 env->SetMethod(process, "hrtime", Hrtime);
2853 env->SetMethod(process, "dlopen", DLOpen);
2855 env->SetMethod(process, "uptime", Uptime);
2856 env->SetMethod(process, "memoryUsage", MemoryUsage);
2858 env->SetMethod(process, "binding", Binding);
2859 env->SetMethod(process, "_linkedBinding", LinkedBinding);
2861 env->SetMethod(process, "_setupNextTick", SetupNextTick);
2862 env->SetMethod(process, "_setupPromises", SetupPromises);
2863 env->SetMethod(process, "_setupDomainUse", SetupDomainUse);
2865 // pre-set _events object for faster emit checks
2866 process->Set(env->events_string(), Object::New(env->isolate()));
2870 #undef READONLY_PROPERTY
2873 static void AtExit() {
2874 uv_tty_reset_mode();
2878 static void SignalExit(int signo) {
2879 uv_tty_reset_mode();
2881 // FreeBSD has a nasty bug, see RegisterSignalHandler for details
2882 struct sigaction sa;
2883 memset(&sa, 0, sizeof(sa));
2884 sa.sa_handler = SIG_DFL;
2885 CHECK_EQ(sigaction(signo, &sa, nullptr), 0);
2891 // Most of the time, it's best to use `console.error` to write
2892 // to the process.stderr stream. However, in some cases, such as
2893 // when debugging the stream.Writable class or the process.nextTick
2894 // function, it is useful to bypass JavaScript entirely.
2895 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2896 CHECK(args.Length() == 1 && args[0]->IsString() &&
2897 "must be called with a single string");
2898 node::Utf8Value message(args.GetIsolate(), args[0]);
2899 fprintf(stderr, "%s\n", *message);
2904 void LoadEnvironment(Environment* env) {
2905 HandleScope handle_scope(env->isolate());
2907 env->isolate()->SetFatalErrorHandler(node::OnFatalError);
2908 env->isolate()->AddMessageListener(OnMessage);
2910 // Compile, execute the src/node.js file. (Which was included as static C
2911 // string in node_natives.h. 'natve_node' is the string containing that
2914 // The node.js file returns a function 'f'
2919 // Disable verbose mode to stop FatalException() handler from trying
2920 // to handle the exception. Errors this early in the start-up phase
2921 // are not safe to ignore.
2922 try_catch.SetVerbose(false);
2924 Local<String> script_name = FIXED_ONE_BYTE_STRING(env->isolate(), "node.js");
2925 Local<Value> f_value = ExecuteString(env, MainSource(env), script_name);
2926 if (try_catch.HasCaught()) {
2927 ReportException(env, try_catch);
2930 CHECK(f_value->IsFunction());
2931 Local<Function> f = Local<Function>::Cast(f_value);
2933 // Now we call 'f' with the 'process' variable that we've built up with
2934 // all our bindings. Inside node.js we'll take care of assigning things to
2937 // We start the process this way in order to be more modular. Developers
2938 // who do not like how 'src/node.js' setups the module system but do like
2939 // Node's I/O bindings may want to replace 'f' with their own function.
2941 // Add a reference to the global object
2942 Local<Object> global = env->context()->Global();
2944 #if defined HAVE_DTRACE || defined HAVE_ETW
2945 InitDTrace(env, global);
2948 #if defined HAVE_LTTNG
2949 InitLTTNG(env, global);
2952 #if defined HAVE_PERFCTR
2953 InitPerfCounters(env, global);
2956 // Enable handling of uncaught exceptions
2957 // (FatalException(), break on uncaught exception in debugger)
2959 // This is not strictly necessary since it's almost impossible
2960 // to attach the debugger fast enought to break on exception
2961 // thrown during process startup.
2962 try_catch.SetVerbose(true);
2964 env->SetMethod(env->process_object(), "_rawDebug", RawDebug);
2966 Local<Value> arg = env->process_object();
2967 f->Call(global, 1, &arg);
2970 static void PrintHelp();
2972 static bool ParseDebugOpt(const char* arg) {
2973 const char* port = nullptr;
2975 if (!strcmp(arg, "--debug")) {
2976 use_debug_agent = true;
2977 } else if (!strncmp(arg, "--debug=", sizeof("--debug=") - 1)) {
2978 use_debug_agent = true;
2979 port = arg + sizeof("--debug=") - 1;
2980 } else if (!strcmp(arg, "--debug-brk")) {
2981 use_debug_agent = true;
2982 debug_wait_connect = true;
2983 } else if (!strncmp(arg, "--debug-brk=", sizeof("--debug-brk=") - 1)) {
2984 use_debug_agent = true;
2985 debug_wait_connect = true;
2986 port = arg + sizeof("--debug-brk=") - 1;
2987 } else if (!strncmp(arg, "--debug-port=", sizeof("--debug-port=") - 1)) {
2988 port = arg + sizeof("--debug-port=") - 1;
2993 if (port != nullptr) {
2994 debug_port = atoi(port);
2995 if (debug_port < 1024 || debug_port > 65535) {
2996 fprintf(stderr, "Debug port must be in range 1024 to 65535.\n");
3005 static void PrintHelp() {
3006 printf("Usage: iojs [options] [ -e script | script.js ] [arguments] \n"
3007 " iojs debug script.js [arguments] \n"
3010 " -v, --version print io.js version\n"
3011 " -e, --eval script evaluate script\n"
3012 " -p, --print evaluate script and print result\n"
3013 " -i, --interactive always enter the REPL even if stdin\n"
3014 " does not appear to be a terminal\n"
3015 " -r, --require module to preload (option can be repeated)\n"
3016 " --no-deprecation silence deprecation warnings\n"
3017 " --throw-deprecation throw an exception anytime a deprecated "
3018 "function is used\n"
3019 " --trace-deprecation show stack traces on deprecations\n"
3020 " --v8-options print v8 command line options\n"
3021 " --max-stack-size=val set max v8 stack size (bytes)\n"
3022 #if defined(NODE_HAVE_I18N_SUPPORT)
3023 " --icu-data-dir=dir set ICU data load path to dir\n"
3024 " (overrides NODE_ICU_DATA)\n"
3025 #if !defined(NODE_HAVE_SMALL_ICU)
3026 " Note: linked-in ICU data is\n"
3031 "Environment variables:\n"
3033 "NODE_PATH ';'-separated list of directories\n"
3035 "NODE_PATH ':'-separated list of directories\n"
3037 " prefixed to the module search path.\n"
3038 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
3039 #if defined(NODE_HAVE_I18N_SUPPORT)
3040 "NODE_ICU_DATA Data path for ICU (Intl object) data\n"
3041 #if !defined(NODE_HAVE_SMALL_ICU)
3042 " (will extend linked-in data)\n"
3046 "Documentation can be found at https://iojs.org/\n");
3050 // Parse command line arguments.
3052 // argv is modified in place. exec_argv and v8_argv are out arguments that
3053 // ParseArgs() allocates memory for and stores a pointer to the output
3054 // vector in. The caller should free them with delete[].
3058 // * argv contains the arguments with node and V8 options filtered out.
3059 // * exec_argv contains both node and V8 options and nothing else.
3060 // * v8_argv contains argv[0] plus any V8 options
3061 static void ParseArgs(int* argc,
3064 const char*** exec_argv,
3066 const char*** v8_argv) {
3067 const unsigned int nargs = static_cast<unsigned int>(*argc);
3068 const char** new_exec_argv = new const char*[nargs];
3069 const char** new_v8_argv = new const char*[nargs];
3070 const char** new_argv = new const char*[nargs];
3071 const char** local_preload_modules = new const char*[nargs];
3073 for (unsigned int i = 0; i < nargs; ++i) {
3074 new_exec_argv[i] = nullptr;
3075 new_v8_argv[i] = nullptr;
3076 new_argv[i] = nullptr;
3077 local_preload_modules[i] = nullptr;
3080 // exec_argv starts with the first option, the other two start with argv[0].
3081 unsigned int new_exec_argc = 0;
3082 unsigned int new_v8_argc = 1;
3083 unsigned int new_argc = 1;
3084 new_v8_argv[0] = argv[0];
3085 new_argv[0] = argv[0];
3087 unsigned int index = 1;
3088 while (index < nargs && argv[index][0] == '-') {
3089 const char* const arg = argv[index];
3090 unsigned int args_consumed = 1;
3092 if (ParseDebugOpt(arg)) {
3093 // Done, consumed by ParseDebugOpt().
3094 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
3095 printf("%s\n", NODE_VERSION);
3097 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
3100 } else if (strcmp(arg, "--eval") == 0 ||
3101 strcmp(arg, "-e") == 0 ||
3102 strcmp(arg, "--print") == 0 ||
3103 strcmp(arg, "-pe") == 0 ||
3104 strcmp(arg, "-p") == 0) {
3105 bool is_eval = strchr(arg, 'e') != nullptr;
3106 bool is_print = strchr(arg, 'p') != nullptr;
3107 print_eval = print_eval || is_print;
3108 // --eval, -e and -pe always require an argument.
3109 if (is_eval == true) {
3111 eval_string = argv[index + 1];
3112 if (eval_string == nullptr) {
3113 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
3116 } else if ((index + 1 < nargs) &&
3117 argv[index + 1] != nullptr &&
3118 argv[index + 1][0] != '-') {
3120 eval_string = argv[index + 1];
3121 if (strncmp(eval_string, "\\-", 2) == 0) {
3122 // Starts with "\\-": escaped expression, drop the backslash.
3126 } else if (strcmp(arg, "--require") == 0 ||
3127 strcmp(arg, "-r") == 0) {
3128 const char* module = argv[index + 1];
3129 if (module == nullptr) {
3130 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
3134 local_preload_modules[preload_module_count++] = module;
3135 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
3137 } else if (strcmp(arg, "--no-deprecation") == 0) {
3138 no_deprecation = true;
3139 } else if (strcmp(arg, "--trace-deprecation") == 0) {
3140 trace_deprecation = true;
3141 } else if (strcmp(arg, "--throw-deprecation") == 0) {
3142 throw_deprecation = true;
3143 } else if (strcmp(arg, "--abort-on-uncaught-exception") == 0 ||
3144 strcmp(arg, "--abort_on_uncaught_exception") == 0) {
3145 abort_on_uncaught_exception = true;
3146 } else if (strcmp(arg, "--v8-options") == 0) {
3147 new_v8_argv[new_v8_argc] = "--help";
3149 #if defined(NODE_HAVE_I18N_SUPPORT)
3150 } else if (strncmp(arg, "--icu-data-dir=", 15) == 0) {
3151 icu_data_dir = arg + 15;
3154 // V8 option. Pass through as-is.
3155 new_v8_argv[new_v8_argc] = arg;
3159 memcpy(new_exec_argv + new_exec_argc,
3161 args_consumed * sizeof(*argv));
3163 new_exec_argc += args_consumed;
3164 index += args_consumed;
3167 // Copy remaining arguments.
3168 const unsigned int args_left = nargs - index;
3169 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
3170 new_argc += args_left;
3172 *exec_argc = new_exec_argc;
3173 *exec_argv = new_exec_argv;
3174 *v8_argc = new_v8_argc;
3175 *v8_argv = new_v8_argv;
3177 // Copy new_argv over argv and update argc.
3178 memcpy(argv, new_argv, new_argc * sizeof(*argv));
3180 *argc = static_cast<int>(new_argc);
3182 // Copy the preload_modules from the local array to an appropriately sized
3184 if (preload_module_count > 0) {
3185 CHECK(!preload_modules);
3186 preload_modules = new const char*[preload_module_count];
3187 memcpy(preload_modules, local_preload_modules,
3188 preload_module_count * sizeof(*preload_modules));
3190 delete[] local_preload_modules;
3194 // Called from V8 Debug Agent TCP thread.
3195 static void DispatchMessagesDebugAgentCallback(Environment* env) {
3196 // TODO(indutny): move async handle to environment
3197 uv_async_send(&dispatch_debug_messages_async);
3201 static void StartDebug(Environment* env, bool wait) {
3202 CHECK(!debugger_running);
3204 env->debugger_agent()->set_dispatch_handler(
3205 DispatchMessagesDebugAgentCallback);
3206 debugger_running = env->debugger_agent()->Start(debug_port, wait);
3207 if (debugger_running == false) {
3208 fprintf(stderr, "Starting debugger on port %d failed\n", debug_port);
3215 // Called from the main thread.
3216 static void EnableDebug(Environment* env) {
3217 CHECK(debugger_running);
3219 // Send message to enable debug in workers
3220 HandleScope handle_scope(env->isolate());
3222 Local<Object> message = Object::New(env->isolate());
3223 message->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "cmd"),
3224 FIXED_ONE_BYTE_STRING(env->isolate(), "NODE_DEBUG_ENABLED"));
3225 Local<Value> argv[] = {
3226 FIXED_ONE_BYTE_STRING(env->isolate(), "internalMessage"),
3229 MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(argv), argv);
3231 // Enabled debugger, possibly making it wait on a semaphore
3232 env->debugger_agent()->Enable();
3236 // Called from the main thread.
3237 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle) {
3238 if (debugger_running == false) {
3239 fprintf(stderr, "Starting debugger agent.\n");
3241 HandleScope scope(node_isolate);
3242 Environment* env = Environment::GetCurrent(node_isolate);
3243 Context::Scope context_scope(env->context());
3245 StartDebug(env, false);
3248 Isolate::Scope isolate_scope(node_isolate);
3249 v8::Debug::ProcessDebugMessages();
3254 static void EnableDebugSignalHandler(int signo) {
3255 // Call only async signal-safe functions here!
3256 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
3257 uv_async_send(&dispatch_debug_messages_async);
3261 static void RegisterSignalHandler(int signal,
3262 void (*handler)(int signal),
3263 bool reset_handler = false) {
3264 struct sigaction sa;
3265 memset(&sa, 0, sizeof(sa));
3266 sa.sa_handler = handler;
3268 // FreeBSD has a nasty bug with SA_RESETHAND reseting the SA_SIGINFO, that is
3269 // in turn set for a libthr wrapper. This leads to a crash.
3270 // Work around the issue by manually setting SIG_DFL in the signal handler
3271 sa.sa_flags = reset_handler ? SA_RESETHAND : 0;
3273 sigfillset(&sa.sa_mask);
3274 CHECK_EQ(sigaction(signal, &sa, nullptr), 0);
3278 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3279 Environment* env = Environment::GetCurrent(args);
3281 if (args.Length() != 1) {
3282 return env->ThrowError("Invalid number of arguments.");
3288 pid = args[0]->IntegerValue();
3289 r = kill(pid, SIGUSR1);
3291 return env->ThrowErrnoException(errno, "kill");
3296 static int RegisterDebugSignalHandler() {
3297 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3298 RegisterSignalHandler(SIGUSR1, EnableDebugSignalHandler);
3299 // Unblock SIGUSR1. A pending SIGUSR1 signal will now be delivered.
3301 sigemptyset(&sigmask);
3302 sigaddset(&sigmask, SIGUSR1);
3303 CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sigmask, nullptr));
3310 DWORD WINAPI EnableDebugThreadProc(void* arg) {
3311 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
3312 uv_async_send(&dispatch_debug_messages_async);
3317 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
3319 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
3323 static int RegisterDebugSignalHandler() {
3324 wchar_t mapping_name[32];
3325 HANDLE mapping_handle;
3327 LPTHREAD_START_ROUTINE* handler;
3329 pid = GetCurrentProcessId();
3331 if (GetDebugSignalHandlerMappingName(pid,
3333 ARRAY_SIZE(mapping_name)) < 0) {
3337 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
3343 if (mapping_handle == nullptr) {
3347 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3348 MapViewOfFile(mapping_handle,
3349 FILE_MAP_ALL_ACCESS,
3353 if (handler == nullptr) {
3354 CloseHandle(mapping_handle);
3358 *handler = EnableDebugThreadProc;
3360 UnmapViewOfFile(static_cast<void*>(handler));
3366 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3367 Environment* env = Environment::GetCurrent(args);
3368 Isolate* isolate = args.GetIsolate();
3370 HANDLE process = nullptr;
3371 HANDLE thread = nullptr;
3372 HANDLE mapping = nullptr;
3373 wchar_t mapping_name[32];
3374 LPTHREAD_START_ROUTINE* handler = nullptr;
3376 if (args.Length() != 1) {
3377 env->ThrowError("Invalid number of arguments.");
3381 pid = (DWORD) args[0]->IntegerValue();
3383 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
3384 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
3388 if (process == nullptr) {
3389 isolate->ThrowException(
3390 WinapiErrnoException(isolate, GetLastError(), "OpenProcess"));
3394 if (GetDebugSignalHandlerMappingName(pid,
3396 ARRAY_SIZE(mapping_name)) < 0) {
3397 env->ThrowErrnoException(errno, "sprintf");
3401 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
3402 if (mapping == nullptr) {
3403 isolate->ThrowException(WinapiErrnoException(isolate,
3405 "OpenFileMappingW"));
3409 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3410 MapViewOfFile(mapping,
3415 if (handler == nullptr || *handler == nullptr) {
3416 isolate->ThrowException(
3417 WinapiErrnoException(isolate, GetLastError(), "MapViewOfFile"));
3421 thread = CreateRemoteThread(process,
3428 if (thread == nullptr) {
3429 isolate->ThrowException(WinapiErrnoException(isolate,
3431 "CreateRemoteThread"));
3435 // Wait for the thread to terminate
3436 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3437 isolate->ThrowException(WinapiErrnoException(isolate,
3439 "WaitForSingleObject"));
3444 if (process != nullptr)
3445 CloseHandle(process);
3446 if (thread != nullptr)
3447 CloseHandle(thread);
3448 if (handler != nullptr)
3449 UnmapViewOfFile(handler);
3450 if (mapping != nullptr)
3451 CloseHandle(mapping);
3456 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3457 v8::Debug::DebugBreak(args.GetIsolate());
3461 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3462 if (debugger_running) {
3463 Environment* env = Environment::GetCurrent(args);
3464 env->debugger_agent()->Stop();
3465 debugger_running = false;
3470 inline void PlatformInit() {
3473 sigemptyset(&sigmask);
3474 sigaddset(&sigmask, SIGUSR1);
3475 const int err = pthread_sigmask(SIG_SETMASK, &sigmask, nullptr);
3477 // Make sure file descriptors 0-2 are valid before we start logging anything.
3478 for (int fd = STDIN_FILENO; fd <= STDERR_FILENO; fd += 1) {
3479 struct stat ignored;
3480 if (fstat(fd, &ignored) == 0)
3482 // Anything but EBADF means something is seriously wrong. We don't
3483 // have to special-case EINTR, fstat() is not interruptible.
3486 if (fd != open("/dev/null", O_RDWR))
3492 // Restore signal dispositions, the parent process may have changed them.
3493 struct sigaction act;
3494 memset(&act, 0, sizeof(act));
3496 // The hard-coded upper limit is because NSIG is not very reliable; on Linux,
3497 // it evaluates to 32, 34 or 64, depending on whether RT signals are enabled.
3498 // Counting up to SIGRTMIN doesn't work for the same reason.
3499 for (unsigned nr = 1; nr < 32; nr += 1) {
3500 if (nr == SIGKILL || nr == SIGSTOP)
3502 act.sa_handler = (nr == SIGPIPE) ? SIG_IGN : SIG_DFL;
3503 CHECK_EQ(0, sigaction(nr, &act, nullptr));
3506 RegisterSignalHandler(SIGINT, SignalExit, true);
3507 RegisterSignalHandler(SIGTERM, SignalExit, true);
3509 // Block SIGPROF signals when sleeping in epoll_wait/kevent/etc. Avoids the
3510 // performance penalty of frequent EINTR wakeups when the profiler is running.
3511 uv_loop_configure(uv_default_loop(), UV_LOOP_BLOCK_SIGNAL, SIGPROF);
3513 // Raise the open file descriptor limit.
3515 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3516 // Do a binary search for the limit.
3517 rlim_t min = lim.rlim_cur;
3518 rlim_t max = 1 << 20;
3519 // But if there's a defined upper bound, don't search, just set it.
3520 if (lim.rlim_max != RLIM_INFINITY) {
3525 lim.rlim_cur = min + (max - min) / 2;
3526 if (setrlimit(RLIMIT_NOFILE, &lim)) {
3531 } while (min + 1 < max);
3537 void Init(int* argc,
3540 const char*** exec_argv) {
3541 // Initialize prog_start_time to get relative uptime.
3542 prog_start_time = static_cast<double>(uv_now(uv_default_loop()));
3544 // Make inherited handles noninheritable.
3545 uv_disable_stdio_inheritance();
3547 // init async debug messages dispatching
3548 // Main thread uses uv_default_loop
3549 uv_async_init(uv_default_loop(),
3550 &dispatch_debug_messages_async,
3551 DispatchDebugMessagesAsyncCallback);
3552 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3554 #if defined(NODE_V8_OPTIONS)
3555 // Should come before the call to V8::SetFlagsFromCommandLine()
3556 // so the user can disable a flag --foo at run-time by passing
3557 // --no_foo from the command line.
3558 V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1);
3561 // Parse a few arguments which are specific to Node.
3563 const char** v8_argv;
3564 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3566 // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
3567 // manually? That would give us a little more control over its runtime
3568 // behavior but it could also interfere with the user's intentions in ways
3569 // we fail to anticipate. Dillema.
3570 for (int i = 1; i < v8_argc; ++i) {
3571 if (strncmp(v8_argv[i], "--prof", sizeof("--prof") - 1) == 0) {
3572 v8_is_profiling = true;
3577 #if defined(NODE_HAVE_I18N_SUPPORT)
3578 if (icu_data_dir == nullptr) {
3579 // if the parameter isn't given, use the env variable.
3580 icu_data_dir = secure_getenv("NODE_ICU_DATA");
3583 // If icu_data_dir is nullptr here, it will load the 'minimal' data.
3584 if (!i18n::InitializeICUDirectory(icu_data_dir)) {
3585 FatalError(nullptr, "Could not initialize ICU "
3586 "(check NODE_ICU_DATA or --icu-data-dir parameters)");
3589 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3590 // the argv array or the elements it points to.
3591 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3593 // Anything that's still in v8_argv is not a V8 or a node option.
3594 for (int i = 1; i < v8_argc; i++) {
3595 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3604 if (debug_wait_connect) {
3605 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3606 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3609 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3611 if (!use_debug_agent) {
3612 RegisterDebugSignalHandler();
3615 // We should set node_is_initialized here instead of in node::Start,
3616 // otherwise embedders using node::Init to initialize everything will not be
3617 // able to set it and native modules will not load for them.
3618 node_is_initialized = true;
3622 struct AtExitCallback {
3623 AtExitCallback* next_;
3624 void (*cb_)(void* arg);
3628 static AtExitCallback* at_exit_functions_;
3631 // TODO(bnoordhuis) Turn into per-context event.
3632 void RunAtExit(Environment* env) {
3633 AtExitCallback* p = at_exit_functions_;
3634 at_exit_functions_ = nullptr;
3637 AtExitCallback* q = p->next_;
3645 void AtExit(void (*cb)(void* arg), void* arg) {
3646 AtExitCallback* p = new AtExitCallback;
3649 p->next_ = at_exit_functions_;
3650 at_exit_functions_ = p;
3654 void EmitBeforeExit(Environment* env) {
3655 HandleScope handle_scope(env->isolate());
3656 Context::Scope context_scope(env->context());
3657 Local<Object> process_object = env->process_object();
3658 Local<String> exit_code = FIXED_ONE_BYTE_STRING(env->isolate(), "exitCode");
3659 Local<Value> args[] = {
3660 FIXED_ONE_BYTE_STRING(env->isolate(), "beforeExit"),
3661 process_object->Get(exit_code)->ToInteger(env->isolate())
3663 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3667 int EmitExit(Environment* env) {
3668 // process.emit('exit')
3669 HandleScope handle_scope(env->isolate());
3670 Context::Scope context_scope(env->context());
3671 Local<Object> process_object = env->process_object();
3672 process_object->Set(env->exiting_string(), True(env->isolate()));
3674 Handle<String> exitCode = env->exit_code_string();
3675 int code = process_object->Get(exitCode)->Int32Value();
3677 Local<Value> args[] = {
3679 Integer::New(env->isolate(), code)
3682 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3684 // Reload exit code, it may be changed by `emit('exit')`
3685 return process_object->Get(exitCode)->Int32Value();
3689 // Just a convenience method
3690 Environment* CreateEnvironment(Isolate* isolate,
3691 Handle<Context> context,
3693 const char* const* argv,
3695 const char* const* exec_argv) {
3697 Context::Scope context_scope(context);
3699 env = CreateEnvironment(isolate,
3707 LoadEnvironment(env);
3712 static Environment* CreateEnvironment(Isolate* isolate,
3713 Handle<Context> context,
3714 NodeInstanceData* instance_data) {
3715 return CreateEnvironment(isolate,
3716 instance_data->event_loop(),
3718 instance_data->argc(),
3719 instance_data->argv(),
3720 instance_data->exec_argc(),
3721 instance_data->exec_argv());
3725 static void HandleCloseCb(uv_handle_t* handle) {
3726 Environment* env = reinterpret_cast<Environment*>(handle->data);
3727 env->FinishHandleCleanup(handle);
3731 static void HandleCleanup(Environment* env,
3732 uv_handle_t* handle,
3735 uv_close(handle, HandleCloseCb);
3739 Environment* CreateEnvironment(Isolate* isolate,
3741 Handle<Context> context,
3743 const char* const* argv,
3745 const char* const* exec_argv) {
3746 HandleScope handle_scope(isolate);
3748 Context::Scope context_scope(context);
3749 Environment* env = Environment::New(context, loop);
3751 isolate->SetAutorunMicrotasks(false);
3753 uv_check_init(env->event_loop(), env->immediate_check_handle());
3755 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3757 uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3759 // Inform V8's CPU profiler when we're idle. The profiler is sampling-based
3760 // but not all samples are created equal; mark the wall clock time spent in
3761 // epoll_wait() and friends so profiling tools can filter it out. The samples
3762 // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
3763 // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
3764 // probably fortify in the API contract, namely that the last started prepare
3765 // or check watcher runs first. It's not 100% foolproof; if an add-on starts
3766 // a prepare or check watcher after us, any samples attributed to its callback
3767 // will be recorded with state=IDLE.
3768 uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
3769 uv_check_init(env->event_loop(), env->idle_check_handle());
3770 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
3771 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
3773 // Register handle cleanups
3774 env->RegisterHandleCleanup(
3775 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()),
3778 env->RegisterHandleCleanup(
3779 reinterpret_cast<uv_handle_t*>(env->immediate_idle_handle()),
3782 env->RegisterHandleCleanup(
3783 reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()),
3786 env->RegisterHandleCleanup(
3787 reinterpret_cast<uv_handle_t*>(env->idle_check_handle()),
3791 if (v8_is_profiling) {
3792 StartProfilerIdleNotifier(env);
3795 Local<FunctionTemplate> process_template = FunctionTemplate::New(isolate);
3796 process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3798 Local<Object> process_object = process_template->GetFunction()->NewInstance();
3799 env->set_process_object(process_object);
3801 SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3807 // Entry point for new node instances, also called directly for the main
3809 static void StartNodeInstance(void* arg) {
3810 NodeInstanceData* instance_data = static_cast<NodeInstanceData*>(arg);
3811 Isolate* isolate = Isolate::New();
3812 // Fetch a reference to the main isolate, so we have a reference to it
3813 // even when we need it to access it from another (debugger) thread.
3814 if (instance_data->is_main())
3815 node_isolate = isolate;
3817 Locker locker(isolate);
3818 Isolate::Scope isolate_scope(isolate);
3819 HandleScope handle_scope(isolate);
3820 Local<Context> context = Context::New(isolate);
3821 Environment* env = CreateEnvironment(isolate, context, instance_data);
3822 Context::Scope context_scope(context);
3823 if (instance_data->is_main())
3824 env->set_using_abort_on_uncaught_exc(abort_on_uncaught_exception);
3825 // Start debug agent when argv has --debug
3826 if (instance_data->use_debug_agent())
3827 StartDebug(env, debug_wait_connect);
3829 LoadEnvironment(env);
3832 if (instance_data->use_debug_agent())
3837 more = uv_run(env->event_loop(), UV_RUN_ONCE);
3838 if (more == false) {
3839 EmitBeforeExit(env);
3841 // Emit `beforeExit` if the loop became alive either after emitting
3842 // event, or after running some callbacks.
3843 more = uv_loop_alive(env->event_loop());
3844 if (uv_run(env->event_loop(), UV_RUN_NOWAIT) != 0)
3847 } while (more == true);
3849 int exit_code = EmitExit(env);
3850 if (instance_data->is_main())
3851 instance_data->set_exit_code(exit_code);
3858 CHECK_NE(isolate, nullptr);
3861 if (instance_data->is_main())
3862 node_isolate = nullptr;
3865 int Start(int argc, char** argv) {
3870 // Hack around with the argv pointer. Used for process.title = "blah".
3871 argv = uv_setup_args(argc, argv);
3873 // This needs to run *before* V8::Initialize(). The const_cast is not
3874 // optional, in case you're wondering.
3876 const char** exec_argv;
3877 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3880 // V8 on Windows doesn't have a good source of entropy. Seed it from
3882 V8::SetEntropySource(crypto::EntropySource);
3885 V8::InitializePlatform(new Platform(4));
3890 NodeInstanceData instance_data(NodeInstanceType::MAIN,
3893 const_cast<const char**>(argv),
3897 StartNodeInstance(&instance_data);
3898 exit_code = instance_data.exit_code();
3903 exec_argv = nullptr;