1 // Copyright Joyent, Inc. and other Node contributors.
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
23 #include "node_buffer.h"
24 #include "node_constants.h"
25 #include "node_file.h"
26 #include "node_http_parser.h"
27 #include "node_javascript.h"
28 #include "node_version.h"
30 #if defined HAVE_PERFCTR
31 #include "node_counters.h"
35 #include "node_crypto.h"
38 #if defined HAVE_DTRACE || defined HAVE_ETW
39 #include "node_dtrace.h"
43 #include "async-wrap.h"
44 #include "async-wrap-inl.h"
47 #include "handle_wrap.h"
49 #include "string_bytes.h"
52 #include "v8-profiler.h"
57 #include <limits.h> // PATH_MAX
63 #include <sys/types.h>
69 #define strcasecmp _stricmp
70 #define getpid _getpid
74 #include <sys/resource.h> // getrlimit, setrlimit
75 #include <unistd.h> // setuid, getuid
78 #if defined(__POSIX__) && !defined(__ANDROID__)
79 #include <pwd.h> // getpwnam()
80 #include <grp.h> // getgrnam()
84 #include <crt_externs.h>
85 #define environ (*_NSGetEnviron())
86 #elif !defined(_MSC_VER)
87 extern char **environ;
93 using v8::ArrayBuffer;
96 using v8::EscapableHandleScope;
99 using v8::FunctionCallbackInfo;
100 using v8::FunctionTemplate;
102 using v8::HandleScope;
103 using v8::HeapStatistics;
111 using v8::ObjectTemplate;
112 using v8::PropertyCallbackInfo;
118 using v8::kExternalUnsignedIntArray;
120 // FIXME(bnoordhuis) Make these per-context?
121 QUEUE handle_wrap_queue = { &handle_wrap_queue, &handle_wrap_queue };
122 QUEUE req_wrap_queue = { &req_wrap_queue, &req_wrap_queue };
124 static bool print_eval = false;
125 static bool force_repl = false;
126 static bool trace_deprecation = false;
127 static bool throw_deprecation = false;
128 static const char* eval_string = NULL;
129 static bool use_debug_agent = false;
130 static bool debug_wait_connect = false;
131 static int debug_port = 5858;
132 static bool v8_is_profiling = false;
133 static node_module* modpending;
134 static node_module* modlist_builtin;
135 static node_module* modlist_addon;
137 // used by C++ modules as well
138 bool no_deprecation = false;
140 // process-relative uptime base, initialized at start-up
141 static double prog_start_time;
142 static bool debugger_running;
143 static uv_async_t dispatch_debug_messages_async;
145 static Isolate* node_isolate = NULL;
148 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
150 // Impose an upper limit to avoid out of memory errors that bring down
152 static const size_t kMaxLength = 0x3fffffff;
153 static ArrayBufferAllocator the_singleton;
154 virtual ~ArrayBufferAllocator() {}
155 virtual void* Allocate(size_t length);
156 virtual void* AllocateUninitialized(size_t length);
157 virtual void Free(void* data, size_t length);
159 ArrayBufferAllocator() {}
160 ArrayBufferAllocator(const ArrayBufferAllocator&);
161 void operator=(const ArrayBufferAllocator&);
164 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
167 void* ArrayBufferAllocator::Allocate(size_t length) {
168 if (length > kMaxLength)
170 char* data = new char[length];
171 memset(data, 0, length);
176 void* ArrayBufferAllocator::AllocateUninitialized(size_t length) {
177 if (length > kMaxLength)
179 return new char[length];
183 void ArrayBufferAllocator::Free(void* data, size_t length) {
184 delete[] static_cast<char*>(data);
188 static void CheckImmediate(uv_check_t* handle, int status) {
189 Environment* env = Environment::from_immediate_check_handle(handle);
190 HandleScope scope(env->isolate());
191 Context::Scope context_scope(env->context());
192 MakeCallback(env, env->process_object(), env->immediate_callback_string());
196 static void IdleImmediateDummy(uv_idle_t*, int) {
197 // Do nothing. Only for maintaining event loop.
198 // TODO(bnoordhuis) Maybe make libuv accept NULL idle callbacks.
202 static inline const char *errno_string(int errorno) {
203 #define ERRNO_CASE(e) case e: return #e;
210 ERRNO_CASE(EADDRINUSE);
214 ERRNO_CASE(EADDRNOTAVAIL);
218 ERRNO_CASE(EAFNOSUPPORT);
226 # if EAGAIN != EWOULDBLOCK
227 ERRNO_CASE(EWOULDBLOCK);
232 ERRNO_CASE(EALREADY);
248 ERRNO_CASE(ECANCELED);
256 ERRNO_CASE(ECONNABORTED);
260 ERRNO_CASE(ECONNREFUSED);
264 ERRNO_CASE(ECONNRESET);
272 ERRNO_CASE(EDESTADDRREQ);
296 ERRNO_CASE(EHOSTUNREACH);
308 ERRNO_CASE(EINPROGRESS);
344 ERRNO_CASE(EMSGSIZE);
348 ERRNO_CASE(EMULTIHOP);
352 ERRNO_CASE(ENAMETOOLONG);
356 ERRNO_CASE(ENETDOWN);
360 ERRNO_CASE(ENETRESET);
364 ERRNO_CASE(ENETUNREACH);
396 # if ENOLINK != ENOLCK
410 ERRNO_CASE(ENOPROTOOPT);
430 ERRNO_CASE(ENOTCONN);
438 ERRNO_CASE(ENOTEMPTY);
442 ERRNO_CASE(ENOTSOCK);
449 ERRNO_CASE(EOPNOTSUPP);
463 ERRNO_CASE(EOVERFLOW);
478 #ifdef EPROTONOSUPPORT
479 ERRNO_CASE(EPROTONOSUPPORT);
483 ERRNO_CASE(EPROTOTYPE);
511 ERRNO_CASE(ETIMEDOUT);
526 const char *signo_string(int signo) {
527 #define SIGNO_CASE(e) case e: return #e;
554 # if SIGABRT != SIGIOT
598 SIGNO_CASE(SIGSTKFLT);
615 SIGNO_CASE(SIGBREAK);
639 SIGNO_CASE(SIGVTALRM);
647 SIGNO_CASE(SIGWINCH);
655 # if SIGPOLL != SIGIO
665 # if SIGPWR != SIGLOST
679 // Convenience methods
682 void ThrowError(v8::Isolate* isolate, const char* errmsg) {
683 Environment::GetCurrent(isolate)->ThrowError(errmsg);
687 void ThrowTypeError(v8::Isolate* isolate, const char* errmsg) {
688 Environment::GetCurrent(isolate)->ThrowTypeError(errmsg);
692 void ThrowRangeError(v8::Isolate* isolate, const char* errmsg) {
693 Environment::GetCurrent(isolate)->ThrowRangeError(errmsg);
697 void ThrowErrnoException(v8::Isolate* isolate,
702 Environment::GetCurrent(isolate)->ThrowErrnoException(errorno,
709 void ThrowUVException(v8::Isolate* isolate,
714 Environment::GetCurrent(isolate)->ThrowErrnoException(errorno,
721 Local<Value> ErrnoException(Isolate* isolate,
726 Environment* env = Environment::GetCurrent(isolate);
729 Local<String> estring = OneByteString(env->isolate(), errno_string(errorno));
730 if (msg == NULL || msg[0] == '\0') {
731 msg = strerror(errorno);
733 Local<String> message = OneByteString(env->isolate(), msg);
735 Local<String> cons1 =
736 String::Concat(estring, FIXED_ONE_BYTE_STRING(env->isolate(), ", "));
737 Local<String> cons2 = String::Concat(cons1, message);
740 Local<String> cons3 =
741 String::Concat(cons2, FIXED_ONE_BYTE_STRING(env->isolate(), " '"));
742 Local<String> cons4 =
743 String::Concat(cons3, String::NewFromUtf8(env->isolate(), path));
744 Local<String> cons5 =
745 String::Concat(cons4, FIXED_ONE_BYTE_STRING(env->isolate(), "'"));
746 e = Exception::Error(cons5);
748 e = Exception::Error(cons2);
751 Local<Object> obj = e->ToObject();
752 obj->Set(env->errno_string(), Integer::New(env->isolate(), errorno));
753 obj->Set(env->code_string(), estring);
756 obj->Set(env->path_string(), String::NewFromUtf8(env->isolate(), path));
759 if (syscall != NULL) {
760 obj->Set(env->syscall_string(), OneByteString(env->isolate(), syscall));
767 // hack alert! copy of ErrnoException, tuned for uv errors
768 Local<Value> UVException(Isolate* isolate,
773 Environment* env = Environment::GetCurrent(isolate);
776 msg = uv_strerror(errorno);
778 Local<String> estring = OneByteString(env->isolate(), uv_err_name(errorno));
779 Local<String> message = OneByteString(env->isolate(), msg);
780 Local<String> cons1 =
781 String::Concat(estring, FIXED_ONE_BYTE_STRING(env->isolate(), ", "));
782 Local<String> cons2 = String::Concat(cons1, message);
786 Local<String> path_str;
790 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
791 path_str = String::Concat(FIXED_ONE_BYTE_STRING(env->isolate(), "\\\\"),
792 String::NewFromUtf8(env->isolate(), path + 8));
793 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
794 path_str = String::NewFromUtf8(env->isolate(), path + 4);
796 path_str = String::NewFromUtf8(env->isolate(), path);
799 path_str = String::NewFromUtf8(env->isolate(), path);
802 Local<String> cons3 =
803 String::Concat(cons2, FIXED_ONE_BYTE_STRING(env->isolate(), " '"));
804 Local<String> cons4 =
805 String::Concat(cons3, path_str);
806 Local<String> cons5 =
807 String::Concat(cons4, FIXED_ONE_BYTE_STRING(env->isolate(), "'"));
808 e = Exception::Error(cons5);
810 e = Exception::Error(cons2);
813 Local<Object> obj = e->ToObject();
814 // TODO(piscisaureus) errno should probably go
815 obj->Set(env->errno_string(), Integer::New(env->isolate(), errorno));
816 obj->Set(env->code_string(), estring);
819 obj->Set(env->path_string(), path_str);
822 if (syscall != NULL) {
823 obj->Set(env->syscall_string(), OneByteString(env->isolate(), syscall));
831 // Does about the same as strerror(),
832 // but supports all windows error messages
833 static const char *winapi_strerror(const int errorno) {
836 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
837 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
838 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
841 // Remove trailing newlines
842 for (int i = strlen(errmsg) - 1;
843 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
849 // FormatMessage failed
850 return "Unknown error";
855 Local<Value> WinapiErrnoException(Isolate* isolate,
860 Environment* env = Environment::GetCurrent(isolate);
862 if (!msg || !msg[0]) {
863 msg = winapi_strerror(errorno);
865 Local<String> message = OneByteString(env->isolate(), msg);
868 Local<String> cons1 =
869 String::Concat(message, FIXED_ONE_BYTE_STRING(isolate, " '"));
870 Local<String> cons2 =
871 String::Concat(cons1, String::NewFromUtf8(isolate, path));
872 Local<String> cons3 =
873 String::Concat(cons2, FIXED_ONE_BYTE_STRING(isolate, "'"));
874 e = Exception::Error(cons3);
876 e = Exception::Error(message);
879 Local<Object> obj = e->ToObject();
880 obj->Set(env->errno_string(), Integer::New(isolate, errorno));
883 obj->Set(env->path_string(), String::NewFromUtf8(isolate, path));
886 if (syscall != NULL) {
887 obj->Set(env->syscall_string(), OneByteString(isolate, syscall));
895 void SetupAsyncListener(const FunctionCallbackInfo<Value>& args) {
896 HandleScope handle_scope(args.GetIsolate());
897 Environment* env = Environment::GetCurrent(args.GetIsolate());
899 assert(args[0]->IsObject());
900 assert(args[1]->IsFunction());
901 assert(args[2]->IsFunction());
902 assert(args[3]->IsFunction());
904 env->set_async_listener_run_function(args[1].As<Function>());
905 env->set_async_listener_load_function(args[2].As<Function>());
906 env->set_async_listener_unload_function(args[3].As<Function>());
908 Local<Object> async_listener_flag_obj = args[0].As<Object>();
909 Environment::AsyncListener* async_listener = env->async_listener();
910 async_listener_flag_obj->SetIndexedPropertiesToExternalArrayData(
911 async_listener->fields(),
912 kExternalUnsignedIntArray,
913 async_listener->fields_count());
915 // Do a little housekeeping.
916 env->process_object()->Delete(
917 FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupAsyncListener"));
921 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
922 Environment* env = Environment::GetCurrent(args.GetIsolate());
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 assert(args[0]->IsArray());
944 assert(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 kExternalUnsignedIntArray,
953 domain_flag->fields_count());
955 // Do a little housekeeping.
956 env->process_object()->Delete(
957 FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupDomainUse"));
961 void SetupNextTick(const FunctionCallbackInfo<Value>& args) {
962 HandleScope handle_scope(args.GetIsolate());
963 Environment* env = Environment::GetCurrent(args.GetIsolate());
965 assert(args[0]->IsObject());
966 assert(args[1]->IsFunction());
968 // Values use to cross communicate with processNextTick.
969 Local<Object> tick_info_obj = args[0].As<Object>();
970 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
971 env->tick_info()->fields(),
972 kExternalUnsignedIntArray,
973 env->tick_info()->fields_count());
975 env->set_tick_callback_function(args[1].As<Function>());
977 // Do a little housekeeping.
978 env->process_object()->Delete(
979 FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupNextTick"));
983 Handle<Value> MakeDomainCallback(Environment* env,
985 const Handle<Function> callback,
987 Handle<Value> argv[]) {
988 // If you hit this assertion, you forgot to enter the v8::Context first.
989 assert(env->context() == env->isolate()->GetCurrentContext());
991 Local<Object> process = env->process_object();
992 Local<Object> object, domain;
993 Local<Value> domain_v;
996 try_catch.SetVerbose(true);
998 bool has_async_queue = false;
1000 if (recv->IsObject()) {
1001 object = recv.As<Object>();
1002 // TODO(trevnorris): This is sucky for performance. Fix it.
1003 has_async_queue = object->Has(env->async_queue_string());
1004 if (has_async_queue) {
1005 env->async_listener_load_function()->Call(process, 1, &recv);
1007 if (try_catch.HasCaught())
1008 return Undefined(env->isolate());
1012 bool has_domain = false;
1014 if (!object.IsEmpty()) {
1015 domain_v = object->Get(env->domain_string());
1016 has_domain = domain_v->IsObject();
1018 domain = domain_v.As<Object>();
1020 if (domain->Get(env->disposed_string())->IsTrue()) {
1021 // domain has been disposed of.
1022 return Undefined(env->isolate());
1025 Local<Function> enter =
1026 domain->Get(env->enter_string()).As<Function>();
1027 assert(enter->IsFunction());
1028 enter->Call(domain, 0, NULL);
1030 if (try_catch.HasCaught()) {
1031 return Undefined(env->isolate());
1036 Local<Value> ret = callback->Call(recv, argc, argv);
1038 if (try_catch.HasCaught()) {
1039 return Undefined(env->isolate());
1043 Local<Function> exit =
1044 domain->Get(env->exit_string()).As<Function>();
1045 assert(exit->IsFunction());
1046 exit->Call(domain, 0, NULL);
1048 if (try_catch.HasCaught()) {
1049 return Undefined(env->isolate());
1053 if (has_async_queue) {
1054 env->async_listener_unload_function()->Call(process, 1, &recv);
1056 if (try_catch.HasCaught())
1057 return Undefined(env->isolate());
1060 Environment::TickInfo* tick_info = env->tick_info();
1062 if (tick_info->last_threw() == 1) {
1063 tick_info->set_last_threw(0);
1067 if (tick_info->in_tick()) {
1071 if (tick_info->length() == 0) {
1072 tick_info->set_index(0);
1076 tick_info->set_in_tick(true);
1078 env->tick_callback_function()->Call(process, 0, NULL);
1080 tick_info->set_in_tick(false);
1082 if (try_catch.HasCaught()) {
1083 tick_info->set_last_threw(true);
1084 return Undefined(env->isolate());
1091 Handle<Value> MakeCallback(Environment* env,
1093 const Handle<Function> callback,
1095 Handle<Value> argv[]) {
1096 if (env->using_domains())
1097 return MakeDomainCallback(env, recv, callback, argc, argv);
1099 // If you hit this assertion, you forgot to enter the v8::Context first.
1100 assert(env->context() == env->isolate()->GetCurrentContext());
1102 Local<Object> process = env->process_object();
1105 try_catch.SetVerbose(true);
1107 // TODO(trevnorris): This is sucky for performance. Fix it.
1108 bool has_async_queue =
1109 recv->IsObject() && recv.As<Object>()->Has(env->async_queue_string());
1110 if (has_async_queue) {
1111 env->async_listener_load_function()->Call(process, 1, &recv);
1112 if (try_catch.HasCaught())
1113 return Undefined(env->isolate());
1116 Local<Value> ret = callback->Call(recv, argc, argv);
1118 if (try_catch.HasCaught()) {
1119 return Undefined(env->isolate());
1122 if (has_async_queue) {
1123 env->async_listener_unload_function()->Call(process, 1, &recv);
1125 if (try_catch.HasCaught())
1126 return Undefined(env->isolate());
1129 Environment::TickInfo* tick_info = env->tick_info();
1131 if (tick_info->in_tick()) {
1135 if (tick_info->length() == 0) {
1136 tick_info->set_index(0);
1140 tick_info->set_in_tick(true);
1142 // process nextTicks after call
1143 env->tick_callback_function()->Call(process, 0, NULL);
1145 tick_info->set_in_tick(false);
1147 if (try_catch.HasCaught()) {
1148 tick_info->set_last_threw(true);
1149 return Undefined(env->isolate());
1157 Handle<Value> MakeCallback(Environment* env,
1158 Handle<Object> recv,
1161 Handle<Value> argv[]) {
1162 Local<Function> callback = recv->Get(index).As<Function>();
1163 assert(callback->IsFunction());
1165 return MakeCallback(env, recv.As<Value>(), callback, argc, argv);
1169 Handle<Value> MakeCallback(Environment* env,
1170 Handle<Object> recv,
1171 Handle<String> symbol,
1173 Handle<Value> argv[]) {
1174 Local<Function> callback = recv->Get(symbol).As<Function>();
1175 assert(callback->IsFunction());
1176 return MakeCallback(env, recv.As<Value>(), callback, argc, argv);
1180 Handle<Value> MakeCallback(Environment* env,
1181 Handle<Object> recv,
1184 Handle<Value> argv[]) {
1185 Local<String> method_string = OneByteString(env->isolate(), method);
1186 return MakeCallback(env, recv, method_string, argc, argv);
1190 Handle<Value> MakeCallback(Isolate* isolate,
1191 Handle<Object> recv,
1194 Handle<Value> argv[]) {
1195 EscapableHandleScope handle_scope(isolate);
1196 Local<Context> context = recv->CreationContext();
1197 Environment* env = Environment::GetCurrent(context);
1198 Context::Scope context_scope(context);
1199 return handle_scope.Escape(
1200 Local<Value>::New(isolate, MakeCallback(env, recv, method, argc, argv)));
1204 Handle<Value> MakeCallback(Isolate* isolate,
1205 Handle<Object> recv,
1206 Handle<String> symbol,
1208 Handle<Value> argv[]) {
1209 EscapableHandleScope handle_scope(isolate);
1210 Local<Context> context = recv->CreationContext();
1211 Environment* env = Environment::GetCurrent(context);
1212 Context::Scope context_scope(context);
1213 return handle_scope.Escape(
1214 Local<Value>::New(isolate, MakeCallback(env, recv, symbol, argc, argv)));
1218 Handle<Value> MakeCallback(Isolate* isolate,
1219 Handle<Object> recv,
1220 Handle<Function> callback,
1222 Handle<Value> argv[]) {
1223 EscapableHandleScope handle_scope(isolate);
1224 Local<Context> context = recv->CreationContext();
1225 Environment* env = Environment::GetCurrent(context);
1226 Context::Scope context_scope(context);
1227 return handle_scope.Escape(Local<Value>::New(
1229 MakeCallback(env, recv.As<Value>(), callback, argc, argv)));
1233 Handle<Value> MakeDomainCallback(Handle<Object> recv,
1234 Handle<Function> callback,
1236 Handle<Value> argv[]) {
1237 Local<Context> context = recv->CreationContext();
1238 Environment* env = Environment::GetCurrent(context);
1239 Context::Scope context_scope(context);
1240 EscapableHandleScope handle_scope(env->isolate());
1241 return handle_scope.Escape(Local<Value>::New(
1243 MakeDomainCallback(env, recv, callback, argc, argv)));
1247 enum encoding ParseEncoding(Isolate* isolate,
1248 Handle<Value> encoding_v,
1249 enum encoding _default) {
1250 HandleScope scope(isolate);
1252 if (!encoding_v->IsString())
1255 String::Utf8Value encoding(encoding_v);
1257 if (strcasecmp(*encoding, "utf8") == 0) {
1259 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1261 } else if (strcasecmp(*encoding, "ascii") == 0) {
1263 } else if (strcasecmp(*encoding, "base64") == 0) {
1265 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1267 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1269 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1271 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1273 } else if (strcasecmp(*encoding, "binary") == 0) {
1275 } else if (strcasecmp(*encoding, "buffer") == 0) {
1277 } else if (strcasecmp(*encoding, "hex") == 0) {
1279 } else if (strcasecmp(*encoding, "raw") == 0) {
1280 if (!no_deprecation) {
1281 fprintf(stderr, "'raw' (array of integers) has been removed. "
1285 } else if (strcasecmp(*encoding, "raws") == 0) {
1286 if (!no_deprecation) {
1287 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1288 "Please update your code.\n");
1296 Local<Value> Encode(Isolate* isolate,
1299 enum encoding encoding) {
1300 return StringBytes::Encode(isolate,
1301 static_cast<const char*>(buf),
1306 // Returns -1 if the handle was not valid for decoding
1307 ssize_t DecodeBytes(Isolate* isolate,
1309 enum encoding encoding) {
1310 HandleScope scope(isolate);
1312 if (val->IsArray()) {
1313 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1319 return StringBytes::Size(isolate, val, encoding);
1323 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1326 // Returns number of bytes written.
1327 ssize_t DecodeWrite(Isolate* isolate,
1331 enum encoding encoding) {
1332 return StringBytes::Write(isolate, buf, buflen, val, encoding, NULL);
1335 void AppendExceptionLine(Environment* env,
1337 Handle<Message> message) {
1338 if (message.IsEmpty())
1341 HandleScope scope(env->isolate());
1342 Local<Object> err_obj;
1343 if (!er.IsEmpty() && er->IsObject()) {
1344 err_obj = er.As<Object>();
1346 // Do it only once per message
1347 if (!err_obj->GetHiddenValue(env->processed_string()).IsEmpty())
1349 err_obj->SetHiddenValue(env->processed_string(), True(env->isolate()));
1352 static char arrow[1024];
1354 // Print (filename):(line number): (message).
1355 String::Utf8Value filename(message->GetScriptResourceName());
1356 const char* filename_string = *filename;
1357 int linenum = message->GetLineNumber();
1358 // Print line of source code.
1359 String::Utf8Value sourceline(message->GetSourceLine());
1360 const char* sourceline_string = *sourceline;
1362 // Because of how node modules work, all scripts are wrapped with a
1363 // "function (module, exports, __filename, ...) {"
1364 // to provide script local variables.
1366 // When reporting errors on the first line of a script, this wrapper
1367 // function is leaked to the user. There used to be a hack here to
1368 // truncate off the first 62 characters, but it caused numerous other
1369 // problems when vm.runIn*Context() methods were used for non-module
1372 // If we ever decide to re-instate such a hack, the following steps
1375 // 1. Pass a flag around to say "this code was wrapped"
1376 // 2. Update the stack frame output so that it is also correct.
1378 // It would probably be simpler to add a line rather than add some
1379 // number of characters to the first line, since V8 truncates the
1380 // sourceline to 78 characters, and we end up not providing very much
1381 // useful debugging info to the user if we remove 62 characters.
1383 int start = message->GetStartColumn();
1384 int end = message->GetEndColumn();
1386 int off = snprintf(arrow,
1394 // Print wavy underline (GetUnderline is deprecated).
1395 for (int i = 0; i < start; i++) {
1396 assert(static_cast<size_t>(off) < sizeof(arrow));
1397 arrow[off++] = (sourceline_string[i] == '\t') ? '\t' : ' ';
1399 for (int i = start; i < end; i++) {
1400 assert(static_cast<size_t>(off) < sizeof(arrow));
1403 assert(static_cast<size_t>(off) < sizeof(arrow) - 1);
1404 arrow[off++] = '\n';
1407 Local<String> arrow_str = String::NewFromUtf8(env->isolate(), arrow);
1411 // Allocation failed, just print it out
1412 if (arrow_str.IsEmpty() || err_obj.IsEmpty() || !err_obj->IsNativeError())
1415 msg = err_obj->Get(env->message_string());
1416 stack = err_obj->Get(env->stack_string());
1418 if (msg.IsEmpty() || stack.IsEmpty())
1421 err_obj->Set(env->message_string(),
1422 String::Concat(arrow_str, msg->ToString()));
1423 err_obj->Set(env->stack_string(),
1424 String::Concat(arrow_str, stack->ToString()));
1428 if (env->printed_error())
1430 env->set_printed_error(true);
1431 uv_tty_reset_mode();
1432 fprintf(stderr, "\n%s", arrow);
1436 static void ReportException(Environment* env,
1438 Handle<Message> message) {
1439 HandleScope scope(env->isolate());
1441 AppendExceptionLine(env, er, message);
1443 Local<Value> trace_value;
1445 if (er->IsUndefined() || er->IsNull())
1446 trace_value = Undefined(env->isolate());
1448 trace_value = er->ToObject()->Get(env->stack_string());
1450 String::Utf8Value trace(trace_value);
1452 // range errors have a trace member set to undefined
1453 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1454 fprintf(stderr, "%s\n", *trace);
1456 // this really only happens for RangeErrors, since they're the only
1457 // kind that won't have all this info in the trace, or when non-Error
1458 // objects are thrown manually.
1459 Local<Value> message;
1462 if (er->IsObject()) {
1463 Local<Object> err_obj = er.As<Object>();
1464 message = err_obj->Get(env->message_string());
1465 name = err_obj->Get(FIXED_ONE_BYTE_STRING(env->isolate(), "name"));
1468 if (message.IsEmpty() ||
1469 message->IsUndefined() ||
1471 name->IsUndefined()) {
1472 // Not an error object. Just print as-is.
1473 String::Utf8Value message(er);
1474 fprintf(stderr, "%s\n", *message);
1476 String::Utf8Value name_string(name);
1477 String::Utf8Value message_string(message);
1478 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1486 static void ReportException(Environment* env, const TryCatch& try_catch) {
1487 ReportException(env, try_catch.Exception(), try_catch.Message());
1491 // Executes a str within the current v8 context.
1492 static Local<Value> ExecuteString(Environment* env,
1493 Handle<String> source,
1494 Handle<Value> filename) {
1495 EscapableHandleScope scope(env->isolate());
1498 // try_catch must be nonverbose to disable FatalException() handler,
1499 // we will handle exceptions ourself.
1500 try_catch.SetVerbose(false);
1502 Local<v8::Script> script = v8::Script::Compile(source, filename);
1503 if (script.IsEmpty()) {
1504 ReportException(env, try_catch);
1508 Local<Value> result = script->Run();
1509 if (result.IsEmpty()) {
1510 ReportException(env, try_catch);
1514 return scope.Escape(result);
1518 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1519 HandleScope scope(args.GetIsolate());
1521 Local<Array> ary = Array::New(args.GetIsolate());
1525 QUEUE_FOREACH(q, &req_wrap_queue) {
1526 ReqWrap<uv_req_t>* w = CONTAINER_OF(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1527 if (w->persistent().IsEmpty())
1529 ary->Set(i++, w->object());
1532 args.GetReturnValue().Set(ary);
1536 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1537 // implemented here for consistency with GetActiveRequests().
1538 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1539 Environment* env = Environment::GetCurrent(args.GetIsolate());
1540 HandleScope scope(env->isolate());
1542 Local<Array> ary = Array::New(env->isolate());
1546 Local<String> owner_sym = env->owner_string();
1548 QUEUE_FOREACH(q, &handle_wrap_queue) {
1549 HandleWrap* w = CONTAINER_OF(q, HandleWrap, handle_wrap_queue_);
1550 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref))
1552 Local<Object> object = w->object();
1553 Local<Value> owner = object->Get(owner_sym);
1554 if (owner->IsUndefined())
1556 ary->Set(i++, owner);
1559 args.GetReturnValue().Set(ary);
1563 static void Abort(const FunctionCallbackInfo<Value>& args) {
1568 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1569 Environment* env = Environment::GetCurrent(args.GetIsolate());
1570 HandleScope scope(env->isolate());
1572 if (args.Length() != 1 || !args[0]->IsString()) {
1573 // FIXME(bnoordhuis) ThrowTypeError?
1574 return env->ThrowError("Bad argument.");
1577 String::Utf8Value path(args[0]);
1578 int err = uv_chdir(*path);
1580 return env->ThrowUVException(err, "uv_chdir");
1585 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1586 Environment* env = Environment::GetCurrent(args.GetIsolate());
1587 HandleScope scope(env->isolate());
1589 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1590 char buf[MAX_PATH * 4];
1595 size_t cwd_len = sizeof(buf);
1596 int err = uv_cwd(buf, &cwd_len);
1598 return env->ThrowUVException(err, "uv_cwd");
1602 // TODO(tjfontaine) in the future libuv will report the size include the null
1603 // for now only windows does, remove conditionals after libuv upgrade
1607 Local<String> cwd = String::NewFromUtf8(env->isolate(),
1609 String::kNormalString,
1611 args.GetReturnValue().Set(cwd);
1615 static void Umask(const FunctionCallbackInfo<Value>& args) {
1616 Environment* env = Environment::GetCurrent(args.GetIsolate());
1617 HandleScope scope(env->isolate());
1620 if (args.Length() < 1 || args[0]->IsUndefined()) {
1622 umask(static_cast<mode_t>(old));
1623 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1624 return env->ThrowTypeError("argument must be an integer or octal string.");
1627 if (args[0]->IsInt32()) {
1628 oct = args[0]->Uint32Value();
1631 String::Utf8Value str(args[0]);
1633 // Parse the octal string.
1634 for (int i = 0; i < str.length(); i++) {
1636 if (c > '7' || c < '0') {
1637 return env->ThrowTypeError("invalid octal string");
1643 old = umask(static_cast<mode_t>(oct));
1646 args.GetReturnValue().Set(old);
1650 #if defined(__POSIX__) && !defined(__ANDROID__)
1652 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1653 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1656 static uid_t uid_by_name(const char* name) {
1664 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1668 return uid_not_found;
1672 static char* name_by_uid(uid_t uid) {
1681 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1682 return strdup(pp->pw_name);
1693 static gid_t gid_by_name(const char* name) {
1701 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1705 return gid_not_found;
1709 #if 0 // For future use.
1710 static const char* name_by_gid(gid_t gid) {
1719 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1720 return strdup(pp->gr_name);
1732 static uid_t uid_by_name(Handle<Value> value) {
1733 if (value->IsUint32()) {
1734 return static_cast<uid_t>(value->Uint32Value());
1736 String::Utf8Value name(value);
1737 return uid_by_name(*name);
1742 static gid_t gid_by_name(Handle<Value> value) {
1743 if (value->IsUint32()) {
1744 return static_cast<gid_t>(value->Uint32Value());
1746 String::Utf8Value name(value);
1747 return gid_by_name(*name);
1752 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1753 // uid_t is an uint32_t on all supported platforms.
1754 args.GetReturnValue().Set(static_cast<uint32_t>(getuid()));
1758 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1759 // gid_t is an uint32_t on all supported platforms.
1760 args.GetReturnValue().Set(static_cast<uint32_t>(getgid()));
1764 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1765 Environment* env = Environment::GetCurrent(args.GetIsolate());
1766 HandleScope scope(env->isolate());
1768 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1769 return env->ThrowTypeError("setgid argument must be a number or a string");
1772 gid_t gid = gid_by_name(args[0]);
1774 if (gid == gid_not_found) {
1775 return env->ThrowError("setgid group id does not exist");
1779 return env->ThrowErrnoException(errno, "setgid");
1784 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1785 Environment* env = Environment::GetCurrent(args.GetIsolate());
1786 HandleScope scope(env->isolate());
1788 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1789 return env->ThrowTypeError("setuid argument must be a number or a string");
1792 uid_t uid = uid_by_name(args[0]);
1794 if (uid == uid_not_found) {
1795 return env->ThrowError("setuid user id does not exist");
1799 return env->ThrowErrnoException(errno, "setuid");
1804 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1805 Environment* env = Environment::GetCurrent(args.GetIsolate());
1806 HandleScope scope(env->isolate());
1808 int ngroups = getgroups(0, NULL);
1810 if (ngroups == -1) {
1811 return env->ThrowErrnoException(errno, "getgroups");
1814 gid_t* groups = new gid_t[ngroups];
1816 ngroups = getgroups(ngroups, groups);
1818 if (ngroups == -1) {
1820 return env->ThrowErrnoException(errno, "getgroups");
1823 Local<Array> groups_list = Array::New(env->isolate(), ngroups);
1824 bool seen_egid = false;
1825 gid_t egid = getegid();
1827 for (int i = 0; i < ngroups; i++) {
1828 groups_list->Set(i, Integer::New(env->isolate(), groups[i]));
1829 if (groups[i] == egid)
1835 if (seen_egid == false) {
1836 groups_list->Set(ngroups, Integer::New(env->isolate(), egid));
1839 args.GetReturnValue().Set(groups_list);
1843 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1844 Environment* env = Environment::GetCurrent(args.GetIsolate());
1845 HandleScope scope(env->isolate());
1847 if (!args[0]->IsArray()) {
1848 return env->ThrowTypeError("argument 1 must be an array");
1851 Local<Array> groups_list = args[0].As<Array>();
1852 size_t size = groups_list->Length();
1853 gid_t* groups = new gid_t[size];
1855 for (size_t i = 0; i < size; i++) {
1856 gid_t gid = gid_by_name(groups_list->Get(i));
1858 if (gid == gid_not_found) {
1860 return env->ThrowError("group name not found");
1866 int rc = setgroups(size, groups);
1870 return env->ThrowErrnoException(errno, "setgroups");
1875 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1876 Environment* env = Environment::GetCurrent(args.GetIsolate());
1877 HandleScope scope(env->isolate());
1879 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1880 return env->ThrowTypeError("argument 1 must be a number or a string");
1883 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1884 return env->ThrowTypeError("argument 2 must be a number or a string");
1887 String::Utf8Value arg0(args[0]);
1892 if (args[0]->IsUint32()) {
1893 user = name_by_uid(args[0]->Uint32Value());
1901 return env->ThrowError("initgroups user not found");
1904 extra_group = gid_by_name(args[1]);
1906 if (extra_group == gid_not_found) {
1909 return env->ThrowError("initgroups extra group not found");
1912 int rc = initgroups(user, extra_group);
1919 return env->ThrowErrnoException(errno, "initgroups");
1923 #endif // __POSIX__ && !defined(__ANDROID__)
1926 void Exit(const FunctionCallbackInfo<Value>& args) {
1927 Environment* env = Environment::GetCurrent(args.GetIsolate());
1928 HandleScope scope(env->isolate());
1929 exit(args[0]->IntegerValue());
1933 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1934 Environment* env = Environment::GetCurrent(args.GetIsolate());
1935 HandleScope scope(env->isolate());
1937 if (uv_uptime(&uptime))
1939 args.GetReturnValue().Set(uptime - prog_start_time);
1943 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1944 Environment* env = Environment::GetCurrent(args.GetIsolate());
1945 HandleScope scope(env->isolate());
1948 int err = uv_resident_set_memory(&rss);
1950 return env->ThrowUVException(err, "uv_resident_set_memory");
1954 HeapStatistics v8_heap_stats;
1955 env->isolate()->GetHeapStatistics(&v8_heap_stats);
1957 Local<Integer> heap_total =
1958 Integer::NewFromUnsigned(env->isolate(), v8_heap_stats.total_heap_size());
1959 Local<Integer> heap_used =
1960 Integer::NewFromUnsigned(env->isolate(), v8_heap_stats.used_heap_size());
1962 Local<Object> info = Object::New(env->isolate());
1963 info->Set(env->rss_string(), Number::New(env->isolate(), rss));
1964 info->Set(env->heap_total_string(), heap_total);
1965 info->Set(env->heap_used_string(), heap_used);
1967 args.GetReturnValue().Set(info);
1971 void Kill(const FunctionCallbackInfo<Value>& args) {
1972 Environment* env = Environment::GetCurrent(args.GetIsolate());
1973 HandleScope scope(env->isolate());
1975 if (args.Length() != 2) {
1976 return env->ThrowError("Bad argument.");
1979 int pid = args[0]->IntegerValue();
1980 int sig = args[1]->Int32Value();
1981 int err = uv_kill(pid, sig);
1982 args.GetReturnValue().Set(err);
1985 // used in Hrtime() below
1986 #define NANOS_PER_SEC 1000000000
1988 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1989 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1990 // so this function instead returns an Array with 2 entries representing seconds
1991 // and nanoseconds, to avoid any integer overflow possibility.
1992 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1993 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1994 Environment* env = Environment::GetCurrent(args.GetIsolate());
1995 HandleScope scope(env->isolate());
1997 uint64_t t = uv_hrtime();
1999 if (args.Length() > 0) {
2000 // return a time diff tuple
2001 if (!args[0]->IsArray()) {
2002 return env->ThrowTypeError(
2003 "process.hrtime() only accepts an Array tuple.");
2005 Local<Array> inArray = Local<Array>::Cast(args[0]);
2006 uint64_t seconds = inArray->Get(0)->Uint32Value();
2007 uint64_t nanos = inArray->Get(1)->Uint32Value();
2008 t -= (seconds * NANOS_PER_SEC) + nanos;
2011 Local<Array> tuple = Array::New(env->isolate(), 2);
2012 tuple->Set(0, Integer::NewFromUnsigned(env->isolate(), t / NANOS_PER_SEC));
2013 tuple->Set(1, Integer::NewFromUnsigned(env->isolate(), t % NANOS_PER_SEC));
2014 args.GetReturnValue().Set(tuple);
2017 extern "C" void node_module_register(void* m) {
2018 struct node_module* mp = reinterpret_cast<struct node_module*>(m);
2020 if (mp->nm_flags & NM_F_BUILTIN) {
2021 mp->nm_link = modlist_builtin;
2022 modlist_builtin = mp;
2024 assert(modpending == NULL);
2029 struct node_module* get_builtin_module(const char* name) {
2030 struct node_module* mp;
2032 for (mp = modlist_builtin; mp != NULL; mp = mp->nm_link) {
2033 if (strcmp(mp->nm_modname, name) == 0)
2037 assert(mp == NULL || (mp->nm_flags & NM_F_BUILTIN) != 0);
2041 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
2043 // DLOpen is process.dlopen(module, filename).
2044 // Used to load 'module.node' dynamically shared objects.
2046 // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
2047 // when two contexts try to load the same shared object. Maybe have a shadow
2048 // cache that's a plain C list or hash table that's shared across contexts?
2049 void DLOpen(const FunctionCallbackInfo<Value>& args) {
2050 HandleScope handle_scope(args.GetIsolate());
2051 Environment* env = Environment::GetCurrent(args.GetIsolate());
2052 struct node_module* mp;
2055 if (args.Length() < 2) {
2056 env->ThrowError("process.dlopen takes exactly 2 arguments.");
2060 Local<Object> module = args[0]->ToObject(); // Cast
2061 String::Utf8Value filename(args[1]); // Cast
2063 Local<String> exports_string = env->exports_string();
2064 Local<Object> exports = module->Get(exports_string)->ToObject();
2066 if (uv_dlopen(*filename, &lib)) {
2067 Local<String> errmsg = OneByteString(env->isolate(), uv_dlerror(&lib));
2069 // Windows needs to add the filename into the error message
2070 errmsg = String::Concat(errmsg, args[1]->ToString());
2072 env->isolate()->ThrowException(Exception::Error(errmsg));
2077 * Objects containing v14 or later modules will have registered themselves
2078 * on the pending list. Activate all of them now. At present, only one
2079 * module per object is supported.
2085 env->ThrowError("Module did not self-register.");
2088 if (mp->nm_version != NODE_MODULE_VERSION) {
2092 "Module version mismatch. Expected %d, got %d.",
2093 NODE_MODULE_VERSION, mp->nm_version);
2094 env->ThrowError(errmsg);
2097 if (mp->nm_flags & NM_F_BUILTIN) {
2098 env->ThrowError("Built-in module self-registered.");
2102 mp->nm_dso_handle = lib.handle;
2103 mp->nm_link = modlist_addon;
2106 if (mp->nm_context_register_func != NULL) {
2107 mp->nm_context_register_func(exports, module, env->context(), mp->nm_priv);
2108 } else if (mp->nm_register_func != NULL) {
2109 mp->nm_register_func(exports, module, mp->nm_priv);
2111 env->ThrowError("Module has no declared entry point.");
2115 // Tell coverity that 'handle' should not be freed when we return.
2116 // coverity[leaked_storage]
2120 static void OnFatalError(const char* location, const char* message) {
2122 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
2124 fprintf(stderr, "FATAL ERROR: %s\n", message);
2131 NO_RETURN void FatalError(const char* location, const char* message) {
2132 OnFatalError(location, message);
2133 // to supress compiler warning
2138 void FatalException(Isolate* isolate,
2139 Handle<Value> error,
2140 Handle<Message> message) {
2141 HandleScope scope(isolate);
2143 Environment* env = Environment::GetCurrent(isolate);
2144 Local<Object> process_object = env->process_object();
2145 Local<String> fatal_exception_string = env->fatal_exception_string();
2146 Local<Function> fatal_exception_function =
2147 process_object->Get(fatal_exception_string).As<Function>();
2149 if (!fatal_exception_function->IsFunction()) {
2150 // failed before the process._fatalException function was added!
2151 // this is probably pretty bad. Nothing to do but report and exit.
2152 ReportException(env, error, message);
2156 TryCatch fatal_try_catch;
2158 // Do not call FatalException when _fatalException handler throws
2159 fatal_try_catch.SetVerbose(false);
2161 // this will return true if the JS layer handled it, false otherwise
2162 Local<Value> caught =
2163 fatal_exception_function->Call(process_object, 1, &error);
2165 if (fatal_try_catch.HasCaught()) {
2166 // the fatal exception function threw, so we must exit
2167 ReportException(env, fatal_try_catch);
2171 if (false == caught->BooleanValue()) {
2172 ReportException(env, error, message);
2178 void FatalException(Isolate* isolate, const TryCatch& try_catch) {
2179 HandleScope scope(isolate);
2180 // TODO(bajtos) do not call FatalException if try_catch is verbose
2181 // (requires V8 API to expose getter for try_catch.is_verbose_)
2182 FatalException(isolate, try_catch.Exception(), try_catch.Message());
2186 void OnMessage(Handle<Message> message, Handle<Value> error) {
2187 // The current version of V8 sends messages for errors only
2188 // (thus `error` is always set).
2189 FatalException(Isolate::GetCurrent(), error, message);
2193 static void Binding(const FunctionCallbackInfo<Value>& args) {
2194 HandleScope handle_scope(args.GetIsolate());
2195 Environment* env = Environment::GetCurrent(args.GetIsolate());
2197 Local<String> module = args[0]->ToString();
2198 String::Utf8Value module_v(module);
2200 Local<Object> cache = env->binding_cache_object();
2201 Local<Object> exports;
2203 if (cache->Has(module)) {
2204 exports = cache->Get(module)->ToObject();
2205 args.GetReturnValue().Set(exports);
2209 // Append a string to process.moduleLoadList
2211 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
2213 Local<Array> modules = env->module_load_list_array();
2214 uint32_t l = modules->Length();
2215 modules->Set(l, OneByteString(env->isolate(), buf));
2217 node_module* mod = get_builtin_module(*module_v);
2219 exports = Object::New(env->isolate());
2220 // Internal bindings don't have a "module" object, only exports.
2221 assert(mod->nm_register_func == NULL);
2222 assert(mod->nm_context_register_func != NULL);
2223 Local<Value> unused = Undefined(env->isolate());
2224 mod->nm_context_register_func(exports, unused,
2225 env->context(), mod->nm_priv);
2226 cache->Set(module, exports);
2227 } else if (!strcmp(*module_v, "constants")) {
2228 exports = Object::New(env->isolate());
2229 DefineConstants(exports);
2230 cache->Set(module, exports);
2231 } else if (!strcmp(*module_v, "natives")) {
2232 exports = Object::New(env->isolate());
2233 DefineJavaScript(env, exports);
2234 cache->Set(module, exports);
2236 return env->ThrowError("No such module");
2239 args.GetReturnValue().Set(exports);
2243 static void ProcessTitleGetter(Local<String> property,
2244 const PropertyCallbackInfo<Value>& info) {
2245 Environment* env = Environment::GetCurrent(info.GetIsolate());
2246 HandleScope scope(env->isolate());
2248 uv_get_process_title(buffer, sizeof(buffer));
2249 info.GetReturnValue().Set(String::NewFromUtf8(env->isolate(), buffer));
2253 static void ProcessTitleSetter(Local<String> property,
2255 const PropertyCallbackInfo<void>& info) {
2256 Environment* env = Environment::GetCurrent(info.GetIsolate());
2257 HandleScope scope(env->isolate());
2258 String::Utf8Value title(value);
2259 // TODO(piscisaureus): protect with a lock
2260 uv_set_process_title(*title);
2264 static void EnvGetter(Local<String> property,
2265 const PropertyCallbackInfo<Value>& info) {
2266 Environment* env = Environment::GetCurrent(info.GetIsolate());
2267 HandleScope scope(env->isolate());
2269 String::Utf8Value key(property);
2270 const char* val = getenv(*key);
2272 return info.GetReturnValue().Set(String::NewFromUtf8(env->isolate(), val));
2275 String::Value key(property);
2276 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2277 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2279 ARRAY_SIZE(buffer));
2280 // If result >= sizeof buffer the buffer was too small. That should never
2281 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2283 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2284 result < ARRAY_SIZE(buffer)) {
2285 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2286 Local<String> rc = String::NewFromTwoByte(env->isolate(), two_byte_buffer);
2287 return info.GetReturnValue().Set(rc);
2290 // Not found. Fetch from prototype.
2291 info.GetReturnValue().Set(
2292 info.Data().As<Object>()->Get(property));
2296 static void EnvSetter(Local<String> property,
2298 const PropertyCallbackInfo<Value>& info) {
2299 Environment* env = Environment::GetCurrent(info.GetIsolate());
2300 HandleScope scope(env->isolate());
2302 String::Utf8Value key(property);
2303 String::Utf8Value val(value);
2304 setenv(*key, *val, 1);
2306 String::Value key(property);
2307 String::Value val(value);
2308 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2309 // Environment variables that start with '=' are read-only.
2310 if (key_ptr[0] != L'=') {
2311 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2314 // Whether it worked or not, always return rval.
2315 info.GetReturnValue().Set(value);
2319 static void EnvQuery(Local<String> property,
2320 const PropertyCallbackInfo<Integer>& info) {
2321 Environment* env = Environment::GetCurrent(info.GetIsolate());
2322 HandleScope scope(env->isolate());
2323 int32_t rc = -1; // Not found unless proven otherwise.
2325 String::Utf8Value key(property);
2329 String::Value key(property);
2330 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2331 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2332 GetLastError() == ERROR_SUCCESS) {
2334 if (key_ptr[0] == L'=') {
2335 // Environment variables that start with '=' are hidden and read-only.
2336 rc = static_cast<int32_t>(v8::ReadOnly) |
2337 static_cast<int32_t>(v8::DontDelete) |
2338 static_cast<int32_t>(v8::DontEnum);
2343 info.GetReturnValue().Set(rc);
2347 static void EnvDeleter(Local<String> property,
2348 const PropertyCallbackInfo<Boolean>& info) {
2349 Environment* env = Environment::GetCurrent(info.GetIsolate());
2350 HandleScope scope(env->isolate());
2353 String::Utf8Value key(property);
2354 rc = getenv(*key) != NULL;
2358 String::Value key(property);
2359 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2360 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2361 // Deletion failed. Return true if the key wasn't there in the first place,
2362 // false if it is still there.
2363 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2364 GetLastError() != ERROR_SUCCESS;
2367 info.GetReturnValue().Set(rc);
2371 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2372 Environment* env = Environment::GetCurrent(info.GetIsolate());
2373 HandleScope scope(env->isolate());
2376 while (environ[size])
2379 Local<Array> envarr = Array::New(env->isolate(), size);
2381 for (int i = 0; i < size; ++i) {
2382 const char* var = environ[i];
2383 const char* s = strchr(var, '=');
2384 const int length = s ? s - var : strlen(var);
2385 Local<String> name = String::NewFromUtf8(env->isolate(),
2387 String::kNormalString,
2389 envarr->Set(i, name);
2392 WCHAR* environment = GetEnvironmentStringsW();
2393 if (environment == NULL)
2394 return; // This should not happen.
2395 Local<Array> envarr = Array::New(env->isolate());
2396 WCHAR* p = environment;
2398 while (*p != NULL) {
2401 // If the key starts with '=' it is a hidden environment variable.
2405 s = wcschr(p, L'=');
2410 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2411 const size_t two_byte_buffer_len = s - p;
2412 Local<String> value = String::NewFromTwoByte(env->isolate(),
2414 String::kNormalString,
2415 two_byte_buffer_len);
2416 envarr->Set(i++, value);
2417 p = s + wcslen(s) + 1;
2419 FreeEnvironmentStringsW(environment);
2422 info.GetReturnValue().Set(envarr);
2426 static Handle<Object> GetFeatures(Environment* env) {
2427 EscapableHandleScope scope(env->isolate());
2429 Local<Object> obj = Object::New(env->isolate());
2430 #if defined(DEBUG) && DEBUG
2431 Local<Value> debug = True(env->isolate());
2433 Local<Value> debug = False(env->isolate());
2434 #endif // defined(DEBUG) && DEBUG
2436 obj->Set(env->debug_string(), debug);
2438 obj->Set(env->uv_string(), True(env->isolate()));
2439 // TODO(bnoordhuis) ping libuv
2440 obj->Set(env->ipv6_lc_string(), True(env->isolate()));
2442 #ifdef OPENSSL_NPN_NEGOTIATED
2443 Local<Boolean> tls_npn = True(env->isolate());
2445 Local<Boolean> tls_npn = False(env->isolate());
2447 obj->Set(env->tls_npn_string(), tls_npn);
2449 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2450 Local<Boolean> tls_sni = True(env->isolate());
2452 Local<Boolean> tls_sni = False(env->isolate());
2454 obj->Set(env->tls_sni_string(), tls_sni);
2456 obj->Set(env->tls_string(),
2457 Boolean::New(env->isolate(), get_builtin_module("crypto") != NULL));
2459 return scope.Escape(obj);
2463 static void DebugPortGetter(Local<String> property,
2464 const PropertyCallbackInfo<Value>& info) {
2465 Environment* env = Environment::GetCurrent(info.GetIsolate());
2466 HandleScope scope(env->isolate());
2467 info.GetReturnValue().Set(debug_port);
2471 static void DebugPortSetter(Local<String> property,
2473 const PropertyCallbackInfo<void>& info) {
2474 Environment* env = Environment::GetCurrent(info.GetIsolate());
2475 HandleScope scope(env->isolate());
2476 debug_port = value->NumberValue();
2480 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2481 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2482 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2485 void NeedImmediateCallbackGetter(Local<String> property,
2486 const PropertyCallbackInfo<Value>& info) {
2487 HandleScope handle_scope(info.GetIsolate());
2488 Environment* env = Environment::GetCurrent(info.GetIsolate());
2489 const uv_check_t* immediate_check_handle = env->immediate_check_handle();
2490 bool active = uv_is_active(
2491 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2492 info.GetReturnValue().Set(active);
2496 static void NeedImmediateCallbackSetter(
2497 Local<String> property,
2499 const PropertyCallbackInfo<void>& info) {
2500 HandleScope handle_scope(info.GetIsolate());
2501 Environment* env = Environment::GetCurrent(info.GetIsolate());
2503 uv_check_t* immediate_check_handle = env->immediate_check_handle();
2504 bool active = uv_is_active(
2505 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2507 if (active == value->BooleanValue())
2510 uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
2513 uv_check_stop(immediate_check_handle);
2514 uv_idle_stop(immediate_idle_handle);
2516 uv_check_start(immediate_check_handle, CheckImmediate);
2517 // Idle handle is needed only to stop the event loop from blocking in poll.
2518 uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
2523 void SetIdle(uv_prepare_t* handle, int) {
2524 Environment* env = Environment::from_idle_prepare_handle(handle);
2525 env->isolate()->GetCpuProfiler()->SetIdle(true);
2529 void ClearIdle(uv_check_t* handle, int) {
2530 Environment* env = Environment::from_idle_check_handle(handle);
2531 env->isolate()->GetCpuProfiler()->SetIdle(false);
2535 void StartProfilerIdleNotifier(Environment* env) {
2536 uv_prepare_start(env->idle_prepare_handle(), SetIdle);
2537 uv_check_start(env->idle_check_handle(), ClearIdle);
2541 void StopProfilerIdleNotifier(Environment* env) {
2542 uv_prepare_stop(env->idle_prepare_handle());
2543 uv_check_stop(env->idle_check_handle());
2547 void StartProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2548 HandleScope handle_scope(args.GetIsolate());
2549 Environment* env = Environment::GetCurrent(args.GetIsolate());
2550 StartProfilerIdleNotifier(env);
2554 void StopProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2555 HandleScope handle_scope(args.GetIsolate());
2556 Environment* env = Environment::GetCurrent(args.GetIsolate());
2557 StopProfilerIdleNotifier(env);
2561 #define READONLY_PROPERTY(obj, str, var) \
2563 obj->Set(OneByteString(env->isolate(), str), var, v8::ReadOnly); \
2567 void SetupProcessObject(Environment* env,
2569 const char* const* argv,
2571 const char* const* exec_argv) {
2572 HandleScope scope(env->isolate());
2574 Local<Object> process = env->process_object();
2576 process->SetAccessor(env->title_string(),
2578 ProcessTitleSetter);
2581 READONLY_PROPERTY(process,
2583 FIXED_ONE_BYTE_STRING(env->isolate(), NODE_VERSION));
2585 // process.moduleLoadList
2586 READONLY_PROPERTY(process,
2588 env->module_load_list_array());
2591 Local<Object> versions = Object::New(env->isolate());
2592 READONLY_PROPERTY(process, "versions", versions);
2594 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2596 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2597 READONLY_PROPERTY(versions,
2599 FIXED_ONE_BYTE_STRING(env->isolate(), http_parser_version));
2601 // +1 to get rid of the leading 'v'
2602 READONLY_PROPERTY(versions,
2604 OneByteString(env->isolate(), NODE_VERSION + 1));
2605 READONLY_PROPERTY(versions,
2607 OneByteString(env->isolate(), V8::GetVersion()));
2608 READONLY_PROPERTY(versions,
2610 OneByteString(env->isolate(), uv_version_string()));
2611 READONLY_PROPERTY(versions,
2613 FIXED_ONE_BYTE_STRING(env->isolate(), ZLIB_VERSION));
2615 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2619 FIXED_ONE_BYTE_STRING(env->isolate(), node_modules_version));
2622 // Stupid code to slice out the version string.
2623 { // NOLINT(whitespace/braces)
2626 for (i = j = 0, k = sizeof(OPENSSL_VERSION_TEXT) - 1; i < k; ++i) {
2627 c = OPENSSL_VERSION_TEXT[i];
2628 if ('0' <= c && c <= '9') {
2629 for (j = i + 1; j < k; ++j) {
2630 c = OPENSSL_VERSION_TEXT[j];
2640 OneByteString(env->isolate(), &OPENSSL_VERSION_TEXT[i], j - i));
2645 READONLY_PROPERTY(process, "arch", OneByteString(env->isolate(), ARCH));
2648 READONLY_PROPERTY(process,
2650 OneByteString(env->isolate(), PLATFORM));
2653 Local<Array> arguments = Array::New(env->isolate(), argc);
2654 for (int i = 0; i < argc; ++i) {
2655 arguments->Set(i, String::NewFromUtf8(env->isolate(), argv[i]));
2657 process->Set(env->argv_string(), arguments);
2660 Local<Array> exec_arguments = Array::New(env->isolate(), exec_argc);
2661 for (int i = 0; i < exec_argc; ++i) {
2662 exec_arguments->Set(i, String::NewFromUtf8(env->isolate(), exec_argv[i]));
2664 process->Set(env->exec_argv_string(), exec_arguments);
2666 // create process.env
2667 Local<ObjectTemplate> process_env_template =
2668 ObjectTemplate::New(env->isolate());
2669 process_env_template->SetNamedPropertyHandler(EnvGetter,
2674 Object::New(env->isolate()));
2675 Local<Object> process_env = process_env_template->NewInstance();
2676 process->Set(env->env_string(), process_env);
2678 READONLY_PROPERTY(process, "pid", Integer::New(env->isolate(), getpid()));
2679 READONLY_PROPERTY(process, "features", GetFeatures(env));
2680 process->SetAccessor(env->need_imm_cb_string(),
2681 NeedImmediateCallbackGetter,
2682 NeedImmediateCallbackSetter);
2686 READONLY_PROPERTY(process,
2688 String::NewFromUtf8(env->isolate(), eval_string));
2693 READONLY_PROPERTY(process, "_print_eval", True(env->isolate()));
2696 // -i, --interactive
2698 READONLY_PROPERTY(process, "_forceRepl", True(env->isolate()));
2702 if (no_deprecation) {
2703 READONLY_PROPERTY(process, "noDeprecation", True(env->isolate()));
2706 // --throw-deprecation
2707 if (throw_deprecation) {
2708 READONLY_PROPERTY(process, "throwDeprecation", True(env->isolate()));
2711 // --trace-deprecation
2712 if (trace_deprecation) {
2713 READONLY_PROPERTY(process, "traceDeprecation", True(env->isolate()));
2716 size_t exec_path_len = 2 * PATH_MAX;
2717 char* exec_path = new char[exec_path_len];
2718 Local<String> exec_path_value;
2719 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2720 exec_path_value = String::NewFromUtf8(env->isolate(),
2722 String::kNormalString,
2725 exec_path_value = String::NewFromUtf8(env->isolate(), argv[0]);
2727 process->Set(env->exec_path_string(), exec_path_value);
2730 process->SetAccessor(env->debug_port_string(),
2734 // define various internal methods
2735 NODE_SET_METHOD(process,
2736 "_startProfilerIdleNotifier",
2737 StartProfilerIdleNotifier);
2738 NODE_SET_METHOD(process,
2739 "_stopProfilerIdleNotifier",
2740 StopProfilerIdleNotifier);
2741 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2742 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2743 NODE_SET_METHOD(process, "reallyExit", Exit);
2744 NODE_SET_METHOD(process, "abort", Abort);
2745 NODE_SET_METHOD(process, "chdir", Chdir);
2746 NODE_SET_METHOD(process, "cwd", Cwd);
2748 NODE_SET_METHOD(process, "umask", Umask);
2750 #if defined(__POSIX__) && !defined(__ANDROID__)
2751 NODE_SET_METHOD(process, "getuid", GetUid);
2752 NODE_SET_METHOD(process, "setuid", SetUid);
2754 NODE_SET_METHOD(process, "setgid", SetGid);
2755 NODE_SET_METHOD(process, "getgid", GetGid);
2757 NODE_SET_METHOD(process, "getgroups", GetGroups);
2758 NODE_SET_METHOD(process, "setgroups", SetGroups);
2759 NODE_SET_METHOD(process, "initgroups", InitGroups);
2760 #endif // __POSIX__ && !defined(__ANDROID__)
2762 NODE_SET_METHOD(process, "_kill", Kill);
2764 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2765 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2766 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2768 NODE_SET_METHOD(process, "hrtime", Hrtime);
2770 NODE_SET_METHOD(process, "dlopen", DLOpen);
2772 NODE_SET_METHOD(process, "uptime", Uptime);
2773 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2775 NODE_SET_METHOD(process, "binding", Binding);
2777 NODE_SET_METHOD(process, "_setupAsyncListener", SetupAsyncListener);
2778 NODE_SET_METHOD(process, "_setupNextTick", SetupNextTick);
2779 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2781 // values use to cross communicate with processNextTick
2782 Local<Object> tick_info_obj = Object::New(env->isolate());
2783 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
2784 env->tick_info()->fields(),
2785 kExternalUnsignedIntArray,
2786 env->tick_info()->fields_count());
2787 process->Set(env->tick_info_string(), tick_info_obj);
2789 // pre-set _events object for faster emit checks
2790 process->Set(env->events_string(), Object::New(env->isolate()));
2794 #undef READONLY_PROPERTY
2797 static void AtExit() {
2798 uv_tty_reset_mode();
2802 static void SignalExit(int signal) {
2803 uv_tty_reset_mode();
2804 _exit(128 + signal);
2808 // Most of the time, it's best to use `console.error` to write
2809 // to the process.stderr stream. However, in some cases, such as
2810 // when debugging the stream.Writable class or the process.nextTick
2811 // function, it is useful to bypass JavaScript entirely.
2812 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2813 Environment* env = Environment::GetCurrent(args.GetIsolate());
2814 HandleScope scope(env->isolate());
2816 assert(args.Length() == 1 && args[0]->IsString() &&
2817 "must be called with a single string");
2819 String::Utf8Value message(args[0]);
2820 fprintf(stderr, "%s\n", *message);
2825 void Load(Environment* env) {
2826 HandleScope handle_scope(env->isolate());
2828 // Compile, execute the src/node.js file. (Which was included as static C
2829 // string in node_natives.h. 'natve_node' is the string containing that
2832 // The node.js file returns a function 'f'
2837 // Disable verbose mode to stop FatalException() handler from trying
2838 // to handle the exception. Errors this early in the start-up phase
2839 // are not safe to ignore.
2840 try_catch.SetVerbose(false);
2842 Local<String> script_name = FIXED_ONE_BYTE_STRING(env->isolate(), "node.js");
2843 Local<Value> f_value = ExecuteString(env, MainSource(env), script_name);
2844 if (try_catch.HasCaught()) {
2845 ReportException(env, try_catch);
2848 assert(f_value->IsFunction());
2849 Local<Function> f = Local<Function>::Cast(f_value);
2851 // Now we call 'f' with the 'process' variable that we've built up with
2852 // all our bindings. Inside node.js we'll take care of assigning things to
2855 // We start the process this way in order to be more modular. Developers
2856 // who do not like how 'src/node.js' setups the module system but do like
2857 // Node's I/O bindings may want to replace 'f' with their own function.
2859 // Add a reference to the global object
2860 Local<Object> global = env->context()->Global();
2862 #if defined HAVE_DTRACE || defined HAVE_ETW
2863 InitDTrace(env, global);
2866 #if defined HAVE_PERFCTR
2867 InitPerfCounters(env, global);
2870 // Enable handling of uncaught exceptions
2871 // (FatalException(), break on uncaught exception in debugger)
2873 // This is not strictly necessary since it's almost impossible
2874 // to attach the debugger fast enought to break on exception
2875 // thrown during process startup.
2876 try_catch.SetVerbose(true);
2878 NODE_SET_METHOD(env->process_object(), "_rawDebug", RawDebug);
2880 Local<Value> arg = env->process_object();
2881 f->Call(global, 1, &arg);
2884 static void PrintHelp();
2886 static bool ParseDebugOpt(const char* arg) {
2887 const char* port = NULL;
2889 if (!strcmp(arg, "--debug")) {
2890 use_debug_agent = true;
2891 } else if (!strncmp(arg, "--debug=", sizeof("--debug=") - 1)) {
2892 use_debug_agent = true;
2893 port = arg + sizeof("--debug=") - 1;
2894 } else if (!strcmp(arg, "--debug-brk")) {
2895 use_debug_agent = true;
2896 debug_wait_connect = true;
2897 } else if (!strncmp(arg, "--debug-brk=", sizeof("--debug-brk=") - 1)) {
2898 use_debug_agent = true;
2899 debug_wait_connect = true;
2900 port = arg + sizeof("--debug-brk=") - 1;
2901 } else if (!strncmp(arg, "--debug-port=", sizeof("--debug-port=") - 1)) {
2902 port = arg + sizeof("--debug-port=") - 1;
2908 debug_port = atoi(port);
2909 if (debug_port < 1024 || debug_port > 65535) {
2910 fprintf(stderr, "Debug port must be in range 1024 to 65535.\n");
2919 static void PrintHelp() {
2920 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2921 " node debug script.js [arguments] \n"
2924 " -v, --version print node's version\n"
2925 " -e, --eval script evaluate script\n"
2926 " -p, --print evaluate script and print result\n"
2927 " -i, --interactive always enter the REPL even if stdin\n"
2928 " does not appear to be a terminal\n"
2929 " --no-deprecation silence deprecation warnings\n"
2930 " --trace-deprecation show stack traces on deprecations\n"
2931 " --v8-options print v8 command line options\n"
2932 " --max-stack-size=val set max v8 stack size (bytes)\n"
2934 "Environment variables:\n"
2936 "NODE_PATH ';'-separated list of directories\n"
2938 "NODE_PATH ':'-separated list of directories\n"
2940 " prefixed to the module search path.\n"
2941 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2942 " global contexts.\n"
2943 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2945 "Documentation can be found at http://nodejs.org/\n");
2949 // Parse command line arguments.
2951 // argv is modified in place. exec_argv and v8_argv are out arguments that
2952 // ParseArgs() allocates memory for and stores a pointer to the output
2953 // vector in. The caller should free them with delete[].
2957 // * argv contains the arguments with node and V8 options filtered out.
2958 // * exec_argv contains both node and V8 options and nothing else.
2959 // * v8_argv contains argv[0] plus any V8 options
2960 static void ParseArgs(int* argc,
2963 const char*** exec_argv,
2965 const char*** v8_argv) {
2966 const unsigned int nargs = static_cast<unsigned int>(*argc);
2967 const char** new_exec_argv = new const char*[nargs];
2968 const char** new_v8_argv = new const char*[nargs];
2969 const char** new_argv = new const char*[nargs];
2971 for (unsigned int i = 0; i < nargs; ++i) {
2972 new_exec_argv[i] = NULL;
2973 new_v8_argv[i] = NULL;
2977 // exec_argv starts with the first option, the other two start with argv[0].
2978 unsigned int new_exec_argc = 0;
2979 unsigned int new_v8_argc = 1;
2980 unsigned int new_argc = 1;
2981 new_v8_argv[0] = argv[0];
2982 new_argv[0] = argv[0];
2984 unsigned int index = 1;
2985 while (index < nargs && argv[index][0] == '-') {
2986 const char* const arg = argv[index];
2987 unsigned int args_consumed = 1;
2989 if (ParseDebugOpt(arg)) {
2990 // Done, consumed by ParseDebugOpt().
2991 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2992 printf("%s\n", NODE_VERSION);
2994 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2997 } else if (strcmp(arg, "--eval") == 0 ||
2998 strcmp(arg, "-e") == 0 ||
2999 strcmp(arg, "--print") == 0 ||
3000 strcmp(arg, "-pe") == 0 ||
3001 strcmp(arg, "-p") == 0) {
3002 bool is_eval = strchr(arg, 'e') != NULL;
3003 bool is_print = strchr(arg, 'p') != NULL;
3004 print_eval = print_eval || is_print;
3005 // --eval, -e and -pe always require an argument.
3006 if (is_eval == true) {
3008 eval_string = argv[index + 1];
3009 if (eval_string == NULL) {
3010 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
3013 } else if ((index + 1 < nargs) &&
3014 argv[index + 1] != NULL &&
3015 argv[index + 1][0] != '-') {
3017 eval_string = argv[index + 1];
3018 if (strncmp(eval_string, "\\-", 2) == 0) {
3019 // Starts with "\\-": escaped expression, drop the backslash.
3023 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
3025 } else if (strcmp(arg, "--no-deprecation") == 0) {
3026 no_deprecation = true;
3027 } else if (strcmp(arg, "--trace-deprecation") == 0) {
3028 trace_deprecation = true;
3029 } else if (strcmp(arg, "--throw-deprecation") == 0) {
3030 throw_deprecation = true;
3031 } else if (strcmp(arg, "--v8-options") == 0) {
3032 new_v8_argv[new_v8_argc] = "--help";
3035 // V8 option. Pass through as-is.
3036 new_v8_argv[new_v8_argc] = arg;
3040 memcpy(new_exec_argv + new_exec_argc,
3042 args_consumed * sizeof(*argv));
3044 new_exec_argc += args_consumed;
3045 index += args_consumed;
3048 // Copy remaining arguments.
3049 const unsigned int args_left = nargs - index;
3050 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
3051 new_argc += args_left;
3053 *exec_argc = new_exec_argc;
3054 *exec_argv = new_exec_argv;
3055 *v8_argc = new_v8_argc;
3056 *v8_argv = new_v8_argv;
3058 // Copy new_argv over argv and update argc.
3059 memcpy(argv, new_argv, new_argc * sizeof(*argv));
3061 *argc = static_cast<int>(new_argc);
3065 // Called from V8 Debug Agent TCP thread.
3066 static void DispatchMessagesDebugAgentCallback() {
3067 uv_async_send(&dispatch_debug_messages_async);
3071 // Called from the main thread.
3072 static void EnableDebug(Isolate* isolate, bool wait_connect) {
3073 assert(debugger_running == false);
3074 Isolate::Scope isolate_scope(isolate);
3075 HandleScope handle_scope(isolate);
3076 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
3078 debugger_running = v8::Debug::EnableAgent("node " NODE_VERSION,
3081 if (debugger_running == false) {
3082 fprintf(stderr, "Starting debugger on port %d failed\n", debug_port);
3086 fprintf(stderr, "Debugger listening on port %d\n", debug_port);
3089 Environment* env = Environment::GetCurrentChecked(isolate);
3091 return; // Still starting up.
3093 Context::Scope context_scope(env->context());
3094 Local<Object> message = Object::New(env->isolate());
3095 message->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "cmd"),
3096 FIXED_ONE_BYTE_STRING(env->isolate(), "NODE_DEBUG_ENABLED"));
3097 Local<Value> argv[] = {
3098 FIXED_ONE_BYTE_STRING(env->isolate(), "internalMessage"),
3101 MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(argv), argv);
3105 // Called from the main thread.
3106 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
3107 if (debugger_running == false) {
3108 fprintf(stderr, "Starting debugger agent.\n");
3109 EnableDebug(node_isolate, false);
3111 Isolate::Scope isolate_scope(node_isolate);
3112 v8::Debug::ProcessDebugMessages();
3117 static volatile sig_atomic_t caught_early_debug_signal;
3120 static void EarlyDebugSignalHandler(int signo) {
3121 caught_early_debug_signal = 1;
3125 static void InstallEarlyDebugSignalHandler() {
3126 struct sigaction sa;
3127 memset(&sa, 0, sizeof(sa));
3128 sa.sa_handler = EarlyDebugSignalHandler;
3129 sigaction(SIGUSR1, &sa, NULL);
3133 static void EnableDebugSignalHandler(int signo) {
3134 // Call only async signal-safe functions here!
3135 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
3136 uv_async_send(&dispatch_debug_messages_async);
3140 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
3141 struct sigaction sa;
3142 memset(&sa, 0, sizeof(sa));
3143 sa.sa_handler = handler;
3144 sigfillset(&sa.sa_mask);
3145 sigaction(signal, &sa, NULL);
3149 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3150 Environment* env = Environment::GetCurrent(args.GetIsolate());
3151 HandleScope scope(env->isolate());
3153 if (args.Length() != 1) {
3154 return env->ThrowError("Invalid number of arguments.");
3160 pid = args[0]->IntegerValue();
3161 r = kill(pid, SIGUSR1);
3163 return env->ThrowErrnoException(errno, "kill");
3168 static int RegisterDebugSignalHandler() {
3169 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3170 RegisterSignalHandler(SIGUSR1, EnableDebugSignalHandler);
3171 // If we caught a SIGUSR1 during the bootstrap process, re-raise it
3172 // now that the debugger infrastructure is in place.
3173 if (caught_early_debug_signal)
3181 DWORD WINAPI EnableDebugThreadProc(void* arg) {
3182 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
3183 uv_async_send(&dispatch_debug_messages_async);
3188 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
3190 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
3194 static int RegisterDebugSignalHandler() {
3195 wchar_t mapping_name[32];
3196 HANDLE mapping_handle;
3198 LPTHREAD_START_ROUTINE* handler;
3200 pid = GetCurrentProcessId();
3202 if (GetDebugSignalHandlerMappingName(pid,
3204 ARRAY_SIZE(mapping_name)) < 0) {
3208 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
3214 if (mapping_handle == NULL) {
3218 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3219 MapViewOfFile(mapping_handle,
3220 FILE_MAP_ALL_ACCESS,
3224 if (handler == NULL) {
3225 CloseHandle(mapping_handle);
3229 *handler = EnableDebugThreadProc;
3231 UnmapViewOfFile(static_cast<void*>(handler));
3237 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3238 Isolate* isolate = args.GetIsolate();
3239 Environment* env = Environment::GetCurrent(isolate);
3240 HandleScope scope(isolate);
3242 HANDLE process = NULL;
3243 HANDLE thread = NULL;
3244 HANDLE mapping = NULL;
3245 wchar_t mapping_name[32];
3246 LPTHREAD_START_ROUTINE* handler = NULL;
3248 if (args.Length() != 1) {
3249 env->ThrowError("Invalid number of arguments.");
3253 pid = (DWORD) args[0]->IntegerValue();
3255 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
3256 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
3260 if (process == NULL) {
3261 isolate->ThrowException(
3262 WinapiErrnoException(isolate, GetLastError(), "OpenProcess"));
3266 if (GetDebugSignalHandlerMappingName(pid,
3268 ARRAY_SIZE(mapping_name)) < 0) {
3269 env->ThrowErrnoException(errno, "sprintf");
3273 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
3274 if (mapping == NULL) {
3275 isolate->ThrowException(WinapiErrnoException(isolate,
3277 "OpenFileMappingW"));
3281 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3282 MapViewOfFile(mapping,
3287 if (handler == NULL || *handler == NULL) {
3288 isolate->ThrowException(
3289 WinapiErrnoException(isolate, GetLastError(), "MapViewOfFile"));
3293 thread = CreateRemoteThread(process,
3300 if (thread == NULL) {
3301 isolate->ThrowException(WinapiErrnoException(isolate,
3303 "CreateRemoteThread"));
3307 // Wait for the thread to terminate
3308 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3309 isolate->ThrowException(WinapiErrnoException(isolate,
3311 "WaitForSingleObject"));
3316 if (process != NULL)
3317 CloseHandle(process);
3319 CloseHandle(thread);
3320 if (handler != NULL)
3321 UnmapViewOfFile(handler);
3322 if (mapping != NULL)
3323 CloseHandle(mapping);
3328 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3329 v8::Debug::DebugBreak(args.GetIsolate());
3333 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3334 if (debugger_running) {
3335 v8::Debug::DisableAgent();
3336 debugger_running = false;
3341 void Init(int* argc,
3344 const char*** exec_argv) {
3345 // Initialize prog_start_time to get relative uptime.
3346 uv_uptime(&prog_start_time);
3348 // Make inherited handles noninheritable.
3349 uv_disable_stdio_inheritance();
3351 // init async debug messages dispatching
3352 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3353 uv_async_init(uv_default_loop(),
3354 &dispatch_debug_messages_async,
3355 DispatchDebugMessagesAsyncCallback);
3356 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3358 #if defined(NODE_V8_OPTIONS)
3359 // Should come before the call to V8::SetFlagsFromCommandLine()
3360 // so the user can disable a flag --foo at run-time by passing
3361 // --no_foo from the command line.
3362 V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1);
3365 // Parse a few arguments which are specific to Node.
3367 const char** v8_argv;
3368 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3370 // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
3371 // manually? That would give us a little more control over its runtime
3372 // behavior but it could also interfere with the user's intentions in ways
3373 // we fail to anticipate. Dillema.
3374 for (int i = 1; i < v8_argc; ++i) {
3375 if (strncmp(v8_argv[i], "--prof", sizeof("--prof") - 1) == 0) {
3376 v8_is_profiling = true;
3381 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3382 // the argv array or the elements it points to.
3383 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3385 // Anything that's still in v8_argv is not a V8 or a node option.
3386 for (int i = 1; i < v8_argc; i++) {
3387 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3396 if (debug_wait_connect) {
3397 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3398 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3401 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3403 // Fetch a reference to the main isolate, so we have a reference to it
3404 // even when we need it to access it from another (debugger) thread.
3405 node_isolate = Isolate::GetCurrent();
3408 // Raise the open file descriptor limit.
3409 { // NOLINT (whitespace/braces)
3411 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3412 // Do a binary search for the limit.
3413 rlim_t min = lim.rlim_cur;
3414 rlim_t max = 1 << 20;
3415 // But if there's a defined upper bound, don't search, just set it.
3416 if (lim.rlim_max != RLIM_INFINITY) {
3421 lim.rlim_cur = min + (max - min) / 2;
3422 if (setrlimit(RLIMIT_NOFILE, &lim)) {
3427 } while (min + 1 < max);
3431 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3432 RegisterSignalHandler(SIGINT, SignalExit);
3433 RegisterSignalHandler(SIGTERM, SignalExit);
3436 V8::SetFatalErrorHandler(node::OnFatalError);
3437 V8::AddMessageListener(OnMessage);
3439 // If the --debug flag was specified then initialize the debug thread.
3440 if (use_debug_agent) {
3441 EnableDebug(node_isolate, debug_wait_connect);
3443 RegisterDebugSignalHandler();
3448 struct AtExitCallback {
3449 AtExitCallback* next_;
3450 void (*cb_)(void* arg);
3454 static AtExitCallback* at_exit_functions_;
3457 // TODO(bnoordhuis) Turn into per-context event.
3458 void RunAtExit(Environment* env) {
3459 AtExitCallback* p = at_exit_functions_;
3460 at_exit_functions_ = NULL;
3463 AtExitCallback* q = p->next_;
3471 void AtExit(void (*cb)(void* arg), void* arg) {
3472 AtExitCallback* p = new AtExitCallback;
3475 p->next_ = at_exit_functions_;
3476 at_exit_functions_ = p;
3480 void EmitBeforeExit(Environment* env) {
3481 Context::Scope context_scope(env->context());
3482 HandleScope handle_scope(env->isolate());
3483 Local<Object> process_object = env->process_object();
3484 Local<String> exit_code = FIXED_ONE_BYTE_STRING(env->isolate(), "exitCode");
3485 Local<Value> args[] = {
3486 FIXED_ONE_BYTE_STRING(env->isolate(), "beforeExit"),
3487 process_object->Get(exit_code)->ToInteger()
3489 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3493 int EmitExit(Environment* env) {
3494 // process.emit('exit')
3495 HandleScope handle_scope(env->isolate());
3496 Context::Scope context_scope(env->context());
3497 Local<Object> process_object = env->process_object();
3498 process_object->Set(env->exiting_string(), True(env->isolate()));
3500 Handle<String> exitCode = env->exit_code_string();
3501 int code = process_object->Get(exitCode)->IntegerValue();
3503 Local<Value> args[] = {
3505 Integer::New(env->isolate(), code)
3508 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3510 // Reload exit code, it may be changed by `emit('exit')`
3511 return process_object->Get(exitCode)->IntegerValue();
3515 Environment* CreateEnvironment(Isolate* isolate,
3517 const char* const* argv,
3519 const char* const* exec_argv) {
3520 HandleScope handle_scope(isolate);
3522 Local<Context> context = Context::New(isolate);
3523 Context::Scope context_scope(context);
3524 Environment* env = Environment::New(context);
3526 uv_check_init(env->event_loop(), env->immediate_check_handle());
3528 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3529 uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3531 // Inform V8's CPU profiler when we're idle. The profiler is sampling-based
3532 // but not all samples are created equal; mark the wall clock time spent in
3533 // epoll_wait() and friends so profiling tools can filter it out. The samples
3534 // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
3535 // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
3536 // probably fortify in the API contract, namely that the last started prepare
3537 // or check watcher runs first. It's not 100% foolproof; if an add-on starts
3538 // a prepare or check watcher after us, any samples attributed to its callback
3539 // will be recorded with state=IDLE.
3540 uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
3541 uv_check_init(env->event_loop(), env->idle_check_handle());
3542 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
3543 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
3545 if (v8_is_profiling) {
3546 StartProfilerIdleNotifier(env);
3549 Local<FunctionTemplate> process_template = FunctionTemplate::New(isolate);
3550 process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3552 Local<Object> process_object = process_template->GetFunction()->NewInstance();
3553 env->set_process_object(process_object);
3555 SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3562 int Start(int argc, char** argv) {
3563 #if !defined(_WIN32)
3564 // Try hard not to lose SIGUSR1 signals during the bootstrap process.
3565 InstallEarlyDebugSignalHandler();
3570 // Hack around with the argv pointer. Used for process.title = "blah".
3571 argv = uv_setup_args(argc, argv);
3573 // This needs to run *before* V8::Initialize(). The const_cast is not
3574 // optional, in case you're wondering.
3576 const char** exec_argv;
3577 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3580 // V8 on Windows doesn't have a good source of entropy. Seed it from
3582 V8::SetEntropySource(crypto::EntropySource);
3588 Locker locker(node_isolate);
3590 CreateEnvironment(node_isolate, argc, argv, exec_argc, exec_argv);
3591 // This Context::Scope is here so EnableDebug() can look up the current
3592 // environment with Environment::GetCurrentChecked().
3593 // TODO(bnoordhuis) Reorder the debugger initialization logic so it can
3596 Context::Scope context_scope(env->context());
3599 more = uv_run(env->event_loop(), UV_RUN_ONCE);
3600 if (more == false) {
3601 EmitBeforeExit(env);
3603 // Emit `beforeExit` if the loop became alive either after emitting
3604 // event, or after running some callbacks.
3605 more = uv_loop_alive(env->event_loop());
3606 if (uv_run(env->event_loop(), UV_RUN_NOWAIT) != 0)
3609 } while (more == true);
3610 code = EmitExit(env);
3618 // Clean up. Not strictly necessary.