1 // Copyright Joyent, Inc. and other Node contributors.
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
23 #include "node_buffer.h"
24 #include "node_constants.h"
25 #include "node_file.h"
26 #include "node_http_parser.h"
27 #include "node_javascript.h"
28 #include "node_version.h"
30 #if defined HAVE_PERFCTR
31 #include "node_counters.h"
35 #include "node_crypto.h"
38 #if defined HAVE_DTRACE || defined HAVE_ETW
39 #include "node_dtrace.h"
43 #include "async-wrap.h"
44 #include "async-wrap-inl.h"
47 #include "handle_wrap.h"
49 #include "string_bytes.h"
52 #include "v8-profiler.h"
57 #include <limits.h> // PATH_MAX
63 #include <sys/types.h>
69 #define strcasecmp _stricmp
70 #define getpid _getpid
74 #include <sys/resource.h> // getrlimit, setrlimit
75 #include <unistd.h> // setuid, getuid
78 #if defined(__POSIX__) && !defined(__ANDROID__)
79 #include <pwd.h> // getpwnam()
80 #include <grp.h> // getgrnam()
84 #include <crt_externs.h>
85 #define environ (*_NSGetEnviron())
86 #elif !defined(_MSC_VER)
87 extern char **environ;
93 using v8::ArrayBuffer;
98 using v8::FunctionCallbackInfo;
99 using v8::FunctionTemplate;
101 using v8::HandleScope;
102 using v8::HeapStatistics;
110 using v8::ObjectTemplate;
111 using v8::PropertyCallbackInfo;
113 using v8::ThrowException;
118 using v8::kExternalUnsignedIntArray;
120 // FIXME(bnoordhuis) Make these per-context?
121 QUEUE handle_wrap_queue = { &handle_wrap_queue, &handle_wrap_queue };
122 QUEUE req_wrap_queue = { &req_wrap_queue, &req_wrap_queue };
124 static bool print_eval = false;
125 static bool force_repl = false;
126 static bool trace_deprecation = false;
127 static bool throw_deprecation = false;
128 static const char* eval_string = NULL;
129 static bool use_debug_agent = false;
130 static bool debug_wait_connect = false;
131 static int debug_port = 5858;
132 static bool v8_is_profiling = false;
134 // used by C++ modules as well
135 bool no_deprecation = false;
137 // process-relative uptime base, initialized at start-up
138 static double prog_start_time;
139 static bool debugger_running;
140 static uv_async_t dispatch_debug_messages_async;
142 // Declared in node_internals.h
143 Isolate* node_isolate = NULL;
146 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
148 // Impose an upper limit to avoid out of memory errors that bring down
150 static const size_t kMaxLength = 0x3fffffff;
151 static ArrayBufferAllocator the_singleton;
152 virtual ~ArrayBufferAllocator() {}
153 virtual void* Allocate(size_t length);
154 virtual void* AllocateUninitialized(size_t length);
155 virtual void Free(void* data, size_t length);
157 ArrayBufferAllocator() {}
158 ArrayBufferAllocator(const ArrayBufferAllocator&);
159 void operator=(const ArrayBufferAllocator&);
162 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
165 void* ArrayBufferAllocator::Allocate(size_t length) {
166 if (length > kMaxLength)
168 char* data = new char[length];
169 memset(data, 0, 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 HandleScope scope(node_isolate);
188 Environment* env = Environment::from_immediate_check_handle(handle);
189 Context::Scope context_scope(env->context());
190 MakeCallback(env, env->process_object(), env->immediate_callback_string());
194 static void IdleImmediateDummy(uv_idle_t*, int) {
195 // Do nothing. Only for maintaining event loop.
196 // TODO(bnoordhuis) Maybe make libuv accept NULL idle callbacks.
200 static inline const char *errno_string(int errorno) {
201 #define ERRNO_CASE(e) case e: return #e;
208 ERRNO_CASE(EADDRINUSE);
212 ERRNO_CASE(EADDRNOTAVAIL);
216 ERRNO_CASE(EAFNOSUPPORT);
224 # if EAGAIN != EWOULDBLOCK
225 ERRNO_CASE(EWOULDBLOCK);
230 ERRNO_CASE(EALREADY);
246 ERRNO_CASE(ECANCELED);
254 ERRNO_CASE(ECONNABORTED);
258 ERRNO_CASE(ECONNREFUSED);
262 ERRNO_CASE(ECONNRESET);
270 ERRNO_CASE(EDESTADDRREQ);
294 ERRNO_CASE(EHOSTUNREACH);
306 ERRNO_CASE(EINPROGRESS);
342 ERRNO_CASE(EMSGSIZE);
346 ERRNO_CASE(EMULTIHOP);
350 ERRNO_CASE(ENAMETOOLONG);
354 ERRNO_CASE(ENETDOWN);
358 ERRNO_CASE(ENETRESET);
362 ERRNO_CASE(ENETUNREACH);
394 # if ENOLINK != ENOLCK
408 ERRNO_CASE(ENOPROTOOPT);
428 ERRNO_CASE(ENOTCONN);
436 ERRNO_CASE(ENOTEMPTY);
440 ERRNO_CASE(ENOTSOCK);
447 ERRNO_CASE(EOPNOTSUPP);
461 ERRNO_CASE(EOVERFLOW);
476 #ifdef EPROTONOSUPPORT
477 ERRNO_CASE(EPROTONOSUPPORT);
481 ERRNO_CASE(EPROTOTYPE);
509 ERRNO_CASE(ETIMEDOUT);
524 const char *signo_string(int signo) {
525 #define SIGNO_CASE(e) case e: return #e;
552 # if SIGABRT != SIGIOT
596 SIGNO_CASE(SIGSTKFLT);
613 SIGNO_CASE(SIGBREAK);
637 SIGNO_CASE(SIGVTALRM);
645 SIGNO_CASE(SIGWINCH);
653 # if SIGPOLL != SIGIO
663 # if SIGPWR != SIGLOST
677 Local<Value> ErrnoException(int errorno,
681 Environment* env = Environment::GetCurrent(node_isolate);
684 Local<String> estring = OneByteString(node_isolate, errno_string(errorno));
685 if (msg == NULL || msg[0] == '\0') {
686 msg = strerror(errorno);
688 Local<String> message = OneByteString(node_isolate, msg);
690 Local<String> cons1 =
691 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
692 Local<String> cons2 = String::Concat(cons1, message);
695 Local<String> cons3 =
696 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
697 Local<String> cons4 =
698 String::Concat(cons3, String::NewFromUtf8(node_isolate, path));
699 Local<String> cons5 =
700 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
701 e = Exception::Error(cons5);
703 e = Exception::Error(cons2);
706 Local<Object> obj = e->ToObject();
707 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
708 obj->Set(env->code_string(), estring);
711 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
714 if (syscall != NULL) {
715 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
722 // hack alert! copy of ErrnoException, tuned for uv errors
723 Local<Value> UVException(int errorno,
727 Environment* env = Environment::GetCurrent(node_isolate);
730 msg = uv_strerror(errorno);
732 Local<String> estring = OneByteString(node_isolate, uv_err_name(errorno));
733 Local<String> message = OneByteString(node_isolate, msg);
734 Local<String> cons1 =
735 String::Concat(estring, FIXED_ONE_BYTE_STRING(node_isolate, ", "));
736 Local<String> cons2 = String::Concat(cons1, message);
740 Local<String> path_str;
744 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
745 path_str = String::Concat(FIXED_ONE_BYTE_STRING(node_isolate, "\\\\"),
746 String::NewFromUtf8(node_isolate, path + 8));
747 } else if (strncmp(path, "\\\\?\\", 4) == 0) {
748 path_str = String::NewFromUtf8(node_isolate, path + 4);
750 path_str = String::NewFromUtf8(node_isolate, path);
753 path_str = String::NewFromUtf8(node_isolate, path);
756 Local<String> cons3 =
757 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
758 Local<String> cons4 =
759 String::Concat(cons3, path_str);
760 Local<String> cons5 =
761 String::Concat(cons4, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
762 e = Exception::Error(cons5);
764 e = Exception::Error(cons2);
767 Local<Object> obj = e->ToObject();
768 // TODO(piscisaureus) errno should probably go
769 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
770 obj->Set(env->code_string(), estring);
773 obj->Set(env->path_string(), path_str);
776 if (syscall != NULL) {
777 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
785 // Does about the same as strerror(),
786 // but supports all windows error messages
787 static const char *winapi_strerror(const int errorno) {
790 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
791 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
792 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
795 // Remove trailing newlines
796 for (int i = strlen(errmsg) - 1;
797 i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
803 // FormatMessage failed
804 return "Unknown error";
809 Local<Value> WinapiErrnoException(int errorno,
813 Environment* env = Environment::GetCurrent(node_isolate);
816 if (!msg || !msg[0]) {
817 msg = winapi_strerror(errorno);
819 Local<String> message = OneByteString(node_isolate, msg);
822 Local<String> cons1 =
823 String::Concat(message, FIXED_ONE_BYTE_STRING(node_isolate, " '"));
824 Local<String> cons2 =
825 String::Concat(cons1, String::NewFromUtf8(node_isolate, path));
826 Local<String> cons3 =
827 String::Concat(cons2, FIXED_ONE_BYTE_STRING(node_isolate, "'"));
828 e = Exception::Error(cons3);
830 e = Exception::Error(message);
833 Local<Object> obj = e->ToObject();
834 obj->Set(env->errno_string(), Integer::New(errorno, node_isolate));
837 obj->Set(env->path_string(), String::NewFromUtf8(node_isolate, path));
840 if (syscall != NULL) {
841 obj->Set(env->syscall_string(), OneByteString(node_isolate, syscall));
849 void SetupAsyncListener(const FunctionCallbackInfo<Value>& args) {
850 HandleScope handle_scope(args.GetIsolate());
851 Environment* env = Environment::GetCurrent(args.GetIsolate());
853 assert(args[0]->IsObject());
854 assert(args[1]->IsFunction());
855 assert(args[2]->IsFunction());
856 assert(args[3]->IsFunction());
857 assert(args[4]->IsFunction());
858 assert(args[5]->IsFunction());
860 env->set_async_listener_run_function(args[1].As<Function>());
861 env->set_async_listener_load_function(args[2].As<Function>());
862 env->set_async_listener_unload_function(args[3].As<Function>());
863 env->set_async_listener_push_function(args[4].As<Function>());
864 env->set_async_listener_strip_function(args[5].As<Function>());
866 Local<Object> async_listener_flag_obj = args[0].As<Object>();
867 Environment::AsyncListener* async_listener = env->async_listener();
868 async_listener_flag_obj->SetIndexedPropertiesToExternalArrayData(
869 async_listener->fields(),
870 kExternalUnsignedIntArray,
871 async_listener->fields_count());
873 // Do a little housekeeping.
874 env->process_object()->Delete(
875 FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupAsyncListener"));
879 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
880 Environment* env = Environment::GetCurrent(args.GetIsolate());
882 if (env->using_domains())
884 env->set_using_domains(true);
886 HandleScope scope(node_isolate);
887 Local<Object> process_object = env->process_object();
889 Local<String> tick_callback_function_key =
890 FIXED_ONE_BYTE_STRING(node_isolate, "_tickDomainCallback");
891 Local<Function> tick_callback_function =
892 process_object->Get(tick_callback_function_key).As<Function>();
894 if (!tick_callback_function->IsFunction()) {
895 fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
899 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"),
900 tick_callback_function);
901 env->set_tick_callback_function(tick_callback_function);
903 assert(args[0]->IsArray());
904 assert(args[1]->IsObject());
906 env->set_domain_array(args[0].As<Array>());
908 Local<Object> domain_flag_obj = args[1].As<Object>();
909 Environment::DomainFlag* domain_flag = env->domain_flag();
910 domain_flag_obj->SetIndexedPropertiesToExternalArrayData(
911 domain_flag->fields(),
912 kExternalUnsignedIntArray,
913 domain_flag->fields_count());
915 // Do a little housekeeping.
916 env->process_object()->Delete(
917 FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupDomainUse"));
921 void SetupNextTick(const FunctionCallbackInfo<Value>& args) {
922 HandleScope handle_scope(args.GetIsolate());
923 Environment* env = Environment::GetCurrent(args.GetIsolate());
925 assert(args[0]->IsObject());
926 assert(args[1]->IsFunction());
928 // Values use to cross communicate with processNextTick.
929 Local<Object> tick_info_obj = args[0].As<Object>();
930 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
931 env->tick_info()->fields(),
932 kExternalUnsignedIntArray,
933 env->tick_info()->fields_count());
935 env->set_tick_callback_function(args[1].As<Function>());
937 // Do a little housekeeping.
938 env->process_object()->Delete(
939 FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupNextTick"));
943 Handle<Value> MakeDomainCallback(Environment* env,
944 Handle<Object> object,
945 const Handle<Function> callback,
947 Handle<Value> argv[]) {
948 // If you hit this assertion, you forgot to enter the v8::Context first.
949 assert(env->context() == env->isolate()->GetCurrentContext());
951 Local<Object> process = env->process_object();
952 Local<Value> domain_v = object->Get(env->domain_string());
953 Local<Object> domain;
956 try_catch.SetVerbose(true);
958 // TODO(trevnorris): This is sucky for performance. Fix it.
959 bool has_async_queue = object->Has(env->async_queue_string());
960 if (has_async_queue) {
961 Local<Value> argv[] = { object };
962 env->async_listener_load_function()->Call(process, ARRAY_SIZE(argv), argv);
964 if (try_catch.HasCaught())
965 return Undefined(node_isolate);
968 bool has_domain = domain_v->IsObject();
970 domain = domain_v.As<Object>();
972 if (domain->Get(env->disposed_string())->IsTrue()) {
973 // domain has been disposed of.
974 return Undefined(node_isolate);
977 Local<Function> enter =
978 domain->Get(env->enter_string()).As<Function>();
979 assert(enter->IsFunction());
980 enter->Call(domain, 0, NULL);
982 if (try_catch.HasCaught()) {
983 return Undefined(node_isolate);
987 Local<Value> ret = callback->Call(object, argc, argv);
989 if (try_catch.HasCaught()) {
990 return Undefined(node_isolate);
994 Local<Function> exit =
995 domain->Get(env->exit_string()).As<Function>();
996 assert(exit->IsFunction());
997 exit->Call(domain, 0, NULL);
999 if (try_catch.HasCaught()) {
1000 return Undefined(node_isolate);
1004 if (has_async_queue) {
1005 Local<Value> val = object.As<Value>();
1006 env->async_listener_unload_function()->Call(process, 1, &val);
1008 if (try_catch.HasCaught())
1009 return Undefined(node_isolate);
1012 Environment::TickInfo* tick_info = env->tick_info();
1014 if (tick_info->last_threw() == 1) {
1015 tick_info->set_last_threw(0);
1019 if (tick_info->in_tick()) {
1023 if (tick_info->length() == 0) {
1024 tick_info->set_index(0);
1028 tick_info->set_in_tick(true);
1030 env->tick_callback_function()->Call(process, 0, NULL);
1032 tick_info->set_in_tick(false);
1034 if (try_catch.HasCaught()) {
1035 tick_info->set_last_threw(true);
1036 return Undefined(node_isolate);
1043 Handle<Value> MakeCallback(Environment* env,
1044 Handle<Object> object,
1045 const Handle<Function> callback,
1047 Handle<Value> argv[]) {
1048 if (env->using_domains())
1049 return MakeDomainCallback(env, object, callback, argc, argv);
1051 // If you hit this assertion, you forgot to enter the v8::Context first.
1052 assert(env->context() == env->isolate()->GetCurrentContext());
1054 Local<Object> process = env->process_object();
1057 try_catch.SetVerbose(true);
1059 // TODO(trevnorris): This is sucky for performance. Fix it.
1060 bool has_async_queue = object->Has(env->async_queue_string());
1061 if (has_async_queue) {
1062 Local<Value> argv[] = { object };
1063 env->async_listener_load_function()->Call(process, ARRAY_SIZE(argv), argv);
1065 if (try_catch.HasCaught())
1066 return Undefined(node_isolate);
1069 Local<Value> ret = callback->Call(object, argc, argv);
1071 if (try_catch.HasCaught()) {
1072 return Undefined(node_isolate);
1075 if (has_async_queue) {
1076 Local<Value> val = object.As<Value>();
1077 env->async_listener_unload_function()->Call(process, 1, &val);
1079 if (try_catch.HasCaught())
1080 return Undefined(node_isolate);
1083 Environment::TickInfo* tick_info = env->tick_info();
1085 if (tick_info->in_tick()) {
1089 if (tick_info->length() == 0) {
1090 tick_info->set_index(0);
1094 tick_info->set_in_tick(true);
1096 // process nextTicks after call
1097 env->tick_callback_function()->Call(process, 0, NULL);
1099 tick_info->set_in_tick(false);
1101 if (try_catch.HasCaught()) {
1102 tick_info->set_last_threw(true);
1103 return Undefined(node_isolate);
1111 Handle<Value> MakeCallback(Environment* env,
1112 const Handle<Object> object,
1115 Handle<Value> argv[]) {
1116 Local<Function> callback = object->Get(index).As<Function>();
1117 assert(callback->IsFunction());
1119 return MakeCallback(env, object, callback, argc, argv);
1123 Handle<Value> MakeCallback(Environment* env,
1124 const Handle<Object> object,
1125 const Handle<String> symbol,
1127 Handle<Value> argv[]) {
1128 Local<Function> callback = object->Get(symbol).As<Function>();
1129 assert(callback->IsFunction());
1130 return MakeCallback(env, object, callback, argc, argv);
1134 Handle<Value> MakeCallback(Environment* env,
1135 const Handle<Object> object,
1138 Handle<Value> argv[]) {
1139 Local<String> method_string = OneByteString(node_isolate, method);
1140 return MakeCallback(env, object, method_string, argc, argv);
1144 Handle<Value> MakeCallback(const Handle<Object> object,
1147 Handle<Value> argv[]) {
1148 Local<Context> context = object->CreationContext();
1149 Environment* env = Environment::GetCurrent(context);
1150 Context::Scope context_scope(context);
1151 HandleScope handle_scope(env->isolate());
1152 return handle_scope.Close(MakeCallback(env, object, method, argc, argv));
1156 Handle<Value> MakeCallback(const Handle<Object> object,
1157 const Handle<String> symbol,
1159 Handle<Value> argv[]) {
1160 Local<Context> context = object->CreationContext();
1161 Environment* env = Environment::GetCurrent(context);
1162 Context::Scope context_scope(context);
1163 HandleScope handle_scope(env->isolate());
1164 return handle_scope.Close(MakeCallback(env, object, symbol, argc, argv));
1168 Handle<Value> MakeCallback(const Handle<Object> object,
1169 const Handle<Function> callback,
1171 Handle<Value> argv[]) {
1172 Local<Context> context = object->CreationContext();
1173 Environment* env = Environment::GetCurrent(context);
1174 Context::Scope context_scope(context);
1175 HandleScope handle_scope(env->isolate());
1176 return handle_scope.Close(MakeCallback(env, object, callback, argc, argv));
1180 Handle<Value> MakeDomainCallback(const Handle<Object> object,
1181 const Handle<Function> callback,
1183 Handle<Value> argv[]) {
1184 Local<Context> context = object->CreationContext();
1185 Environment* env = Environment::GetCurrent(context);
1186 Context::Scope context_scope(context);
1187 HandleScope handle_scope(env->isolate());
1188 return handle_scope.Close(
1189 MakeDomainCallback(env, object, callback, argc, argv));
1193 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1194 HandleScope scope(node_isolate);
1196 if (!encoding_v->IsString())
1199 String::Utf8Value encoding(encoding_v);
1201 if (strcasecmp(*encoding, "utf8") == 0) {
1203 } else if (strcasecmp(*encoding, "utf-8") == 0) {
1205 } else if (strcasecmp(*encoding, "ascii") == 0) {
1207 } else if (strcasecmp(*encoding, "base64") == 0) {
1209 } else if (strcasecmp(*encoding, "ucs2") == 0) {
1211 } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1213 } else if (strcasecmp(*encoding, "utf16le") == 0) {
1215 } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1217 } else if (strcasecmp(*encoding, "binary") == 0) {
1219 } else if (strcasecmp(*encoding, "buffer") == 0) {
1221 } else if (strcasecmp(*encoding, "hex") == 0) {
1223 } else if (strcasecmp(*encoding, "raw") == 0) {
1224 if (!no_deprecation) {
1225 fprintf(stderr, "'raw' (array of integers) has been removed. "
1229 } else if (strcasecmp(*encoding, "raws") == 0) {
1230 if (!no_deprecation) {
1231 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1232 "Please update your code.\n");
1240 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1241 return StringBytes::Encode(static_cast<const char*>(buf),
1246 // Returns -1 if the handle was not valid for decoding
1247 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1248 HandleScope scope(node_isolate);
1250 if (val->IsArray()) {
1251 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1257 return StringBytes::Size(val, encoding);
1261 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1264 // Returns number of bytes written.
1265 ssize_t DecodeWrite(char *buf,
1267 v8::Handle<v8::Value> val,
1268 enum encoding encoding) {
1269 return StringBytes::Write(buf, buflen, val, encoding, NULL);
1272 void DisplayExceptionLine(Handle<Message> message) {
1273 // Prevent re-entry into this function. For example, if there is
1274 // a throw from a program in vm.runInThisContext(code, filename, true),
1275 // then we want to show the original failure, not the secondary one.
1276 static bool displayed_error = false;
1278 if (displayed_error)
1280 displayed_error = true;
1282 uv_tty_reset_mode();
1284 fprintf(stderr, "\n");
1286 if (!message.IsEmpty()) {
1287 // Print (filename):(line number): (message).
1288 String::Utf8Value filename(message->GetScriptResourceName());
1289 const char* filename_string = *filename;
1290 int linenum = message->GetLineNumber();
1291 fprintf(stderr, "%s:%i\n", filename_string, linenum);
1292 // Print line of source code.
1293 String::Utf8Value sourceline(message->GetSourceLine());
1294 const char* sourceline_string = *sourceline;
1296 // Because of how node modules work, all scripts are wrapped with a
1297 // "function (module, exports, __filename, ...) {"
1298 // to provide script local variables.
1300 // When reporting errors on the first line of a script, this wrapper
1301 // function is leaked to the user. There used to be a hack here to
1302 // truncate off the first 62 characters, but it caused numerous other
1303 // problems when vm.runIn*Context() methods were used for non-module
1306 // If we ever decide to re-instate such a hack, the following steps
1309 // 1. Pass a flag around to say "this code was wrapped"
1310 // 2. Update the stack frame output so that it is also correct.
1312 // It would probably be simpler to add a line rather than add some
1313 // number of characters to the first line, since V8 truncates the
1314 // sourceline to 78 characters, and we end up not providing very much
1315 // useful debugging info to the user if we remove 62 characters.
1317 int start = message->GetStartColumn();
1318 int end = message->GetEndColumn();
1320 fprintf(stderr, "%s\n", sourceline_string);
1321 // Print wavy underline (GetUnderline is deprecated).
1322 for (int i = 0; i < start; i++) {
1323 fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1325 for (int i = start; i < end; i++) {
1328 fputc('\n', stderr);
1333 static void ReportException(Handle<Value> er, Handle<Message> message) {
1334 HandleScope scope(node_isolate);
1336 DisplayExceptionLine(message);
1338 Local<Value> trace_value;
1340 if (er->IsUndefined() || er->IsNull()) {
1341 trace_value = Undefined(node_isolate);
1344 er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack"));
1347 String::Utf8Value trace(trace_value);
1349 // range errors have a trace member set to undefined
1350 if (trace.length() > 0 && !trace_value->IsUndefined()) {
1351 fprintf(stderr, "%s\n", *trace);
1353 // this really only happens for RangeErrors, since they're the only
1354 // kind that won't have all this info in the trace, or when non-Error
1355 // objects are thrown manually.
1356 Local<Value> message;
1359 if (er->IsObject()) {
1360 Local<Object> err_obj = er.As<Object>();
1361 message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1362 name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1365 if (message.IsEmpty() ||
1366 message->IsUndefined() ||
1368 name->IsUndefined()) {
1369 // Not an error object. Just print as-is.
1370 String::Utf8Value message(er);
1371 fprintf(stderr, "%s\n", *message);
1373 String::Utf8Value name_string(name);
1374 String::Utf8Value message_string(message);
1375 fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1383 static void ReportException(const TryCatch& try_catch) {
1384 ReportException(try_catch.Exception(), try_catch.Message());
1388 // Executes a str within the current v8 context.
1389 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1390 HandleScope scope(node_isolate);
1393 // try_catch must be nonverbose to disable FatalException() handler,
1394 // we will handle exceptions ourself.
1395 try_catch.SetVerbose(false);
1397 Local<v8::Script> script = v8::Script::Compile(source, filename);
1398 if (script.IsEmpty()) {
1399 ReportException(try_catch);
1403 Local<Value> result = script->Run();
1404 if (result.IsEmpty()) {
1405 ReportException(try_catch);
1409 return scope.Close(result);
1413 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1414 HandleScope scope(node_isolate);
1416 Local<Array> ary = Array::New();
1420 QUEUE_FOREACH(q, &req_wrap_queue) {
1421 ReqWrap<uv_req_t>* w = CONTAINER_OF(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1422 if (w->persistent().IsEmpty())
1424 ary->Set(i++, w->object());
1427 args.GetReturnValue().Set(ary);
1431 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1432 // implemented here for consistency with GetActiveRequests().
1433 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1434 HandleScope scope(node_isolate);
1436 Local<Array> ary = Array::New();
1440 Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1442 QUEUE_FOREACH(q, &handle_wrap_queue) {
1443 HandleWrap* w = CONTAINER_OF(q, HandleWrap, handle_wrap_queue_);
1444 if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref))
1446 Local<Object> object = w->object();
1447 Local<Value> owner = object->Get(owner_sym);
1448 if (owner->IsUndefined())
1450 ary->Set(i++, owner);
1453 args.GetReturnValue().Set(ary);
1457 static void Abort(const FunctionCallbackInfo<Value>& args) {
1462 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1463 HandleScope scope(node_isolate);
1465 if (args.Length() != 1 || !args[0]->IsString()) {
1466 return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError?
1469 String::Utf8Value path(args[0]);
1470 int err = uv_chdir(*path);
1472 return ThrowUVException(err, "uv_chdir");
1477 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1478 HandleScope scope(node_isolate);
1480 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1481 char buf[MAX_PATH * 4 + 1];
1483 char buf[PATH_MAX + 1];
1486 int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1488 return ThrowUVException(err, "uv_cwd");
1491 buf[ARRAY_SIZE(buf) - 1] = '\0';
1492 Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1494 args.GetReturnValue().Set(cwd);
1498 static void Umask(const FunctionCallbackInfo<Value>& args) {
1499 HandleScope scope(node_isolate);
1502 if (args.Length() < 1 || args[0]->IsUndefined()) {
1504 umask(static_cast<mode_t>(old));
1505 } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1506 return ThrowTypeError("argument must be an integer or octal string.");
1509 if (args[0]->IsInt32()) {
1510 oct = args[0]->Uint32Value();
1513 String::Utf8Value str(args[0]);
1515 // Parse the octal string.
1516 for (int i = 0; i < str.length(); i++) {
1518 if (c > '7' || c < '0') {
1519 return ThrowTypeError("invalid octal string");
1525 old = umask(static_cast<mode_t>(oct));
1528 args.GetReturnValue().Set(old);
1532 #if defined(__POSIX__) && !defined(__ANDROID__)
1534 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1535 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1538 static uid_t uid_by_name(const char* name) {
1546 if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1550 return uid_not_found;
1554 static char* name_by_uid(uid_t uid) {
1563 if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1564 return strdup(pp->pw_name);
1575 static gid_t gid_by_name(const char* name) {
1583 if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1587 return gid_not_found;
1591 #if 0 // For future use.
1592 static const char* name_by_gid(gid_t gid) {
1601 if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1602 return strdup(pp->gr_name);
1614 static uid_t uid_by_name(Handle<Value> value) {
1615 if (value->IsUint32()) {
1616 return static_cast<uid_t>(value->Uint32Value());
1618 String::Utf8Value name(value);
1619 return uid_by_name(*name);
1624 static gid_t gid_by_name(Handle<Value> value) {
1625 if (value->IsUint32()) {
1626 return static_cast<gid_t>(value->Uint32Value());
1628 String::Utf8Value name(value);
1629 return gid_by_name(*name);
1634 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1635 // uid_t is an uint32_t on all supported platforms.
1636 args.GetReturnValue().Set(static_cast<uint32_t>(getuid()));
1640 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1641 // gid_t is an uint32_t on all supported platforms.
1642 args.GetReturnValue().Set(static_cast<uint32_t>(getgid()));
1646 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1647 HandleScope scope(node_isolate);
1649 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1650 return ThrowTypeError("setgid argument must be a number or a string");
1653 gid_t gid = gid_by_name(args[0]);
1655 if (gid == gid_not_found) {
1656 return ThrowError("setgid group id does not exist");
1660 return ThrowErrnoException(errno, "setgid");
1665 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1666 HandleScope scope(node_isolate);
1668 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1669 return ThrowTypeError("setuid argument must be a number or a string");
1672 uid_t uid = uid_by_name(args[0]);
1674 if (uid == uid_not_found) {
1675 return ThrowError("setuid user id does not exist");
1679 return ThrowErrnoException(errno, "setuid");
1684 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1685 HandleScope scope(node_isolate);
1687 int ngroups = getgroups(0, NULL);
1689 if (ngroups == -1) {
1690 return ThrowErrnoException(errno, "getgroups");
1693 gid_t* groups = new gid_t[ngroups];
1695 ngroups = getgroups(ngroups, groups);
1697 if (ngroups == -1) {
1699 return ThrowErrnoException(errno, "getgroups");
1702 Local<Array> groups_list = Array::New(ngroups);
1703 bool seen_egid = false;
1704 gid_t egid = getegid();
1706 for (int i = 0; i < ngroups; i++) {
1707 groups_list->Set(i, Integer::New(groups[i], node_isolate));
1708 if (groups[i] == egid)
1714 if (seen_egid == false) {
1715 groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1718 args.GetReturnValue().Set(groups_list);
1722 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1723 HandleScope scope(node_isolate);
1725 if (!args[0]->IsArray()) {
1726 return ThrowTypeError("argument 1 must be an array");
1729 Local<Array> groups_list = args[0].As<Array>();
1730 size_t size = groups_list->Length();
1731 gid_t* groups = new gid_t[size];
1733 for (size_t i = 0; i < size; i++) {
1734 gid_t gid = gid_by_name(groups_list->Get(i));
1736 if (gid == gid_not_found) {
1738 return ThrowError("group name not found");
1744 int rc = setgroups(size, groups);
1748 return ThrowErrnoException(errno, "setgroups");
1753 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1754 HandleScope scope(node_isolate);
1756 if (!args[0]->IsUint32() && !args[0]->IsString()) {
1757 return ThrowTypeError("argument 1 must be a number or a string");
1760 if (!args[1]->IsUint32() && !args[1]->IsString()) {
1761 return ThrowTypeError("argument 2 must be a number or a string");
1764 String::Utf8Value arg0(args[0]);
1769 if (args[0]->IsUint32()) {
1770 user = name_by_uid(args[0]->Uint32Value());
1778 return ThrowError("initgroups user not found");
1781 extra_group = gid_by_name(args[1]);
1783 if (extra_group == gid_not_found) {
1786 return ThrowError("initgroups extra group not found");
1789 int rc = initgroups(user, extra_group);
1796 return ThrowErrnoException(errno, "initgroups");
1800 #endif // __POSIX__ && !defined(__ANDROID__)
1803 void Exit(const FunctionCallbackInfo<Value>& args) {
1804 HandleScope scope(node_isolate);
1805 exit(args[0]->IntegerValue());
1809 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1810 HandleScope scope(node_isolate);
1812 if (uv_uptime(&uptime))
1814 args.GetReturnValue().Set(uptime - prog_start_time);
1818 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1819 HandleScope handle_scope(args.GetIsolate());
1820 Environment* env = Environment::GetCurrent(args.GetIsolate());
1823 int err = uv_resident_set_memory(&rss);
1825 return ThrowUVException(err, "uv_resident_set_memory");
1829 HeapStatistics v8_heap_stats;
1830 node_isolate->GetHeapStatistics(&v8_heap_stats);
1832 Local<Integer> heap_total =
1833 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(), node_isolate);
1834 Local<Integer> heap_used =
1835 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(), node_isolate);
1837 Local<Object> info = Object::New();
1838 info->Set(env->rss_string(), Number::New(node_isolate, rss));
1839 info->Set(env->heap_total_string(), heap_total);
1840 info->Set(env->heap_used_string(), heap_used);
1842 args.GetReturnValue().Set(info);
1846 void Kill(const FunctionCallbackInfo<Value>& args) {
1847 HandleScope scope(node_isolate);
1849 if (args.Length() != 2) {
1850 return ThrowError("Bad argument.");
1853 int pid = args[0]->IntegerValue();
1854 int sig = args[1]->Int32Value();
1855 int err = uv_kill(pid, sig);
1856 args.GetReturnValue().Set(err);
1859 // used in Hrtime() below
1860 #define NANOS_PER_SEC 1000000000
1862 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1863 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1864 // so this function instead returns an Array with 2 entries representing seconds
1865 // and nanoseconds, to avoid any integer overflow possibility.
1866 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1867 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1868 HandleScope scope(node_isolate);
1870 uint64_t t = uv_hrtime();
1872 if (args.Length() > 0) {
1873 // return a time diff tuple
1874 if (!args[0]->IsArray()) {
1875 return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1877 Local<Array> inArray = Local<Array>::Cast(args[0]);
1878 uint64_t seconds = inArray->Get(0)->Uint32Value();
1879 uint64_t nanos = inArray->Get(1)->Uint32Value();
1880 t -= (seconds * NANOS_PER_SEC) + nanos;
1883 Local<Array> tuple = Array::New(2);
1884 tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1885 tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1886 args.GetReturnValue().Set(tuple);
1890 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1892 // DLOpen is process.dlopen(module, filename).
1893 // Used to load 'module.node' dynamically shared objects.
1895 // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
1896 // when two contexts try to load the same shared object. Maybe have a shadow
1897 // cache that's a plain C list or hash table that's shared across contexts?
1898 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1899 HandleScope handle_scope(args.GetIsolate());
1900 Environment* env = Environment::GetCurrent(args.GetIsolate());
1901 char symbol[1024], *base, *pos;
1905 if (args.Length() < 2) {
1906 return ThrowError("process.dlopen takes exactly 2 arguments.");
1909 Local<Object> module = args[0]->ToObject(); // Cast
1910 String::Utf8Value filename(args[1]); // Cast
1912 Local<String> exports_string = env->exports_string();
1913 Local<Object> exports = module->Get(exports_string)->ToObject();
1915 if (uv_dlopen(*filename, &lib)) {
1916 Local<String> errmsg = OneByteString(env->isolate(), uv_dlerror(&lib));
1918 // Windows needs to add the filename into the error message
1919 errmsg = String::Concat(errmsg, args[1]->ToString());
1921 ThrowException(Exception::Error(errmsg));
1925 String::Utf8Value path(args[1]);
1928 /* Find the shared library filename within the full path. */
1930 pos = strrchr(base, '/');
1936 pos = strpbrk(base, "\\/:");
1944 /* Strip the .node extension. */
1945 pos = strrchr(base, '.');
1950 /* Add the `_module` suffix to the extension name. */
1951 r = snprintf(symbol, sizeof symbol, "%s_module", base);
1952 if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1953 return ThrowError("Out of memory.");
1956 /* Replace dashes with underscores. When loading foo-bar.node,
1957 * look for foo_bar_module, not foo-bar_module.
1959 for (pos = symbol; *pos != '\0'; ++pos) {
1964 node_module_struct *mod;
1965 if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1967 snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1968 return ThrowError(errmsg);
1971 if (mod->version != NODE_MODULE_VERSION) {
1975 "Module version mismatch. Expected %d, got %d.",
1976 NODE_MODULE_VERSION, mod->version);
1977 return ThrowError(errmsg);
1980 // Execute the C++ module
1981 if (mod->register_context_func != NULL) {
1982 mod->register_context_func(exports, module, env->context());
1983 } else if (mod->register_func != NULL) {
1984 mod->register_func(exports, module);
1986 return ThrowError("Module has no declared entry point.");
1989 // Tell coverity that 'handle' should not be freed when we return.
1990 // coverity[leaked_storage]
1994 static void OnFatalError(const char* location, const char* message) {
1996 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1998 fprintf(stderr, "FATAL ERROR: %s\n", message);
2005 NO_RETURN void FatalError(const char* location, const char* message) {
2006 OnFatalError(location, message);
2007 // to supress compiler warning
2012 void FatalException(Handle<Value> error, Handle<Message> message) {
2013 HandleScope scope(node_isolate);
2015 Environment* env = Environment::GetCurrent(node_isolate);
2016 Local<Object> process_object = env->process_object();
2017 Local<String> fatal_exception_string = env->fatal_exception_string();
2018 Local<Function> fatal_exception_function =
2019 process_object->Get(fatal_exception_string).As<Function>();
2021 if (!fatal_exception_function->IsFunction()) {
2022 // failed before the process._fatalException function was added!
2023 // this is probably pretty bad. Nothing to do but report and exit.
2024 ReportException(error, message);
2028 TryCatch fatal_try_catch;
2030 // Do not call FatalException when _fatalException handler throws
2031 fatal_try_catch.SetVerbose(false);
2033 // this will return true if the JS layer handled it, false otherwise
2034 Local<Value> caught =
2035 fatal_exception_function->Call(process_object, 1, &error);
2037 if (fatal_try_catch.HasCaught()) {
2038 // the fatal exception function threw, so we must exit
2039 ReportException(fatal_try_catch);
2043 if (false == caught->BooleanValue()) {
2044 ReportException(error, message);
2050 void FatalException(const TryCatch& try_catch) {
2051 HandleScope scope(node_isolate);
2052 // TODO(bajtos) do not call FatalException if try_catch is verbose
2053 // (requires V8 API to expose getter for try_catch.is_verbose_)
2054 FatalException(try_catch.Exception(), try_catch.Message());
2058 void OnMessage(Handle<Message> message, Handle<Value> error) {
2059 // The current version of V8 sends messages for errors only
2060 // (thus `error` is always set).
2061 FatalException(error, message);
2065 static void Binding(const FunctionCallbackInfo<Value>& args) {
2066 HandleScope handle_scope(args.GetIsolate());
2067 Environment* env = Environment::GetCurrent(args.GetIsolate());
2069 Local<String> module = args[0]->ToString();
2070 String::Utf8Value module_v(module);
2072 Local<Object> cache = env->binding_cache_object();
2073 Local<Object> exports;
2075 if (cache->Has(module)) {
2076 exports = cache->Get(module)->ToObject();
2077 args.GetReturnValue().Set(exports);
2081 // Append a string to process.moduleLoadList
2083 snprintf(buf, sizeof(buf), "Binding %s", *module_v);
2085 Local<Array> modules = env->module_load_list_array();
2086 uint32_t l = modules->Length();
2087 modules->Set(l, OneByteString(node_isolate, buf));
2089 node_module_struct* mod = get_builtin_module(*module_v);
2091 exports = Object::New();
2092 // Internal bindings don't have a "module" object, only exports.
2093 assert(mod->register_func == NULL);
2094 assert(mod->register_context_func != NULL);
2095 Local<Value> unused = Undefined(env->isolate());
2096 mod->register_context_func(exports, unused, env->context());
2097 cache->Set(module, exports);
2098 } else if (!strcmp(*module_v, "constants")) {
2099 exports = Object::New();
2100 DefineConstants(exports);
2101 cache->Set(module, exports);
2102 } else if (!strcmp(*module_v, "natives")) {
2103 exports = Object::New();
2104 DefineJavaScript(exports);
2105 cache->Set(module, exports);
2107 return ThrowError("No such module");
2110 args.GetReturnValue().Set(exports);
2114 static void ProcessTitleGetter(Local<String> property,
2115 const PropertyCallbackInfo<Value>& info) {
2116 HandleScope scope(node_isolate);
2118 uv_get_process_title(buffer, sizeof(buffer));
2119 info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2123 static void ProcessTitleSetter(Local<String> property,
2125 const PropertyCallbackInfo<void>& info) {
2126 HandleScope scope(node_isolate);
2127 String::Utf8Value title(value);
2128 // TODO(piscisaureus): protect with a lock
2129 uv_set_process_title(*title);
2133 static void EnvGetter(Local<String> property,
2134 const PropertyCallbackInfo<Value>& info) {
2135 HandleScope scope(node_isolate);
2137 String::Utf8Value key(property);
2138 const char* val = getenv(*key);
2140 return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2143 String::Value key(property);
2144 WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2145 DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2147 ARRAY_SIZE(buffer));
2148 // If result >= sizeof buffer the buffer was too small. That should never
2149 // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2151 if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2152 result < ARRAY_SIZE(buffer)) {
2153 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2154 Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2155 return info.GetReturnValue().Set(rc);
2158 // Not found. Fetch from prototype.
2159 info.GetReturnValue().Set(
2160 info.Data().As<Object>()->Get(property));
2164 static void EnvSetter(Local<String> property,
2166 const PropertyCallbackInfo<Value>& info) {
2167 HandleScope scope(node_isolate);
2169 String::Utf8Value key(property);
2170 String::Utf8Value val(value);
2171 setenv(*key, *val, 1);
2173 String::Value key(property);
2174 String::Value val(value);
2175 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2176 // Environment variables that start with '=' are read-only.
2177 if (key_ptr[0] != L'=') {
2178 SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2181 // Whether it worked or not, always return rval.
2182 info.GetReturnValue().Set(value);
2186 static void EnvQuery(Local<String> property,
2187 const PropertyCallbackInfo<Integer>& info) {
2188 HandleScope scope(node_isolate);
2189 int32_t rc = -1; // Not found unless proven otherwise.
2191 String::Utf8Value key(property);
2195 String::Value key(property);
2196 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2197 if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2198 GetLastError() == ERROR_SUCCESS) {
2200 if (key_ptr[0] == L'=') {
2201 // Environment variables that start with '=' are hidden and read-only.
2202 rc = static_cast<int32_t>(v8::ReadOnly) |
2203 static_cast<int32_t>(v8::DontDelete) |
2204 static_cast<int32_t>(v8::DontEnum);
2209 info.GetReturnValue().Set(rc);
2213 static void EnvDeleter(Local<String> property,
2214 const PropertyCallbackInfo<Boolean>& info) {
2215 HandleScope scope(node_isolate);
2218 String::Utf8Value key(property);
2219 rc = getenv(*key) != NULL;
2223 String::Value key(property);
2224 WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2225 if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2226 // Deletion failed. Return true if the key wasn't there in the first place,
2227 // false if it is still there.
2228 rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2229 GetLastError() != ERROR_SUCCESS;
2232 info.GetReturnValue().Set(rc);
2236 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2237 HandleScope scope(node_isolate);
2240 while (environ[size])
2243 Local<Array> env = Array::New(size);
2245 for (int i = 0; i < size; ++i) {
2246 const char* var = environ[i];
2247 const char* s = strchr(var, '=');
2248 const int length = s ? s - var : strlen(var);
2249 Local<String> name = String::NewFromUtf8(node_isolate,
2251 String::kNormalString,
2256 WCHAR* environment = GetEnvironmentStringsW();
2257 if (environment == NULL)
2258 return; // This should not happen.
2259 Local<Array> env = Array::New();
2260 WCHAR* p = environment;
2262 while (*p != NULL) {
2265 // If the key starts with '=' it is a hidden environment variable.
2269 s = wcschr(p, L'=');
2274 const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2275 const size_t two_byte_buffer_len = s - p;
2276 Local<String> value = String::NewFromTwoByte(node_isolate,
2278 String::kNormalString,
2279 two_byte_buffer_len);
2280 env->Set(i++, value);
2281 p = s + wcslen(s) + 1;
2283 FreeEnvironmentStringsW(environment);
2286 info.GetReturnValue().Set(env);
2290 static Handle<Object> GetFeatures() {
2291 HandleScope scope(node_isolate);
2293 Local<Object> obj = Object::New();
2294 #if defined(DEBUG) && DEBUG
2295 Local<Value> debug = True(node_isolate);
2297 Local<Value> debug = False(node_isolate);
2298 #endif // defined(DEBUG) && DEBUG
2300 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2302 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2303 // TODO(bnoordhuis) ping libuv
2304 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2306 #ifdef OPENSSL_NPN_NEGOTIATED
2307 Local<Boolean> tls_npn = True(node_isolate);
2309 Local<Boolean> tls_npn = False(node_isolate);
2311 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"), tls_npn);
2313 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2314 Local<Boolean> tls_sni = True(node_isolate);
2316 Local<Boolean> tls_sni = False(node_isolate);
2318 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"), tls_sni);
2320 obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2321 Boolean::New(get_builtin_module("crypto") != NULL));
2323 return scope.Close(obj);
2327 static void DebugPortGetter(Local<String> property,
2328 const PropertyCallbackInfo<Value>& info) {
2329 HandleScope scope(node_isolate);
2330 info.GetReturnValue().Set(debug_port);
2334 static void DebugPortSetter(Local<String> property,
2336 const PropertyCallbackInfo<void>& info) {
2337 HandleScope scope(node_isolate);
2338 debug_port = value->NumberValue();
2342 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2343 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2344 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2347 void NeedImmediateCallbackGetter(Local<String> property,
2348 const PropertyCallbackInfo<Value>& info) {
2349 HandleScope handle_scope(info.GetIsolate());
2350 Environment* env = Environment::GetCurrent(info.GetIsolate());
2351 const uv_check_t* immediate_check_handle = env->immediate_check_handle();
2352 bool active = uv_is_active(
2353 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2354 info.GetReturnValue().Set(active);
2358 static void NeedImmediateCallbackSetter(
2359 Local<String> property,
2361 const PropertyCallbackInfo<void>& info) {
2362 HandleScope handle_scope(info.GetIsolate());
2363 Environment* env = Environment::GetCurrent(info.GetIsolate());
2365 uv_check_t* immediate_check_handle = env->immediate_check_handle();
2366 bool active = uv_is_active(
2367 reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2369 if (active == value->BooleanValue())
2372 uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
2375 uv_check_stop(immediate_check_handle);
2376 uv_idle_stop(immediate_idle_handle);
2378 uv_check_start(immediate_check_handle, CheckImmediate);
2379 // Idle handle is needed only to stop the event loop from blocking in poll.
2380 uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
2385 void SetIdle(uv_prepare_t* handle, int) {
2386 Environment* env = Environment::from_idle_prepare_handle(handle);
2387 env->isolate()->GetCpuProfiler()->SetIdle(true);
2391 void ClearIdle(uv_check_t* handle, int) {
2392 Environment* env = Environment::from_idle_check_handle(handle);
2393 env->isolate()->GetCpuProfiler()->SetIdle(false);
2397 void StartProfilerIdleNotifier(Environment* env) {
2398 uv_prepare_start(env->idle_prepare_handle(), SetIdle);
2399 uv_check_start(env->idle_check_handle(), ClearIdle);
2403 void StopProfilerIdleNotifier(Environment* env) {
2404 uv_prepare_stop(env->idle_prepare_handle());
2405 uv_check_stop(env->idle_check_handle());
2409 void StartProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2410 HandleScope handle_scope(args.GetIsolate());
2411 Environment* env = Environment::GetCurrent(args.GetIsolate());
2412 StartProfilerIdleNotifier(env);
2416 void StopProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2417 HandleScope handle_scope(args.GetIsolate());
2418 Environment* env = Environment::GetCurrent(args.GetIsolate());
2419 StopProfilerIdleNotifier(env);
2423 #define READONLY_PROPERTY(obj, str, var) \
2425 obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly); \
2429 void SetupProcessObject(Environment* env,
2431 const char* const* argv,
2433 const char* const* exec_argv) {
2434 HandleScope scope(node_isolate);
2436 Local<Object> process = env->process_object();
2438 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2440 ProcessTitleSetter);
2443 READONLY_PROPERTY(process,
2445 FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2447 // process.moduleLoadList
2448 READONLY_PROPERTY(process,
2450 env->module_load_list_array());
2453 Local<Object> versions = Object::New();
2454 READONLY_PROPERTY(process, "versions", versions);
2456 const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2458 NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2459 READONLY_PROPERTY(versions,
2461 FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2463 // +1 to get rid of the leading 'v'
2464 READONLY_PROPERTY(versions,
2466 OneByteString(node_isolate, NODE_VERSION + 1));
2467 READONLY_PROPERTY(versions,
2469 OneByteString(node_isolate, V8::GetVersion()));
2470 READONLY_PROPERTY(versions,
2472 OneByteString(node_isolate, uv_version_string()));
2473 READONLY_PROPERTY(versions,
2475 FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2477 const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2478 READONLY_PROPERTY(versions,
2480 FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2483 // Stupid code to slice out the version string.
2484 { // NOLINT(whitespace/braces)
2487 for (i = j = 0, k = sizeof(OPENSSL_VERSION_TEXT) - 1; i < k; ++i) {
2488 c = OPENSSL_VERSION_TEXT[i];
2489 if ('0' <= c && c <= '9') {
2490 for (j = i + 1; j < k; ++j) {
2491 c = OPENSSL_VERSION_TEXT[j];
2501 OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2506 READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2509 READONLY_PROPERTY(process,
2511 OneByteString(node_isolate, PLATFORM));
2514 Local<Array> arguments = Array::New(argc);
2515 for (int i = 0; i < argc; ++i) {
2516 arguments->Set(i, String::NewFromUtf8(node_isolate, argv[i]));
2518 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2521 Local<Array> exec_arguments = Array::New(exec_argc);
2522 for (int i = 0; i < exec_argc; ++i) {
2523 exec_arguments->Set(i, String::NewFromUtf8(node_isolate, exec_argv[i]));
2525 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_arguments);
2527 // create process.env
2528 Local<ObjectTemplate> process_env_template = ObjectTemplate::New();
2529 process_env_template->SetNamedPropertyHandler(EnvGetter,
2535 Local<Object> process_env = process_env_template->NewInstance();
2536 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), process_env);
2538 READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2539 READONLY_PROPERTY(process, "features", GetFeatures());
2540 process->SetAccessor(
2541 FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2542 NeedImmediateCallbackGetter,
2543 NeedImmediateCallbackSetter);
2547 READONLY_PROPERTY(process,
2549 String::NewFromUtf8(node_isolate, eval_string));
2554 READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2557 // -i, --interactive
2559 READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2563 if (no_deprecation) {
2564 READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2567 // --throw-deprecation
2568 if (throw_deprecation) {
2569 READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2572 // --trace-deprecation
2573 if (trace_deprecation) {
2574 READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2577 size_t exec_path_len = 2 * PATH_MAX;
2578 char* exec_path = new char[exec_path_len];
2579 Local<String> exec_path_value;
2580 if (uv_exepath(exec_path, &exec_path_len) == 0) {
2581 exec_path_value = String::NewFromUtf8(node_isolate,
2583 String::kNormalString,
2586 exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2588 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2592 process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2596 // define various internal methods
2597 NODE_SET_METHOD(process,
2598 "_startProfilerIdleNotifier",
2599 StartProfilerIdleNotifier);
2600 NODE_SET_METHOD(process,
2601 "_stopProfilerIdleNotifier",
2602 StopProfilerIdleNotifier);
2603 NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2604 NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2605 NODE_SET_METHOD(process, "reallyExit", Exit);
2606 NODE_SET_METHOD(process, "abort", Abort);
2607 NODE_SET_METHOD(process, "chdir", Chdir);
2608 NODE_SET_METHOD(process, "cwd", Cwd);
2610 NODE_SET_METHOD(process, "umask", Umask);
2612 #if defined(__POSIX__) && !defined(__ANDROID__)
2613 NODE_SET_METHOD(process, "getuid", GetUid);
2614 NODE_SET_METHOD(process, "setuid", SetUid);
2616 NODE_SET_METHOD(process, "setgid", SetGid);
2617 NODE_SET_METHOD(process, "getgid", GetGid);
2619 NODE_SET_METHOD(process, "getgroups", GetGroups);
2620 NODE_SET_METHOD(process, "setgroups", SetGroups);
2621 NODE_SET_METHOD(process, "initgroups", InitGroups);
2622 #endif // __POSIX__ && !defined(__ANDROID__)
2624 NODE_SET_METHOD(process, "_kill", Kill);
2626 NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2627 NODE_SET_METHOD(process, "_debugPause", DebugPause);
2628 NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2630 NODE_SET_METHOD(process, "hrtime", Hrtime);
2632 NODE_SET_METHOD(process, "dlopen", DLOpen);
2634 NODE_SET_METHOD(process, "uptime", Uptime);
2635 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2637 NODE_SET_METHOD(process, "binding", Binding);
2639 NODE_SET_METHOD(process, "_setupAsyncListener", SetupAsyncListener);
2640 NODE_SET_METHOD(process, "_setupNextTick", SetupNextTick);
2641 NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2643 // values use to cross communicate with processNextTick
2644 Local<Object> tick_info_obj = Object::New();
2645 tick_info_obj->SetIndexedPropertiesToExternalArrayData(
2646 env->tick_info()->fields(),
2647 kExternalUnsignedIntArray,
2648 env->tick_info()->fields_count());
2649 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfo"), tick_info_obj);
2651 // pre-set _events object for faster emit checks
2652 process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2656 #undef READONLY_PROPERTY
2659 static void AtExit() {
2660 uv_tty_reset_mode();
2664 static void SignalExit(int signal) {
2665 uv_tty_reset_mode();
2666 _exit(128 + signal);
2670 // Most of the time, it's best to use `console.error` to write
2671 // to the process.stderr stream. However, in some cases, such as
2672 // when debugging the stream.Writable class or the process.nextTick
2673 // function, it is useful to bypass JavaScript entirely.
2674 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2675 HandleScope scope(node_isolate);
2677 assert(args.Length() == 1 && args[0]->IsString() &&
2678 "must be called with a single string");
2680 String::Utf8Value message(args[0]);
2681 fprintf(stderr, "%s\n", *message);
2686 void Load(Environment* env) {
2687 HandleScope handle_scope(node_isolate);
2689 // Compile, execute the src/node.js file. (Which was included as static C
2690 // string in node_natives.h. 'natve_node' is the string containing that
2693 // The node.js file returns a function 'f'
2698 // Disable verbose mode to stop FatalException() handler from trying
2699 // to handle the exception. Errors this early in the start-up phase
2700 // are not safe to ignore.
2701 try_catch.SetVerbose(false);
2703 Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2704 Local<Value> f_value = ExecuteString(MainSource(), script_name);
2705 if (try_catch.HasCaught()) {
2706 ReportException(try_catch);
2709 assert(f_value->IsFunction());
2710 Local<Function> f = Local<Function>::Cast(f_value);
2712 // Now we call 'f' with the 'process' variable that we've built up with
2713 // all our bindings. Inside node.js we'll take care of assigning things to
2716 // We start the process this way in order to be more modular. Developers
2717 // who do not like how 'src/node.js' setups the module system but do like
2718 // Node's I/O bindings may want to replace 'f' with their own function.
2720 // Add a reference to the global object
2721 Local<Object> global = env->context()->Global();
2723 #if defined HAVE_DTRACE || defined HAVE_ETW
2727 #if defined HAVE_PERFCTR
2728 InitPerfCounters(global);
2731 // Enable handling of uncaught exceptions
2732 // (FatalException(), break on uncaught exception in debugger)
2734 // This is not strictly necessary since it's almost impossible
2735 // to attach the debugger fast enought to break on exception
2736 // thrown during process startup.
2737 try_catch.SetVerbose(true);
2739 NODE_SET_METHOD(env->process_object(), "_rawDebug", RawDebug);
2741 Local<Value> arg = env->process_object();
2742 f->Call(global, 1, &arg);
2745 static void PrintHelp();
2747 static bool ParseDebugOpt(const char* arg) {
2748 const char* port = NULL;
2750 if (!strcmp(arg, "--debug")) {
2751 use_debug_agent = true;
2752 } else if (!strncmp(arg, "--debug=", sizeof("--debug=") - 1)) {
2753 use_debug_agent = true;
2754 port = arg + sizeof("--debug=") - 1;
2755 } else if (!strcmp(arg, "--debug-brk")) {
2756 use_debug_agent = true;
2757 debug_wait_connect = true;
2758 } else if (!strncmp(arg, "--debug-brk=", sizeof("--debug-brk=") - 1)) {
2759 use_debug_agent = true;
2760 debug_wait_connect = true;
2761 port = arg + sizeof("--debug-brk=") - 1;
2762 } else if (!strncmp(arg, "--debug-port=", sizeof("--debug-port=") - 1)) {
2763 port = arg + sizeof("--debug-port=") - 1;
2769 debug_port = atoi(port);
2770 if (debug_port < 1024 || debug_port > 65535) {
2771 fprintf(stderr, "Debug port must be in range 1024 to 65535.\n");
2780 static void PrintHelp() {
2781 printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2782 " node debug script.js [arguments] \n"
2785 " -v, --version print node's version\n"
2786 " -e, --eval script evaluate script\n"
2787 " -p, --print evaluate script and print result\n"
2788 " -i, --interactive always enter the REPL even if stdin\n"
2789 " does not appear to be a terminal\n"
2790 " --no-deprecation silence deprecation warnings\n"
2791 " --trace-deprecation show stack traces on deprecations\n"
2792 " --v8-options print v8 command line options\n"
2793 " --max-stack-size=val set max v8 stack size (bytes)\n"
2795 "Environment variables:\n"
2797 "NODE_PATH ';'-separated list of directories\n"
2799 "NODE_PATH ':'-separated list of directories\n"
2801 " prefixed to the module search path.\n"
2802 "NODE_MODULE_CONTEXTS Set to 1 to load modules in their own\n"
2803 " global contexts.\n"
2804 "NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL\n"
2806 "Documentation can be found at http://nodejs.org/\n");
2810 // Parse command line arguments.
2812 // argv is modified in place. exec_argv and v8_argv are out arguments that
2813 // ParseArgs() allocates memory for and stores a pointer to the output
2814 // vector in. The caller should free them with delete[].
2818 // * argv contains the arguments with node and V8 options filtered out.
2819 // * exec_argv contains both node and V8 options and nothing else.
2820 // * v8_argv contains argv[0] plus any V8 options
2821 static void ParseArgs(int* argc,
2824 const char*** exec_argv,
2826 const char*** v8_argv) {
2827 const unsigned int nargs = static_cast<unsigned int>(*argc);
2828 const char** new_exec_argv = new const char*[nargs];
2829 const char** new_v8_argv = new const char*[nargs];
2830 const char** new_argv = new const char*[nargs];
2832 for (unsigned int i = 0; i < nargs; ++i) {
2833 new_exec_argv[i] = NULL;
2834 new_v8_argv[i] = NULL;
2838 // exec_argv starts with the first option, the other two start with argv[0].
2839 unsigned int new_exec_argc = 0;
2840 unsigned int new_v8_argc = 1;
2841 unsigned int new_argc = 1;
2842 new_v8_argv[0] = argv[0];
2843 new_argv[0] = argv[0];
2845 unsigned int index = 1;
2846 while (index < nargs && argv[index][0] == '-') {
2847 const char* const arg = argv[index];
2848 unsigned int args_consumed = 1;
2850 if (ParseDebugOpt(arg)) {
2851 // Done, consumed by ParseDebugOpt().
2852 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2853 printf("%s\n", NODE_VERSION);
2855 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2858 } else if (strcmp(arg, "--eval") == 0 ||
2859 strcmp(arg, "-e") == 0 ||
2860 strcmp(arg, "--print") == 0 ||
2861 strcmp(arg, "-pe") == 0 ||
2862 strcmp(arg, "-p") == 0) {
2863 bool is_eval = strchr(arg, 'e') != NULL;
2864 bool is_print = strchr(arg, 'p') != NULL;
2865 print_eval = print_eval || is_print;
2866 // --eval, -e and -pe always require an argument.
2867 if (is_eval == true) {
2869 eval_string = argv[index + 1];
2870 if (eval_string == NULL) {
2871 fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
2874 } else if (argv[index + 1] != NULL && argv[index + 1][0] != '-') {
2876 eval_string = argv[index + 1];
2877 if (strncmp(eval_string, "\\-", 2) == 0) {
2878 // Starts with "\\-": escaped expression, drop the backslash.
2882 } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2884 } else if (strcmp(arg, "--no-deprecation") == 0) {
2885 no_deprecation = true;
2886 } else if (strcmp(arg, "--trace-deprecation") == 0) {
2887 trace_deprecation = true;
2888 } else if (strcmp(arg, "--throw-deprecation") == 0) {
2889 throw_deprecation = true;
2890 } else if (strcmp(arg, "--v8-options") == 0) {
2891 new_v8_argv[new_v8_argc] = "--help";
2894 // V8 option. Pass through as-is.
2895 new_v8_argv[new_v8_argc] = arg;
2899 memcpy(new_exec_argv + new_exec_argc,
2901 args_consumed * sizeof(*argv));
2903 new_exec_argc += args_consumed;
2904 index += args_consumed;
2907 // Copy remaining arguments.
2908 const unsigned int args_left = nargs - index;
2909 memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
2910 new_argc += args_left;
2912 *exec_argc = new_exec_argc;
2913 *exec_argv = new_exec_argv;
2914 *v8_argc = new_v8_argc;
2915 *v8_argv = new_v8_argv;
2917 // Copy new_argv over argv and update argc.
2918 memcpy(argv, new_argv, new_argc * sizeof(*argv));
2920 *argc = static_cast<int>(new_argc);
2924 // Called from V8 Debug Agent TCP thread.
2925 static void DispatchMessagesDebugAgentCallback() {
2926 uv_async_send(&dispatch_debug_messages_async);
2930 // Called from the main thread.
2931 static void EnableDebug(bool wait_connect) {
2932 assert(debugger_running == false);
2933 Isolate* isolate = node_isolate; // TODO(bnoordhuis) Multi-isolate support.
2934 Isolate::Scope isolate_scope(isolate);
2935 HandleScope handle_scope(isolate);
2936 v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2938 debugger_running = v8::Debug::EnableAgent("node " NODE_VERSION,
2941 if (debugger_running == false) {
2942 fprintf(stderr, "Starting debugger on port %d failed\n", debug_port);
2946 fprintf(stderr, "Debugger listening on port %d\n", debug_port);
2949 Environment* env = Environment::GetCurrentChecked(isolate);
2951 return; // Still starting up.
2953 Context::Scope context_scope(env->context());
2954 Local<Object> message = Object::New();
2955 message->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "cmd"),
2956 FIXED_ONE_BYTE_STRING(env->isolate(), "NODE_DEBUG_ENABLED"));
2957 Local<Value> argv[] = {
2958 FIXED_ONE_BYTE_STRING(env->isolate(), "internalMessage"),
2961 MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(argv), argv);
2965 // Called from the main thread.
2966 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2967 if (debugger_running == false) {
2968 fprintf(stderr, "Starting debugger agent.\n");
2971 Isolate::Scope isolate_scope(node_isolate);
2972 v8::Debug::ProcessDebugMessages();
2977 static volatile sig_atomic_t caught_early_debug_signal;
2980 static void EarlyDebugSignalHandler(int signo) {
2981 caught_early_debug_signal = 1;
2985 static void InstallEarlyDebugSignalHandler() {
2986 struct sigaction sa;
2987 memset(&sa, 0, sizeof(sa));
2988 sa.sa_handler = EarlyDebugSignalHandler;
2989 sigaction(SIGUSR1, &sa, NULL);
2993 static void EnableDebugSignalHandler(int signo) {
2994 // Call only async signal-safe functions here!
2995 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
2996 uv_async_send(&dispatch_debug_messages_async);
3000 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
3001 struct sigaction sa;
3002 memset(&sa, 0, sizeof(sa));
3003 sa.sa_handler = handler;
3004 sigfillset(&sa.sa_mask);
3005 sigaction(signal, &sa, NULL);
3009 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3010 HandleScope scope(node_isolate);
3012 if (args.Length() != 1) {
3013 return ThrowError("Invalid number of arguments.");
3019 pid = args[0]->IntegerValue();
3020 r = kill(pid, SIGUSR1);
3022 return ThrowErrnoException(errno, "kill");
3027 static int RegisterDebugSignalHandler() {
3028 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3029 RegisterSignalHandler(SIGUSR1, EnableDebugSignalHandler);
3030 // If we caught a SIGUSR1 during the bootstrap process, re-raise it
3031 // now that the debugger infrastructure is in place.
3032 if (caught_early_debug_signal)
3040 DWORD WINAPI EnableDebugThreadProc(void* arg) {
3041 v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
3042 uv_async_send(&dispatch_debug_messages_async);
3047 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
3049 return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
3053 static int RegisterDebugSignalHandler() {
3054 wchar_t mapping_name[32];
3055 HANDLE mapping_handle;
3057 LPTHREAD_START_ROUTINE* handler;
3059 pid = GetCurrentProcessId();
3061 if (GetDebugSignalHandlerMappingName(pid,
3063 ARRAY_SIZE(mapping_name)) < 0) {
3067 mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
3073 if (mapping_handle == NULL) {
3077 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3078 MapViewOfFile(mapping_handle,
3079 FILE_MAP_ALL_ACCESS,
3083 if (handler == NULL) {
3084 CloseHandle(mapping_handle);
3088 *handler = EnableDebugThreadProc;
3090 UnmapViewOfFile(static_cast<void*>(handler));
3096 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3097 HandleScope scope(node_isolate);
3099 HANDLE process = NULL;
3100 HANDLE thread = NULL;
3101 HANDLE mapping = NULL;
3102 wchar_t mapping_name[32];
3103 LPTHREAD_START_ROUTINE* handler = NULL;
3105 if (args.Length() != 1) {
3106 ThrowError("Invalid number of arguments.");
3110 pid = (DWORD) args[0]->IntegerValue();
3112 process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
3113 PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
3117 if (process == NULL) {
3118 ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
3122 if (GetDebugSignalHandlerMappingName(pid,
3124 ARRAY_SIZE(mapping_name)) < 0) {
3125 ThrowErrnoException(errno, "sprintf");
3129 mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
3130 if (mapping == NULL) {
3131 ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
3135 handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3136 MapViewOfFile(mapping,
3141 if (handler == NULL || *handler == NULL) {
3142 ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
3146 thread = CreateRemoteThread(process,
3153 if (thread == NULL) {
3154 ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
3158 // Wait for the thread to terminate
3159 if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3160 ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
3165 if (process != NULL)
3166 CloseHandle(process);
3168 CloseHandle(thread);
3169 if (handler != NULL)
3170 UnmapViewOfFile(handler);
3171 if (mapping != NULL)
3172 CloseHandle(mapping);
3177 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3178 v8::Debug::DebugBreak(node_isolate);
3182 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3183 if (debugger_running) {
3184 v8::Debug::DisableAgent();
3185 debugger_running = false;
3190 void Init(int* argc,
3193 const char*** exec_argv) {
3194 // Initialize prog_start_time to get relative uptime.
3195 uv_uptime(&prog_start_time);
3197 // Make inherited handles noninheritable.
3198 uv_disable_stdio_inheritance();
3200 // init async debug messages dispatching
3201 // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3202 uv_async_init(uv_default_loop(),
3203 &dispatch_debug_messages_async,
3204 DispatchDebugMessagesAsyncCallback);
3205 uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3207 // Parse a few arguments which are specific to Node.
3209 const char** v8_argv;
3210 ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3212 // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
3213 // manually? That would give us a little more control over its runtime
3214 // behavior but it could also interfere with the user's intentions in ways
3215 // we fail to anticipate. Dillema.
3216 for (int i = 1; i < v8_argc; ++i) {
3217 if (strncmp(v8_argv[i], "--prof", sizeof("--prof") - 1) == 0) {
3218 v8_is_profiling = true;
3223 // The const_cast doesn't violate conceptual const-ness. V8 doesn't modify
3224 // the argv array or the elements it points to.
3225 V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3227 // Anything that's still in v8_argv is not a V8 or a node option.
3228 for (int i = 1; i < v8_argc; i++) {
3229 fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3238 if (debug_wait_connect) {
3239 const char expose_debug_as[] = "--expose_debug_as=v8debug";
3240 V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3243 V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3245 // Fetch a reference to the main isolate, so we have a reference to it
3246 // even when we need it to access it from another (debugger) thread.
3247 node_isolate = Isolate::GetCurrent();
3250 // Raise the open file descriptor limit.
3251 { // NOLINT (whitespace/braces)
3253 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3254 // Do a binary search for the limit.
3255 rlim_t min = lim.rlim_cur;
3256 rlim_t max = 1 << 20;
3257 // But if there's a defined upper bound, don't search, just set it.
3258 if (lim.rlim_max != RLIM_INFINITY) {
3263 lim.rlim_cur = min + (max - min) / 2;
3264 if (setrlimit(RLIMIT_NOFILE, &lim)) {
3269 } while (min + 1 < max);
3273 RegisterSignalHandler(SIGPIPE, SIG_IGN);
3274 RegisterSignalHandler(SIGINT, SignalExit);
3275 RegisterSignalHandler(SIGTERM, SignalExit);
3278 V8::SetFatalErrorHandler(node::OnFatalError);
3279 V8::AddMessageListener(OnMessage);
3281 // If the --debug flag was specified then initialize the debug thread.
3282 if (use_debug_agent) {
3283 EnableDebug(debug_wait_connect);
3285 RegisterDebugSignalHandler();
3290 struct AtExitCallback {
3291 AtExitCallback* next_;
3292 void (*cb_)(void* arg);
3296 static AtExitCallback* at_exit_functions_;
3299 // TODO(bnoordhuis) Turn into per-context event.
3300 void RunAtExit(Environment* env) {
3301 AtExitCallback* p = at_exit_functions_;
3302 at_exit_functions_ = NULL;
3305 AtExitCallback* q = p->next_;
3313 void AtExit(void (*cb)(void* arg), void* arg) {
3314 AtExitCallback* p = new AtExitCallback;
3317 p->next_ = at_exit_functions_;
3318 at_exit_functions_ = p;
3322 void EmitExit(Environment* env) {
3323 // process.emit('exit')
3324 HandleScope handle_scope(env->isolate());
3325 Context::Scope context_scope(env->context());
3326 Local<Object> process_object = env->process_object();
3327 process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3328 True(node_isolate));
3330 Handle<String> exitCode = FIXED_ONE_BYTE_STRING(node_isolate, "exitCode");
3331 int code = process_object->Get(exitCode)->IntegerValue();
3333 Local<Value> args[] = {
3334 FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3335 Integer::New(code, node_isolate)
3338 MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3343 Environment* CreateEnvironment(Isolate* isolate,
3345 const char* const* argv,
3347 const char* const* exec_argv) {
3348 HandleScope handle_scope(isolate);
3350 Local<Context> context = Context::New(isolate);
3351 Context::Scope context_scope(context);
3352 Environment* env = Environment::New(context);
3354 uv_check_init(env->event_loop(), env->immediate_check_handle());
3356 reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3357 uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3359 // Inform V8's CPU profiler when we're idle. The profiler is sampling-based
3360 // but not all samples are created equal; mark the wall clock time spent in
3361 // epoll_wait() and friends so profiling tools can filter it out. The samples
3362 // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
3363 // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
3364 // probably fortify in the API contract, namely that the last started prepare
3365 // or check watcher runs first. It's not 100% foolproof; if an add-on starts
3366 // a prepare or check watcher after us, any samples attributed to its callback
3367 // will be recorded with state=IDLE.
3368 uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
3369 uv_check_init(env->event_loop(), env->idle_check_handle());
3370 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
3371 uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
3373 if (v8_is_profiling) {
3374 StartProfilerIdleNotifier(env);
3377 Local<FunctionTemplate> process_template = FunctionTemplate::New();
3378 process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3380 Local<Object> process_object = process_template->GetFunction()->NewInstance();
3381 env->set_process_object(process_object);
3383 SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3390 int Start(int argc, char** argv) {
3391 #if !defined(_WIN32)
3392 // Try hard not to lose SIGUSR1 signals during the bootstrap process.
3393 InstallEarlyDebugSignalHandler();
3398 // Hack around with the argv pointer. Used for process.title = "blah".
3399 argv = uv_setup_args(argc, argv);
3401 // This needs to run *before* V8::Initialize(). The const_cast is not
3402 // optional, in case you're wondering.
3404 const char** exec_argv;
3405 Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3408 // V8 on Windows doesn't have a good source of entropy. Seed it from
3410 V8::SetEntropySource(crypto::EntropySource);
3415 Locker locker(node_isolate);
3417 CreateEnvironment(node_isolate, argc, argv, exec_argc, exec_argv);
3418 // This Context::Scope is here so EnableDebug() can look up the current
3419 // environment with Environment::GetCurrentChecked().
3420 // TODO(bnoordhuis) Reorder the debugger initialization logic so it can
3422 Context::Scope context_scope(env->context());
3423 uv_run(env->event_loop(), UV_RUN_DEFAULT);
3431 // Clean up. Not strictly necessary.