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;
98 using v8::FunctionCallbackInfo;
99 using v8::FunctionTemplate;
101 using v8::HandleScope;
102 using v8::HeapStatistics;
110 using v8::ObjectTemplate;
111 using v8::PropertyCallbackInfo;
113 using v8::ThrowException;
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 // Declared in node_internals.h
146 Isolate* node_isolate = NULL;
149 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
151 // Impose an upper limit to avoid out of memory errors that bring down
153 static const size_t kMaxLength = 0x3fffffff;
154 static ArrayBufferAllocator the_singleton;
155 virtual ~ArrayBufferAllocator() {}
156 virtual void* Allocate(size_t length);
157 virtual void* AllocateUninitialized(size_t length);
158 virtual void Free(void* data, size_t length);
160 ArrayBufferAllocator() {}
161 ArrayBufferAllocator(const ArrayBufferAllocator&);
162 void operator=(const ArrayBufferAllocator&);
165 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
168 void* ArrayBufferAllocator::Allocate(size_t length) {
169 if (length > kMaxLength)
171 char* data = new char[length];
172 memset(data, 0, length);
177 void* ArrayBufferAllocator::AllocateUninitialized(size_t length) {
178 if (length > kMaxLength)
180 return new char[length];
184 void ArrayBufferAllocator::Free(void* data, size_t length) {
185 delete[] static_cast<char*>(data);
189 static void CheckImmediate(uv_check_t* handle, int status) {
190 HandleScope scope(node_isolate);
191 Environment* env = Environment::from_immediate_check_handle(handle);
192 Context::Scope context_scope(env->context());
193 MakeCallback(env, env->process_object(), env->immediate_callback_string());
197 static void IdleImmediateDummy(uv_idle_t*, int) {
198 // Do nothing. Only for maintaining event loop.
199 // TODO(bnoordhuis) Maybe make libuv accept NULL idle callbacks.
203 static inline const char *errno_string(int errorno) {
204 #define ERRNO_CASE(e) case e: return #e;
211 ERRNO_CASE(EADDRINUSE);
215 ERRNO_CASE(EADDRNOTAVAIL);
219 ERRNO_CASE(EAFNOSUPPORT);
227 # if EAGAIN != EWOULDBLOCK
228 ERRNO_CASE(EWOULDBLOCK);
233 ERRNO_CASE(EALREADY);
249 ERRNO_CASE(ECANCELED);
257 ERRNO_CASE(ECONNABORTED);
261 ERRNO_CASE(ECONNREFUSED);
265 ERRNO_CASE(ECONNRESET);
273 ERRNO_CASE(EDESTADDRREQ);
297 ERRNO_CASE(EHOSTUNREACH);
309 ERRNO_CASE(EINPROGRESS);
345 ERRNO_CASE(EMSGSIZE);
349 ERRNO_CASE(EMULTIHOP);
353 ERRNO_CASE(ENAMETOOLONG);
357 ERRNO_CASE(ENETDOWN);
361 ERRNO_CASE(ENETRESET);
365 ERRNO_CASE(ENETUNREACH);
397 # if ENOLINK != ENOLCK
411 ERRNO_CASE(ENOPROTOOPT);
431 ERRNO_CASE(ENOTCONN);
439 ERRNO_CASE(ENOTEMPTY);
443 ERRNO_CASE(ENOTSOCK);
450 ERRNO_CASE(EOPNOTSUPP);
464 ERRNO_CASE(EOVERFLOW);
479 #ifdef EPROTONOSUPPORT
480 ERRNO_CASE(EPROTONOSUPPORT);
484 ERRNO_CASE(EPROTOTYPE);
512 ERRNO_CASE(ETIMEDOUT);
527 const char *signo_string(int signo) {
528 #define SIGNO_CASE(e) case e: return #e;
555 # if SIGABRT != SIGIOT
599 SIGNO_CASE(SIGSTKFLT);
616 SIGNO_CASE(SIGBREAK);
640 SIGNO_CASE(SIGVTALRM);
648 SIGNO_CASE(SIGWINCH);
656 # if SIGPOLL != SIGIO
666 # if SIGPWR != SIGLOST
680 Local<Value> ErrnoException(int errorno,
684 Environment* env = Environment::GetCurrent(node_isolate);
687 Local<String> estring = OneByteString(node_isolate, errno_string(errorno));
688 if (msg == NULL || msg[0] == '\0') {
689 msg = strerror(errorno);
691 Local<String> message = OneByteString(node_isolate, msg);
693 Local<String> cons1 =
694 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
695 Local<String> cons2 = String::Concat(cons1, message);
698 Local<String> cons3 =
699 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
700 Local<String> cons4 =
701 String::Concat(cons3, String::NewFromUtf8(node_isolate, path));
702 Local<String> cons5 =
703 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
704 e = Exception::Error(cons5);
706 e = Exception::Error(cons2);
709 Local<Object> obj = e->ToObject();
710 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
711 obj->Set(env->code_string(), estring);
714 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
717 if (syscall != NULL) {
718 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
725 // hack alert! copy of ErrnoException, tuned for uv errors
726 Local<Value> UVException(int errorno,
730 Environment* env = Environment::GetCurrent(node_isolate);
733 msg = uv_strerror(errorno);
735 Local<String> estring = OneByteString(node_isolate, uv_err_name(errorno));
736 Local<String> message = OneByteString(node_isolate, msg);
737 Local<String> cons1 =
738 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
739 Local<String> cons2 = String::Concat(cons1, message);
743 Local<String> path_str;
747 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
748 path_str = String::Concat(FIXED_ONE_BYTE_STRING(node_isolate, "\\\\"),
749 String::NewFromUtf8(node_isolate, path + 8));
750 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
751 path_str = String::NewFromUtf8(node_isolate, path + 4);
753 path_str = String::NewFromUtf8(node_isolate, path);
756 path_str = String::NewFromUtf8(node_isolate, path);
759 Local<String> cons3 =
760 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
761 Local<String> cons4 =
762 String::Concat(cons3, path_str);
763 Local<String> cons5 =
764 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
765 e = Exception::Error(cons5);
767 e = Exception::Error(cons2);
770 Local<Object> obj = e->ToObject();
771 // TODO(piscisaureus) errno should probably go
772 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
773 obj->Set(env->code_string(), estring);
776 obj->Set(env->path_string(), path_str);
779 if (syscall != NULL) {
780 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
788 // Does about the same as strerror(),
789 // but supports all windows error messages
790 static const char *winapi_strerror(const int errorno) {
793 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
794 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
795 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
798 // Remove trailing newlines
799 for (int i = strlen(errmsg) - 1;
800 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
806 // FormatMessage failed
807 return "Unknown error";
812 Local<Value> WinapiErrnoException(int errorno,
816 Environment* env = Environment::GetCurrent(node_isolate);
819 if (!msg || !msg[0]) {
820 msg = winapi_strerror(errorno);
822 Local<String> message = OneByteString(node_isolate, msg);
825 Local<String> cons1 =
826 String::Concat(message, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
827 Local<String> cons2 =
828 String::Concat(cons1, String::NewFromUtf8(node_isolate, path));
829 Local<String> cons3 =
830 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
831 e = Exception::Error(cons3);
833 e = Exception::Error(message);
836 Local<Object> obj = e->ToObject();
837 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
840 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
843 if (syscall != NULL) {
844 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
852 void SetupAsyncListener(const FunctionCallbackInfo<Value>& args) {
853 HandleScope handle_scope(args.GetIsolate());
854 Environment* env = Environment::GetCurrent(args.GetIsolate());
856 assert(args[0]->IsObject());
857 assert(args[1]->IsFunction());
858 assert(args[2]->IsFunction());
859 assert(args[3]->IsFunction());
861 env->set_async_listener_run_function(args[1].As<Function>());
862 env->set_async_listener_load_function(args[2].As<Function>());
863 env->set_async_listener_unload_function(args[3].As<Function>());
865 Local<Object> async_listener_flag_obj = args[0].As<Object>();
866 Environment::AsyncListener* async_listener = env->async_listener();
867 async_listener_flag_obj->SetIndexedPropertiesToExternalArrayData(
868 async_listener->fields(),
869 kExternalUnsignedIntArray,
870 async_listener->fields_count());
872 // Do a little housekeeping.
873 env->process_object()->Delete(
874 FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupAsyncListener"));
878 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
879 Environment* env = Environment::GetCurrent(args.GetIsolate());
881 if (env->using_domains())
883 env->set_using_domains(true);
885 HandleScope scope(node_isolate);
886 Local<Object> process_object = env->process_object();
888 Local<String> tick_callback_function_key =
889 FIXED_ONE_BYTE_STRING(node_isolate, "_tickDomainCallback");
890 Local<Function> tick_callback_function =
891 process_object->Get(tick_callback_function_key).As<Function>();
893 if (!tick_callback_function->IsFunction()) {
894 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
898 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"),
899 tick_callback_function);
900 env->set_tick_callback_function(tick_callback_function);
902 assert(args[0]->IsArray());
903 assert(args[1]->IsObject());
905 env->set_domain_array(args[0].As<Array>());
907 Local<Object> domain_flag_obj = args[1].As<Object>();
908 Environment::DomainFlag* domain_flag = env->domain_flag();
909 domain_flag_obj->SetIndexedPropertiesToExternalArrayData(
910 domain_flag->fields(),
911 kExternalUnsignedIntArray,
912 domain_flag->fields_count());
914 // Do a little housekeeping.
915 env->process_object()->Delete(
916 FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupDomainUse"));
920 void SetupNextTick(const FunctionCallbackInfo<Value>& args) {
921 HandleScope handle_scope(args.GetIsolate());
922 Environment* env = Environment::GetCurrent(args.GetIsolate());
924 assert(args[0]->IsObject());
925 assert(args[1]->IsFunction());
927 // Values use to cross communicate with processNextTick.
928 Local<Object> tick_info_obj = args[0].As<Object>();
929 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
930 env->tick_info()->fields(),
931 kExternalUnsignedIntArray,
932 env->tick_info()->fields_count());
934 env->set_tick_callback_function(args[1].As<Function>());
936 // Do a little housekeeping.
937 env->process_object()->Delete(
938 FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupNextTick"));
942 Handle<Value> MakeDomainCallback(Environment* env,
944 const Handle<Function> callback,
946 Handle<Value> argv[]) {
947 // If you hit this assertion, you forgot to enter the v8::Context first.
948 assert(env->context() == env->isolate()->GetCurrentContext());
950 Local<Object> process = env->process_object();
951 Local<Object> object, domain;
952 Local<Value> domain_v;
955 try_catch.SetVerbose(true);
957 bool has_async_queue = false;
959 if (recv->IsObject()) {
960 object = recv.As<Object>();
961 // TODO(trevnorris): This is sucky for performance. Fix it.
962 has_async_queue = object->Has(env->async_queue_string());
963 if (has_async_queue) {
964 env->async_listener_load_function()->Call(process, 1, &recv);
966 if (try_catch.HasCaught())
967 return Undefined(node_isolate);
971 bool has_domain = false;
973 if (!object.IsEmpty()) {
974 domain_v = object->Get(env->domain_string());
975 has_domain = domain_v->IsObject();
977 domain = domain_v.As<Object>();
979 if (domain->Get(env->disposed_string())->IsTrue()) {
980 // domain has been disposed of.
981 return Undefined(node_isolate);
984 Local<Function> enter =
985 domain->Get(env->enter_string()).As<Function>();
986 assert(enter->IsFunction());
987 enter->Call(domain, 0, NULL);
989 if (try_catch.HasCaught()) {
990 return Undefined(node_isolate);
995 Local<Value> ret = callback->Call(recv, argc, argv);
997 if (try_catch.HasCaught()) {
998 return Undefined(node_isolate);
1002 Local<Function> exit =
1003 domain->Get(env->exit_string()).As<Function>();
1004 assert(exit->IsFunction());
1005 exit->Call(domain, 0, NULL);
1007 if (try_catch.HasCaught()) {
1008 return Undefined(node_isolate);
1012 if (has_async_queue) {
1013 env->async_listener_unload_function()->Call(process, 1, &recv);
1015 if (try_catch.HasCaught())
1016 return Undefined(node_isolate);
1019 Environment::TickInfo* tick_info = env->tick_info();
1021 if (tick_info->last_threw() == 1) {
1022 tick_info->set_last_threw(0);
1026 if (tick_info->in_tick()) {
1030 if (tick_info->length() == 0) {
1031 tick_info->set_index(0);
1035 tick_info->set_in_tick(true);
1037 env->tick_callback_function()->Call(process, 0, NULL);
1039 tick_info->set_in_tick(false);
1041 if (try_catch.HasCaught()) {
1042 tick_info->set_last_threw(true);
1043 return Undefined(node_isolate);
1050 Handle<Value> MakeCallback(Environment* env,
1052 const Handle<Function> callback,
1054 Handle<Value> argv[]) {
1055 if (env->using_domains())
1056 return MakeDomainCallback(env, recv, callback, argc, argv);
1058 // If you hit this assertion, you forgot to enter the v8::Context first.
1059 assert(env->context() == env->isolate()->GetCurrentContext());
1061 Local<Object> process = env->process_object();
1064 try_catch.SetVerbose(true);
1066 // TODO(trevnorris): This is sucky for performance. Fix it.
1067 bool has_async_queue =
1068 recv->IsObject() && recv.As<Object>()->Has(env->async_queue_string());
1069 if (has_async_queue) {
1070 env->async_listener_load_function()->Call(process, 1, &recv);
1071 if (try_catch.HasCaught())
1072 return Undefined(node_isolate);
1075 Local<Value> ret = callback->Call(recv, argc, argv);
1077 if (try_catch.HasCaught()) {
1078 return Undefined(node_isolate);
1081 if (has_async_queue) {
1082 env->async_listener_unload_function()->Call(process, 1, &recv);
1084 if (try_catch.HasCaught())
1085 return Undefined(node_isolate);
1088 Environment::TickInfo* tick_info = env->tick_info();
1090 if (tick_info->in_tick()) {
1094 if (tick_info->length() == 0) {
1095 tick_info->set_index(0);
1099 tick_info->set_in_tick(true);
1101 // process nextTicks after call
1102 env->tick_callback_function()->Call(process, 0, NULL);
1104 tick_info->set_in_tick(false);
1106 if (try_catch.HasCaught()) {
1107 tick_info->set_last_threw(true);
1108 return Undefined(node_isolate);
1116 Handle<Value> MakeCallback(Environment* env,
1117 Handle<Object> recv,
1120 Handle<Value> argv[]) {
1121 Local<Function> callback = recv->Get(index).As<Function>();
1122 assert(callback->IsFunction());
1124 return MakeCallback(env, recv.As<Value>(), callback, argc, argv);
1128 Handle<Value> MakeCallback(Environment* env,
1129 Handle<Object> recv,
1130 Handle<String> symbol,
1132 Handle<Value> argv[]) {
1133 Local<Function> callback = recv->Get(symbol).As<Function>();
1134 assert(callback->IsFunction());
1135 return MakeCallback(env, recv.As<Value>(), callback, argc, argv);
1139 Handle<Value> MakeCallback(Environment* env,
1140 Handle<Object> recv,
1143 Handle<Value> argv[]) {
1144 Local<String> method_string = OneByteString(node_isolate, method);
1145 return MakeCallback(env, recv, method_string, argc, argv);
1149 Handle<Value> MakeCallback(Handle<Object> recv,
1152 Handle<Value> argv[]) {
1153 Local<Context> context = recv->CreationContext();
1154 Environment* env = Environment::GetCurrent(context);
1155 Context::Scope context_scope(context);
1156 HandleScope handle_scope(env->isolate());
1157 return handle_scope.Close(MakeCallback(env, recv, method, argc, argv));
1161 Handle<Value> MakeCallback(Handle<Object> recv,
1162 Handle<String> symbol,
1164 Handle<Value> argv[]) {
1165 Local<Context> context = recv->CreationContext();
1166 Environment* env = Environment::GetCurrent(context);
1167 Context::Scope context_scope(context);
1168 HandleScope handle_scope(env->isolate());
1169 return handle_scope.Close(MakeCallback(env, recv, symbol, argc, argv));
1173 Handle<Value> MakeCallback(Handle<Object> recv,
1174 Handle<Function> callback,
1176 Handle<Value> argv[]) {
1177 Local<Context> context = recv->CreationContext();
1178 Environment* env = Environment::GetCurrent(context);
1179 Context::Scope context_scope(context);
1180 HandleScope handle_scope(env->isolate());
1181 return handle_scope.Close(
1182 MakeCallback(env, recv.As<Value>(), callback, argc, argv));
1186 Handle<Value> MakeDomainCallback(Handle<Object> recv,
1187 Handle<Function> callback,
1189 Handle<Value> argv[]) {
1190 Local<Context> context = recv->CreationContext();
1191 Environment* env = Environment::GetCurrent(context);
1192 Context::Scope context_scope(context);
1193 HandleScope handle_scope(env->isolate());
1194 return handle_scope.Close(
1195 MakeDomainCallback(env, recv, callback, argc, argv));
1199 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1200 HandleScope scope(node_isolate);
1202 if (!encoding_v->IsString())
1205 String::Utf8Value encoding(encoding_v);
1207 if (strcasecmp(*encoding, "utf8") == 0) {
1209 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1211 } else if (strcasecmp(*encoding, "ascii") == 0) {
1213 } else if (strcasecmp(*encoding, "base64") == 0) {
1215 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1217 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1219 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1221 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1223 } else if (strcasecmp(*encoding, "binary") == 0) {
1225 } else if (strcasecmp(*encoding, "buffer") == 0) {
1227 } else if (strcasecmp(*encoding, "hex") == 0) {
1229 } else if (strcasecmp(*encoding, "raw") == 0) {
1230 if (!no_deprecation) {
1231 fprintf(stderr, "'raw' (array of integers) has been removed. "
1235 } else if (strcasecmp(*encoding, "raws") == 0) {
1236 if (!no_deprecation) {
1237 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1238 "Please update your code.\n");
1246 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1247 return StringBytes::Encode(static_cast<const char*>(buf),
1252 // Returns -1 if the handle was not valid for decoding
1253 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1254 HandleScope scope(node_isolate);
1256 if (val->IsArray()) {
1257 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1263 return StringBytes::Size(val, encoding);
1267 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1270 // Returns number of bytes written.
1271 ssize_t DecodeWrite(char *buf,
1273 v8::Handle<v8::Value> val,
1274 enum encoding encoding) {
1275 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1278 void DisplayExceptionLine(Handle<Message> message) {
1279 // Prevent re-entry into this function. For example, if there is
1280 // a throw from a program in vm.runInThisContext(code, filename, true),
1281 // then we want to show the original failure, not the secondary one.
1282 static bool displayed_error = false;
1284 if (displayed_error)
1286 displayed_error = true;
1288 uv_tty_reset_mode();
1290 fprintf(stderr, "\n");
1292 if (!message.IsEmpty()) {
1293 // Print (filename):(line number): (message).
1294 String::Utf8Value filename(message->GetScriptResourceName());
1295 const char* filename_string = *filename;
1296 int linenum = message->GetLineNumber();
1297 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1298 // Print line of source code.
1299 String::Utf8Value sourceline(message->GetSourceLine());
1300 const char* sourceline_string = *sourceline;
1302 // Because of how node modules work, all scripts are wrapped with a
1303 // "function (module, exports, __filename, ...) {"
1304 // to provide script local variables.
1306 // When reporting errors on the first line of a script, this wrapper
1307 // function is leaked to the user. There used to be a hack here to
1308 // truncate off the first 62 characters, but it caused numerous other
1309 // problems when vm.runIn*Context() methods were used for non-module
1312 // If we ever decide to re-instate such a hack, the following steps
1315 // 1. Pass a flag around to say "this code was wrapped"
1316 // 2. Update the stack frame output so that it is also correct.
1318 // It would probably be simpler to add a line rather than add some
1319 // number of characters to the first line, since V8 truncates the
1320 // sourceline to 78 characters, and we end up not providing very much
1321 // useful debugging info to the user if we remove 62 characters.
1323 int start = message->GetStartColumn();
1324 int end = message->GetEndColumn();
1326 fprintf(stderr, "%s\n", sourceline_string);
1327 // Print wavy underline (GetUnderline is deprecated).
1328 for (int i = 0; i < start; i++) {
1329 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1331 for (int i = start; i < end; i++) {
1334 fputc('\n', stderr);
1339 static void ReportException(Handle<Value> er, Handle<Message> message) {
1340 HandleScope scope(node_isolate);
1342 DisplayExceptionLine(message);
1344 Local<Value> trace_value;
1346 if (er->IsUndefined() || er->IsNull()) {
1347 trace_value = Undefined(node_isolate);
1350 er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack"));
1353 String::Utf8Value trace(trace_value);
1355 // range errors have a trace member set to undefined
1356 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1357 fprintf(stderr, "%s\n", *trace);
1359 // this really only happens for RangeErrors, since they're the only
1360 // kind that won't have all this info in the trace, or when non-Error
1361 // objects are thrown manually.
1362 Local<Value> message;
1365 if (er->IsObject()) {
1366 Local<Object> err_obj = er.As<Object>();
1367 message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1368 name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1371 if (message.IsEmpty() ||
1372 message->IsUndefined() ||
1374 name->IsUndefined()) {
1375 // Not an error object. Just print as-is.
1376 String::Utf8Value message(er);
1377 fprintf(stderr, "%s\n", *message);
1379 String::Utf8Value name_string(name);
1380 String::Utf8Value message_string(message);
1381 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1389 static void ReportException(const TryCatch& try_catch) {
1390 ReportException(try_catch.Exception(), try_catch.Message());
1394 // Executes a str within the current v8 context.
1395 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1396 HandleScope scope(node_isolate);
1399 // try_catch must be nonverbose to disable FatalException() handler,
1400 // we will handle exceptions ourself.
1401 try_catch.SetVerbose(false);
1403 Local<v8::Script> script = v8::Script::Compile(source, filename);
1404 if (script.IsEmpty()) {
1405 ReportException(try_catch);
1409 Local<Value> result = script->Run();
1410 if (result.IsEmpty()) {
1411 ReportException(try_catch);
1415 return scope.Close(result);
1419 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1420 HandleScope scope(node_isolate);
1422 Local<Array> ary = Array::New();
1426 QUEUE_FOREACH(q, &req_wrap_queue) {
1427 ReqWrap<uv_req_t>* w = CONTAINER_OF(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1428 if (w->persistent().IsEmpty())
1430 ary->Set(i++, w->object());
1433 args.GetReturnValue().Set(ary);
1437 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1438 // implemented here for consistency with GetActiveRequests().
1439 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1440 HandleScope scope(node_isolate);
1442 Local<Array> ary = Array::New();
1446 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1448 QUEUE_FOREACH(q, &handle_wrap_queue) {
1449 HandleWrap* w = CONTAINER_OF(q, HandleWrap, handle_wrap_queue_);
1450 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref))
1452 Local<Object> object = w->object();
1453 Local<Value> owner = object->Get(owner_sym);
1454 if (owner->IsUndefined())
1456 ary->Set(i++, owner);
1459 args.GetReturnValue().Set(ary);
1463 static void Abort(const FunctionCallbackInfo<Value>& args) {
1468 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1469 HandleScope scope(node_isolate);
1471 if (args.Length() != 1 || !args[0]->IsString()) {
1472 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1475 String::Utf8Value path(args[0]);
1476 int err = uv_chdir(*path);
1478 return ThrowUVException(err, "uv_chdir");
1483 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1484 HandleScope scope(node_isolate);
1486 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1487 char buf[MAX_PATH * 4 + 1];
1489 char buf[PATH_MAX + 1];
1492 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1494 return ThrowUVException(err, "uv_cwd");
1497 buf[ARRAY_SIZE(buf) - 1] = '\0';
1498 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1500 args.GetReturnValue().Set(cwd);
1504 static void Umask(const FunctionCallbackInfo<Value>& args) {
1505 HandleScope scope(node_isolate);
1508 if (args.Length() < 1 || args[0]->IsUndefined()) {
1510 umask(static_cast<mode_t>(old));
1511 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1512 return ThrowTypeError("argument must be an integer or octal string.");
1515 if (args[0]->IsInt32()) {
1516 oct = args[0]->Uint32Value();
1519 String::Utf8Value str(args[0]);
1521 // Parse the octal string.
1522 for (int i = 0; i < str.length(); i++) {
1524 if (c > '7' || c < '0') {
1525 return ThrowTypeError("invalid octal string");
1531 old = umask(static_cast<mode_t>(oct));
1534 args.GetReturnValue().Set(old);
1538 #if defined(__POSIX__) && !defined(__ANDROID__)
1540 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1541 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1544 static uid_t uid_by_name(const char* name) {
1552 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1556 return uid_not_found;
1560 static char* name_by_uid(uid_t uid) {
1569 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1570 return strdup(pp->pw_name);
1581 static gid_t gid_by_name(const char* name) {
1589 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1593 return gid_not_found;
1597 #if 0 // For future use.
1598 static const char* name_by_gid(gid_t gid) {
1607 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1608 return strdup(pp->gr_name);
1620 static uid_t uid_by_name(Handle<Value> value) {
1621 if (value->IsUint32()) {
1622 return static_cast<uid_t>(value->Uint32Value());
1624 String::Utf8Value name(value);
1625 return uid_by_name(*name);
1630 static gid_t gid_by_name(Handle<Value> value) {
1631 if (value->IsUint32()) {
1632 return static_cast<gid_t>(value->Uint32Value());
1634 String::Utf8Value name(value);
1635 return gid_by_name(*name);
1640 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1641 // uid_t is an uint32_t on all supported platforms.
1642 args.GetReturnValue().Set(static_cast<uint32_t>(getuid()));
1646 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1647 // gid_t is an uint32_t on all supported platforms.
1648 args.GetReturnValue().Set(static_cast<uint32_t>(getgid()));
1652 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1653 HandleScope scope(node_isolate);
1655 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1656 return ThrowTypeError("setgid argument must be a number or a string");
1659 gid_t gid = gid_by_name(args[0]);
1661 if (gid == gid_not_found) {
1662 return ThrowError("setgid group id does not exist");
1666 return ThrowErrnoException(errno, "setgid");
1671 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1672 HandleScope scope(node_isolate);
1674 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1675 return ThrowTypeError("setuid argument must be a number or a string");
1678 uid_t uid = uid_by_name(args[0]);
1680 if (uid == uid_not_found) {
1681 return ThrowError("setuid user id does not exist");
1685 return ThrowErrnoException(errno, "setuid");
1690 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1691 HandleScope scope(node_isolate);
1693 int ngroups = getgroups(0, NULL);
1695 if (ngroups == -1) {
1696 return ThrowErrnoException(errno, "getgroups");
1699 gid_t* groups = new gid_t[ngroups];
1701 ngroups = getgroups(ngroups, groups);
1703 if (ngroups == -1) {
1705 return ThrowErrnoException(errno, "getgroups");
1708 Local<Array> groups_list = Array::New(ngroups);
1709 bool seen_egid = false;
1710 gid_t egid = getegid();
1712 for (int i = 0; i < ngroups; i++) {
1713 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1714 if (groups[i] == egid)
1720 if (seen_egid == false) {
1721 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1724 args.GetReturnValue().Set(groups_list);
1728 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1729 HandleScope scope(node_isolate);
1731 if (!args[0]->IsArray()) {
1732 return ThrowTypeError("argument 1 must be an array");
1735 Local<Array> groups_list = args[0].As<Array>();
1736 size_t size = groups_list->Length();
1737 gid_t* groups = new gid_t[size];
1739 for (size_t i = 0; i < size; i++) {
1740 gid_t gid = gid_by_name(groups_list->Get(i));
1742 if (gid == gid_not_found) {
1744 return ThrowError("group name not found");
1750 int rc = setgroups(size, groups);
1754 return ThrowErrnoException(errno, "setgroups");
1759 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1760 HandleScope scope(node_isolate);
1762 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1763 return ThrowTypeError("argument 1 must be a number or a string");
1766 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1767 return ThrowTypeError("argument 2 must be a number or a string");
1770 String::Utf8Value arg0(args[0]);
1775 if (args[0]->IsUint32()) {
1776 user = name_by_uid(args[0]->Uint32Value());
1784 return ThrowError("initgroups user not found");
1787 extra_group = gid_by_name(args[1]);
1789 if (extra_group == gid_not_found) {
1792 return ThrowError("initgroups extra group not found");
1795 int rc = initgroups(user, extra_group);
1802 return ThrowErrnoException(errno, "initgroups");
1806 #endif // __POSIX__ && !defined(__ANDROID__)
1809 void Exit(const FunctionCallbackInfo<Value>& args) {
1810 HandleScope scope(node_isolate);
1811 exit(args[0]->IntegerValue());
1815 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1816 HandleScope scope(node_isolate);
1818 if (uv_uptime(&uptime))
1820 args.GetReturnValue().Set(uptime - prog_start_time);
1824 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1825 HandleScope handle_scope(args.GetIsolate());
1826 Environment* env = Environment::GetCurrent(args.GetIsolate());
1829 int err = uv_resident_set_memory(&rss);
1831 return ThrowUVException(err, "uv_resident_set_memory");
1835 HeapStatistics v8_heap_stats;
1836 node_isolate->GetHeapStatistics(&v8_heap_stats);
1838 Local<Integer> heap_total =
1839 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(), node_isolate);
1840 Local<Integer> heap_used =
1841 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(), node_isolate);
1843 Local<Object> info = Object::New();
1844 info->Set(env->rss_string(), Number::New(node_isolate, rss));
1845 info->Set(env->heap_total_string(), heap_total);
1846 info->Set(env->heap_used_string(), heap_used);
1848 args.GetReturnValue().Set(info);
1852 void Kill(const FunctionCallbackInfo<Value>& args) {
1853 HandleScope scope(node_isolate);
1855 if (args.Length() != 2) {
1856 return ThrowError("Bad argument.");
1859 int pid = args[0]->IntegerValue();
1860 int sig = args[1]->Int32Value();
1861 int err = uv_kill(pid, sig);
1862 args.GetReturnValue().Set(err);
1865 // used in Hrtime() below
1866 #define NANOS_PER_SEC 1000000000
1868 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1869 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1870 // so this function instead returns an Array with 2 entries representing seconds
1871 // and nanoseconds, to avoid any integer overflow possibility.
1872 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1873 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1874 HandleScope scope(node_isolate);
1876 uint64_t t = uv_hrtime();
1878 if (args.Length() > 0) {
1879 // return a time diff tuple
1880 if (!args[0]->IsArray()) {
1881 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1883 Local<Array> inArray = Local<Array>::Cast(args[0]);
1884 uint64_t seconds = inArray->Get(0)->Uint32Value();
1885 uint64_t nanos = inArray->Get(1)->Uint32Value();
1886 t -= (seconds * NANOS_PER_SEC) + nanos;
1889 Local<Array> tuple = Array::New(2);
1890 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1891 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1892 args.GetReturnValue().Set(tuple);
1895 extern "C" void node_module_register(void* m) {
1896 struct node_module* mp = reinterpret_cast<struct node_module*>(m);
1898 if (mp->nm_flags & NM_F_BUILTIN) {
1899 mp->nm_link = modlist_builtin;
1900 modlist_builtin = mp;
1902 assert(modpending == NULL);
1907 struct node_module* get_builtin_module(const char* name) {
1908 struct node_module* mp;
1910 for (mp = modlist_builtin; mp != NULL; mp = mp->nm_link) {
1911 if (strcmp(mp->nm_modname, name) == 0)
1915 assert(mp == NULL || (mp->nm_flags & NM_F_BUILTIN) != 0);
1919 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1921 // DLOpen is process.dlopen(module, filename).
1922 // Used to load 'module.node' dynamically shared objects.
1924 // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
1925 // when two contexts try to load the same shared object. Maybe have a shadow
1926 // cache that's a plain C list or hash table that's shared across contexts?
1927 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1928 HandleScope handle_scope(args.GetIsolate());
1929 Environment* env = Environment::GetCurrent(args.GetIsolate());
1930 struct node_module* mp;
1933 if (args.Length() < 2) {
1934 ThrowError("process.dlopen takes exactly 2 arguments.");
1938 Local<Object> module = args[0]->ToObject(); // Cast
1939 String::Utf8Value filename(args[1]); // Cast
1941 Local<String> exports_string = env->exports_string();
1942 Local<Object> exports = module->Get(exports_string)->ToObject();
1944 if (uv_dlopen(*filename, &lib)) {
1945 Local<String> errmsg = OneByteString(env->isolate(), uv_dlerror(&lib));
1947 // Windows needs to add the filename into the error message
1948 errmsg = String::Concat(errmsg, args[1]->ToString());
1950 ThrowException(Exception::Error(errmsg));
1955 * Objects containing v14 or later modules will have registered themselves
1956 * on the pending list. Activate all of them now. At present, only one
1957 * module per object is supported.
1963 ThrowError("Module did not self-register.");
1966 if (mp->nm_version != NODE_MODULE_VERSION) {
1970 "Module version mismatch. Expected %d, got %d.",
1971 NODE_MODULE_VERSION, mp->nm_version);
1975 if (mp->nm_flags & NM_F_BUILTIN) {
1976 ThrowError("Built-in module self-registered.");
1980 mp->nm_dso_handle = lib.handle;
1981 mp->nm_link = modlist_addon;
1984 if (mp->nm_context_register_func != NULL) {
1985 mp->nm_context_register_func(exports, module, env->context(), mp->nm_priv);
1986 } else if (mp->nm_register_func != NULL) {
1987 mp->nm_register_func(exports, module, mp->nm_priv);
1989 ThrowError("Module has no declared entry point.");
1993 // Tell coverity that 'handle' should not be freed when we return.
1994 // coverity[leaked_storage]
1998 static void OnFatalError(const char* location, const char* message) {
2000 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
2002 fprintf(stderr, "FATAL ERROR: %s\n", message);
2009 NO_RETURN void FatalError(const char* location, const char* message) {
2010 OnFatalError(location, message);
2011 // to supress compiler warning
2016 void FatalException(Handle<Value> error, Handle<Message> message) {
2017 HandleScope scope(node_isolate);
2019 Environment* env = Environment::GetCurrent(node_isolate);
2020 Local<Object> process_object = env->process_object();
2021 Local<String> fatal_exception_string = env->fatal_exception_string();
2022 Local<Function> fatal_exception_function =
2023 process_object->Get(fatal_exception_string).As<Function>();
2025 if (!fatal_exception_function->IsFunction()) {
2026 // failed before the process._fatalException function was added!
2027 // this is probably pretty bad. Nothing to do but report and exit.
2028 ReportException(error, message);
2032 TryCatch fatal_try_catch;
2034 // Do not call FatalException when _fatalException handler throws
2035 fatal_try_catch.SetVerbose(false);
2037 // this will return true if the JS layer handled it, false otherwise
2038 Local<Value> caught =
2039 fatal_exception_function->Call(process_object, 1, &error);
2041 if (fatal_try_catch.HasCaught()) {
2042 // the fatal exception function threw, so we must exit
2043 ReportException(fatal_try_catch);
2047 if (false == caught->BooleanValue()) {
2048 ReportException(error, message);
2054 void FatalException(const TryCatch& try_catch) {
2055 HandleScope scope(node_isolate);
2056 // TODO(bajtos) do not call FatalException if try_catch is verbose
2057 // (requires V8 API to expose getter for try_catch.is_verbose_)
2058 FatalException(try_catch.Exception(), try_catch.Message());
2062 void OnMessage(Handle<Message> message, Handle<Value> error) {
2063 // The current version of V8 sends messages for errors only
2064 // (thus `error` is always set).
2065 FatalException(error, message);
2069 static void Binding(const FunctionCallbackInfo<Value>& args) {
2070 HandleScope handle_scope(args.GetIsolate());
2071 Environment* env = Environment::GetCurrent(args.GetIsolate());
2073 Local<String> module = args[0]->ToString();
2074 String::Utf8Value module_v(module);
2076 Local<Object> cache = env->binding_cache_object();
2077 Local<Object> exports;
2079 if (cache->Has(module)) {
2080 exports = cache->Get(module)->ToObject();
2081 args.GetReturnValue().Set(exports);
2085 // Append a string to process.moduleLoadList
2087 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
2089 Local<Array> modules = env->module_load_list_array();
2090 uint32_t l = modules->Length();
2091 modules->Set(l, OneByteString(node_isolate, buf));
2093 node_module* mod = get_builtin_module(*module_v);
2095 exports = Object::New();
2096 // Internal bindings don't have a "module" object, only exports.
2097 assert(mod->nm_register_func == NULL);
2098 assert(mod->nm_context_register_func != NULL);
2099 Local<Value> unused = Undefined(env->isolate());
2100 mod->nm_context_register_func(exports, unused,
2101 env->context(), mod->nm_priv);
2102 cache->Set(module, exports);
2103 } else if (!strcmp(*module_v, "constants")) {
2104 exports = Object::New();
2105 DefineConstants(exports);
2106 cache->Set(module, exports);
2107 } else if (!strcmp(*module_v, "natives")) {
2108 exports = Object::New();
2109 DefineJavaScript(exports);
2110 cache->Set(module, exports);
2112 return ThrowError("No such module");
2115 args.GetReturnValue().Set(exports);
2119 static void ProcessTitleGetter(Local<String> property,
2120 const PropertyCallbackInfo<Value>& info) {
2121 HandleScope scope(node_isolate);
2123 uv_get_process_title(buffer, sizeof(buffer));
2124 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2128 static void ProcessTitleSetter(Local<String> property,
2130 const PropertyCallbackInfo<void>& info) {
2131 HandleScope scope(node_isolate);
2132 String::Utf8Value title(value);
2133 // TODO(piscisaureus): protect with a lock
2134 uv_set_process_title(*title);
2138 static void EnvGetter(Local<String> property,
2139 const PropertyCallbackInfo<Value>& info) {
2140 HandleScope scope(node_isolate);
2142 String::Utf8Value key(property);
2143 const char* val = getenv(*key);
2145 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2148 String::Value key(property);
2149 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2150 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2152 ARRAY_SIZE(buffer));
2153 // If result >= sizeof buffer the buffer was too small. That should never
2154 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2156 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2157 result < ARRAY_SIZE(buffer)) {
2158 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2159 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2160 return info.GetReturnValue().Set(rc);
2163 // Not found. Fetch from prototype.
2164 info.GetReturnValue().Set(
2165 info.Data().As<Object>()->Get(property));
2169 static void EnvSetter(Local<String> property,
2171 const PropertyCallbackInfo<Value>& info) {
2172 HandleScope scope(node_isolate);
2174 String::Utf8Value key(property);
2175 String::Utf8Value val(value);
2176 setenv(*key, *val, 1);
2178 String::Value key(property);
2179 String::Value val(value);
2180 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2181 // Environment variables that start with '=' are read-only.
2182 if (key_ptr[0] != L'=') {
2183 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2186 // Whether it worked or not, always return rval.
2187 info.GetReturnValue().Set(value);
2191 static void EnvQuery(Local<String> property,
2192 const PropertyCallbackInfo<Integer>& info) {
2193 HandleScope scope(node_isolate);
2194 int32_t rc = -1; // Not found unless proven otherwise.
2196 String::Utf8Value key(property);
2200 String::Value key(property);
2201 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2202 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2203 GetLastError() == ERROR_SUCCESS) {
2205 if (key_ptr[0] == L'=') {
2206 // Environment variables that start with '=' are hidden and read-only.
2207 rc = static_cast<int32_t>(v8::ReadOnly) |
2208 static_cast<int32_t>(v8::DontDelete) |
2209 static_cast<int32_t>(v8::DontEnum);
2214 info.GetReturnValue().Set(rc);
2218 static void EnvDeleter(Local<String> property,
2219 const PropertyCallbackInfo<Boolean>& info) {
2220 HandleScope scope(node_isolate);
2223 String::Utf8Value key(property);
2224 rc = getenv(*key) != NULL;
2228 String::Value key(property);
2229 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2230 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2231 // Deletion failed. Return true if the key wasn't there in the first place,
2232 // false if it is still there.
2233 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2234 GetLastError() != ERROR_SUCCESS;
2237 info.GetReturnValue().Set(rc);
2241 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2242 HandleScope scope(node_isolate);
2245 while (environ[size])
2248 Local<Array> env = Array::New(size);
2250 for (int i = 0; i < size; ++i) {
2251 const char* var = environ[i];
2252 const char* s = strchr(var, '=');
2253 const int length = s ? s - var : strlen(var);
2254 Local<String> name = String::NewFromUtf8(node_isolate,
2256 String::kNormalString,
2261 WCHAR* environment = GetEnvironmentStringsW();
2262 if (environment == NULL)
2263 return; // This should not happen.
2264 Local<Array> env = Array::New();
2265 WCHAR* p = environment;
2267 while (*p != NULL) {
2270 // If the key starts with '=' it is a hidden environment variable.
2274 s = wcschr(p, L'=');
2279 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2280 const size_t two_byte_buffer_len = s - p;
2281 Local<String> value = String::NewFromTwoByte(node_isolate,
2283 String::kNormalString,
2284 two_byte_buffer_len);
2285 env->Set(i++, value);
2286 p = s + wcslen(s) + 1;
2288 FreeEnvironmentStringsW(environment);
2291 info.GetReturnValue().Set(env);
2295 static Handle<Object> GetFeatures() {
2296 HandleScope scope(node_isolate);
2298 Local<Object> obj = Object::New();
2299 #if defined(DEBUG) && DEBUG
2300 Local<Value> debug = True(node_isolate);
2302 Local<Value> debug = False(node_isolate);
2303 #endif // defined(DEBUG) && DEBUG
2305 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2307 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2308 // TODO(bnoordhuis) ping libuv
2309 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2311 #ifdef OPENSSL_NPN_NEGOTIATED
2312 Local<Boolean> tls_npn = True(node_isolate);
2314 Local<Boolean> tls_npn = False(node_isolate);
2316 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"), tls_npn);
2318 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2319 Local<Boolean> tls_sni = True(node_isolate);
2321 Local<Boolean> tls_sni = False(node_isolate);
2323 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"), tls_sni);
2325 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2326 Boolean::New(get_builtin_module("crypto") != NULL));
2328 return scope.Close(obj);
2332 static void DebugPortGetter(Local<String> property,
2333 const PropertyCallbackInfo<Value>& info) {
2334 HandleScope scope(node_isolate);
2335 info.GetReturnValue().Set(debug_port);
2339 static void DebugPortSetter(Local<String> property,
2341 const PropertyCallbackInfo<void>& info) {
2342 HandleScope scope(node_isolate);
2343 debug_port = value->NumberValue();
2347 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2348 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2349 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2352 void NeedImmediateCallbackGetter(Local<String> property,
2353 const PropertyCallbackInfo<Value>& info) {
2354 HandleScope handle_scope(info.GetIsolate());
2355 Environment* env = Environment::GetCurrent(info.GetIsolate());
2356 const uv_check_t* immediate_check_handle = env->immediate_check_handle();
2357 bool active = uv_is_active(
2358 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2359 info.GetReturnValue().Set(active);
2363 static void NeedImmediateCallbackSetter(
2364 Local<String> property,
2366 const PropertyCallbackInfo<void>& info) {
2367 HandleScope handle_scope(info.GetIsolate());
2368 Environment* env = Environment::GetCurrent(info.GetIsolate());
2370 uv_check_t* immediate_check_handle = env->immediate_check_handle();
2371 bool active = uv_is_active(
2372 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2374 if (active == value->BooleanValue())
2377 uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
2380 uv_check_stop(immediate_check_handle);
2381 uv_idle_stop(immediate_idle_handle);
2383 uv_check_start(immediate_check_handle, CheckImmediate);
2384 // Idle handle is needed only to stop the event loop from blocking in poll.
2385 uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
2390 void SetIdle(uv_prepare_t* handle, int) {
2391 Environment* env = Environment::from_idle_prepare_handle(handle);
2392 env->isolate()->GetCpuProfiler()->SetIdle(true);
2396 void ClearIdle(uv_check_t* handle, int) {
2397 Environment* env = Environment::from_idle_check_handle(handle);
2398 env->isolate()->GetCpuProfiler()->SetIdle(false);
2402 void StartProfilerIdleNotifier(Environment* env) {
2403 uv_prepare_start(env->idle_prepare_handle(), SetIdle);
2404 uv_check_start(env->idle_check_handle(), ClearIdle);
2408 void StopProfilerIdleNotifier(Environment* env) {
2409 uv_prepare_stop(env->idle_prepare_handle());
2410 uv_check_stop(env->idle_check_handle());
2414 void StartProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2415 HandleScope handle_scope(args.GetIsolate());
2416 Environment* env = Environment::GetCurrent(args.GetIsolate());
2417 StartProfilerIdleNotifier(env);
2421 void StopProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2422 HandleScope handle_scope(args.GetIsolate());
2423 Environment* env = Environment::GetCurrent(args.GetIsolate());
2424 StopProfilerIdleNotifier(env);
2428 #define READONLY_PROPERTY(obj, str, var) \
2430 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2434 void SetupProcessObject(Environment* env,
2436 const char* const* argv,
2438 const char* const* exec_argv) {
2439 HandleScope scope(node_isolate);
2441 Local<Object> process = env->process_object();
2443 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2445 ProcessTitleSetter);
2448 READONLY_PROPERTY(process,
2450 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2452 // process.moduleLoadList
2453 READONLY_PROPERTY(process,
2455 env->module_load_list_array());
2458 Local<Object> versions = Object::New();
2459 READONLY_PROPERTY(process, "versions", versions);
2461 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2463 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2464 READONLY_PROPERTY(versions,
2466 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2468 // +1 to get rid of the leading 'v'
2469 READONLY_PROPERTY(versions,
2471 OneByteString(node_isolate, NODE_VERSION + 1));
2472 READONLY_PROPERTY(versions,
2474 OneByteString(node_isolate, V8::GetVersion()));
2475 READONLY_PROPERTY(versions,
2477 OneByteString(node_isolate, uv_version_string()));
2478 READONLY_PROPERTY(versions,
2480 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2482 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2483 READONLY_PROPERTY(versions,
2485 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2488 // Stupid code to slice out the version string.
2489 { // NOLINT(whitespace/braces)
2492 for (i = j = 0, k = sizeof(OPENSSL_VERSION_TEXT) - 1; i < k; ++i) {
2493 c = OPENSSL_VERSION_TEXT[i];
2494 if ('0' <= c && c <= '9') {
2495 for (j = i + 1; j < k; ++j) {
2496 c = OPENSSL_VERSION_TEXT[j];
2506 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2511 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2514 READONLY_PROPERTY(process,
2516 OneByteString(node_isolate, PLATFORM));
2519 Local<Array> arguments = Array::New(argc);
2520 for (int i = 0; i < argc; ++i) {
2521 arguments->Set(i, String::NewFromUtf8(node_isolate, argv[i]));
2523 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2526 Local<Array> exec_arguments = Array::New(exec_argc);
2527 for (int i = 0; i < exec_argc; ++i) {
2528 exec_arguments->Set(i, String::NewFromUtf8(node_isolate, exec_argv[i]));
2530 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_arguments);
2532 // create process.env
2533 Local<ObjectTemplate> process_env_template = ObjectTemplate::New();
2534 process_env_template->SetNamedPropertyHandler(EnvGetter,
2540 Local<Object> process_env = process_env_template->NewInstance();
2541 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), process_env);
2543 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2544 READONLY_PROPERTY(process, "features", GetFeatures());
2545 process->SetAccessor(
2546 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2547 NeedImmediateCallbackGetter,
2548 NeedImmediateCallbackSetter);
2552 READONLY_PROPERTY(process,
2554 String::NewFromUtf8(node_isolate, eval_string));
2559 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2562 // -i, --interactive
2564 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2568 if (no_deprecation) {
2569 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2572 // --throw-deprecation
2573 if (throw_deprecation) {
2574 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2577 // --trace-deprecation
2578 if (trace_deprecation) {
2579 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2582 size_t exec_path_len = 2 * PATH_MAX;
2583 char* exec_path = new char[exec_path_len];
2584 Local<String> exec_path_value;
2585 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2586 exec_path_value = String::NewFromUtf8(node_isolate,
2588 String::kNormalString,
2591 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2593 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2597 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2601 // define various internal methods
2602 NODE_SET_METHOD(process,
2603 "_startProfilerIdleNotifier",
2604 StartProfilerIdleNotifier);
2605 NODE_SET_METHOD(process,
2606 "_stopProfilerIdleNotifier",
2607 StopProfilerIdleNotifier);
2608 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2609 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2610 NODE_SET_METHOD(process, "reallyExit", Exit);
2611 NODE_SET_METHOD(process, "abort", Abort);
2612 NODE_SET_METHOD(process, "chdir", Chdir);
2613 NODE_SET_METHOD(process, "cwd", Cwd);
2615 NODE_SET_METHOD(process, "umask", Umask);
2617 #if defined(__POSIX__) && !defined(__ANDROID__)
2618 NODE_SET_METHOD(process, "getuid", GetUid);
2619 NODE_SET_METHOD(process, "setuid", SetUid);
2621 NODE_SET_METHOD(process, "setgid", SetGid);
2622 NODE_SET_METHOD(process, "getgid", GetGid);
2624 NODE_SET_METHOD(process, "getgroups", GetGroups);
2625 NODE_SET_METHOD(process, "setgroups", SetGroups);
2626 NODE_SET_METHOD(process, "initgroups", InitGroups);
2627 #endif // __POSIX__ && !defined(__ANDROID__)
2629 NODE_SET_METHOD(process, "_kill", Kill);
2631 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2632 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2633 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2635 NODE_SET_METHOD(process, "hrtime", Hrtime);
2637 NODE_SET_METHOD(process, "dlopen", DLOpen);
2639 NODE_SET_METHOD(process, "uptime", Uptime);
2640 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2642 NODE_SET_METHOD(process, "binding", Binding);
2644 NODE_SET_METHOD(process, "_setupAsyncListener", SetupAsyncListener);
2645 NODE_SET_METHOD(process, "_setupNextTick", SetupNextTick);
2646 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2648 // values use to cross communicate with processNextTick
2649 Local<Object> tick_info_obj = Object::New();
2650 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
2651 env->tick_info()->fields(),
2652 kExternalUnsignedIntArray,
2653 env->tick_info()->fields_count());
2654 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfo"), tick_info_obj);
2656 // pre-set _events object for faster emit checks
2657 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2661 #undef READONLY_PROPERTY
2664 static void AtExit() {
2665 uv_tty_reset_mode();
2669 static void SignalExit(int signal) {
2670 uv_tty_reset_mode();
2671 _exit(128 + signal);
2675 // Most of the time, it's best to use `console.error` to write
2676 // to the process.stderr stream. However, in some cases, such as
2677 // when debugging the stream.Writable class or the process.nextTick
2678 // function, it is useful to bypass JavaScript entirely.
2679 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2680 HandleScope scope(node_isolate);
2682 assert(args.Length() == 1 && args[0]->IsString() &&
2683 "must be called with a single string");
2685 String::Utf8Value message(args[0]);
2686 fprintf(stderr, "%s\n", *message);
2691 void Load(Environment* env) {
2692 HandleScope handle_scope(node_isolate);
2694 // Compile, execute the src/node.js file. (Which was included as static C
2695 // string in node_natives.h. 'natve_node' is the string containing that
2698 // The node.js file returns a function 'f'
2703 // Disable verbose mode to stop FatalException() handler from trying
2704 // to handle the exception. Errors this early in the start-up phase
2705 // are not safe to ignore.
2706 try_catch.SetVerbose(false);
2708 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2709 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2710 if (try_catch.HasCaught()) {
2711 ReportException(try_catch);
2714 assert(f_value->IsFunction());
2715 Local<Function> f = Local<Function>::Cast(f_value);
2717 // Now we call 'f' with the 'process' variable that we've built up with
2718 // all our bindings. Inside node.js we'll take care of assigning things to
2721 // We start the process this way in order to be more modular. Developers
2722 // who do not like how 'src/node.js' setups the module system but do like
2723 // Node's I/O bindings may want to replace 'f' with their own function.
2725 // Add a reference to the global object
2726 Local<Object> global = env->context()->Global();
2728 #if defined HAVE_DTRACE || defined HAVE_ETW
2732 #if defined HAVE_PERFCTR
2733 InitPerfCounters(global);
2736 // Enable handling of uncaught exceptions
2737 // (FatalException(), break on uncaught exception in debugger)
2739 // This is not strictly necessary since it's almost impossible
2740 // to attach the debugger fast enought to break on exception
2741 // thrown during process startup.
2742 try_catch.SetVerbose(true);
2744 NODE_SET_METHOD(env->process_object(), "_rawDebug", RawDebug);
2746 Local<Value> arg = env->process_object();
2747 f->Call(global, 1, &arg);
2750 static void PrintHelp();
2752 static bool ParseDebugOpt(const char* arg) {
2753 const char* port = NULL;
2755 if (!strcmp(arg, "--debug")) {
2756 use_debug_agent = true;
2757 } else if (!strncmp(arg, "--debug=", sizeof("--debug=") - 1)) {
2758 use_debug_agent = true;
2759 port = arg + sizeof("--debug=") - 1;
2760 } else if (!strcmp(arg, "--debug-brk")) {
2761 use_debug_agent = true;
2762 debug_wait_connect = true;
2763 } else if (!strncmp(arg, "--debug-brk=", sizeof("--debug-brk=") - 1)) {
2764 use_debug_agent = true;
2765 debug_wait_connect = true;
2766 port = arg + sizeof("--debug-brk=") - 1;
2767 } else if (!strncmp(arg, "--debug-port=", sizeof("--debug-port=") - 1)) {
2768 port = arg + sizeof("--debug-port=") - 1;
2774 debug_port = atoi(port);
2775 if (debug_port < 1024 || debug_port > 65535) {
2776 fprintf(stderr, "Debug port must be in range 1024 to 65535.\n");
2785 static void PrintHelp() {
2786 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2787 " node debug script.js [arguments] \n"
2790 " -v, --version print node's version\n"
2791 " -e, --eval script evaluate script\n"
2792 " -p, --print evaluate script and print result\n"
2793 " -i, --interactive always enter the REPL even if stdin\n"
2794 " does not appear to be a terminal\n"
2795 " --no-deprecation silence deprecation warnings\n"
2796 " --trace-deprecation show stack traces on deprecations\n"
2797 " --v8-options print v8 command line options\n"
2798 " --max-stack-size=val set max v8 stack size (bytes)\n"
2800 "Environment variables:\n"
2802 "NODE_PATH ';'-separated list of directories\n"
2804 "NODE_PATH ':'-separated list of directories\n"
2806 " prefixed to the module search path.\n"
2807 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2808 " global contexts.\n"
2809 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2811 "Documentation can be found at http://nodejs.org/\n");
2815 // Parse command line arguments.
2817 // argv is modified in place. exec_argv and v8_argv are out arguments that
2818 // ParseArgs() allocates memory for and stores a pointer to the output
2819 // vector in. The caller should free them with delete[].
2823 // * argv contains the arguments with node and V8 options filtered out.
2824 // * exec_argv contains both node and V8 options and nothing else.
2825 // * v8_argv contains argv[0] plus any V8 options
2826 static void ParseArgs(int* argc,
2829 const char*** exec_argv,
2831 const char*** v8_argv) {
2832 const unsigned int nargs = static_cast<unsigned int>(*argc);
2833 const char** new_exec_argv = new const char*[nargs];
2834 const char** new_v8_argv = new const char*[nargs];
2835 const char** new_argv = new const char*[nargs];
2837 for (unsigned int i = 0; i < nargs; ++i) {
2838 new_exec_argv[i] = NULL;
2839 new_v8_argv[i] = NULL;
2843 // exec_argv starts with the first option, the other two start with argv[0].
2844 unsigned int new_exec_argc = 0;
2845 unsigned int new_v8_argc = 1;
2846 unsigned int new_argc = 1;
2847 new_v8_argv[0] = argv[0];
2848 new_argv[0] = argv[0];
2850 unsigned int index = 1;
2851 while (index < nargs && argv[index][0] == '-') {
2852 const char* const arg = argv[index];
2853 unsigned int args_consumed = 1;
2855 if (ParseDebugOpt(arg)) {
2856 // Done, consumed by ParseDebugOpt().
2857 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2858 printf("%s\n", NODE_VERSION);
2860 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2863 } else if (strcmp(arg, "--eval") == 0 ||
2864 strcmp(arg, "-e") == 0 ||
2865 strcmp(arg, "--print") == 0 ||
2866 strcmp(arg, "-pe") == 0 ||
2867 strcmp(arg, "-p") == 0) {
2868 bool is_eval = strchr(arg, 'e') != NULL;
2869 bool is_print = strchr(arg, 'p') != NULL;
2870 print_eval = print_eval || is_print;
2871 // --eval, -e and -pe always require an argument.
2872 if (is_eval == true) {
2874 eval_string = argv[index + 1];
2875 if (eval_string == NULL) {
2876 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
2879 } else if ((index + 1 < nargs) &&
2880 argv[index + 1] != NULL &&
2881 argv[index + 1][0] != '-') {
2883 eval_string = argv[index + 1];
2884 if (strncmp(eval_string, "\\-", 2) == 0) {
2885 // Starts with "\\-": escaped expression, drop the backslash.
2889 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2891 } else if (strcmp(arg, "--no-deprecation") == 0) {
2892 no_deprecation = true;
2893 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2894 trace_deprecation = true;
2895 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2896 throw_deprecation = true;
2897 } else if (strcmp(arg, "--v8-options") == 0) {
2898 new_v8_argv[new_v8_argc] = "--help";
2901 // V8 option. Pass through as-is.
2902 new_v8_argv[new_v8_argc] = arg;
2906 memcpy(new_exec_argv + new_exec_argc,
2908 args_consumed * sizeof(*argv));
2910 new_exec_argc += args_consumed;
2911 index += args_consumed;
2914 // Copy remaining arguments.
2915 const unsigned int args_left = nargs - index;
2916 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
2917 new_argc += args_left;
2919 *exec_argc = new_exec_argc;
2920 *exec_argv = new_exec_argv;
2921 *v8_argc = new_v8_argc;
2922 *v8_argv = new_v8_argv;
2924 // Copy new_argv over argv and update argc.
2925 memcpy(argv, new_argv, new_argc * sizeof(*argv));
2927 *argc = static_cast<int>(new_argc);
2931 // Called from V8 Debug Agent TCP thread.
2932 static void DispatchMessagesDebugAgentCallback() {
2933 uv_async_send(&dispatch_debug_messages_async);
2937 // Called from the main thread.
2938 static void EnableDebug(bool wait_connect) {
2939 assert(debugger_running == false);
2940 Isolate* isolate = node_isolate; // TODO(bnoordhuis) Multi-isolate support.
2941 Isolate::Scope isolate_scope(isolate);
2942 HandleScope handle_scope(isolate);
2943 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2945 debugger_running = v8::Debug::EnableAgent("node " NODE_VERSION,
2948 if (debugger_running == false) {
2949 fprintf(stderr, "Starting debugger on port %d failed\n", debug_port);
2953 fprintf(stderr, "Debugger listening on port %d\n", debug_port);
2956 Environment* env = Environment::GetCurrentChecked(isolate);
2958 return; // Still starting up.
2960 Context::Scope context_scope(env->context());
2961 Local<Object> message = Object::New();
2962 message->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "cmd"),
2963 FIXED_ONE_BYTE_STRING(env->isolate(), "NODE_DEBUG_ENABLED"));
2964 Local<Value> argv[] = {
2965 FIXED_ONE_BYTE_STRING(env->isolate(), "internalMessage"),
2968 MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(argv), argv);
2972 // Called from the main thread.
2973 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2974 if (debugger_running == false) {
2975 fprintf(stderr, "Starting debugger agent.\n");
2978 Isolate::Scope isolate_scope(node_isolate);
2979 v8::Debug::ProcessDebugMessages();
2984 static volatile sig_atomic_t caught_early_debug_signal;
2987 static void EarlyDebugSignalHandler(int signo) {
2988 caught_early_debug_signal = 1;
2992 static void InstallEarlyDebugSignalHandler() {
2993 struct sigaction sa;
2994 memset(&sa, 0, sizeof(sa));
2995 sa.sa_handler = EarlyDebugSignalHandler;
2996 sigaction(SIGUSR1, &sa, NULL);
3000 static void EnableDebugSignalHandler(int signo) {
3001 // Call only async signal-safe functions here!
3002 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
3003 uv_async_send(&dispatch_debug_messages_async);
3007 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
3008 struct sigaction sa;
3009 memset(&sa, 0, sizeof(sa));
3010 sa.sa_handler = handler;
3011 sigfillset(&sa.sa_mask);
3012 sigaction(signal, &sa, NULL);
3016 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3017 HandleScope scope(node_isolate);
3019 if (args.Length() != 1) {
3020 return ThrowError("Invalid number of arguments.");
3026 pid = args[0]->IntegerValue();
3027 r = kill(pid, SIGUSR1);
3029 return ThrowErrnoException(errno, "kill");
3034 static int RegisterDebugSignalHandler() {
3035 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3036 RegisterSignalHandler(SIGUSR1, EnableDebugSignalHandler);
3037 // If we caught a SIGUSR1 during the bootstrap process, re-raise it
3038 // now that the debugger infrastructure is in place.
3039 if (caught_early_debug_signal)
3047 DWORD WINAPI EnableDebugThreadProc(void* arg) {
3048 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
3049 uv_async_send(&dispatch_debug_messages_async);
3054 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
3056 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
3060 static int RegisterDebugSignalHandler() {
3061 wchar_t mapping_name[32];
3062 HANDLE mapping_handle;
3064 LPTHREAD_START_ROUTINE* handler;
3066 pid = GetCurrentProcessId();
3068 if (GetDebugSignalHandlerMappingName(pid,
3070 ARRAY_SIZE(mapping_name)) < 0) {
3074 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
3080 if (mapping_handle == NULL) {
3084 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3085 MapViewOfFile(mapping_handle,
3086 FILE_MAP_ALL_ACCESS,
3090 if (handler == NULL) {
3091 CloseHandle(mapping_handle);
3095 *handler = EnableDebugThreadProc;
3097 UnmapViewOfFile(static_cast<void*>(handler));
3103 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3104 HandleScope scope(node_isolate);
3106 HANDLE process = NULL;
3107 HANDLE thread = NULL;
3108 HANDLE mapping = NULL;
3109 wchar_t mapping_name[32];
3110 LPTHREAD_START_ROUTINE* handler = NULL;
3112 if (args.Length() != 1) {
3113 ThrowError("Invalid number of arguments.");
3117 pid = (DWORD) args[0]->IntegerValue();
3119 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
3120 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
3124 if (process == NULL) {
3125 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
3129 if (GetDebugSignalHandlerMappingName(pid,
3131 ARRAY_SIZE(mapping_name)) < 0) {
3132 ThrowErrnoException(errno, "sprintf");
3136 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
3137 if (mapping == NULL) {
3138 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
3142 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3143 MapViewOfFile(mapping,
3148 if (handler == NULL || *handler == NULL) {
3149 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
3153 thread = CreateRemoteThread(process,
3160 if (thread == NULL) {
3161 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
3165 // Wait for the thread to terminate
3166 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3167 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
3172 if (process != NULL)
3173 CloseHandle(process);
3175 CloseHandle(thread);
3176 if (handler != NULL)
3177 UnmapViewOfFile(handler);
3178 if (mapping != NULL)
3179 CloseHandle(mapping);
3184 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3185 v8::Debug::DebugBreak(node_isolate);
3189 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3190 if (debugger_running) {
3191 v8::Debug::DisableAgent();
3192 debugger_running = false;
3197 void Init(int* argc,
3200 const char*** exec_argv) {
3201 // Initialize prog_start_time to get relative uptime.
3202 uv_uptime(&prog_start_time);
3204 // Make inherited handles noninheritable.
3205 uv_disable_stdio_inheritance();
3207 // init async debug messages dispatching
3208 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3209 uv_async_init(uv_default_loop(),
3210 &dispatch_debug_messages_async,
3211 DispatchDebugMessagesAsyncCallback);
3212 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3214 // Parse a few arguments which are specific to Node.
3216 const char** v8_argv;
3217 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3219 // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
3220 // manually? That would give us a little more control over its runtime
3221 // behavior but it could also interfere with the user's intentions in ways
3222 // we fail to anticipate. Dillema.
3223 for (int i = 1; i < v8_argc; ++i) {
3224 if (strncmp(v8_argv[i], "--prof", sizeof("--prof") - 1) == 0) {
3225 v8_is_profiling = true;
3230 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3231 // the argv array or the elements it points to.
3232 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3234 // Anything that's still in v8_argv is not a V8 or a node option.
3235 for (int i = 1; i < v8_argc; i++) {
3236 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3245 if (debug_wait_connect) {
3246 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3247 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3250 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3252 // Fetch a reference to the main isolate, so we have a reference to it
3253 // even when we need it to access it from another (debugger) thread.
3254 node_isolate = Isolate::GetCurrent();
3257 // Raise the open file descriptor limit.
3258 { // NOLINT (whitespace/braces)
3260 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3261 // Do a binary search for the limit.
3262 rlim_t min = lim.rlim_cur;
3263 rlim_t max = 1 << 20;
3264 // But if there's a defined upper bound, don't search, just set it.
3265 if (lim.rlim_max != RLIM_INFINITY) {
3270 lim.rlim_cur = min + (max - min) / 2;
3271 if (setrlimit(RLIMIT_NOFILE, &lim)) {
3276 } while (min + 1 < max);
3280 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3281 RegisterSignalHandler(SIGINT, SignalExit);
3282 RegisterSignalHandler(SIGTERM, SignalExit);
3285 V8::SetFatalErrorHandler(node::OnFatalError);
3286 V8::AddMessageListener(OnMessage);
3288 // If the --debug flag was specified then initialize the debug thread.
3289 if (use_debug_agent) {
3290 EnableDebug(debug_wait_connect);
3292 RegisterDebugSignalHandler();
3297 struct AtExitCallback {
3298 AtExitCallback* next_;
3299 void (*cb_)(void* arg);
3303 static AtExitCallback* at_exit_functions_;
3306 // TODO(bnoordhuis) Turn into per-context event.
3307 void RunAtExit(Environment* env) {
3308 AtExitCallback* p = at_exit_functions_;
3309 at_exit_functions_ = NULL;
3312 AtExitCallback* q = p->next_;
3320 void AtExit(void (*cb)(void* arg), void* arg) {
3321 AtExitCallback* p = new AtExitCallback;
3324 p->next_ = at_exit_functions_;
3325 at_exit_functions_ = p;
3329 int EmitExit(Environment* env) {
3330 // process.emit('exit')
3331 HandleScope handle_scope(env->isolate());
3332 Context::Scope context_scope(env->context());
3333 Local<Object> process_object = env->process_object();
3334 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3335 True(node_isolate));
3337 Handle<String> exitCode = FIXED_ONE_BYTE_STRING(node_isolate, "exitCode");
3338 int code = process_object->Get(exitCode)->IntegerValue();
3340 Local<Value> args[] = {
3341 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3342 Integer::New(code, node_isolate)
3345 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3350 Environment* CreateEnvironment(Isolate* isolate,
3352 const char* const* argv,
3354 const char* const* exec_argv) {
3355 HandleScope handle_scope(isolate);
3357 Local<Context> context = Context::New(isolate);
3358 Context::Scope context_scope(context);
3359 Environment* env = Environment::New(context);
3361 uv_check_init(env->event_loop(), env->immediate_check_handle());
3363 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3364 uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3366 // Inform V8's CPU profiler when we're idle. The profiler is sampling-based
3367 // but not all samples are created equal; mark the wall clock time spent in
3368 // epoll_wait() and friends so profiling tools can filter it out. The samples
3369 // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
3370 // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
3371 // probably fortify in the API contract, namely that the last started prepare
3372 // or check watcher runs first. It's not 100% foolproof; if an add-on starts
3373 // a prepare or check watcher after us, any samples attributed to its callback
3374 // will be recorded with state=IDLE.
3375 uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
3376 uv_check_init(env->event_loop(), env->idle_check_handle());
3377 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
3378 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
3380 if (v8_is_profiling) {
3381 StartProfilerIdleNotifier(env);
3384 Local<FunctionTemplate> process_template = FunctionTemplate::New();
3385 process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3387 Local<Object> process_object = process_template->GetFunction()->NewInstance();
3388 env->set_process_object(process_object);
3390 SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3397 int Start(int argc, char** argv) {
3398 #if !defined(_WIN32)
3399 // Try hard not to lose SIGUSR1 signals during the bootstrap process.
3400 InstallEarlyDebugSignalHandler();
3405 // Hack around with the argv pointer. Used for process.title = "blah".
3406 argv = uv_setup_args(argc, argv);
3408 // This needs to run *before* V8::Initialize(). The const_cast is not
3409 // optional, in case you're wondering.
3411 const char** exec_argv;
3412 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3415 // V8 on Windows doesn't have a good source of entropy. Seed it from
3417 V8::SetEntropySource(crypto::EntropySource);
3423 Locker locker(node_isolate);
3425 CreateEnvironment(node_isolate, argc, argv, exec_argc, exec_argv);
3426 // This Context::Scope is here so EnableDebug() can look up the current
3427 // environment with Environment::GetCurrentChecked().
3428 // TODO(bnoordhuis) Reorder the debugger initialization logic so it can
3430 Context::Scope context_scope(env->context());
3431 uv_run(env->event_loop(), UV_RUN_DEFAULT);
3432 code = EmitExit(env);
3439 // Clean up. Not strictly necessary.