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 || defined HAVE_SYSTEMTAP
39 #include "node_dtrace.h"
43 #include "node_provider.h"
49 #include "handle_wrap.h"
51 #include "string_bytes.h"
54 #include "v8-profiler.h"
59 #include <limits.h> // PATH_MAX
65 #include <sys/types.h>
71 #define strcasecmp _stricmp
72 #define getpid _getpid
76 #include <sys/resource.h> // getrlimit, setrlimit
77 #include <unistd.h> // setuid, getuid
80 #if defined(__POSIX__) && !defined(__ANDROID__)
81 #include <pwd.h> // getpwnam()
82 #include <grp.h> // getgrnam()
86 #include <crt_externs.h>
87 #define environ (*_NSGetEnviron())
88 #elif !defined(_MSC_VER)
89 extern char **environ;
95 using v8::ArrayBuffer;
100 using v8::FunctionCallbackInfo;
101 using v8::FunctionTemplate;
103 using v8::HandleScope;
104 using v8::HeapStatistics;
112 using v8::ObjectTemplate;
113 using v8::PropertyCallbackInfo;
115 using v8::ThrowException;
120 using v8::kExternalUnsignedIntArray;
122 // FIXME(bnoordhuis) Make these per-context?
123 QUEUE handle_wrap_queue = { &handle_wrap_queue, &handle_wrap_queue };
124 QUEUE req_wrap_queue = { &req_wrap_queue, &req_wrap_queue };
126 static bool print_eval = false;
127 static bool force_repl = false;
128 static bool trace_deprecation = false;
129 static bool throw_deprecation = false;
130 static const char* eval_string = NULL;
131 static bool use_debug_agent = false;
132 static bool debug_wait_connect = false;
133 static int debug_port = 5858;
134 static bool v8_is_profiling = false;
136 // used by C++ modules as well
137 bool no_deprecation = false;
139 // process-relative uptime base, initialized at start-up
140 static double prog_start_time;
141 static bool debugger_running;
142 static uv_async_t dispatch_debug_messages_async;
144 // Declared in node_internals.h
145 Isolate* node_isolate = NULL;
148 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
150 // Impose an upper limit to avoid out of memory errors that bring down
152 static const size_t kMaxLength = 0x3fffffff;
153 static ArrayBufferAllocator the_singleton;
154 virtual ~ArrayBufferAllocator() {}
155 virtual void* Allocate(size_t length);
156 virtual void Free(void* data);
158 ArrayBufferAllocator() {}
159 ArrayBufferAllocator(const ArrayBufferAllocator&);
160 void operator=(const ArrayBufferAllocator&);
163 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
166 void* ArrayBufferAllocator::Allocate(size_t length) {
167 if (length > kMaxLength) return NULL;
168 return new char[length];
172 void ArrayBufferAllocator::Free(void* data) {
173 delete[] static_cast<char*>(data);
177 static void CheckImmediate(uv_check_t* handle, int status) {
178 Environment* env = Environment::from_immediate_check_handle(handle);
179 Context::Scope context_scope(env->context());
180 MakeCallback(env, env->process_object(), env->immediate_callback_string());
184 static void IdleImmediateDummy(uv_idle_t*, int) {
185 // Do nothing. Only for maintaining event loop.
186 // TODO(bnoordhuis) Maybe make libuv accept NULL idle callbacks.
190 static inline const char *errno_string(int errorno) {
191 #define ERRNO_CASE(e) case e: return #e;
198 ERRNO_CASE(EADDRINUSE);
202 ERRNO_CASE(EADDRNOTAVAIL);
206 ERRNO_CASE(EAFNOSUPPORT);
214 # if EAGAIN != EWOULDBLOCK
215 ERRNO_CASE(EWOULDBLOCK);
220 ERRNO_CASE(EALREADY);
236 ERRNO_CASE(ECANCELED);
244 ERRNO_CASE(ECONNABORTED);
248 ERRNO_CASE(ECONNREFUSED);
252 ERRNO_CASE(ECONNRESET);
260 ERRNO_CASE(EDESTADDRREQ);
284 ERRNO_CASE(EHOSTUNREACH);
296 ERRNO_CASE(EINPROGRESS);
332 ERRNO_CASE(EMSGSIZE);
336 ERRNO_CASE(EMULTIHOP);
340 ERRNO_CASE(ENAMETOOLONG);
344 ERRNO_CASE(ENETDOWN);
348 ERRNO_CASE(ENETRESET);
352 ERRNO_CASE(ENETUNREACH);
384 # if ENOLINK != ENOLCK
398 ERRNO_CASE(ENOPROTOOPT);
418 ERRNO_CASE(ENOTCONN);
426 ERRNO_CASE(ENOTEMPTY);
430 ERRNO_CASE(ENOTSOCK);
437 ERRNO_CASE(EOPNOTSUPP);
451 ERRNO_CASE(EOVERFLOW);
466 #ifdef EPROTONOSUPPORT
467 ERRNO_CASE(EPROTONOSUPPORT);
471 ERRNO_CASE(EPROTOTYPE);
499 ERRNO_CASE(ETIMEDOUT);
514 const char *signo_string(int signo) {
515 #define SIGNO_CASE(e) case e: return #e;
542 # if SIGABRT != SIGIOT
586 SIGNO_CASE(SIGSTKFLT);
603 SIGNO_CASE(SIGBREAK);
627 SIGNO_CASE(SIGVTALRM);
635 SIGNO_CASE(SIGWINCH);
643 # if SIGPOLL != SIGIO
653 # if SIGPWR != SIGLOST
667 Local<Value> ErrnoException(int errorno,
671 Environment* env = Environment::GetCurrent(node_isolate);
674 Local<String> estring = OneByteString(node_isolate, errno_string(errorno));
675 if (msg == NULL || msg[0] == '\0') {
676 msg = strerror(errorno);
678 Local<String> message = OneByteString(node_isolate, msg);
680 Local<String> cons1 =
681 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
682 Local<String> cons2 = String::Concat(cons1, message);
685 Local<String> cons3 =
686 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
687 Local<String> cons4 =
688 String::Concat(cons3, String::NewFromUtf8(node_isolate, path));
689 Local<String> cons5 =
690 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
691 e = Exception::Error(cons5);
693 e = Exception::Error(cons2);
696 Local<Object> obj = e->ToObject();
697 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
698 obj->Set(env->code_string(), estring);
701 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
704 if (syscall != NULL) {
705 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
712 // hack alert! copy of ErrnoException, tuned for uv errors
713 Local<Value> UVException(int errorno,
717 Environment* env = Environment::GetCurrent(node_isolate);
720 msg = uv_strerror(errorno);
722 Local<String> estring = OneByteString(node_isolate, uv_err_name(errorno));
723 Local<String> message = OneByteString(node_isolate, msg);
724 Local<String> cons1 =
725 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
726 Local<String> cons2 = String::Concat(cons1, message);
730 Local<String> path_str;
734 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
735 path_str = String::Concat(FIXED_ONE_BYTE_STRING(node_isolate, "\\\\"),
736 String::NewFromUtf8(node_isolate, path + 8));
737 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
738 path_str = String::NewFromUtf8(node_isolate, path + 4);
740 path_str = String::NewFromUtf8(node_isolate, path);
743 path_str = String::NewFromUtf8(node_isolate, path);
746 Local<String> cons3 =
747 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
748 Local<String> cons4 =
749 String::Concat(cons3, path_str);
750 Local<String> cons5 =
751 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
752 e = Exception::Error(cons5);
754 e = Exception::Error(cons2);
757 Local<Object> obj = e->ToObject();
758 // TODO(piscisaureus) errno should probably go
759 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
760 obj->Set(env->code_string(), estring);
763 obj->Set(env->path_string(), path_str);
766 if (syscall != NULL) {
767 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
775 // Does about the same as strerror(),
776 // but supports all windows error messages
777 static const char *winapi_strerror(const int errorno) {
780 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
781 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
782 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
785 // Remove trailing newlines
786 for (int i = strlen(errmsg) - 1;
787 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
793 // FormatMessage failed
794 return "Unknown error";
799 Local<Value> WinapiErrnoException(int errorno,
803 Environment* env = Environment::GetCurrent(node_isolate);
806 if (!msg || !msg[0]) {
807 msg = winapi_strerror(errorno);
809 Local<String> message = OneByteString(node_isolate, msg);
812 Local<String> cons1 =
813 String::Concat(message, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
814 Local<String> cons2 =
815 String::Concat(cons1, String::NewFromUtf8(node_isolate, path));
816 Local<String> cons3 =
817 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
818 e = Exception::Error(cons3);
820 e = Exception::Error(message);
823 Local<Object> obj = e->ToObject();
824 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
827 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
830 if (syscall != NULL) {
831 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
839 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
840 Environment* env = Environment::GetCurrent(args.GetIsolate());
842 if (env->using_domains()) return;
843 env->set_using_domains(true);
845 HandleScope scope(node_isolate);
846 Local<Object> process_object = env->process_object();
848 Local<String> tick_callback_function_key =
849 FIXED_ONE_BYTE_STRING(node_isolate, "_tickDomainCallback");
850 Local<Function> tick_callback_function =
851 process_object->Get(tick_callback_function_key).As<Function>();
853 if (!tick_callback_function->IsFunction()) {
854 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
858 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"),
859 tick_callback_function);
860 env->set_tick_callback_function(tick_callback_function);
862 if (!args[0]->IsArray()) {
863 fprintf(stderr, "_setupDomainUse first argument must be an array\n");
866 env->set_domain_array(args[0].As<Array>());
868 if (!args[1]->IsObject()) {
869 fprintf(stderr, "_setupDomainUse second argument must be an object\n");
873 Local<Object> domain_flag_obj = args[1].As<Object>();
874 Environment::DomainFlag* domain_flag = env->domain_flag();
875 domain_flag_obj->SetIndexedPropertiesToExternalArrayData(
876 domain_flag->fields(),
877 kExternalUnsignedIntArray,
878 domain_flag->fields_count());
882 Handle<Value> MakeDomainCallback(Environment* env,
883 const Handle<Object> object,
884 const Handle<Function> callback,
886 Handle<Value> argv[]) {
887 // If you hit this assertion, you forgot to enter the v8::Context first.
888 assert(env->context() == env->isolate()->GetCurrentContext());
890 // TODO(trevnorris) Hook for long stack traces to be made here.
892 Local<Value> domain_v = object->Get(env->domain_string());
893 Local<Object> domain;
896 try_catch.SetVerbose(true);
898 bool has_domain = domain_v->IsObject();
900 domain = domain_v.As<Object>();
902 if (domain->Get(env->disposed_string())->IsTrue()) {
903 // domain has been disposed of.
904 return Undefined(node_isolate);
907 Local<Function> enter =
908 domain->Get(env->enter_string()).As<Function>();
909 assert(enter->IsFunction());
910 enter->Call(domain, 0, NULL);
912 if (try_catch.HasCaught()) {
913 return Undefined(node_isolate);
917 Local<Value> ret = callback->Call(object, argc, argv);
919 if (try_catch.HasCaught()) {
920 return Undefined(node_isolate);
924 Local<Function> exit =
925 domain->Get(env->exit_string()).As<Function>();
926 assert(exit->IsFunction());
927 exit->Call(domain, 0, NULL);
929 if (try_catch.HasCaught()) {
930 return Undefined(node_isolate);
934 Environment::TickInfo* tick_info = env->tick_info();
936 if (tick_info->last_threw() == 1) {
937 tick_info->set_last_threw(0);
941 if (tick_info->in_tick() == 1) {
945 if (tick_info->length() == 0) {
946 tick_info->set_index(0);
950 // process nextTicks after call
951 Local<Object> process_object = env->process_object();
952 Local<Function> tick_callback_function = env->tick_callback_function();
953 tick_callback_function->Call(process_object, 0, NULL);
955 if (try_catch.HasCaught()) {
956 return Undefined(node_isolate);
963 Handle<Value> MakeCallback(Environment* env,
964 const Handle<Object> object,
965 const Handle<Function> callback,
967 Handle<Value> argv[]) {
968 // If you hit this assertion, you forgot to enter the v8::Context first.
969 assert(env->context() == env->isolate()->GetCurrentContext());
971 // TODO(trevnorris) Hook for long stack traces to be made here.
972 Local<Object> process_object = env->process_object();
974 if (env->using_domains())
975 return MakeDomainCallback(env, object, callback, argc, argv);
978 try_catch.SetVerbose(true);
980 Local<Value> ret = callback->Call(object, argc, argv);
982 if (try_catch.HasCaught()) {
983 return Undefined(node_isolate);
986 Environment::TickInfo* tick_info = env->tick_info();
988 if (tick_info->in_tick() == 1) {
992 if (tick_info->length() == 0) {
993 tick_info->set_index(0);
997 // lazy load no domain next tick callbacks
998 Local<Function> tick_callback_function = env->tick_callback_function();
999 if (tick_callback_function.IsEmpty()) {
1000 Local<String> tick_callback_function_key =
1001 FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback");
1002 tick_callback_function =
1003 process_object->Get(tick_callback_function_key).As<Function>();
1004 if (!tick_callback_function->IsFunction()) {
1005 fprintf(stderr, "process._tickCallback assigned to non-function\n");
1008 env->set_tick_callback_function(tick_callback_function);
1011 // process nextTicks after call
1012 tick_callback_function->Call(process_object, 0, NULL);
1014 if (try_catch.HasCaught()) {
1015 return Undefined(node_isolate);
1023 Handle<Value> MakeCallback(Environment* env,
1024 const Handle<Object> object,
1027 Handle<Value> argv[]) {
1028 // If you hit this assertion, you forgot to enter the v8::Context first.
1029 assert(env->context() == env->isolate()->GetCurrentContext());
1031 Local<Function> callback = object->Get(index).As<Function>();
1032 assert(callback->IsFunction());
1034 if (env->using_domains()) {
1035 return MakeDomainCallback(env, object, callback, argc, argv);
1038 return MakeCallback(env, object, callback, argc, argv);
1042 Handle<Value> MakeCallback(Environment* env,
1043 const Handle<Object> object,
1044 const Handle<String> symbol,
1046 Handle<Value> argv[]) {
1047 // If you hit this assertion, you forgot to enter the v8::Context first.
1048 assert(env->context() == env->isolate()->GetCurrentContext());
1050 Local<Function> callback = object->Get(symbol).As<Function>();
1051 assert(callback->IsFunction());
1053 if (env->using_domains()) {
1054 return MakeDomainCallback(env, object, callback, argc, argv);
1057 return MakeCallback(env, object, callback, argc, argv);
1061 Handle<Value> MakeCallback(Environment* env,
1062 const Handle<Object> object,
1065 Handle<Value> argv[]) {
1066 // If you hit this assertion, you forgot to enter the v8::Context first.
1067 assert(env->context() == env->isolate()->GetCurrentContext());
1068 Local<String> method_string = OneByteString(node_isolate, method);
1069 return MakeCallback(env, object, method_string, argc, argv);
1073 Handle<Value> MakeCallback(const Handle<Object> object,
1076 Handle<Value> argv[]) {
1077 Local<Context> context = object->CreationContext();
1078 Environment* env = Environment::GetCurrent(context);
1079 Context::Scope context_scope(context);
1080 HandleScope handle_scope(env->isolate());
1081 return handle_scope.Close(MakeCallback(env, object, method, argc, argv));
1085 Handle<Value> MakeCallback(const Handle<Object> object,
1086 const Handle<String> symbol,
1088 Handle<Value> argv[]) {
1089 Local<Context> context = object->CreationContext();
1090 Environment* env = Environment::GetCurrent(context);
1091 Context::Scope context_scope(context);
1092 HandleScope handle_scope(env->isolate());
1093 return handle_scope.Close(MakeCallback(env, object, symbol, argc, argv));
1097 Handle<Value> MakeCallback(const Handle<Object> object,
1098 const Handle<Function> callback,
1100 Handle<Value> argv[]) {
1101 Local<Context> context = object->CreationContext();
1102 Environment* env = Environment::GetCurrent(context);
1103 Context::Scope context_scope(context);
1104 HandleScope handle_scope(env->isolate());
1105 return handle_scope.Close(MakeCallback(env, object, callback, argc, argv));
1109 Handle<Value> MakeDomainCallback(const Handle<Object> object,
1110 const Handle<Function> callback,
1112 Handle<Value> argv[]) {
1113 Local<Context> context = object->CreationContext();
1114 Environment* env = Environment::GetCurrent(context);
1115 Context::Scope context_scope(context);
1116 HandleScope handle_scope(env->isolate());
1117 return handle_scope.Close(
1118 MakeDomainCallback(env, object, callback, argc, argv));
1122 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1123 HandleScope scope(node_isolate);
1125 if (!encoding_v->IsString()) return _default;
1127 String::Utf8Value encoding(encoding_v);
1129 if (strcasecmp(*encoding, "utf8") == 0) {
1131 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1133 } else if (strcasecmp(*encoding, "ascii") == 0) {
1135 } else if (strcasecmp(*encoding, "base64") == 0) {
1137 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1139 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1141 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1143 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1145 } else if (strcasecmp(*encoding, "binary") == 0) {
1147 } else if (strcasecmp(*encoding, "buffer") == 0) {
1149 } else if (strcasecmp(*encoding, "hex") == 0) {
1151 } else if (strcasecmp(*encoding, "raw") == 0) {
1152 if (!no_deprecation) {
1153 fprintf(stderr, "'raw' (array of integers) has been removed. "
1157 } else if (strcasecmp(*encoding, "raws") == 0) {
1158 if (!no_deprecation) {
1159 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1160 "Please update your code.\n");
1168 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1169 return StringBytes::Encode(static_cast<const char*>(buf),
1174 // Returns -1 if the handle was not valid for decoding
1175 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1176 HandleScope scope(node_isolate);
1178 if (val->IsArray()) {
1179 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1185 return StringBytes::Size(val, encoding);
1189 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1192 // Returns number of bytes written.
1193 ssize_t DecodeWrite(char *buf,
1195 v8::Handle<v8::Value> val,
1196 enum encoding encoding) {
1197 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1200 void DisplayExceptionLine(Handle<Message> message) {
1201 // Prevent re-entry into this function. For example, if there is
1202 // a throw from a program in vm.runInThisContext(code, filename, true),
1203 // then we want to show the original failure, not the secondary one.
1204 static bool displayed_error = false;
1206 if (displayed_error) return;
1207 displayed_error = true;
1209 uv_tty_reset_mode();
1211 fprintf(stderr, "\n");
1213 if (!message.IsEmpty()) {
1214 // Print (filename):(line number): (message).
1215 String::Utf8Value filename(message->GetScriptResourceName());
1216 const char* filename_string = *filename;
1217 int linenum = message->GetLineNumber();
1218 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1219 // Print line of source code.
1220 String::Utf8Value sourceline(message->GetSourceLine());
1221 const char* sourceline_string = *sourceline;
1223 // Because of how node modules work, all scripts are wrapped with a
1224 // "function (module, exports, __filename, ...) {"
1225 // to provide script local variables.
1227 // When reporting errors on the first line of a script, this wrapper
1228 // function is leaked to the user. There used to be a hack here to
1229 // truncate off the first 62 characters, but it caused numerous other
1230 // problems when vm.runIn*Context() methods were used for non-module
1233 // If we ever decide to re-instate such a hack, the following steps
1236 // 1. Pass a flag around to say "this code was wrapped"
1237 // 2. Update the stack frame output so that it is also correct.
1239 // It would probably be simpler to add a line rather than add some
1240 // number of characters to the first line, since V8 truncates the
1241 // sourceline to 78 characters, and we end up not providing very much
1242 // useful debugging info to the user if we remove 62 characters.
1244 int start = message->GetStartColumn();
1245 int end = message->GetEndColumn();
1247 fprintf(stderr, "%s\n", sourceline_string);
1248 // Print wavy underline (GetUnderline is deprecated).
1249 for (int i = 0; i < start; i++) {
1250 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1252 for (int i = start; i < end; i++) {
1255 fputc('\n', stderr);
1260 static void ReportException(Handle<Value> er, Handle<Message> message) {
1261 HandleScope scope(node_isolate);
1263 DisplayExceptionLine(message);
1265 Local<Value> trace_value(
1266 er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack")));
1267 String::Utf8Value trace(trace_value);
1269 // range errors have a trace member set to undefined
1270 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1271 fprintf(stderr, "%s\n", *trace);
1273 // this really only happens for RangeErrors, since they're the only
1274 // kind that won't have all this info in the trace, or when non-Error
1275 // objects are thrown manually.
1276 Local<Value> message;
1279 if (er->IsObject()) {
1280 Local<Object> err_obj = er.As<Object>();
1281 message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1282 name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1285 if (message.IsEmpty() ||
1286 message->IsUndefined() ||
1288 name->IsUndefined()) {
1289 // Not an error object. Just print as-is.
1290 String::Utf8Value message(er);
1291 fprintf(stderr, "%s\n", *message);
1293 String::Utf8Value name_string(name);
1294 String::Utf8Value message_string(message);
1295 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1303 static void ReportException(const TryCatch& try_catch) {
1304 ReportException(try_catch.Exception(), try_catch.Message());
1308 // Executes a str within the current v8 context.
1309 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1310 HandleScope scope(node_isolate);
1313 // try_catch must be nonverbose to disable FatalException() handler,
1314 // we will handle exceptions ourself.
1315 try_catch.SetVerbose(false);
1317 Local<v8::Script> script = v8::Script::Compile(source, filename);
1318 if (script.IsEmpty()) {
1319 ReportException(try_catch);
1323 Local<Value> result = script->Run();
1324 if (result.IsEmpty()) {
1325 ReportException(try_catch);
1329 return scope.Close(result);
1333 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1334 HandleScope scope(node_isolate);
1336 Local<Array> ary = Array::New();
1340 QUEUE_FOREACH(q, &req_wrap_queue) {
1341 ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1342 if (w->persistent().IsEmpty()) continue;
1343 ary->Set(i++, w->object());
1346 args.GetReturnValue().Set(ary);
1350 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1351 // implemented here for consistency with GetActiveRequests().
1352 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1353 HandleScope scope(node_isolate);
1355 Local<Array> ary = Array::New();
1359 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1361 QUEUE_FOREACH(q, &handle_wrap_queue) {
1362 HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1363 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue;
1364 Local<Object> object = w->object();
1365 Local<Value> owner = object->Get(owner_sym);
1366 if (owner->IsUndefined()) owner = object;
1367 ary->Set(i++, owner);
1370 args.GetReturnValue().Set(ary);
1374 static void Abort(const FunctionCallbackInfo<Value>& args) {
1379 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1380 HandleScope scope(node_isolate);
1382 if (args.Length() != 1 || !args[0]->IsString()) {
1383 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1386 String::Utf8Value path(args[0]);
1387 int err = uv_chdir(*path);
1389 return ThrowUVException(err, "uv_chdir");
1394 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1395 HandleScope scope(node_isolate);
1397 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1398 char buf[MAX_PATH * 4 + 1];
1400 char buf[PATH_MAX + 1];
1403 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1405 return ThrowUVException(err, "uv_cwd");
1408 buf[ARRAY_SIZE(buf) - 1] = '\0';
1409 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1411 args.GetReturnValue().Set(cwd);
1415 static void Umask(const FunctionCallbackInfo<Value>& args) {
1416 HandleScope scope(node_isolate);
1419 if (args.Length() < 1 || args[0]->IsUndefined()) {
1421 umask(static_cast<mode_t>(old));
1422 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1423 return ThrowTypeError("argument must be an integer or octal string.");
1426 if (args[0]->IsInt32()) {
1427 oct = args[0]->Uint32Value();
1430 String::Utf8Value str(args[0]);
1432 // Parse the octal string.
1433 for (int i = 0; i < str.length(); i++) {
1435 if (c > '7' || c < '0') {
1436 return ThrowTypeError("invalid octal string");
1442 old = umask(static_cast<mode_t>(oct));
1445 args.GetReturnValue().Set(old);
1449 #if defined(__POSIX__) && !defined(__ANDROID__)
1451 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1452 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1455 static uid_t uid_by_name(const char* name) {
1463 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1467 return uid_not_found;
1471 static char* name_by_uid(uid_t uid) {
1480 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1481 return strdup(pp->pw_name);
1492 static gid_t gid_by_name(const char* name) {
1500 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1504 return gid_not_found;
1508 #if 0 // For future use.
1509 static const char* name_by_gid(gid_t gid) {
1518 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1519 return strdup(pp->gr_name);
1531 static uid_t uid_by_name(Handle<Value> value) {
1532 if (value->IsUint32()) {
1533 return static_cast<uid_t>(value->Uint32Value());
1535 String::Utf8Value name(value);
1536 return uid_by_name(*name);
1541 static gid_t gid_by_name(Handle<Value> value) {
1542 if (value->IsUint32()) {
1543 return static_cast<gid_t>(value->Uint32Value());
1545 String::Utf8Value name(value);
1546 return gid_by_name(*name);
1551 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1552 // uid_t is an uint32_t on all supported platforms.
1553 args.GetReturnValue().Set(static_cast<uint32_t>(getuid()));
1557 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1558 // gid_t is an uint32_t on all supported platforms.
1559 args.GetReturnValue().Set(static_cast<uint32_t>(getgid()));
1563 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1564 HandleScope scope(node_isolate);
1566 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1567 return ThrowTypeError("setgid argument must be a number or a string");
1570 gid_t gid = gid_by_name(args[0]);
1572 if (gid == gid_not_found) {
1573 return ThrowError("setgid group id does not exist");
1577 return ThrowErrnoException(errno, "setgid");
1582 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1583 HandleScope scope(node_isolate);
1585 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1586 return ThrowTypeError("setuid argument must be a number or a string");
1589 uid_t uid = uid_by_name(args[0]);
1591 if (uid == uid_not_found) {
1592 return ThrowError("setuid user id does not exist");
1596 return ThrowErrnoException(errno, "setuid");
1601 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1602 HandleScope scope(node_isolate);
1604 int ngroups = getgroups(0, NULL);
1606 if (ngroups == -1) {
1607 return ThrowErrnoException(errno, "getgroups");
1610 gid_t* groups = new gid_t[ngroups];
1612 ngroups = getgroups(ngroups, groups);
1614 if (ngroups == -1) {
1616 return ThrowErrnoException(errno, "getgroups");
1619 Local<Array> groups_list = Array::New(ngroups);
1620 bool seen_egid = false;
1621 gid_t egid = getegid();
1623 for (int i = 0; i < ngroups; i++) {
1624 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1625 if (groups[i] == egid) seen_egid = true;
1630 if (seen_egid == false) {
1631 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1634 args.GetReturnValue().Set(groups_list);
1638 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1639 HandleScope scope(node_isolate);
1641 if (!args[0]->IsArray()) {
1642 return ThrowTypeError("argument 1 must be an array");
1645 Local<Array> groups_list = args[0].As<Array>();
1646 size_t size = groups_list->Length();
1647 gid_t* groups = new gid_t[size];
1649 for (size_t i = 0; i < size; i++) {
1650 gid_t gid = gid_by_name(groups_list->Get(i));
1652 if (gid == gid_not_found) {
1654 return ThrowError("group name not found");
1660 int rc = setgroups(size, groups);
1664 return ThrowErrnoException(errno, "setgroups");
1669 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1670 HandleScope scope(node_isolate);
1672 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1673 return ThrowTypeError("argument 1 must be a number or a string");
1676 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1677 return ThrowTypeError("argument 2 must be a number or a string");
1680 String::Utf8Value arg0(args[0]);
1685 if (args[0]->IsUint32()) {
1686 user = name_by_uid(args[0]->Uint32Value());
1694 return ThrowError("initgroups user not found");
1697 extra_group = gid_by_name(args[1]);
1699 if (extra_group == gid_not_found) {
1700 if (must_free) free(user);
1701 return ThrowError("initgroups extra group not found");
1704 int rc = initgroups(user, extra_group);
1711 return ThrowErrnoException(errno, "initgroups");
1715 #endif // __POSIX__ && !defined(__ANDROID__)
1718 void Exit(const FunctionCallbackInfo<Value>& args) {
1719 HandleScope scope(node_isolate);
1720 exit(args[0]->IntegerValue());
1724 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1725 HandleScope scope(node_isolate);
1727 if (uv_uptime(&uptime)) return;
1728 args.GetReturnValue().Set(uptime - prog_start_time);
1732 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1733 Environment* env = Environment::GetCurrent(args.GetIsolate());
1734 HandleScope handle_scope(args.GetIsolate());
1737 int err = uv_resident_set_memory(&rss);
1739 return ThrowUVException(err, "uv_resident_set_memory");
1743 HeapStatistics v8_heap_stats;
1744 node_isolate->GetHeapStatistics(&v8_heap_stats);
1746 Local<Integer> heap_total =
1747 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(), node_isolate);
1748 Local<Integer> heap_used =
1749 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(), node_isolate);
1751 Local<Object> info = Object::New();
1752 info->Set(env->rss_string(), Number::New(node_isolate, rss));
1753 info->Set(env->heap_total_string(), heap_total);
1754 info->Set(env->heap_used_string(), heap_used);
1756 args.GetReturnValue().Set(info);
1760 void Kill(const FunctionCallbackInfo<Value>& args) {
1761 HandleScope scope(node_isolate);
1763 if (args.Length() != 2) {
1764 return ThrowError("Bad argument.");
1767 int pid = args[0]->IntegerValue();
1768 int sig = args[1]->Int32Value();
1769 int err = uv_kill(pid, sig);
1770 args.GetReturnValue().Set(err);
1773 // used in Hrtime() below
1774 #define NANOS_PER_SEC 1000000000
1776 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1777 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1778 // so this function instead returns an Array with 2 entries representing seconds
1779 // and nanoseconds, to avoid any integer overflow possibility.
1780 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1781 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1782 HandleScope scope(node_isolate);
1784 uint64_t t = uv_hrtime();
1786 if (args.Length() > 0) {
1787 // return a time diff tuple
1788 if (!args[0]->IsArray()) {
1789 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1791 Local<Array> inArray = Local<Array>::Cast(args[0]);
1792 uint64_t seconds = inArray->Get(0)->Uint32Value();
1793 uint64_t nanos = inArray->Get(1)->Uint32Value();
1794 t -= (seconds * NANOS_PER_SEC) + nanos;
1797 Local<Array> tuple = Array::New(2);
1798 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1799 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1800 args.GetReturnValue().Set(tuple);
1804 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1806 // DLOpen is process.dlopen(module, filename).
1807 // Used to load 'module.node' dynamically shared objects.
1809 // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
1810 // when two contexts try to load the same shared object. Maybe have a shadow
1811 // cache that's a plain C list or hash table that's shared across contexts?
1812 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1813 Environment* env = Environment::GetCurrent(args.GetIsolate());
1814 HandleScope handle_scope(args.GetIsolate());
1815 char symbol[1024], *base, *pos;
1819 if (args.Length() < 2) {
1820 return ThrowError("process.dlopen takes exactly 2 arguments.");
1823 Local<Object> module = args[0]->ToObject(); // Cast
1824 String::Utf8Value filename(args[1]); // Cast
1826 Local<String> exports_string = env->exports_string();
1827 Local<Object> exports = module->Get(exports_string)->ToObject();
1829 if (uv_dlopen(*filename, &lib)) {
1830 Local<String> errmsg = OneByteString(env->isolate(), uv_dlerror(&lib));
1832 // Windows needs to add the filename into the error message
1833 errmsg = String::Concat(errmsg, args[1]->ToString());
1835 ThrowException(Exception::Error(errmsg));
1839 String::Utf8Value path(args[1]);
1842 /* Find the shared library filename within the full path. */
1844 pos = strrchr(base, '/');
1850 pos = strpbrk(base, "\\/:");
1858 /* Strip the .node extension. */
1859 pos = strrchr(base, '.');
1864 /* Add the `_module` suffix to the extension name. */
1865 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1866 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1867 return ThrowError("Out of memory.");
1870 /* Replace dashes with underscores. When loading foo-bar.node,
1871 * look for foo_bar_module, not foo-bar_module.
1873 for (pos = symbol; *pos != '\0'; ++pos) {
1874 if (*pos == '-') *pos = '_';
1877 node_module_struct *mod;
1878 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1880 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1881 return ThrowError(errmsg);
1884 if (mod->version != NODE_MODULE_VERSION) {
1888 "Module version mismatch. Expected %d, got %d.",
1889 NODE_MODULE_VERSION, mod->version);
1890 return ThrowError(errmsg);
1893 // Execute the C++ module
1894 if (mod->register_context_func != NULL) {
1895 mod->register_context_func(exports, module, env->context());
1896 } else if (mod->register_func != NULL) {
1897 mod->register_func(exports, module);
1899 return ThrowError("Module has no declared entry point.");
1902 // Tell coverity that 'handle' should not be freed when we return.
1903 // coverity[leaked_storage]
1907 static void OnFatalError(const char* location, const char* message) {
1909 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1911 fprintf(stderr, "FATAL ERROR: %s\n", message);
1921 NO_RETURN void FatalError(const char* location, const char* message) {
1922 OnFatalError(location, message);
1923 // to supress compiler warning
1928 void FatalException(Handle<Value> error, Handle<Message> message) {
1929 HandleScope scope(node_isolate);
1931 Environment* env = Environment::GetCurrent(node_isolate);
1932 Local<Object> process_object = env->process_object();
1933 Local<String> fatal_exception_string = env->fatal_exception_string();
1934 Local<Function> fatal_exception_function =
1935 process_object->Get(fatal_exception_string).As<Function>();
1937 if (!fatal_exception_function->IsFunction()) {
1938 // failed before the process._fatalException function was added!
1939 // this is probably pretty bad. Nothing to do but report and exit.
1940 ReportException(error, message);
1944 TryCatch fatal_try_catch;
1946 // Do not call FatalException when _fatalException handler throws
1947 fatal_try_catch.SetVerbose(false);
1949 // this will return true if the JS layer handled it, false otherwise
1950 Local<Value> caught =
1951 fatal_exception_function->Call(process_object, 1, &error);
1953 if (fatal_try_catch.HasCaught()) {
1954 // the fatal exception function threw, so we must exit
1955 ReportException(fatal_try_catch);
1959 if (false == caught->BooleanValue()) {
1960 ReportException(error, message);
1966 void FatalException(const TryCatch& try_catch) {
1967 HandleScope scope(node_isolate);
1968 // TODO(bajtos) do not call FatalException if try_catch is verbose
1969 // (requires V8 API to expose getter for try_catch.is_verbose_)
1970 FatalException(try_catch.Exception(), try_catch.Message());
1974 void OnMessage(Handle<Message> message, Handle<Value> error) {
1975 // The current version of V8 sends messages for errors only
1976 // (thus `error` is always set).
1977 FatalException(error, message);
1981 static void Binding(const FunctionCallbackInfo<Value>& args) {
1982 Environment* env = Environment::GetCurrent(args.GetIsolate());
1983 HandleScope handle_scope(args.GetIsolate());
1985 Local<String> module = args[0]->ToString();
1986 String::Utf8Value module_v(module);
1988 Local<Object> cache = env->binding_cache_object();
1989 Local<Object> exports;
1991 if (cache->Has(module)) {
1992 exports = cache->Get(module)->ToObject();
1993 args.GetReturnValue().Set(exports);
1997 // Append a string to process.moduleLoadList
1999 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
2001 Local<Array> modules = env->module_load_list_array();
2002 uint32_t l = modules->Length();
2003 modules->Set(l, OneByteString(node_isolate, buf));
2005 node_module_struct* mod = get_builtin_module(*module_v);
2007 exports = Object::New();
2008 // Internal bindings don't have a "module" object, only exports.
2009 assert(mod->register_func == NULL);
2010 assert(mod->register_context_func != NULL);
2011 Local<Value> unused = Undefined(env->isolate());
2012 mod->register_context_func(exports, unused, env->context());
2013 cache->Set(module, exports);
2014 } else if (!strcmp(*module_v, "constants")) {
2015 exports = Object::New();
2016 DefineConstants(exports);
2017 cache->Set(module, exports);
2018 } else if (!strcmp(*module_v, "natives")) {
2019 exports = Object::New();
2020 DefineJavaScript(exports);
2021 cache->Set(module, exports);
2023 return ThrowError("No such module");
2026 args.GetReturnValue().Set(exports);
2030 static void ProcessTitleGetter(Local<String> property,
2031 const PropertyCallbackInfo<Value>& info) {
2032 HandleScope scope(node_isolate);
2034 uv_get_process_title(buffer, sizeof(buffer));
2035 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2039 static void ProcessTitleSetter(Local<String> property,
2041 const PropertyCallbackInfo<void>& info) {
2042 HandleScope scope(node_isolate);
2043 String::Utf8Value title(value);
2044 // TODO(piscisaureus): protect with a lock
2045 uv_set_process_title(*title);
2049 static void EnvGetter(Local<String> property,
2050 const PropertyCallbackInfo<Value>& info) {
2051 HandleScope scope(node_isolate);
2053 String::Utf8Value key(property);
2054 const char* val = getenv(*key);
2056 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2059 String::Value key(property);
2060 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2061 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2063 ARRAY_SIZE(buffer));
2064 // If result >= sizeof buffer the buffer was too small. That should never
2065 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2067 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2068 result < ARRAY_SIZE(buffer)) {
2069 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2070 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2071 return info.GetReturnValue().Set(rc);
2074 // Not found. Fetch from prototype.
2075 info.GetReturnValue().Set(
2076 info.Data().As<Object>()->Get(property));
2080 static void EnvSetter(Local<String> property,
2082 const PropertyCallbackInfo<Value>& info) {
2083 HandleScope scope(node_isolate);
2085 String::Utf8Value key(property);
2086 String::Utf8Value val(value);
2087 setenv(*key, *val, 1);
2089 String::Value key(property);
2090 String::Value val(value);
2091 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2092 // Environment variables that start with '=' are read-only.
2093 if (key_ptr[0] != L'=') {
2094 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2097 // Whether it worked or not, always return rval.
2098 info.GetReturnValue().Set(value);
2102 static void EnvQuery(Local<String> property,
2103 const PropertyCallbackInfo<Integer>& info) {
2104 HandleScope scope(node_isolate);
2105 int32_t rc = -1; // Not found unless proven otherwise.
2107 String::Utf8Value key(property);
2108 if (getenv(*key)) rc = 0;
2110 String::Value key(property);
2111 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2112 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2113 GetLastError() == ERROR_SUCCESS) {
2115 if (key_ptr[0] == L'=') {
2116 // Environment variables that start with '=' are hidden and read-only.
2117 rc = static_cast<int32_t>(v8::ReadOnly) |
2118 static_cast<int32_t>(v8::DontDelete) |
2119 static_cast<int32_t>(v8::DontEnum);
2123 if (rc != -1) info.GetReturnValue().Set(rc);
2127 static void EnvDeleter(Local<String> property,
2128 const PropertyCallbackInfo<Boolean>& info) {
2129 HandleScope scope(node_isolate);
2132 String::Utf8Value key(property);
2133 rc = getenv(*key) != NULL;
2134 if (rc) unsetenv(*key);
2136 String::Value key(property);
2137 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2138 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2139 // Deletion failed. Return true if the key wasn't there in the first place,
2140 // false if it is still there.
2141 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2142 GetLastError() != ERROR_SUCCESS;
2145 info.GetReturnValue().Set(rc);
2149 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2150 HandleScope scope(node_isolate);
2153 while (environ[size]) size++;
2155 Local<Array> env = Array::New(size);
2157 for (int i = 0; i < size; ++i) {
2158 const char* var = environ[i];
2159 const char* s = strchr(var, '=');
2160 const int length = s ? s - var : strlen(var);
2161 Local<String> name = String::NewFromUtf8(node_isolate,
2163 String::kNormalString,
2168 WCHAR* environment = GetEnvironmentStringsW();
2169 if (environment == NULL) return; // This should not happen.
2170 Local<Array> env = Array::New();
2171 WCHAR* p = environment;
2173 while (*p != NULL) {
2176 // If the key starts with '=' it is a hidden environment variable.
2180 s = wcschr(p, L'=');
2185 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2186 const size_t two_byte_buffer_len = s - p;
2187 Local<String> value = String::NewFromTwoByte(node_isolate,
2189 String::kNormalString,
2190 two_byte_buffer_len);
2191 env->Set(i++, value);
2192 p = s + wcslen(s) + 1;
2194 FreeEnvironmentStringsW(environment);
2197 info.GetReturnValue().Set(env);
2201 static Handle<Object> GetFeatures() {
2202 HandleScope scope(node_isolate);
2204 Local<Object> obj = Object::New();
2205 #if defined(DEBUG) && DEBUG
2206 Local<Value> debug = True(node_isolate);
2208 Local<Value> debug = False(node_isolate);
2209 #endif // defined(DEBUG) && DEBUG
2211 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2213 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2214 // TODO(bnoordhuis) ping libuv
2215 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2217 #ifdef OPENSSL_NPN_NEGOTIATED
2218 Local<Boolean> tls_npn = True(node_isolate);
2220 Local<Boolean> tls_npn = False(node_isolate);
2222 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"), tls_npn);
2224 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2225 Local<Boolean> tls_sni = True(node_isolate);
2227 Local<Boolean> tls_sni = False(node_isolate);
2229 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"), tls_sni);
2231 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2232 Boolean::New(get_builtin_module("crypto") != NULL));
2234 return scope.Close(obj);
2238 static void DebugPortGetter(Local<String> property,
2239 const PropertyCallbackInfo<Value>& info) {
2240 HandleScope scope(node_isolate);
2241 info.GetReturnValue().Set(debug_port);
2245 static void DebugPortSetter(Local<String> property,
2247 const PropertyCallbackInfo<void>& info) {
2248 HandleScope scope(node_isolate);
2249 debug_port = value->NumberValue();
2253 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2254 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2255 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2258 void NeedImmediateCallbackGetter(Local<String> property,
2259 const PropertyCallbackInfo<Value>& info) {
2260 Environment* env = Environment::GetCurrent(info.GetIsolate());
2261 const uv_check_t* immediate_check_handle = env->immediate_check_handle();
2262 bool active = uv_is_active(
2263 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2264 info.GetReturnValue().Set(active);
2268 static void NeedImmediateCallbackSetter(
2269 Local<String> property,
2271 const PropertyCallbackInfo<void>& info) {
2272 Environment* env = Environment::GetCurrent(info.GetIsolate());
2273 HandleScope handle_scope(info.GetIsolate());
2275 uv_check_t* immediate_check_handle = env->immediate_check_handle();
2276 bool active = uv_is_active(
2277 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2279 if (active == value->BooleanValue())
2282 uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
2285 uv_check_stop(immediate_check_handle);
2286 uv_idle_stop(immediate_idle_handle);
2288 uv_check_start(immediate_check_handle, CheckImmediate);
2289 // Idle handle is needed only to stop the event loop from blocking in poll.
2290 uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
2295 void SetIdle(uv_prepare_t* handle, int) {
2296 Environment* env = Environment::from_idle_prepare_handle(handle);
2297 env->isolate()->GetCpuProfiler()->SetIdle(true);
2301 void ClearIdle(uv_check_t* handle, int) {
2302 Environment* env = Environment::from_idle_check_handle(handle);
2303 env->isolate()->GetCpuProfiler()->SetIdle(false);
2307 void StartProfilerIdleNotifier(Environment* env) {
2308 uv_prepare_start(env->idle_prepare_handle(), SetIdle);
2309 uv_check_start(env->idle_check_handle(), ClearIdle);
2313 void StopProfilerIdleNotifier(Environment* env) {
2314 uv_prepare_stop(env->idle_prepare_handle());
2315 uv_check_stop(env->idle_check_handle());
2319 void StartProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2320 StartProfilerIdleNotifier(Environment::GetCurrent(args.GetIsolate()));
2324 void StopProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2325 StopProfilerIdleNotifier(Environment::GetCurrent(args.GetIsolate()));
2329 #define READONLY_PROPERTY(obj, str, var) \
2331 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2335 void SetupProcessObject(Environment* env,
2337 const char* const* argv,
2339 const char* const* exec_argv) {
2340 HandleScope scope(node_isolate);
2343 Local<Object> process = env->process_object();
2345 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2347 ProcessTitleSetter);
2350 READONLY_PROPERTY(process,
2352 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2354 // process.moduleLoadList
2355 READONLY_PROPERTY(process,
2357 env->module_load_list_array());
2360 Local<Object> versions = Object::New();
2361 READONLY_PROPERTY(process, "versions", versions);
2363 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2365 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2366 READONLY_PROPERTY(versions,
2368 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2370 // +1 to get rid of the leading 'v'
2371 READONLY_PROPERTY(versions,
2373 OneByteString(node_isolate, NODE_VERSION + 1));
2374 READONLY_PROPERTY(versions,
2376 OneByteString(node_isolate, V8::GetVersion()));
2377 READONLY_PROPERTY(versions,
2379 OneByteString(node_isolate, uv_version_string()));
2380 READONLY_PROPERTY(versions,
2382 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2384 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2385 READONLY_PROPERTY(versions,
2387 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2390 // Stupid code to slice out the version string.
2391 int c, l = strlen(OPENSSL_VERSION_TEXT);
2392 for (i = j = 0; i < l; i++) {
2393 c = OPENSSL_VERSION_TEXT[i];
2394 if ('0' <= c && c <= '9') {
2395 for (j = i + 1; j < l; j++) {
2396 c = OPENSSL_VERSION_TEXT[j];
2397 if (c == ' ') break;
2405 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2409 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2412 READONLY_PROPERTY(process,
2414 OneByteString(node_isolate, PLATFORM));
2417 Local<Array> arguments = Array::New(argc);
2418 for (int i = 0; i < argc; ++i) {
2419 arguments->Set(i, String::NewFromUtf8(node_isolate, argv[i]));
2421 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2424 Local<Array> exec_arguments = Array::New(exec_argc);
2425 for (int i = 0; i < exec_argc; ++i) {
2426 exec_arguments->Set(i, String::NewFromUtf8(node_isolate, exec_argv[i]));
2428 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_arguments);
2430 // create process.env
2431 Local<ObjectTemplate> process_env_template = ObjectTemplate::New();
2432 process_env_template->SetNamedPropertyHandler(EnvGetter,
2438 Local<Object> process_env = process_env_template->NewInstance();
2439 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), process_env);
2441 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2442 READONLY_PROPERTY(process, "features", GetFeatures());
2443 process->SetAccessor(
2444 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2445 NeedImmediateCallbackGetter,
2446 NeedImmediateCallbackSetter);
2450 READONLY_PROPERTY(process,
2452 String::NewFromUtf8(node_isolate, eval_string));
2457 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2460 // -i, --interactive
2462 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2466 if (no_deprecation) {
2467 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2470 // --throw-deprecation
2471 if (throw_deprecation) {
2472 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2475 // --trace-deprecation
2476 if (trace_deprecation) {
2477 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2480 size_t exec_path_len = 2 * PATH_MAX;
2481 char* exec_path = new char[exec_path_len];
2482 Local<String> exec_path_value;
2483 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2484 exec_path_value = String::NewFromUtf8(node_isolate,
2486 String::kNormalString,
2489 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2491 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2495 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2499 // define various internal methods
2500 NODE_SET_METHOD(process,
2501 "_startProfilerIdleNotifier",
2502 StartProfilerIdleNotifier);
2503 NODE_SET_METHOD(process,
2504 "_stopProfilerIdleNotifier",
2505 StopProfilerIdleNotifier);
2506 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2507 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2508 NODE_SET_METHOD(process, "reallyExit", Exit);
2509 NODE_SET_METHOD(process, "abort", Abort);
2510 NODE_SET_METHOD(process, "chdir", Chdir);
2511 NODE_SET_METHOD(process, "cwd", Cwd);
2513 NODE_SET_METHOD(process, "umask", Umask);
2515 #if defined(__POSIX__) && !defined(__ANDROID__)
2516 NODE_SET_METHOD(process, "getuid", GetUid);
2517 NODE_SET_METHOD(process, "setuid", SetUid);
2519 NODE_SET_METHOD(process, "setgid", SetGid);
2520 NODE_SET_METHOD(process, "getgid", GetGid);
2522 NODE_SET_METHOD(process, "getgroups", GetGroups);
2523 NODE_SET_METHOD(process, "setgroups", SetGroups);
2524 NODE_SET_METHOD(process, "initgroups", InitGroups);
2525 #endif // __POSIX__ && !defined(__ANDROID__)
2527 NODE_SET_METHOD(process, "_kill", Kill);
2529 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2530 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2531 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2533 NODE_SET_METHOD(process, "hrtime", Hrtime);
2535 NODE_SET_METHOD(process, "dlopen", DLOpen);
2537 NODE_SET_METHOD(process, "uptime", Uptime);
2538 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2540 NODE_SET_METHOD(process, "binding", Binding);
2542 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2544 // values use to cross communicate with processNextTick
2545 Local<Object> tick_info_obj = Object::New();
2546 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
2547 env->tick_info()->fields(),
2548 kExternalUnsignedIntArray,
2549 env->tick_info()->fields_count());
2550 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfo"), tick_info_obj);
2552 // pre-set _events object for faster emit checks
2553 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2557 #undef READONLY_PROPERTY
2560 static void AtExit() {
2561 uv_tty_reset_mode();
2565 static void SignalExit(int signal) {
2566 uv_tty_reset_mode();
2567 _exit(128 + signal);
2571 // Most of the time, it's best to use `console.error` to write
2572 // to the process.stderr stream. However, in some cases, such as
2573 // when debugging the stream.Writable class or the process.nextTick
2574 // function, it is useful to bypass JavaScript entirely.
2575 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2576 HandleScope scope(node_isolate);
2578 assert(args.Length() == 1 && args[0]->IsString() &&
2579 "must be called with a single string");
2581 String::Utf8Value message(args[0]);
2582 fprintf(stderr, "%s\n", *message);
2587 void Load(Environment* env) {
2588 HandleScope handle_scope(node_isolate);
2590 // Compile, execute the src/node.js file. (Which was included as static C
2591 // string in node_natives.h. 'natve_node' is the string containing that
2594 // The node.js file returns a function 'f'
2599 // Disable verbose mode to stop FatalException() handler from trying
2600 // to handle the exception. Errors this early in the start-up phase
2601 // are not safe to ignore.
2602 try_catch.SetVerbose(false);
2604 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2605 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2606 if (try_catch.HasCaught()) {
2607 ReportException(try_catch);
2610 assert(f_value->IsFunction());
2611 Local<Function> f = Local<Function>::Cast(f_value);
2613 // Now we call 'f' with the 'process' variable that we've built up with
2614 // all our bindings. Inside node.js we'll take care of assigning things to
2617 // We start the process this way in order to be more modular. Developers
2618 // who do not like how 'src/node.js' setups the module system but do like
2619 // Node's I/O bindings may want to replace 'f' with their own function.
2621 // Add a reference to the global object
2622 Local<Object> global = env->context()->Global();
2624 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2628 #if defined HAVE_PERFCTR
2629 InitPerfCounters(global);
2632 // Enable handling of uncaught exceptions
2633 // (FatalException(), break on uncaught exception in debugger)
2635 // This is not strictly necessary since it's almost impossible
2636 // to attach the debugger fast enought to break on exception
2637 // thrown during process startup.
2638 try_catch.SetVerbose(true);
2640 NODE_SET_METHOD(env->process_object(), "_rawDebug", RawDebug);
2642 Local<Value> arg = env->process_object();
2643 f->Call(global, 1, &arg);
2646 static void PrintHelp();
2648 static void ParseDebugOpt(const char* arg) {
2651 if (strstr(arg, "--debug-port=") == arg) {
2652 p = 1 + strchr(arg, '=');
2653 debug_port = atoi(p);
2655 use_debug_agent = true;
2656 if (!strcmp(arg, "--debug-brk")) {
2657 debug_wait_connect = true;
2659 } else if (!strcmp(arg, "--debug")) {
2661 } else if (strstr(arg, "--debug-brk=") == arg) {
2662 debug_wait_connect = true;
2663 p = 1 + strchr(arg, '=');
2664 debug_port = atoi(p);
2665 } else if (strstr(arg, "--debug=") == arg) {
2666 p = 1 + strchr(arg, '=');
2667 debug_port = atoi(p);
2670 if (p && debug_port > 1024 && debug_port < 65536)
2673 fprintf(stderr, "Bad debug option.\n");
2674 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2680 static void PrintHelp() {
2681 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2682 " node debug script.js [arguments] \n"
2685 " -v, --version print node's version\n"
2686 " -e, --eval script evaluate script\n"
2687 " -p, --print evaluate script and print result\n"
2688 " -i, --interactive always enter the REPL even if stdin\n"
2689 " does not appear to be a terminal\n"
2690 " --no-deprecation silence deprecation warnings\n"
2691 " --trace-deprecation show stack traces on deprecations\n"
2692 " --v8-options print v8 command line options\n"
2693 " --max-stack-size=val set max v8 stack size (bytes)\n"
2695 "Environment variables:\n"
2697 "NODE_PATH ';'-separated list of directories\n"
2699 "NODE_PATH ':'-separated list of directories\n"
2701 " prefixed to the module search path.\n"
2702 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2703 " global contexts.\n"
2704 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2706 "Documentation can be found at http://nodejs.org/\n");
2710 // Parse command line arguments.
2712 // argv is modified in place. exec_argv and v8_argv are out arguments that
2713 // ParseArgs() allocates memory for and stores a pointer to the output
2714 // vector in. The caller should free them with delete[].
2718 // * argv contains the arguments with node and V8 options filtered out.
2719 // * exec_argv contains both node and V8 options and nothing else.
2720 // * v8_argv contains argv[0] plus any V8 options
2721 static void ParseArgs(int* argc,
2724 const char*** exec_argv,
2726 const char*** v8_argv) {
2727 const unsigned int nargs = static_cast<unsigned int>(*argc);
2728 const char** new_exec_argv = new const char*[nargs];
2729 const char** new_v8_argv = new const char*[nargs];
2730 const char** new_argv = new const char*[nargs];
2732 for (unsigned int i = 0; i < nargs; ++i) {
2733 new_exec_argv[i] = NULL;
2734 new_v8_argv[i] = NULL;
2738 // exec_argv starts with the first option, the other two start with argv[0].
2739 unsigned int new_exec_argc = 0;
2740 unsigned int new_v8_argc = 1;
2741 unsigned int new_argc = 1;
2742 new_v8_argv[0] = argv[0];
2743 new_argv[0] = argv[0];
2745 unsigned int index = 1;
2746 while (index < nargs && argv[index][0] == '-') {
2747 const char* const arg = argv[index];
2748 unsigned int args_consumed = 1;
2750 if (strstr(arg, "--debug") == arg) {
2752 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2753 printf("%s\n", NODE_VERSION);
2755 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2758 } else if (strcmp(arg, "--eval") == 0 ||
2759 strcmp(arg, "-e") == 0 ||
2760 strcmp(arg, "--print") == 0 ||
2761 strcmp(arg, "-pe") == 0 ||
2762 strcmp(arg, "-p") == 0) {
2763 bool is_eval = strchr(arg, 'e') != NULL;
2764 bool is_print = strchr(arg, 'p') != NULL;
2765 print_eval = print_eval || is_print;
2766 // --eval, -e and -pe always require an argument.
2767 if (is_eval == true) {
2769 eval_string = argv[index + 1];
2770 if (eval_string == NULL) {
2771 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
2774 } else if (argv[index + 1] != NULL && argv[index + 1][0] != '-') {
2776 eval_string = argv[index + 1];
2777 if (strncmp(eval_string, "\\-", 2) == 0) {
2778 // Starts with "\\-": escaped expression, drop the backslash.
2782 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2784 } else if (strcmp(arg, "--no-deprecation") == 0) {
2785 no_deprecation = true;
2786 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2787 trace_deprecation = true;
2788 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2789 throw_deprecation = true;
2790 } else if (strcmp(arg, "--v8-options") == 0) {
2791 new_v8_argv[new_v8_argc] = "--help";
2794 // V8 option. Pass through as-is.
2795 new_v8_argv[new_v8_argc] = arg;
2799 memcpy(new_exec_argv + new_exec_argc,
2801 args_consumed * sizeof(*argv));
2803 new_exec_argc += args_consumed;
2804 index += args_consumed;
2807 // Copy remaining arguments.
2808 const unsigned int args_left = nargs - index;
2809 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
2810 new_argc += args_left;
2812 *exec_argc = new_exec_argc;
2813 *exec_argv = new_exec_argv;
2814 *v8_argc = new_v8_argc;
2815 *v8_argv = new_v8_argv;
2817 // Copy new_argv over argv and update argc.
2818 memcpy(argv, new_argv, new_argc * sizeof(*argv));
2820 *argc = static_cast<int>(new_argc);
2824 // Called from V8 Debug Agent TCP thread.
2825 static void DispatchMessagesDebugAgentCallback() {
2826 uv_async_send(&dispatch_debug_messages_async);
2830 // Called from the main thread.
2831 static void EnableDebug(bool wait_connect) {
2832 assert(debugger_running == false);
2833 Isolate* isolate = node_isolate; // TODO(bnoordhuis) Multi-isolate support.
2834 Isolate::Scope isolate_scope(isolate);
2835 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2837 debugger_running = v8::Debug::EnableAgent("node " NODE_VERSION,
2840 if (debugger_running == false) {
2841 fprintf(stderr, "Starting debugger on port %d failed\n", debug_port);
2845 fprintf(stderr, "Debugger listening on port %d\n", debug_port);
2848 Environment* env = Environment::GetCurrentChecked(isolate);
2850 return; // Still starting up.
2852 Context::Scope context_scope(env->context());
2853 HandleScope handle_scope(env->isolate());
2854 Local<Object> message = Object::New();
2855 message->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "cmd"),
2856 FIXED_ONE_BYTE_STRING(env->isolate(), "NODE_DEBUG_ENABLED"));
2857 Local<Value> argv[] = {
2858 FIXED_ONE_BYTE_STRING(env->isolate(), "internalMessage"),
2861 MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(argv), argv);
2865 // Called from the main thread.
2866 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2867 if (debugger_running == false) {
2868 fprintf(stderr, "Starting debugger agent.\n");
2871 Isolate::Scope isolate_scope(node_isolate);
2872 v8::Debug::ProcessDebugMessages();
2877 static volatile sig_atomic_t caught_early_debug_signal;
2880 static void EarlyDebugSignalHandler(int signo) {
2881 caught_early_debug_signal = 1;
2885 static void InstallEarlyDebugSignalHandler() {
2886 struct sigaction sa;
2887 memset(&sa, 0, sizeof(sa));
2888 sa.sa_handler = EarlyDebugSignalHandler;
2889 sigaction(SIGUSR1, &sa, NULL);
2893 static void EnableDebugSignalHandler(int signo) {
2894 // Call only async signal-safe functions here!
2895 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
2896 uv_async_send(&dispatch_debug_messages_async);
2900 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2901 struct sigaction sa;
2902 memset(&sa, 0, sizeof(sa));
2903 sa.sa_handler = handler;
2904 sigfillset(&sa.sa_mask);
2905 sigaction(signal, &sa, NULL);
2909 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2910 HandleScope scope(node_isolate);
2912 if (args.Length() != 1) {
2913 return ThrowError("Invalid number of arguments.");
2919 pid = args[0]->IntegerValue();
2920 r = kill(pid, SIGUSR1);
2922 return ThrowErrnoException(errno, "kill");
2927 static int RegisterDebugSignalHandler() {
2928 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
2929 RegisterSignalHandler(SIGUSR1, EnableDebugSignalHandler);
2930 // If we caught a SIGUSR1 during the bootstrap process, re-raise it
2931 // now that the debugger infrastructure is in place.
2932 if (caught_early_debug_signal) raise(SIGUSR1);
2939 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2940 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
2941 uv_async_send(&dispatch_debug_messages_async);
2946 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2948 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2952 static int RegisterDebugSignalHandler() {
2953 wchar_t mapping_name[32];
2954 HANDLE mapping_handle;
2956 LPTHREAD_START_ROUTINE* handler;
2958 pid = GetCurrentProcessId();
2960 if (GetDebugSignalHandlerMappingName(pid,
2962 ARRAY_SIZE(mapping_name)) < 0) {
2966 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2972 if (mapping_handle == NULL) {
2976 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2977 MapViewOfFile(mapping_handle,
2978 FILE_MAP_ALL_ACCESS,
2982 if (handler == NULL) {
2983 CloseHandle(mapping_handle);
2987 *handler = EnableDebugThreadProc;
2989 UnmapViewOfFile(static_cast<void*>(handler));
2995 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2996 HandleScope scope(node_isolate);
2998 HANDLE process = NULL;
2999 HANDLE thread = NULL;
3000 HANDLE mapping = NULL;
3001 wchar_t mapping_name[32];
3002 LPTHREAD_START_ROUTINE* handler = NULL;
3004 if (args.Length() != 1) {
3005 ThrowError("Invalid number of arguments.");
3009 pid = (DWORD) args[0]->IntegerValue();
3011 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
3012 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
3016 if (process == NULL) {
3017 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
3021 if (GetDebugSignalHandlerMappingName(pid,
3023 ARRAY_SIZE(mapping_name)) < 0) {
3024 ThrowErrnoException(errno, "sprintf");
3028 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
3029 if (mapping == NULL) {
3030 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
3034 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3035 MapViewOfFile(mapping,
3040 if (handler == NULL || *handler == NULL) {
3041 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
3045 thread = CreateRemoteThread(process,
3052 if (thread == NULL) {
3053 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
3057 // Wait for the thread to terminate
3058 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3059 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
3064 if (process != NULL)
3065 CloseHandle(process);
3067 CloseHandle(thread);
3068 if (handler != NULL)
3069 UnmapViewOfFile(handler);
3070 if (mapping != NULL)
3071 CloseHandle(mapping);
3076 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3077 v8::Debug::DebugBreak(node_isolate);
3081 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3082 if (debugger_running) {
3083 v8::Debug::DisableAgent();
3084 debugger_running = false;
3089 void Init(int* argc,
3092 const char*** exec_argv) {
3093 // Initialize prog_start_time to get relative uptime.
3094 uv_uptime(&prog_start_time);
3096 // Make inherited handles noninheritable.
3097 uv_disable_stdio_inheritance();
3099 // init async debug messages dispatching
3100 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3101 uv_async_init(uv_default_loop(),
3102 &dispatch_debug_messages_async,
3103 DispatchDebugMessagesAsyncCallback);
3104 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3106 // Parse a few arguments which are specific to Node.
3108 const char** v8_argv;
3109 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3111 // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
3112 // manually? That would give us a little more control over its runtime
3113 // behavior but it could also interfere with the user's intentions in ways
3114 // we fail to anticipate. Dillema.
3115 for (int i = 1; i < v8_argc; ++i) {
3116 if (strncmp(v8_argv[i], "--prof", sizeof("--prof") - 1) == 0) {
3117 v8_is_profiling = true;
3122 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3123 // the argv array or the elements it points to.
3124 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3126 // Anything that's still in v8_argv is not a V8 or a node option.
3127 for (int i = 1; i < v8_argc; i++) {
3128 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3137 if (debug_wait_connect) {
3138 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3139 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3142 const char typed_arrays_flag[] = "--harmony_typed_arrays";
3143 V8::SetFlagsFromString(typed_arrays_flag, sizeof(typed_arrays_flag) - 1);
3144 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3146 // Fetch a reference to the main isolate, so we have a reference to it
3147 // even when we need it to access it from another (debugger) thread.
3148 node_isolate = Isolate::GetCurrent();
3151 // Raise the open file descriptor limit.
3152 { // NOLINT (whitespace/braces)
3154 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3155 // Do a binary search for the limit.
3156 rlim_t min = lim.rlim_cur;
3157 rlim_t max = 1 << 20;
3158 // But if there's a defined upper bound, don't search, just set it.
3159 if (lim.rlim_max != RLIM_INFINITY) {
3164 lim.rlim_cur = min + (max - min) / 2;
3165 if (setrlimit(RLIMIT_NOFILE, &lim)) {
3170 } while (min + 1 < max);
3174 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3175 RegisterSignalHandler(SIGINT, SignalExit);
3176 RegisterSignalHandler(SIGTERM, SignalExit);
3179 V8::SetFatalErrorHandler(node::OnFatalError);
3180 V8::AddMessageListener(OnMessage);
3182 // If the --debug flag was specified then initialize the debug thread.
3183 if (use_debug_agent) {
3184 EnableDebug(debug_wait_connect);
3186 RegisterDebugSignalHandler();
3191 struct AtExitCallback {
3192 AtExitCallback* next_;
3193 void (*cb_)(void* arg);
3197 static AtExitCallback* at_exit_functions_;
3200 // TODO(bnoordhuis) Turn into per-context event.
3201 void RunAtExit(Environment* env) {
3202 AtExitCallback* p = at_exit_functions_;
3203 at_exit_functions_ = NULL;
3206 AtExitCallback* q = p->next_;
3214 void AtExit(void (*cb)(void* arg), void* arg) {
3215 AtExitCallback* p = new AtExitCallback;
3218 p->next_ = at_exit_functions_;
3219 at_exit_functions_ = p;
3223 void EmitExit(Environment* env) {
3224 // process.emit('exit')
3225 Context::Scope context_scope(env->context());
3226 HandleScope handle_scope(env->isolate());
3227 Local<Object> process_object = env->process_object();
3228 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3229 True(node_isolate));
3231 Handle<String> exitCode = FIXED_ONE_BYTE_STRING(node_isolate, "exitCode");
3232 int code = process_object->Get(exitCode)->IntegerValue();
3234 Local<Value> args[] = {
3235 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3236 Integer::New(code, node_isolate)
3239 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3244 Environment* CreateEnvironment(Isolate* isolate,
3246 const char* const* argv,
3248 const char* const* exec_argv) {
3249 HandleScope handle_scope(isolate);
3251 Local<Context> context = Context::New(isolate);
3252 Context::Scope context_scope(context);
3253 Environment* env = Environment::New(context);
3255 uv_check_init(env->event_loop(), env->immediate_check_handle());
3257 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3258 uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3260 // Inform V8's CPU profiler when we're idle. The profiler is sampling-based
3261 // but not all samples are created equal; mark the wall clock time spent in
3262 // epoll_wait() and friends so profiling tools can filter it out. The samples
3263 // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
3264 // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
3265 // probably fortify in the API contract, namely that the last started prepare
3266 // or check watcher runs first. It's not 100% foolproof; if an add-on starts
3267 // a prepare or check watcher after us, any samples attributed to its callback
3268 // will be recorded with state=IDLE.
3269 uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
3270 uv_check_init(env->event_loop(), env->idle_check_handle());
3271 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
3272 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
3274 if (v8_is_profiling) {
3275 StartProfilerIdleNotifier(env);
3278 Local<FunctionTemplate> process_template = FunctionTemplate::New();
3279 process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3281 Local<Object> process_object = process_template->GetFunction()->NewInstance();
3282 env->set_process_object(process_object);
3284 SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3291 int Start(int argc, char** argv) {
3292 #if !defined(_WIN32)
3293 // Try hard not to lose SIGUSR1 signals during the bootstrap process.
3294 InstallEarlyDebugSignalHandler();
3299 // Hack around with the argv pointer. Used for process.title = "blah".
3300 argv = uv_setup_args(argc, argv);
3302 // This needs to run *before* V8::Initialize(). The const_cast is not
3303 // optional, in case you're wondering.
3305 const char** exec_argv;
3306 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3309 // V8 on Windows doesn't have a good source of entropy. Seed it from
3311 V8::SetEntropySource(crypto::EntropySource);
3316 Locker locker(node_isolate);
3318 CreateEnvironment(node_isolate, argc, argv, exec_argc, exec_argv);
3319 Context::Scope context_scope(env->context());
3320 HandleScope handle_scope(env->isolate());
3321 uv_run(env->event_loop(), UV_RUN_DEFAULT);
3329 // Clean up. Not strictly necessary.