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 HandleScope handle_scope(node_isolate); // FIXME(bnoordhuis) Isolate-ify.
1154 Local<Context> context = recv->CreationContext();
1155 Environment* env = Environment::GetCurrent(context);
1156 Context::Scope context_scope(context);
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 HandleScope handle_scope(node_isolate); // FIXME(bnoordhuis) Isolate-ify.
1166 Local<Context> context = recv->CreationContext();
1167 Environment* env = Environment::GetCurrent(context);
1168 Context::Scope context_scope(context);
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 HandleScope handle_scope(node_isolate); // FIXME(bnoordhuis) Isolate-ify.
1178 Local<Context> context = recv->CreationContext();
1179 Environment* env = Environment::GetCurrent(context);
1180 Context::Scope context_scope(context);
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 AppendExceptionLine(Environment* env,
1280 Handle<Message> message) {
1281 if (message.IsEmpty())
1284 HandleScope scope(env->isolate());
1285 Local<Object> err_obj;
1286 if (!er.IsEmpty() && er->IsObject()) {
1287 err_obj = er.As<Object>();
1289 // Do it only once per message
1290 if (!err_obj->GetHiddenValue(env->processed_string()).IsEmpty())
1292 err_obj->SetHiddenValue(env->processed_string(), True(env->isolate()));
1295 static char arrow[1024];
1297 // Print (filename):(line number): (message).
1298 String::Utf8Value filename(message->GetScriptResourceName());
1299 const char* filename_string = *filename;
1300 int linenum = message->GetLineNumber();
1301 // Print line of source code.
1302 String::Utf8Value sourceline(message->GetSourceLine());
1303 const char* sourceline_string = *sourceline;
1305 // Because of how node modules work, all scripts are wrapped with a
1306 // "function (module, exports, __filename, ...) {"
1307 // to provide script local variables.
1309 // When reporting errors on the first line of a script, this wrapper
1310 // function is leaked to the user. There used to be a hack here to
1311 // truncate off the first 62 characters, but it caused numerous other
1312 // problems when vm.runIn*Context() methods were used for non-module
1315 // If we ever decide to re-instate such a hack, the following steps
1318 // 1. Pass a flag around to say "this code was wrapped"
1319 // 2. Update the stack frame output so that it is also correct.
1321 // It would probably be simpler to add a line rather than add some
1322 // number of characters to the first line, since V8 truncates the
1323 // sourceline to 78 characters, and we end up not providing very much
1324 // useful debugging info to the user if we remove 62 characters.
1326 int start = message->GetStartColumn();
1327 int end = message->GetEndColumn();
1329 int off = snprintf(arrow,
1337 // Print wavy underline (GetUnderline is deprecated).
1338 for (int i = 0; i < start; i++) {
1339 assert(static_cast<size_t>(off) < sizeof(arrow));
1340 arrow[off++] = (sourceline_string[i] == '\t') ? '\t' : ' ';
1342 for (int i = start; i < end; i++) {
1343 assert(static_cast<size_t>(off) < sizeof(arrow));
1346 assert(static_cast<size_t>(off) < sizeof(arrow) - 1);
1347 arrow[off++] = '\n';
1350 Local<String> arrow_str = String::NewFromUtf8(env->isolate(), arrow);
1354 // Allocation failed, just print it out
1355 if (arrow_str.IsEmpty() || err_obj.IsEmpty() || !err_obj->IsNativeError())
1358 msg = err_obj->Get(env->message_string());
1359 stack = err_obj->Get(env->stack_string());
1361 if (msg.IsEmpty() || stack.IsEmpty())
1364 err_obj->Set(env->message_string(),
1365 String::Concat(arrow_str, msg->ToString()));
1366 err_obj->Set(env->stack_string(),
1367 String::Concat(arrow_str, stack->ToString()));
1371 if (env->printed_error())
1373 env->set_printed_error(true);
1374 uv_tty_reset_mode();
1375 fprintf(stderr, "\n%s", arrow);
1379 static void ReportException(Environment* env,
1381 Handle<Message> message) {
1382 HandleScope scope(env->isolate());
1384 AppendExceptionLine(env, er, message);
1386 Local<Value> trace_value;
1388 if (er->IsUndefined() || er->IsNull())
1389 trace_value = Undefined(env->isolate());
1391 trace_value = er->ToObject()->Get(env->stack_string());
1393 String::Utf8Value trace(trace_value);
1395 // range errors have a trace member set to undefined
1396 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1397 fprintf(stderr, "%s\n", *trace);
1399 // this really only happens for RangeErrors, since they're the only
1400 // kind that won't have all this info in the trace, or when non-Error
1401 // objects are thrown manually.
1402 Local<Value> message;
1405 if (er->IsObject()) {
1406 Local<Object> err_obj = er.As<Object>();
1407 message = err_obj->Get(env->message_string());
1408 name = err_obj->Get(FIXED_ONE_BYTE_STRING(env->isolate(), "name"));
1411 if (message.IsEmpty() ||
1412 message->IsUndefined() ||
1414 name->IsUndefined()) {
1415 // Not an error object. Just print as-is.
1416 String::Utf8Value message(er);
1417 fprintf(stderr, "%s\n", *message);
1419 String::Utf8Value name_string(name);
1420 String::Utf8Value message_string(message);
1421 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1429 static void ReportException(Environment* env, const TryCatch& try_catch) {
1430 ReportException(env, try_catch.Exception(), try_catch.Message());
1434 // Executes a str within the current v8 context.
1435 static Local<Value> ExecuteString(Environment* env,
1436 Handle<String> source,
1437 Handle<Value> filename) {
1438 HandleScope scope(env->isolate());
1441 // try_catch must be nonverbose to disable FatalException() handler,
1442 // we will handle exceptions ourself.
1443 try_catch.SetVerbose(false);
1445 Local<v8::Script> script = v8::Script::Compile(source, filename);
1446 if (script.IsEmpty()) {
1447 ReportException(env, try_catch);
1451 Local<Value> result = script->Run();
1452 if (result.IsEmpty()) {
1453 ReportException(env, try_catch);
1457 return scope.Close(result);
1461 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1462 HandleScope scope(node_isolate);
1464 Local<Array> ary = Array::New();
1468 QUEUE_FOREACH(q, &req_wrap_queue) {
1469 ReqWrap<uv_req_t>* w = CONTAINER_OF(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1470 if (w->persistent().IsEmpty())
1472 ary->Set(i++, w->object());
1475 args.GetReturnValue().Set(ary);
1479 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1480 // implemented here for consistency with GetActiveRequests().
1481 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1482 HandleScope scope(node_isolate);
1484 Local<Array> ary = Array::New();
1488 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1490 QUEUE_FOREACH(q, &handle_wrap_queue) {
1491 HandleWrap* w = CONTAINER_OF(q, HandleWrap, handle_wrap_queue_);
1492 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref))
1494 Local<Object> object = w->object();
1495 Local<Value> owner = object->Get(owner_sym);
1496 if (owner->IsUndefined())
1498 ary->Set(i++, owner);
1501 args.GetReturnValue().Set(ary);
1505 static void Abort(const FunctionCallbackInfo<Value>& args) {
1510 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1511 HandleScope scope(node_isolate);
1513 if (args.Length() != 1 || !args[0]->IsString()) {
1514 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1517 String::Utf8Value path(args[0]);
1518 int err = uv_chdir(*path);
1520 return ThrowUVException(err, "uv_chdir");
1525 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1526 HandleScope scope(node_isolate);
1528 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1529 char buf[MAX_PATH * 4 + 1];
1531 char buf[PATH_MAX + 1];
1534 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1536 return ThrowUVException(err, "uv_cwd");
1539 buf[ARRAY_SIZE(buf) - 1] = '\0';
1540 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1542 args.GetReturnValue().Set(cwd);
1546 static void Umask(const FunctionCallbackInfo<Value>& args) {
1547 HandleScope scope(node_isolate);
1550 if (args.Length() < 1 || args[0]->IsUndefined()) {
1552 umask(static_cast<mode_t>(old));
1553 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1554 return ThrowTypeError("argument must be an integer or octal string.");
1557 if (args[0]->IsInt32()) {
1558 oct = args[0]->Uint32Value();
1561 String::Utf8Value str(args[0]);
1563 // Parse the octal string.
1564 for (int i = 0; i < str.length(); i++) {
1566 if (c > '7' || c < '0') {
1567 return ThrowTypeError("invalid octal string");
1573 old = umask(static_cast<mode_t>(oct));
1576 args.GetReturnValue().Set(old);
1580 #if defined(__POSIX__) && !defined(__ANDROID__)
1582 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1583 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1586 static uid_t uid_by_name(const char* name) {
1594 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1598 return uid_not_found;
1602 static char* name_by_uid(uid_t uid) {
1611 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1612 return strdup(pp->pw_name);
1623 static gid_t gid_by_name(const char* name) {
1631 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1635 return gid_not_found;
1639 #if 0 // For future use.
1640 static const char* name_by_gid(gid_t gid) {
1649 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1650 return strdup(pp->gr_name);
1662 static uid_t uid_by_name(Handle<Value> value) {
1663 if (value->IsUint32()) {
1664 return static_cast<uid_t>(value->Uint32Value());
1666 String::Utf8Value name(value);
1667 return uid_by_name(*name);
1672 static gid_t gid_by_name(Handle<Value> value) {
1673 if (value->IsUint32()) {
1674 return static_cast<gid_t>(value->Uint32Value());
1676 String::Utf8Value name(value);
1677 return gid_by_name(*name);
1682 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1683 // uid_t is an uint32_t on all supported platforms.
1684 args.GetReturnValue().Set(static_cast<uint32_t>(getuid()));
1688 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1689 // gid_t is an uint32_t on all supported platforms.
1690 args.GetReturnValue().Set(static_cast<uint32_t>(getgid()));
1694 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1695 HandleScope scope(node_isolate);
1697 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1698 return ThrowTypeError("setgid argument must be a number or a string");
1701 gid_t gid = gid_by_name(args[0]);
1703 if (gid == gid_not_found) {
1704 return ThrowError("setgid group id does not exist");
1708 return ThrowErrnoException(errno, "setgid");
1713 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1714 HandleScope scope(node_isolate);
1716 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1717 return ThrowTypeError("setuid argument must be a number or a string");
1720 uid_t uid = uid_by_name(args[0]);
1722 if (uid == uid_not_found) {
1723 return ThrowError("setuid user id does not exist");
1727 return ThrowErrnoException(errno, "setuid");
1732 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1733 HandleScope scope(node_isolate);
1735 int ngroups = getgroups(0, NULL);
1737 if (ngroups == -1) {
1738 return ThrowErrnoException(errno, "getgroups");
1741 gid_t* groups = new gid_t[ngroups];
1743 ngroups = getgroups(ngroups, groups);
1745 if (ngroups == -1) {
1747 return ThrowErrnoException(errno, "getgroups");
1750 Local<Array> groups_list = Array::New(ngroups);
1751 bool seen_egid = false;
1752 gid_t egid = getegid();
1754 for (int i = 0; i < ngroups; i++) {
1755 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1756 if (groups[i] == egid)
1762 if (seen_egid == false) {
1763 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1766 args.GetReturnValue().Set(groups_list);
1770 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1771 HandleScope scope(node_isolate);
1773 if (!args[0]->IsArray()) {
1774 return ThrowTypeError("argument 1 must be an array");
1777 Local<Array> groups_list = args[0].As<Array>();
1778 size_t size = groups_list->Length();
1779 gid_t* groups = new gid_t[size];
1781 for (size_t i = 0; i < size; i++) {
1782 gid_t gid = gid_by_name(groups_list->Get(i));
1784 if (gid == gid_not_found) {
1786 return ThrowError("group name not found");
1792 int rc = setgroups(size, groups);
1796 return ThrowErrnoException(errno, "setgroups");
1801 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1802 HandleScope scope(node_isolate);
1804 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1805 return ThrowTypeError("argument 1 must be a number or a string");
1808 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1809 return ThrowTypeError("argument 2 must be a number or a string");
1812 String::Utf8Value arg0(args[0]);
1817 if (args[0]->IsUint32()) {
1818 user = name_by_uid(args[0]->Uint32Value());
1826 return ThrowError("initgroups user not found");
1829 extra_group = gid_by_name(args[1]);
1831 if (extra_group == gid_not_found) {
1834 return ThrowError("initgroups extra group not found");
1837 int rc = initgroups(user, extra_group);
1844 return ThrowErrnoException(errno, "initgroups");
1848 #endif // __POSIX__ && !defined(__ANDROID__)
1851 void Exit(const FunctionCallbackInfo<Value>& args) {
1852 HandleScope scope(node_isolate);
1853 exit(args[0]->IntegerValue());
1857 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1858 HandleScope scope(node_isolate);
1860 if (uv_uptime(&uptime))
1862 args.GetReturnValue().Set(uptime - prog_start_time);
1866 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1867 HandleScope handle_scope(args.GetIsolate());
1868 Environment* env = Environment::GetCurrent(args.GetIsolate());
1871 int err = uv_resident_set_memory(&rss);
1873 return ThrowUVException(err, "uv_resident_set_memory");
1877 HeapStatistics v8_heap_stats;
1878 node_isolate->GetHeapStatistics(&v8_heap_stats);
1880 Local<Integer> heap_total =
1881 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(), node_isolate);
1882 Local<Integer> heap_used =
1883 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(), node_isolate);
1885 Local<Object> info = Object::New();
1886 info->Set(env->rss_string(), Number::New(node_isolate, rss));
1887 info->Set(env->heap_total_string(), heap_total);
1888 info->Set(env->heap_used_string(), heap_used);
1890 args.GetReturnValue().Set(info);
1894 void Kill(const FunctionCallbackInfo<Value>& args) {
1895 HandleScope scope(node_isolate);
1897 if (args.Length() != 2) {
1898 return ThrowError("Bad argument.");
1901 int pid = args[0]->IntegerValue();
1902 int sig = args[1]->Int32Value();
1903 int err = uv_kill(pid, sig);
1904 args.GetReturnValue().Set(err);
1907 // used in Hrtime() below
1908 #define NANOS_PER_SEC 1000000000
1910 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1911 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1912 // so this function instead returns an Array with 2 entries representing seconds
1913 // and nanoseconds, to avoid any integer overflow possibility.
1914 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1915 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1916 HandleScope scope(node_isolate);
1918 uint64_t t = uv_hrtime();
1920 if (args.Length() > 0) {
1921 // return a time diff tuple
1922 if (!args[0]->IsArray()) {
1923 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1925 Local<Array> inArray = Local<Array>::Cast(args[0]);
1926 uint64_t seconds = inArray->Get(0)->Uint32Value();
1927 uint64_t nanos = inArray->Get(1)->Uint32Value();
1928 t -= (seconds * NANOS_PER_SEC) + nanos;
1931 Local<Array> tuple = Array::New(2);
1932 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1933 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1934 args.GetReturnValue().Set(tuple);
1937 extern "C" void node_module_register(void* m) {
1938 struct node_module* mp = reinterpret_cast<struct node_module*>(m);
1940 if (mp->nm_flags & NM_F_BUILTIN) {
1941 mp->nm_link = modlist_builtin;
1942 modlist_builtin = mp;
1944 assert(modpending == NULL);
1949 struct node_module* get_builtin_module(const char* name) {
1950 struct node_module* mp;
1952 for (mp = modlist_builtin; mp != NULL; mp = mp->nm_link) {
1953 if (strcmp(mp->nm_modname, name) == 0)
1957 assert(mp == NULL || (mp->nm_flags & NM_F_BUILTIN) != 0);
1961 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1963 // DLOpen is process.dlopen(module, filename).
1964 // Used to load 'module.node' dynamically shared objects.
1966 // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
1967 // when two contexts try to load the same shared object. Maybe have a shadow
1968 // cache that's a plain C list or hash table that's shared across contexts?
1969 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1970 HandleScope handle_scope(args.GetIsolate());
1971 Environment* env = Environment::GetCurrent(args.GetIsolate());
1972 struct node_module* mp;
1975 if (args.Length() < 2) {
1976 ThrowError("process.dlopen takes exactly 2 arguments.");
1980 Local<Object> module = args[0]->ToObject(); // Cast
1981 String::Utf8Value filename(args[1]); // Cast
1983 Local<String> exports_string = env->exports_string();
1984 Local<Object> exports = module->Get(exports_string)->ToObject();
1986 if (uv_dlopen(*filename, &lib)) {
1987 Local<String> errmsg = OneByteString(env->isolate(), uv_dlerror(&lib));
1989 // Windows needs to add the filename into the error message
1990 errmsg = String::Concat(errmsg, args[1]->ToString());
1992 ThrowException(Exception::Error(errmsg));
1997 * Objects containing v14 or later modules will have registered themselves
1998 * on the pending list. Activate all of them now. At present, only one
1999 * module per object is supported.
2005 ThrowError("Module did not self-register.");
2008 if (mp->nm_version != NODE_MODULE_VERSION) {
2012 "Module version mismatch. Expected %d, got %d.",
2013 NODE_MODULE_VERSION, mp->nm_version);
2017 if (mp->nm_flags & NM_F_BUILTIN) {
2018 ThrowError("Built-in module self-registered.");
2022 mp->nm_dso_handle = lib.handle;
2023 mp->nm_link = modlist_addon;
2026 if (mp->nm_context_register_func != NULL) {
2027 mp->nm_context_register_func(exports, module, env->context(), mp->nm_priv);
2028 } else if (mp->nm_register_func != NULL) {
2029 mp->nm_register_func(exports, module, mp->nm_priv);
2031 ThrowError("Module has no declared entry point.");
2035 // Tell coverity that 'handle' should not be freed when we return.
2036 // coverity[leaked_storage]
2040 static void OnFatalError(const char* location, const char* message) {
2042 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
2044 fprintf(stderr, "FATAL ERROR: %s\n", message);
2051 NO_RETURN void FatalError(const char* location, const char* message) {
2052 OnFatalError(location, message);
2053 // to supress compiler warning
2058 void FatalException(Handle<Value> error, Handle<Message> message) {
2059 HandleScope scope(node_isolate);
2061 Environment* env = Environment::GetCurrent(node_isolate);
2062 Local<Object> process_object = env->process_object();
2063 Local<String> fatal_exception_string = env->fatal_exception_string();
2064 Local<Function> fatal_exception_function =
2065 process_object->Get(fatal_exception_string).As<Function>();
2067 if (!fatal_exception_function->IsFunction()) {
2068 // failed before the process._fatalException function was added!
2069 // this is probably pretty bad. Nothing to do but report and exit.
2070 ReportException(env, error, message);
2074 TryCatch fatal_try_catch;
2076 // Do not call FatalException when _fatalException handler throws
2077 fatal_try_catch.SetVerbose(false);
2079 // this will return true if the JS layer handled it, false otherwise
2080 Local<Value> caught =
2081 fatal_exception_function->Call(process_object, 1, &error);
2083 if (fatal_try_catch.HasCaught()) {
2084 // the fatal exception function threw, so we must exit
2085 ReportException(env, fatal_try_catch);
2089 if (false == caught->BooleanValue()) {
2090 ReportException(env, error, message);
2096 void FatalException(const TryCatch& try_catch) {
2097 HandleScope scope(node_isolate);
2098 // TODO(bajtos) do not call FatalException if try_catch is verbose
2099 // (requires V8 API to expose getter for try_catch.is_verbose_)
2100 FatalException(try_catch.Exception(), try_catch.Message());
2104 void OnMessage(Handle<Message> message, Handle<Value> error) {
2105 // The current version of V8 sends messages for errors only
2106 // (thus `error` is always set).
2107 FatalException(error, message);
2111 static void Binding(const FunctionCallbackInfo<Value>& args) {
2112 HandleScope handle_scope(args.GetIsolate());
2113 Environment* env = Environment::GetCurrent(args.GetIsolate());
2115 Local<String> module = args[0]->ToString();
2116 String::Utf8Value module_v(module);
2118 Local<Object> cache = env->binding_cache_object();
2119 Local<Object> exports;
2121 if (cache->Has(module)) {
2122 exports = cache->Get(module)->ToObject();
2123 args.GetReturnValue().Set(exports);
2127 // Append a string to process.moduleLoadList
2129 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
2131 Local<Array> modules = env->module_load_list_array();
2132 uint32_t l = modules->Length();
2133 modules->Set(l, OneByteString(node_isolate, buf));
2135 node_module* mod = get_builtin_module(*module_v);
2137 exports = Object::New();
2138 // Internal bindings don't have a "module" object, only exports.
2139 assert(mod->nm_register_func == NULL);
2140 assert(mod->nm_context_register_func != NULL);
2141 Local<Value> unused = Undefined(env->isolate());
2142 mod->nm_context_register_func(exports, unused,
2143 env->context(), mod->nm_priv);
2144 cache->Set(module, exports);
2145 } else if (!strcmp(*module_v, "constants")) {
2146 exports = Object::New();
2147 DefineConstants(exports);
2148 cache->Set(module, exports);
2149 } else if (!strcmp(*module_v, "natives")) {
2150 exports = Object::New();
2151 DefineJavaScript(exports);
2152 cache->Set(module, exports);
2154 return ThrowError("No such module");
2157 args.GetReturnValue().Set(exports);
2161 static void ProcessTitleGetter(Local<String> property,
2162 const PropertyCallbackInfo<Value>& info) {
2163 HandleScope scope(node_isolate);
2165 uv_get_process_title(buffer, sizeof(buffer));
2166 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2170 static void ProcessTitleSetter(Local<String> property,
2172 const PropertyCallbackInfo<void>& info) {
2173 HandleScope scope(node_isolate);
2174 String::Utf8Value title(value);
2175 // TODO(piscisaureus): protect with a lock
2176 uv_set_process_title(*title);
2180 static void EnvGetter(Local<String> property,
2181 const PropertyCallbackInfo<Value>& info) {
2182 HandleScope scope(node_isolate);
2184 String::Utf8Value key(property);
2185 const char* val = getenv(*key);
2187 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2190 String::Value key(property);
2191 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2192 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2194 ARRAY_SIZE(buffer));
2195 // If result >= sizeof buffer the buffer was too small. That should never
2196 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2198 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2199 result < ARRAY_SIZE(buffer)) {
2200 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2201 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2202 return info.GetReturnValue().Set(rc);
2205 // Not found. Fetch from prototype.
2206 info.GetReturnValue().Set(
2207 info.Data().As<Object>()->Get(property));
2211 static void EnvSetter(Local<String> property,
2213 const PropertyCallbackInfo<Value>& info) {
2214 HandleScope scope(node_isolate);
2216 String::Utf8Value key(property);
2217 String::Utf8Value val(value);
2218 setenv(*key, *val, 1);
2220 String::Value key(property);
2221 String::Value val(value);
2222 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2223 // Environment variables that start with '=' are read-only.
2224 if (key_ptr[0] != L'=') {
2225 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2228 // Whether it worked or not, always return rval.
2229 info.GetReturnValue().Set(value);
2233 static void EnvQuery(Local<String> property,
2234 const PropertyCallbackInfo<Integer>& info) {
2235 HandleScope scope(node_isolate);
2236 int32_t rc = -1; // Not found unless proven otherwise.
2238 String::Utf8Value key(property);
2242 String::Value key(property);
2243 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2244 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2245 GetLastError() == ERROR_SUCCESS) {
2247 if (key_ptr[0] == L'=') {
2248 // Environment variables that start with '=' are hidden and read-only.
2249 rc = static_cast<int32_t>(v8::ReadOnly) |
2250 static_cast<int32_t>(v8::DontDelete) |
2251 static_cast<int32_t>(v8::DontEnum);
2256 info.GetReturnValue().Set(rc);
2260 static void EnvDeleter(Local<String> property,
2261 const PropertyCallbackInfo<Boolean>& info) {
2262 HandleScope scope(node_isolate);
2265 String::Utf8Value key(property);
2266 rc = getenv(*key) != NULL;
2270 String::Value key(property);
2271 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2272 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2273 // Deletion failed. Return true if the key wasn't there in the first place,
2274 // false if it is still there.
2275 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2276 GetLastError() != ERROR_SUCCESS;
2279 info.GetReturnValue().Set(rc);
2283 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2284 HandleScope scope(node_isolate);
2287 while (environ[size])
2290 Local<Array> env = Array::New(size);
2292 for (int i = 0; i < size; ++i) {
2293 const char* var = environ[i];
2294 const char* s = strchr(var, '=');
2295 const int length = s ? s - var : strlen(var);
2296 Local<String> name = String::NewFromUtf8(node_isolate,
2298 String::kNormalString,
2303 WCHAR* environment = GetEnvironmentStringsW();
2304 if (environment == NULL)
2305 return; // This should not happen.
2306 Local<Array> env = Array::New();
2307 WCHAR* p = environment;
2309 while (*p != NULL) {
2312 // If the key starts with '=' it is a hidden environment variable.
2316 s = wcschr(p, L'=');
2321 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2322 const size_t two_byte_buffer_len = s - p;
2323 Local<String> value = String::NewFromTwoByte(node_isolate,
2325 String::kNormalString,
2326 two_byte_buffer_len);
2327 env->Set(i++, value);
2328 p = s + wcslen(s) + 1;
2330 FreeEnvironmentStringsW(environment);
2333 info.GetReturnValue().Set(env);
2337 static Handle<Object> GetFeatures() {
2338 HandleScope scope(node_isolate);
2340 Local<Object> obj = Object::New();
2341 #if defined(DEBUG) && DEBUG
2342 Local<Value> debug = True(node_isolate);
2344 Local<Value> debug = False(node_isolate);
2345 #endif // defined(DEBUG) && DEBUG
2347 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2349 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2350 // TODO(bnoordhuis) ping libuv
2351 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2353 #ifdef OPENSSL_NPN_NEGOTIATED
2354 Local<Boolean> tls_npn = True(node_isolate);
2356 Local<Boolean> tls_npn = False(node_isolate);
2358 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"), tls_npn);
2360 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2361 Local<Boolean> tls_sni = True(node_isolate);
2363 Local<Boolean> tls_sni = False(node_isolate);
2365 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"), tls_sni);
2367 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2368 Boolean::New(get_builtin_module("crypto") != NULL));
2370 return scope.Close(obj);
2374 static void DebugPortGetter(Local<String> property,
2375 const PropertyCallbackInfo<Value>& info) {
2376 HandleScope scope(node_isolate);
2377 info.GetReturnValue().Set(debug_port);
2381 static void DebugPortSetter(Local<String> property,
2383 const PropertyCallbackInfo<void>& info) {
2384 HandleScope scope(node_isolate);
2385 debug_port = value->NumberValue();
2389 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2390 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2391 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2394 void NeedImmediateCallbackGetter(Local<String> property,
2395 const PropertyCallbackInfo<Value>& info) {
2396 HandleScope handle_scope(info.GetIsolate());
2397 Environment* env = Environment::GetCurrent(info.GetIsolate());
2398 const uv_check_t* immediate_check_handle = env->immediate_check_handle();
2399 bool active = uv_is_active(
2400 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2401 info.GetReturnValue().Set(active);
2405 static void NeedImmediateCallbackSetter(
2406 Local<String> property,
2408 const PropertyCallbackInfo<void>& info) {
2409 HandleScope handle_scope(info.GetIsolate());
2410 Environment* env = Environment::GetCurrent(info.GetIsolate());
2412 uv_check_t* immediate_check_handle = env->immediate_check_handle();
2413 bool active = uv_is_active(
2414 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2416 if (active == value->BooleanValue())
2419 uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
2422 uv_check_stop(immediate_check_handle);
2423 uv_idle_stop(immediate_idle_handle);
2425 uv_check_start(immediate_check_handle, CheckImmediate);
2426 // Idle handle is needed only to stop the event loop from blocking in poll.
2427 uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
2432 void SetIdle(uv_prepare_t* handle, int) {
2433 Environment* env = Environment::from_idle_prepare_handle(handle);
2434 env->isolate()->GetCpuProfiler()->SetIdle(true);
2438 void ClearIdle(uv_check_t* handle, int) {
2439 Environment* env = Environment::from_idle_check_handle(handle);
2440 env->isolate()->GetCpuProfiler()->SetIdle(false);
2444 void StartProfilerIdleNotifier(Environment* env) {
2445 uv_prepare_start(env->idle_prepare_handle(), SetIdle);
2446 uv_check_start(env->idle_check_handle(), ClearIdle);
2450 void StopProfilerIdleNotifier(Environment* env) {
2451 uv_prepare_stop(env->idle_prepare_handle());
2452 uv_check_stop(env->idle_check_handle());
2456 void StartProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2457 HandleScope handle_scope(args.GetIsolate());
2458 Environment* env = Environment::GetCurrent(args.GetIsolate());
2459 StartProfilerIdleNotifier(env);
2463 void StopProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2464 HandleScope handle_scope(args.GetIsolate());
2465 Environment* env = Environment::GetCurrent(args.GetIsolate());
2466 StopProfilerIdleNotifier(env);
2470 #define READONLY_PROPERTY(obj, str, var) \
2472 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2476 void SetupProcessObject(Environment* env,
2478 const char* const* argv,
2480 const char* const* exec_argv) {
2481 HandleScope scope(node_isolate);
2483 Local<Object> process = env->process_object();
2485 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2487 ProcessTitleSetter);
2490 READONLY_PROPERTY(process,
2492 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2494 // process.moduleLoadList
2495 READONLY_PROPERTY(process,
2497 env->module_load_list_array());
2500 Local<Object> versions = Object::New();
2501 READONLY_PROPERTY(process, "versions", versions);
2503 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2505 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2506 READONLY_PROPERTY(versions,
2508 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2510 // +1 to get rid of the leading 'v'
2511 READONLY_PROPERTY(versions,
2513 OneByteString(node_isolate, NODE_VERSION + 1));
2514 READONLY_PROPERTY(versions,
2516 OneByteString(node_isolate, V8::GetVersion()));
2517 READONLY_PROPERTY(versions,
2519 OneByteString(node_isolate, uv_version_string()));
2520 READONLY_PROPERTY(versions,
2522 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2524 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2525 READONLY_PROPERTY(versions,
2527 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2530 // Stupid code to slice out the version string.
2531 { // NOLINT(whitespace/braces)
2534 for (i = j = 0, k = sizeof(OPENSSL_VERSION_TEXT) - 1; i < k; ++i) {
2535 c = OPENSSL_VERSION_TEXT[i];
2536 if ('0' <= c && c <= '9') {
2537 for (j = i + 1; j < k; ++j) {
2538 c = OPENSSL_VERSION_TEXT[j];
2548 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2553 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2556 READONLY_PROPERTY(process,
2558 OneByteString(node_isolate, PLATFORM));
2561 Local<Array> arguments = Array::New(argc);
2562 for (int i = 0; i < argc; ++i) {
2563 arguments->Set(i, String::NewFromUtf8(node_isolate, argv[i]));
2565 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2568 Local<Array> exec_arguments = Array::New(exec_argc);
2569 for (int i = 0; i < exec_argc; ++i) {
2570 exec_arguments->Set(i, String::NewFromUtf8(node_isolate, exec_argv[i]));
2572 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_arguments);
2574 // create process.env
2575 Local<ObjectTemplate> process_env_template = ObjectTemplate::New();
2576 process_env_template->SetNamedPropertyHandler(EnvGetter,
2582 Local<Object> process_env = process_env_template->NewInstance();
2583 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), process_env);
2585 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2586 READONLY_PROPERTY(process, "features", GetFeatures());
2587 process->SetAccessor(
2588 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2589 NeedImmediateCallbackGetter,
2590 NeedImmediateCallbackSetter);
2594 READONLY_PROPERTY(process,
2596 String::NewFromUtf8(node_isolate, eval_string));
2601 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2604 // -i, --interactive
2606 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2610 if (no_deprecation) {
2611 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2614 // --throw-deprecation
2615 if (throw_deprecation) {
2616 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2619 // --trace-deprecation
2620 if (trace_deprecation) {
2621 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2624 size_t exec_path_len = 2 * PATH_MAX;
2625 char* exec_path = new char[exec_path_len];
2626 Local<String> exec_path_value;
2627 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2628 exec_path_value = String::NewFromUtf8(node_isolate,
2630 String::kNormalString,
2633 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2635 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2639 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2643 // define various internal methods
2644 NODE_SET_METHOD(process,
2645 "_startProfilerIdleNotifier",
2646 StartProfilerIdleNotifier);
2647 NODE_SET_METHOD(process,
2648 "_stopProfilerIdleNotifier",
2649 StopProfilerIdleNotifier);
2650 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2651 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2652 NODE_SET_METHOD(process, "reallyExit", Exit);
2653 NODE_SET_METHOD(process, "abort", Abort);
2654 NODE_SET_METHOD(process, "chdir", Chdir);
2655 NODE_SET_METHOD(process, "cwd", Cwd);
2657 NODE_SET_METHOD(process, "umask", Umask);
2659 #if defined(__POSIX__) && !defined(__ANDROID__)
2660 NODE_SET_METHOD(process, "getuid", GetUid);
2661 NODE_SET_METHOD(process, "setuid", SetUid);
2663 NODE_SET_METHOD(process, "setgid", SetGid);
2664 NODE_SET_METHOD(process, "getgid", GetGid);
2666 NODE_SET_METHOD(process, "getgroups", GetGroups);
2667 NODE_SET_METHOD(process, "setgroups", SetGroups);
2668 NODE_SET_METHOD(process, "initgroups", InitGroups);
2669 #endif // __POSIX__ && !defined(__ANDROID__)
2671 NODE_SET_METHOD(process, "_kill", Kill);
2673 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2674 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2675 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2677 NODE_SET_METHOD(process, "hrtime", Hrtime);
2679 NODE_SET_METHOD(process, "dlopen", DLOpen);
2681 NODE_SET_METHOD(process, "uptime", Uptime);
2682 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2684 NODE_SET_METHOD(process, "binding", Binding);
2686 NODE_SET_METHOD(process, "_setupAsyncListener", SetupAsyncListener);
2687 NODE_SET_METHOD(process, "_setupNextTick", SetupNextTick);
2688 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2690 // values use to cross communicate with processNextTick
2691 Local<Object> tick_info_obj = Object::New();
2692 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
2693 env->tick_info()->fields(),
2694 kExternalUnsignedIntArray,
2695 env->tick_info()->fields_count());
2696 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfo"), tick_info_obj);
2698 // pre-set _events object for faster emit checks
2699 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2703 #undef READONLY_PROPERTY
2706 static void AtExit() {
2707 uv_tty_reset_mode();
2711 static void SignalExit(int signal) {
2712 uv_tty_reset_mode();
2713 _exit(128 + signal);
2717 // Most of the time, it's best to use `console.error` to write
2718 // to the process.stderr stream. However, in some cases, such as
2719 // when debugging the stream.Writable class or the process.nextTick
2720 // function, it is useful to bypass JavaScript entirely.
2721 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2722 HandleScope scope(node_isolate);
2724 assert(args.Length() == 1 && args[0]->IsString() &&
2725 "must be called with a single string");
2727 String::Utf8Value message(args[0]);
2728 fprintf(stderr, "%s\n", *message);
2733 void Load(Environment* env) {
2734 HandleScope handle_scope(node_isolate);
2736 // Compile, execute the src/node.js file. (Which was included as static C
2737 // string in node_natives.h. 'natve_node' is the string containing that
2740 // The node.js file returns a function 'f'
2745 // Disable verbose mode to stop FatalException() handler from trying
2746 // to handle the exception. Errors this early in the start-up phase
2747 // are not safe to ignore.
2748 try_catch.SetVerbose(false);
2750 Local<String> script_name = FIXED_ONE_BYTE_STRING(env->isolate(), "node.js");
2751 Local<Value> f_value = ExecuteString(env, MainSource(), script_name);
2752 if (try_catch.HasCaught()) {
2753 ReportException(env, try_catch);
2756 assert(f_value->IsFunction());
2757 Local<Function> f = Local<Function>::Cast(f_value);
2759 // Now we call 'f' with the 'process' variable that we've built up with
2760 // all our bindings. Inside node.js we'll take care of assigning things to
2763 // We start the process this way in order to be more modular. Developers
2764 // who do not like how 'src/node.js' setups the module system but do like
2765 // Node's I/O bindings may want to replace 'f' with their own function.
2767 // Add a reference to the global object
2768 Local<Object> global = env->context()->Global();
2770 #if defined HAVE_DTRACE || defined HAVE_ETW
2774 #if defined HAVE_PERFCTR
2775 InitPerfCounters(global);
2778 // Enable handling of uncaught exceptions
2779 // (FatalException(), break on uncaught exception in debugger)
2781 // This is not strictly necessary since it's almost impossible
2782 // to attach the debugger fast enought to break on exception
2783 // thrown during process startup.
2784 try_catch.SetVerbose(true);
2786 NODE_SET_METHOD(env->process_object(), "_rawDebug", RawDebug);
2788 Local<Value> arg = env->process_object();
2789 f->Call(global, 1, &arg);
2792 static void PrintHelp();
2794 static bool ParseDebugOpt(const char* arg) {
2795 const char* port = NULL;
2797 if (!strcmp(arg, "--debug")) {
2798 use_debug_agent = true;
2799 } else if (!strncmp(arg, "--debug=", sizeof("--debug=") - 1)) {
2800 use_debug_agent = true;
2801 port = arg + sizeof("--debug=") - 1;
2802 } else if (!strcmp(arg, "--debug-brk")) {
2803 use_debug_agent = true;
2804 debug_wait_connect = true;
2805 } else if (!strncmp(arg, "--debug-brk=", sizeof("--debug-brk=") - 1)) {
2806 use_debug_agent = true;
2807 debug_wait_connect = true;
2808 port = arg + sizeof("--debug-brk=") - 1;
2809 } else if (!strncmp(arg, "--debug-port=", sizeof("--debug-port=") - 1)) {
2810 port = arg + sizeof("--debug-port=") - 1;
2816 debug_port = atoi(port);
2817 if (debug_port < 1024 || debug_port > 65535) {
2818 fprintf(stderr, "Debug port must be in range 1024 to 65535.\n");
2827 static void PrintHelp() {
2828 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2829 " node debug script.js [arguments] \n"
2832 " -v, --version print node's version\n"
2833 " -e, --eval script evaluate script\n"
2834 " -p, --print evaluate script and print result\n"
2835 " -i, --interactive always enter the REPL even if stdin\n"
2836 " does not appear to be a terminal\n"
2837 " --no-deprecation silence deprecation warnings\n"
2838 " --trace-deprecation show stack traces on deprecations\n"
2839 " --v8-options print v8 command line options\n"
2840 " --max-stack-size=val set max v8 stack size (bytes)\n"
2842 "Environment variables:\n"
2844 "NODE_PATH ';'-separated list of directories\n"
2846 "NODE_PATH ':'-separated list of directories\n"
2848 " prefixed to the module search path.\n"
2849 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2850 " global contexts.\n"
2851 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2853 "Documentation can be found at http://nodejs.org/\n");
2857 // Parse command line arguments.
2859 // argv is modified in place. exec_argv and v8_argv are out arguments that
2860 // ParseArgs() allocates memory for and stores a pointer to the output
2861 // vector in. The caller should free them with delete[].
2865 // * argv contains the arguments with node and V8 options filtered out.
2866 // * exec_argv contains both node and V8 options and nothing else.
2867 // * v8_argv contains argv[0] plus any V8 options
2868 static void ParseArgs(int* argc,
2871 const char*** exec_argv,
2873 const char*** v8_argv) {
2874 const unsigned int nargs = static_cast<unsigned int>(*argc);
2875 const char** new_exec_argv = new const char*[nargs];
2876 const char** new_v8_argv = new const char*[nargs];
2877 const char** new_argv = new const char*[nargs];
2879 for (unsigned int i = 0; i < nargs; ++i) {
2880 new_exec_argv[i] = NULL;
2881 new_v8_argv[i] = NULL;
2885 // exec_argv starts with the first option, the other two start with argv[0].
2886 unsigned int new_exec_argc = 0;
2887 unsigned int new_v8_argc = 1;
2888 unsigned int new_argc = 1;
2889 new_v8_argv[0] = argv[0];
2890 new_argv[0] = argv[0];
2892 unsigned int index = 1;
2893 while (index < nargs && argv[index][0] == '-') {
2894 const char* const arg = argv[index];
2895 unsigned int args_consumed = 1;
2897 if (ParseDebugOpt(arg)) {
2898 // Done, consumed by ParseDebugOpt().
2899 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2900 printf("%s\n", NODE_VERSION);
2902 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2905 } else if (strcmp(arg, "--eval") == 0 ||
2906 strcmp(arg, "-e") == 0 ||
2907 strcmp(arg, "--print") == 0 ||
2908 strcmp(arg, "-pe") == 0 ||
2909 strcmp(arg, "-p") == 0) {
2910 bool is_eval = strchr(arg, 'e') != NULL;
2911 bool is_print = strchr(arg, 'p') != NULL;
2912 print_eval = print_eval || is_print;
2913 // --eval, -e and -pe always require an argument.
2914 if (is_eval == true) {
2916 eval_string = argv[index + 1];
2917 if (eval_string == NULL) {
2918 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
2921 } else if ((index + 1 < nargs) &&
2922 argv[index + 1] != NULL &&
2923 argv[index + 1][0] != '-') {
2925 eval_string = argv[index + 1];
2926 if (strncmp(eval_string, "\\-", 2) == 0) {
2927 // Starts with "\\-": escaped expression, drop the backslash.
2931 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2933 } else if (strcmp(arg, "--no-deprecation") == 0) {
2934 no_deprecation = true;
2935 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2936 trace_deprecation = true;
2937 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2938 throw_deprecation = true;
2939 } else if (strcmp(arg, "--v8-options") == 0) {
2940 new_v8_argv[new_v8_argc] = "--help";
2943 // V8 option. Pass through as-is.
2944 new_v8_argv[new_v8_argc] = arg;
2948 memcpy(new_exec_argv + new_exec_argc,
2950 args_consumed * sizeof(*argv));
2952 new_exec_argc += args_consumed;
2953 index += args_consumed;
2956 // Copy remaining arguments.
2957 const unsigned int args_left = nargs - index;
2958 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
2959 new_argc += args_left;
2961 *exec_argc = new_exec_argc;
2962 *exec_argv = new_exec_argv;
2963 *v8_argc = new_v8_argc;
2964 *v8_argv = new_v8_argv;
2966 // Copy new_argv over argv and update argc.
2967 memcpy(argv, new_argv, new_argc * sizeof(*argv));
2969 *argc = static_cast<int>(new_argc);
2973 // Called from V8 Debug Agent TCP thread.
2974 static void DispatchMessagesDebugAgentCallback() {
2975 uv_async_send(&dispatch_debug_messages_async);
2979 // Called from the main thread.
2980 static void EnableDebug(bool wait_connect) {
2981 assert(debugger_running == false);
2982 Isolate* isolate = node_isolate; // TODO(bnoordhuis) Multi-isolate support.
2983 Isolate::Scope isolate_scope(isolate);
2984 HandleScope handle_scope(isolate);
2985 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2987 debugger_running = v8::Debug::EnableAgent("node " NODE_VERSION,
2990 if (debugger_running == false) {
2991 fprintf(stderr, "Starting debugger on port %d failed\n", debug_port);
2995 fprintf(stderr, "Debugger listening on port %d\n", debug_port);
2998 Environment* env = Environment::GetCurrentChecked(isolate);
3000 return; // Still starting up.
3002 Context::Scope context_scope(env->context());
3003 Local<Object> message = Object::New();
3004 message->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "cmd"),
3005 FIXED_ONE_BYTE_STRING(env->isolate(), "NODE_DEBUG_ENABLED"));
3006 Local<Value> argv[] = {
3007 FIXED_ONE_BYTE_STRING(env->isolate(), "internalMessage"),
3010 MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(argv), argv);
3014 // Called from the main thread.
3015 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
3016 if (debugger_running == false) {
3017 fprintf(stderr, "Starting debugger agent.\n");
3020 Isolate::Scope isolate_scope(node_isolate);
3021 v8::Debug::ProcessDebugMessages();
3026 static volatile sig_atomic_t caught_early_debug_signal;
3029 static void EarlyDebugSignalHandler(int signo) {
3030 caught_early_debug_signal = 1;
3034 static void InstallEarlyDebugSignalHandler() {
3035 struct sigaction sa;
3036 memset(&sa, 0, sizeof(sa));
3037 sa.sa_handler = EarlyDebugSignalHandler;
3038 sigaction(SIGUSR1, &sa, NULL);
3042 static void EnableDebugSignalHandler(int signo) {
3043 // Call only async signal-safe functions here!
3044 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
3045 uv_async_send(&dispatch_debug_messages_async);
3049 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
3050 struct sigaction sa;
3051 memset(&sa, 0, sizeof(sa));
3052 sa.sa_handler = handler;
3053 sigfillset(&sa.sa_mask);
3054 sigaction(signal, &sa, NULL);
3058 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3059 HandleScope scope(node_isolate);
3061 if (args.Length() != 1) {
3062 return ThrowError("Invalid number of arguments.");
3068 pid = args[0]->IntegerValue();
3069 r = kill(pid, SIGUSR1);
3071 return ThrowErrnoException(errno, "kill");
3076 static int RegisterDebugSignalHandler() {
3077 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3078 RegisterSignalHandler(SIGUSR1, EnableDebugSignalHandler);
3079 // If we caught a SIGUSR1 during the bootstrap process, re-raise it
3080 // now that the debugger infrastructure is in place.
3081 if (caught_early_debug_signal)
3089 DWORD WINAPI EnableDebugThreadProc(void* arg) {
3090 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
3091 uv_async_send(&dispatch_debug_messages_async);
3096 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
3098 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
3102 static int RegisterDebugSignalHandler() {
3103 wchar_t mapping_name[32];
3104 HANDLE mapping_handle;
3106 LPTHREAD_START_ROUTINE* handler;
3108 pid = GetCurrentProcessId();
3110 if (GetDebugSignalHandlerMappingName(pid,
3112 ARRAY_SIZE(mapping_name)) < 0) {
3116 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
3122 if (mapping_handle == NULL) {
3126 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3127 MapViewOfFile(mapping_handle,
3128 FILE_MAP_ALL_ACCESS,
3132 if (handler == NULL) {
3133 CloseHandle(mapping_handle);
3137 *handler = EnableDebugThreadProc;
3139 UnmapViewOfFile(static_cast<void*>(handler));
3145 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3146 HandleScope scope(node_isolate);
3148 HANDLE process = NULL;
3149 HANDLE thread = NULL;
3150 HANDLE mapping = NULL;
3151 wchar_t mapping_name[32];
3152 LPTHREAD_START_ROUTINE* handler = NULL;
3154 if (args.Length() != 1) {
3155 ThrowError("Invalid number of arguments.");
3159 pid = (DWORD) args[0]->IntegerValue();
3161 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
3162 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
3166 if (process == NULL) {
3167 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
3171 if (GetDebugSignalHandlerMappingName(pid,
3173 ARRAY_SIZE(mapping_name)) < 0) {
3174 ThrowErrnoException(errno, "sprintf");
3178 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
3179 if (mapping == NULL) {
3180 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
3184 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3185 MapViewOfFile(mapping,
3190 if (handler == NULL || *handler == NULL) {
3191 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
3195 thread = CreateRemoteThread(process,
3202 if (thread == NULL) {
3203 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
3207 // Wait for the thread to terminate
3208 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3209 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
3214 if (process != NULL)
3215 CloseHandle(process);
3217 CloseHandle(thread);
3218 if (handler != NULL)
3219 UnmapViewOfFile(handler);
3220 if (mapping != NULL)
3221 CloseHandle(mapping);
3226 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3227 v8::Debug::DebugBreak(node_isolate);
3231 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3232 if (debugger_running) {
3233 v8::Debug::DisableAgent();
3234 debugger_running = false;
3239 void Init(int* argc,
3242 const char*** exec_argv) {
3243 // Initialize prog_start_time to get relative uptime.
3244 uv_uptime(&prog_start_time);
3246 // Make inherited handles noninheritable.
3247 uv_disable_stdio_inheritance();
3249 // init async debug messages dispatching
3250 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3251 uv_async_init(uv_default_loop(),
3252 &dispatch_debug_messages_async,
3253 DispatchDebugMessagesAsyncCallback);
3254 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3256 // Parse a few arguments which are specific to Node.
3258 const char** v8_argv;
3259 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3261 // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
3262 // manually? That would give us a little more control over its runtime
3263 // behavior but it could also interfere with the user's intentions in ways
3264 // we fail to anticipate. Dillema.
3265 for (int i = 1; i < v8_argc; ++i) {
3266 if (strncmp(v8_argv[i], "--prof", sizeof("--prof") - 1) == 0) {
3267 v8_is_profiling = true;
3272 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3273 // the argv array or the elements it points to.
3274 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3276 // Anything that's still in v8_argv is not a V8 or a node option.
3277 for (int i = 1; i < v8_argc; i++) {
3278 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3287 if (debug_wait_connect) {
3288 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3289 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3292 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3294 // Fetch a reference to the main isolate, so we have a reference to it
3295 // even when we need it to access it from another (debugger) thread.
3296 node_isolate = Isolate::GetCurrent();
3299 // Raise the open file descriptor limit.
3300 { // NOLINT (whitespace/braces)
3302 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3303 // Do a binary search for the limit.
3304 rlim_t min = lim.rlim_cur;
3305 rlim_t max = 1 << 20;
3306 // But if there's a defined upper bound, don't search, just set it.
3307 if (lim.rlim_max != RLIM_INFINITY) {
3312 lim.rlim_cur = min + (max - min) / 2;
3313 if (setrlimit(RLIMIT_NOFILE, &lim)) {
3318 } while (min + 1 < max);
3322 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3323 RegisterSignalHandler(SIGINT, SignalExit);
3324 RegisterSignalHandler(SIGTERM, SignalExit);
3327 V8::SetFatalErrorHandler(node::OnFatalError);
3328 V8::AddMessageListener(OnMessage);
3330 // If the --debug flag was specified then initialize the debug thread.
3331 if (use_debug_agent) {
3332 EnableDebug(debug_wait_connect);
3334 RegisterDebugSignalHandler();
3339 struct AtExitCallback {
3340 AtExitCallback* next_;
3341 void (*cb_)(void* arg);
3345 static AtExitCallback* at_exit_functions_;
3348 // TODO(bnoordhuis) Turn into per-context event.
3349 void RunAtExit(Environment* env) {
3350 AtExitCallback* p = at_exit_functions_;
3351 at_exit_functions_ = NULL;
3354 AtExitCallback* q = p->next_;
3362 void AtExit(void (*cb)(void* arg), void* arg) {
3363 AtExitCallback* p = new AtExitCallback;
3366 p->next_ = at_exit_functions_;
3367 at_exit_functions_ = p;
3371 int EmitExit(Environment* env) {
3372 // process.emit('exit')
3373 HandleScope handle_scope(env->isolate());
3374 Context::Scope context_scope(env->context());
3375 Local<Object> process_object = env->process_object();
3376 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3377 True(node_isolate));
3379 Handle<String> exitCode = FIXED_ONE_BYTE_STRING(node_isolate, "exitCode");
3380 int code = process_object->Get(exitCode)->IntegerValue();
3382 Local<Value> args[] = {
3383 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3384 Integer::New(code, node_isolate)
3387 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3389 // Reload exit code, it may be changed by `emit('exit')`
3390 return process_object->Get(exitCode)->IntegerValue();
3394 Environment* CreateEnvironment(Isolate* isolate,
3396 const char* const* argv,
3398 const char* const* exec_argv) {
3399 HandleScope handle_scope(isolate);
3401 Local<Context> context = Context::New(isolate);
3402 Context::Scope context_scope(context);
3403 Environment* env = Environment::New(context);
3405 uv_check_init(env->event_loop(), env->immediate_check_handle());
3407 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3408 uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3410 // Inform V8's CPU profiler when we're idle. The profiler is sampling-based
3411 // but not all samples are created equal; mark the wall clock time spent in
3412 // epoll_wait() and friends so profiling tools can filter it out. The samples
3413 // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
3414 // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
3415 // probably fortify in the API contract, namely that the last started prepare
3416 // or check watcher runs first. It's not 100% foolproof; if an add-on starts
3417 // a prepare or check watcher after us, any samples attributed to its callback
3418 // will be recorded with state=IDLE.
3419 uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
3420 uv_check_init(env->event_loop(), env->idle_check_handle());
3421 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
3422 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
3424 if (v8_is_profiling) {
3425 StartProfilerIdleNotifier(env);
3428 Local<FunctionTemplate> process_template = FunctionTemplate::New();
3429 process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3431 Local<Object> process_object = process_template->GetFunction()->NewInstance();
3432 env->set_process_object(process_object);
3434 SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3441 int Start(int argc, char** argv) {
3442 #if !defined(_WIN32)
3443 // Try hard not to lose SIGUSR1 signals during the bootstrap process.
3444 InstallEarlyDebugSignalHandler();
3449 // Hack around with the argv pointer. Used for process.title = "blah".
3450 argv = uv_setup_args(argc, argv);
3452 // This needs to run *before* V8::Initialize(). The const_cast is not
3453 // optional, in case you're wondering.
3455 const char** exec_argv;
3456 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3459 // V8 on Windows doesn't have a good source of entropy. Seed it from
3461 V8::SetEntropySource(crypto::EntropySource);
3467 Locker locker(node_isolate);
3469 CreateEnvironment(node_isolate, argc, argv, exec_argc, exec_argv);
3470 // This Context::Scope is here so EnableDebug() can look up the current
3471 // environment with Environment::GetCurrentChecked().
3472 // TODO(bnoordhuis) Reorder the debugger initialization logic so it can
3474 Context::Scope context_scope(env->context());
3475 uv_run(env->event_loop(), UV_RUN_DEFAULT);
3476 code = EmitExit(env);
3483 // Clean up. Not strictly necessary.