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"
27 #include "async-wrap.h"
28 #include "async-wrap-inl.h"
31 #include "handle_wrap.h"
33 #include "string_bytes.h"
37 #include "v8-profiler.h"
41 #include <limits.h> // PATH_MAX
47 #include <sys/types.h>
53 #define strcasecmp _stricmp
54 #define getpid _getpid
58 #include <sys/resource.h> // getrlimit, setrlimit
59 #include <unistd.h> // setuid, getuid
62 #if defined(__POSIX__) && !defined(__ANDROID__)
63 #include <pwd.h> // getpwnam()
64 #include <grp.h> // getgrnam()
68 #include <crt_externs.h>
69 #define environ (*_NSGetEnviron())
70 #elif !defined(_MSC_VER)
71 extern char **environ;
77 using v8::ArrayBuffer;
80 using v8::EscapableHandleScope;
83 using v8::FunctionCallbackInfo;
84 using v8::FunctionTemplate;
86 using v8::HandleScope;
87 using v8::HeapStatistics;
95 using v8::ObjectTemplate;
96 using v8::PropertyCallbackInfo;
102 using v8::kExternalUint32Array;
104 static bool print_eval = false;
105 static bool force_repl = false;
106 static bool trace_deprecation = false;
107 static bool throw_deprecation = false;
108 static const char* eval_string = nullptr;
109 static bool use_debug_agent = false;
110 static bool debug_wait_connect = false;
111 static int debug_port = 5858;
112 static bool v8_is_profiling = false;
113 static bool node_is_initialized = false;
114 static node_module* modpending;
115 static node_module* modlist_builtin;
116 static node_module* modlist_linked;
117 static node_module* modlist_addon;
119 #if defined(NODE_HAVE_I18N_SUPPORT)
120 // Path to ICU data (for i18n / Intl)
121 static const char* icu_data_dir = nullptr;
124 // used by C++ modules as well
125 bool no_deprecation = false;
127 // process-relative uptime base, initialized at start-up
128 static double prog_start_time;
129 static bool debugger_running;
130 static uv_async_t dispatch_debug_messages_async;
132 static Isolate* node_isolate = nullptr;
134 int WRITE_UTF8_FLAGS = v8::String::HINT_MANY_WRITES_EXPECTED |
135 v8::String::NO_NULL_TERMINATION;
137 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
139 // Impose an upper limit to avoid out of memory errors that bring down
141 static const size_t kMaxLength = 0x3fffffff;
142 static ArrayBufferAllocator the_singleton;
143 virtual ~ArrayBufferAllocator() = default;
144 virtual void* Allocate(size_t length) override;
145 virtual void* AllocateUninitialized(size_t length) override;
146 virtual void Free(void* data, size_t length) override;
148 ArrayBufferAllocator() = default;
149 DISALLOW_COPY_AND_ASSIGN(ArrayBufferAllocator);
152 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
155 void* ArrayBufferAllocator::Allocate(size_t length) {
156 if (length > kMaxLength)
158 char* data = new char[length];
159 memset(data, 0, length);
164 void* ArrayBufferAllocator::AllocateUninitialized(size_t length) {
165 if (length > kMaxLength)
167 return new char[length];
171 void ArrayBufferAllocator::Free(void* data, size_t length) {
172 delete[] static_cast<char*>(data);
176 static void CheckImmediate(uv_check_t* handle) {
177 Environment* env = Environment::from_immediate_check_handle(handle);
178 HandleScope scope(env->isolate());
179 Context::Scope context_scope(env->context());
180 MakeCallback(env, env->process_object(), env->immediate_callback_string());
184 static void IdleImmediateDummy(uv_idle_t* handle) {
185 // Do nothing. Only for maintaining event loop.
186 // TODO(bnoordhuis) Maybe make libuv accept nullptr idle callbacks.
190 static inline const char *errno_string(int errorno) {
191 #define ERRNO_CASE(e) case e: return #e;
198 ERRNO_CASE(EADDRINUSE);
202 ERRNO_CASE(EADDRNOTAVAIL);
206 ERRNO_CASE(EAFNOSUPPORT);
214 # if EAGAIN != EWOULDBLOCK
215 ERRNO_CASE(EWOULDBLOCK);
220 ERRNO_CASE(EALREADY);
236 ERRNO_CASE(ECANCELED);
244 ERRNO_CASE(ECONNABORTED);
248 ERRNO_CASE(ECONNREFUSED);
252 ERRNO_CASE(ECONNRESET);
260 ERRNO_CASE(EDESTADDRREQ);
284 ERRNO_CASE(EHOSTUNREACH);
296 ERRNO_CASE(EINPROGRESS);
332 ERRNO_CASE(EMSGSIZE);
336 ERRNO_CASE(EMULTIHOP);
340 ERRNO_CASE(ENAMETOOLONG);
344 ERRNO_CASE(ENETDOWN);
348 ERRNO_CASE(ENETRESET);
352 ERRNO_CASE(ENETUNREACH);
384 # if ENOLINK != ENOLCK
398 ERRNO_CASE(ENOPROTOOPT);
418 ERRNO_CASE(ENOTCONN);
426 ERRNO_CASE(ENOTEMPTY);
430 ERRNO_CASE(ENOTSOCK);
437 ERRNO_CASE(EOPNOTSUPP);
451 ERRNO_CASE(EOVERFLOW);
466 #ifdef EPROTONOSUPPORT
467 ERRNO_CASE(EPROTONOSUPPORT);
471 ERRNO_CASE(EPROTOTYPE);
499 ERRNO_CASE(ETIMEDOUT);
514 const char *signo_string(int signo) {
515 #define SIGNO_CASE(e) case e: return #e;
542 # if SIGABRT != SIGIOT
586 SIGNO_CASE(SIGSTKFLT);
603 SIGNO_CASE(SIGBREAK);
627 SIGNO_CASE(SIGVTALRM);
635 SIGNO_CASE(SIGWINCH);
643 # if SIGPOLL != SIGIO
653 # if SIGPWR != SIGLOST
667 // Convenience methods
670 void ThrowError(v8::Isolate* isolate, const char* errmsg) {
671 Environment::GetCurrent(isolate)->ThrowError(errmsg);
675 void ThrowTypeError(v8::Isolate* isolate, const char* errmsg) {
676 Environment::GetCurrent(isolate)->ThrowTypeError(errmsg);
680 void ThrowRangeError(v8::Isolate* isolate, const char* errmsg) {
681 Environment::GetCurrent(isolate)->ThrowRangeError(errmsg);
685 void ThrowErrnoException(v8::Isolate* isolate,
690 Environment::GetCurrent(isolate)->ThrowErrnoException(errorno,
697 void ThrowUVException(v8::Isolate* isolate,
702 Environment::GetCurrent(isolate)->ThrowErrnoException(errorno,
709 Local<Value> ErrnoException(Isolate* isolate,
714 Environment* env = Environment::GetCurrent(isolate);
717 Local<String> estring = OneByteString(env->isolate(), errno_string(errorno));
718 if (msg == nullptr || msg[0] == '\0') {
719 msg = strerror(errorno);
721 Local<String> message = OneByteString(env->isolate(), msg);
723 Local<String> cons1 =
724 String::Concat(estring, FIXED_ONE_BYTE_STRING(env->isolate(), ", "));
725 Local<String> cons2 = String::Concat(cons1, message);
728 Local<String> cons3 =
729 String::Concat(cons2, FIXED_ONE_BYTE_STRING(env->isolate(), " '"));
730 Local<String> cons4 =
731 String::Concat(cons3, String::NewFromUtf8(env->isolate(), path));
732 Local<String> cons5 =
733 String::Concat(cons4, FIXED_ONE_BYTE_STRING(env->isolate(), "'"));
734 e = Exception::Error(cons5);
736 e = Exception::Error(cons2);
739 Local<Object> obj = e->ToObject(env->isolate());
740 obj->Set(env->errno_string(), Integer::New(env->isolate(), errorno));
741 obj->Set(env->code_string(), estring);
743 if (path != nullptr) {
744 obj->Set(env->path_string(), String::NewFromUtf8(env->isolate(), path));
747 if (syscall != nullptr) {
748 obj->Set(env->syscall_string(), OneByteString(env->isolate(), syscall));
755 // hack alert! copy of ErrnoException, tuned for uv errors
756 Local<Value> UVException(Isolate* isolate,
761 Environment* env = Environment::GetCurrent(isolate);
764 msg = uv_strerror(errorno);
766 Local<String> estring = OneByteString(env->isolate(), uv_err_name(errorno));
767 Local<String> message = OneByteString(env->isolate(), msg);
768 Local<String> cons1 =
769 String::Concat(estring, FIXED_ONE_BYTE_STRING(env->isolate(), ", "));
770 Local<String> cons2 = String::Concat(cons1, message);
774 Local<String> path_str;
778 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
779 path_str = String::Concat(FIXED_ONE_BYTE_STRING(env->isolate(), "\\\\"),
780 String::NewFromUtf8(env->isolate(), path + 8));
781 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
782 path_str = String::NewFromUtf8(env->isolate(), path + 4);
784 path_str = String::NewFromUtf8(env->isolate(), path);
787 path_str = String::NewFromUtf8(env->isolate(), path);
790 Local<String> cons3 =
791 String::Concat(cons2, FIXED_ONE_BYTE_STRING(env->isolate(), " '"));
792 Local<String> cons4 =
793 String::Concat(cons3, path_str);
794 Local<String> cons5 =
795 String::Concat(cons4, FIXED_ONE_BYTE_STRING(env->isolate(), "'"));
796 e = Exception::Error(cons5);
798 e = Exception::Error(cons2);
801 Local<Object> obj = e->ToObject(env->isolate());
802 // TODO(piscisaureus) errno should probably go
803 obj->Set(env->errno_string(), Integer::New(env->isolate(), errorno));
804 obj->Set(env->code_string(), estring);
806 if (path != nullptr) {
807 obj->Set(env->path_string(), path_str);
810 if (syscall != nullptr) {
811 obj->Set(env->syscall_string(), OneByteString(env->isolate(), syscall));
818 // Look up environment variable unless running as setuid root.
819 inline const char* secure_getenv(const char* key) {
821 if (getuid() != geteuid() || getgid() != getegid())
829 // Does about the same as strerror(),
830 // but supports all windows error messages
831 static const char *winapi_strerror(const int errorno, bool* must_free) {
832 char *errmsg = nullptr;
834 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
835 FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorno,
836 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, nullptr);
841 // Remove trailing newlines
842 for (int i = strlen(errmsg) - 1;
843 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
849 // FormatMessage failed
851 return "Unknown error";
856 Local<Value> WinapiErrnoException(Isolate* isolate,
861 Environment* env = Environment::GetCurrent(isolate);
863 bool must_free = false;
864 if (!msg || !msg[0]) {
865 msg = winapi_strerror(errorno, &must_free);
867 Local<String> message = OneByteString(env->isolate(), msg);
870 Local<String> cons1 =
871 String::Concat(message, FIXED_ONE_BYTE_STRING(isolate, " '"));
872 Local<String> cons2 =
873 String::Concat(cons1, String::NewFromUtf8(isolate, path));
874 Local<String> cons3 =
875 String::Concat(cons2, FIXED_ONE_BYTE_STRING(isolate, "'"));
876 e = Exception::Error(cons3);
878 e = Exception::Error(message);
881 Local<Object> obj = e->ToObject(env->isolate());
882 obj->Set(env->errno_string(), Integer::New(isolate, errorno));
884 if (path != nullptr) {
885 obj->Set(env->path_string(), String::NewFromUtf8(isolate, path));
888 if (syscall != nullptr) {
889 obj->Set(env->syscall_string(), OneByteString(isolate, syscall));
893 LocalFree((HLOCAL)msg);
900 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
901 Environment* env = Environment::GetCurrent(args);
903 if (env->using_domains())
905 env->set_using_domains(true);
907 HandleScope scope(env->isolate());
908 Local<Object> process_object = env->process_object();
910 Local<String> tick_callback_function_key = env->tick_domain_cb_string();
911 Local<Function> tick_callback_function =
912 process_object->Get(tick_callback_function_key).As<Function>();
914 if (!tick_callback_function->IsFunction()) {
915 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
919 process_object->Set(env->tick_callback_string(), tick_callback_function);
920 env->set_tick_callback_function(tick_callback_function);
922 CHECK(args[0]->IsArray());
923 CHECK(args[1]->IsObject());
925 env->set_domain_array(args[0].As<Array>());
927 Local<Object> domain_flag_obj = args[1].As<Object>();
928 Environment::DomainFlag* domain_flag = env->domain_flag();
929 domain_flag_obj->SetIndexedPropertiesToExternalArrayData(
930 domain_flag->fields(),
931 kExternalUint32Array,
932 domain_flag->fields_count());
934 // Do a little housekeeping.
935 env->process_object()->Delete(
936 FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupDomainUse"));
939 void RunMicrotasks(const FunctionCallbackInfo<Value>& args) {
940 args.GetIsolate()->RunMicrotasks();
944 void SetupNextTick(const FunctionCallbackInfo<Value>& args) {
945 Environment* env = Environment::GetCurrent(args);
947 CHECK(args[0]->IsObject());
948 CHECK(args[1]->IsFunction());
949 CHECK(args[2]->IsObject());
951 // Values use to cross communicate with processNextTick.
952 Local<Object> tick_info_obj = args[0].As<Object>();
953 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
954 env->tick_info()->fields(),
955 kExternalUint32Array,
956 env->tick_info()->fields_count());
958 env->set_tick_callback_function(args[1].As<Function>());
960 env->SetMethod(args[2].As<Object>(), "runMicrotasks", RunMicrotasks);
962 // Do a little housekeeping.
963 env->process_object()->Delete(
964 FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupNextTick"));
968 Handle<Value> MakeCallback(Environment* env,
970 const Handle<Function> callback,
972 Handle<Value> argv[]) {
973 // If you hit this assertion, you forgot to enter the v8::Context first.
974 CHECK_EQ(env->context(), env->isolate()->GetCurrentContext());
976 Local<Object> process = env->process_object();
977 Local<Object> object, domain;
978 bool has_async_queue = false;
979 bool has_domain = false;
981 if (recv->IsObject()) {
982 object = recv.As<Object>();
983 Local<Value> async_queue_v = object->Get(env->async_queue_string());
984 if (async_queue_v->IsObject())
985 has_async_queue = true;
988 if (env->using_domains()) {
989 CHECK(recv->IsObject());
990 Local<Value> domain_v = object->Get(env->domain_string());
991 has_domain = domain_v->IsObject();
993 domain = domain_v.As<Object>();
994 if (domain->Get(env->disposed_string())->IsTrue())
995 return Undefined(env->isolate());
1000 try_catch.SetVerbose(true);
1003 Local<Value> enter_v = domain->Get(env->enter_string());
1004 if (enter_v->IsFunction()) {
1005 enter_v.As<Function>()->Call(domain, 0, nullptr);
1006 if (try_catch.HasCaught())
1007 return Undefined(env->isolate());
1011 if (has_async_queue) {
1012 try_catch.SetVerbose(false);
1013 env->async_hooks_pre_function()->Call(object, 0, nullptr);
1014 if (try_catch.HasCaught())
1015 FatalError("node:;MakeCallback", "pre hook threw");
1016 try_catch.SetVerbose(true);
1019 Local<Value> ret = callback->Call(recv, argc, argv);
1021 if (has_async_queue) {
1022 try_catch.SetVerbose(false);
1023 env->async_hooks_post_function()->Call(object, 0, nullptr);
1024 if (try_catch.HasCaught())
1025 FatalError("node::MakeCallback", "post hook threw");
1026 try_catch.SetVerbose(true);
1030 Local<Value> exit_v = domain->Get(env->exit_string());
1031 if (exit_v->IsFunction()) {
1032 exit_v.As<Function>()->Call(domain, 0, nullptr);
1033 if (try_catch.HasCaught())
1034 return Undefined(env->isolate());
1037 env->tick_callback_function()->Call(process, 0, nullptr);
1038 CHECK_EQ(env->context(), env->isolate()->GetCurrentContext());
1040 if (try_catch.HasCaught()) {
1041 return Undefined(env->isolate());
1044 Environment::TickInfo* tick_info = env->tick_info();
1046 if (tick_info->in_tick()) {
1050 if (tick_info->length() == 0) {
1051 env->isolate()->RunMicrotasks();
1054 if (tick_info->length() == 0) {
1055 tick_info->set_index(0);
1059 tick_info->set_in_tick(true);
1061 // process nextTicks after call
1062 env->tick_callback_function()->Call(process, 0, nullptr);
1064 tick_info->set_in_tick(false);
1066 if (try_catch.HasCaught()) {
1067 tick_info->set_last_threw(true);
1068 return Undefined(env->isolate());
1076 Handle<Value> MakeCallback(Environment* env,
1077 Handle<Object> recv,
1080 Handle<Value> argv[]) {
1081 Local<Value> cb_v = recv->Get(index);
1082 CHECK(cb_v->IsFunction());
1083 return MakeCallback(env, recv.As<Value>(), cb_v.As<Function>(), argc, argv);
1087 Handle<Value> MakeCallback(Environment* env,
1088 Handle<Object> recv,
1089 Handle<String> symbol,
1091 Handle<Value> argv[]) {
1092 Local<Value> cb_v = recv->Get(symbol);
1093 CHECK(cb_v->IsFunction());
1094 return MakeCallback(env, recv.As<Value>(), cb_v.As<Function>(), argc, argv);
1098 Handle<Value> MakeCallback(Environment* env,
1099 Handle<Object> recv,
1102 Handle<Value> argv[]) {
1103 Local<String> method_string = OneByteString(env->isolate(), method);
1104 return MakeCallback(env, recv, method_string, argc, argv);
1108 Handle<Value> MakeCallback(Isolate* isolate,
1109 Handle<Object> recv,
1112 Handle<Value> argv[]) {
1113 EscapableHandleScope handle_scope(isolate);
1114 Local<Context> context = recv->CreationContext();
1115 Environment* env = Environment::GetCurrent(context);
1116 Context::Scope context_scope(context);
1117 return handle_scope.Escape(
1118 Local<Value>::New(isolate, MakeCallback(env, recv, method, argc, argv)));
1122 Handle<Value> MakeCallback(Isolate* isolate,
1123 Handle<Object> recv,
1124 Handle<String> symbol,
1126 Handle<Value> argv[]) {
1127 EscapableHandleScope handle_scope(isolate);
1128 Local<Context> context = recv->CreationContext();
1129 Environment* env = Environment::GetCurrent(context);
1130 Context::Scope context_scope(context);
1131 return handle_scope.Escape(
1132 Local<Value>::New(isolate, MakeCallback(env, recv, symbol, argc, argv)));
1136 Handle<Value> MakeCallback(Isolate* isolate,
1137 Handle<Object> recv,
1138 Handle<Function> callback,
1140 Handle<Value> argv[]) {
1141 EscapableHandleScope handle_scope(isolate);
1142 Local<Context> context = recv->CreationContext();
1143 Environment* env = Environment::GetCurrent(context);
1144 Context::Scope context_scope(context);
1145 return handle_scope.Escape(Local<Value>::New(
1147 MakeCallback(env, recv.As<Value>(), callback, argc, argv)));
1151 enum encoding ParseEncoding(Isolate* isolate,
1152 Handle<Value> encoding_v,
1153 enum encoding _default) {
1154 HandleScope scope(isolate);
1156 if (!encoding_v->IsString())
1159 node::Utf8Value encoding(isolate, encoding_v);
1161 if (strcasecmp(*encoding, "utf8") == 0) {
1163 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1165 } else if (strcasecmp(*encoding, "ascii") == 0) {
1167 } else if (strcasecmp(*encoding, "base64") == 0) {
1169 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1171 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1173 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1175 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1177 } else if (strcasecmp(*encoding, "binary") == 0) {
1179 } else if (strcasecmp(*encoding, "buffer") == 0) {
1181 } else if (strcasecmp(*encoding, "hex") == 0) {
1183 } else if (strcasecmp(*encoding, "raw") == 0) {
1184 if (!no_deprecation) {
1185 fprintf(stderr, "'raw' (array of integers) has been removed. "
1189 } else if (strcasecmp(*encoding, "raws") == 0) {
1190 if (!no_deprecation) {
1191 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1192 "Please update your code.\n");
1200 Local<Value> Encode(Isolate* isolate,
1203 enum encoding encoding) {
1204 CHECK_NE(encoding, UCS2);
1205 return StringBytes::Encode(isolate, buf, len, encoding);
1208 Local<Value> Encode(Isolate* isolate, const uint16_t* buf, size_t len) {
1209 return StringBytes::Encode(isolate, buf, len);
1212 // Returns -1 if the handle was not valid for decoding
1213 ssize_t DecodeBytes(Isolate* isolate,
1215 enum encoding encoding) {
1216 HandleScope scope(isolate);
1218 if (val->IsArray()) {
1219 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1225 return StringBytes::Size(isolate, val, encoding);
1228 // Returns number of bytes written.
1229 ssize_t DecodeWrite(Isolate* isolate,
1233 enum encoding encoding) {
1234 return StringBytes::Write(isolate, buf, buflen, val, encoding, nullptr);
1237 void AppendExceptionLine(Environment* env,
1239 Handle<Message> message) {
1240 if (message.IsEmpty())
1243 HandleScope scope(env->isolate());
1244 Local<Object> err_obj;
1245 if (!er.IsEmpty() && er->IsObject()) {
1246 err_obj = er.As<Object>();
1248 // Do it only once per message
1249 if (!err_obj->GetHiddenValue(env->processed_string()).IsEmpty())
1251 err_obj->SetHiddenValue(env->processed_string(), True(env->isolate()));
1256 // Print (filename):(line number): (message).
1257 node::Utf8Value filename(env->isolate(), message->GetScriptResourceName());
1258 const char* filename_string = *filename;
1259 int linenum = message->GetLineNumber();
1260 // Print line of source code.
1261 node::Utf8Value sourceline(env->isolate(), message->GetSourceLine());
1262 const char* sourceline_string = *sourceline;
1264 // Because of how node modules work, all scripts are wrapped with a
1265 // "function (module, exports, __filename, ...) {"
1266 // to provide script local variables.
1268 // When reporting errors on the first line of a script, this wrapper
1269 // function is leaked to the user. There used to be a hack here to
1270 // truncate off the first 62 characters, but it caused numerous other
1271 // problems when vm.runIn*Context() methods were used for non-module
1274 // If we ever decide to re-instate such a hack, the following steps
1277 // 1. Pass a flag around to say "this code was wrapped"
1278 // 2. Update the stack frame output so that it is also correct.
1280 // It would probably be simpler to add a line rather than add some
1281 // number of characters to the first line, since V8 truncates the
1282 // sourceline to 78 characters, and we end up not providing very much
1283 // useful debugging info to the user if we remove 62 characters.
1285 int start = message->GetStartColumn();
1286 int end = message->GetEndColumn();
1288 int off = snprintf(arrow,
1296 // Print wavy underline (GetUnderline is deprecated).
1297 for (int i = 0; i < start; i++) {
1298 if (sourceline_string[i] == '\0' ||
1299 static_cast<size_t>(off) >= sizeof(arrow)) {
1302 CHECK_LT(static_cast<size_t>(off), sizeof(arrow));
1303 arrow[off++] = (sourceline_string[i] == '\t') ? '\t' : ' ';
1305 for (int i = start; i < end; i++) {
1306 if (sourceline_string[i] == '\0' ||
1307 static_cast<size_t>(off) >= sizeof(arrow)) {
1310 CHECK_LT(static_cast<size_t>(off), sizeof(arrow));
1313 CHECK_LE(static_cast<size_t>(off - 1), sizeof(arrow) - 1);
1314 arrow[off++] = '\n';
1317 Local<String> arrow_str = String::NewFromUtf8(env->isolate(), arrow);
1321 // Allocation failed, just print it out
1322 if (arrow_str.IsEmpty() || err_obj.IsEmpty() || !err_obj->IsNativeError())
1325 msg = err_obj->Get(env->message_string());
1326 stack = err_obj->Get(env->stack_string());
1328 if (msg.IsEmpty() || stack.IsEmpty())
1331 err_obj->Set(env->message_string(),
1332 String::Concat(arrow_str, msg->ToString(env->isolate())));
1333 err_obj->Set(env->stack_string(),
1334 String::Concat(arrow_str, stack->ToString(env->isolate())));
1338 if (env->printed_error())
1340 env->set_printed_error(true);
1341 uv_tty_reset_mode();
1342 fprintf(stderr, "\n%s", arrow);
1346 static void ReportException(Environment* env,
1348 Handle<Message> message) {
1349 HandleScope scope(env->isolate());
1351 AppendExceptionLine(env, er, message);
1353 Local<Value> trace_value;
1355 if (er->IsUndefined() || er->IsNull())
1356 trace_value = Undefined(env->isolate());
1358 trace_value = er->ToObject(env->isolate())->Get(env->stack_string());
1360 node::Utf8Value trace(env->isolate(), trace_value);
1362 // range errors have a trace member set to undefined
1363 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1364 fprintf(stderr, "%s\n", *trace);
1366 // this really only happens for RangeErrors, since they're the only
1367 // kind that won't have all this info in the trace, or when non-Error
1368 // objects are thrown manually.
1369 Local<Value> message;
1372 if (er->IsObject()) {
1373 Local<Object> err_obj = er.As<Object>();
1374 message = err_obj->Get(env->message_string());
1375 name = err_obj->Get(FIXED_ONE_BYTE_STRING(env->isolate(), "name"));
1378 if (message.IsEmpty() ||
1379 message->IsUndefined() ||
1381 name->IsUndefined()) {
1382 // Not an error object. Just print as-is.
1383 node::Utf8Value message(env->isolate(), er);
1384 fprintf(stderr, "%s\n", *message);
1386 node::Utf8Value name_string(env->isolate(), name);
1387 node::Utf8Value message_string(env->isolate(), message);
1388 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1396 static void ReportException(Environment* env, const TryCatch& try_catch) {
1397 ReportException(env, try_catch.Exception(), try_catch.Message());
1401 // Executes a str within the current v8 context.
1402 static Local<Value> ExecuteString(Environment* env,
1403 Handle<String> source,
1404 Handle<String> filename) {
1405 EscapableHandleScope scope(env->isolate());
1408 // try_catch must be nonverbose to disable FatalException() handler,
1409 // we will handle exceptions ourself.
1410 try_catch.SetVerbose(false);
1412 Local<v8::Script> script = v8::Script::Compile(source, filename);
1413 if (script.IsEmpty()) {
1414 ReportException(env, try_catch);
1418 Local<Value> result = script->Run();
1419 if (result.IsEmpty()) {
1420 ReportException(env, try_catch);
1424 return scope.Escape(result);
1428 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1429 Environment* env = Environment::GetCurrent(args);
1431 Local<Array> ary = Array::New(args.GetIsolate());
1435 QUEUE_FOREACH(q, env->req_wrap_queue()) {
1436 ReqWrap<uv_req_t>* w = ContainerOf(&ReqWrap<uv_req_t>::req_wrap_queue_, q);
1437 if (w->persistent().IsEmpty())
1439 ary->Set(i++, w->object());
1442 args.GetReturnValue().Set(ary);
1446 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1447 // implemented here for consistency with GetActiveRequests().
1448 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1449 Environment* env = Environment::GetCurrent(args);
1451 Local<Array> ary = Array::New(env->isolate());
1455 Local<String> owner_sym = env->owner_string();
1457 QUEUE_FOREACH(q, env->handle_wrap_queue()) {
1458 HandleWrap* w = ContainerOf(&HandleWrap::handle_wrap_queue_, q);
1459 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref))
1461 Local<Object> object = w->object();
1462 Local<Value> owner = object->Get(owner_sym);
1463 if (owner->IsUndefined())
1465 ary->Set(i++, owner);
1468 args.GetReturnValue().Set(ary);
1472 static void Abort(const FunctionCallbackInfo<Value>& args) {
1477 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1478 Environment* env = Environment::GetCurrent(args);
1480 if (args.Length() != 1 || !args[0]->IsString()) {
1481 return env->ThrowTypeError("Bad argument.");
1484 node::Utf8Value path(args.GetIsolate(), args[0]);
1485 int err = uv_chdir(*path);
1487 return env->ThrowUVException(err, "uv_chdir");
1492 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1493 Environment* env = Environment::GetCurrent(args);
1495 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1496 char buf[MAX_PATH * 4];
1501 size_t cwd_len = sizeof(buf);
1502 int err = uv_cwd(buf, &cwd_len);
1504 return env->ThrowUVException(err, "uv_cwd");
1507 Local<String> cwd = String::NewFromUtf8(env->isolate(),
1509 String::kNormalString,
1511 args.GetReturnValue().Set(cwd);
1515 static void Umask(const FunctionCallbackInfo<Value>& args) {
1516 Environment* env = Environment::GetCurrent(args);
1519 if (args.Length() < 1 || args[0]->IsUndefined()) {
1521 umask(static_cast<mode_t>(old));
1522 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1523 return env->ThrowTypeError("argument must be an integer or octal string.");
1526 if (args[0]->IsInt32()) {
1527 oct = args[0]->Uint32Value();
1530 node::Utf8Value str(env->isolate(), args[0]);
1532 // Parse the octal string.
1533 for (size_t i = 0; i < str.length(); i++) {
1535 if (c > '7' || c < '0') {
1536 return env->ThrowTypeError("invalid octal string");
1542 old = umask(static_cast<mode_t>(oct));
1545 args.GetReturnValue().Set(old);
1549 #if defined(__POSIX__) && !defined(__ANDROID__)
1551 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1552 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1555 static uid_t uid_by_name(const char* name) {
1563 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != nullptr) {
1567 return uid_not_found;
1571 static char* name_by_uid(uid_t uid) {
1580 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 &&
1582 return strdup(pp->pw_name);
1593 static gid_t gid_by_name(const char* name) {
1601 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != nullptr) {
1605 return gid_not_found;
1609 #if 0 // For future use.
1610 static const char* name_by_gid(gid_t gid) {
1619 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 &&
1621 return strdup(pp->gr_name);
1633 static uid_t uid_by_name(Handle<Value> value) {
1634 if (value->IsUint32()) {
1635 return static_cast<uid_t>(value->Uint32Value());
1637 // TODO(trevnorris): Fix to not use GetCurrent().
1638 node::Utf8Value name(Isolate::GetCurrent(), value);
1639 return uid_by_name(*name);
1644 static gid_t gid_by_name(Handle<Value> value) {
1645 if (value->IsUint32()) {
1646 return static_cast<gid_t>(value->Uint32Value());
1648 // TODO(trevnorris): Fix to not use GetCurrent().
1649 node::Utf8Value name(Isolate::GetCurrent(), value);
1650 return gid_by_name(*name);
1655 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1656 // uid_t is an uint32_t on all supported platforms.
1657 args.GetReturnValue().Set(static_cast<uint32_t>(getuid()));
1661 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1662 // gid_t is an uint32_t on all supported platforms.
1663 args.GetReturnValue().Set(static_cast<uint32_t>(getgid()));
1667 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1668 Environment* env = Environment::GetCurrent(args);
1670 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1671 return env->ThrowTypeError("setgid argument must be a number or a string");
1674 gid_t gid = gid_by_name(args[0]);
1676 if (gid == gid_not_found) {
1677 return env->ThrowError("setgid group id does not exist");
1681 return env->ThrowErrnoException(errno, "setgid");
1686 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1687 Environment* env = Environment::GetCurrent(args);
1689 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1690 return env->ThrowTypeError("setuid argument must be a number or a string");
1693 uid_t uid = uid_by_name(args[0]);
1695 if (uid == uid_not_found) {
1696 return env->ThrowError("setuid user id does not exist");
1700 return env->ThrowErrnoException(errno, "setuid");
1705 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1706 Environment* env = Environment::GetCurrent(args);
1708 int ngroups = getgroups(0, nullptr);
1710 if (ngroups == -1) {
1711 return env->ThrowErrnoException(errno, "getgroups");
1714 gid_t* groups = new gid_t[ngroups];
1716 ngroups = getgroups(ngroups, groups);
1718 if (ngroups == -1) {
1720 return env->ThrowErrnoException(errno, "getgroups");
1723 Local<Array> groups_list = Array::New(env->isolate(), ngroups);
1724 bool seen_egid = false;
1725 gid_t egid = getegid();
1727 for (int i = 0; i < ngroups; i++) {
1728 groups_list->Set(i, Integer::New(env->isolate(), groups[i]));
1729 if (groups[i] == egid)
1735 if (seen_egid == false) {
1736 groups_list->Set(ngroups, Integer::New(env->isolate(), egid));
1739 args.GetReturnValue().Set(groups_list);
1743 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1744 Environment* env = Environment::GetCurrent(args);
1746 if (!args[0]->IsArray()) {
1747 return env->ThrowTypeError("argument 1 must be an array");
1750 Local<Array> groups_list = args[0].As<Array>();
1751 size_t size = groups_list->Length();
1752 gid_t* groups = new gid_t[size];
1754 for (size_t i = 0; i < size; i++) {
1755 gid_t gid = gid_by_name(groups_list->Get(i));
1757 if (gid == gid_not_found) {
1759 return env->ThrowError("group name not found");
1765 int rc = setgroups(size, groups);
1769 return env->ThrowErrnoException(errno, "setgroups");
1774 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1775 Environment* env = Environment::GetCurrent(args);
1777 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1778 return env->ThrowTypeError("argument 1 must be a number or a string");
1781 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1782 return env->ThrowTypeError("argument 2 must be a number or a string");
1785 node::Utf8Value arg0(env->isolate(), args[0]);
1790 if (args[0]->IsUint32()) {
1791 user = name_by_uid(args[0]->Uint32Value());
1798 if (user == nullptr) {
1799 return env->ThrowError("initgroups user not found");
1802 extra_group = gid_by_name(args[1]);
1804 if (extra_group == gid_not_found) {
1807 return env->ThrowError("initgroups extra group not found");
1810 int rc = initgroups(user, extra_group);
1817 return env->ThrowErrnoException(errno, "initgroups");
1821 #endif // __POSIX__ && !defined(__ANDROID__)
1824 void Exit(const FunctionCallbackInfo<Value>& args) {
1825 exit(args[0]->Int32Value());
1829 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1830 Environment* env = Environment::GetCurrent(args);
1833 uv_update_time(env->event_loop());
1834 uptime = uv_now(env->event_loop()) - prog_start_time;
1836 args.GetReturnValue().Set(Number::New(env->isolate(), uptime / 1000));
1840 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1841 Environment* env = Environment::GetCurrent(args);
1844 int err = uv_resident_set_memory(&rss);
1846 return env->ThrowUVException(err, "uv_resident_set_memory");
1850 HeapStatistics v8_heap_stats;
1851 env->isolate()->GetHeapStatistics(&v8_heap_stats);
1853 Local<Integer> heap_total =
1854 Integer::NewFromUnsigned(env->isolate(), v8_heap_stats.total_heap_size());
1855 Local<Integer> heap_used =
1856 Integer::NewFromUnsigned(env->isolate(), v8_heap_stats.used_heap_size());
1858 Local<Object> info = Object::New(env->isolate());
1859 info->Set(env->rss_string(), Number::New(env->isolate(), rss));
1860 info->Set(env->heap_total_string(), heap_total);
1861 info->Set(env->heap_used_string(), heap_used);
1863 args.GetReturnValue().Set(info);
1867 void Kill(const FunctionCallbackInfo<Value>& args) {
1868 Environment* env = Environment::GetCurrent(args);
1870 if (args.Length() != 2) {
1871 return env->ThrowError("Bad argument.");
1874 int pid = args[0]->Int32Value();
1875 int sig = args[1]->Int32Value();
1876 int err = uv_kill(pid, sig);
1877 args.GetReturnValue().Set(err);
1880 // used in Hrtime() below
1881 #define NANOS_PER_SEC 1000000000
1883 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1884 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1885 // so this function instead returns an Array with 2 entries representing seconds
1886 // and nanoseconds, to avoid any integer overflow possibility.
1887 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1888 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1889 Environment* env = Environment::GetCurrent(args);
1891 uint64_t t = uv_hrtime();
1893 if (args.Length() > 0) {
1894 // return a time diff tuple
1895 if (!args[0]->IsArray()) {
1896 return env->ThrowTypeError(
1897 "process.hrtime() only accepts an Array tuple.");
1899 Local<Array> inArray = Local<Array>::Cast(args[0]);
1900 uint64_t seconds = inArray->Get(0)->Uint32Value();
1901 uint64_t nanos = inArray->Get(1)->Uint32Value();
1902 t -= (seconds * NANOS_PER_SEC) + nanos;
1905 Local<Array> tuple = Array::New(env->isolate(), 2);
1906 tuple->Set(0, Integer::NewFromUnsigned(env->isolate(), t / NANOS_PER_SEC));
1907 tuple->Set(1, Integer::NewFromUnsigned(env->isolate(), t % NANOS_PER_SEC));
1908 args.GetReturnValue().Set(tuple);
1911 extern "C" void node_module_register(void* m) {
1912 struct node_module* mp = reinterpret_cast<struct node_module*>(m);
1914 if (mp->nm_flags & NM_F_BUILTIN) {
1915 mp->nm_link = modlist_builtin;
1916 modlist_builtin = mp;
1917 } else if (!node_is_initialized) {
1918 // "Linked" modules are included as part of the node project.
1919 // Like builtins they are registered *before* node::Init runs.
1920 mp->nm_flags = NM_F_LINKED;
1921 mp->nm_link = modlist_linked;
1922 modlist_linked = mp;
1928 struct node_module* get_builtin_module(const char* name) {
1929 struct node_module* mp;
1931 for (mp = modlist_builtin; mp != nullptr; mp = mp->nm_link) {
1932 if (strcmp(mp->nm_modname, name) == 0)
1936 CHECK(mp == nullptr || (mp->nm_flags & NM_F_BUILTIN) != 0);
1940 struct node_module* get_linked_module(const char* name) {
1941 struct node_module* mp;
1943 for (mp = modlist_linked; mp != nullptr; mp = mp->nm_link) {
1944 if (strcmp(mp->nm_modname, name) == 0)
1948 CHECK(mp == nullptr || (mp->nm_flags & NM_F_LINKED) != 0);
1952 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1954 // DLOpen is process.dlopen(module, filename).
1955 // Used to load 'module.node' dynamically shared objects.
1957 // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
1958 // when two contexts try to load the same shared object. Maybe have a shadow
1959 // cache that's a plain C list or hash table that's shared across contexts?
1960 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1961 Environment* env = Environment::GetCurrent(args);
1964 CHECK_EQ(modpending, nullptr);
1966 if (args.Length() < 2) {
1967 env->ThrowError("process.dlopen takes exactly 2 arguments.");
1971 Local<Object> module = args[0]->ToObject(env->isolate()); // Cast
1972 node::Utf8Value filename(env->isolate(), args[1]); // Cast
1973 const bool is_dlopen_error = uv_dlopen(*filename, &lib);
1975 // Objects containing v14 or later modules will have registered themselves
1976 // on the pending list. Activate all of them now. At present, only one
1977 // module per object is supported.
1978 node_module* const mp = modpending;
1979 modpending = nullptr;
1981 if (is_dlopen_error) {
1982 Local<String> errmsg = OneByteString(env->isolate(), uv_dlerror(&lib));
1984 // Windows needs to add the filename into the error message
1985 errmsg = String::Concat(errmsg, args[1]->ToString(env->isolate()));
1987 env->isolate()->ThrowException(Exception::Error(errmsg));
1991 if (mp == nullptr) {
1992 env->ThrowError("Module did not self-register.");
1995 if (mp->nm_version != NODE_MODULE_VERSION) {
1999 "Module version mismatch. Expected %d, got %d.",
2000 NODE_MODULE_VERSION, mp->nm_version);
2001 env->ThrowError(errmsg);
2004 if (mp->nm_flags & NM_F_BUILTIN) {
2005 env->ThrowError("Built-in module self-registered.");
2009 mp->nm_dso_handle = lib.handle;
2010 mp->nm_link = modlist_addon;
2013 Local<String> exports_string = env->exports_string();
2014 Local<Object> exports = module->Get(exports_string)->ToObject(env->isolate());
2016 if (mp->nm_context_register_func != nullptr) {
2017 mp->nm_context_register_func(exports, module, env->context(), mp->nm_priv);
2018 } else if (mp->nm_register_func != nullptr) {
2019 mp->nm_register_func(exports, module, mp->nm_priv);
2021 env->ThrowError("Module has no declared entry point.");
2025 // Tell coverity that 'handle' should not be freed when we return.
2026 // coverity[leaked_storage]
2030 static void OnFatalError(const char* location, const char* message) {
2032 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
2034 fprintf(stderr, "FATAL ERROR: %s\n", message);
2041 NO_RETURN void FatalError(const char* location, const char* message) {
2042 OnFatalError(location, message);
2043 // to supress compiler warning
2048 void FatalException(Isolate* isolate,
2049 Handle<Value> error,
2050 Handle<Message> message) {
2051 HandleScope scope(isolate);
2053 Environment* env = Environment::GetCurrent(isolate);
2054 Local<Object> process_object = env->process_object();
2055 Local<String> fatal_exception_string = env->fatal_exception_string();
2056 Local<Function> fatal_exception_function =
2057 process_object->Get(fatal_exception_string).As<Function>();
2059 if (!fatal_exception_function->IsFunction()) {
2060 // failed before the process._fatalException function was added!
2061 // this is probably pretty bad. Nothing to do but report and exit.
2062 ReportException(env, error, message);
2066 TryCatch fatal_try_catch;
2068 // Do not call FatalException when _fatalException handler throws
2069 fatal_try_catch.SetVerbose(false);
2071 // this will return true if the JS layer handled it, false otherwise
2072 Local<Value> caught =
2073 fatal_exception_function->Call(process_object, 1, &error);
2075 if (fatal_try_catch.HasCaught()) {
2076 // the fatal exception function threw, so we must exit
2077 ReportException(env, fatal_try_catch);
2081 if (false == caught->BooleanValue()) {
2082 ReportException(env, error, message);
2088 void FatalException(Isolate* isolate, const TryCatch& try_catch) {
2089 HandleScope scope(isolate);
2090 // TODO(bajtos) do not call FatalException if try_catch is verbose
2091 // (requires V8 API to expose getter for try_catch.is_verbose_)
2092 FatalException(isolate, try_catch.Exception(), try_catch.Message());
2096 void OnMessage(Handle<Message> message, Handle<Value> error) {
2097 // The current version of V8 sends messages for errors only
2098 // (thus `error` is always set).
2099 FatalException(Isolate::GetCurrent(), error, message);
2103 static void Binding(const FunctionCallbackInfo<Value>& args) {
2104 Environment* env = Environment::GetCurrent(args);
2106 Local<String> module = args[0]->ToString(env->isolate());
2107 node::Utf8Value module_v(env->isolate(), module);
2109 Local<Object> cache = env->binding_cache_object();
2110 Local<Object> exports;
2112 if (cache->Has(module)) {
2113 exports = cache->Get(module)->ToObject(env->isolate());
2114 args.GetReturnValue().Set(exports);
2118 // Append a string to process.moduleLoadList
2120 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
2122 Local<Array> modules = env->module_load_list_array();
2123 uint32_t l = modules->Length();
2124 modules->Set(l, OneByteString(env->isolate(), buf));
2126 node_module* mod = get_builtin_module(*module_v);
2127 if (mod != nullptr) {
2128 exports = Object::New(env->isolate());
2129 // Internal bindings don't have a "module" object, only exports.
2130 CHECK_EQ(mod->nm_register_func, nullptr);
2131 CHECK_NE(mod->nm_context_register_func, nullptr);
2132 Local<Value> unused = Undefined(env->isolate());
2133 mod->nm_context_register_func(exports, unused,
2134 env->context(), mod->nm_priv);
2135 cache->Set(module, exports);
2136 } else if (!strcmp(*module_v, "constants")) {
2137 exports = Object::New(env->isolate());
2138 DefineConstants(exports);
2139 cache->Set(module, exports);
2140 } else if (!strcmp(*module_v, "natives")) {
2141 exports = Object::New(env->isolate());
2142 DefineJavaScript(env, exports);
2143 cache->Set(module, exports);
2148 "No such module: %s",
2150 return env->ThrowError(errmsg);
2153 args.GetReturnValue().Set(exports);
2156 static void LinkedBinding(const FunctionCallbackInfo<Value>& args) {
2157 Environment* env = Environment::GetCurrent(args.GetIsolate());
2159 Local<String> module = args[0]->ToString(env->isolate());
2161 Local<Object> cache = env->binding_cache_object();
2162 Local<Value> exports_v = cache->Get(module);
2164 if (exports_v->IsObject())
2165 return args.GetReturnValue().Set(exports_v.As<Object>());
2167 node::Utf8Value module_v(env->isolate(), module);
2168 node_module* mod = get_linked_module(*module_v);
2170 if (mod == nullptr) {
2174 "No such module was linked: %s",
2176 return env->ThrowError(errmsg);
2179 Local<Object> exports = Object::New(env->isolate());
2181 if (mod->nm_context_register_func != nullptr) {
2182 mod->nm_context_register_func(exports,
2186 } else if (mod->nm_register_func != nullptr) {
2187 mod->nm_register_func(exports, module, mod->nm_priv);
2189 return env->ThrowError("Linked module has no declared entry point.");
2192 cache->Set(module, exports);
2194 args.GetReturnValue().Set(exports);
2197 static void ProcessTitleGetter(Local<String> property,
2198 const PropertyCallbackInfo<Value>& info) {
2199 Environment* env = Environment::GetCurrent(info.GetIsolate());
2200 HandleScope scope(env->isolate());
2202 uv_get_process_title(buffer, sizeof(buffer));
2203 info.GetReturnValue().Set(String::NewFromUtf8(env->isolate(), buffer));
2207 static void ProcessTitleSetter(Local<String> property,
2209 const PropertyCallbackInfo<void>& info) {
2210 Environment* env = Environment::GetCurrent(info.GetIsolate());
2211 HandleScope scope(env->isolate());
2212 node::Utf8Value title(env->isolate(), value);
2213 // TODO(piscisaureus): protect with a lock
2214 uv_set_process_title(*title);
2218 static void EnvGetter(Local<String> property,
2219 const PropertyCallbackInfo<Value>& info) {
2220 Environment* env = Environment::GetCurrent(info.GetIsolate());
2221 HandleScope scope(env->isolate());
2223 node::Utf8Value key(env->isolate(), property);
2224 const char* val = getenv(*key);
2226 return info.GetReturnValue().Set(String::NewFromUtf8(env->isolate(), val));
2229 String::Value key(property);
2230 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2231 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2233 ARRAY_SIZE(buffer));
2234 // If result >= sizeof buffer the buffer was too small. That should never
2235 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2237 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2238 result < ARRAY_SIZE(buffer)) {
2239 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2240 Local<String> rc = String::NewFromTwoByte(env->isolate(), two_byte_buffer);
2241 return info.GetReturnValue().Set(rc);
2244 // Not found. Fetch from prototype.
2245 info.GetReturnValue().Set(
2246 info.Data().As<Object>()->Get(property));
2250 static void EnvSetter(Local<String> property,
2252 const PropertyCallbackInfo<Value>& info) {
2253 Environment* env = Environment::GetCurrent(info.GetIsolate());
2254 HandleScope scope(env->isolate());
2256 node::Utf8Value key(env->isolate(), property);
2257 node::Utf8Value val(env->isolate(), value);
2258 setenv(*key, *val, 1);
2260 String::Value key(property);
2261 String::Value val(value);
2262 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2263 // Environment variables that start with '=' are read-only.
2264 if (key_ptr[0] != L'=') {
2265 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2268 // Whether it worked or not, always return rval.
2269 info.GetReturnValue().Set(value);
2273 static void EnvQuery(Local<String> property,
2274 const PropertyCallbackInfo<Integer>& info) {
2275 Environment* env = Environment::GetCurrent(info.GetIsolate());
2276 HandleScope scope(env->isolate());
2277 int32_t rc = -1; // Not found unless proven otherwise.
2279 node::Utf8Value key(env->isolate(), property);
2283 String::Value key(property);
2284 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2285 if (GetEnvironmentVariableW(key_ptr, nullptr, 0) > 0 ||
2286 GetLastError() == ERROR_SUCCESS) {
2288 if (key_ptr[0] == L'=') {
2289 // Environment variables that start with '=' are hidden and read-only.
2290 rc = static_cast<int32_t>(v8::ReadOnly) |
2291 static_cast<int32_t>(v8::DontDelete) |
2292 static_cast<int32_t>(v8::DontEnum);
2297 info.GetReturnValue().Set(rc);
2301 static void EnvDeleter(Local<String> property,
2302 const PropertyCallbackInfo<Boolean>& info) {
2303 Environment* env = Environment::GetCurrent(info.GetIsolate());
2304 HandleScope scope(env->isolate());
2307 node::Utf8Value key(env->isolate(), property);
2308 rc = getenv(*key) != nullptr;
2312 String::Value key(property);
2313 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2314 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, nullptr)) {
2315 // Deletion failed. Return true if the key wasn't there in the first place,
2316 // false if it is still there.
2317 rc = GetEnvironmentVariableW(key_ptr, nullptr, 0) == 0 &&
2318 GetLastError() != ERROR_SUCCESS;
2321 info.GetReturnValue().Set(rc);
2325 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2326 Environment* env = Environment::GetCurrent(info.GetIsolate());
2327 HandleScope scope(env->isolate());
2330 while (environ[size])
2333 Local<Array> envarr = Array::New(env->isolate(), size);
2335 for (int i = 0; i < size; ++i) {
2336 const char* var = environ[i];
2337 const char* s = strchr(var, '=');
2338 const int length = s ? s - var : strlen(var);
2339 Local<String> name = String::NewFromUtf8(env->isolate(),
2341 String::kNormalString,
2343 envarr->Set(i, name);
2346 WCHAR* environment = GetEnvironmentStringsW();
2347 if (environment == nullptr)
2348 return; // This should not happen.
2349 Local<Array> envarr = Array::New(env->isolate());
2350 WCHAR* p = environment;
2355 // If the key starts with '=' it is a hidden environment variable.
2359 s = wcschr(p, L'=');
2364 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2365 const size_t two_byte_buffer_len = s - p;
2366 Local<String> value = String::NewFromTwoByte(env->isolate(),
2368 String::kNormalString,
2369 two_byte_buffer_len);
2370 envarr->Set(i++, value);
2371 p = s + wcslen(s) + 1;
2373 FreeEnvironmentStringsW(environment);
2376 info.GetReturnValue().Set(envarr);
2380 static Handle<Object> GetFeatures(Environment* env) {
2381 EscapableHandleScope scope(env->isolate());
2383 Local<Object> obj = Object::New(env->isolate());
2384 #if defined(DEBUG) && DEBUG
2385 Local<Value> debug = True(env->isolate());
2387 Local<Value> debug = False(env->isolate());
2388 #endif // defined(DEBUG) && DEBUG
2390 obj->Set(env->debug_string(), debug);
2392 obj->Set(env->uv_string(), True(env->isolate()));
2393 // TODO(bnoordhuis) ping libuv
2394 obj->Set(env->ipv6_lc_string(), True(env->isolate()));
2396 #ifdef OPENSSL_NPN_NEGOTIATED
2397 Local<Boolean> tls_npn = True(env->isolate());
2399 Local<Boolean> tls_npn = False(env->isolate());
2401 obj->Set(env->tls_npn_string(), tls_npn);
2403 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2404 Local<Boolean> tls_sni = True(env->isolate());
2406 Local<Boolean> tls_sni = False(env->isolate());
2408 obj->Set(env->tls_sni_string(), tls_sni);
2410 #if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_set_tlsext_status_cb)
2411 Local<Boolean> tls_ocsp = True(env->isolate());
2413 Local<Boolean> tls_ocsp = False(env->isolate());
2414 #endif // !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_set_tlsext_status_cb)
2415 obj->Set(env->tls_ocsp_string(), tls_ocsp);
2417 obj->Set(env->tls_string(),
2418 Boolean::New(env->isolate(),
2419 get_builtin_module("crypto") != nullptr));
2421 return scope.Escape(obj);
2425 static void DebugPortGetter(Local<String> property,
2426 const PropertyCallbackInfo<Value>& info) {
2427 Environment* env = Environment::GetCurrent(info.GetIsolate());
2428 HandleScope scope(env->isolate());
2429 info.GetReturnValue().Set(debug_port);
2433 static void DebugPortSetter(Local<String> property,
2435 const PropertyCallbackInfo<void>& info) {
2436 Environment* env = Environment::GetCurrent(info.GetIsolate());
2437 HandleScope scope(env->isolate());
2438 debug_port = value->Int32Value();
2442 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2443 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2444 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2447 void NeedImmediateCallbackGetter(Local<String> property,
2448 const PropertyCallbackInfo<Value>& info) {
2449 Environment* env = Environment::GetCurrent(info.GetIsolate());
2450 const uv_check_t* immediate_check_handle = env->immediate_check_handle();
2451 bool active = uv_is_active(
2452 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2453 info.GetReturnValue().Set(active);
2457 static void NeedImmediateCallbackSetter(
2458 Local<String> property,
2460 const PropertyCallbackInfo<void>& info) {
2461 HandleScope handle_scope(info.GetIsolate());
2462 Environment* env = Environment::GetCurrent(info.GetIsolate());
2464 uv_check_t* immediate_check_handle = env->immediate_check_handle();
2465 bool active = uv_is_active(
2466 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2468 if (active == value->BooleanValue())
2471 uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
2474 uv_check_stop(immediate_check_handle);
2475 uv_idle_stop(immediate_idle_handle);
2477 uv_check_start(immediate_check_handle, CheckImmediate);
2478 // Idle handle is needed only to stop the event loop from blocking in poll.
2479 uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
2484 void SetIdle(uv_prepare_t* handle) {
2485 Environment* env = Environment::from_idle_prepare_handle(handle);
2486 env->isolate()->GetCpuProfiler()->SetIdle(true);
2490 void ClearIdle(uv_check_t* handle) {
2491 Environment* env = Environment::from_idle_check_handle(handle);
2492 env->isolate()->GetCpuProfiler()->SetIdle(false);
2496 void StartProfilerIdleNotifier(Environment* env) {
2497 uv_prepare_start(env->idle_prepare_handle(), SetIdle);
2498 uv_check_start(env->idle_check_handle(), ClearIdle);
2502 void StopProfilerIdleNotifier(Environment* env) {
2503 uv_prepare_stop(env->idle_prepare_handle());
2504 uv_check_stop(env->idle_check_handle());
2508 void StartProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2509 Environment* env = Environment::GetCurrent(args);
2510 StartProfilerIdleNotifier(env);
2514 void StopProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2515 Environment* env = Environment::GetCurrent(args);
2516 StopProfilerIdleNotifier(env);
2520 #define READONLY_PROPERTY(obj, str, var) \
2522 obj->ForceSet(OneByteString(env->isolate(), str), var, v8::ReadOnly); \
2526 void SetupProcessObject(Environment* env,
2528 const char* const* argv,
2530 const char* const* exec_argv) {
2531 HandleScope scope(env->isolate());
2533 Local<Object> process = env->process_object();
2535 process->SetAccessor(env->title_string(),
2537 ProcessTitleSetter);
2540 READONLY_PROPERTY(process,
2542 FIXED_ONE_BYTE_STRING(env->isolate(), NODE_VERSION));
2544 // process.moduleLoadList
2545 READONLY_PROPERTY(process,
2547 env->module_load_list_array());
2550 Local<Object> versions = Object::New(env->isolate());
2551 READONLY_PROPERTY(process, "versions", versions);
2553 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2555 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2556 READONLY_PROPERTY(versions,
2558 FIXED_ONE_BYTE_STRING(env->isolate(), http_parser_version));
2560 // +1 to get rid of the leading 'v'
2561 READONLY_PROPERTY(versions,
2563 OneByteString(env->isolate(), NODE_VERSION + 1));
2564 READONLY_PROPERTY(versions,
2566 OneByteString(env->isolate(), V8::GetVersion()));
2567 READONLY_PROPERTY(versions,
2569 OneByteString(env->isolate(), uv_version_string()));
2570 READONLY_PROPERTY(versions,
2572 FIXED_ONE_BYTE_STRING(env->isolate(), ZLIB_VERSION));
2574 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2578 FIXED_ONE_BYTE_STRING(env->isolate(), node_modules_version));
2581 // Stupid code to slice out the version string.
2582 { // NOLINT(whitespace/braces)
2585 for (i = j = 0, k = sizeof(OPENSSL_VERSION_TEXT) - 1; i < k; ++i) {
2586 c = OPENSSL_VERSION_TEXT[i];
2587 if ('0' <= c && c <= '9') {
2588 for (j = i + 1; j < k; ++j) {
2589 c = OPENSSL_VERSION_TEXT[j];
2599 OneByteString(env->isolate(), &OPENSSL_VERSION_TEXT[i], j - i));
2604 READONLY_PROPERTY(process, "arch", OneByteString(env->isolate(), NODE_ARCH));
2607 READONLY_PROPERTY(process,
2609 OneByteString(env->isolate(), NODE_PLATFORM));
2612 Local<Array> arguments = Array::New(env->isolate(), argc);
2613 for (int i = 0; i < argc; ++i) {
2614 arguments->Set(i, String::NewFromUtf8(env->isolate(), argv[i]));
2616 process->Set(env->argv_string(), arguments);
2619 Local<Array> exec_arguments = Array::New(env->isolate(), exec_argc);
2620 for (int i = 0; i < exec_argc; ++i) {
2621 exec_arguments->Set(i, String::NewFromUtf8(env->isolate(), exec_argv[i]));
2623 process->Set(env->exec_argv_string(), exec_arguments);
2625 // create process.env
2626 Local<ObjectTemplate> process_env_template =
2627 ObjectTemplate::New(env->isolate());
2628 process_env_template->SetNamedPropertyHandler(EnvGetter,
2633 Object::New(env->isolate()));
2634 Local<Object> process_env = process_env_template->NewInstance();
2635 process->Set(env->env_string(), process_env);
2637 READONLY_PROPERTY(process, "pid", Integer::New(env->isolate(), getpid()));
2638 READONLY_PROPERTY(process, "features", GetFeatures(env));
2639 process->SetAccessor(env->need_imm_cb_string(),
2640 NeedImmediateCallbackGetter,
2641 NeedImmediateCallbackSetter);
2645 READONLY_PROPERTY(process,
2647 String::NewFromUtf8(env->isolate(), eval_string));
2652 READONLY_PROPERTY(process, "_print_eval", True(env->isolate()));
2655 // -i, --interactive
2657 READONLY_PROPERTY(process, "_forceRepl", True(env->isolate()));
2661 if (no_deprecation) {
2662 READONLY_PROPERTY(process, "noDeprecation", True(env->isolate()));
2665 // --throw-deprecation
2666 if (throw_deprecation) {
2667 READONLY_PROPERTY(process, "throwDeprecation", True(env->isolate()));
2670 // --trace-deprecation
2671 if (trace_deprecation) {
2672 READONLY_PROPERTY(process, "traceDeprecation", True(env->isolate()));
2675 size_t exec_path_len = 2 * PATH_MAX;
2676 char* exec_path = new char[exec_path_len];
2677 Local<String> exec_path_value;
2678 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2679 exec_path_value = String::NewFromUtf8(env->isolate(),
2681 String::kNormalString,
2684 exec_path_value = String::NewFromUtf8(env->isolate(), argv[0]);
2686 process->Set(env->exec_path_string(), exec_path_value);
2689 process->SetAccessor(env->debug_port_string(),
2693 // define various internal methods
2694 env->SetMethod(process,
2695 "_startProfilerIdleNotifier",
2696 StartProfilerIdleNotifier);
2697 env->SetMethod(process,
2698 "_stopProfilerIdleNotifier",
2699 StopProfilerIdleNotifier);
2700 env->SetMethod(process, "_getActiveRequests", GetActiveRequests);
2701 env->SetMethod(process, "_getActiveHandles", GetActiveHandles);
2702 env->SetMethod(process, "reallyExit", Exit);
2703 env->SetMethod(process, "abort", Abort);
2704 env->SetMethod(process, "chdir", Chdir);
2705 env->SetMethod(process, "cwd", Cwd);
2707 env->SetMethod(process, "umask", Umask);
2709 #if defined(__POSIX__) && !defined(__ANDROID__)
2710 env->SetMethod(process, "getuid", GetUid);
2711 env->SetMethod(process, "setuid", SetUid);
2713 env->SetMethod(process, "setgid", SetGid);
2714 env->SetMethod(process, "getgid", GetGid);
2716 env->SetMethod(process, "getgroups", GetGroups);
2717 env->SetMethod(process, "setgroups", SetGroups);
2718 env->SetMethod(process, "initgroups", InitGroups);
2719 #endif // __POSIX__ && !defined(__ANDROID__)
2721 env->SetMethod(process, "_kill", Kill);
2723 env->SetMethod(process, "_debugProcess", DebugProcess);
2724 env->SetMethod(process, "_debugPause", DebugPause);
2725 env->SetMethod(process, "_debugEnd", DebugEnd);
2727 env->SetMethod(process, "hrtime", Hrtime);
2729 env->SetMethod(process, "dlopen", DLOpen);
2731 env->SetMethod(process, "uptime", Uptime);
2732 env->SetMethod(process, "memoryUsage", MemoryUsage);
2734 env->SetMethod(process, "binding", Binding);
2735 env->SetMethod(process, "_linkedBinding", LinkedBinding);
2737 env->SetMethod(process, "_setupNextTick", SetupNextTick);
2738 env->SetMethod(process, "_setupDomainUse", SetupDomainUse);
2740 // pre-set _events object for faster emit checks
2741 process->Set(env->events_string(), Object::New(env->isolate()));
2745 #undef READONLY_PROPERTY
2748 static void AtExit() {
2749 uv_tty_reset_mode();
2753 static void SignalExit(int signo) {
2754 uv_tty_reset_mode();
2759 // Most of the time, it's best to use `console.error` to write
2760 // to the process.stderr stream. However, in some cases, such as
2761 // when debugging the stream.Writable class or the process.nextTick
2762 // function, it is useful to bypass JavaScript entirely.
2763 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2764 CHECK(args.Length() == 1 && args[0]->IsString() &&
2765 "must be called with a single string");
2766 node::Utf8Value message(args.GetIsolate(), args[0]);
2767 fprintf(stderr, "%s\n", *message);
2772 void LoadEnvironment(Environment* env) {
2773 HandleScope handle_scope(env->isolate());
2775 env->isolate()->SetFatalErrorHandler(node::OnFatalError);
2776 env->isolate()->AddMessageListener(OnMessage);
2778 // Compile, execute the src/node.js file. (Which was included as static C
2779 // string in node_natives.h. 'natve_node' is the string containing that
2782 // The node.js file returns a function 'f'
2787 // Disable verbose mode to stop FatalException() handler from trying
2788 // to handle the exception. Errors this early in the start-up phase
2789 // are not safe to ignore.
2790 try_catch.SetVerbose(false);
2792 Local<String> script_name = FIXED_ONE_BYTE_STRING(env->isolate(), "node.js");
2793 Local<Value> f_value = ExecuteString(env, MainSource(env), script_name);
2794 if (try_catch.HasCaught()) {
2795 ReportException(env, try_catch);
2798 CHECK(f_value->IsFunction());
2799 Local<Function> f = Local<Function>::Cast(f_value);
2801 // Now we call 'f' with the 'process' variable that we've built up with
2802 // all our bindings. Inside node.js we'll take care of assigning things to
2805 // We start the process this way in order to be more modular. Developers
2806 // who do not like how 'src/node.js' setups the module system but do like
2807 // Node's I/O bindings may want to replace 'f' with their own function.
2809 // Add a reference to the global object
2810 Local<Object> global = env->context()->Global();
2812 #if defined HAVE_DTRACE || defined HAVE_ETW
2813 InitDTrace(env, global);
2816 #if defined HAVE_PERFCTR
2817 InitPerfCounters(env, global);
2820 // Enable handling of uncaught exceptions
2821 // (FatalException(), break on uncaught exception in debugger)
2823 // This is not strictly necessary since it's almost impossible
2824 // to attach the debugger fast enought to break on exception
2825 // thrown during process startup.
2826 try_catch.SetVerbose(true);
2828 env->SetMethod(env->process_object(), "_rawDebug", RawDebug);
2830 Local<Value> arg = env->process_object();
2831 f->Call(global, 1, &arg);
2834 static void PrintHelp();
2836 static bool ParseDebugOpt(const char* arg) {
2837 const char* port = nullptr;
2839 if (!strcmp(arg, "--debug")) {
2840 use_debug_agent = true;
2841 } else if (!strncmp(arg, "--debug=", sizeof("--debug=") - 1)) {
2842 use_debug_agent = true;
2843 port = arg + sizeof("--debug=") - 1;
2844 } else if (!strcmp(arg, "--debug-brk")) {
2845 use_debug_agent = true;
2846 debug_wait_connect = true;
2847 } else if (!strncmp(arg, "--debug-brk=", sizeof("--debug-brk=") - 1)) {
2848 use_debug_agent = true;
2849 debug_wait_connect = true;
2850 port = arg + sizeof("--debug-brk=") - 1;
2851 } else if (!strncmp(arg, "--debug-port=", sizeof("--debug-port=") - 1)) {
2852 port = arg + sizeof("--debug-port=") - 1;
2857 if (port != nullptr) {
2858 debug_port = atoi(port);
2859 if (debug_port < 1024 || debug_port > 65535) {
2860 fprintf(stderr, "Debug port must be in range 1024 to 65535.\n");
2869 static void PrintHelp() {
2870 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2871 " node debug script.js [arguments] \n"
2874 " -v, --version print node's version\n"
2875 " -e, --eval script evaluate script\n"
2876 " -p, --print evaluate script and print result\n"
2877 " -i, --interactive always enter the REPL even if stdin\n"
2878 " does not appear to be a terminal\n"
2879 " --no-deprecation silence deprecation warnings\n"
2880 " --throw-deprecation throw an exception anytime a deprecated "
2881 "function is used\n"
2882 " --trace-deprecation show stack traces on deprecations\n"
2883 " --v8-options print v8 command line options\n"
2884 " --max-stack-size=val set max v8 stack size (bytes)\n"
2885 #if defined(NODE_HAVE_I18N_SUPPORT)
2886 " --icu-data-dir=dir set ICU data load path to dir\n"
2887 " (overrides NODE_ICU_DATA)\n"
2888 #if !defined(NODE_HAVE_SMALL_ICU)
2889 " Note: linked-in ICU data is\n"
2894 "Environment variables:\n"
2896 "NODE_PATH ';'-separated list of directories\n"
2898 "NODE_PATH ':'-separated list of directories\n"
2900 " prefixed to the module search path.\n"
2901 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2902 " global contexts.\n"
2903 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2904 #if defined(NODE_HAVE_I18N_SUPPORT)
2905 "NODE_ICU_DATA Data path for ICU (Intl object) data\n"
2906 #if !defined(NODE_HAVE_SMALL_ICU)
2907 " (will extend linked-in data)\n"
2911 "Documentation can be found at http://nodejs.org/\n");
2915 // Parse command line arguments.
2917 // argv is modified in place. exec_argv and v8_argv are out arguments that
2918 // ParseArgs() allocates memory for and stores a pointer to the output
2919 // vector in. The caller should free them with delete[].
2923 // * argv contains the arguments with node and V8 options filtered out.
2924 // * exec_argv contains both node and V8 options and nothing else.
2925 // * v8_argv contains argv[0] plus any V8 options
2926 static void ParseArgs(int* argc,
2929 const char*** exec_argv,
2931 const char*** v8_argv) {
2932 const unsigned int nargs = static_cast<unsigned int>(*argc);
2933 const char** new_exec_argv = new const char*[nargs];
2934 const char** new_v8_argv = new const char*[nargs];
2935 const char** new_argv = new const char*[nargs];
2937 for (unsigned int i = 0; i < nargs; ++i) {
2938 new_exec_argv[i] = nullptr;
2939 new_v8_argv[i] = nullptr;
2940 new_argv[i] = nullptr;
2943 // exec_argv starts with the first option, the other two start with argv[0].
2944 unsigned int new_exec_argc = 0;
2945 unsigned int new_v8_argc = 1;
2946 unsigned int new_argc = 1;
2947 new_v8_argv[0] = argv[0];
2948 new_argv[0] = argv[0];
2950 unsigned int index = 1;
2951 while (index < nargs && argv[index][0] == '-') {
2952 const char* const arg = argv[index];
2953 unsigned int args_consumed = 1;
2955 if (ParseDebugOpt(arg)) {
2956 // Done, consumed by ParseDebugOpt().
2957 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2958 printf("%s\n", NODE_VERSION);
2960 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2963 } else if (strcmp(arg, "--eval") == 0 ||
2964 strcmp(arg, "-e") == 0 ||
2965 strcmp(arg, "--print") == 0 ||
2966 strcmp(arg, "-pe") == 0 ||
2967 strcmp(arg, "-p") == 0) {
2968 bool is_eval = strchr(arg, 'e') != nullptr;
2969 bool is_print = strchr(arg, 'p') != nullptr;
2970 print_eval = print_eval || is_print;
2971 // --eval, -e and -pe always require an argument.
2972 if (is_eval == true) {
2974 eval_string = argv[index + 1];
2975 if (eval_string == nullptr) {
2976 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
2979 } else if ((index + 1 < nargs) &&
2980 argv[index + 1] != nullptr &&
2981 argv[index + 1][0] != '-') {
2983 eval_string = argv[index + 1];
2984 if (strncmp(eval_string, "\\-", 2) == 0) {
2985 // Starts with "\\-": escaped expression, drop the backslash.
2989 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2991 } else if (strcmp(arg, "--no-deprecation") == 0) {
2992 no_deprecation = true;
2993 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2994 trace_deprecation = true;
2995 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2996 throw_deprecation = true;
2997 } else if (strcmp(arg, "--v8-options") == 0) {
2998 new_v8_argv[new_v8_argc] = "--help";
3000 #if defined(NODE_HAVE_I18N_SUPPORT)
3001 } else if (strncmp(arg, "--icu-data-dir=", 15) == 0) {
3002 icu_data_dir = arg + 15;
3005 // V8 option. Pass through as-is.
3006 new_v8_argv[new_v8_argc] = arg;
3010 memcpy(new_exec_argv + new_exec_argc,
3012 args_consumed * sizeof(*argv));
3014 new_exec_argc += args_consumed;
3015 index += args_consumed;
3018 // Copy remaining arguments.
3019 const unsigned int args_left = nargs - index;
3020 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
3021 new_argc += args_left;
3023 *exec_argc = new_exec_argc;
3024 *exec_argv = new_exec_argv;
3025 *v8_argc = new_v8_argc;
3026 *v8_argv = new_v8_argv;
3028 // Copy new_argv over argv and update argc.
3029 memcpy(argv, new_argv, new_argc * sizeof(*argv));
3031 *argc = static_cast<int>(new_argc);
3035 // Called from V8 Debug Agent TCP thread.
3036 static void DispatchMessagesDebugAgentCallback(Environment* env) {
3037 // TODO(indutny): move async handle to environment
3038 uv_async_send(&dispatch_debug_messages_async);
3042 static void StartDebug(Environment* env, bool wait) {
3043 CHECK(!debugger_running);
3045 env->debugger_agent()->set_dispatch_handler(
3046 DispatchMessagesDebugAgentCallback);
3047 debugger_running = env->debugger_agent()->Start(debug_port, wait);
3048 if (debugger_running == false) {
3049 fprintf(stderr, "Starting debugger on port %d failed\n", debug_port);
3056 // Called from the main thread.
3057 static void EnableDebug(Environment* env) {
3058 CHECK(debugger_running);
3060 // Send message to enable debug in workers
3061 HandleScope handle_scope(env->isolate());
3063 Local<Object> message = Object::New(env->isolate());
3064 message->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "cmd"),
3065 FIXED_ONE_BYTE_STRING(env->isolate(), "NODE_DEBUG_ENABLED"));
3066 Local<Value> argv[] = {
3067 FIXED_ONE_BYTE_STRING(env->isolate(), "internalMessage"),
3070 MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(argv), argv);
3072 // Enabled debugger, possibly making it wait on a semaphore
3073 env->debugger_agent()->Enable();
3077 // Called from the main thread.
3078 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle) {
3079 if (debugger_running == false) {
3080 fprintf(stderr, "Starting debugger agent.\n");
3082 Environment* env = Environment::GetCurrent(node_isolate);
3083 Context::Scope context_scope(env->context());
3085 StartDebug(env, false);
3088 Isolate::Scope isolate_scope(node_isolate);
3089 v8::Debug::ProcessDebugMessages();
3094 static volatile sig_atomic_t caught_early_debug_signal;
3097 static void EarlyDebugSignalHandler(int signo) {
3098 caught_early_debug_signal = 1;
3102 static void InstallEarlyDebugSignalHandler() {
3103 struct sigaction sa;
3104 memset(&sa, 0, sizeof(sa));
3105 sa.sa_handler = EarlyDebugSignalHandler;
3106 sigaction(SIGUSR1, &sa, nullptr);
3110 static void EnableDebugSignalHandler(int signo) {
3111 // Call only async signal-safe functions here!
3112 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
3113 uv_async_send(&dispatch_debug_messages_async);
3117 static void RegisterSignalHandler(int signal,
3118 void (*handler)(int signal),
3119 bool reset_handler = false) {
3120 struct sigaction sa;
3121 memset(&sa, 0, sizeof(sa));
3122 sa.sa_handler = handler;
3123 sa.sa_flags = reset_handler ? SA_RESETHAND : 0;
3124 sigfillset(&sa.sa_mask);
3125 CHECK_EQ(sigaction(signal, &sa, nullptr), 0);
3129 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3130 Environment* env = Environment::GetCurrent(args);
3132 if (args.Length() != 1) {
3133 return env->ThrowError("Invalid number of arguments.");
3139 pid = args[0]->IntegerValue();
3140 r = kill(pid, SIGUSR1);
3142 return env->ThrowErrnoException(errno, "kill");
3147 static int RegisterDebugSignalHandler() {
3148 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3149 RegisterSignalHandler(SIGUSR1, EnableDebugSignalHandler);
3150 // If we caught a SIGUSR1 during the bootstrap process, re-raise it
3151 // now that the debugger infrastructure is in place.
3152 if (caught_early_debug_signal)
3160 DWORD WINAPI EnableDebugThreadProc(void* arg) {
3161 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
3162 uv_async_send(&dispatch_debug_messages_async);
3167 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
3169 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
3173 static int RegisterDebugSignalHandler() {
3174 wchar_t mapping_name[32];
3175 HANDLE mapping_handle;
3177 LPTHREAD_START_ROUTINE* handler;
3179 pid = GetCurrentProcessId();
3181 if (GetDebugSignalHandlerMappingName(pid,
3183 ARRAY_SIZE(mapping_name)) < 0) {
3187 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
3193 if (mapping_handle == nullptr) {
3197 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3198 MapViewOfFile(mapping_handle,
3199 FILE_MAP_ALL_ACCESS,
3203 if (handler == nullptr) {
3204 CloseHandle(mapping_handle);
3208 *handler = EnableDebugThreadProc;
3210 UnmapViewOfFile(static_cast<void*>(handler));
3216 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3217 Environment* env = Environment::GetCurrent(args);
3218 Isolate* isolate = args.GetIsolate();
3220 HANDLE process = nullptr;
3221 HANDLE thread = nullptr;
3222 HANDLE mapping = nullptr;
3223 wchar_t mapping_name[32];
3224 LPTHREAD_START_ROUTINE* handler = nullptr;
3226 if (args.Length() != 1) {
3227 env->ThrowError("Invalid number of arguments.");
3231 pid = (DWORD) args[0]->IntegerValue();
3233 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
3234 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
3238 if (process == nullptr) {
3239 isolate->ThrowException(
3240 WinapiErrnoException(isolate, GetLastError(), "OpenProcess"));
3244 if (GetDebugSignalHandlerMappingName(pid,
3246 ARRAY_SIZE(mapping_name)) < 0) {
3247 env->ThrowErrnoException(errno, "sprintf");
3251 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
3252 if (mapping == nullptr) {
3253 isolate->ThrowException(WinapiErrnoException(isolate,
3255 "OpenFileMappingW"));
3259 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3260 MapViewOfFile(mapping,
3265 if (handler == nullptr || *handler == nullptr) {
3266 isolate->ThrowException(
3267 WinapiErrnoException(isolate, GetLastError(), "MapViewOfFile"));
3271 thread = CreateRemoteThread(process,
3278 if (thread == nullptr) {
3279 isolate->ThrowException(WinapiErrnoException(isolate,
3281 "CreateRemoteThread"));
3285 // Wait for the thread to terminate
3286 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3287 isolate->ThrowException(WinapiErrnoException(isolate,
3289 "WaitForSingleObject"));
3294 if (process != nullptr)
3295 CloseHandle(process);
3296 if (thread != nullptr)
3297 CloseHandle(thread);
3298 if (handler != nullptr)
3299 UnmapViewOfFile(handler);
3300 if (mapping != nullptr)
3301 CloseHandle(mapping);
3306 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3307 v8::Debug::DebugBreak(args.GetIsolate());
3311 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3312 if (debugger_running) {
3313 Environment* env = Environment::GetCurrent(args);
3314 env->debugger_agent()->Stop();
3315 debugger_running = false;
3320 void Init(int* argc,
3323 const char*** exec_argv) {
3324 // Initialize prog_start_time to get relative uptime.
3325 prog_start_time = static_cast<double>(uv_now(uv_default_loop()));
3327 // Make inherited handles noninheritable.
3328 uv_disable_stdio_inheritance();
3330 // init async debug messages dispatching
3331 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3332 uv_async_init(uv_default_loop(),
3333 &dispatch_debug_messages_async,
3334 DispatchDebugMessagesAsyncCallback);
3335 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3337 // TODO(bnoordhuis) V8 3.32 is unshipping Harmony classes for the moment.
3338 // We're currently at 3.31, disable classes for feature parity. Remove
3339 // again when we upgrade.
3340 V8::SetFlagsFromString("--noharmony_classes",
3341 sizeof("--noharmony_classes") - 1);
3342 V8::SetFlagsFromString("--noharmony_object_literals",
3343 sizeof("--noharmony_object_literals") - 1);
3345 #if defined(NODE_V8_OPTIONS)
3346 // Should come before the call to V8::SetFlagsFromCommandLine()
3347 // so the user can disable a flag --foo at run-time by passing
3348 // --no_foo from the command line.
3349 V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1);
3352 // Parse a few arguments which are specific to Node.
3354 const char** v8_argv;
3355 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3357 // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
3358 // manually? That would give us a little more control over its runtime
3359 // behavior but it could also interfere with the user's intentions in ways
3360 // we fail to anticipate. Dillema.
3361 for (int i = 1; i < v8_argc; ++i) {
3362 if (strncmp(v8_argv[i], "--prof", sizeof("--prof") - 1) == 0) {
3363 v8_is_profiling = true;
3368 #if defined(NODE_HAVE_I18N_SUPPORT)
3369 if (icu_data_dir == nullptr) {
3370 // if the parameter isn't given, use the env variable.
3371 icu_data_dir = secure_getenv("NODE_ICU_DATA");
3374 // If icu_data_dir is nullptr here, it will load the 'minimal' data.
3375 if (!i18n::InitializeICUDirectory(icu_data_dir)) {
3376 FatalError(nullptr, "Could not initialize ICU "
3377 "(check NODE_ICU_DATA or --icu-data-dir parameters)");
3380 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3381 // the argv array or the elements it points to.
3382 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3384 // Anything that's still in v8_argv is not a V8 or a node option.
3385 for (int i = 1; i < v8_argc; i++) {
3386 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3395 if (debug_wait_connect) {
3396 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3397 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3400 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3403 // Raise the open file descriptor limit.
3404 { // NOLINT (whitespace/braces)
3406 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3407 // Do a binary search for the limit.
3408 rlim_t min = lim.rlim_cur;
3409 rlim_t max = 1 << 20;
3410 // But if there's a defined upper bound, don't search, just set it.
3411 if (lim.rlim_max != RLIM_INFINITY) {
3416 lim.rlim_cur = min + (max - min) / 2;
3417 if (setrlimit(RLIMIT_NOFILE, &lim)) {
3422 } while (min + 1 < max);
3426 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3427 RegisterSignalHandler(SIGINT, SignalExit, true);
3428 RegisterSignalHandler(SIGTERM, SignalExit, true);
3431 if (!use_debug_agent) {
3432 RegisterDebugSignalHandler();
3437 struct AtExitCallback {
3438 AtExitCallback* next_;
3439 void (*cb_)(void* arg);
3443 static AtExitCallback* at_exit_functions_;
3446 // TODO(bnoordhuis) Turn into per-context event.
3447 void RunAtExit(Environment* env) {
3448 AtExitCallback* p = at_exit_functions_;
3449 at_exit_functions_ = nullptr;
3452 AtExitCallback* q = p->next_;
3460 void AtExit(void (*cb)(void* arg), void* arg) {
3461 AtExitCallback* p = new AtExitCallback;
3464 p->next_ = at_exit_functions_;
3465 at_exit_functions_ = p;
3469 void EmitBeforeExit(Environment* env) {
3470 Context::Scope context_scope(env->context());
3471 HandleScope handle_scope(env->isolate());
3472 Local<Object> process_object = env->process_object();
3473 Local<String> exit_code = FIXED_ONE_BYTE_STRING(env->isolate(), "exitCode");
3474 Local<Value> args[] = {
3475 FIXED_ONE_BYTE_STRING(env->isolate(), "beforeExit"),
3476 process_object->Get(exit_code)->ToInteger(env->isolate())
3478 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3482 int EmitExit(Environment* env) {
3483 // process.emit('exit')
3484 HandleScope handle_scope(env->isolate());
3485 Context::Scope context_scope(env->context());
3486 Local<Object> process_object = env->process_object();
3487 process_object->Set(env->exiting_string(), True(env->isolate()));
3489 Handle<String> exitCode = env->exit_code_string();
3490 int code = process_object->Get(exitCode)->Int32Value();
3492 Local<Value> args[] = {
3494 Integer::New(env->isolate(), code)
3497 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3499 // Reload exit code, it may be changed by `emit('exit')`
3500 return process_object->Get(exitCode)->Int32Value();
3504 // Just a convenience method
3505 Environment* CreateEnvironment(Isolate* isolate,
3506 Handle<Context> context,
3508 const char* const* argv,
3510 const char* const* exec_argv) {
3512 Context::Scope context_scope(context);
3514 env = CreateEnvironment(isolate,
3522 LoadEnvironment(env);
3528 static void HandleCloseCb(uv_handle_t* handle) {
3529 Environment* env = reinterpret_cast<Environment*>(handle->data);
3530 env->FinishHandleCleanup(handle);
3534 static void HandleCleanup(Environment* env,
3535 uv_handle_t* handle,
3538 uv_close(handle, HandleCloseCb);
3542 Environment* CreateEnvironment(Isolate* isolate,
3544 Handle<Context> context,
3546 const char* const* argv,
3548 const char* const* exec_argv) {
3549 HandleScope handle_scope(isolate);
3551 Context::Scope context_scope(context);
3552 Environment* env = Environment::New(context, loop);
3554 isolate->SetAutorunMicrotasks(false);
3556 uv_check_init(env->event_loop(), env->immediate_check_handle());
3558 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3560 uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3562 // Inform V8's CPU profiler when we're idle. The profiler is sampling-based
3563 // but not all samples are created equal; mark the wall clock time spent in
3564 // epoll_wait() and friends so profiling tools can filter it out. The samples
3565 // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
3566 // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
3567 // probably fortify in the API contract, namely that the last started prepare
3568 // or check watcher runs first. It's not 100% foolproof; if an add-on starts
3569 // a prepare or check watcher after us, any samples attributed to its callback
3570 // will be recorded with state=IDLE.
3571 uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
3572 uv_check_init(env->event_loop(), env->idle_check_handle());
3573 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
3574 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
3576 // Register handle cleanups
3577 env->RegisterHandleCleanup(
3578 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()),
3581 env->RegisterHandleCleanup(
3582 reinterpret_cast<uv_handle_t*>(env->immediate_idle_handle()),
3585 env->RegisterHandleCleanup(
3586 reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()),
3589 env->RegisterHandleCleanup(
3590 reinterpret_cast<uv_handle_t*>(env->idle_check_handle()),
3594 if (v8_is_profiling) {
3595 StartProfilerIdleNotifier(env);
3598 Local<FunctionTemplate> process_template = FunctionTemplate::New(isolate);
3599 process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3601 Local<Object> process_object = process_template->GetFunction()->NewInstance();
3602 env->set_process_object(process_object);
3604 SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3610 int Start(int argc, char** argv) {
3611 const char* replaceInvalid = secure_getenv("NODE_INVALID_UTF8");
3613 if (replaceInvalid == nullptr)
3614 WRITE_UTF8_FLAGS |= String::REPLACE_INVALID_UTF8;
3616 #if !defined(_WIN32)
3617 // Try hard not to lose SIGUSR1 signals during the bootstrap process.
3618 InstallEarlyDebugSignalHandler();
3623 // Hack around with the argv pointer. Used for process.title = "blah".
3624 argv = uv_setup_args(argc, argv);
3626 // This needs to run *before* V8::Initialize(). The const_cast is not
3627 // optional, in case you're wondering.
3629 const char** exec_argv;
3630 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3633 // V8 on Windows doesn't have a good source of entropy. Seed it from
3635 V8::SetEntropySource(crypto::EntropySource);
3638 V8::InitializePlatform(new Platform(4));
3642 node_is_initialized = true;
3644 // Fetch a reference to the main isolate, so we have a reference to it
3645 // even when we need it to access it from another (debugger) thread.
3646 node_isolate = Isolate::New();
3648 Locker locker(node_isolate);
3649 Isolate::Scope isolate_scope(node_isolate);
3650 HandleScope handle_scope(node_isolate);
3651 Local<Context> context = Context::New(node_isolate);
3652 Environment* env = CreateEnvironment(
3660 Context::Scope context_scope(context);
3662 // Start debug agent when argv has --debug
3663 if (use_debug_agent)
3664 StartDebug(env, debug_wait_connect);
3666 LoadEnvironment(env);
3669 if (use_debug_agent)
3674 more = uv_run(env->event_loop(), UV_RUN_ONCE);
3675 if (more == false) {
3676 EmitBeforeExit(env);
3678 // Emit `beforeExit` if the loop became alive either after emitting
3679 // event, or after running some callbacks.
3680 more = uv_loop_alive(env->event_loop());
3681 if (uv_run(env->event_loop(), UV_RUN_NOWAIT) != 0)
3684 } while (more == true);
3685 code = EmitExit(env);
3692 CHECK_NE(node_isolate, nullptr);
3693 node_isolate->Dispose();
3694 node_isolate = nullptr;
3698 exec_argv = nullptr;