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* AllocateUninitialized(size_t length);
157 virtual void Free(void* data, size_t length);
159 ArrayBufferAllocator() {}
160 ArrayBufferAllocator(const ArrayBufferAllocator&);
161 void operator=(const ArrayBufferAllocator&);
164 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
167 void* ArrayBufferAllocator::Allocate(size_t length) {
168 if (length > kMaxLength)
170 return new char[length];
174 void* ArrayBufferAllocator::AllocateUninitialized(size_t length) {
175 if (length > kMaxLength)
177 return new char[length];
181 void ArrayBufferAllocator::Free(void* data, size_t length) {
182 delete[] static_cast<char*>(data);
186 static void CheckImmediate(uv_check_t* handle, int status) {
187 Environment* env = Environment::from_immediate_check_handle(handle);
188 Context::Scope context_scope(env->context());
189 MakeCallback(env, env->process_object(), env->immediate_callback_string());
193 static void IdleImmediateDummy(uv_idle_t*, int) {
194 // Do nothing. Only for maintaining event loop.
195 // TODO(bnoordhuis) Maybe make libuv accept NULL idle callbacks.
199 static inline const char *errno_string(int errorno) {
200 #define ERRNO_CASE(e) case e: return #e;
207 ERRNO_CASE(EADDRINUSE);
211 ERRNO_CASE(EADDRNOTAVAIL);
215 ERRNO_CASE(EAFNOSUPPORT);
223 # if EAGAIN != EWOULDBLOCK
224 ERRNO_CASE(EWOULDBLOCK);
229 ERRNO_CASE(EALREADY);
245 ERRNO_CASE(ECANCELED);
253 ERRNO_CASE(ECONNABORTED);
257 ERRNO_CASE(ECONNREFUSED);
261 ERRNO_CASE(ECONNRESET);
269 ERRNO_CASE(EDESTADDRREQ);
293 ERRNO_CASE(EHOSTUNREACH);
305 ERRNO_CASE(EINPROGRESS);
341 ERRNO_CASE(EMSGSIZE);
345 ERRNO_CASE(EMULTIHOP);
349 ERRNO_CASE(ENAMETOOLONG);
353 ERRNO_CASE(ENETDOWN);
357 ERRNO_CASE(ENETRESET);
361 ERRNO_CASE(ENETUNREACH);
393 # if ENOLINK != ENOLCK
407 ERRNO_CASE(ENOPROTOOPT);
427 ERRNO_CASE(ENOTCONN);
435 ERRNO_CASE(ENOTEMPTY);
439 ERRNO_CASE(ENOTSOCK);
446 ERRNO_CASE(EOPNOTSUPP);
460 ERRNO_CASE(EOVERFLOW);
475 #ifdef EPROTONOSUPPORT
476 ERRNO_CASE(EPROTONOSUPPORT);
480 ERRNO_CASE(EPROTOTYPE);
508 ERRNO_CASE(ETIMEDOUT);
523 const char *signo_string(int signo) {
524 #define SIGNO_CASE(e) case e: return #e;
551 # if SIGABRT != SIGIOT
595 SIGNO_CASE(SIGSTKFLT);
612 SIGNO_CASE(SIGBREAK);
636 SIGNO_CASE(SIGVTALRM);
644 SIGNO_CASE(SIGWINCH);
652 # if SIGPOLL != SIGIO
662 # if SIGPWR != SIGLOST
676 Local<Value> ErrnoException(int errorno,
680 Environment* env = Environment::GetCurrent(node_isolate);
683 Local<String> estring = OneByteString(node_isolate, errno_string(errorno));
684 if (msg == NULL || msg[0] == '\0') {
685 msg = strerror(errorno);
687 Local<String> message = OneByteString(node_isolate, msg);
689 Local<String> cons1 =
690 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
691 Local<String> cons2 = String::Concat(cons1, message);
694 Local<String> cons3 =
695 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
696 Local<String> cons4 =
697 String::Concat(cons3, String::NewFromUtf8(node_isolate, path));
698 Local<String> cons5 =
699 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
700 e = Exception::Error(cons5);
702 e = Exception::Error(cons2);
705 Local<Object> obj = e->ToObject();
706 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
707 obj->Set(env->code_string(), estring);
710 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
713 if (syscall != NULL) {
714 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
721 // hack alert! copy of ErrnoException, tuned for uv errors
722 Local<Value> UVException(int errorno,
726 Environment* env = Environment::GetCurrent(node_isolate);
729 msg = uv_strerror(errorno);
731 Local<String> estring = OneByteString(node_isolate, uv_err_name(errorno));
732 Local<String> message = OneByteString(node_isolate, msg);
733 Local<String> cons1 =
734 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
735 Local<String> cons2 = String::Concat(cons1, message);
739 Local<String> path_str;
743 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
744 path_str = String::Concat(FIXED_ONE_BYTE_STRING(node_isolate, "\\\\"),
745 String::NewFromUtf8(node_isolate, path + 8));
746 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
747 path_str = String::NewFromUtf8(node_isolate, path + 4);
749 path_str = String::NewFromUtf8(node_isolate, path);
752 path_str = String::NewFromUtf8(node_isolate, path);
755 Local<String> cons3 =
756 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
757 Local<String> cons4 =
758 String::Concat(cons3, path_str);
759 Local<String> cons5 =
760 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
761 e = Exception::Error(cons5);
763 e = Exception::Error(cons2);
766 Local<Object> obj = e->ToObject();
767 // TODO(piscisaureus) errno should probably go
768 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
769 obj->Set(env->code_string(), estring);
772 obj->Set(env->path_string(), path_str);
775 if (syscall != NULL) {
776 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
784 // Does about the same as strerror(),
785 // but supports all windows error messages
786 static const char *winapi_strerror(const int errorno) {
789 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
790 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
791 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
794 // Remove trailing newlines
795 for (int i = strlen(errmsg) - 1;
796 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
802 // FormatMessage failed
803 return "Unknown error";
808 Local<Value> WinapiErrnoException(int errorno,
812 Environment* env = Environment::GetCurrent(node_isolate);
815 if (!msg || !msg[0]) {
816 msg = winapi_strerror(errorno);
818 Local<String> message = OneByteString(node_isolate, msg);
821 Local<String> cons1 =
822 String::Concat(message, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
823 Local<String> cons2 =
824 String::Concat(cons1, String::NewFromUtf8(node_isolate, path));
825 Local<String> cons3 =
826 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
827 e = Exception::Error(cons3);
829 e = Exception::Error(message);
832 Local<Object> obj = e->ToObject();
833 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
836 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
839 if (syscall != NULL) {
840 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
848 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
849 Environment* env = Environment::GetCurrent(args.GetIsolate());
851 if (env->using_domains())
853 env->set_using_domains(true);
855 HandleScope scope(node_isolate);
856 Local<Object> process_object = env->process_object();
858 Local<String> tick_callback_function_key =
859 FIXED_ONE_BYTE_STRING(node_isolate, "_tickDomainCallback");
860 Local<Function> tick_callback_function =
861 process_object->Get(tick_callback_function_key).As<Function>();
863 if (!tick_callback_function->IsFunction()) {
864 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
868 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"),
869 tick_callback_function);
870 env->set_tick_callback_function(tick_callback_function);
872 if (!args[0]->IsArray()) {
873 fprintf(stderr, "_setupDomainUse first argument must be an array\n");
876 env->set_domain_array(args[0].As<Array>());
878 if (!args[1]->IsObject()) {
879 fprintf(stderr, "_setupDomainUse second argument must be an object\n");
883 Local<Object> domain_flag_obj = args[1].As<Object>();
884 Environment::DomainFlag* domain_flag = env->domain_flag();
885 domain_flag_obj->SetIndexedPropertiesToExternalArrayData(
886 domain_flag->fields(),
887 kExternalUnsignedIntArray,
888 domain_flag->fields_count());
892 Handle<Value> MakeDomainCallback(Environment* env,
893 const Handle<Object> object,
894 const Handle<Function> callback,
896 Handle<Value> argv[]) {
897 // If you hit this assertion, you forgot to enter the v8::Context first.
898 assert(env->context() == env->isolate()->GetCurrentContext());
900 // TODO(trevnorris) Hook for long stack traces to be made here.
902 Local<Value> domain_v = object->Get(env->domain_string());
903 Local<Object> domain;
906 try_catch.SetVerbose(true);
908 bool has_domain = domain_v->IsObject();
910 domain = domain_v.As<Object>();
912 if (domain->Get(env->disposed_string())->IsTrue()) {
913 // domain has been disposed of.
914 return Undefined(node_isolate);
917 Local<Function> enter =
918 domain->Get(env->enter_string()).As<Function>();
919 assert(enter->IsFunction());
920 enter->Call(domain, 0, NULL);
922 if (try_catch.HasCaught()) {
923 return Undefined(node_isolate);
927 Local<Value> ret = callback->Call(object, argc, argv);
929 if (try_catch.HasCaught()) {
930 return Undefined(node_isolate);
934 Local<Function> exit =
935 domain->Get(env->exit_string()).As<Function>();
936 assert(exit->IsFunction());
937 exit->Call(domain, 0, NULL);
939 if (try_catch.HasCaught()) {
940 return Undefined(node_isolate);
944 Environment::TickInfo* tick_info = env->tick_info();
946 if (tick_info->last_threw() == 1) {
947 tick_info->set_last_threw(0);
951 if (tick_info->in_tick() == 1) {
955 if (tick_info->length() == 0) {
956 tick_info->set_index(0);
960 // process nextTicks after call
961 Local<Object> process_object = env->process_object();
962 Local<Function> tick_callback_function = env->tick_callback_function();
963 tick_callback_function->Call(process_object, 0, NULL);
965 if (try_catch.HasCaught()) {
966 return Undefined(node_isolate);
973 Handle<Value> MakeCallback(Environment* env,
974 const Handle<Object> object,
975 const Handle<Function> callback,
977 Handle<Value> argv[]) {
978 // If you hit this assertion, you forgot to enter the v8::Context first.
979 assert(env->context() == env->isolate()->GetCurrentContext());
981 // TODO(trevnorris) Hook for long stack traces to be made here.
982 Local<Object> process_object = env->process_object();
984 if (env->using_domains())
985 return MakeDomainCallback(env, object, callback, argc, argv);
988 try_catch.SetVerbose(true);
990 Local<Value> ret = callback->Call(object, argc, argv);
992 if (try_catch.HasCaught()) {
993 return Undefined(node_isolate);
996 Environment::TickInfo* tick_info = env->tick_info();
998 if (tick_info->in_tick() == 1) {
1002 if (tick_info->length() == 0) {
1003 tick_info->set_index(0);
1007 // lazy load no domain next tick callbacks
1008 Local<Function> tick_callback_function = env->tick_callback_function();
1009 if (tick_callback_function.IsEmpty()) {
1010 Local<String> tick_callback_function_key =
1011 FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback");
1012 tick_callback_function =
1013 process_object->Get(tick_callback_function_key).As<Function>();
1014 if (!tick_callback_function->IsFunction()) {
1015 fprintf(stderr, "process._tickCallback assigned to non-function\n");
1018 env->set_tick_callback_function(tick_callback_function);
1021 // process nextTicks after call
1022 tick_callback_function->Call(process_object, 0, NULL);
1024 if (try_catch.HasCaught()) {
1025 return Undefined(node_isolate);
1033 Handle<Value> MakeCallback(Environment* env,
1034 const Handle<Object> object,
1037 Handle<Value> argv[]) {
1038 // If you hit this assertion, you forgot to enter the v8::Context first.
1039 assert(env->context() == env->isolate()->GetCurrentContext());
1041 Local<Function> callback = object->Get(index).As<Function>();
1042 assert(callback->IsFunction());
1044 if (env->using_domains()) {
1045 return MakeDomainCallback(env, object, callback, argc, argv);
1048 return MakeCallback(env, object, callback, argc, argv);
1052 Handle<Value> MakeCallback(Environment* env,
1053 const Handle<Object> object,
1054 const Handle<String> symbol,
1056 Handle<Value> argv[]) {
1057 // If you hit this assertion, you forgot to enter the v8::Context first.
1058 assert(env->context() == env->isolate()->GetCurrentContext());
1060 Local<Function> callback = object->Get(symbol).As<Function>();
1061 assert(callback->IsFunction());
1063 if (env->using_domains()) {
1064 return MakeDomainCallback(env, object, callback, argc, argv);
1067 return MakeCallback(env, object, callback, argc, argv);
1071 Handle<Value> MakeCallback(Environment* env,
1072 const Handle<Object> object,
1075 Handle<Value> argv[]) {
1076 // If you hit this assertion, you forgot to enter the v8::Context first.
1077 assert(env->context() == env->isolate()->GetCurrentContext());
1078 Local<String> method_string = OneByteString(node_isolate, method);
1079 return MakeCallback(env, object, method_string, argc, argv);
1083 Handle<Value> MakeCallback(const Handle<Object> object,
1086 Handle<Value> argv[]) {
1087 Local<Context> context = object->CreationContext();
1088 Environment* env = Environment::GetCurrent(context);
1089 Context::Scope context_scope(context);
1090 HandleScope handle_scope(env->isolate());
1091 return handle_scope.Close(MakeCallback(env, object, method, argc, argv));
1095 Handle<Value> MakeCallback(const Handle<Object> object,
1096 const Handle<String> symbol,
1098 Handle<Value> argv[]) {
1099 Local<Context> context = object->CreationContext();
1100 Environment* env = Environment::GetCurrent(context);
1101 Context::Scope context_scope(context);
1102 HandleScope handle_scope(env->isolate());
1103 return handle_scope.Close(MakeCallback(env, object, symbol, argc, argv));
1107 Handle<Value> MakeCallback(const Handle<Object> object,
1108 const Handle<Function> callback,
1110 Handle<Value> argv[]) {
1111 Local<Context> context = object->CreationContext();
1112 Environment* env = Environment::GetCurrent(context);
1113 Context::Scope context_scope(context);
1114 HandleScope handle_scope(env->isolate());
1115 return handle_scope.Close(MakeCallback(env, object, callback, argc, argv));
1119 Handle<Value> MakeDomainCallback(const Handle<Object> object,
1120 const Handle<Function> callback,
1122 Handle<Value> argv[]) {
1123 Local<Context> context = object->CreationContext();
1124 Environment* env = Environment::GetCurrent(context);
1125 Context::Scope context_scope(context);
1126 HandleScope handle_scope(env->isolate());
1127 return handle_scope.Close(
1128 MakeDomainCallback(env, object, callback, argc, argv));
1132 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1133 HandleScope scope(node_isolate);
1135 if (!encoding_v->IsString())
1138 String::Utf8Value encoding(encoding_v);
1140 if (strcasecmp(*encoding, "utf8") == 0) {
1142 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1144 } else if (strcasecmp(*encoding, "ascii") == 0) {
1146 } else if (strcasecmp(*encoding, "base64") == 0) {
1148 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1150 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1152 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1154 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1156 } else if (strcasecmp(*encoding, "binary") == 0) {
1158 } else if (strcasecmp(*encoding, "buffer") == 0) {
1160 } else if (strcasecmp(*encoding, "hex") == 0) {
1162 } else if (strcasecmp(*encoding, "raw") == 0) {
1163 if (!no_deprecation) {
1164 fprintf(stderr, "'raw' (array of integers) has been removed. "
1168 } else if (strcasecmp(*encoding, "raws") == 0) {
1169 if (!no_deprecation) {
1170 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1171 "Please update your code.\n");
1179 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1180 return StringBytes::Encode(static_cast<const char*>(buf),
1185 // Returns -1 if the handle was not valid for decoding
1186 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1187 HandleScope scope(node_isolate);
1189 if (val->IsArray()) {
1190 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1196 return StringBytes::Size(val, encoding);
1200 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1203 // Returns number of bytes written.
1204 ssize_t DecodeWrite(char *buf,
1206 v8::Handle<v8::Value> val,
1207 enum encoding encoding) {
1208 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1211 void DisplayExceptionLine(Handle<Message> message) {
1212 // Prevent re-entry into this function. For example, if there is
1213 // a throw from a program in vm.runInThisContext(code, filename, true),
1214 // then we want to show the original failure, not the secondary one.
1215 static bool displayed_error = false;
1217 if (displayed_error)
1219 displayed_error = true;
1221 uv_tty_reset_mode();
1223 fprintf(stderr, "\n");
1225 if (!message.IsEmpty()) {
1226 // Print (filename):(line number): (message).
1227 String::Utf8Value filename(message->GetScriptResourceName());
1228 const char* filename_string = *filename;
1229 int linenum = message->GetLineNumber();
1230 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1231 // Print line of source code.
1232 String::Utf8Value sourceline(message->GetSourceLine());
1233 const char* sourceline_string = *sourceline;
1235 // Because of how node modules work, all scripts are wrapped with a
1236 // "function (module, exports, __filename, ...) {"
1237 // to provide script local variables.
1239 // When reporting errors on the first line of a script, this wrapper
1240 // function is leaked to the user. There used to be a hack here to
1241 // truncate off the first 62 characters, but it caused numerous other
1242 // problems when vm.runIn*Context() methods were used for non-module
1245 // If we ever decide to re-instate such a hack, the following steps
1248 // 1. Pass a flag around to say "this code was wrapped"
1249 // 2. Update the stack frame output so that it is also correct.
1251 // It would probably be simpler to add a line rather than add some
1252 // number of characters to the first line, since V8 truncates the
1253 // sourceline to 78 characters, and we end up not providing very much
1254 // useful debugging info to the user if we remove 62 characters.
1256 int start = message->GetStartColumn();
1257 int end = message->GetEndColumn();
1259 fprintf(stderr, "%s\n", sourceline_string);
1260 // Print wavy underline (GetUnderline is deprecated).
1261 for (int i = 0; i < start; i++) {
1262 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1264 for (int i = start; i < end; i++) {
1267 fputc('\n', stderr);
1272 static void ReportException(Handle<Value> er, Handle<Message> message) {
1273 HandleScope scope(node_isolate);
1275 DisplayExceptionLine(message);
1277 Local<Value> trace_value(
1278 er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack")));
1279 String::Utf8Value trace(trace_value);
1281 // range errors have a trace member set to undefined
1282 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1283 fprintf(stderr, "%s\n", *trace);
1285 // this really only happens for RangeErrors, since they're the only
1286 // kind that won't have all this info in the trace, or when non-Error
1287 // objects are thrown manually.
1288 Local<Value> message;
1291 if (er->IsObject()) {
1292 Local<Object> err_obj = er.As<Object>();
1293 message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1294 name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1297 if (message.IsEmpty() ||
1298 message->IsUndefined() ||
1300 name->IsUndefined()) {
1301 // Not an error object. Just print as-is.
1302 String::Utf8Value message(er);
1303 fprintf(stderr, "%s\n", *message);
1305 String::Utf8Value name_string(name);
1306 String::Utf8Value message_string(message);
1307 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1315 static void ReportException(const TryCatch& try_catch) {
1316 ReportException(try_catch.Exception(), try_catch.Message());
1320 // Executes a str within the current v8 context.
1321 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1322 HandleScope scope(node_isolate);
1325 // try_catch must be nonverbose to disable FatalException() handler,
1326 // we will handle exceptions ourself.
1327 try_catch.SetVerbose(false);
1329 Local<v8::Script> script = v8::Script::Compile(source, filename);
1330 if (script.IsEmpty()) {
1331 ReportException(try_catch);
1335 Local<Value> result = script->Run();
1336 if (result.IsEmpty()) {
1337 ReportException(try_catch);
1341 return scope.Close(result);
1345 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1346 HandleScope scope(node_isolate);
1348 Local<Array> ary = Array::New();
1352 QUEUE_FOREACH(q, &req_wrap_queue) {
1353 ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1354 if (w->persistent().IsEmpty())
1356 ary->Set(i++, w->object());
1359 args.GetReturnValue().Set(ary);
1363 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1364 // implemented here for consistency with GetActiveRequests().
1365 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1366 HandleScope scope(node_isolate);
1368 Local<Array> ary = Array::New();
1372 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1374 QUEUE_FOREACH(q, &handle_wrap_queue) {
1375 HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1376 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref))
1378 Local<Object> object = w->object();
1379 Local<Value> owner = object->Get(owner_sym);
1380 if (owner->IsUndefined())
1382 ary->Set(i++, owner);
1385 args.GetReturnValue().Set(ary);
1389 static void Abort(const FunctionCallbackInfo<Value>& args) {
1394 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1395 HandleScope scope(node_isolate);
1397 if (args.Length() != 1 || !args[0]->IsString()) {
1398 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1401 String::Utf8Value path(args[0]);
1402 int err = uv_chdir(*path);
1404 return ThrowUVException(err, "uv_chdir");
1409 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1410 HandleScope scope(node_isolate);
1412 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1413 char buf[MAX_PATH * 4 + 1];
1415 char buf[PATH_MAX + 1];
1418 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1420 return ThrowUVException(err, "uv_cwd");
1423 buf[ARRAY_SIZE(buf) - 1] = '\0';
1424 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1426 args.GetReturnValue().Set(cwd);
1430 static void Umask(const FunctionCallbackInfo<Value>& args) {
1431 HandleScope scope(node_isolate);
1434 if (args.Length() < 1 || args[0]->IsUndefined()) {
1436 umask(static_cast<mode_t>(old));
1437 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1438 return ThrowTypeError("argument must be an integer or octal string.");
1441 if (args[0]->IsInt32()) {
1442 oct = args[0]->Uint32Value();
1445 String::Utf8Value str(args[0]);
1447 // Parse the octal string.
1448 for (int i = 0; i < str.length(); i++) {
1450 if (c > '7' || c < '0') {
1451 return ThrowTypeError("invalid octal string");
1457 old = umask(static_cast<mode_t>(oct));
1460 args.GetReturnValue().Set(old);
1464 #if defined(__POSIX__) && !defined(__ANDROID__)
1466 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1467 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1470 static uid_t uid_by_name(const char* name) {
1478 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1482 return uid_not_found;
1486 static char* name_by_uid(uid_t uid) {
1495 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1496 return strdup(pp->pw_name);
1507 static gid_t gid_by_name(const char* name) {
1515 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1519 return gid_not_found;
1523 #if 0 // For future use.
1524 static const char* name_by_gid(gid_t gid) {
1533 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1534 return strdup(pp->gr_name);
1546 static uid_t uid_by_name(Handle<Value> value) {
1547 if (value->IsUint32()) {
1548 return static_cast<uid_t>(value->Uint32Value());
1550 String::Utf8Value name(value);
1551 return uid_by_name(*name);
1556 static gid_t gid_by_name(Handle<Value> value) {
1557 if (value->IsUint32()) {
1558 return static_cast<gid_t>(value->Uint32Value());
1560 String::Utf8Value name(value);
1561 return gid_by_name(*name);
1566 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1567 // uid_t is an uint32_t on all supported platforms.
1568 args.GetReturnValue().Set(static_cast<uint32_t>(getuid()));
1572 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1573 // gid_t is an uint32_t on all supported platforms.
1574 args.GetReturnValue().Set(static_cast<uint32_t>(getgid()));
1578 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1579 HandleScope scope(node_isolate);
1581 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1582 return ThrowTypeError("setgid argument must be a number or a string");
1585 gid_t gid = gid_by_name(args[0]);
1587 if (gid == gid_not_found) {
1588 return ThrowError("setgid group id does not exist");
1592 return ThrowErrnoException(errno, "setgid");
1597 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1598 HandleScope scope(node_isolate);
1600 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1601 return ThrowTypeError("setuid argument must be a number or a string");
1604 uid_t uid = uid_by_name(args[0]);
1606 if (uid == uid_not_found) {
1607 return ThrowError("setuid user id does not exist");
1611 return ThrowErrnoException(errno, "setuid");
1616 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1617 HandleScope scope(node_isolate);
1619 int ngroups = getgroups(0, NULL);
1621 if (ngroups == -1) {
1622 return ThrowErrnoException(errno, "getgroups");
1625 gid_t* groups = new gid_t[ngroups];
1627 ngroups = getgroups(ngroups, groups);
1629 if (ngroups == -1) {
1631 return ThrowErrnoException(errno, "getgroups");
1634 Local<Array> groups_list = Array::New(ngroups);
1635 bool seen_egid = false;
1636 gid_t egid = getegid();
1638 for (int i = 0; i < ngroups; i++) {
1639 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1640 if (groups[i] == egid)
1646 if (seen_egid == false) {
1647 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1650 args.GetReturnValue().Set(groups_list);
1654 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1655 HandleScope scope(node_isolate);
1657 if (!args[0]->IsArray()) {
1658 return ThrowTypeError("argument 1 must be an array");
1661 Local<Array> groups_list = args[0].As<Array>();
1662 size_t size = groups_list->Length();
1663 gid_t* groups = new gid_t[size];
1665 for (size_t i = 0; i < size; i++) {
1666 gid_t gid = gid_by_name(groups_list->Get(i));
1668 if (gid == gid_not_found) {
1670 return ThrowError("group name not found");
1676 int rc = setgroups(size, groups);
1680 return ThrowErrnoException(errno, "setgroups");
1685 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1686 HandleScope scope(node_isolate);
1688 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1689 return ThrowTypeError("argument 1 must be a number or a string");
1692 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1693 return ThrowTypeError("argument 2 must be a number or a string");
1696 String::Utf8Value arg0(args[0]);
1701 if (args[0]->IsUint32()) {
1702 user = name_by_uid(args[0]->Uint32Value());
1710 return ThrowError("initgroups user not found");
1713 extra_group = gid_by_name(args[1]);
1715 if (extra_group == gid_not_found) {
1718 return ThrowError("initgroups extra group not found");
1721 int rc = initgroups(user, extra_group);
1728 return ThrowErrnoException(errno, "initgroups");
1732 #endif // __POSIX__ && !defined(__ANDROID__)
1735 void Exit(const FunctionCallbackInfo<Value>& args) {
1736 HandleScope scope(node_isolate);
1737 exit(args[0]->IntegerValue());
1741 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1742 HandleScope scope(node_isolate);
1744 if (uv_uptime(&uptime))
1746 args.GetReturnValue().Set(uptime - prog_start_time);
1750 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1751 Environment* env = Environment::GetCurrent(args.GetIsolate());
1752 HandleScope handle_scope(args.GetIsolate());
1755 int err = uv_resident_set_memory(&rss);
1757 return ThrowUVException(err, "uv_resident_set_memory");
1761 HeapStatistics v8_heap_stats;
1762 node_isolate->GetHeapStatistics(&v8_heap_stats);
1764 Local<Integer> heap_total =
1765 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(), node_isolate);
1766 Local<Integer> heap_used =
1767 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(), node_isolate);
1769 Local<Object> info = Object::New();
1770 info->Set(env->rss_string(), Number::New(node_isolate, rss));
1771 info->Set(env->heap_total_string(), heap_total);
1772 info->Set(env->heap_used_string(), heap_used);
1774 args.GetReturnValue().Set(info);
1778 void Kill(const FunctionCallbackInfo<Value>& args) {
1779 HandleScope scope(node_isolate);
1781 if (args.Length() != 2) {
1782 return ThrowError("Bad argument.");
1785 int pid = args[0]->IntegerValue();
1786 int sig = args[1]->Int32Value();
1787 int err = uv_kill(pid, sig);
1788 args.GetReturnValue().Set(err);
1791 // used in Hrtime() below
1792 #define NANOS_PER_SEC 1000000000
1794 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1795 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1796 // so this function instead returns an Array with 2 entries representing seconds
1797 // and nanoseconds, to avoid any integer overflow possibility.
1798 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1799 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1800 HandleScope scope(node_isolate);
1802 uint64_t t = uv_hrtime();
1804 if (args.Length() > 0) {
1805 // return a time diff tuple
1806 if (!args[0]->IsArray()) {
1807 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1809 Local<Array> inArray = Local<Array>::Cast(args[0]);
1810 uint64_t seconds = inArray->Get(0)->Uint32Value();
1811 uint64_t nanos = inArray->Get(1)->Uint32Value();
1812 t -= (seconds * NANOS_PER_SEC) + nanos;
1815 Local<Array> tuple = Array::New(2);
1816 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1817 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1818 args.GetReturnValue().Set(tuple);
1822 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1824 // DLOpen is process.dlopen(module, filename).
1825 // Used to load 'module.node' dynamically shared objects.
1827 // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
1828 // when two contexts try to load the same shared object. Maybe have a shadow
1829 // cache that's a plain C list or hash table that's shared across contexts?
1830 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1831 Environment* env = Environment::GetCurrent(args.GetIsolate());
1832 HandleScope handle_scope(args.GetIsolate());
1833 char symbol[1024], *base, *pos;
1837 if (args.Length() < 2) {
1838 return ThrowError("process.dlopen takes exactly 2 arguments.");
1841 Local<Object> module = args[0]->ToObject(); // Cast
1842 String::Utf8Value filename(args[1]); // Cast
1844 Local<String> exports_string = env->exports_string();
1845 Local<Object> exports = module->Get(exports_string)->ToObject();
1847 if (uv_dlopen(*filename, &lib)) {
1848 Local<String> errmsg = OneByteString(env->isolate(), uv_dlerror(&lib));
1850 // Windows needs to add the filename into the error message
1851 errmsg = String::Concat(errmsg, args[1]->ToString());
1853 ThrowException(Exception::Error(errmsg));
1857 String::Utf8Value path(args[1]);
1860 /* Find the shared library filename within the full path. */
1862 pos = strrchr(base, '/');
1868 pos = strpbrk(base, "\\/:");
1876 /* Strip the .node extension. */
1877 pos = strrchr(base, '.');
1882 /* Add the `_module` suffix to the extension name. */
1883 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1884 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1885 return ThrowError("Out of memory.");
1888 /* Replace dashes with underscores. When loading foo-bar.node,
1889 * look for foo_bar_module, not foo-bar_module.
1891 for (pos = symbol; *pos != '\0'; ++pos) {
1896 node_module_struct *mod;
1897 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1899 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1900 return ThrowError(errmsg);
1903 if (mod->version != NODE_MODULE_VERSION) {
1907 "Module version mismatch. Expected %d, got %d.",
1908 NODE_MODULE_VERSION, mod->version);
1909 return ThrowError(errmsg);
1912 // Execute the C++ module
1913 if (mod->register_context_func != NULL) {
1914 mod->register_context_func(exports, module, env->context());
1915 } else if (mod->register_func != NULL) {
1916 mod->register_func(exports, module);
1918 return ThrowError("Module has no declared entry point.");
1921 // Tell coverity that 'handle' should not be freed when we return.
1922 // coverity[leaked_storage]
1926 static void OnFatalError(const char* location, const char* message) {
1928 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1930 fprintf(stderr, "FATAL ERROR: %s\n", message);
1940 NO_RETURN void FatalError(const char* location, const char* message) {
1941 OnFatalError(location, message);
1942 // to supress compiler warning
1947 void FatalException(Handle<Value> error, Handle<Message> message) {
1948 HandleScope scope(node_isolate);
1950 Environment* env = Environment::GetCurrent(node_isolate);
1951 Local<Object> process_object = env->process_object();
1952 Local<String> fatal_exception_string = env->fatal_exception_string();
1953 Local<Function> fatal_exception_function =
1954 process_object->Get(fatal_exception_string).As<Function>();
1956 if (!fatal_exception_function->IsFunction()) {
1957 // failed before the process._fatalException function was added!
1958 // this is probably pretty bad. Nothing to do but report and exit.
1959 ReportException(error, message);
1963 TryCatch fatal_try_catch;
1965 // Do not call FatalException when _fatalException handler throws
1966 fatal_try_catch.SetVerbose(false);
1968 // this will return true if the JS layer handled it, false otherwise
1969 Local<Value> caught =
1970 fatal_exception_function->Call(process_object, 1, &error);
1972 if (fatal_try_catch.HasCaught()) {
1973 // the fatal exception function threw, so we must exit
1974 ReportException(fatal_try_catch);
1978 if (false == caught->BooleanValue()) {
1979 ReportException(error, message);
1985 void FatalException(const TryCatch& try_catch) {
1986 HandleScope scope(node_isolate);
1987 // TODO(bajtos) do not call FatalException if try_catch is verbose
1988 // (requires V8 API to expose getter for try_catch.is_verbose_)
1989 FatalException(try_catch.Exception(), try_catch.Message());
1993 void OnMessage(Handle<Message> message, Handle<Value> error) {
1994 // The current version of V8 sends messages for errors only
1995 // (thus `error` is always set).
1996 FatalException(error, message);
2000 static void Binding(const FunctionCallbackInfo<Value>& args) {
2001 Environment* env = Environment::GetCurrent(args.GetIsolate());
2002 HandleScope handle_scope(args.GetIsolate());
2004 Local<String> module = args[0]->ToString();
2005 String::Utf8Value module_v(module);
2007 Local<Object> cache = env->binding_cache_object();
2008 Local<Object> exports;
2010 if (cache->Has(module)) {
2011 exports = cache->Get(module)->ToObject();
2012 args.GetReturnValue().Set(exports);
2016 // Append a string to process.moduleLoadList
2018 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
2020 Local<Array> modules = env->module_load_list_array();
2021 uint32_t l = modules->Length();
2022 modules->Set(l, OneByteString(node_isolate, buf));
2024 node_module_struct* mod = get_builtin_module(*module_v);
2026 exports = Object::New();
2027 // Internal bindings don't have a "module" object, only exports.
2028 assert(mod->register_func == NULL);
2029 assert(mod->register_context_func != NULL);
2030 Local<Value> unused = Undefined(env->isolate());
2031 mod->register_context_func(exports, unused, env->context());
2032 cache->Set(module, exports);
2033 } else if (!strcmp(*module_v, "constants")) {
2034 exports = Object::New();
2035 DefineConstants(exports);
2036 cache->Set(module, exports);
2037 } else if (!strcmp(*module_v, "natives")) {
2038 exports = Object::New();
2039 DefineJavaScript(exports);
2040 cache->Set(module, exports);
2042 return ThrowError("No such module");
2045 args.GetReturnValue().Set(exports);
2049 static void ProcessTitleGetter(Local<String> property,
2050 const PropertyCallbackInfo<Value>& info) {
2051 HandleScope scope(node_isolate);
2053 uv_get_process_title(buffer, sizeof(buffer));
2054 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2058 static void ProcessTitleSetter(Local<String> property,
2060 const PropertyCallbackInfo<void>& info) {
2061 HandleScope scope(node_isolate);
2062 String::Utf8Value title(value);
2063 // TODO(piscisaureus): protect with a lock
2064 uv_set_process_title(*title);
2068 static void EnvGetter(Local<String> property,
2069 const PropertyCallbackInfo<Value>& info) {
2070 HandleScope scope(node_isolate);
2072 String::Utf8Value key(property);
2073 const char* val = getenv(*key);
2075 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2078 String::Value key(property);
2079 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2080 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2082 ARRAY_SIZE(buffer));
2083 // If result >= sizeof buffer the buffer was too small. That should never
2084 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2086 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2087 result < ARRAY_SIZE(buffer)) {
2088 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2089 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2090 return info.GetReturnValue().Set(rc);
2093 // Not found. Fetch from prototype.
2094 info.GetReturnValue().Set(
2095 info.Data().As<Object>()->Get(property));
2099 static void EnvSetter(Local<String> property,
2101 const PropertyCallbackInfo<Value>& info) {
2102 HandleScope scope(node_isolate);
2104 String::Utf8Value key(property);
2105 String::Utf8Value val(value);
2106 setenv(*key, *val, 1);
2108 String::Value key(property);
2109 String::Value val(value);
2110 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2111 // Environment variables that start with '=' are read-only.
2112 if (key_ptr[0] != L'=') {
2113 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2116 // Whether it worked or not, always return rval.
2117 info.GetReturnValue().Set(value);
2121 static void EnvQuery(Local<String> property,
2122 const PropertyCallbackInfo<Integer>& info) {
2123 HandleScope scope(node_isolate);
2124 int32_t rc = -1; // Not found unless proven otherwise.
2126 String::Utf8Value key(property);
2130 String::Value key(property);
2131 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2132 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2133 GetLastError() == ERROR_SUCCESS) {
2135 if (key_ptr[0] == L'=') {
2136 // Environment variables that start with '=' are hidden and read-only.
2137 rc = static_cast<int32_t>(v8::ReadOnly) |
2138 static_cast<int32_t>(v8::DontDelete) |
2139 static_cast<int32_t>(v8::DontEnum);
2144 info.GetReturnValue().Set(rc);
2148 static void EnvDeleter(Local<String> property,
2149 const PropertyCallbackInfo<Boolean>& info) {
2150 HandleScope scope(node_isolate);
2153 String::Utf8Value key(property);
2154 rc = getenv(*key) != NULL;
2158 String::Value key(property);
2159 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2160 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2161 // Deletion failed. Return true if the key wasn't there in the first place,
2162 // false if it is still there.
2163 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2164 GetLastError() != ERROR_SUCCESS;
2167 info.GetReturnValue().Set(rc);
2171 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2172 HandleScope scope(node_isolate);
2175 while (environ[size])
2178 Local<Array> env = Array::New(size);
2180 for (int i = 0; i < size; ++i) {
2181 const char* var = environ[i];
2182 const char* s = strchr(var, '=');
2183 const int length = s ? s - var : strlen(var);
2184 Local<String> name = String::NewFromUtf8(node_isolate,
2186 String::kNormalString,
2191 WCHAR* environment = GetEnvironmentStringsW();
2192 if (environment == NULL)
2193 return; // This should not happen.
2194 Local<Array> env = Array::New();
2195 WCHAR* p = environment;
2197 while (*p != NULL) {
2200 // If the key starts with '=' it is a hidden environment variable.
2204 s = wcschr(p, L'=');
2209 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2210 const size_t two_byte_buffer_len = s - p;
2211 Local<String> value = String::NewFromTwoByte(node_isolate,
2213 String::kNormalString,
2214 two_byte_buffer_len);
2215 env->Set(i++, value);
2216 p = s + wcslen(s) + 1;
2218 FreeEnvironmentStringsW(environment);
2221 info.GetReturnValue().Set(env);
2225 static Handle<Object> GetFeatures() {
2226 HandleScope scope(node_isolate);
2228 Local<Object> obj = Object::New();
2229 #if defined(DEBUG) && DEBUG
2230 Local<Value> debug = True(node_isolate);
2232 Local<Value> debug = False(node_isolate);
2233 #endif // defined(DEBUG) && DEBUG
2235 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2237 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2238 // TODO(bnoordhuis) ping libuv
2239 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2241 #ifdef OPENSSL_NPN_NEGOTIATED
2242 Local<Boolean> tls_npn = True(node_isolate);
2244 Local<Boolean> tls_npn = False(node_isolate);
2246 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"), tls_npn);
2248 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2249 Local<Boolean> tls_sni = True(node_isolate);
2251 Local<Boolean> tls_sni = False(node_isolate);
2253 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"), tls_sni);
2255 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2256 Boolean::New(get_builtin_module("crypto") != NULL));
2258 return scope.Close(obj);
2262 static void DebugPortGetter(Local<String> property,
2263 const PropertyCallbackInfo<Value>& info) {
2264 HandleScope scope(node_isolate);
2265 info.GetReturnValue().Set(debug_port);
2269 static void DebugPortSetter(Local<String> property,
2271 const PropertyCallbackInfo<void>& info) {
2272 HandleScope scope(node_isolate);
2273 debug_port = value->NumberValue();
2277 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2278 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2279 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2282 void NeedImmediateCallbackGetter(Local<String> property,
2283 const PropertyCallbackInfo<Value>& info) {
2284 Environment* env = Environment::GetCurrent(info.GetIsolate());
2285 const uv_check_t* immediate_check_handle = env->immediate_check_handle();
2286 bool active = uv_is_active(
2287 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2288 info.GetReturnValue().Set(active);
2292 static void NeedImmediateCallbackSetter(
2293 Local<String> property,
2295 const PropertyCallbackInfo<void>& info) {
2296 Environment* env = Environment::GetCurrent(info.GetIsolate());
2297 HandleScope handle_scope(info.GetIsolate());
2299 uv_check_t* immediate_check_handle = env->immediate_check_handle();
2300 bool active = uv_is_active(
2301 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2303 if (active == value->BooleanValue())
2306 uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
2309 uv_check_stop(immediate_check_handle);
2310 uv_idle_stop(immediate_idle_handle);
2312 uv_check_start(immediate_check_handle, CheckImmediate);
2313 // Idle handle is needed only to stop the event loop from blocking in poll.
2314 uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
2319 void SetIdle(uv_prepare_t* handle, int) {
2320 Environment* env = Environment::from_idle_prepare_handle(handle);
2321 env->isolate()->GetCpuProfiler()->SetIdle(true);
2325 void ClearIdle(uv_check_t* handle, int) {
2326 Environment* env = Environment::from_idle_check_handle(handle);
2327 env->isolate()->GetCpuProfiler()->SetIdle(false);
2331 void StartProfilerIdleNotifier(Environment* env) {
2332 uv_prepare_start(env->idle_prepare_handle(), SetIdle);
2333 uv_check_start(env->idle_check_handle(), ClearIdle);
2337 void StopProfilerIdleNotifier(Environment* env) {
2338 uv_prepare_stop(env->idle_prepare_handle());
2339 uv_check_stop(env->idle_check_handle());
2343 void StartProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2344 StartProfilerIdleNotifier(Environment::GetCurrent(args.GetIsolate()));
2348 void StopProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2349 StopProfilerIdleNotifier(Environment::GetCurrent(args.GetIsolate()));
2353 #define READONLY_PROPERTY(obj, str, var) \
2355 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2359 void SetupProcessObject(Environment* env,
2361 const char* const* argv,
2363 const char* const* exec_argv) {
2364 HandleScope scope(node_isolate);
2367 Local<Object> process = env->process_object();
2369 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2371 ProcessTitleSetter);
2374 READONLY_PROPERTY(process,
2376 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2378 // process.moduleLoadList
2379 READONLY_PROPERTY(process,
2381 env->module_load_list_array());
2384 Local<Object> versions = Object::New();
2385 READONLY_PROPERTY(process, "versions", versions);
2387 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2389 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2390 READONLY_PROPERTY(versions,
2392 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2394 // +1 to get rid of the leading 'v'
2395 READONLY_PROPERTY(versions,
2397 OneByteString(node_isolate, NODE_VERSION + 1));
2398 READONLY_PROPERTY(versions,
2400 OneByteString(node_isolate, V8::GetVersion()));
2401 READONLY_PROPERTY(versions,
2403 OneByteString(node_isolate, uv_version_string()));
2404 READONLY_PROPERTY(versions,
2406 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2408 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2409 READONLY_PROPERTY(versions,
2411 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2414 // Stupid code to slice out the version string.
2415 int c, l = strlen(OPENSSL_VERSION_TEXT);
2416 for (i = j = 0; i < l; i++) {
2417 c = OPENSSL_VERSION_TEXT[i];
2418 if ('0' <= c && c <= '9') {
2419 for (j = i + 1; j < l; j++) {
2420 c = OPENSSL_VERSION_TEXT[j];
2430 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2434 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2437 READONLY_PROPERTY(process,
2439 OneByteString(node_isolate, PLATFORM));
2442 Local<Array> arguments = Array::New(argc);
2443 for (int i = 0; i < argc; ++i) {
2444 arguments->Set(i, String::NewFromUtf8(node_isolate, argv[i]));
2446 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2449 Local<Array> exec_arguments = Array::New(exec_argc);
2450 for (int i = 0; i < exec_argc; ++i) {
2451 exec_arguments->Set(i, String::NewFromUtf8(node_isolate, exec_argv[i]));
2453 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_arguments);
2455 // create process.env
2456 Local<ObjectTemplate> process_env_template = ObjectTemplate::New();
2457 process_env_template->SetNamedPropertyHandler(EnvGetter,
2463 Local<Object> process_env = process_env_template->NewInstance();
2464 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), process_env);
2466 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2467 READONLY_PROPERTY(process, "features", GetFeatures());
2468 process->SetAccessor(
2469 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2470 NeedImmediateCallbackGetter,
2471 NeedImmediateCallbackSetter);
2475 READONLY_PROPERTY(process,
2477 String::NewFromUtf8(node_isolate, eval_string));
2482 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2485 // -i, --interactive
2487 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2491 if (no_deprecation) {
2492 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2495 // --throw-deprecation
2496 if (throw_deprecation) {
2497 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2500 // --trace-deprecation
2501 if (trace_deprecation) {
2502 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2505 size_t exec_path_len = 2 * PATH_MAX;
2506 char* exec_path = new char[exec_path_len];
2507 Local<String> exec_path_value;
2508 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2509 exec_path_value = String::NewFromUtf8(node_isolate,
2511 String::kNormalString,
2514 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2516 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2520 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2524 // define various internal methods
2525 NODE_SET_METHOD(process,
2526 "_startProfilerIdleNotifier",
2527 StartProfilerIdleNotifier);
2528 NODE_SET_METHOD(process,
2529 "_stopProfilerIdleNotifier",
2530 StopProfilerIdleNotifier);
2531 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2532 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2533 NODE_SET_METHOD(process, "reallyExit", Exit);
2534 NODE_SET_METHOD(process, "abort", Abort);
2535 NODE_SET_METHOD(process, "chdir", Chdir);
2536 NODE_SET_METHOD(process, "cwd", Cwd);
2538 NODE_SET_METHOD(process, "umask", Umask);
2540 #if defined(__POSIX__) && !defined(__ANDROID__)
2541 NODE_SET_METHOD(process, "getuid", GetUid);
2542 NODE_SET_METHOD(process, "setuid", SetUid);
2544 NODE_SET_METHOD(process, "setgid", SetGid);
2545 NODE_SET_METHOD(process, "getgid", GetGid);
2547 NODE_SET_METHOD(process, "getgroups", GetGroups);
2548 NODE_SET_METHOD(process, "setgroups", SetGroups);
2549 NODE_SET_METHOD(process, "initgroups", InitGroups);
2550 #endif // __POSIX__ && !defined(__ANDROID__)
2552 NODE_SET_METHOD(process, "_kill", Kill);
2554 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2555 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2556 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2558 NODE_SET_METHOD(process, "hrtime", Hrtime);
2560 NODE_SET_METHOD(process, "dlopen", DLOpen);
2562 NODE_SET_METHOD(process, "uptime", Uptime);
2563 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2565 NODE_SET_METHOD(process, "binding", Binding);
2567 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2569 // values use to cross communicate with processNextTick
2570 Local<Object> tick_info_obj = Object::New();
2571 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
2572 env->tick_info()->fields(),
2573 kExternalUnsignedIntArray,
2574 env->tick_info()->fields_count());
2575 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfo"), tick_info_obj);
2577 // pre-set _events object for faster emit checks
2578 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2582 #undef READONLY_PROPERTY
2585 static void AtExit() {
2586 uv_tty_reset_mode();
2590 static void SignalExit(int signal) {
2591 uv_tty_reset_mode();
2592 _exit(128 + signal);
2596 // Most of the time, it's best to use `console.error` to write
2597 // to the process.stderr stream. However, in some cases, such as
2598 // when debugging the stream.Writable class or the process.nextTick
2599 // function, it is useful to bypass JavaScript entirely.
2600 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2601 HandleScope scope(node_isolate);
2603 assert(args.Length() == 1 && args[0]->IsString() &&
2604 "must be called with a single string");
2606 String::Utf8Value message(args[0]);
2607 fprintf(stderr, "%s\n", *message);
2612 void Load(Environment* env) {
2613 HandleScope handle_scope(node_isolate);
2615 // Compile, execute the src/node.js file. (Which was included as static C
2616 // string in node_natives.h. 'natve_node' is the string containing that
2619 // The node.js file returns a function 'f'
2624 // Disable verbose mode to stop FatalException() handler from trying
2625 // to handle the exception. Errors this early in the start-up phase
2626 // are not safe to ignore.
2627 try_catch.SetVerbose(false);
2629 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2630 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2631 if (try_catch.HasCaught()) {
2632 ReportException(try_catch);
2635 assert(f_value->IsFunction());
2636 Local<Function> f = Local<Function>::Cast(f_value);
2638 // Now we call 'f' with the 'process' variable that we've built up with
2639 // all our bindings. Inside node.js we'll take care of assigning things to
2642 // We start the process this way in order to be more modular. Developers
2643 // who do not like how 'src/node.js' setups the module system but do like
2644 // Node's I/O bindings may want to replace 'f' with their own function.
2646 // Add a reference to the global object
2647 Local<Object> global = env->context()->Global();
2649 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2653 #if defined HAVE_PERFCTR
2654 InitPerfCounters(global);
2657 // Enable handling of uncaught exceptions
2658 // (FatalException(), break on uncaught exception in debugger)
2660 // This is not strictly necessary since it's almost impossible
2661 // to attach the debugger fast enought to break on exception
2662 // thrown during process startup.
2663 try_catch.SetVerbose(true);
2665 NODE_SET_METHOD(env->process_object(), "_rawDebug", RawDebug);
2667 Local<Value> arg = env->process_object();
2668 f->Call(global, 1, &arg);
2671 static void PrintHelp();
2673 static void ParseDebugOpt(const char* arg) {
2676 if (strstr(arg, "--debug-port=") == arg) {
2677 p = 1 + strchr(arg, '=');
2678 debug_port = atoi(p);
2680 use_debug_agent = true;
2681 if (!strcmp(arg, "--debug-brk")) {
2682 debug_wait_connect = true;
2684 } else if (!strcmp(arg, "--debug")) {
2686 } else if (strstr(arg, "--debug-brk=") == arg) {
2687 debug_wait_connect = true;
2688 p = 1 + strchr(arg, '=');
2689 debug_port = atoi(p);
2690 } else if (strstr(arg, "--debug=") == arg) {
2691 p = 1 + strchr(arg, '=');
2692 debug_port = atoi(p);
2695 if (p && debug_port > 1024 && debug_port < 65536)
2698 fprintf(stderr, "Bad debug option.\n");
2700 fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2706 static void PrintHelp() {
2707 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2708 " node debug script.js [arguments] \n"
2711 " -v, --version print node's version\n"
2712 " -e, --eval script evaluate script\n"
2713 " -p, --print evaluate script and print result\n"
2714 " -i, --interactive always enter the REPL even if stdin\n"
2715 " does not appear to be a terminal\n"
2716 " --no-deprecation silence deprecation warnings\n"
2717 " --trace-deprecation show stack traces on deprecations\n"
2718 " --v8-options print v8 command line options\n"
2719 " --max-stack-size=val set max v8 stack size (bytes)\n"
2721 "Environment variables:\n"
2723 "NODE_PATH ';'-separated list of directories\n"
2725 "NODE_PATH ':'-separated list of directories\n"
2727 " prefixed to the module search path.\n"
2728 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2729 " global contexts.\n"
2730 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2732 "Documentation can be found at http://nodejs.org/\n");
2736 // Parse command line arguments.
2738 // argv is modified in place. exec_argv and v8_argv are out arguments that
2739 // ParseArgs() allocates memory for and stores a pointer to the output
2740 // vector in. The caller should free them with delete[].
2744 // * argv contains the arguments with node and V8 options filtered out.
2745 // * exec_argv contains both node and V8 options and nothing else.
2746 // * v8_argv contains argv[0] plus any V8 options
2747 static void ParseArgs(int* argc,
2750 const char*** exec_argv,
2752 const char*** v8_argv) {
2753 const unsigned int nargs = static_cast<unsigned int>(*argc);
2754 const char** new_exec_argv = new const char*[nargs];
2755 const char** new_v8_argv = new const char*[nargs];
2756 const char** new_argv = new const char*[nargs];
2758 for (unsigned int i = 0; i < nargs; ++i) {
2759 new_exec_argv[i] = NULL;
2760 new_v8_argv[i] = NULL;
2764 // exec_argv starts with the first option, the other two start with argv[0].
2765 unsigned int new_exec_argc = 0;
2766 unsigned int new_v8_argc = 1;
2767 unsigned int new_argc = 1;
2768 new_v8_argv[0] = argv[0];
2769 new_argv[0] = argv[0];
2771 unsigned int index = 1;
2772 while (index < nargs && argv[index][0] == '-') {
2773 const char* const arg = argv[index];
2774 unsigned int args_consumed = 1;
2776 if (strstr(arg, "--debug") == arg) {
2778 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2779 printf("%s\n", NODE_VERSION);
2781 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2784 } else if (strcmp(arg, "--eval") == 0 ||
2785 strcmp(arg, "-e") == 0 ||
2786 strcmp(arg, "--print") == 0 ||
2787 strcmp(arg, "-pe") == 0 ||
2788 strcmp(arg, "-p") == 0) {
2789 bool is_eval = strchr(arg, 'e') != NULL;
2790 bool is_print = strchr(arg, 'p') != NULL;
2791 print_eval = print_eval || is_print;
2792 // --eval, -e and -pe always require an argument.
2793 if (is_eval == true) {
2795 eval_string = argv[index + 1];
2796 if (eval_string == NULL) {
2797 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
2800 } else if (argv[index + 1] != NULL && argv[index + 1][0] != '-') {
2802 eval_string = argv[index + 1];
2803 if (strncmp(eval_string, "\\-", 2) == 0) {
2804 // Starts with "\\-": escaped expression, drop the backslash.
2808 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2810 } else if (strcmp(arg, "--no-deprecation") == 0) {
2811 no_deprecation = true;
2812 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2813 trace_deprecation = true;
2814 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2815 throw_deprecation = true;
2816 } else if (strcmp(arg, "--v8-options") == 0) {
2817 new_v8_argv[new_v8_argc] = "--help";
2820 // V8 option. Pass through as-is.
2821 new_v8_argv[new_v8_argc] = arg;
2825 memcpy(new_exec_argv + new_exec_argc,
2827 args_consumed * sizeof(*argv));
2829 new_exec_argc += args_consumed;
2830 index += args_consumed;
2833 // Copy remaining arguments.
2834 const unsigned int args_left = nargs - index;
2835 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
2836 new_argc += args_left;
2838 *exec_argc = new_exec_argc;
2839 *exec_argv = new_exec_argv;
2840 *v8_argc = new_v8_argc;
2841 *v8_argv = new_v8_argv;
2843 // Copy new_argv over argv and update argc.
2844 memcpy(argv, new_argv, new_argc * sizeof(*argv));
2846 *argc = static_cast<int>(new_argc);
2850 // Called from V8 Debug Agent TCP thread.
2851 static void DispatchMessagesDebugAgentCallback() {
2852 uv_async_send(&dispatch_debug_messages_async);
2856 // Called from the main thread.
2857 static void EnableDebug(bool wait_connect) {
2858 assert(debugger_running == false);
2859 Isolate* isolate = node_isolate; // TODO(bnoordhuis) Multi-isolate support.
2860 Isolate::Scope isolate_scope(isolate);
2861 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2863 debugger_running = v8::Debug::EnableAgent("node " NODE_VERSION,
2866 if (debugger_running == false) {
2867 fprintf(stderr, "Starting debugger on port %d failed\n", debug_port);
2871 fprintf(stderr, "Debugger listening on port %d\n", debug_port);
2874 Environment* env = Environment::GetCurrentChecked(isolate);
2876 return; // Still starting up.
2878 Context::Scope context_scope(env->context());
2879 HandleScope handle_scope(env->isolate());
2880 Local<Object> message = Object::New();
2881 message->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "cmd"),
2882 FIXED_ONE_BYTE_STRING(env->isolate(), "NODE_DEBUG_ENABLED"));
2883 Local<Value> argv[] = {
2884 FIXED_ONE_BYTE_STRING(env->isolate(), "internalMessage"),
2887 MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(argv), argv);
2891 // Called from the main thread.
2892 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2893 if (debugger_running == false) {
2894 fprintf(stderr, "Starting debugger agent.\n");
2897 Isolate::Scope isolate_scope(node_isolate);
2898 v8::Debug::ProcessDebugMessages();
2903 static volatile sig_atomic_t caught_early_debug_signal;
2906 static void EarlyDebugSignalHandler(int signo) {
2907 caught_early_debug_signal = 1;
2911 static void InstallEarlyDebugSignalHandler() {
2912 struct sigaction sa;
2913 memset(&sa, 0, sizeof(sa));
2914 sa.sa_handler = EarlyDebugSignalHandler;
2915 sigaction(SIGUSR1, &sa, NULL);
2919 static void EnableDebugSignalHandler(int signo) {
2920 // Call only async signal-safe functions here!
2921 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
2922 uv_async_send(&dispatch_debug_messages_async);
2926 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2927 struct sigaction sa;
2928 memset(&sa, 0, sizeof(sa));
2929 sa.sa_handler = handler;
2930 sigfillset(&sa.sa_mask);
2931 sigaction(signal, &sa, NULL);
2935 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2936 HandleScope scope(node_isolate);
2938 if (args.Length() != 1) {
2939 return ThrowError("Invalid number of arguments.");
2945 pid = args[0]->IntegerValue();
2946 r = kill(pid, SIGUSR1);
2948 return ThrowErrnoException(errno, "kill");
2953 static int RegisterDebugSignalHandler() {
2954 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
2955 RegisterSignalHandler(SIGUSR1, EnableDebugSignalHandler);
2956 // If we caught a SIGUSR1 during the bootstrap process, re-raise it
2957 // now that the debugger infrastructure is in place.
2958 if (caught_early_debug_signal)
2966 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2967 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
2968 uv_async_send(&dispatch_debug_messages_async);
2973 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2975 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2979 static int RegisterDebugSignalHandler() {
2980 wchar_t mapping_name[32];
2981 HANDLE mapping_handle;
2983 LPTHREAD_START_ROUTINE* handler;
2985 pid = GetCurrentProcessId();
2987 if (GetDebugSignalHandlerMappingName(pid,
2989 ARRAY_SIZE(mapping_name)) < 0) {
2993 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2999 if (mapping_handle == NULL) {
3003 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3004 MapViewOfFile(mapping_handle,
3005 FILE_MAP_ALL_ACCESS,
3009 if (handler == NULL) {
3010 CloseHandle(mapping_handle);
3014 *handler = EnableDebugThreadProc;
3016 UnmapViewOfFile(static_cast<void*>(handler));
3022 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3023 HandleScope scope(node_isolate);
3025 HANDLE process = NULL;
3026 HANDLE thread = NULL;
3027 HANDLE mapping = NULL;
3028 wchar_t mapping_name[32];
3029 LPTHREAD_START_ROUTINE* handler = NULL;
3031 if (args.Length() != 1) {
3032 ThrowError("Invalid number of arguments.");
3036 pid = (DWORD) args[0]->IntegerValue();
3038 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
3039 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
3043 if (process == NULL) {
3044 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
3048 if (GetDebugSignalHandlerMappingName(pid,
3050 ARRAY_SIZE(mapping_name)) < 0) {
3051 ThrowErrnoException(errno, "sprintf");
3055 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
3056 if (mapping == NULL) {
3057 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
3061 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3062 MapViewOfFile(mapping,
3067 if (handler == NULL || *handler == NULL) {
3068 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
3072 thread = CreateRemoteThread(process,
3079 if (thread == NULL) {
3080 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
3084 // Wait for the thread to terminate
3085 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3086 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
3091 if (process != NULL)
3092 CloseHandle(process);
3094 CloseHandle(thread);
3095 if (handler != NULL)
3096 UnmapViewOfFile(handler);
3097 if (mapping != NULL)
3098 CloseHandle(mapping);
3103 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3104 v8::Debug::DebugBreak(node_isolate);
3108 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3109 if (debugger_running) {
3110 v8::Debug::DisableAgent();
3111 debugger_running = false;
3116 void Init(int* argc,
3119 const char*** exec_argv) {
3120 // Initialize prog_start_time to get relative uptime.
3121 uv_uptime(&prog_start_time);
3123 // Make inherited handles noninheritable.
3124 uv_disable_stdio_inheritance();
3126 // init async debug messages dispatching
3127 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3128 uv_async_init(uv_default_loop(),
3129 &dispatch_debug_messages_async,
3130 DispatchDebugMessagesAsyncCallback);
3131 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3133 // Parse a few arguments which are specific to Node.
3135 const char** v8_argv;
3136 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3138 // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
3139 // manually? That would give us a little more control over its runtime
3140 // behavior but it could also interfere with the user's intentions in ways
3141 // we fail to anticipate. Dillema.
3142 for (int i = 1; i < v8_argc; ++i) {
3143 if (strncmp(v8_argv[i], "--prof", sizeof("--prof") - 1) == 0) {
3144 v8_is_profiling = true;
3149 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3150 // the argv array or the elements it points to.
3151 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3153 // Anything that's still in v8_argv is not a V8 or a node option.
3154 for (int i = 1; i < v8_argc; i++) {
3155 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3164 if (debug_wait_connect) {
3165 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3166 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3169 const char typed_arrays_flag[] = "--harmony_typed_arrays";
3170 V8::SetFlagsFromString(typed_arrays_flag, sizeof(typed_arrays_flag) - 1);
3171 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3173 // Fetch a reference to the main isolate, so we have a reference to it
3174 // even when we need it to access it from another (debugger) thread.
3175 node_isolate = Isolate::GetCurrent();
3178 // Raise the open file descriptor limit.
3179 { // NOLINT (whitespace/braces)
3181 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3182 // Do a binary search for the limit.
3183 rlim_t min = lim.rlim_cur;
3184 rlim_t max = 1 << 20;
3185 // But if there's a defined upper bound, don't search, just set it.
3186 if (lim.rlim_max != RLIM_INFINITY) {
3191 lim.rlim_cur = min + (max - min) / 2;
3192 if (setrlimit(RLIMIT_NOFILE, &lim)) {
3197 } while (min + 1 < max);
3201 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3202 RegisterSignalHandler(SIGINT, SignalExit);
3203 RegisterSignalHandler(SIGTERM, SignalExit);
3206 V8::SetFatalErrorHandler(node::OnFatalError);
3207 V8::AddMessageListener(OnMessage);
3209 // If the --debug flag was specified then initialize the debug thread.
3210 if (use_debug_agent) {
3211 EnableDebug(debug_wait_connect);
3213 RegisterDebugSignalHandler();
3218 struct AtExitCallback {
3219 AtExitCallback* next_;
3220 void (*cb_)(void* arg);
3224 static AtExitCallback* at_exit_functions_;
3227 // TODO(bnoordhuis) Turn into per-context event.
3228 void RunAtExit(Environment* env) {
3229 AtExitCallback* p = at_exit_functions_;
3230 at_exit_functions_ = NULL;
3233 AtExitCallback* q = p->next_;
3241 void AtExit(void (*cb)(void* arg), void* arg) {
3242 AtExitCallback* p = new AtExitCallback;
3245 p->next_ = at_exit_functions_;
3246 at_exit_functions_ = p;
3250 void EmitExit(Environment* env) {
3251 // process.emit('exit')
3252 Context::Scope context_scope(env->context());
3253 HandleScope handle_scope(env->isolate());
3254 Local<Object> process_object = env->process_object();
3255 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3256 True(node_isolate));
3258 Handle<String> exitCode = FIXED_ONE_BYTE_STRING(node_isolate, "exitCode");
3259 int code = process_object->Get(exitCode)->IntegerValue();
3261 Local<Value> args[] = {
3262 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3263 Integer::New(code, node_isolate)
3266 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3271 Environment* CreateEnvironment(Isolate* isolate,
3273 const char* const* argv,
3275 const char* const* exec_argv) {
3276 HandleScope handle_scope(isolate);
3278 Local<Context> context = Context::New(isolate);
3279 Context::Scope context_scope(context);
3280 Environment* env = Environment::New(context);
3282 uv_check_init(env->event_loop(), env->immediate_check_handle());
3284 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3285 uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3287 // Inform V8's CPU profiler when we're idle. The profiler is sampling-based
3288 // but not all samples are created equal; mark the wall clock time spent in
3289 // epoll_wait() and friends so profiling tools can filter it out. The samples
3290 // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
3291 // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
3292 // probably fortify in the API contract, namely that the last started prepare
3293 // or check watcher runs first. It's not 100% foolproof; if an add-on starts
3294 // a prepare or check watcher after us, any samples attributed to its callback
3295 // will be recorded with state=IDLE.
3296 uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
3297 uv_check_init(env->event_loop(), env->idle_check_handle());
3298 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
3299 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
3301 if (v8_is_profiling) {
3302 StartProfilerIdleNotifier(env);
3305 Local<FunctionTemplate> process_template = FunctionTemplate::New();
3306 process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3308 Local<Object> process_object = process_template->GetFunction()->NewInstance();
3309 env->set_process_object(process_object);
3311 SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3318 int Start(int argc, char** argv) {
3319 #if !defined(_WIN32)
3320 // Try hard not to lose SIGUSR1 signals during the bootstrap process.
3321 InstallEarlyDebugSignalHandler();
3326 // Hack around with the argv pointer. Used for process.title = "blah".
3327 argv = uv_setup_args(argc, argv);
3329 // This needs to run *before* V8::Initialize(). The const_cast is not
3330 // optional, in case you're wondering.
3332 const char** exec_argv;
3333 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3336 // V8 on Windows doesn't have a good source of entropy. Seed it from
3338 V8::SetEntropySource(crypto::EntropySource);
3343 Locker locker(node_isolate);
3345 CreateEnvironment(node_isolate, argc, argv, exec_argc, exec_argv);
3346 Context::Scope context_scope(env->context());
3347 HandleScope handle_scope(env->isolate());
3348 uv_run(env->event_loop(), UV_RUN_DEFAULT);
3356 // Clean up. Not strictly necessary.