1 // Copyright Joyent, Inc. and other Node contributors.
2 //
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:
10 //
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
13 //
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.
21
22 #include "node.h"
23
24 // ========== local headers ==========
25
26 #include "debug_utils-inl.h"
27 #include "env-inl.h"
28 #include "histogram-inl.h"
29 #include "memory_tracker-inl.h"
30 #include "node_binding.h"
31 #include "node_builtins.h"
32 #include "node_errors.h"
33 #include "node_internals.h"
34 #include "node_main_instance.h"
35 #include "node_metadata.h"
36 #include "node_options-inl.h"
37 #include "node_perf.h"
38 #include "node_process-inl.h"
39 #include "node_realm-inl.h"
40 #include "node_report.h"
41 #include "node_revert.h"
42 #include "node_sea.h"
43 #include "node_snapshot_builder.h"
44 #include "node_v8_platform-inl.h"
45 #include "node_version.h"
46
47 #if HAVE_OPENSSL
48 #include "node_crypto.h"
49 #endif
50
51 #if defined(NODE_HAVE_I18N_SUPPORT)
52 #include "node_i18n.h"
53 #endif
54
55 #if HAVE_INSPECTOR
56 #include "inspector_agent.h"
57 #include "inspector_io.h"
58 #endif
59
60 #if defined HAVE_DTRACE || defined HAVE_ETW
61 #include "node_dtrace.h"
62 #endif
63
64 #if NODE_USE_V8_PLATFORM
65 #include "libplatform/libplatform.h"
66 #endif // NODE_USE_V8_PLATFORM
67 #include "v8-profiler.h"
68
69 #if HAVE_INSPECTOR
70 #include "inspector/worker_inspector.h" // ParentInspectorHandle
71 #endif
72
73 #ifdef NODE_ENABLE_VTUNE_PROFILING
74 #include "../deps/v8/src/third_party/vtune/v8-vtune.h"
75 #endif
76
77 #include "large_pages/node_large_page.h"
78
79 #if defined(__APPLE__) || defined(__linux__) || defined(_WIN32)
80 #define NODE_USE_V8_WASM_TRAP_HANDLER 1
81 #else
82 #define NODE_USE_V8_WASM_TRAP_HANDLER 0
83 #endif
84
85 #if NODE_USE_V8_WASM_TRAP_HANDLER
86 #if defined(_WIN32)
87 #include "v8-wasm-trap-handler-win.h"
88 #else
89 #include <atomic>
90 #include "v8-wasm-trap-handler-posix.h"
91 #endif
92 #endif // NODE_USE_V8_WASM_TRAP_HANDLER
93
94 // ========== global C headers ==========
95
96 #include <fcntl.h> // _O_RDWR
97 #include <sys/types.h>
98
99 #if defined(NODE_HAVE_I18N_SUPPORT)
100 #include <unicode/uvernum.h>
101 #include <unicode/utypes.h>
102 #endif
103
104
105 #if defined(LEAK_SANITIZER)
106 #include <sanitizer/lsan_interface.h>
107 #endif
108
109 #if defined(_MSC_VER)
110 #include <direct.h>
111 #include <io.h>
112 #define STDIN_FILENO 0
113 #else
114 #include <pthread.h>
115 #include <sys/resource.h> // getrlimit, setrlimit
116 #include <termios.h> // tcgetattr, tcsetattr
117 #include <unistd.h> // STDIN_FILENO, STDERR_FILENO
118 #endif
119
120 // ========== global C++ headers ==========
121
122 #include <cerrno>
123 #include <climits> // PATH_MAX
124 #include <csignal>
125 #include <cstdio>
126 #include <cstdlib>
127 #include <cstring>
128
129 #include <string>
130 #include <tuple>
131 #include <vector>
132
133 namespace node {
134
135 using v8::EscapableHandleScope;
136 using v8::Isolate;
137 using v8::Local;
138 using v8::MaybeLocal;
139 using v8::Object;
140 using v8::V8;
141 using v8::Value;
142
143 namespace per_process {
144
145 // node_revert.h
146 // Bit flag used to track security reverts.
147 unsigned int reverted_cve = 0;
148
149 // util.h
150 // Tells whether the per-process V8::Initialize() is called and
151 // if it is safe to call v8::Isolate::TryGetCurrent().
152 bool v8_initialized = false;
153
154 // node_internals.h
155 // process-relative uptime base in nanoseconds, initialized in node::Start()
156 uint64_t node_start_time;
157
158 #if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
159 PVOID old_vectored_exception_handler;
160 #endif
161
162 // node_v8_platform-inl.h
163 struct V8Platform v8_platform;
164 } // namespace per_process
165
166 // The section in the OpenSSL configuration file to be loaded.
167 const char* conf_section_name = STRINGIFY(NODE_OPENSSL_CONF_NAME);
168
169 #ifdef __POSIX__
SignalExit(int signo,siginfo_t * info,void * ucontext)170 void SignalExit(int signo, siginfo_t* info, void* ucontext) {
171 ResetStdio();
172 raise(signo);
173 }
174 #endif // __POSIX__
175
176 #if HAVE_INSPECTOR
InitializeInspector(std::unique_ptr<inspector::ParentInspectorHandle> parent_handle)177 int Environment::InitializeInspector(
178 std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
179 std::string inspector_path;
180 bool is_main = !parent_handle;
181 if (parent_handle) {
182 inspector_path = parent_handle->url();
183 inspector_agent_->SetParentHandle(std::move(parent_handle));
184 } else {
185 inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
186 }
187
188 CHECK(!inspector_agent_->IsListening());
189 // Inspector agent can't fail to start, but if it was configured to listen
190 // right away on the websocket port and fails to bind/etc, this will return
191 // false.
192 inspector_agent_->Start(inspector_path,
193 options_->debug_options(),
194 inspector_host_port(),
195 is_main);
196 if (options_->debug_options().inspector_enabled &&
197 !inspector_agent_->IsListening()) {
198 return 12; // Signal internal error
199 }
200
201 profiler::StartProfilers(this);
202
203 if (inspector_agent_->options().break_node_first_line) {
204 inspector_agent_->PauseOnNextJavascriptStatement("Break at bootstrap");
205 }
206
207 return 0;
208 }
209 #endif // HAVE_INSPECTOR
210
211 #define ATOMIC_WAIT_EVENTS(V) \
212 V(kStartWait, "started") \
213 V(kWokenUp, "was woken up by another thread") \
214 V(kTimedOut, "timed out") \
215 V(kTerminatedExecution, "was stopped by terminated execution") \
216 V(kAPIStopped, "was stopped through the embedder API") \
217 V(kNotEqual, "did not wait because the values mismatched") \
218
AtomicsWaitCallback(Isolate::AtomicsWaitEvent event,Local<v8::SharedArrayBuffer> array_buffer,size_t offset_in_bytes,int64_t value,double timeout_in_ms,Isolate::AtomicsWaitWakeHandle * stop_handle,void * data)219 static void AtomicsWaitCallback(Isolate::AtomicsWaitEvent event,
220 Local<v8::SharedArrayBuffer> array_buffer,
221 size_t offset_in_bytes, int64_t value,
222 double timeout_in_ms,
223 Isolate::AtomicsWaitWakeHandle* stop_handle,
224 void* data) {
225 Environment* env = static_cast<Environment*>(data);
226
227 const char* message = "(unknown event)";
228 switch (event) {
229 #define V(key, msg) \
230 case Isolate::AtomicsWaitEvent::key: \
231 message = msg; \
232 break;
233 ATOMIC_WAIT_EVENTS(V)
234 #undef V
235 }
236
237 fprintf(stderr,
238 "(node:%d) [Thread %" PRIu64 "] Atomics.wait(%p + %zx, %" PRId64
239 ", %.f) %s\n",
240 static_cast<int>(uv_os_getpid()),
241 env->thread_id(),
242 array_buffer->Data(),
243 offset_in_bytes,
244 value,
245 timeout_in_ms,
246 message);
247 }
248
InitializeDiagnostics()249 void Environment::InitializeDiagnostics() {
250 isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
251 Environment::BuildEmbedderGraph, this);
252 if (heap_snapshot_near_heap_limit_ > 0) {
253 AddHeapSnapshotNearHeapLimitCallback();
254 }
255 if (options_->trace_uncaught)
256 isolate_->SetCaptureStackTraceForUncaughtExceptions(true);
257 if (options_->trace_atomics_wait) {
258 isolate_->SetAtomicsWaitCallback(AtomicsWaitCallback, this);
259 AddCleanupHook([](void* data) {
260 Environment* env = static_cast<Environment*>(data);
261 env->isolate()->SetAtomicsWaitCallback(nullptr, nullptr);
262 }, this);
263 }
264
265 #if defined HAVE_DTRACE || defined HAVE_ETW
266 InitDTrace(this);
267 #endif
268 }
269
270 static
StartExecution(Environment * env,const char * main_script_id)271 MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
272 EscapableHandleScope scope(env->isolate());
273 CHECK_NOT_NULL(main_script_id);
274 Realm* realm = env->principal_realm();
275
276 return scope.EscapeMaybe(realm->ExecuteBootstrapper(main_script_id));
277 }
278
StartExecution(Environment * env,StartExecutionCallback cb)279 MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
280 InternalCallbackScope callback_scope(
281 env,
282 Object::New(env->isolate()),
283 { 1, 0 },
284 InternalCallbackScope::kSkipAsyncHooks);
285
286 if (cb != nullptr) {
287 EscapableHandleScope scope(env->isolate());
288
289 if (StartExecution(env, "internal/main/environment").IsEmpty()) return {};
290
291 StartExecutionCallbackInfo info = {
292 env->process_object(),
293 env->builtin_module_require(),
294 };
295
296 return scope.EscapeMaybe(cb(info));
297 }
298
299 // TODO(joyeecheung): move these conditions into JS land and let the
300 // deserialize main function take precedence. For workers, we need to
301 // move the pre-execution part into a different file that can be
302 // reused when dealing with user-defined main functions.
303 if (!env->snapshot_deserialize_main().IsEmpty()) {
304 return env->RunSnapshotDeserializeMain();
305 }
306
307 if (env->worker_context() != nullptr) {
308 return StartExecution(env, "internal/main/worker_thread");
309 }
310
311 std::string first_argv;
312 if (env->argv().size() > 1) {
313 first_argv = env->argv()[1];
314 }
315
316 #ifndef DISABLE_SINGLE_EXECUTABLE_APPLICATION
317 if (sea::IsSingleExecutable()) {
318 // TODO(addaleax): Find a way to reuse:
319 //
320 // LoadEnvironment(Environment*, const char*)
321 //
322 // instead and not add yet another main entry point here because this
323 // already duplicates existing code.
324 return StartExecution(env, "internal/main/single_executable_application");
325 }
326 #endif
327
328 if (first_argv == "inspect") {
329 return StartExecution(env, "internal/main/inspect");
330 }
331
332 if (per_process::cli_options->build_snapshot) {
333 return StartExecution(env, "internal/main/mksnapshot");
334 }
335
336 if (per_process::cli_options->print_help) {
337 return StartExecution(env, "internal/main/print_help");
338 }
339
340
341 if (env->options()->prof_process) {
342 return StartExecution(env, "internal/main/prof_process");
343 }
344
345 // -e/--eval without -i/--interactive
346 if (env->options()->has_eval_string && !env->options()->force_repl) {
347 return StartExecution(env, "internal/main/eval_string");
348 }
349
350 if (env->options()->syntax_check_only) {
351 return StartExecution(env, "internal/main/check_syntax");
352 }
353
354 if (env->options()->test_runner) {
355 return StartExecution(env, "internal/main/test_runner");
356 }
357
358 if (env->options()->watch_mode) {
359 return StartExecution(env, "internal/main/watch_mode");
360 }
361
362 if (!first_argv.empty() && first_argv != "-") {
363 return StartExecution(env, "internal/main/run_main_module");
364 }
365
366 if (env->options()->force_repl || uv_guess_handle(STDIN_FILENO) == UV_TTY) {
367 return StartExecution(env, "internal/main/repl");
368 }
369
370 return StartExecution(env, "internal/main/eval_stdin");
371 }
372
373 #ifdef __POSIX__
374 typedef void (*sigaction_cb)(int signo, siginfo_t* info, void* ucontext);
375 #endif
376 #if NODE_USE_V8_WASM_TRAP_HANDLER
377 #if defined(_WIN32)
TrapWebAssemblyOrContinue(EXCEPTION_POINTERS * exception)378 static LONG TrapWebAssemblyOrContinue(EXCEPTION_POINTERS* exception) {
379 if (v8::TryHandleWebAssemblyTrapWindows(exception)) {
380 return EXCEPTION_CONTINUE_EXECUTION;
381 }
382 return EXCEPTION_CONTINUE_SEARCH;
383 }
384 #else
385 static std::atomic<sigaction_cb> previous_sigsegv_action;
386 // TODO(align behavior between macos and other in next major version)
387 #if defined(__APPLE__)
388 static std::atomic<sigaction_cb> previous_sigbus_action;
389 #endif // __APPLE__
390
TrapWebAssemblyOrContinue(int signo,siginfo_t * info,void * ucontext)391 void TrapWebAssemblyOrContinue(int signo, siginfo_t* info, void* ucontext) {
392 if (!v8::TryHandleWebAssemblyTrapPosix(signo, info, ucontext)) {
393 #if defined(__APPLE__)
394 sigaction_cb prev = signo == SIGBUS ? previous_sigbus_action.load()
395 : previous_sigsegv_action.load();
396 #else
397 sigaction_cb prev = previous_sigsegv_action.load();
398 #endif // __APPLE__
399 if (prev != nullptr) {
400 prev(signo, info, ucontext);
401 } else {
402 // Reset to the default signal handler, i.e. cause a hard crash.
403 struct sigaction sa;
404 memset(&sa, 0, sizeof(sa));
405 sa.sa_handler = SIG_DFL;
406 CHECK_EQ(sigaction(signo, &sa, nullptr), 0);
407
408 ResetStdio();
409 raise(signo);
410 }
411 }
412 }
413 #endif // defined(_WIN32)
414 #endif // NODE_USE_V8_WASM_TRAP_HANDLER
415
416 #ifdef __POSIX__
RegisterSignalHandler(int signal,sigaction_cb handler,bool reset_handler)417 void RegisterSignalHandler(int signal,
418 sigaction_cb handler,
419 bool reset_handler) {
420 CHECK_NOT_NULL(handler);
421 #if NODE_USE_V8_WASM_TRAP_HANDLER
422 if (signal == SIGSEGV) {
423 CHECK(previous_sigsegv_action.is_lock_free());
424 CHECK(!reset_handler);
425 previous_sigsegv_action.store(handler);
426 return;
427 }
428 // TODO(align behavior between macos and other in next major version)
429 #if defined(__APPLE__)
430 if (signal == SIGBUS) {
431 CHECK(previous_sigbus_action.is_lock_free());
432 CHECK(!reset_handler);
433 previous_sigbus_action.store(handler);
434 return;
435 }
436 #endif // __APPLE__
437 #endif // NODE_USE_V8_WASM_TRAP_HANDLER
438 struct sigaction sa;
439 memset(&sa, 0, sizeof(sa));
440 sa.sa_sigaction = handler;
441 sa.sa_flags = reset_handler ? SA_RESETHAND : 0;
442 sigfillset(&sa.sa_mask);
443 CHECK_EQ(sigaction(signal, &sa, nullptr), 0);
444 }
445 #endif // __POSIX__
446
447 #ifdef __POSIX__
448 static struct {
449 int flags;
450 bool isatty;
451 struct stat stat;
452 struct termios termios;
453 } stdio[1 + STDERR_FILENO];
454 #endif // __POSIX__
455
ResetSignalHandlers()456 void ResetSignalHandlers() {
457 #ifdef __POSIX__
458 // Restore signal dispositions, the parent process may have changed them.
459 struct sigaction act;
460 memset(&act, 0, sizeof(act));
461
462 // The hard-coded upper limit is because NSIG is not very reliable; on Linux,
463 // it evaluates to 32, 34 or 64, depending on whether RT signals are enabled.
464 // Counting up to SIGRTMIN doesn't work for the same reason.
465 for (unsigned nr = 1; nr < kMaxSignal; nr += 1) {
466 if (nr == SIGKILL || nr == SIGSTOP)
467 continue;
468 act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
469 if (act.sa_handler == SIG_DFL) {
470 // The only bad handler value we can inhert from before exec is SIG_IGN
471 // (any actual function pointer is reset to SIG_DFL during exec).
472 // If that's the case, we want to reset it back to SIG_DFL.
473 // However, it's also possible that an embeder (or an LD_PRELOAD-ed
474 // library) has set up own signal handler for own purposes
475 // (e.g. profiling). If that's the case, we want to keep it intact.
476 struct sigaction old;
477 CHECK_EQ(0, sigaction(nr, nullptr, &old));
478 if ((old.sa_flags & SA_SIGINFO) || old.sa_handler != SIG_IGN) continue;
479 }
480 CHECK_EQ(0, sigaction(nr, &act, nullptr));
481 }
482 #endif // __POSIX__
483 }
484
485 static std::atomic<uint32_t> init_process_flags = 0;
486
PlatformInit(ProcessInitializationFlags::Flags flags)487 static void PlatformInit(ProcessInitializationFlags::Flags flags) {
488 // init_process_flags is accessed in ResetStdio(),
489 // which can be called from signal handlers.
490 CHECK(init_process_flags.is_lock_free());
491 init_process_flags.store(flags);
492
493 if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
494 atexit(ResetStdio);
495 }
496
497 #ifdef __POSIX__
498 if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
499 // Disable stdio buffering, it interacts poorly with printf()
500 // calls elsewhere in the program (e.g., any logging from V8.)
501 setvbuf(stdout, nullptr, _IONBF, 0);
502 setvbuf(stderr, nullptr, _IONBF, 0);
503
504 // Make sure file descriptors 0-2 are valid before we start logging
505 // anything.
506 for (auto& s : stdio) {
507 const int fd = &s - stdio;
508 if (fstat(fd, &s.stat) == 0) continue;
509
510 // Anything but EBADF means something is seriously wrong. We don't
511 // have to special-case EINTR, fstat() is not interruptible.
512 if (errno != EBADF) ABORT();
513
514 // If EBADF (file descriptor doesn't exist), open /dev/null and duplicate
515 // its file descriptor to the invalid file descriptor. Make sure *that*
516 // file descriptor is valid. POSIX doesn't guarantee the next file
517 // descriptor open(2) gives us is the lowest available number anymore in
518 // POSIX.1-2017, which is why dup2(2) is needed.
519 int null_fd;
520
521 do {
522 null_fd = open("/dev/null", O_RDWR);
523 } while (null_fd < 0 && errno == EINTR);
524
525 if (null_fd != fd) {
526 int err;
527
528 do {
529 err = dup2(null_fd, fd);
530 } while (err < 0 && errno == EINTR);
531 CHECK_EQ(err, 0);
532 }
533
534 if (fstat(fd, &s.stat) < 0) ABORT();
535 }
536 }
537
538 if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
539 #if HAVE_INSPECTOR
540 sigset_t sigmask;
541 sigemptyset(&sigmask);
542 sigaddset(&sigmask, SIGUSR1);
543 const int err = pthread_sigmask(SIG_SETMASK, &sigmask, nullptr);
544 CHECK_EQ(err, 0);
545 #endif // HAVE_INSPECTOR
546
547 ResetSignalHandlers();
548 }
549
550 if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
551 // Record the state of the stdio file descriptors so we can restore it
552 // on exit. Needs to happen before installing signal handlers because
553 // they make use of that information.
554 for (auto& s : stdio) {
555 const int fd = &s - stdio;
556 int err;
557
558 do {
559 s.flags = fcntl(fd, F_GETFL);
560 } while (s.flags == -1 && errno == EINTR); // NOLINT
561 CHECK_NE(s.flags, -1);
562
563 if (uv_guess_handle(fd) != UV_TTY) continue;
564 s.isatty = true;
565
566 do {
567 err = tcgetattr(fd, &s.termios);
568 } while (err == -1 && errno == EINTR); // NOLINT
569 CHECK_EQ(err, 0);
570 }
571 }
572
573 if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
574 RegisterSignalHandler(SIGINT, SignalExit, true);
575 RegisterSignalHandler(SIGTERM, SignalExit, true);
576
577 #if NODE_USE_V8_WASM_TRAP_HANDLER
578 #if defined(_WIN32)
579 {
580 constexpr ULONG first = TRUE;
581 per_process::old_vectored_exception_handler =
582 AddVectoredExceptionHandler(first, TrapWebAssemblyOrContinue);
583 }
584 #else
585 // Tell V8 to disable emitting WebAssembly
586 // memory bounds checks. This means that we have
587 // to catch the SIGSEGV/SIGBUS in TrapWebAssemblyOrContinue
588 // and pass the signal context to V8.
589 {
590 struct sigaction sa;
591 memset(&sa, 0, sizeof(sa));
592 sa.sa_sigaction = TrapWebAssemblyOrContinue;
593 sa.sa_flags = SA_SIGINFO;
594 CHECK_EQ(sigaction(SIGSEGV, &sa, nullptr), 0);
595 // TODO(align behavior between macos and other in next major version)
596 #if defined(__APPLE__)
597 CHECK_EQ(sigaction(SIGBUS, &sa, nullptr), 0);
598 #endif
599 }
600 #endif // defined(_WIN32)
601 V8::EnableWebAssemblyTrapHandler(false);
602 #endif // NODE_USE_V8_WASM_TRAP_HANDLER
603 }
604
605 if (!(flags & ProcessInitializationFlags::kNoAdjustResourceLimits)) {
606 // Raise the open file descriptor limit.
607 struct rlimit lim;
608 if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
609 // Do a binary search for the limit.
610 rlim_t min = lim.rlim_cur;
611 rlim_t max = 1 << 20;
612 // But if there's a defined upper bound, don't search, just set it.
613 if (lim.rlim_max != RLIM_INFINITY) {
614 min = lim.rlim_max;
615 max = lim.rlim_max;
616 }
617 do {
618 lim.rlim_cur = min + (max - min) / 2;
619 if (setrlimit(RLIMIT_NOFILE, &lim)) {
620 max = lim.rlim_cur;
621 } else {
622 min = lim.rlim_cur;
623 }
624 } while (min + 1 < max);
625 }
626 }
627 #endif // __POSIX__
628 #ifdef _WIN32
629 if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
630 for (int fd = 0; fd <= 2; ++fd) {
631 auto handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
632 if (handle == INVALID_HANDLE_VALUE ||
633 GetFileType(handle) == FILE_TYPE_UNKNOWN) {
634 // Ignore _close result. If it fails or not depends on used Windows
635 // version. We will just check _open result.
636 _close(fd);
637 if (fd != _open("nul", _O_RDWR)) ABORT();
638 }
639 }
640 }
641 #endif // _WIN32
642 }
643
644 // Safe to call more than once and from signal handlers.
ResetStdio()645 void ResetStdio() {
646 if (init_process_flags.load() &
647 ProcessInitializationFlags::kNoStdioInitialization) {
648 return;
649 }
650
651 uv_tty_reset_mode();
652 #ifdef __POSIX__
653 for (auto& s : stdio) {
654 const int fd = &s - stdio;
655
656 struct stat tmp;
657 if (-1 == fstat(fd, &tmp)) {
658 CHECK_EQ(errno, EBADF); // Program closed file descriptor.
659 continue;
660 }
661
662 bool is_same_file =
663 (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
664 if (!is_same_file) continue; // Program reopened file descriptor.
665
666 int flags;
667 do
668 flags = fcntl(fd, F_GETFL);
669 while (flags == -1 && errno == EINTR); // NOLINT
670 CHECK_NE(flags, -1);
671
672 // Restore the O_NONBLOCK flag if it changed.
673 if (O_NONBLOCK & (flags ^ s.flags)) {
674 flags &= ~O_NONBLOCK;
675 flags |= s.flags & O_NONBLOCK;
676
677 int err;
678 do
679 err = fcntl(fd, F_SETFL, flags);
680 while (err == -1 && errno == EINTR); // NOLINT
681 CHECK_NE(err, -1);
682 }
683
684 if (s.isatty) {
685 sigset_t sa;
686 int err;
687
688 // We might be a background job that doesn't own the TTY so block SIGTTOU
689 // before making the tcsetattr() call, otherwise that signal suspends us.
690 sigemptyset(&sa);
691 sigaddset(&sa, SIGTTOU);
692
693 CHECK_EQ(0, pthread_sigmask(SIG_BLOCK, &sa, nullptr));
694 do
695 err = tcsetattr(fd, TCSANOW, &s.termios);
696 while (err == -1 && errno == EINTR); // NOLINT
697 CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
698
699 // Normally we expect err == 0. But if macOS App Sandbox is enabled,
700 // tcsetattr will fail with err == -1 and errno == EPERM.
701 CHECK_IMPLIES(err != 0, err == -1 && errno == EPERM);
702 }
703 }
704 #endif // __POSIX__
705 }
706
707
ProcessGlobalArgs(std::vector<std::string> * args,std::vector<std::string> * exec_args,std::vector<std::string> * errors,OptionEnvvarSettings settings)708 int ProcessGlobalArgs(std::vector<std::string>* args,
709 std::vector<std::string>* exec_args,
710 std::vector<std::string>* errors,
711 OptionEnvvarSettings settings) {
712 // Parse a few arguments which are specific to Node.
713 std::vector<std::string> v8_args;
714
715 Mutex::ScopedLock lock(per_process::cli_options_mutex);
716 options_parser::Parse(
717 args,
718 exec_args,
719 &v8_args,
720 per_process::cli_options.get(),
721 settings,
722 errors);
723
724 if (!errors->empty()) return 9;
725
726 std::string revert_error;
727 for (const std::string& cve : per_process::cli_options->security_reverts) {
728 Revert(cve.c_str(), &revert_error);
729 if (!revert_error.empty()) {
730 errors->emplace_back(std::move(revert_error));
731 return 12;
732 }
733 }
734
735 if (per_process::cli_options->disable_proto != "delete" &&
736 per_process::cli_options->disable_proto != "throw" &&
737 per_process::cli_options->disable_proto != "") {
738 errors->emplace_back("invalid mode passed to --disable-proto");
739 return 12;
740 }
741
742 // TODO(aduh95): remove this when the harmony-import-assertions flag
743 // is removed in V8.
744 if (std::find(v8_args.begin(), v8_args.end(),
745 "--no-harmony-import-assertions") == v8_args.end()) {
746 v8_args.emplace_back("--harmony-import-assertions");
747 }
748 // TODO(aduh95): remove this when the harmony-import-attributes flag
749 // is removed in V8.
750 if (std::find(v8_args.begin(),
751 v8_args.end(),
752 "--no-harmony-import-attributes") == v8_args.end()) {
753 v8_args.emplace_back("--harmony-import-attributes");
754 }
755
756 auto env_opts = per_process::cli_options->per_isolate->per_env;
757 if (std::find(v8_args.begin(), v8_args.end(),
758 "--abort-on-uncaught-exception") != v8_args.end() ||
759 std::find(v8_args.begin(), v8_args.end(),
760 "--abort_on_uncaught_exception") != v8_args.end()) {
761 env_opts->abort_on_uncaught_exception = true;
762 }
763
764 #ifdef __POSIX__
765 // Block SIGPROF signals when sleeping in epoll_wait/kevent/etc. Avoids the
766 // performance penalty of frequent EINTR wakeups when the profiler is running.
767 // Only do this for v8.log profiling, as it breaks v8::CpuProfiler users.
768 if (std::find(v8_args.begin(), v8_args.end(), "--prof") != v8_args.end()) {
769 uv_loop_configure(uv_default_loop(), UV_LOOP_BLOCK_SIGNAL, SIGPROF);
770 }
771 #endif
772
773 std::vector<char*> v8_args_as_char_ptr(v8_args.size());
774 if (v8_args.size() > 0) {
775 for (size_t i = 0; i < v8_args.size(); ++i)
776 v8_args_as_char_ptr[i] = v8_args[i].data();
777 int argc = v8_args.size();
778 V8::SetFlagsFromCommandLine(&argc, v8_args_as_char_ptr.data(), true);
779 v8_args_as_char_ptr.resize(argc);
780 }
781
782 // Anything that's still in v8_argv is not a V8 or a node option.
783 for (size_t i = 1; i < v8_args_as_char_ptr.size(); i++)
784 errors->push_back("bad option: " + std::string(v8_args_as_char_ptr[i]));
785
786 if (v8_args_as_char_ptr.size() > 1) return 9;
787
788 return 0;
789 }
790
791 static std::atomic_bool init_called{false};
792
793 // TODO(addaleax): Turn this into a wrapper around InitializeOncePerProcess()
794 // (with the corresponding additional flags set), then eventually remove this.
InitializeNodeWithArgs(std::vector<std::string> * argv,std::vector<std::string> * exec_argv,std::vector<std::string> * errors)795 int InitializeNodeWithArgs(std::vector<std::string>* argv,
796 std::vector<std::string>* exec_argv,
797 std::vector<std::string>* errors) {
798 return InitializeNodeWithArgs(argv, exec_argv, errors,
799 ProcessFlags::kNoFlags);
800 }
801
InitializeNodeWithArgs(std::vector<std::string> * argv,std::vector<std::string> * exec_argv,std::vector<std::string> * errors,ProcessInitializationFlags::Flags flags)802 int InitializeNodeWithArgs(std::vector<std::string>* argv,
803 std::vector<std::string>* exec_argv,
804 std::vector<std::string>* errors,
805 ProcessInitializationFlags::Flags flags) {
806 // Make sure InitializeNodeWithArgs() is called only once.
807 CHECK(!init_called.exchange(true));
808
809 // Initialize node_start_time to get relative uptime.
810 per_process::node_start_time = uv_hrtime();
811
812 // Register built-in bindings
813 binding::RegisterBuiltinBindings();
814
815 // Make inherited handles noninheritable.
816 if (!(flags & ProcessInitializationFlags::kEnableStdioInheritance) &&
817 !(flags & ProcessInitializationFlags::kNoStdioInitialization)) {
818 uv_disable_stdio_inheritance();
819 }
820
821 // Cache the original command line to be
822 // used in diagnostic reports.
823 per_process::cli_options->cmdline = *argv;
824
825 #if defined(NODE_V8_OPTIONS)
826 // Should come before the call to V8::SetFlagsFromCommandLine()
827 // so the user can disable a flag --foo at run-time by passing
828 // --no_foo from the command line.
829 V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1);
830 #endif
831
832 HandleEnvOptions(per_process::cli_options->per_isolate->per_env);
833
834 #if !defined(NODE_WITHOUT_NODE_OPTIONS)
835 if (!(flags & ProcessInitializationFlags::kDisableNodeOptionsEnv)) {
836 std::string node_options;
837
838 if (credentials::SafeGetenv("NODE_OPTIONS", &node_options)) {
839 std::vector<std::string> env_argv =
840 ParseNodeOptionsEnvVar(node_options, errors);
841
842 if (!errors->empty()) return 9;
843
844 // [0] is expected to be the program name, fill it in from the real argv.
845 env_argv.insert(env_argv.begin(), argv->at(0));
846
847 const int exit_code = ProcessGlobalArgs(&env_argv,
848 nullptr,
849 errors,
850 kAllowedInEnvvar);
851 if (exit_code != 0) return exit_code;
852 }
853 }
854 #endif
855
856 if (!(flags & ProcessInitializationFlags::kDisableCLIOptions)) {
857 const int exit_code = ProcessGlobalArgs(argv,
858 exec_argv,
859 errors,
860 kDisallowedInEnvvar);
861 if (exit_code != 0) return exit_code;
862 }
863
864 // Set the process.title immediately after processing argv if --title is set.
865 if (!per_process::cli_options->title.empty())
866 uv_set_process_title(per_process::cli_options->title.c_str());
867
868 #if defined(NODE_HAVE_I18N_SUPPORT)
869 if (!(flags & ProcessInitializationFlags::kNoICU)) {
870 // If the parameter isn't given, use the env variable.
871 if (per_process::cli_options->icu_data_dir.empty())
872 credentials::SafeGetenv("NODE_ICU_DATA",
873 &per_process::cli_options->icu_data_dir);
874
875 #ifdef NODE_ICU_DEFAULT_DATA_DIR
876 // If neither the CLI option nor the environment variable was specified,
877 // fall back to the configured default
878 if (per_process::cli_options->icu_data_dir.empty()) {
879 // Check whether the NODE_ICU_DEFAULT_DATA_DIR contains the right data
880 // file and can be read.
881 static const char full_path[] =
882 NODE_ICU_DEFAULT_DATA_DIR "/" U_ICUDATA_NAME ".dat";
883
884 FILE* f = fopen(full_path, "rb");
885
886 if (f != nullptr) {
887 fclose(f);
888 per_process::cli_options->icu_data_dir = NODE_ICU_DEFAULT_DATA_DIR;
889 }
890 }
891 #endif // NODE_ICU_DEFAULT_DATA_DIR
892
893 // Initialize ICU.
894 // If icu_data_dir is empty here, it will load the 'minimal' data.
895 if (!i18n::InitializeICUDirectory(per_process::cli_options->icu_data_dir)) {
896 errors->push_back("could not initialize ICU "
897 "(check NODE_ICU_DATA or --icu-data-dir parameters)\n");
898 return 9;
899 }
900 per_process::metadata.versions.InitializeIntlVersions();
901 }
902
903 # ifndef __POSIX__
904 std::string tz;
905 if (credentials::SafeGetenv("TZ", &tz) && !tz.empty()) {
906 i18n::SetDefaultTimeZone(tz.c_str());
907 }
908 # endif
909
910 #endif // defined(NODE_HAVE_I18N_SUPPORT)
911
912 // We should set node_is_initialized here instead of in node::Start,
913 // otherwise embedders using node::Init to initialize everything will not be
914 // able to set it and native addons will not load for them.
915 node_is_initialized = true;
916 return 0;
917 }
918
InitializeOncePerProcess(const std::vector<std::string> & args,ProcessInitializationFlags::Flags flags)919 std::unique_ptr<InitializationResult> InitializeOncePerProcess(
920 const std::vector<std::string>& args,
921 ProcessInitializationFlags::Flags flags) {
922 auto result = std::make_unique<InitializationResultImpl>();
923 result->args_ = args;
924
925 if (!(flags & ProcessInitializationFlags::kNoParseGlobalDebugVariables)) {
926 // Initialized the enabled list for Debug() calls with system
927 // environment variables.
928 per_process::enabled_debug_list.Parse();
929 }
930
931 PlatformInit(flags);
932
933 // This needs to run *before* V8::Initialize().
934 {
935 result->exit_code_ = InitializeNodeWithArgs(
936 &result->args_, &result->exec_args_, &result->errors_, flags);
937 if (result->exit_code() != 0) {
938 result->early_return_ = true;
939 return result;
940 }
941 }
942
943 if (!(flags & ProcessInitializationFlags::kNoUseLargePages) &&
944 (per_process::cli_options->use_largepages == "on" ||
945 per_process::cli_options->use_largepages == "silent")) {
946 int lp_result = node::MapStaticCodeToLargePages();
947 if (per_process::cli_options->use_largepages == "on" && lp_result != 0) {
948 result->errors_.emplace_back(node::LargePagesError(lp_result));
949 }
950 }
951
952 if (!(flags & ProcessInitializationFlags::kNoPrintHelpOrVersionOutput)) {
953 if (per_process::cli_options->print_version) {
954 printf("%s\n", NODE_VERSION);
955 result->exit_code_ = 0;
956 result->early_return_ = true;
957 return result;
958 }
959
960 if (per_process::cli_options->print_bash_completion) {
961 std::string completion = options_parser::GetBashCompletion();
962 printf("%s\n", completion.c_str());
963 result->exit_code_ = 0;
964 result->early_return_ = true;
965 return result;
966 }
967
968 if (per_process::cli_options->print_v8_help) {
969 V8::SetFlagsFromString("--help", static_cast<size_t>(6));
970 result->exit_code_ = 0;
971 result->early_return_ = true;
972 return result;
973 }
974 }
975
976 if (!(flags & ProcessInitializationFlags::kNoInitOpenSSL)) {
977 #if HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
978 auto GetOpenSSLErrorString = []() -> std::string {
979 std::string ret;
980 ERR_print_errors_cb(
981 [](const char* str, size_t len, void* opaque) {
982 std::string* ret = static_cast<std::string*>(opaque);
983 ret->append(str, len);
984 ret->append("\n");
985 return 0;
986 },
987 static_cast<void*>(&ret));
988 return ret;
989 };
990
991 // In the case of FIPS builds we should make sure
992 // the random source is properly initialized first.
993 #if OPENSSL_VERSION_MAJOR >= 3
994 // Call OPENSSL_init_crypto to initialize OPENSSL_INIT_LOAD_CONFIG to
995 // avoid the default behavior where errors raised during the parsing of the
996 // OpenSSL configuration file are not propagated and cannot be detected.
997 //
998 // If FIPS is configured the OpenSSL configuration file will have an
999 // .include pointing to the fipsmodule.cnf file generated by the openssl
1000 // fipsinstall command. If the path to this file is incorrect no error
1001 // will be reported.
1002 //
1003 // For Node.js this will mean that CSPRNG() will be called by V8 as
1004 // part of its initialization process, and CSPRNG() will in turn call
1005 // call RAND_status which will now always return 0, leading to an endless
1006 // loop and the node process will appear to hang/freeze.
1007
1008 // Passing NULL as the config file will allow the default openssl.cnf file
1009 // to be loaded, but the default section in that file will not be used,
1010 // instead only the section that matches the value of conf_section_name
1011 // will be read from the default configuration file.
1012 const char* conf_file = nullptr;
1013 // To allow for using the previous default where the 'openssl_conf' appname
1014 // was used, the command line option 'openssl-shared-config' can be used to
1015 // force the old behavior.
1016 if (per_process::cli_options->openssl_shared_config) {
1017 conf_section_name = "openssl_conf";
1018 }
1019 // Use OPENSSL_CONF environment variable is set.
1020 std::string env_openssl_conf;
1021 credentials::SafeGetenv("OPENSSL_CONF", &env_openssl_conf);
1022 if (!env_openssl_conf.empty()) {
1023 conf_file = env_openssl_conf.c_str();
1024 }
1025 // Use --openssl-conf command line option if specified.
1026 if (!per_process::cli_options->openssl_config.empty()) {
1027 conf_file = per_process::cli_options->openssl_config.c_str();
1028 }
1029
1030 OPENSSL_INIT_SETTINGS* settings = OPENSSL_INIT_new();
1031 OPENSSL_INIT_set_config_filename(settings, conf_file);
1032 OPENSSL_INIT_set_config_appname(settings, conf_section_name);
1033 OPENSSL_INIT_set_config_file_flags(settings,
1034 CONF_MFLAGS_IGNORE_MISSING_FILE);
1035
1036 OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, settings);
1037 OPENSSL_INIT_free(settings);
1038
1039 if (ERR_peek_error() != 0) {
1040 // XXX: ERR_GET_REASON does not return something that is
1041 // useful as an exit code at all.
1042 result->exit_code_ = ERR_GET_REASON(ERR_peek_error());
1043 result->early_return_ = true;
1044 result->errors_.emplace_back("OpenSSL configuration error:\n" +
1045 GetOpenSSLErrorString());
1046 return result;
1047 }
1048 #else // OPENSSL_VERSION_MAJOR < 3
1049 if (FIPS_mode()) {
1050 OPENSSL_init();
1051 }
1052 #endif
1053 if (!crypto::ProcessFipsOptions()) {
1054 // XXX: ERR_GET_REASON does not return something that is
1055 // useful as an exit code at all.
1056 result->exit_code_ = ERR_GET_REASON(ERR_peek_error());
1057 result->early_return_ = true;
1058 result->errors_.emplace_back(
1059 "OpenSSL error when trying to enable FIPS:\n" +
1060 GetOpenSSLErrorString());
1061 return result;
1062 }
1063
1064 // Ensure CSPRNG is properly seeded.
1065 CHECK(crypto::CSPRNG(nullptr, 0).is_ok());
1066
1067 V8::SetEntropySource([](unsigned char* buffer, size_t length) {
1068 // V8 falls back to very weak entropy when this function fails
1069 // and /dev/urandom isn't available. That wouldn't be so bad if
1070 // the entropy was only used for Math.random() but it's also used for
1071 // hash table and address space layout randomization. Better to abort.
1072 CHECK(crypto::CSPRNG(buffer, length).is_ok());
1073 return true;
1074 });
1075
1076 {
1077 std::string extra_ca_certs;
1078 if (credentials::SafeGetenv("NODE_EXTRA_CA_CERTS", &extra_ca_certs))
1079 crypto::UseExtraCaCerts(extra_ca_certs);
1080 }
1081 #endif // HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
1082 }
1083
1084 if (!(flags & ProcessInitializationFlags::kNoInitializeNodeV8Platform)) {
1085 per_process::v8_platform.Initialize(
1086 static_cast<int>(per_process::cli_options->v8_thread_pool_size));
1087 result->platform_ = per_process::v8_platform.Platform();
1088 }
1089
1090 if (!(flags & ProcessInitializationFlags::kNoInitializeV8)) {
1091 V8::Initialize();
1092 }
1093
1094 performance::performance_v8_start = PERFORMANCE_NOW();
1095 per_process::v8_initialized = true;
1096
1097 return result;
1098 }
1099
TearDownOncePerProcess()1100 void TearDownOncePerProcess() {
1101 const uint64_t flags = init_process_flags.load();
1102 ResetStdio();
1103 if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
1104 ResetSignalHandlers();
1105 }
1106
1107 per_process::v8_initialized = false;
1108 if (!(flags & ProcessInitializationFlags::kNoInitializeV8)) {
1109 V8::Dispose();
1110 }
1111
1112 #if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
1113 if (!(flags & ProcessInitializationFlags::kNoDefaultSignalHandling)) {
1114 RemoveVectoredExceptionHandler(per_process::old_vectored_exception_handler);
1115 }
1116 #endif
1117
1118 if (!(flags & ProcessInitializationFlags::kNoInitializeNodeV8Platform)) {
1119 V8::DisposePlatform();
1120 // uv_run cannot be called from the time before the beforeExit callback
1121 // runs until the program exits unless the event loop has any referenced
1122 // handles after beforeExit terminates. This prevents unrefed timers
1123 // that happen to terminate during shutdown from being run unsafely.
1124 // Since uv_run cannot be called, uv_async handles held by the platform
1125 // will never be fully cleaned up.
1126 per_process::v8_platform.Dispose();
1127 }
1128 }
1129
~InitializationResult()1130 InitializationResult::~InitializationResult() {}
~InitializationResultImpl()1131 InitializationResultImpl::~InitializationResultImpl() {}
1132
GenerateAndWriteSnapshotData(const SnapshotData ** snapshot_data_ptr,const InitializationResult * result)1133 int GenerateAndWriteSnapshotData(const SnapshotData** snapshot_data_ptr,
1134 const InitializationResult* result) {
1135 int exit_code = result->exit_code();
1136 // nullptr indicates there's no snapshot data.
1137 DCHECK_NULL(*snapshot_data_ptr);
1138
1139 // node:embedded_snapshot_main indicates that we are using the
1140 // embedded snapshot and we are not supposed to clean it up.
1141 if (result->args()[1] == "node:embedded_snapshot_main") {
1142 *snapshot_data_ptr = SnapshotBuilder::GetEmbeddedSnapshotData();
1143 if (*snapshot_data_ptr == nullptr) {
1144 // The Node.js binary is built without embedded snapshot
1145 fprintf(stderr,
1146 "node:embedded_snapshot_main was specified as snapshot "
1147 "entry point but Node.js was built without embedded "
1148 "snapshot.\n");
1149 exit_code = 1;
1150 return exit_code;
1151 }
1152 } else {
1153 // Otherwise, load and run the specified main script.
1154 std::unique_ptr<SnapshotData> generated_data =
1155 std::make_unique<SnapshotData>();
1156 exit_code = node::SnapshotBuilder::Generate(
1157 generated_data.get(), result->args(), result->exec_args());
1158 if (exit_code == 0) {
1159 *snapshot_data_ptr = generated_data.release();
1160 } else {
1161 return exit_code;
1162 }
1163 }
1164
1165 // Get the path to write the snapshot blob to.
1166 std::string snapshot_blob_path;
1167 if (!per_process::cli_options->snapshot_blob.empty()) {
1168 snapshot_blob_path = per_process::cli_options->snapshot_blob;
1169 } else {
1170 // Defaults to snapshot.blob in the current working directory.
1171 snapshot_blob_path = std::string("snapshot.blob");
1172 }
1173
1174 FILE* fp = fopen(snapshot_blob_path.c_str(), "wb");
1175 if (fp != nullptr) {
1176 (*snapshot_data_ptr)->ToBlob(fp);
1177 fclose(fp);
1178 } else {
1179 fprintf(stderr,
1180 "Cannot open %s for writing a snapshot.\n",
1181 snapshot_blob_path.c_str());
1182 exit_code = 1;
1183 }
1184 return exit_code;
1185 }
1186
LoadSnapshotDataAndRun(const SnapshotData ** snapshot_data_ptr,const InitializationResult * result)1187 int LoadSnapshotDataAndRun(const SnapshotData** snapshot_data_ptr,
1188 const InitializationResult* result) {
1189 int exit_code = result->exit_code();
1190 // nullptr indicates there's no snapshot data.
1191 DCHECK_NULL(*snapshot_data_ptr);
1192 // --snapshot-blob indicates that we are reading a customized snapshot.
1193 if (!per_process::cli_options->snapshot_blob.empty()) {
1194 std::string filename = per_process::cli_options->snapshot_blob;
1195 FILE* fp = fopen(filename.c_str(), "rb");
1196 if (fp == nullptr) {
1197 fprintf(stderr, "Cannot open %s", filename.c_str());
1198 exit_code = 1;
1199 return exit_code;
1200 }
1201 std::unique_ptr<SnapshotData> read_data = std::make_unique<SnapshotData>();
1202 bool ok = SnapshotData::FromBlob(read_data.get(), fp);
1203 fclose(fp);
1204 if (!ok) {
1205 // If we fail to read the customized snapshot, simply exit with 1.
1206 exit_code = 1;
1207 return exit_code;
1208 }
1209 *snapshot_data_ptr = read_data.release();
1210 } else if (per_process::cli_options->node_snapshot) {
1211 // If --snapshot-blob is not specified, we are reading the embedded
1212 // snapshot, but we will skip it if --no-node-snapshot is specified.
1213 const node::SnapshotData* read_data =
1214 SnapshotBuilder::GetEmbeddedSnapshotData();
1215 if (read_data != nullptr && read_data->Check()) {
1216 // If we fail to read the embedded snapshot, treat it as if Node.js
1217 // was built without one.
1218 *snapshot_data_ptr = read_data;
1219 }
1220 }
1221
1222 NodeMainInstance main_instance(*snapshot_data_ptr,
1223 uv_default_loop(),
1224 per_process::v8_platform.Platform(),
1225 result->args(),
1226 result->exec_args());
1227 exit_code = main_instance.Run();
1228 return exit_code;
1229 }
1230
Start(int argc,char ** argv)1231 int Start(int argc, char** argv) {
1232 #ifndef DISABLE_SINGLE_EXECUTABLE_APPLICATION
1233 std::tie(argc, argv) = sea::FixupArgsForSEA(argc, argv);
1234 #endif
1235
1236 CHECK_GT(argc, 0);
1237
1238 // Hack around with the argv pointer. Used for process.title = "blah".
1239 argv = uv_setup_args(argc, argv);
1240
1241 std::unique_ptr<InitializationResult> result =
1242 InitializeOncePerProcess(std::vector<std::string>(argv, argv + argc));
1243 for (const std::string& error : result->errors()) {
1244 FPrintF(stderr, "%s: %s\n", result->args().at(0), error);
1245 }
1246 if (result->early_return()) {
1247 return result->exit_code();
1248 }
1249
1250 DCHECK_EQ(result->exit_code(), 0);
1251 const SnapshotData* snapshot_data = nullptr;
1252
1253 auto cleanup_process = OnScopeLeave([&]() {
1254 TearDownOncePerProcess();
1255
1256 if (snapshot_data != nullptr &&
1257 snapshot_data->data_ownership == SnapshotData::DataOwnership::kOwned) {
1258 delete snapshot_data;
1259 }
1260 });
1261
1262 uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);
1263
1264 // --build-snapshot indicates that we are in snapshot building mode.
1265 if (per_process::cli_options->build_snapshot) {
1266 if (result->args().size() < 2) {
1267 fprintf(stderr,
1268 "--build-snapshot must be used with an entry point script.\n"
1269 "Usage: node --build-snapshot /path/to/entry.js\n");
1270 return 9;
1271 }
1272 return GenerateAndWriteSnapshotData(&snapshot_data, result.get());
1273 }
1274
1275 // Without --build-snapshot, we are in snapshot loading mode.
1276 return LoadSnapshotDataAndRun(&snapshot_data, result.get());
1277 }
1278
Stop(Environment * env)1279 int Stop(Environment* env) {
1280 return Stop(env, StopFlags::kNoFlags);
1281 }
1282
Stop(Environment * env,StopFlags::Flags flags)1283 int Stop(Environment* env, StopFlags::Flags flags) {
1284 env->ExitEnv(flags);
1285 return 0;
1286 }
1287
1288 } // namespace node
1289
1290 #if !HAVE_INSPECTOR
Initialize()1291 void Initialize() {}
1292
1293 NODE_BINDING_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1294 #endif // !HAVE_INSPECTOR
1295