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,
943 Handle<Object> object,
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<Value> domain_v = object->Get(env->domain_string());
952 Local<Object> domain;
955 try_catch.SetVerbose(true);
957 // TODO(trevnorris): This is sucky for performance. Fix it.
958 bool has_async_queue = object->Has(env->async_queue_string());
959 if (has_async_queue) {
960 Local<Value> argv[] = { object };
961 env->async_listener_load_function()->Call(process, ARRAY_SIZE(argv), argv);
963 if (try_catch.HasCaught())
964 return Undefined(node_isolate);
967 bool has_domain = domain_v->IsObject();
969 domain = domain_v.As<Object>();
971 if (domain->Get(env->disposed_string())->IsTrue()) {
972 // domain has been disposed of.
973 return Undefined(node_isolate);
976 Local<Function> enter =
977 domain->Get(env->enter_string()).As<Function>();
978 assert(enter->IsFunction());
979 enter->Call(domain, 0, NULL);
981 if (try_catch.HasCaught()) {
982 return Undefined(node_isolate);
986 Local<Value> ret = callback->Call(object, argc, argv);
988 if (try_catch.HasCaught()) {
989 return Undefined(node_isolate);
993 Local<Function> exit =
994 domain->Get(env->exit_string()).As<Function>();
995 assert(exit->IsFunction());
996 exit->Call(domain, 0, NULL);
998 if (try_catch.HasCaught()) {
999 return Undefined(node_isolate);
1003 if (has_async_queue) {
1004 Local<Value> val = object.As<Value>();
1005 env->async_listener_unload_function()->Call(process, 1, &val);
1007 if (try_catch.HasCaught())
1008 return Undefined(node_isolate);
1011 Environment::TickInfo* tick_info = env->tick_info();
1013 if (tick_info->last_threw() == 1) {
1014 tick_info->set_last_threw(0);
1018 if (tick_info->in_tick()) {
1022 if (tick_info->length() == 0) {
1023 tick_info->set_index(0);
1027 tick_info->set_in_tick(true);
1029 env->tick_callback_function()->Call(process, 0, NULL);
1031 tick_info->set_in_tick(false);
1033 if (try_catch.HasCaught()) {
1034 tick_info->set_last_threw(true);
1035 return Undefined(node_isolate);
1042 Handle<Value> MakeCallback(Environment* env,
1043 Handle<Object> object,
1044 const Handle<Function> callback,
1046 Handle<Value> argv[]) {
1047 if (env->using_domains())
1048 return MakeDomainCallback(env, object, callback, argc, argv);
1050 // If you hit this assertion, you forgot to enter the v8::Context first.
1051 assert(env->context() == env->isolate()->GetCurrentContext());
1053 Local<Object> process = env->process_object();
1056 try_catch.SetVerbose(true);
1058 // TODO(trevnorris): This is sucky for performance. Fix it.
1059 bool has_async_queue = object->Has(env->async_queue_string());
1060 if (has_async_queue) {
1061 Local<Value> argv[] = { object };
1062 env->async_listener_load_function()->Call(process, ARRAY_SIZE(argv), argv);
1064 if (try_catch.HasCaught())
1065 return Undefined(node_isolate);
1068 Local<Value> ret = callback->Call(object, argc, argv);
1070 if (try_catch.HasCaught()) {
1071 return Undefined(node_isolate);
1074 if (has_async_queue) {
1075 Local<Value> val = object.As<Value>();
1076 env->async_listener_unload_function()->Call(process, 1, &val);
1078 if (try_catch.HasCaught())
1079 return Undefined(node_isolate);
1082 Environment::TickInfo* tick_info = env->tick_info();
1084 if (tick_info->in_tick()) {
1088 if (tick_info->length() == 0) {
1089 tick_info->set_index(0);
1093 tick_info->set_in_tick(true);
1095 // process nextTicks after call
1096 env->tick_callback_function()->Call(process, 0, NULL);
1098 tick_info->set_in_tick(false);
1100 if (try_catch.HasCaught()) {
1101 tick_info->set_last_threw(true);
1102 return Undefined(node_isolate);
1110 Handle<Value> MakeCallback(Environment* env,
1111 const Handle<Object> object,
1114 Handle<Value> argv[]) {
1115 Local<Function> callback = object->Get(index).As<Function>();
1116 assert(callback->IsFunction());
1118 return MakeCallback(env, object, callback, argc, argv);
1122 Handle<Value> MakeCallback(Environment* env,
1123 const Handle<Object> object,
1124 const Handle<String> symbol,
1126 Handle<Value> argv[]) {
1127 Local<Function> callback = object->Get(symbol).As<Function>();
1128 assert(callback->IsFunction());
1129 return MakeCallback(env, object, callback, argc, argv);
1133 Handle<Value> MakeCallback(Environment* env,
1134 const Handle<Object> object,
1137 Handle<Value> argv[]) {
1138 Local<String> method_string = OneByteString(node_isolate, method);
1139 return MakeCallback(env, object, method_string, argc, argv);
1143 Handle<Value> MakeCallback(const Handle<Object> object,
1146 Handle<Value> argv[]) {
1147 Local<Context> context = object->CreationContext();
1148 Environment* env = Environment::GetCurrent(context);
1149 Context::Scope context_scope(context);
1150 HandleScope handle_scope(env->isolate());
1151 return handle_scope.Close(MakeCallback(env, object, method, argc, argv));
1155 Handle<Value> MakeCallback(const Handle<Object> object,
1156 const Handle<String> symbol,
1158 Handle<Value> argv[]) {
1159 Local<Context> context = object->CreationContext();
1160 Environment* env = Environment::GetCurrent(context);
1161 Context::Scope context_scope(context);
1162 HandleScope handle_scope(env->isolate());
1163 return handle_scope.Close(MakeCallback(env, object, symbol, argc, argv));
1167 Handle<Value> MakeCallback(const Handle<Object> object,
1168 const Handle<Function> callback,
1170 Handle<Value> argv[]) {
1171 Local<Context> context = object->CreationContext();
1172 Environment* env = Environment::GetCurrent(context);
1173 Context::Scope context_scope(context);
1174 HandleScope handle_scope(env->isolate());
1175 return handle_scope.Close(MakeCallback(env, object, callback, argc, argv));
1179 Handle<Value> MakeDomainCallback(const Handle<Object> object,
1180 const Handle<Function> callback,
1182 Handle<Value> argv[]) {
1183 Local<Context> context = object->CreationContext();
1184 Environment* env = Environment::GetCurrent(context);
1185 Context::Scope context_scope(context);
1186 HandleScope handle_scope(env->isolate());
1187 return handle_scope.Close(
1188 MakeDomainCallback(env, object, callback, argc, argv));
1192 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1193 HandleScope scope(node_isolate);
1195 if (!encoding_v->IsString())
1198 String::Utf8Value encoding(encoding_v);
1200 if (strcasecmp(*encoding, "utf8") == 0) {
1202 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1204 } else if (strcasecmp(*encoding, "ascii") == 0) {
1206 } else if (strcasecmp(*encoding, "base64") == 0) {
1208 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1210 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1212 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1214 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1216 } else if (strcasecmp(*encoding, "binary") == 0) {
1218 } else if (strcasecmp(*encoding, "buffer") == 0) {
1220 } else if (strcasecmp(*encoding, "hex") == 0) {
1222 } else if (strcasecmp(*encoding, "raw") == 0) {
1223 if (!no_deprecation) {
1224 fprintf(stderr, "'raw' (array of integers) has been removed. "
1228 } else if (strcasecmp(*encoding, "raws") == 0) {
1229 if (!no_deprecation) {
1230 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1231 "Please update your code.\n");
1239 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1240 return StringBytes::Encode(static_cast<const char*>(buf),
1245 // Returns -1 if the handle was not valid for decoding
1246 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1247 HandleScope scope(node_isolate);
1249 if (val->IsArray()) {
1250 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1256 return StringBytes::Size(val, encoding);
1260 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1263 // Returns number of bytes written.
1264 ssize_t DecodeWrite(char *buf,
1266 v8::Handle<v8::Value> val,
1267 enum encoding encoding) {
1268 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1271 void DisplayExceptionLine(Handle<Message> message) {
1272 // Prevent re-entry into this function. For example, if there is
1273 // a throw from a program in vm.runInThisContext(code, filename, true),
1274 // then we want to show the original failure, not the secondary one.
1275 static bool displayed_error = false;
1277 if (displayed_error)
1279 displayed_error = true;
1281 uv_tty_reset_mode();
1283 fprintf(stderr, "\n");
1285 if (!message.IsEmpty()) {
1286 // Print (filename):(line number): (message).
1287 String::Utf8Value filename(message->GetScriptResourceName());
1288 const char* filename_string = *filename;
1289 int linenum = message->GetLineNumber();
1290 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1291 // Print line of source code.
1292 String::Utf8Value sourceline(message->GetSourceLine());
1293 const char* sourceline_string = *sourceline;
1295 // Because of how node modules work, all scripts are wrapped with a
1296 // "function (module, exports, __filename, ...) {"
1297 // to provide script local variables.
1299 // When reporting errors on the first line of a script, this wrapper
1300 // function is leaked to the user. There used to be a hack here to
1301 // truncate off the first 62 characters, but it caused numerous other
1302 // problems when vm.runIn*Context() methods were used for non-module
1305 // If we ever decide to re-instate such a hack, the following steps
1308 // 1. Pass a flag around to say "this code was wrapped"
1309 // 2. Update the stack frame output so that it is also correct.
1311 // It would probably be simpler to add a line rather than add some
1312 // number of characters to the first line, since V8 truncates the
1313 // sourceline to 78 characters, and we end up not providing very much
1314 // useful debugging info to the user if we remove 62 characters.
1316 int start = message->GetStartColumn();
1317 int end = message->GetEndColumn();
1319 fprintf(stderr, "%s\n", sourceline_string);
1320 // Print wavy underline (GetUnderline is deprecated).
1321 for (int i = 0; i < start; i++) {
1322 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1324 for (int i = start; i < end; i++) {
1327 fputc('\n', stderr);
1332 static void ReportException(Handle<Value> er, Handle<Message> message) {
1333 HandleScope scope(node_isolate);
1335 DisplayExceptionLine(message);
1337 Local<Value> trace_value;
1339 if (er->IsUndefined() || er->IsNull()) {
1340 trace_value = Undefined(node_isolate);
1343 er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack"));
1346 String::Utf8Value trace(trace_value);
1348 // range errors have a trace member set to undefined
1349 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1350 fprintf(stderr, "%s\n", *trace);
1352 // this really only happens for RangeErrors, since they're the only
1353 // kind that won't have all this info in the trace, or when non-Error
1354 // objects are thrown manually.
1355 Local<Value> message;
1358 if (er->IsObject()) {
1359 Local<Object> err_obj = er.As<Object>();
1360 message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1361 name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1364 if (message.IsEmpty() ||
1365 message->IsUndefined() ||
1367 name->IsUndefined()) {
1368 // Not an error object. Just print as-is.
1369 String::Utf8Value message(er);
1370 fprintf(stderr, "%s\n", *message);
1372 String::Utf8Value name_string(name);
1373 String::Utf8Value message_string(message);
1374 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1382 static void ReportException(const TryCatch& try_catch) {
1383 ReportException(try_catch.Exception(), try_catch.Message());
1387 // Executes a str within the current v8 context.
1388 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1389 HandleScope scope(node_isolate);
1392 // try_catch must be nonverbose to disable FatalException() handler,
1393 // we will handle exceptions ourself.
1394 try_catch.SetVerbose(false);
1396 Local<v8::Script> script = v8::Script::Compile(source, filename);
1397 if (script.IsEmpty()) {
1398 ReportException(try_catch);
1402 Local<Value> result = script->Run();
1403 if (result.IsEmpty()) {
1404 ReportException(try_catch);
1408 return scope.Close(result);
1412 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1413 HandleScope scope(node_isolate);
1415 Local<Array> ary = Array::New();
1419 QUEUE_FOREACH(q, &req_wrap_queue) {
1420 ReqWrap<uv_req_t>* w = CONTAINER_OF(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1421 if (w->persistent().IsEmpty())
1423 ary->Set(i++, w->object());
1426 args.GetReturnValue().Set(ary);
1430 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1431 // implemented here for consistency with GetActiveRequests().
1432 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1433 HandleScope scope(node_isolate);
1435 Local<Array> ary = Array::New();
1439 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1441 QUEUE_FOREACH(q, &handle_wrap_queue) {
1442 HandleWrap* w = CONTAINER_OF(q, HandleWrap, handle_wrap_queue_);
1443 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref))
1445 Local<Object> object = w->object();
1446 Local<Value> owner = object->Get(owner_sym);
1447 if (owner->IsUndefined())
1449 ary->Set(i++, owner);
1452 args.GetReturnValue().Set(ary);
1456 static void Abort(const FunctionCallbackInfo<Value>& args) {
1461 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1462 HandleScope scope(node_isolate);
1464 if (args.Length() != 1 || !args[0]->IsString()) {
1465 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1468 String::Utf8Value path(args[0]);
1469 int err = uv_chdir(*path);
1471 return ThrowUVException(err, "uv_chdir");
1476 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1477 HandleScope scope(node_isolate);
1479 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1480 char buf[MAX_PATH * 4 + 1];
1482 char buf[PATH_MAX + 1];
1485 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1487 return ThrowUVException(err, "uv_cwd");
1490 buf[ARRAY_SIZE(buf) - 1] = '\0';
1491 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1493 args.GetReturnValue().Set(cwd);
1497 static void Umask(const FunctionCallbackInfo<Value>& args) {
1498 HandleScope scope(node_isolate);
1501 if (args.Length() < 1 || args[0]->IsUndefined()) {
1503 umask(static_cast<mode_t>(old));
1504 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1505 return ThrowTypeError("argument must be an integer or octal string.");
1508 if (args[0]->IsInt32()) {
1509 oct = args[0]->Uint32Value();
1512 String::Utf8Value str(args[0]);
1514 // Parse the octal string.
1515 for (int i = 0; i < str.length(); i++) {
1517 if (c > '7' || c < '0') {
1518 return ThrowTypeError("invalid octal string");
1524 old = umask(static_cast<mode_t>(oct));
1527 args.GetReturnValue().Set(old);
1531 #if defined(__POSIX__) && !defined(__ANDROID__)
1533 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1534 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1537 static uid_t uid_by_name(const char* name) {
1545 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1549 return uid_not_found;
1553 static char* name_by_uid(uid_t uid) {
1562 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1563 return strdup(pp->pw_name);
1574 static gid_t gid_by_name(const char* name) {
1582 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1586 return gid_not_found;
1590 #if 0 // For future use.
1591 static const char* name_by_gid(gid_t gid) {
1600 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1601 return strdup(pp->gr_name);
1613 static uid_t uid_by_name(Handle<Value> value) {
1614 if (value->IsUint32()) {
1615 return static_cast<uid_t>(value->Uint32Value());
1617 String::Utf8Value name(value);
1618 return uid_by_name(*name);
1623 static gid_t gid_by_name(Handle<Value> value) {
1624 if (value->IsUint32()) {
1625 return static_cast<gid_t>(value->Uint32Value());
1627 String::Utf8Value name(value);
1628 return gid_by_name(*name);
1633 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1634 // uid_t is an uint32_t on all supported platforms.
1635 args.GetReturnValue().Set(static_cast<uint32_t>(getuid()));
1639 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1640 // gid_t is an uint32_t on all supported platforms.
1641 args.GetReturnValue().Set(static_cast<uint32_t>(getgid()));
1645 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1646 HandleScope scope(node_isolate);
1648 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1649 return ThrowTypeError("setgid argument must be a number or a string");
1652 gid_t gid = gid_by_name(args[0]);
1654 if (gid == gid_not_found) {
1655 return ThrowError("setgid group id does not exist");
1659 return ThrowErrnoException(errno, "setgid");
1664 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1665 HandleScope scope(node_isolate);
1667 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1668 return ThrowTypeError("setuid argument must be a number or a string");
1671 uid_t uid = uid_by_name(args[0]);
1673 if (uid == uid_not_found) {
1674 return ThrowError("setuid user id does not exist");
1678 return ThrowErrnoException(errno, "setuid");
1683 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1684 HandleScope scope(node_isolate);
1686 int ngroups = getgroups(0, NULL);
1688 if (ngroups == -1) {
1689 return ThrowErrnoException(errno, "getgroups");
1692 gid_t* groups = new gid_t[ngroups];
1694 ngroups = getgroups(ngroups, groups);
1696 if (ngroups == -1) {
1698 return ThrowErrnoException(errno, "getgroups");
1701 Local<Array> groups_list = Array::New(ngroups);
1702 bool seen_egid = false;
1703 gid_t egid = getegid();
1705 for (int i = 0; i < ngroups; i++) {
1706 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1707 if (groups[i] == egid)
1713 if (seen_egid == false) {
1714 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1717 args.GetReturnValue().Set(groups_list);
1721 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1722 HandleScope scope(node_isolate);
1724 if (!args[0]->IsArray()) {
1725 return ThrowTypeError("argument 1 must be an array");
1728 Local<Array> groups_list = args[0].As<Array>();
1729 size_t size = groups_list->Length();
1730 gid_t* groups = new gid_t[size];
1732 for (size_t i = 0; i < size; i++) {
1733 gid_t gid = gid_by_name(groups_list->Get(i));
1735 if (gid == gid_not_found) {
1737 return ThrowError("group name not found");
1743 int rc = setgroups(size, groups);
1747 return ThrowErrnoException(errno, "setgroups");
1752 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1753 HandleScope scope(node_isolate);
1755 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1756 return ThrowTypeError("argument 1 must be a number or a string");
1759 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1760 return ThrowTypeError("argument 2 must be a number or a string");
1763 String::Utf8Value arg0(args[0]);
1768 if (args[0]->IsUint32()) {
1769 user = name_by_uid(args[0]->Uint32Value());
1777 return ThrowError("initgroups user not found");
1780 extra_group = gid_by_name(args[1]);
1782 if (extra_group == gid_not_found) {
1785 return ThrowError("initgroups extra group not found");
1788 int rc = initgroups(user, extra_group);
1795 return ThrowErrnoException(errno, "initgroups");
1799 #endif // __POSIX__ && !defined(__ANDROID__)
1802 void Exit(const FunctionCallbackInfo<Value>& args) {
1803 HandleScope scope(node_isolate);
1804 exit(args[0]->IntegerValue());
1808 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1809 HandleScope scope(node_isolate);
1811 if (uv_uptime(&uptime))
1813 args.GetReturnValue().Set(uptime - prog_start_time);
1817 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1818 HandleScope handle_scope(args.GetIsolate());
1819 Environment* env = Environment::GetCurrent(args.GetIsolate());
1822 int err = uv_resident_set_memory(&rss);
1824 return ThrowUVException(err, "uv_resident_set_memory");
1828 HeapStatistics v8_heap_stats;
1829 node_isolate->GetHeapStatistics(&v8_heap_stats);
1831 Local<Integer> heap_total =
1832 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(), node_isolate);
1833 Local<Integer> heap_used =
1834 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(), node_isolate);
1836 Local<Object> info = Object::New();
1837 info->Set(env->rss_string(), Number::New(node_isolate, rss));
1838 info->Set(env->heap_total_string(), heap_total);
1839 info->Set(env->heap_used_string(), heap_used);
1841 args.GetReturnValue().Set(info);
1845 void Kill(const FunctionCallbackInfo<Value>& args) {
1846 HandleScope scope(node_isolate);
1848 if (args.Length() != 2) {
1849 return ThrowError("Bad argument.");
1852 int pid = args[0]->IntegerValue();
1853 int sig = args[1]->Int32Value();
1854 int err = uv_kill(pid, sig);
1855 args.GetReturnValue().Set(err);
1858 // used in Hrtime() below
1859 #define NANOS_PER_SEC 1000000000
1861 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1862 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1863 // so this function instead returns an Array with 2 entries representing seconds
1864 // and nanoseconds, to avoid any integer overflow possibility.
1865 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1866 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1867 HandleScope scope(node_isolate);
1869 uint64_t t = uv_hrtime();
1871 if (args.Length() > 0) {
1872 // return a time diff tuple
1873 if (!args[0]->IsArray()) {
1874 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1876 Local<Array> inArray = Local<Array>::Cast(args[0]);
1877 uint64_t seconds = inArray->Get(0)->Uint32Value();
1878 uint64_t nanos = inArray->Get(1)->Uint32Value();
1879 t -= (seconds * NANOS_PER_SEC) + nanos;
1882 Local<Array> tuple = Array::New(2);
1883 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1884 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1885 args.GetReturnValue().Set(tuple);
1888 extern "C" void node_module_register(void* m) {
1889 struct node_module* mp = reinterpret_cast<struct node_module*>(m);
1891 if (mp->nm_flags & NM_F_BUILTIN) {
1892 mp->nm_link = modlist_builtin;
1893 modlist_builtin = mp;
1895 assert(modpending == NULL);
1900 struct node_module* get_builtin_module(const char* name) {
1901 struct node_module* mp;
1903 for (mp = modlist_builtin; mp != NULL; mp = mp->nm_link) {
1904 if (strcmp(mp->nm_modname, name) == 0)
1908 assert(mp == NULL || (mp->nm_flags & NM_F_BUILTIN) != 0);
1912 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1914 // DLOpen is process.dlopen(module, filename).
1915 // Used to load 'module.node' dynamically shared objects.
1917 // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
1918 // when two contexts try to load the same shared object. Maybe have a shadow
1919 // cache that's a plain C list or hash table that's shared across contexts?
1920 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1921 HandleScope handle_scope(args.GetIsolate());
1922 Environment* env = Environment::GetCurrent(args.GetIsolate());
1923 struct node_module* mp;
1926 if (args.Length() < 2) {
1927 ThrowError("process.dlopen takes exactly 2 arguments.");
1931 Local<Object> module = args[0]->ToObject(); // Cast
1932 String::Utf8Value filename(args[1]); // Cast
1934 Local<String> exports_string = env->exports_string();
1935 Local<Object> exports = module->Get(exports_string)->ToObject();
1937 if (uv_dlopen(*filename, &lib)) {
1938 Local<String> errmsg = OneByteString(env->isolate(), uv_dlerror(&lib));
1940 // Windows needs to add the filename into the error message
1941 errmsg = String::Concat(errmsg, args[1]->ToString());
1943 ThrowException(Exception::Error(errmsg));
1948 * Objects containing v14 or later modules will have registered themselves
1949 * on the pending list. Activate all of them now. At present, only one
1950 * module per object is supported.
1956 ThrowError("Module did not self-register.");
1959 if (mp->nm_version != NODE_MODULE_VERSION) {
1963 "Module version mismatch. Expected %d, got %d.",
1964 NODE_MODULE_VERSION, mp->nm_version);
1968 if (mp->nm_flags & NM_F_BUILTIN) {
1969 ThrowError("Built-in module self-registered.");
1973 mp->nm_dso_handle = lib.handle;
1974 mp->nm_link = modlist_addon;
1977 if (mp->nm_context_register_func != NULL) {
1978 mp->nm_context_register_func(exports, module, env->context(), mp->nm_priv);
1979 } else if (mp->nm_register_func != NULL) {
1980 mp->nm_register_func(exports, module, mp->nm_priv);
1982 ThrowError("Module has no declared entry point.");
1986 // Tell coverity that 'handle' should not be freed when we return.
1987 // coverity[leaked_storage]
1991 static void OnFatalError(const char* location, const char* message) {
1993 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1995 fprintf(stderr, "FATAL ERROR: %s\n", message);
2002 NO_RETURN void FatalError(const char* location, const char* message) {
2003 OnFatalError(location, message);
2004 // to supress compiler warning
2009 void FatalException(Handle<Value> error, Handle<Message> message) {
2010 HandleScope scope(node_isolate);
2012 Environment* env = Environment::GetCurrent(node_isolate);
2013 Local<Object> process_object = env->process_object();
2014 Local<String> fatal_exception_string = env->fatal_exception_string();
2015 Local<Function> fatal_exception_function =
2016 process_object->Get(fatal_exception_string).As<Function>();
2018 if (!fatal_exception_function->IsFunction()) {
2019 // failed before the process._fatalException function was added!
2020 // this is probably pretty bad. Nothing to do but report and exit.
2021 ReportException(error, message);
2025 TryCatch fatal_try_catch;
2027 // Do not call FatalException when _fatalException handler throws
2028 fatal_try_catch.SetVerbose(false);
2030 // this will return true if the JS layer handled it, false otherwise
2031 Local<Value> caught =
2032 fatal_exception_function->Call(process_object, 1, &error);
2034 if (fatal_try_catch.HasCaught()) {
2035 // the fatal exception function threw, so we must exit
2036 ReportException(fatal_try_catch);
2040 if (false == caught->BooleanValue()) {
2041 ReportException(error, message);
2047 void FatalException(const TryCatch& try_catch) {
2048 HandleScope scope(node_isolate);
2049 // TODO(bajtos) do not call FatalException if try_catch is verbose
2050 // (requires V8 API to expose getter for try_catch.is_verbose_)
2051 FatalException(try_catch.Exception(), try_catch.Message());
2055 void OnMessage(Handle<Message> message, Handle<Value> error) {
2056 // The current version of V8 sends messages for errors only
2057 // (thus `error` is always set).
2058 FatalException(error, message);
2062 static void Binding(const FunctionCallbackInfo<Value>& args) {
2063 HandleScope handle_scope(args.GetIsolate());
2064 Environment* env = Environment::GetCurrent(args.GetIsolate());
2066 Local<String> module = args[0]->ToString();
2067 String::Utf8Value module_v(module);
2069 Local<Object> cache = env->binding_cache_object();
2070 Local<Object> exports;
2072 if (cache->Has(module)) {
2073 exports = cache->Get(module)->ToObject();
2074 args.GetReturnValue().Set(exports);
2078 // Append a string to process.moduleLoadList
2080 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
2082 Local<Array> modules = env->module_load_list_array();
2083 uint32_t l = modules->Length();
2084 modules->Set(l, OneByteString(node_isolate, buf));
2086 node_module* mod = get_builtin_module(*module_v);
2088 exports = Object::New();
2089 // Internal bindings don't have a "module" object, only exports.
2090 assert(mod->nm_register_func == NULL);
2091 assert(mod->nm_context_register_func != NULL);
2092 Local<Value> unused = Undefined(env->isolate());
2093 mod->nm_context_register_func(exports, unused,
2094 env->context(), mod->nm_priv);
2095 cache->Set(module, exports);
2096 } else if (!strcmp(*module_v, "constants")) {
2097 exports = Object::New();
2098 DefineConstants(exports);
2099 cache->Set(module, exports);
2100 } else if (!strcmp(*module_v, "natives")) {
2101 exports = Object::New();
2102 DefineJavaScript(exports);
2103 cache->Set(module, exports);
2105 return ThrowError("No such module");
2108 args.GetReturnValue().Set(exports);
2112 static void ProcessTitleGetter(Local<String> property,
2113 const PropertyCallbackInfo<Value>& info) {
2114 HandleScope scope(node_isolate);
2116 uv_get_process_title(buffer, sizeof(buffer));
2117 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2121 static void ProcessTitleSetter(Local<String> property,
2123 const PropertyCallbackInfo<void>& info) {
2124 HandleScope scope(node_isolate);
2125 String::Utf8Value title(value);
2126 // TODO(piscisaureus): protect with a lock
2127 uv_set_process_title(*title);
2131 static void EnvGetter(Local<String> property,
2132 const PropertyCallbackInfo<Value>& info) {
2133 HandleScope scope(node_isolate);
2135 String::Utf8Value key(property);
2136 const char* val = getenv(*key);
2138 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2141 String::Value key(property);
2142 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2143 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2145 ARRAY_SIZE(buffer));
2146 // If result >= sizeof buffer the buffer was too small. That should never
2147 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2149 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2150 result < ARRAY_SIZE(buffer)) {
2151 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2152 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2153 return info.GetReturnValue().Set(rc);
2156 // Not found. Fetch from prototype.
2157 info.GetReturnValue().Set(
2158 info.Data().As<Object>()->Get(property));
2162 static void EnvSetter(Local<String> property,
2164 const PropertyCallbackInfo<Value>& info) {
2165 HandleScope scope(node_isolate);
2167 String::Utf8Value key(property);
2168 String::Utf8Value val(value);
2169 setenv(*key, *val, 1);
2171 String::Value key(property);
2172 String::Value val(value);
2173 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2174 // Environment variables that start with '=' are read-only.
2175 if (key_ptr[0] != L'=') {
2176 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2179 // Whether it worked or not, always return rval.
2180 info.GetReturnValue().Set(value);
2184 static void EnvQuery(Local<String> property,
2185 const PropertyCallbackInfo<Integer>& info) {
2186 HandleScope scope(node_isolate);
2187 int32_t rc = -1; // Not found unless proven otherwise.
2189 String::Utf8Value key(property);
2193 String::Value key(property);
2194 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2195 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2196 GetLastError() == ERROR_SUCCESS) {
2198 if (key_ptr[0] == L'=') {
2199 // Environment variables that start with '=' are hidden and read-only.
2200 rc = static_cast<int32_t>(v8::ReadOnly) |
2201 static_cast<int32_t>(v8::DontDelete) |
2202 static_cast<int32_t>(v8::DontEnum);
2207 info.GetReturnValue().Set(rc);
2211 static void EnvDeleter(Local<String> property,
2212 const PropertyCallbackInfo<Boolean>& info) {
2213 HandleScope scope(node_isolate);
2216 String::Utf8Value key(property);
2217 rc = getenv(*key) != NULL;
2221 String::Value key(property);
2222 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2223 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2224 // Deletion failed. Return true if the key wasn't there in the first place,
2225 // false if it is still there.
2226 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2227 GetLastError() != ERROR_SUCCESS;
2230 info.GetReturnValue().Set(rc);
2234 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2235 HandleScope scope(node_isolate);
2238 while (environ[size])
2241 Local<Array> env = Array::New(size);
2243 for (int i = 0; i < size; ++i) {
2244 const char* var = environ[i];
2245 const char* s = strchr(var, '=');
2246 const int length = s ? s - var : strlen(var);
2247 Local<String> name = String::NewFromUtf8(node_isolate,
2249 String::kNormalString,
2254 WCHAR* environment = GetEnvironmentStringsW();
2255 if (environment == NULL)
2256 return; // This should not happen.
2257 Local<Array> env = Array::New();
2258 WCHAR* p = environment;
2260 while (*p != NULL) {
2263 // If the key starts with '=' it is a hidden environment variable.
2267 s = wcschr(p, L'=');
2272 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2273 const size_t two_byte_buffer_len = s - p;
2274 Local<String> value = String::NewFromTwoByte(node_isolate,
2276 String::kNormalString,
2277 two_byte_buffer_len);
2278 env->Set(i++, value);
2279 p = s + wcslen(s) + 1;
2281 FreeEnvironmentStringsW(environment);
2284 info.GetReturnValue().Set(env);
2288 static Handle<Object> GetFeatures() {
2289 HandleScope scope(node_isolate);
2291 Local<Object> obj = Object::New();
2292 #if defined(DEBUG) && DEBUG
2293 Local<Value> debug = True(node_isolate);
2295 Local<Value> debug = False(node_isolate);
2296 #endif // defined(DEBUG) && DEBUG
2298 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2300 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2301 // TODO(bnoordhuis) ping libuv
2302 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2304 #ifdef OPENSSL_NPN_NEGOTIATED
2305 Local<Boolean> tls_npn = True(node_isolate);
2307 Local<Boolean> tls_npn = False(node_isolate);
2309 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"), tls_npn);
2311 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2312 Local<Boolean> tls_sni = True(node_isolate);
2314 Local<Boolean> tls_sni = False(node_isolate);
2316 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"), tls_sni);
2318 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2319 Boolean::New(get_builtin_module("crypto") != NULL));
2321 return scope.Close(obj);
2325 static void DebugPortGetter(Local<String> property,
2326 const PropertyCallbackInfo<Value>& info) {
2327 HandleScope scope(node_isolate);
2328 info.GetReturnValue().Set(debug_port);
2332 static void DebugPortSetter(Local<String> property,
2334 const PropertyCallbackInfo<void>& info) {
2335 HandleScope scope(node_isolate);
2336 debug_port = value->NumberValue();
2340 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2341 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2342 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2345 void NeedImmediateCallbackGetter(Local<String> property,
2346 const PropertyCallbackInfo<Value>& info) {
2347 HandleScope handle_scope(info.GetIsolate());
2348 Environment* env = Environment::GetCurrent(info.GetIsolate());
2349 const uv_check_t* immediate_check_handle = env->immediate_check_handle();
2350 bool active = uv_is_active(
2351 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2352 info.GetReturnValue().Set(active);
2356 static void NeedImmediateCallbackSetter(
2357 Local<String> property,
2359 const PropertyCallbackInfo<void>& info) {
2360 HandleScope handle_scope(info.GetIsolate());
2361 Environment* env = Environment::GetCurrent(info.GetIsolate());
2363 uv_check_t* immediate_check_handle = env->immediate_check_handle();
2364 bool active = uv_is_active(
2365 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2367 if (active == value->BooleanValue())
2370 uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
2373 uv_check_stop(immediate_check_handle);
2374 uv_idle_stop(immediate_idle_handle);
2376 uv_check_start(immediate_check_handle, CheckImmediate);
2377 // Idle handle is needed only to stop the event loop from blocking in poll.
2378 uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
2383 void SetIdle(uv_prepare_t* handle, int) {
2384 Environment* env = Environment::from_idle_prepare_handle(handle);
2385 env->isolate()->GetCpuProfiler()->SetIdle(true);
2389 void ClearIdle(uv_check_t* handle, int) {
2390 Environment* env = Environment::from_idle_check_handle(handle);
2391 env->isolate()->GetCpuProfiler()->SetIdle(false);
2395 void StartProfilerIdleNotifier(Environment* env) {
2396 uv_prepare_start(env->idle_prepare_handle(), SetIdle);
2397 uv_check_start(env->idle_check_handle(), ClearIdle);
2401 void StopProfilerIdleNotifier(Environment* env) {
2402 uv_prepare_stop(env->idle_prepare_handle());
2403 uv_check_stop(env->idle_check_handle());
2407 void StartProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2408 HandleScope handle_scope(args.GetIsolate());
2409 Environment* env = Environment::GetCurrent(args.GetIsolate());
2410 StartProfilerIdleNotifier(env);
2414 void StopProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2415 HandleScope handle_scope(args.GetIsolate());
2416 Environment* env = Environment::GetCurrent(args.GetIsolate());
2417 StopProfilerIdleNotifier(env);
2421 #define READONLY_PROPERTY(obj, str, var) \
2423 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2427 void SetupProcessObject(Environment* env,
2429 const char* const* argv,
2431 const char* const* exec_argv) {
2432 HandleScope scope(node_isolate);
2434 Local<Object> process = env->process_object();
2436 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2438 ProcessTitleSetter);
2441 READONLY_PROPERTY(process,
2443 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2445 // process.moduleLoadList
2446 READONLY_PROPERTY(process,
2448 env->module_load_list_array());
2451 Local<Object> versions = Object::New();
2452 READONLY_PROPERTY(process, "versions", versions);
2454 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2456 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2457 READONLY_PROPERTY(versions,
2459 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2461 // +1 to get rid of the leading 'v'
2462 READONLY_PROPERTY(versions,
2464 OneByteString(node_isolate, NODE_VERSION + 1));
2465 READONLY_PROPERTY(versions,
2467 OneByteString(node_isolate, V8::GetVersion()));
2468 READONLY_PROPERTY(versions,
2470 OneByteString(node_isolate, uv_version_string()));
2471 READONLY_PROPERTY(versions,
2473 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2475 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2476 READONLY_PROPERTY(versions,
2478 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2481 // Stupid code to slice out the version string.
2482 { // NOLINT(whitespace/braces)
2485 for (i = j = 0, k = sizeof(OPENSSL_VERSION_TEXT) - 1; i < k; ++i) {
2486 c = OPENSSL_VERSION_TEXT[i];
2487 if ('0' <= c && c <= '9') {
2488 for (j = i + 1; j < k; ++j) {
2489 c = OPENSSL_VERSION_TEXT[j];
2499 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2504 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2507 READONLY_PROPERTY(process,
2509 OneByteString(node_isolate, PLATFORM));
2512 Local<Array> arguments = Array::New(argc);
2513 for (int i = 0; i < argc; ++i) {
2514 arguments->Set(i, String::NewFromUtf8(node_isolate, argv[i]));
2516 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2519 Local<Array> exec_arguments = Array::New(exec_argc);
2520 for (int i = 0; i < exec_argc; ++i) {
2521 exec_arguments->Set(i, String::NewFromUtf8(node_isolate, exec_argv[i]));
2523 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_arguments);
2525 // create process.env
2526 Local<ObjectTemplate> process_env_template = ObjectTemplate::New();
2527 process_env_template->SetNamedPropertyHandler(EnvGetter,
2533 Local<Object> process_env = process_env_template->NewInstance();
2534 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), process_env);
2536 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2537 READONLY_PROPERTY(process, "features", GetFeatures());
2538 process->SetAccessor(
2539 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2540 NeedImmediateCallbackGetter,
2541 NeedImmediateCallbackSetter);
2545 READONLY_PROPERTY(process,
2547 String::NewFromUtf8(node_isolate, eval_string));
2552 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2555 // -i, --interactive
2557 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2561 if (no_deprecation) {
2562 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2565 // --throw-deprecation
2566 if (throw_deprecation) {
2567 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2570 // --trace-deprecation
2571 if (trace_deprecation) {
2572 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2575 size_t exec_path_len = 2 * PATH_MAX;
2576 char* exec_path = new char[exec_path_len];
2577 Local<String> exec_path_value;
2578 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2579 exec_path_value = String::NewFromUtf8(node_isolate,
2581 String::kNormalString,
2584 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2586 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2590 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2594 // define various internal methods
2595 NODE_SET_METHOD(process,
2596 "_startProfilerIdleNotifier",
2597 StartProfilerIdleNotifier);
2598 NODE_SET_METHOD(process,
2599 "_stopProfilerIdleNotifier",
2600 StopProfilerIdleNotifier);
2601 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2602 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2603 NODE_SET_METHOD(process, "reallyExit", Exit);
2604 NODE_SET_METHOD(process, "abort", Abort);
2605 NODE_SET_METHOD(process, "chdir", Chdir);
2606 NODE_SET_METHOD(process, "cwd", Cwd);
2608 NODE_SET_METHOD(process, "umask", Umask);
2610 #if defined(__POSIX__) && !defined(__ANDROID__)
2611 NODE_SET_METHOD(process, "getuid", GetUid);
2612 NODE_SET_METHOD(process, "setuid", SetUid);
2614 NODE_SET_METHOD(process, "setgid", SetGid);
2615 NODE_SET_METHOD(process, "getgid", GetGid);
2617 NODE_SET_METHOD(process, "getgroups", GetGroups);
2618 NODE_SET_METHOD(process, "setgroups", SetGroups);
2619 NODE_SET_METHOD(process, "initgroups", InitGroups);
2620 #endif // __POSIX__ && !defined(__ANDROID__)
2622 NODE_SET_METHOD(process, "_kill", Kill);
2624 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2625 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2626 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2628 NODE_SET_METHOD(process, "hrtime", Hrtime);
2630 NODE_SET_METHOD(process, "dlopen", DLOpen);
2632 NODE_SET_METHOD(process, "uptime", Uptime);
2633 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2635 NODE_SET_METHOD(process, "binding", Binding);
2637 NODE_SET_METHOD(process, "_setupAsyncListener", SetupAsyncListener);
2638 NODE_SET_METHOD(process, "_setupNextTick", SetupNextTick);
2639 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2641 // values use to cross communicate with processNextTick
2642 Local<Object> tick_info_obj = Object::New();
2643 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
2644 env->tick_info()->fields(),
2645 kExternalUnsignedIntArray,
2646 env->tick_info()->fields_count());
2647 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfo"), tick_info_obj);
2649 // pre-set _events object for faster emit checks
2650 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2654 #undef READONLY_PROPERTY
2657 static void AtExit() {
2658 uv_tty_reset_mode();
2662 static void SignalExit(int signal) {
2663 uv_tty_reset_mode();
2664 _exit(128 + signal);
2668 // Most of the time, it's best to use `console.error` to write
2669 // to the process.stderr stream. However, in some cases, such as
2670 // when debugging the stream.Writable class or the process.nextTick
2671 // function, it is useful to bypass JavaScript entirely.
2672 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2673 HandleScope scope(node_isolate);
2675 assert(args.Length() == 1 && args[0]->IsString() &&
2676 "must be called with a single string");
2678 String::Utf8Value message(args[0]);
2679 fprintf(stderr, "%s\n", *message);
2684 void Load(Environment* env) {
2685 HandleScope handle_scope(node_isolate);
2687 // Compile, execute the src/node.js file. (Which was included as static C
2688 // string in node_natives.h. 'natve_node' is the string containing that
2691 // The node.js file returns a function 'f'
2696 // Disable verbose mode to stop FatalException() handler from trying
2697 // to handle the exception. Errors this early in the start-up phase
2698 // are not safe to ignore.
2699 try_catch.SetVerbose(false);
2701 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2702 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2703 if (try_catch.HasCaught()) {
2704 ReportException(try_catch);
2707 assert(f_value->IsFunction());
2708 Local<Function> f = Local<Function>::Cast(f_value);
2710 // Now we call 'f' with the 'process' variable that we've built up with
2711 // all our bindings. Inside node.js we'll take care of assigning things to
2714 // We start the process this way in order to be more modular. Developers
2715 // who do not like how 'src/node.js' setups the module system but do like
2716 // Node's I/O bindings may want to replace 'f' with their own function.
2718 // Add a reference to the global object
2719 Local<Object> global = env->context()->Global();
2721 #if defined HAVE_DTRACE || defined HAVE_ETW
2725 #if defined HAVE_PERFCTR
2726 InitPerfCounters(global);
2729 // Enable handling of uncaught exceptions
2730 // (FatalException(), break on uncaught exception in debugger)
2732 // This is not strictly necessary since it's almost impossible
2733 // to attach the debugger fast enought to break on exception
2734 // thrown during process startup.
2735 try_catch.SetVerbose(true);
2737 NODE_SET_METHOD(env->process_object(), "_rawDebug", RawDebug);
2739 Local<Value> arg = env->process_object();
2740 f->Call(global, 1, &arg);
2743 static void PrintHelp();
2745 static bool ParseDebugOpt(const char* arg) {
2746 const char* port = NULL;
2748 if (!strcmp(arg, "--debug")) {
2749 use_debug_agent = true;
2750 } else if (!strncmp(arg, "--debug=", sizeof("--debug=") - 1)) {
2751 use_debug_agent = true;
2752 port = arg + sizeof("--debug=") - 1;
2753 } else if (!strcmp(arg, "--debug-brk")) {
2754 use_debug_agent = true;
2755 debug_wait_connect = true;
2756 } else if (!strncmp(arg, "--debug-brk=", sizeof("--debug-brk=") - 1)) {
2757 use_debug_agent = true;
2758 debug_wait_connect = true;
2759 port = arg + sizeof("--debug-brk=") - 1;
2760 } else if (!strncmp(arg, "--debug-port=", sizeof("--debug-port=") - 1)) {
2761 port = arg + sizeof("--debug-port=") - 1;
2767 debug_port = atoi(port);
2768 if (debug_port < 1024 || debug_port > 65535) {
2769 fprintf(stderr, "Debug port must be in range 1024 to 65535.\n");
2778 static void PrintHelp() {
2779 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2780 " node debug script.js [arguments] \n"
2783 " -v, --version print node's version\n"
2784 " -e, --eval script evaluate script\n"
2785 " -p, --print evaluate script and print result\n"
2786 " -i, --interactive always enter the REPL even if stdin\n"
2787 " does not appear to be a terminal\n"
2788 " --no-deprecation silence deprecation warnings\n"
2789 " --trace-deprecation show stack traces on deprecations\n"
2790 " --v8-options print v8 command line options\n"
2791 " --max-stack-size=val set max v8 stack size (bytes)\n"
2793 "Environment variables:\n"
2795 "NODE_PATH ';'-separated list of directories\n"
2797 "NODE_PATH ':'-separated list of directories\n"
2799 " prefixed to the module search path.\n"
2800 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2801 " global contexts.\n"
2802 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2804 "Documentation can be found at http://nodejs.org/\n");
2808 // Parse command line arguments.
2810 // argv is modified in place. exec_argv and v8_argv are out arguments that
2811 // ParseArgs() allocates memory for and stores a pointer to the output
2812 // vector in. The caller should free them with delete[].
2816 // * argv contains the arguments with node and V8 options filtered out.
2817 // * exec_argv contains both node and V8 options and nothing else.
2818 // * v8_argv contains argv[0] plus any V8 options
2819 static void ParseArgs(int* argc,
2822 const char*** exec_argv,
2824 const char*** v8_argv) {
2825 const unsigned int nargs = static_cast<unsigned int>(*argc);
2826 const char** new_exec_argv = new const char*[nargs];
2827 const char** new_v8_argv = new const char*[nargs];
2828 const char** new_argv = new const char*[nargs];
2830 for (unsigned int i = 0; i < nargs; ++i) {
2831 new_exec_argv[i] = NULL;
2832 new_v8_argv[i] = NULL;
2836 // exec_argv starts with the first option, the other two start with argv[0].
2837 unsigned int new_exec_argc = 0;
2838 unsigned int new_v8_argc = 1;
2839 unsigned int new_argc = 1;
2840 new_v8_argv[0] = argv[0];
2841 new_argv[0] = argv[0];
2843 unsigned int index = 1;
2844 while (index < nargs && argv[index][0] == '-') {
2845 const char* const arg = argv[index];
2846 unsigned int args_consumed = 1;
2848 if (ParseDebugOpt(arg)) {
2849 // Done, consumed by ParseDebugOpt().
2850 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2851 printf("%s\n", NODE_VERSION);
2853 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2856 } else if (strcmp(arg, "--eval") == 0 ||
2857 strcmp(arg, "-e") == 0 ||
2858 strcmp(arg, "--print") == 0 ||
2859 strcmp(arg, "-pe") == 0 ||
2860 strcmp(arg, "-p") == 0) {
2861 bool is_eval = strchr(arg, 'e') != NULL;
2862 bool is_print = strchr(arg, 'p') != NULL;
2863 print_eval = print_eval || is_print;
2864 // --eval, -e and -pe always require an argument.
2865 if (is_eval == true) {
2867 eval_string = argv[index + 1];
2868 if (eval_string == NULL) {
2869 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
2872 } else if ((index + 1 < nargs) &&
2873 argv[index + 1] != NULL &&
2874 argv[index + 1][0] != '-') {
2876 eval_string = argv[index + 1];
2877 if (strncmp(eval_string, "\\-", 2) == 0) {
2878 // Starts with "\\-": escaped expression, drop the backslash.
2882 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2884 } else if (strcmp(arg, "--no-deprecation") == 0) {
2885 no_deprecation = true;
2886 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2887 trace_deprecation = true;
2888 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2889 throw_deprecation = true;
2890 } else if (strcmp(arg, "--v8-options") == 0) {
2891 new_v8_argv[new_v8_argc] = "--help";
2894 // V8 option. Pass through as-is.
2895 new_v8_argv[new_v8_argc] = arg;
2899 memcpy(new_exec_argv + new_exec_argc,
2901 args_consumed * sizeof(*argv));
2903 new_exec_argc += args_consumed;
2904 index += args_consumed;
2907 // Copy remaining arguments.
2908 const unsigned int args_left = nargs - index;
2909 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
2910 new_argc += args_left;
2912 *exec_argc = new_exec_argc;
2913 *exec_argv = new_exec_argv;
2914 *v8_argc = new_v8_argc;
2915 *v8_argv = new_v8_argv;
2917 // Copy new_argv over argv and update argc.
2918 memcpy(argv, new_argv, new_argc * sizeof(*argv));
2920 *argc = static_cast<int>(new_argc);
2924 // Called from V8 Debug Agent TCP thread.
2925 static void DispatchMessagesDebugAgentCallback() {
2926 uv_async_send(&dispatch_debug_messages_async);
2930 // Called from the main thread.
2931 static void EnableDebug(bool wait_connect) {
2932 assert(debugger_running == false);
2933 Isolate* isolate = node_isolate; // TODO(bnoordhuis) Multi-isolate support.
2934 Isolate::Scope isolate_scope(isolate);
2935 HandleScope handle_scope(isolate);
2936 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2938 debugger_running = v8::Debug::EnableAgent("node " NODE_VERSION,
2941 if (debugger_running == false) {
2942 fprintf(stderr, "Starting debugger on port %d failed\n", debug_port);
2946 fprintf(stderr, "Debugger listening on port %d\n", debug_port);
2949 Environment* env = Environment::GetCurrentChecked(isolate);
2951 return; // Still starting up.
2953 Context::Scope context_scope(env->context());
2954 Local<Object> message = Object::New();
2955 message->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "cmd"),
2956 FIXED_ONE_BYTE_STRING(env->isolate(), "NODE_DEBUG_ENABLED"));
2957 Local<Value> argv[] = {
2958 FIXED_ONE_BYTE_STRING(env->isolate(), "internalMessage"),
2961 MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(argv), argv);
2965 // Called from the main thread.
2966 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2967 if (debugger_running == false) {
2968 fprintf(stderr, "Starting debugger agent.\n");
2971 Isolate::Scope isolate_scope(node_isolate);
2972 v8::Debug::ProcessDebugMessages();
2977 static volatile sig_atomic_t caught_early_debug_signal;
2980 static void EarlyDebugSignalHandler(int signo) {
2981 caught_early_debug_signal = 1;
2985 static void InstallEarlyDebugSignalHandler() {
2986 struct sigaction sa;
2987 memset(&sa, 0, sizeof(sa));
2988 sa.sa_handler = EarlyDebugSignalHandler;
2989 sigaction(SIGUSR1, &sa, NULL);
2993 static void EnableDebugSignalHandler(int signo) {
2994 // Call only async signal-safe functions here!
2995 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
2996 uv_async_send(&dispatch_debug_messages_async);
3000 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
3001 struct sigaction sa;
3002 memset(&sa, 0, sizeof(sa));
3003 sa.sa_handler = handler;
3004 sigfillset(&sa.sa_mask);
3005 sigaction(signal, &sa, NULL);
3009 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3010 HandleScope scope(node_isolate);
3012 if (args.Length() != 1) {
3013 return ThrowError("Invalid number of arguments.");
3019 pid = args[0]->IntegerValue();
3020 r = kill(pid, SIGUSR1);
3022 return ThrowErrnoException(errno, "kill");
3027 static int RegisterDebugSignalHandler() {
3028 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3029 RegisterSignalHandler(SIGUSR1, EnableDebugSignalHandler);
3030 // If we caught a SIGUSR1 during the bootstrap process, re-raise it
3031 // now that the debugger infrastructure is in place.
3032 if (caught_early_debug_signal)
3040 DWORD WINAPI EnableDebugThreadProc(void* arg) {
3041 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
3042 uv_async_send(&dispatch_debug_messages_async);
3047 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
3049 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
3053 static int RegisterDebugSignalHandler() {
3054 wchar_t mapping_name[32];
3055 HANDLE mapping_handle;
3057 LPTHREAD_START_ROUTINE* handler;
3059 pid = GetCurrentProcessId();
3061 if (GetDebugSignalHandlerMappingName(pid,
3063 ARRAY_SIZE(mapping_name)) < 0) {
3067 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
3073 if (mapping_handle == NULL) {
3077 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3078 MapViewOfFile(mapping_handle,
3079 FILE_MAP_ALL_ACCESS,
3083 if (handler == NULL) {
3084 CloseHandle(mapping_handle);
3088 *handler = EnableDebugThreadProc;
3090 UnmapViewOfFile(static_cast<void*>(handler));
3096 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3097 HandleScope scope(node_isolate);
3099 HANDLE process = NULL;
3100 HANDLE thread = NULL;
3101 HANDLE mapping = NULL;
3102 wchar_t mapping_name[32];
3103 LPTHREAD_START_ROUTINE* handler = NULL;
3105 if (args.Length() != 1) {
3106 ThrowError("Invalid number of arguments.");
3110 pid = (DWORD) args[0]->IntegerValue();
3112 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
3113 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
3117 if (process == NULL) {
3118 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
3122 if (GetDebugSignalHandlerMappingName(pid,
3124 ARRAY_SIZE(mapping_name)) < 0) {
3125 ThrowErrnoException(errno, "sprintf");
3129 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
3130 if (mapping == NULL) {
3131 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
3135 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3136 MapViewOfFile(mapping,
3141 if (handler == NULL || *handler == NULL) {
3142 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
3146 thread = CreateRemoteThread(process,
3153 if (thread == NULL) {
3154 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
3158 // Wait for the thread to terminate
3159 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3160 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
3165 if (process != NULL)
3166 CloseHandle(process);
3168 CloseHandle(thread);
3169 if (handler != NULL)
3170 UnmapViewOfFile(handler);
3171 if (mapping != NULL)
3172 CloseHandle(mapping);
3177 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3178 v8::Debug::DebugBreak(node_isolate);
3182 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3183 if (debugger_running) {
3184 v8::Debug::DisableAgent();
3185 debugger_running = false;
3190 void Init(int* argc,
3193 const char*** exec_argv) {
3194 // Initialize prog_start_time to get relative uptime.
3195 uv_uptime(&prog_start_time);
3197 // Make inherited handles noninheritable.
3198 uv_disable_stdio_inheritance();
3200 // init async debug messages dispatching
3201 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3202 uv_async_init(uv_default_loop(),
3203 &dispatch_debug_messages_async,
3204 DispatchDebugMessagesAsyncCallback);
3205 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3207 // Parse a few arguments which are specific to Node.
3209 const char** v8_argv;
3210 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3212 // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
3213 // manually? That would give us a little more control over its runtime
3214 // behavior but it could also interfere with the user's intentions in ways
3215 // we fail to anticipate. Dillema.
3216 for (int i = 1; i < v8_argc; ++i) {
3217 if (strncmp(v8_argv[i], "--prof", sizeof("--prof") - 1) == 0) {
3218 v8_is_profiling = true;
3223 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3224 // the argv array or the elements it points to.
3225 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3227 // Anything that's still in v8_argv is not a V8 or a node option.
3228 for (int i = 1; i < v8_argc; i++) {
3229 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3238 if (debug_wait_connect) {
3239 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3240 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3243 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3245 // Fetch a reference to the main isolate, so we have a reference to it
3246 // even when we need it to access it from another (debugger) thread.
3247 node_isolate = Isolate::GetCurrent();
3250 // Raise the open file descriptor limit.
3251 { // NOLINT (whitespace/braces)
3253 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3254 // Do a binary search for the limit.
3255 rlim_t min = lim.rlim_cur;
3256 rlim_t max = 1 << 20;
3257 // But if there's a defined upper bound, don't search, just set it.
3258 if (lim.rlim_max != RLIM_INFINITY) {
3263 lim.rlim_cur = min + (max - min) / 2;
3264 if (setrlimit(RLIMIT_NOFILE, &lim)) {
3269 } while (min + 1 < max);
3273 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3274 RegisterSignalHandler(SIGINT, SignalExit);
3275 RegisterSignalHandler(SIGTERM, SignalExit);
3278 V8::SetFatalErrorHandler(node::OnFatalError);
3279 V8::AddMessageListener(OnMessage);
3281 // If the --debug flag was specified then initialize the debug thread.
3282 if (use_debug_agent) {
3283 EnableDebug(debug_wait_connect);
3285 RegisterDebugSignalHandler();
3290 struct AtExitCallback {
3291 AtExitCallback* next_;
3292 void (*cb_)(void* arg);
3296 static AtExitCallback* at_exit_functions_;
3299 // TODO(bnoordhuis) Turn into per-context event.
3300 void RunAtExit(Environment* env) {
3301 AtExitCallback* p = at_exit_functions_;
3302 at_exit_functions_ = NULL;
3305 AtExitCallback* q = p->next_;
3313 void AtExit(void (*cb)(void* arg), void* arg) {
3314 AtExitCallback* p = new AtExitCallback;
3317 p->next_ = at_exit_functions_;
3318 at_exit_functions_ = p;
3322 int EmitExit(Environment* env) {
3323 // process.emit('exit')
3324 HandleScope handle_scope(env->isolate());
3325 Context::Scope context_scope(env->context());
3326 Local<Object> process_object = env->process_object();
3327 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3328 True(node_isolate));
3330 Handle<String> exitCode = FIXED_ONE_BYTE_STRING(node_isolate, "exitCode");
3331 int code = process_object->Get(exitCode)->IntegerValue();
3333 Local<Value> args[] = {
3334 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3335 Integer::New(code, node_isolate)
3338 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3343 Environment* CreateEnvironment(Isolate* isolate,
3345 const char* const* argv,
3347 const char* const* exec_argv) {
3348 HandleScope handle_scope(isolate);
3350 Local<Context> context = Context::New(isolate);
3351 Context::Scope context_scope(context);
3352 Environment* env = Environment::New(context);
3354 uv_check_init(env->event_loop(), env->immediate_check_handle());
3356 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3357 uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3359 // Inform V8's CPU profiler when we're idle. The profiler is sampling-based
3360 // but not all samples are created equal; mark the wall clock time spent in
3361 // epoll_wait() and friends so profiling tools can filter it out. The samples
3362 // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
3363 // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
3364 // probably fortify in the API contract, namely that the last started prepare
3365 // or check watcher runs first. It's not 100% foolproof; if an add-on starts
3366 // a prepare or check watcher after us, any samples attributed to its callback
3367 // will be recorded with state=IDLE.
3368 uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
3369 uv_check_init(env->event_loop(), env->idle_check_handle());
3370 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
3371 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
3373 if (v8_is_profiling) {
3374 StartProfilerIdleNotifier(env);
3377 Local<FunctionTemplate> process_template = FunctionTemplate::New();
3378 process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3380 Local<Object> process_object = process_template->GetFunction()->NewInstance();
3381 env->set_process_object(process_object);
3383 SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3390 int Start(int argc, char** argv) {
3391 #if !defined(_WIN32)
3392 // Try hard not to lose SIGUSR1 signals during the bootstrap process.
3393 InstallEarlyDebugSignalHandler();
3398 // Hack around with the argv pointer. Used for process.title = "blah".
3399 argv = uv_setup_args(argc, argv);
3401 // This needs to run *before* V8::Initialize(). The const_cast is not
3402 // optional, in case you're wondering.
3404 const char** exec_argv;
3405 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3408 // V8 on Windows doesn't have a good source of entropy. Seed it from
3410 V8::SetEntropySource(crypto::EntropySource);
3416 Locker locker(node_isolate);
3418 CreateEnvironment(node_isolate, argc, argv, exec_argc, exec_argv);
3419 // This Context::Scope is here so EnableDebug() can look up the current
3420 // environment with Environment::GetCurrentChecked().
3421 // TODO(bnoordhuis) Reorder the debugger initialization logic so it can
3423 Context::Scope context_scope(env->context());
3424 uv_run(env->event_loop(), UV_RUN_DEFAULT);
3425 code = EmitExit(env);
3432 // Clean up. Not strictly necessary.