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