#include "node.h" #include "node_buffer.h" #include "node_constants.h" #include "node_file.h" #include "node_http_parser.h" #include "node_javascript.h" #include "node_version.h" #include "node_internals.h" #include "node_revert.h" #if defined HAVE_PERFCTR #include "node_counters.h" #endif #if HAVE_OPENSSL #include "node_crypto.h" #endif #if defined(NODE_HAVE_I18N_SUPPORT) #include "node_i18n.h" #endif #if defined HAVE_DTRACE || defined HAVE_ETW #include "node_dtrace.h" #endif #if defined HAVE_LTTNG #include "node_lttng.h" #endif #include "ares.h" #include "async-wrap.h" #include "async-wrap-inl.h" #include "env.h" #include "env-inl.h" #include "handle_wrap.h" #include "req-wrap.h" #include "req-wrap-inl.h" #include "string_bytes.h" #include "util.h" #include "uv.h" #include "libplatform/libplatform.h" #include "v8-debug.h" #include "v8-profiler.h" #include "zlib.h" #ifdef NODE_ENABLE_VTUNE_PROFILING #include "../deps/v8/src/third_party/vtune/v8-vtune.h" #endif #include #include // PATH_MAX #include #include #include #include #include #include #include #if defined(NODE_HAVE_I18N_SUPPORT) #include #endif #if defined(LEAK_SANITIZER) #include #endif #if defined(_MSC_VER) #include #include #define getpid GetCurrentProcessId #define umask _umask typedef int mode_t; #else #include #include // getrlimit, setrlimit #include // setuid, getuid #endif #if defined(__POSIX__) && !defined(__ANDROID__) #include // getpwnam() #include // getgrnam() #endif #ifdef __APPLE__ #include #define environ (*_NSGetEnviron()) #elif !defined(_MSC_VER) extern char **environ; #endif namespace node { using v8::Array; using v8::ArrayBuffer; using v8::Boolean; using v8::Context; using v8::EscapableHandleScope; using v8::Exception; using v8::Float64Array; using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; using v8::HeapStatistics; using v8::Integer; using v8::Isolate; using v8::Local; using v8::Locker; using v8::MaybeLocal; using v8::Message; using v8::Name; using v8::Null; using v8::Number; using v8::Object; using v8::ObjectTemplate; using v8::Promise; using v8::PromiseRejectMessage; using v8::PropertyCallbackInfo; using v8::ScriptOrigin; using v8::SealHandleScope; using v8::String; using v8::TryCatch; using v8::Uint32; using v8::Uint32Array; using v8::V8; using v8::Value; static bool print_eval = false; static bool force_repl = false; static bool syntax_check_only = false; static bool trace_deprecation = false; static bool throw_deprecation = false; static bool trace_sync_io = false; static bool track_heap_objects = false; static const char* eval_string = nullptr; static unsigned int preload_module_count = 0; static const char** preload_modules = nullptr; static bool use_debug_agent = false; static bool debug_wait_connect = false; static int debug_port = 5858; static const int v8_default_thread_pool_size = 4; static int v8_thread_pool_size = v8_default_thread_pool_size; static bool prof_process = false; static bool v8_is_profiling = false; static bool node_is_initialized = false; static node_module* modpending; static node_module* modlist_builtin; static node_module* modlist_linked; static node_module* modlist_addon; #if defined(NODE_HAVE_I18N_SUPPORT) // Path to ICU data (for i18n / Intl) static const char* icu_data_dir = nullptr; #endif // used by C++ modules as well bool no_deprecation = false; #if HAVE_OPENSSL && NODE_FIPS_MODE // used by crypto module bool enable_fips_crypto = false; bool force_fips_crypto = false; #endif // true if process warnings should be suppressed bool no_process_warnings = false; bool trace_warnings = false; // Set in node.cc by ParseArgs when --preserve-symlinks is used. // Used in node_config.cc to set a constant on process.binding('config') // that is used by lib/module.js bool config_preserve_symlinks = false; // process-relative uptime base, initialized at start-up static double prog_start_time; static bool debugger_running; static uv_async_t dispatch_debug_messages_async; static uv_mutex_t node_isolate_mutex; static v8::Isolate* node_isolate; static v8::Platform* default_platform; #ifdef __POSIX__ static uv_sem_t debug_semaphore; #endif static void PrintErrorString(const char* format, ...) { va_list ap; va_start(ap, format); #ifdef _WIN32 HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE); // Check if stderr is something other than a tty/console if (stderr_handle == INVALID_HANDLE_VALUE || stderr_handle == nullptr || uv_guess_handle(_fileno(stderr)) != UV_TTY) { vfprintf(stderr, format, ap); va_end(ap); return; } // Fill in any placeholders int n = _vscprintf(format, ap); std::vector out(n + 1); vsprintf(out.data(), format, ap); // Get required wide buffer size n = MultiByteToWideChar(CP_UTF8, 0, out.data(), -1, nullptr, 0); std::vector wbuf(n); MultiByteToWideChar(CP_UTF8, 0, out.data(), -1, wbuf.data(), n); WriteConsoleW(stderr_handle, wbuf.data(), n, nullptr, nullptr); #else vfprintf(stderr, format, ap); #endif va_end(ap); } static void CheckImmediate(uv_check_t* handle) { Environment* env = Environment::from_immediate_check_handle(handle); HandleScope scope(env->isolate()); Context::Scope context_scope(env->context()); MakeCallback(env, env->process_object(), env->immediate_callback_string()); } static void IdleImmediateDummy(uv_idle_t* handle) { // Do nothing. Only for maintaining event loop. // TODO(bnoordhuis) Maybe make libuv accept nullptr idle callbacks. } static inline const char *errno_string(int errorno) { #define ERRNO_CASE(e) case e: return #e; switch (errorno) { #ifdef EACCES ERRNO_CASE(EACCES); #endif #ifdef EADDRINUSE ERRNO_CASE(EADDRINUSE); #endif #ifdef EADDRNOTAVAIL ERRNO_CASE(EADDRNOTAVAIL); #endif #ifdef EAFNOSUPPORT ERRNO_CASE(EAFNOSUPPORT); #endif #ifdef EAGAIN ERRNO_CASE(EAGAIN); #endif #ifdef EWOULDBLOCK # if EAGAIN != EWOULDBLOCK ERRNO_CASE(EWOULDBLOCK); # endif #endif #ifdef EALREADY ERRNO_CASE(EALREADY); #endif #ifdef EBADF ERRNO_CASE(EBADF); #endif #ifdef EBADMSG ERRNO_CASE(EBADMSG); #endif #ifdef EBUSY ERRNO_CASE(EBUSY); #endif #ifdef ECANCELED ERRNO_CASE(ECANCELED); #endif #ifdef ECHILD ERRNO_CASE(ECHILD); #endif #ifdef ECONNABORTED ERRNO_CASE(ECONNABORTED); #endif #ifdef ECONNREFUSED ERRNO_CASE(ECONNREFUSED); #endif #ifdef ECONNRESET ERRNO_CASE(ECONNRESET); #endif #ifdef EDEADLK ERRNO_CASE(EDEADLK); #endif #ifdef EDESTADDRREQ ERRNO_CASE(EDESTADDRREQ); #endif #ifdef EDOM ERRNO_CASE(EDOM); #endif #ifdef EDQUOT ERRNO_CASE(EDQUOT); #endif #ifdef EEXIST ERRNO_CASE(EEXIST); #endif #ifdef EFAULT ERRNO_CASE(EFAULT); #endif #ifdef EFBIG ERRNO_CASE(EFBIG); #endif #ifdef EHOSTUNREACH ERRNO_CASE(EHOSTUNREACH); #endif #ifdef EIDRM ERRNO_CASE(EIDRM); #endif #ifdef EILSEQ ERRNO_CASE(EILSEQ); #endif #ifdef EINPROGRESS ERRNO_CASE(EINPROGRESS); #endif #ifdef EINTR ERRNO_CASE(EINTR); #endif #ifdef EINVAL ERRNO_CASE(EINVAL); #endif #ifdef EIO ERRNO_CASE(EIO); #endif #ifdef EISCONN ERRNO_CASE(EISCONN); #endif #ifdef EISDIR ERRNO_CASE(EISDIR); #endif #ifdef ELOOP ERRNO_CASE(ELOOP); #endif #ifdef EMFILE ERRNO_CASE(EMFILE); #endif #ifdef EMLINK ERRNO_CASE(EMLINK); #endif #ifdef EMSGSIZE ERRNO_CASE(EMSGSIZE); #endif #ifdef EMULTIHOP ERRNO_CASE(EMULTIHOP); #endif #ifdef ENAMETOOLONG ERRNO_CASE(ENAMETOOLONG); #endif #ifdef ENETDOWN ERRNO_CASE(ENETDOWN); #endif #ifdef ENETRESET ERRNO_CASE(ENETRESET); #endif #ifdef ENETUNREACH ERRNO_CASE(ENETUNREACH); #endif #ifdef ENFILE ERRNO_CASE(ENFILE); #endif #ifdef ENOBUFS ERRNO_CASE(ENOBUFS); #endif #ifdef ENODATA ERRNO_CASE(ENODATA); #endif #ifdef ENODEV ERRNO_CASE(ENODEV); #endif #ifdef ENOENT ERRNO_CASE(ENOENT); #endif #ifdef ENOEXEC ERRNO_CASE(ENOEXEC); #endif #ifdef ENOLINK ERRNO_CASE(ENOLINK); #endif #ifdef ENOLCK # if ENOLINK != ENOLCK ERRNO_CASE(ENOLCK); # endif #endif #ifdef ENOMEM ERRNO_CASE(ENOMEM); #endif #ifdef ENOMSG ERRNO_CASE(ENOMSG); #endif #ifdef ENOPROTOOPT ERRNO_CASE(ENOPROTOOPT); #endif #ifdef ENOSPC ERRNO_CASE(ENOSPC); #endif #ifdef ENOSR ERRNO_CASE(ENOSR); #endif #ifdef ENOSTR ERRNO_CASE(ENOSTR); #endif #ifdef ENOSYS ERRNO_CASE(ENOSYS); #endif #ifdef ENOTCONN ERRNO_CASE(ENOTCONN); #endif #ifdef ENOTDIR ERRNO_CASE(ENOTDIR); #endif #ifdef ENOTEMPTY # if ENOTEMPTY != EEXIST ERRNO_CASE(ENOTEMPTY); # endif #endif #ifdef ENOTSOCK ERRNO_CASE(ENOTSOCK); #endif #ifdef ENOTSUP ERRNO_CASE(ENOTSUP); #else # ifdef EOPNOTSUPP ERRNO_CASE(EOPNOTSUPP); # endif #endif #ifdef ENOTTY ERRNO_CASE(ENOTTY); #endif #ifdef ENXIO ERRNO_CASE(ENXIO); #endif #ifdef EOVERFLOW ERRNO_CASE(EOVERFLOW); #endif #ifdef EPERM ERRNO_CASE(EPERM); #endif #ifdef EPIPE ERRNO_CASE(EPIPE); #endif #ifdef EPROTO ERRNO_CASE(EPROTO); #endif #ifdef EPROTONOSUPPORT ERRNO_CASE(EPROTONOSUPPORT); #endif #ifdef EPROTOTYPE ERRNO_CASE(EPROTOTYPE); #endif #ifdef ERANGE ERRNO_CASE(ERANGE); #endif #ifdef EROFS ERRNO_CASE(EROFS); #endif #ifdef ESPIPE ERRNO_CASE(ESPIPE); #endif #ifdef ESRCH ERRNO_CASE(ESRCH); #endif #ifdef ESTALE ERRNO_CASE(ESTALE); #endif #ifdef ETIME ERRNO_CASE(ETIME); #endif #ifdef ETIMEDOUT ERRNO_CASE(ETIMEDOUT); #endif #ifdef ETXTBSY ERRNO_CASE(ETXTBSY); #endif #ifdef EXDEV ERRNO_CASE(EXDEV); #endif default: return ""; } } const char *signo_string(int signo) { #define SIGNO_CASE(e) case e: return #e; switch (signo) { #ifdef SIGHUP SIGNO_CASE(SIGHUP); #endif #ifdef SIGINT SIGNO_CASE(SIGINT); #endif #ifdef SIGQUIT SIGNO_CASE(SIGQUIT); #endif #ifdef SIGILL SIGNO_CASE(SIGILL); #endif #ifdef SIGTRAP SIGNO_CASE(SIGTRAP); #endif #ifdef SIGABRT SIGNO_CASE(SIGABRT); #endif #ifdef SIGIOT # if SIGABRT != SIGIOT SIGNO_CASE(SIGIOT); # endif #endif #ifdef SIGBUS SIGNO_CASE(SIGBUS); #endif #ifdef SIGFPE SIGNO_CASE(SIGFPE); #endif #ifdef SIGKILL SIGNO_CASE(SIGKILL); #endif #ifdef SIGUSR1 SIGNO_CASE(SIGUSR1); #endif #ifdef SIGSEGV SIGNO_CASE(SIGSEGV); #endif #ifdef SIGUSR2 SIGNO_CASE(SIGUSR2); #endif #ifdef SIGPIPE SIGNO_CASE(SIGPIPE); #endif #ifdef SIGALRM SIGNO_CASE(SIGALRM); #endif SIGNO_CASE(SIGTERM); #ifdef SIGCHLD SIGNO_CASE(SIGCHLD); #endif #ifdef SIGSTKFLT SIGNO_CASE(SIGSTKFLT); #endif #ifdef SIGCONT SIGNO_CASE(SIGCONT); #endif #ifdef SIGSTOP SIGNO_CASE(SIGSTOP); #endif #ifdef SIGTSTP SIGNO_CASE(SIGTSTP); #endif #ifdef SIGBREAK SIGNO_CASE(SIGBREAK); #endif #ifdef SIGTTIN SIGNO_CASE(SIGTTIN); #endif #ifdef SIGTTOU SIGNO_CASE(SIGTTOU); #endif #ifdef SIGURG SIGNO_CASE(SIGURG); #endif #ifdef SIGXCPU SIGNO_CASE(SIGXCPU); #endif #ifdef SIGXFSZ SIGNO_CASE(SIGXFSZ); #endif #ifdef SIGVTALRM SIGNO_CASE(SIGVTALRM); #endif #ifdef SIGPROF SIGNO_CASE(SIGPROF); #endif #ifdef SIGWINCH SIGNO_CASE(SIGWINCH); #endif #ifdef SIGIO SIGNO_CASE(SIGIO); #endif #ifdef SIGPOLL # if SIGPOLL != SIGIO SIGNO_CASE(SIGPOLL); # endif #endif #ifdef SIGLOST # if SIGLOST != SIGABRT SIGNO_CASE(SIGLOST); # endif #endif #ifdef SIGPWR # if SIGPWR != SIGLOST SIGNO_CASE(SIGPWR); # endif #endif #ifdef SIGINFO # if !defined(SIGPWR) || SIGINFO != SIGPWR SIGNO_CASE(SIGINFO); # endif #endif #ifdef SIGSYS SIGNO_CASE(SIGSYS); #endif default: return ""; } } // Convenience methods void ThrowError(v8::Isolate* isolate, const char* errmsg) { Environment::GetCurrent(isolate)->ThrowError(errmsg); } void ThrowTypeError(v8::Isolate* isolate, const char* errmsg) { Environment::GetCurrent(isolate)->ThrowTypeError(errmsg); } void ThrowRangeError(v8::Isolate* isolate, const char* errmsg) { Environment::GetCurrent(isolate)->ThrowRangeError(errmsg); } void ThrowErrnoException(v8::Isolate* isolate, int errorno, const char* syscall, const char* message, const char* path) { Environment::GetCurrent(isolate)->ThrowErrnoException(errorno, syscall, message, path); } void ThrowUVException(v8::Isolate* isolate, int errorno, const char* syscall, const char* message, const char* path, const char* dest) { Environment::GetCurrent(isolate) ->ThrowUVException(errorno, syscall, message, path, dest); } Local ErrnoException(Isolate* isolate, int errorno, const char *syscall, const char *msg, const char *path) { Environment* env = Environment::GetCurrent(isolate); Local e; Local estring = OneByteString(env->isolate(), errno_string(errorno)); if (msg == nullptr || msg[0] == '\0') { msg = strerror(errorno); } Local message = OneByteString(env->isolate(), msg); Local cons = String::Concat(estring, FIXED_ONE_BYTE_STRING(env->isolate(), ", ")); cons = String::Concat(cons, message); Local path_string; if (path != nullptr) { // FIXME(bnoordhuis) It's questionable to interpret the file path as UTF-8. path_string = String::NewFromUtf8(env->isolate(), path); } if (path_string.IsEmpty() == false) { cons = String::Concat(cons, FIXED_ONE_BYTE_STRING(env->isolate(), " '")); cons = String::Concat(cons, path_string); cons = String::Concat(cons, FIXED_ONE_BYTE_STRING(env->isolate(), "'")); } e = Exception::Error(cons); Local obj = e->ToObject(env->isolate()); obj->Set(env->errno_string(), Integer::New(env->isolate(), errorno)); obj->Set(env->code_string(), estring); if (path_string.IsEmpty() == false) { obj->Set(env->path_string(), path_string); } if (syscall != nullptr) { obj->Set(env->syscall_string(), OneByteString(env->isolate(), syscall)); } return e; } static Local StringFromPath(Isolate* isolate, const char* path) { #ifdef _WIN32 if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) { return String::Concat(FIXED_ONE_BYTE_STRING(isolate, "\\\\"), String::NewFromUtf8(isolate, path + 8)); } else if (strncmp(path, "\\\\?\\", 4) == 0) { return String::NewFromUtf8(isolate, path + 4); } #endif return String::NewFromUtf8(isolate, path); } Local UVException(Isolate* isolate, int errorno, const char* syscall, const char* msg, const char* path) { return UVException(isolate, errorno, syscall, msg, path, nullptr); } Local UVException(Isolate* isolate, int errorno, const char* syscall, const char* msg, const char* path, const char* dest) { Environment* env = Environment::GetCurrent(isolate); if (!msg || !msg[0]) msg = uv_strerror(errorno); Local js_code = OneByteString(isolate, uv_err_name(errorno)); Local js_syscall = OneByteString(isolate, syscall); Local js_path; Local js_dest; Local js_msg = js_code; js_msg = String::Concat(js_msg, FIXED_ONE_BYTE_STRING(isolate, ": ")); js_msg = String::Concat(js_msg, OneByteString(isolate, msg)); js_msg = String::Concat(js_msg, FIXED_ONE_BYTE_STRING(isolate, ", ")); js_msg = String::Concat(js_msg, js_syscall); if (path != nullptr) { js_path = StringFromPath(isolate, path); js_msg = String::Concat(js_msg, FIXED_ONE_BYTE_STRING(isolate, " '")); js_msg = String::Concat(js_msg, js_path); js_msg = String::Concat(js_msg, FIXED_ONE_BYTE_STRING(isolate, "'")); } if (dest != nullptr) { js_dest = StringFromPath(isolate, dest); js_msg = String::Concat(js_msg, FIXED_ONE_BYTE_STRING(isolate, " -> '")); js_msg = String::Concat(js_msg, js_dest); js_msg = String::Concat(js_msg, FIXED_ONE_BYTE_STRING(isolate, "'")); } Local e = Exception::Error(js_msg)->ToObject(isolate); // TODO(piscisaureus) errno should probably go; the user has no way of // knowing which uv errno value maps to which error. e->Set(env->errno_string(), Integer::New(isolate, errorno)); e->Set(env->code_string(), js_code); e->Set(env->syscall_string(), js_syscall); if (!js_path.IsEmpty()) e->Set(env->path_string(), js_path); if (!js_dest.IsEmpty()) e->Set(env->dest_string(), js_dest); return e; } // Look up environment variable unless running as setuid root. inline const char* secure_getenv(const char* key) { #ifndef _WIN32 if (getuid() != geteuid() || getgid() != getegid()) return nullptr; #endif return getenv(key); } #ifdef _WIN32 // Does about the same as strerror(), // but supports all windows error messages static const char *winapi_strerror(const int errorno, bool* must_free) { char *errmsg = nullptr; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorno, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, nullptr); if (errmsg) { *must_free = true; // Remove trailing newlines for (int i = strlen(errmsg) - 1; i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) { errmsg[i] = '\0'; } return errmsg; } else { // FormatMessage failed *must_free = false; return "Unknown error"; } } Local WinapiErrnoException(Isolate* isolate, int errorno, const char* syscall, const char* msg, const char* path) { Environment* env = Environment::GetCurrent(isolate); Local e; bool must_free = false; if (!msg || !msg[0]) { msg = winapi_strerror(errorno, &must_free); } Local message = OneByteString(env->isolate(), msg); if (path) { Local cons1 = String::Concat(message, FIXED_ONE_BYTE_STRING(isolate, " '")); Local cons2 = String::Concat(cons1, String::NewFromUtf8(isolate, path)); Local cons3 = String::Concat(cons2, FIXED_ONE_BYTE_STRING(isolate, "'")); e = Exception::Error(cons3); } else { e = Exception::Error(message); } Local obj = e->ToObject(env->isolate()); obj->Set(env->errno_string(), Integer::New(isolate, errorno)); if (path != nullptr) { obj->Set(env->path_string(), String::NewFromUtf8(isolate, path)); } if (syscall != nullptr) { obj->Set(env->syscall_string(), OneByteString(isolate, syscall)); } if (must_free) LocalFree((HLOCAL)msg); return e; } #endif void* ArrayBufferAllocator::Allocate(size_t size) { if (env_ == nullptr || !env_->array_buffer_allocator_info()->no_zero_fill() || zero_fill_all_buffers) return calloc(size, 1); env_->array_buffer_allocator_info()->reset_fill_flag(); return malloc(size); } static bool DomainHasErrorHandler(const Environment* env, const Local& domain) { HandleScope scope(env->isolate()); Local domain_event_listeners_v = domain->Get(env->events_string()); if (!domain_event_listeners_v->IsObject()) return false; Local domain_event_listeners_o = domain_event_listeners_v.As(); Local domain_error_listeners_v = domain_event_listeners_o->Get(env->error_string()); if (domain_error_listeners_v->IsFunction() || (domain_error_listeners_v->IsArray() && domain_error_listeners_v.As()->Length() > 0)) return true; return false; } static bool DomainsStackHasErrorHandler(const Environment* env) { HandleScope scope(env->isolate()); if (!env->using_domains()) return false; Local domains_stack_array = env->domains_stack_array().As(); if (domains_stack_array->Length() == 0) return false; uint32_t domains_stack_length = domains_stack_array->Length(); for (uint32_t i = domains_stack_length; i > 0; --i) { Local domain_v = domains_stack_array->Get(i - 1); if (!domain_v->IsObject()) return false; Local domain = domain_v.As(); if (DomainHasErrorHandler(env, domain)) return true; } return false; } static bool ShouldAbortOnUncaughtException(Isolate* isolate) { HandleScope scope(isolate); Environment* env = Environment::GetCurrent(isolate); Local process_object = env->process_object(); Local emitting_top_level_domain_error_key = env->emitting_top_level_domain_error_string(); bool isEmittingTopLevelDomainError = process_object->Get(emitting_top_level_domain_error_key)->BooleanValue(); return isEmittingTopLevelDomainError || !DomainsStackHasErrorHandler(env); } void SetupDomainUse(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); if (env->using_domains()) return; env->set_using_domains(true); HandleScope scope(env->isolate()); Local process_object = env->process_object(); Local tick_callback_function_key = env->tick_domain_cb_string(); Local tick_callback_function = process_object->Get(tick_callback_function_key).As(); if (!tick_callback_function->IsFunction()) { fprintf(stderr, "process._tickDomainCallback assigned to non-function\n"); ABORT(); } process_object->Set(env->tick_callback_string(), tick_callback_function); env->set_tick_callback_function(tick_callback_function); CHECK(args[0]->IsArray()); env->set_domain_array(args[0].As()); CHECK(args[1]->IsArray()); env->set_domains_stack_array(args[1].As()); // Do a little housekeeping. env->process_object()->Delete( env->context(), FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupDomainUse")).FromJust(); uint32_t* const fields = env->domain_flag()->fields(); uint32_t const fields_count = env->domain_flag()->fields_count(); Local array_buffer = ArrayBuffer::New(env->isolate(), fields, sizeof(*fields) * fields_count); args.GetReturnValue().Set(Uint32Array::New(array_buffer, 0, fields_count)); } void RunMicrotasks(const FunctionCallbackInfo& args) { args.GetIsolate()->RunMicrotasks(); } void SetupProcessObject(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK(args[0]->IsFunction()); env->set_push_values_to_array_function(args[0].As()); env->process_object()->Delete( env->context(), FIXED_ONE_BYTE_STRING(env->isolate(), "_setupProcessObject")).FromJust(); } void SetupNextTick(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK(args[0]->IsFunction()); CHECK(args[1]->IsObject()); env->set_tick_callback_function(args[0].As()); env->SetMethod(args[1].As(), "runMicrotasks", RunMicrotasks); // Do a little housekeeping. env->process_object()->Delete( env->context(), FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupNextTick")).FromJust(); // Values use to cross communicate with processNextTick. uint32_t* const fields = env->tick_info()->fields(); uint32_t const fields_count = env->tick_info()->fields_count(); Local array_buffer = ArrayBuffer::New(env->isolate(), fields, sizeof(*fields) * fields_count); args.GetReturnValue().Set(Uint32Array::New(array_buffer, 0, fields_count)); } void PromiseRejectCallback(PromiseRejectMessage message) { Local promise = message.GetPromise(); Isolate* isolate = promise->GetIsolate(); Local value = message.GetValue(); Local event = Integer::New(isolate, message.GetEvent()); Environment* env = Environment::GetCurrent(isolate); Local callback = env->promise_reject_function(); if (value.IsEmpty()) value = Undefined(isolate); Local args[] = { event, promise, value }; Local process = env->process_object(); callback->Call(process, arraysize(args), args); } void SetupPromises(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); Isolate* isolate = env->isolate(); CHECK(args[0]->IsFunction()); isolate->SetPromiseRejectCallback(PromiseRejectCallback); env->set_promise_reject_function(args[0].As()); env->process_object()->Delete( env->context(), FIXED_ONE_BYTE_STRING(args.GetIsolate(), "_setupPromises")).FromJust(); } Local MakeCallback(Environment* env, Local recv, const Local callback, int argc, Local argv[]) { // If you hit this assertion, you forgot to enter the v8::Context first. CHECK_EQ(env->context(), env->isolate()->GetCurrentContext()); Local pre_fn = env->async_hooks_pre_function(); Local post_fn = env->async_hooks_post_function(); Local object, domain; bool ran_init_callback = false; bool has_domain = false; Environment::AsyncCallbackScope callback_scope(env); // TODO(trevnorris): Adding "_asyncQueue" to the "this" in the init callback // is a horrible way to detect usage. Rethink how detection should happen. if (recv->IsObject()) { object = recv.As(); Local async_queue_v = object->Get(env->async_queue_string()); if (async_queue_v->IsObject()) ran_init_callback = true; } if (env->using_domains()) { CHECK(recv->IsObject()); Local domain_v = object->Get(env->domain_string()); has_domain = domain_v->IsObject(); if (has_domain) { domain = domain_v.As(); if (domain->Get(env->disposed_string())->IsTrue()) return Undefined(env->isolate()); } } if (has_domain) { Local enter_v = domain->Get(env->enter_string()); if (enter_v->IsFunction()) { if (enter_v.As()->Call(domain, 0, nullptr).IsEmpty()) { FatalError("node::MakeCallback", "domain enter callback threw, please report this"); } } } if (ran_init_callback && !pre_fn.IsEmpty()) { TryCatch try_catch(env->isolate()); MaybeLocal ar = pre_fn->Call(env->context(), object, 0, nullptr); if (ar.IsEmpty()) { ClearFatalExceptionHandlers(env); FatalException(env->isolate(), try_catch); return Local(); } } Local ret = callback->Call(recv, argc, argv); if (ran_init_callback && !post_fn.IsEmpty()) { Local did_throw = Boolean::New(env->isolate(), ret.IsEmpty()); // Currently there's no way to retrieve an uid from node::MakeCallback(). // This needs to be fixed. Local vals[] = { Undefined(env->isolate()).As(), did_throw }; TryCatch try_catch(env->isolate()); MaybeLocal ar = post_fn->Call(env->context(), object, arraysize(vals), vals); if (ar.IsEmpty()) { ClearFatalExceptionHandlers(env); FatalException(env->isolate(), try_catch); return Local(); } } if (ret.IsEmpty()) { // NOTE: For backwards compatibility with public API we return Undefined() // if the top level call threw. return callback_scope.in_makecallback() ? ret : Undefined(env->isolate()).As(); } if (has_domain) { Local exit_v = domain->Get(env->exit_string()); if (exit_v->IsFunction()) { if (exit_v.As()->Call(domain, 0, nullptr).IsEmpty()) { FatalError("node::MakeCallback", "domain exit callback threw, please report this"); } } } if (callback_scope.in_makecallback()) { return ret; } Environment::TickInfo* tick_info = env->tick_info(); if (tick_info->length() == 0) { env->isolate()->RunMicrotasks(); } Local process = env->process_object(); if (tick_info->length() == 0) { tick_info->set_index(0); } if (env->tick_callback_function()->Call(process, 0, nullptr).IsEmpty()) { return Undefined(env->isolate()); } return ret; } // Internal only. Local MakeCallback(Environment* env, Local recv, uint32_t index, int argc, Local argv[]) { Local cb_v = recv->Get(index); CHECK(cb_v->IsFunction()); return MakeCallback(env, recv.As(), cb_v.As(), argc, argv); } Local MakeCallback(Environment* env, Local recv, Local symbol, int argc, Local argv[]) { Local cb_v = recv->Get(symbol); CHECK(cb_v->IsFunction()); return MakeCallback(env, recv.As(), cb_v.As(), argc, argv); } Local MakeCallback(Environment* env, Local recv, const char* method, int argc, Local argv[]) { Local method_string = OneByteString(env->isolate(), method); return MakeCallback(env, recv, method_string, argc, argv); } Local MakeCallback(Isolate* isolate, Local recv, const char* method, int argc, Local argv[]) { EscapableHandleScope handle_scope(isolate); Local context = recv->CreationContext(); Environment* env = Environment::GetCurrent(context); Context::Scope context_scope(context); return handle_scope.Escape( Local::New(isolate, MakeCallback(env, recv, method, argc, argv))); } Local MakeCallback(Isolate* isolate, Local recv, Local symbol, int argc, Local argv[]) { EscapableHandleScope handle_scope(isolate); Local context = recv->CreationContext(); Environment* env = Environment::GetCurrent(context); Context::Scope context_scope(context); return handle_scope.Escape( Local::New(isolate, MakeCallback(env, recv, symbol, argc, argv))); } Local MakeCallback(Isolate* isolate, Local recv, Local callback, int argc, Local argv[]) { EscapableHandleScope handle_scope(isolate); Local context = recv->CreationContext(); Environment* env = Environment::GetCurrent(context); Context::Scope context_scope(context); return handle_scope.Escape(Local::New( isolate, MakeCallback(env, recv.As(), callback, argc, argv))); } enum encoding ParseEncoding(const char* encoding, enum encoding default_encoding) { switch (encoding[0]) { case 'u': // utf8, utf16le if (encoding[1] == 't' && encoding[2] == 'f') { // Skip `-` encoding += encoding[3] == '-' ? 4 : 3; if (encoding[0] == '8' && encoding[1] == '\0') return UTF8; if (strncmp(encoding, "16le", 4) == 0) return UCS2; // ucs2 } else if (encoding[1] == 'c' && encoding[2] == 's') { encoding += encoding[3] == '-' ? 4 : 3; if (encoding[0] == '2' && encoding[1] == '\0') return UCS2; } break; case 'b': // binary if (encoding[1] == 'i') { if (strncmp(encoding + 2, "nary", 4) == 0) return BINARY; // buffer } else if (encoding[1] == 'u') { if (strncmp(encoding + 2, "ffer", 4) == 0) return BUFFER; } break; case '\0': return default_encoding; default: break; } if (StringEqualNoCase(encoding, "utf8")) { return UTF8; } else if (StringEqualNoCase(encoding, "utf-8")) { return UTF8; } else if (StringEqualNoCase(encoding, "ascii")) { return ASCII; } else if (StringEqualNoCase(encoding, "base64")) { return BASE64; } else if (StringEqualNoCase(encoding, "ucs2")) { return UCS2; } else if (StringEqualNoCase(encoding, "ucs-2")) { return UCS2; } else if (StringEqualNoCase(encoding, "utf16le")) { return UCS2; } else if (StringEqualNoCase(encoding, "utf-16le")) { return UCS2; } else if (StringEqualNoCase(encoding, "binary")) { return BINARY; } else if (StringEqualNoCase(encoding, "buffer")) { return BUFFER; } else if (StringEqualNoCase(encoding, "hex")) { return HEX; } else { return default_encoding; } } enum encoding ParseEncoding(Isolate* isolate, Local encoding_v, enum encoding default_encoding) { if (!encoding_v->IsString()) return default_encoding; node::Utf8Value encoding(isolate, encoding_v); return ParseEncoding(*encoding, default_encoding); } Local Encode(Isolate* isolate, const char* buf, size_t len, enum encoding encoding) { CHECK_NE(encoding, UCS2); return StringBytes::Encode(isolate, buf, len, encoding); } Local Encode(Isolate* isolate, const uint16_t* buf, size_t len) { return StringBytes::Encode(isolate, buf, len); } // Returns -1 if the handle was not valid for decoding ssize_t DecodeBytes(Isolate* isolate, Local val, enum encoding encoding) { HandleScope scope(isolate); if (val->IsArray()) { fprintf(stderr, "'raw' encoding (array of integers) has been removed. " "Use 'binary'.\n"); UNREACHABLE(); return -1; } return StringBytes::Size(isolate, val, encoding); } // Returns number of bytes written. ssize_t DecodeWrite(Isolate* isolate, char* buf, size_t buflen, Local val, enum encoding encoding) { return StringBytes::Write(isolate, buf, buflen, val, encoding, nullptr); } bool IsExceptionDecorated(Environment* env, Local er) { if (!er.IsEmpty() && er->IsObject()) { Local err_obj = er.As(); auto maybe_value = err_obj->GetPrivate(env->context(), env->decorated_private_symbol()); Local decorated; return maybe_value.ToLocal(&decorated) && decorated->IsTrue(); } return false; } void AppendExceptionLine(Environment* env, Local er, Local message) { if (message.IsEmpty()) return; HandleScope scope(env->isolate()); Local err_obj; if (!er.IsEmpty() && er->IsObject()) { err_obj = er.As(); auto context = env->context(); auto processed_private_symbol = env->processed_private_symbol(); // Do it only once per message if (err_obj->HasPrivate(context, processed_private_symbol).FromJust()) return; err_obj->SetPrivate( context, processed_private_symbol, True(env->isolate())); } // Print (filename):(line number): (message). node::Utf8Value filename(env->isolate(), message->GetScriptResourceName()); const char* filename_string = *filename; int linenum = message->GetLineNumber(); // Print line of source code. node::Utf8Value sourceline(env->isolate(), message->GetSourceLine()); const char* sourceline_string = *sourceline; // Because of how node modules work, all scripts are wrapped with a // "function (module, exports, __filename, ...) {" // to provide script local variables. // // When reporting errors on the first line of a script, this wrapper // function is leaked to the user. There used to be a hack here to // truncate off the first 62 characters, but it caused numerous other // problems when vm.runIn*Context() methods were used for non-module // code. // // If we ever decide to re-instate such a hack, the following steps // must be taken: // // 1. Pass a flag around to say "this code was wrapped" // 2. Update the stack frame output so that it is also correct. // // It would probably be simpler to add a line rather than add some // number of characters to the first line, since V8 truncates the // sourceline to 78 characters, and we end up not providing very much // useful debugging info to the user if we remove 62 characters. int start = message->GetStartColumn(env->context()).FromJust(); int end = message->GetEndColumn(env->context()).FromJust(); char arrow[1024]; int max_off = sizeof(arrow) - 2; int off = snprintf(arrow, sizeof(arrow), "%s:%i\n%s\n", filename_string, linenum, sourceline_string); CHECK_GE(off, 0); if (off > max_off) { off = max_off; } // Print wavy underline (GetUnderline is deprecated). for (int i = 0; i < start; i++) { if (sourceline_string[i] == '\0' || off >= max_off) { break; } CHECK_LT(off, max_off); arrow[off++] = (sourceline_string[i] == '\t') ? '\t' : ' '; } for (int i = start; i < end; i++) { if (sourceline_string[i] == '\0' || off >= max_off) { break; } CHECK_LT(off, max_off); arrow[off++] = '^'; } CHECK_LE(off, max_off); arrow[off] = '\n'; arrow[off + 1] = '\0'; Local arrow_str = String::NewFromUtf8(env->isolate(), arrow); if (!arrow_str.IsEmpty() && !err_obj.IsEmpty() && err_obj->IsNativeError()) { err_obj->SetPrivate( env->context(), env->arrow_message_private_symbol(), arrow_str); return; } // Allocation failed, just print it out. if (env->printed_error()) return; env->set_printed_error(true); uv_tty_reset_mode(); PrintErrorString("\n%s", arrow); } static void ReportException(Environment* env, Local er, Local message) { HandleScope scope(env->isolate()); AppendExceptionLine(env, er, message); Local trace_value; Local arrow; const bool decorated = IsExceptionDecorated(env, er); if (er->IsUndefined() || er->IsNull()) { trace_value = Undefined(env->isolate()); } else { Local err_obj = er->ToObject(env->isolate()); trace_value = err_obj->Get(env->stack_string()); arrow = err_obj->GetPrivate( env->context(), env->arrow_message_private_symbol()).ToLocalChecked(); } node::Utf8Value trace(env->isolate(), trace_value); // range errors have a trace member set to undefined if (trace.length() > 0 && !trace_value->IsUndefined()) { if (arrow.IsEmpty() || !arrow->IsString() || decorated) { PrintErrorString("%s\n", *trace); } else { node::Utf8Value arrow_string(env->isolate(), arrow); PrintErrorString("%s\n%s\n", *arrow_string, *trace); } } else { // this really only happens for RangeErrors, since they're the only // kind that won't have all this info in the trace, or when non-Error // objects are thrown manually. Local message; Local name; if (er->IsObject()) { Local err_obj = er.As(); message = err_obj->Get(env->message_string()); name = err_obj->Get(FIXED_ONE_BYTE_STRING(env->isolate(), "name")); } if (message.IsEmpty() || message->IsUndefined() || name.IsEmpty() || name->IsUndefined()) { // Not an error object. Just print as-is. String::Utf8Value message(er); PrintErrorString("%s\n", *message ? *message : ""); } else { node::Utf8Value name_string(env->isolate(), name); node::Utf8Value message_string(env->isolate(), message); if (arrow.IsEmpty() || !arrow->IsString() || decorated) { PrintErrorString("%s: %s\n", *name_string, *message_string); } else { node::Utf8Value arrow_string(env->isolate(), arrow); PrintErrorString("%s\n%s: %s\n", *arrow_string, *name_string, *message_string); } } } fflush(stderr); } static void ReportException(Environment* env, const TryCatch& try_catch) { ReportException(env, try_catch.Exception(), try_catch.Message()); } // Executes a str within the current v8 context. static Local ExecuteString(Environment* env, Local source, Local filename) { EscapableHandleScope scope(env->isolate()); TryCatch try_catch(env->isolate()); // try_catch must be nonverbose to disable FatalException() handler, // we will handle exceptions ourself. try_catch.SetVerbose(false); ScriptOrigin origin(filename); MaybeLocal<:script> script = v8::Script::Compile(env->context(), source, &origin); if (script.IsEmpty()) { ReportException(env, try_catch); exit(3); } Local result = script.ToLocalChecked()->Run(); if (result.IsEmpty()) { ReportException(env, try_catch); exit(4); } return scope.Escape(result); } static void GetActiveRequests(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); Local ary = Array::New(args.GetIsolate()); Local ctx = env->context(); Local fn = env->push_values_to_array_function(); Local argv[NODE_PUSH_VAL_TO_ARRAY_MAX]; size_t idx = 0; for (auto w : *env->req_wrap_queue()) { if (w->persistent().IsEmpty()) continue; argv[idx] = w->object(); if (++idx >= arraysize(argv)) { fn->Call(ctx, ary, idx, argv).ToLocalChecked(); idx = 0; } } if (idx > 0) { fn->Call(ctx, ary, idx, argv).ToLocalChecked(); } args.GetReturnValue().Set(ary); } // Non-static, friend of HandleWrap. Could have been a HandleWrap method but // implemented here for consistency with GetActiveRequests(). void GetActiveHandles(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); Local ary = Array::New(env->isolate()); Local ctx = env->context(); Local fn = env->push_values_to_array_function(); Local argv[NODE_PUSH_VAL_TO_ARRAY_MAX]; size_t idx = 0; Local owner_sym = env->owner_string(); for (auto w : *env->handle_wrap_queue()) { if (w->persistent().IsEmpty() || !HandleWrap::HasRef(w)) continue; Local object = w->object(); Local owner = object->Get(owner_sym); if (owner->IsUndefined()) owner = object; argv[idx] = owner; if (++idx >= arraysize(argv)) { fn->Call(ctx, ary, idx, argv).ToLocalChecked(); idx = 0; } } if (idx > 0) { fn->Call(ctx, ary, idx, argv).ToLocalChecked(); } args.GetReturnValue().Set(ary); } static void Abort(const FunctionCallbackInfo& args) { ABORT(); } static void Chdir(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); if (args.Length() != 1 || !args[0]->IsString()) { return env->ThrowTypeError("Bad argument."); } node::Utf8Value path(args.GetIsolate(), args[0]); int err = uv_chdir(*path); if (err) { return env->ThrowUVException(err, "uv_chdir"); } } static void Cwd(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); #ifdef _WIN32 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */ char buf[MAX_PATH * 4]; #else char buf[PATH_MAX]; #endif size_t cwd_len = sizeof(buf); int err = uv_cwd(buf, &cwd_len); if (err) { return env->ThrowUVException(err, "uv_cwd"); } Local cwd = String::NewFromUtf8(env->isolate(), buf, String::kNormalString, cwd_len); args.GetReturnValue().Set(cwd); } static void Umask(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); uint32_t old; if (args.Length() < 1 || args[0]->IsUndefined()) { old = umask(0); umask(static_cast(old)); } else if (!args[0]->IsInt32() && !args[0]->IsString()) { return env->ThrowTypeError("argument must be an integer or octal string."); } else { int oct; if (args[0]->IsInt32()) { oct = args[0]->Uint32Value(); } else { oct = 0; node::Utf8Value str(env->isolate(), args[0]); // Parse the octal string. for (size_t i = 0; i < str.length(); i++) { char c = (*str)[i]; if (c > '7' || c < '0') { return env->ThrowTypeError("invalid octal string"); } oct *= 8; oct += c - '0'; } } old = umask(static_cast(oct)); } args.GetReturnValue().Set(old); } #if defined(__POSIX__) && !defined(__ANDROID__) static const uid_t uid_not_found = static_cast(-1); static const gid_t gid_not_found = static_cast(-1); static uid_t uid_by_name(const char* name) { struct passwd pwd; struct passwd* pp; char buf[8192]; errno = 0; pp = nullptr; if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != nullptr) { return pp->pw_uid; } return uid_not_found; } static char* name_by_uid(uid_t uid) { struct passwd pwd; struct passwd* pp; char buf[8192]; int rc; errno = 0; pp = nullptr; if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != nullptr) { return strdup(pp->pw_name); } if (rc == 0) { errno = ENOENT; } return nullptr; } static gid_t gid_by_name(const char* name) { struct group pwd; struct group* pp; char buf[8192]; errno = 0; pp = nullptr; if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != nullptr) { return pp->gr_gid; } return gid_not_found; } #if 0 // For future use. static const char* name_by_gid(gid_t gid) { struct group pwd; struct group* pp; char buf[8192]; int rc; errno = 0; pp = nullptr; if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != nullptr) { return strdup(pp->gr_name); } if (rc == 0) { errno = ENOENT; } return nullptr; } #endif static uid_t uid_by_name(Isolate* isolate, Local value) { if (value->IsUint32()) { return static_cast(value->Uint32Value()); } else { node::Utf8Value name(isolate, value); return uid_by_name(*name); } } static gid_t gid_by_name(Isolate* isolate, Local value) { if (value->IsUint32()) { return static_cast(value->Uint32Value()); } else { node::Utf8Value name(isolate, value); return gid_by_name(*name); } } static void GetUid(const FunctionCallbackInfo& args) { // uid_t is an uint32_t on all supported platforms. args.GetReturnValue().Set(static_cast(getuid())); } static void GetGid(const FunctionCallbackInfo& args) { // gid_t is an uint32_t on all supported platforms. args.GetReturnValue().Set(static_cast(getgid())); } static void GetEUid(const FunctionCallbackInfo& args) { // uid_t is an uint32_t on all supported platforms. args.GetReturnValue().Set(static_cast(geteuid())); } static void GetEGid(const FunctionCallbackInfo& args) { // gid_t is an uint32_t on all supported platforms. args.GetReturnValue().Set(static_cast(getegid())); } static void SetGid(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); if (!args[0]->IsUint32() && !args[0]->IsString()) { return env->ThrowTypeError("setgid argument must be a number or a string"); } gid_t gid = gid_by_name(env->isolate(), args[0]); if (gid == gid_not_found) { return env->ThrowError("setgid group id does not exist"); } if (setgid(gid)) { return env->ThrowErrnoException(errno, "setgid"); } } static void SetEGid(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); if (!args[0]->IsUint32() && !args[0]->IsString()) { return env->ThrowTypeError("setegid argument must be a number or string"); } gid_t gid = gid_by_name(env->isolate(), args[0]); if (gid == gid_not_found) { return env->ThrowError("setegid group id does not exist"); } if (setegid(gid)) { return env->ThrowErrnoException(errno, "setegid"); } } static void SetUid(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); if (!args[0]->IsUint32() && !args[0]->IsString()) { return env->ThrowTypeError("setuid argument must be a number or a string"); } uid_t uid = uid_by_name(env->isolate(), args[0]); if (uid == uid_not_found) { return env->ThrowError("setuid user id does not exist"); } if (setuid(uid)) { return env->ThrowErrnoException(errno, "setuid"); } } static void SetEUid(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); if (!args[0]->IsUint32() && !args[0]->IsString()) { return env->ThrowTypeError("seteuid argument must be a number or string"); } uid_t uid = uid_by_name(env->isolate(), args[0]); if (uid == uid_not_found) { return env->ThrowError("seteuid user id does not exist"); } if (seteuid(uid)) { return env->ThrowErrnoException(errno, "seteuid"); } } static void GetGroups(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); int ngroups = getgroups(0, nullptr); if (ngroups == -1) { return env->ThrowErrnoException(errno, "getgroups"); } gid_t* groups = new gid_t[ngroups]; ngroups = getgroups(ngroups, groups); if (ngroups == -1) { delete[] groups; return env->ThrowErrnoException(errno, "getgroups"); } Local groups_list = Array::New(env->isolate(), ngroups); bool seen_egid = false; gid_t egid = getegid(); for (int i = 0; i < ngroups; i++) { groups_list->Set(i, Integer::New(env->isolate(), groups[i])); if (groups[i] == egid) seen_egid = true; } delete[] groups; if (seen_egid == false) { groups_list->Set(ngroups, Integer::New(env->isolate(), egid)); } args.GetReturnValue().Set(groups_list); } static void SetGroups(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); if (!args[0]->IsArray()) { return env->ThrowTypeError("argument 1 must be an array"); } Local groups_list = args[0].As(); size_t size = groups_list->Length(); gid_t* groups = new gid_t[size]; for (size_t i = 0; i < size; i++) { gid_t gid = gid_by_name(env->isolate(), groups_list->Get(i)); if (gid == gid_not_found) { delete[] groups; return env->ThrowError("group name not found"); } groups[i] = gid; } int rc = setgroups(size, groups); delete[] groups; if (rc == -1) { return env->ThrowErrnoException(errno, "setgroups"); } } static void InitGroups(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); if (!args[0]->IsUint32() && !args[0]->IsString()) { return env->ThrowTypeError("argument 1 must be a number or a string"); } if (!args[1]->IsUint32() && !args[1]->IsString()) { return env->ThrowTypeError("argument 2 must be a number or a string"); } node::Utf8Value arg0(env->isolate(), args[0]); gid_t extra_group; bool must_free; char* user; if (args[0]->IsUint32()) { user = name_by_uid(args[0]->Uint32Value()); must_free = true; } else { user = *arg0; must_free = false; } if (user == nullptr) { return env->ThrowError("initgroups user not found"); } extra_group = gid_by_name(env->isolate(), args[1]); if (extra_group == gid_not_found) { if (must_free) free(user); return env->ThrowError("initgroups extra group not found"); } int rc = initgroups(user, extra_group); if (must_free) { free(user); } if (rc) { return env->ThrowErrnoException(errno, "initgroups"); } } #endif // __POSIX__ && !defined(__ANDROID__) void Exit(const FunctionCallbackInfo& args) { exit(args[0]->Int32Value()); } static void Uptime(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); double uptime; uv_update_time(env->event_loop()); uptime = uv_now(env->event_loop()) - prog_start_time; args.GetReturnValue().Set(Number::New(env->isolate(), uptime / 1000)); } void MemoryUsage(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); size_t rss; int err = uv_resident_set_memory(&rss); if (err) { return env->ThrowUVException(err, "uv_resident_set_memory"); } // V8 memory usage HeapStatistics v8_heap_stats; env->isolate()->GetHeapStatistics(&v8_heap_stats); Local heap_total = Number::New(env->isolate(), v8_heap_stats.total_heap_size()); Local heap_used = Number::New(env->isolate(), v8_heap_stats.used_heap_size()); Local info = Object::New(env->isolate()); info->Set(env->rss_string(), Number::New(env->isolate(), rss)); info->Set(env->heap_total_string(), heap_total); info->Set(env->heap_used_string(), heap_used); args.GetReturnValue().Set(info); } void Kill(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); if (args.Length() != 2) { return env->ThrowError("Bad argument."); } int pid = args[0]->Int32Value(); int sig = args[1]->Int32Value(); int err = uv_kill(pid, sig); args.GetReturnValue().Set(err); } // used in Hrtime() below #define NANOS_PER_SEC 1000000000 // Hrtime exposes libuv's uv_hrtime() high-resolution timer. // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds, // so this function instead returns an Array with 2 entries representing seconds // and nanoseconds, to avoid any integer overflow possibility. // Pass in an Array from a previous hrtime() call to instead get a time diff. void Hrtime(const FunctionCallbackInfo& args) { uint64_t t = uv_hrtime(); Local ab = args[0].As()->Buffer(); uint32_t* fields = static_cast(ab->GetContents().Data()); // These three indices will contain the values for the hrtime tuple. The // seconds value is broken into the upper/lower 32 bits and stored in two // uint32 fields to be converted back in JS. fields[0] = (t / NANOS_PER_SEC) >> 32; fields[1] = (t / NANOS_PER_SEC) & 0xffffffff; fields[2] = t % NANOS_PER_SEC; } // Microseconds in a second, as a float, used in CPUUsage() below #define MICROS_PER_SEC 1e6 // CPUUsage use libuv's uv_getrusage() this-process resource usage accessor, // to access ru_utime (user CPU time used) and ru_stime (system CPU time used), // which are uv_timeval_t structs (long tv_sec, long tv_usec). // Returns those values as Float64 microseconds in the elements of the array // passed to the function. void CPUUsage(const FunctionCallbackInfo& args) { uv_rusage_t rusage; // Call libuv to get the values we'll return. int err = uv_getrusage(&rusage); if (err) { // On error, return the strerror version of the error code. Local errmsg = OneByteString(args.GetIsolate(), uv_strerror(err)); args.GetReturnValue().Set(errmsg); return; } // Get the double array pointer from the Float64Array argument. CHECK(args[0]->IsFloat64Array()); Local array = args[0].As(); CHECK_EQ(array->Length(), 2); Local ab = array->Buffer(); double* fields = static_cast(ab->GetContents().Data()); // Set the Float64Array elements to be user / system values in microseconds. fields[0] = MICROS_PER_SEC * rusage.ru_utime.tv_sec + rusage.ru_utime.tv_usec; fields[1] = MICROS_PER_SEC * rusage.ru_stime.tv_sec + rusage.ru_stime.tv_usec; } extern "C" void node_module_register(void* m) { struct node_module* mp = reinterpret_cast(m); if (mp->nm_flags & NM_F_BUILTIN) { mp->nm_link = modlist_builtin; modlist_builtin = mp; } else if (!node_is_initialized) { // "Linked" modules are included as part of the node project. // Like builtins they are registered *before* node::Init runs. mp->nm_flags = NM_F_LINKED; mp->nm_link = modlist_linked; modlist_linked = mp; } else { modpending = mp; } } struct node_module* get_builtin_module(const char* name) { struct node_module* mp; for (mp = modlist_builtin; mp != nullptr; mp = mp->nm_link) { if (strcmp(mp->nm_modname, name) == 0) break; } CHECK(mp == nullptr || (mp->nm_flags & NM_F_BUILTIN) != 0); return (mp); } struct node_module* get_linked_module(const char* name) { struct node_module* mp; for (mp = modlist_linked; mp != nullptr; mp = mp->nm_link) { if (strcmp(mp->nm_modname, name) == 0) break; } CHECK(mp == nullptr || (mp->nm_flags & NM_F_LINKED) != 0); return mp; } typedef void (UV_DYNAMIC* extInit)(Local exports); // DLOpen is process.dlopen(module, filename). // Used to load 'module.node' dynamically shared objects. // // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict // when two contexts try to load the same shared object. Maybe have a shadow // cache that's a plain C list or hash table that's shared across contexts? void DLOpen(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); uv_lib_t lib; CHECK_EQ(modpending, nullptr); if (args.Length() != 2) { env->ThrowError("process.dlopen takes exactly 2 arguments."); return; } Local module = args[0]->ToObject(env->isolate()); // Cast node::Utf8Value filename(env->isolate(), args[1]); // Cast const bool is_dlopen_error = uv_dlopen(*filename, &lib); // Objects containing v14 or later modules will have registered themselves // on the pending list. Activate all of them now. At present, only one // module per object is supported. node_module* const mp = modpending; modpending = nullptr; if (is_dlopen_error) { Local errmsg = OneByteString(env->isolate(), uv_dlerror(&lib)); uv_dlclose(&lib); #ifdef _WIN32 // Windows needs to add the filename into the error message errmsg = String::Concat(errmsg, args[1]->ToString(env->isolate())); #endif // _WIN32 env->isolate()->ThrowException(Exception::Error(errmsg)); return; } if (mp == nullptr) { uv_dlclose(&lib); env->ThrowError("Module did not self-register."); return; } if (mp->nm_version != NODE_MODULE_VERSION) { char errmsg[1024]; snprintf(errmsg, sizeof(errmsg), "Module version mismatch. Expected %d, got %d.", NODE_MODULE_VERSION, mp->nm_version); // NOTE: `mp` is allocated inside of the shared library's memory, calling // `uv_dlclose` will deallocate it uv_dlclose(&lib); env->ThrowError(errmsg); return; } if (mp->nm_flags & NM_F_BUILTIN) { uv_dlclose(&lib); env->ThrowError("Built-in module self-registered."); return; } mp->nm_dso_handle = lib.handle; mp->nm_link = modlist_addon; modlist_addon = mp; Local exports_string = env->exports_string(); Local exports = module->Get(exports_string)->ToObject(env->isolate()); if (mp->nm_context_register_func != nullptr) { mp->nm_context_register_func(exports, module, env->context(), mp->nm_priv); } else if (mp->nm_register_func != nullptr) { mp->nm_register_func(exports, module, mp->nm_priv); } else { uv_dlclose(&lib); env->ThrowError("Module has no declared entry point."); return; } // Tell coverity that 'handle' should not be freed when we return. // coverity[leaked_storage] } static void OnFatalError(const char* location, const char* message) { if (location) { PrintErrorString("FATAL ERROR: %s %s\n", location, message); } else { PrintErrorString("FATAL ERROR: %s\n", message); } fflush(stderr); ABORT(); } NO_RETURN void FatalError(const char* location, const char* message) { OnFatalError(location, message); // to suppress compiler warning ABORT(); } void FatalException(Isolate* isolate, Local error, Local message) { HandleScope scope(isolate); Environment* env = Environment::GetCurrent(isolate); Local process_object = env->process_object(); Local fatal_exception_string = env->fatal_exception_string(); Local fatal_exception_function = process_object->Get(fatal_exception_string).As(); if (!fatal_exception_function->IsFunction()) { // failed before the process._fatalException function was added! // this is probably pretty bad. Nothing to do but report and exit. ReportException(env, error, message); exit(6); } TryCatch fatal_try_catch(isolate); // Do not call FatalException when _fatalException handler throws fatal_try_catch.SetVerbose(false); // this will return true if the JS layer handled it, false otherwise Local caught = fatal_exception_function->Call(process_object, 1, &error); if (fatal_try_catch.HasCaught()) { // the fatal exception function threw, so we must exit ReportException(env, fatal_try_catch); exit(7); } if (false == caught->BooleanValue()) { ReportException(env, error, message); exit(1); } } void FatalException(Isolate* isolate, const TryCatch& try_catch) { HandleScope scope(isolate); // TODO(bajtos) do not call FatalException if try_catch is verbose // (requires V8 API to expose getter for try_catch.is_verbose_) FatalException(isolate, try_catch.Exception(), try_catch.Message()); } void OnMessage(Local message, Local error) { // The current version of V8 sends messages for errors only // (thus `error` is always set). FatalException(Isolate::GetCurrent(), error, message); } void ClearFatalExceptionHandlers(Environment* env) { Local process = env->process_object(); Local events = process->Get(env->context(), env->events_string()).ToLocalChecked(); if (events->IsObject()) { events.As()->Set( env->context(), OneByteString(env->isolate(), "uncaughtException"), Undefined(env->isolate())).FromJust(); } process->Set( env->context(), env->domain_string(), Undefined(env->isolate())).FromJust(); } static void Binding(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); Local module = args[0]->ToString(env->isolate()); node::Utf8Value module_v(env->isolate(), module); Local cache = env->binding_cache_object(); Local exports; if (cache->Has(env->context(), module).FromJust()) { exports = cache->Get(module)->ToObject(env->isolate()); args.GetReturnValue().Set(exports); return; } // Append a string to process.moduleLoadList char buf[1024]; snprintf(buf, sizeof(buf), "Binding %s", *module_v); Local modules = env->module_load_list_array(); uint32_t l = modules->Length(); modules->Set(l, OneByteString(env->isolate(), buf)); node_module* mod = get_builtin_module(*module_v); if (mod != nullptr) { exports = Object::New(env->isolate()); // Internal bindings don't have a "module" object, only exports. CHECK_EQ(mod->nm_register_func, nullptr); CHECK_NE(mod->nm_context_register_func, nullptr); Local