GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.cc Lines: 389 452 86.1 %
Date: 2022-05-22 04:15:48 Branches: 228 341 66.9 %

Line Branch Exec Source
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_errors.h"
32
#include "node_internals.h"
33
#include "node_main_instance.h"
34
#include "node_metadata.h"
35
#include "node_native_module_env.h"
36
#include "node_options-inl.h"
37
#include "node_perf.h"
38
#include "node_process-inl.h"
39
#include "node_report.h"
40
#include "node_revert.h"
41
#include "node_snapshot_builder.h"
42
#include "node_v8_platform-inl.h"
43
#include "node_version.h"
44
45
#if HAVE_OPENSSL
46
#include "node_crypto.h"
47
#endif
48
49
#if defined(NODE_HAVE_I18N_SUPPORT)
50
#include "node_i18n.h"
51
#endif
52
53
#if HAVE_INSPECTOR
54
#include "inspector_agent.h"
55
#include "inspector_io.h"
56
#endif
57
58
#if defined HAVE_DTRACE || defined HAVE_ETW
59
#include "node_dtrace.h"
60
#endif
61
62
#if NODE_USE_V8_PLATFORM
63
#include "libplatform/libplatform.h"
64
#endif  // NODE_USE_V8_PLATFORM
65
#include "v8-profiler.h"
66
67
#if HAVE_INSPECTOR
68
#include "inspector/worker_inspector.h"  // ParentInspectorHandle
69
#endif
70
71
#include "large_pages/node_large_page.h"
72
73
#if defined(__APPLE__) || defined(__linux__) || defined(_WIN32)
74
#define NODE_USE_V8_WASM_TRAP_HANDLER 1
75
#else
76
#define NODE_USE_V8_WASM_TRAP_HANDLER 0
77
#endif
78
79
#if NODE_USE_V8_WASM_TRAP_HANDLER
80
#if defined(_WIN32)
81
#include "v8-wasm-trap-handler-win.h"
82
#else
83
#include <atomic>
84
#include "v8-wasm-trap-handler-posix.h"
85
#endif
86
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
87
88
// ========== global C headers ==========
89
90
#include <fcntl.h>  // _O_RDWR
91
#include <sys/types.h>
92
93
#if defined(NODE_HAVE_I18N_SUPPORT)
94
#include <unicode/uvernum.h>
95
#include <unicode/utypes.h>
96
#endif
97
98
99
#if defined(LEAK_SANITIZER)
100
#include <sanitizer/lsan_interface.h>
101
#endif
102
103
#if defined(_MSC_VER)
104
#include <direct.h>
105
#include <io.h>
106
#define STDIN_FILENO 0
107
#else
108
#include <pthread.h>
109
#include <sys/resource.h>  // getrlimit, setrlimit
110
#include <termios.h>       // tcgetattr, tcsetattr
111
#include <unistd.h>        // STDIN_FILENO, STDERR_FILENO
112
#endif
113
114
// ========== global C++ headers ==========
115
116
#include <cerrno>
117
#include <climits>  // PATH_MAX
118
#include <csignal>
119
#include <cstdio>
120
#include <cstdlib>
121
#include <cstring>
122
123
#include <string>
124
#include <vector>
125
126
namespace node {
127
128
using native_module::NativeModuleEnv;
129
130
using v8::EscapableHandleScope;
131
using v8::Function;
132
using v8::FunctionCallbackInfo;
133
using v8::Isolate;
134
using v8::Local;
135
using v8::MaybeLocal;
136
using v8::Object;
137
using v8::String;
138
using v8::Undefined;
139
using v8::V8;
140
using v8::Value;
141
142
namespace per_process {
143
144
// node_revert.h
145
// Bit flag used to track security reverts.
146
unsigned int reverted_cve = 0;
147
148
// util.h
149
// Tells whether the per-process V8::Initialize() is called and
150
// if it is safe to call v8::Isolate::TryGetCurrent().
151
bool v8_initialized = false;
152
153
// node_internals.h
154
// process-relative uptime base in nanoseconds, initialized in node::Start()
155
uint64_t node_start_time;
156
157
#if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
158
PVOID old_vectored_exception_handler;
159
#endif
160
161
// node_v8_platform-inl.h
162
struct V8Platform v8_platform;
163
}  // namespace per_process
164
165
#ifdef __POSIX__
166
void SignalExit(int signo, siginfo_t* info, void* ucontext) {
167
  ResetStdio();
168
  raise(signo);
169
}
170
#endif  // __POSIX__
171
172
10248
MaybeLocal<Value> ExecuteBootstrapper(Environment* env,
173
                                      const char* id,
174
                                      std::vector<Local<String>>* parameters,
175
                                      std::vector<Local<Value>>* arguments) {
176
10248
  EscapableHandleScope scope(env->isolate());
177
  MaybeLocal<Function> maybe_fn =
178
10248
      NativeModuleEnv::LookupAndCompile(env->context(), id, parameters, env);
179
180
  Local<Function> fn;
181
10248
  if (!maybe_fn.ToLocal(&fn)) {
182
    return MaybeLocal<Value>();
183
  }
184
185
  MaybeLocal<Value> result = fn->Call(env->context(),
186
                                      Undefined(env->isolate()),
187
10248
                                      arguments->size(),
188
30744
                                      arguments->data());
189
190
  // If there was an error during bootstrap, it must be unrecoverable
191
  // (e.g. max call stack exceeded). Clear the stack so that the
192
  // AsyncCallbackScope destructor doesn't fail on the id check.
193
  // There are only two ways to have a stack size > 1: 1) the user manually
194
  // called MakeCallback or 2) user awaited during bootstrap, which triggered
195
  // _tickCallback().
196
10006
  if (result.IsEmpty()) {
197
33
    env->async_hooks()->clear_async_id_stack();
198
  }
199
200
10006
  return scope.EscapeMaybe(result);
201
}
202
203
#if HAVE_INSPECTOR
204
6020
int Environment::InitializeInspector(
205
    std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
206
12040
  std::string inspector_path;
207
6020
  bool is_main = !parent_handle;
208
6020
  if (parent_handle) {
209
793
    inspector_path = parent_handle->url();
210
793
    inspector_agent_->SetParentHandle(std::move(parent_handle));
211
  } else {
212
5227
    inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
213
  }
214
215
6020
  CHECK(!inspector_agent_->IsListening());
216
  // Inspector agent can't fail to start, but if it was configured to listen
217
  // right away on the websocket port and fails to bind/etc, this will return
218
  // false.
219
12040
  inspector_agent_->Start(inspector_path,
220
6020
                          options_->debug_options(),
221
12040
                          inspector_host_port(),
222
                          is_main);
223

6101
  if (options_->debug_options().inspector_enabled &&
224
81
      !inspector_agent_->IsListening()) {
225
5
    return 12;  // Signal internal error
226
  }
227
228
6015
  profiler::StartProfilers(this);
229
230
6015
  if (inspector_agent_->options().break_node_first_line) {
231
1
    inspector_agent_->PauseOnNextJavascriptStatement("Break at bootstrap");
232
  }
233
234
6015
  return 0;
235
}
236
#endif  // HAVE_INSPECTOR
237
238
#define ATOMIC_WAIT_EVENTS(V)                                               \
239
  V(kStartWait,           "started")                                        \
240
  V(kWokenUp,             "was woken up by another thread")                 \
241
  V(kTimedOut,            "timed out")                                      \
242
  V(kTerminatedExecution, "was stopped by terminated execution")            \
243
  V(kAPIStopped,          "was stopped through the embedder API")           \
244
  V(kNotEqual,            "did not wait because the values mismatched")     \
245
246
8
static void AtomicsWaitCallback(Isolate::AtomicsWaitEvent event,
247
                                Local<v8::SharedArrayBuffer> array_buffer,
248
                                size_t offset_in_bytes, int64_t value,
249
                                double timeout_in_ms,
250
                                Isolate::AtomicsWaitWakeHandle* stop_handle,
251
                                void* data) {
252
8
  Environment* env = static_cast<Environment*>(data);
253
254
8
  const char* message = "(unknown event)";
255

8
  switch (event) {
256
#define V(key, msg)                         \
257
    case Isolate::AtomicsWaitEvent::key:    \
258
      message = msg;                        \
259
      break;
260
8
    ATOMIC_WAIT_EVENTS(V)
261
#undef V
262
  }
263
264
16
  fprintf(stderr,
265
          "(node:%d) [Thread %" PRIu64 "] Atomics.wait(%p + %zx, %" PRId64
266
              ", %.f) %s\n",
267
8
          static_cast<int>(uv_os_getpid()),
268
          env->thread_id(),
269
16
          array_buffer->GetBackingStore()->Data(),
270
          offset_in_bytes,
271
          value,
272
          timeout_in_ms,
273
          message);
274
8
}
275
276
5991
void Environment::InitializeDiagnostics() {
277
5991
  isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
278
      Environment::BuildEmbedderGraph, this);
279
5991
  if (options_->heap_snapshot_near_heap_limit > 0) {
280
1
    isolate_->AddNearHeapLimitCallback(Environment::NearHeapLimitCallback,
281
                                       this);
282
  }
283
5991
  if (options_->trace_uncaught)
284
3
    isolate_->SetCaptureStackTraceForUncaughtExceptions(true);
285
5991
  if (options_->trace_atomics_wait) {
286
2
    isolate_->SetAtomicsWaitCallback(AtomicsWaitCallback, this);
287
2
    AddCleanupHook([](void* data) {
288
2
      Environment* env = static_cast<Environment*>(data);
289
2
      env->isolate()->SetAtomicsWaitCallback(nullptr, nullptr);
290
2
    }, this);
291
  }
292
293
#if defined HAVE_DTRACE || defined HAVE_ETW
294
  InitDTrace(this);
295
#endif
296
5991
}
297
298
848
MaybeLocal<Value> Environment::BootstrapInternalLoaders() {
299
848
  EscapableHandleScope scope(isolate_);
300
301
  // Create binding loaders
302
  std::vector<Local<String>> loaders_params = {
303
848
      process_string(),
304
848
      FIXED_ONE_BYTE_STRING(isolate_, "getLinkedBinding"),
305
848
      FIXED_ONE_BYTE_STRING(isolate_, "getInternalBinding"),
306
1696
      primordials_string()};
307
  std::vector<Local<Value>> loaders_args = {
308
      process_object(),
309
848
      NewFunctionTemplate(binding::GetLinkedBinding)
310
848
          ->GetFunction(context())
311
          .ToLocalChecked(),
312
848
      NewFunctionTemplate(binding::GetInternalBinding)
313
848
          ->GetFunction(context())
314
          .ToLocalChecked(),
315
5936
      primordials()};
316
317
  // Bootstrap internal loaders
318
  Local<Value> loader_exports;
319
848
  if (!ExecuteBootstrapper(
320
848
           this, "internal/bootstrap/loaders", &loaders_params, &loaders_args)
321
848
           .ToLocal(&loader_exports)) {
322
    return MaybeLocal<Value>();
323
  }
324
848
  CHECK(loader_exports->IsObject());
325
848
  Local<Object> loader_exports_obj = loader_exports.As<Object>();
326
  Local<Value> internal_binding_loader =
327
1696
      loader_exports_obj->Get(context(), internal_binding_string())
328
848
          .ToLocalChecked();
329
848
  CHECK(internal_binding_loader->IsFunction());
330
848
  set_internal_binding_loader(internal_binding_loader.As<Function>());
331
  Local<Value> require =
332
2544
      loader_exports_obj->Get(context(), require_string()).ToLocalChecked();
333
848
  CHECK(require->IsFunction());
334
848
  set_native_module_require(require.As<Function>());
335
336
848
  return scope.Escape(loader_exports);
337
}
338
339
848
MaybeLocal<Value> Environment::BootstrapNode() {
340
848
  EscapableHandleScope scope(isolate_);
341
342
1696
  Local<Object> global = context()->Global();
343
  // TODO(joyeecheung): this can be done in JS land now.
344
1696
  global->Set(context(), FIXED_ONE_BYTE_STRING(isolate_, "global"), global)
345
      .Check();
346
347
  // process, require, internalBinding, primordials
348
  std::vector<Local<String>> node_params = {
349
848
      process_string(),
350
848
      require_string(),
351
848
      internal_binding_string(),
352
1696
      primordials_string()};
353
  std::vector<Local<Value>> node_args = {
354
      process_object(),
355
      native_module_require(),
356
      internal_binding_loader(),
357
5088
      primordials()};
358
359
  MaybeLocal<Value> result = ExecuteBootstrapper(
360
848
      this, "internal/bootstrap/node", &node_params, &node_args);
361
362
848
  if (result.IsEmpty()) {
363
    return MaybeLocal<Value>();
364
  }
365
366
848
  if (!no_browser_globals()) {
367
    result = ExecuteBootstrapper(
368
848
        this, "internal/bootstrap/browser", &node_params, &node_args);
369
370
848
    if (result.IsEmpty()) {
371
      return MaybeLocal<Value>();
372
    }
373
  }
374
375
  // TODO(joyeecheung): skip these in the snapshot building for workers.
376
  auto thread_switch_id =
377
848
      is_main_thread() ? "internal/bootstrap/switches/is_main_thread"
378
848
                       : "internal/bootstrap/switches/is_not_main_thread";
379
  result =
380
848
      ExecuteBootstrapper(this, thread_switch_id, &node_params, &node_args);
381
382
848
  if (result.IsEmpty()) {
383
    return MaybeLocal<Value>();
384
  }
385
386
  auto process_state_switch_id =
387
848
      owns_process_state()
388
848
          ? "internal/bootstrap/switches/does_own_process_state"
389
848
          : "internal/bootstrap/switches/does_not_own_process_state";
390
  result = ExecuteBootstrapper(
391
848
      this, process_state_switch_id, &node_params, &node_args);
392
393
848
  if (result.IsEmpty()) {
394
    return MaybeLocal<Value>();
395
  }
396
397
848
  Local<String> env_string = FIXED_ONE_BYTE_STRING(isolate_, "env");
398
  Local<Object> env_var_proxy;
399
2544
  if (!CreateEnvVarProxy(context(), isolate_).ToLocal(&env_var_proxy) ||
400

3392
      process_object()->Set(context(), env_string, env_var_proxy).IsNothing()) {
401
    return MaybeLocal<Value>();
402
  }
403
404
848
  return scope.EscapeMaybe(result);
405
}
406
407
848
MaybeLocal<Value> Environment::RunBootstrapping() {
408
848
  EscapableHandleScope scope(isolate_);
409
410
848
  CHECK(!has_run_bootstrapping_code());
411
412
1696
  if (BootstrapInternalLoaders().IsEmpty()) {
413
    return MaybeLocal<Value>();
414
  }
415
416
  Local<Value> result;
417
1696
  if (!BootstrapNode().ToLocal(&result)) {
418
    return MaybeLocal<Value>();
419
  }
420
421
  // Make sure that no request or handle is created during bootstrap -
422
  // if necessary those should be done in pre-execution.
423
  // Usually, doing so would trigger the checks present in the ReqWrap and
424
  // HandleWrap classes, so this is only a consistency check.
425
848
  CHECK(req_wrap_queue()->IsEmpty());
426
848
  CHECK(handle_wrap_queue()->IsEmpty());
427
428
848
  DoneBootstrapping();
429
430
848
  return scope.Escape(result);
431
}
432
433
5982
void MarkBootstrapComplete(const FunctionCallbackInfo<Value>& args) {
434
5982
  Environment* env = Environment::GetCurrent(args);
435
5982
  env->performance_state()->Mark(
436
      performance::NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE);
437
5982
}
438
439
static
440
5991
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
441
5991
  EscapableHandleScope scope(env->isolate());
442
5991
  CHECK_NOT_NULL(main_script_id);
443
444
  std::vector<Local<String>> parameters = {
445
5991
      env->process_string(),
446
5991
      env->require_string(),
447
5991
      env->internal_binding_string(),
448
5991
      env->primordials_string(),
449
11742
      FIXED_ONE_BYTE_STRING(env->isolate(), "markBootstrapComplete")};
450
451
  std::vector<Local<Value>> arguments = {
452
      env->process_object(),
453
      env->native_module_require(),
454
      env->internal_binding_loader(),
455
      env->primordials(),
456
5991
      env->NewFunctionTemplate(MarkBootstrapComplete)
457
5991
          ->GetFunction(env->context())
458
35946
          .ToLocalChecked()};
459
460
  return scope.EscapeMaybe(
461
11742
      ExecuteBootstrapper(env, main_script_id, &parameters, &arguments));
462
}
463
464
5991
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
465
  InternalCallbackScope callback_scope(
466
      env,
467
      Object::New(env->isolate()),
468
      { 1, 0 },
469
11740
      InternalCallbackScope::kSkipAsyncHooks);
470
471
5991
  if (cb != nullptr) {
472
22
    EscapableHandleScope scope(env->isolate());
473
474
44
    if (StartExecution(env, "internal/bootstrap/environment").IsEmpty())
475
      return {};
476
477
    StartExecutionCallbackInfo info = {
478
22
      env->process_object(),
479
22
      env->native_module_require(),
480
    };
481
482
42
    return scope.EscapeMaybe(cb(info));
483
  }
484
485
5969
  if (env->worker_context() != nullptr) {
486
789
    return StartExecution(env, "internal/main/worker_thread");
487
  }
488
489
10120
  std::string first_argv;
490
5180
  if (env->argv().size() > 1) {
491
4694
    first_argv = env->argv()[1];
492
  }
493
494
5180
  if (first_argv == "inspect") {
495
36
    return StartExecution(env, "internal/main/inspect");
496
  }
497
498
5144
  if (per_process::cli_options->build_snapshot) {
499
    return StartExecution(env, "internal/main/mksnapshot");
500
  }
501
502
5144
  if (per_process::cli_options->print_help) {
503
1
    return StartExecution(env, "internal/main/print_help");
504
  }
505
506
507
5143
  if (env->options()->prof_process) {
508
1
    return StartExecution(env, "internal/main/prof_process");
509
  }
510
511
  // -e/--eval without -i/--interactive
512


5142
  if (env->options()->has_eval_string && !env->options()->force_repl) {
513
453
    return StartExecution(env, "internal/main/eval_string");
514
  }
515
516
4689
  if (env->options()->syntax_check_only) {
517
36
    return StartExecution(env, "internal/main/check_syntax");
518
  }
519
520
4653
  if (env->options()->test_runner) {
521
5
    return StartExecution(env, "internal/main/test_runner");
522
  }
523
524

4648
  if (!first_argv.empty() && first_argv != "-") {
525
4605
    return StartExecution(env, "internal/main/run_main_module");
526
  }
527
528


43
  if (env->options()->force_repl || uv_guess_handle(STDIN_FILENO) == UV_TTY) {
529
26
    return StartExecution(env, "internal/main/repl");
530
  }
531
532
17
  return StartExecution(env, "internal/main/eval_stdin");
533
}
534
535
#ifdef __POSIX__
536
typedef void (*sigaction_cb)(int signo, siginfo_t* info, void* ucontext);
537
#endif
538
#if NODE_USE_V8_WASM_TRAP_HANDLER
539
#if defined(_WIN32)
540
static LONG TrapWebAssemblyOrContinue(EXCEPTION_POINTERS* exception) {
541
  if (v8::TryHandleWebAssemblyTrapWindows(exception)) {
542
    return EXCEPTION_CONTINUE_EXECUTION;
543
  }
544
  return EXCEPTION_CONTINUE_SEARCH;
545
}
546
#else
547
static std::atomic<sigaction_cb> previous_sigsegv_action;
548
549
6
void TrapWebAssemblyOrContinue(int signo, siginfo_t* info, void* ucontext) {
550
6
  if (!v8::TryHandleWebAssemblyTrapPosix(signo, info, ucontext)) {
551
6
    sigaction_cb prev = previous_sigsegv_action.load();
552
6
    if (prev != nullptr) {
553
6
      prev(signo, info, ucontext);
554
    } else {
555
      // Reset to the default signal handler, i.e. cause a hard crash.
556
      struct sigaction sa;
557
      memset(&sa, 0, sizeof(sa));
558
      sa.sa_handler = SIG_DFL;
559
      CHECK_EQ(sigaction(signo, &sa, nullptr), 0);
560
561
      ResetStdio();
562
      raise(signo);
563
    }
564
  }
565
6
}
566
#endif  // defined(_WIN32)
567
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
568
569
#ifdef __POSIX__
570
16119
void RegisterSignalHandler(int signal,
571
                           sigaction_cb handler,
572
                           bool reset_handler) {
573
16119
  CHECK_NOT_NULL(handler);
574
#if NODE_USE_V8_WASM_TRAP_HANDLER
575
16119
  if (signal == SIGSEGV) {
576
4
    CHECK(previous_sigsegv_action.is_lock_free());
577
4
    CHECK(!reset_handler);
578
4
    previous_sigsegv_action.store(handler);
579
4
    return;
580
  }
581
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
582
  struct sigaction sa;
583
16115
  memset(&sa, 0, sizeof(sa));
584
16115
  sa.sa_sigaction = handler;
585
16115
  sa.sa_flags = reset_handler ? SA_RESETHAND : 0;
586
16115
  sigfillset(&sa.sa_mask);
587
16115
  CHECK_EQ(sigaction(signal, &sa, nullptr), 0);
588
}
589
#endif  // __POSIX__
590
591
#ifdef __POSIX__
592
static struct {
593
  int flags;
594
  bool isatty;
595
  struct stat stat;
596
  struct termios termios;
597
} stdio[1 + STDERR_FILENO];
598
#endif  // __POSIX__
599
600
601
5244
inline void PlatformInit() {
602
#ifdef __POSIX__
603
#if HAVE_INSPECTOR
604
  sigset_t sigmask;
605
5244
  sigemptyset(&sigmask);
606
5244
  sigaddset(&sigmask, SIGUSR1);
607
5244
  const int err = pthread_sigmask(SIG_SETMASK, &sigmask, nullptr);
608
#endif  // HAVE_INSPECTOR
609
610
  // Make sure file descriptors 0-2 are valid before we start logging anything.
611
20976
  for (auto& s : stdio) {
612
15732
    const int fd = &s - stdio;
613
15732
    if (fstat(fd, &s.stat) == 0)
614
15730
      continue;
615
    // Anything but EBADF means something is seriously wrong.  We don't
616
    // have to special-case EINTR, fstat() is not interruptible.
617
2
    if (errno != EBADF)
618
      ABORT();
619
2
    if (fd != open("/dev/null", O_RDWR))
620
      ABORT();
621
2
    if (fstat(fd, &s.stat) != 0)
622
      ABORT();
623
  }
624
625
#if HAVE_INSPECTOR
626
5244
  CHECK_EQ(err, 0);
627
#endif  // HAVE_INSPECTOR
628
629
  // TODO(addaleax): NODE_SHARED_MODE does not really make sense here.
630
#ifndef NODE_SHARED_MODE
631
  // Restore signal dispositions, the parent process may have changed them.
632
  struct sigaction act;
633
5244
  memset(&act, 0, sizeof(act));
634
635
  // The hard-coded upper limit is because NSIG is not very reliable; on Linux,
636
  // it evaluates to 32, 34 or 64, depending on whether RT signals are enabled.
637
  // Counting up to SIGRTMIN doesn't work for the same reason.
638
167808
  for (unsigned nr = 1; nr < kMaxSignal; nr += 1) {
639

162564
    if (nr == SIGKILL || nr == SIGSTOP)
640
10488
      continue;
641

152076
    act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
642
152076
    CHECK_EQ(0, sigaction(nr, &act, nullptr));
643
  }
644
#endif  // !NODE_SHARED_MODE
645
646
  // Record the state of the stdio file descriptors so we can restore it
647
  // on exit.  Needs to happen before installing signal handlers because
648
  // they make use of that information.
649
20976
  for (auto& s : stdio) {
650
15732
    const int fd = &s - stdio;
651
    int err;
652
653
    do
654
15732
      s.flags = fcntl(fd, F_GETFL);
655

15732
    while (s.flags == -1 && errno == EINTR);  // NOLINT
656
15732
    CHECK_NE(s.flags, -1);
657
658
15732
    if (uv_guess_handle(fd) != UV_TTY) continue;
659
120
    s.isatty = true;
660
661
    do
662
120
      err = tcgetattr(fd, &s.termios);
663

120
    while (err == -1 && errno == EINTR);  // NOLINT
664
120
    CHECK_EQ(err, 0);
665
  }
666
667
5244
  RegisterSignalHandler(SIGINT, SignalExit, true);
668
5244
  RegisterSignalHandler(SIGTERM, SignalExit, true);
669
670
#if NODE_USE_V8_WASM_TRAP_HANDLER
671
#if defined(_WIN32)
672
  {
673
    constexpr ULONG first = TRUE;
674
    per_process::old_vectored_exception_handler =
675
        AddVectoredExceptionHandler(first, TrapWebAssemblyOrContinue);
676
  }
677
#else
678
  // Tell V8 to disable emitting WebAssembly
679
  // memory bounds checks. This means that we have
680
  // to catch the SIGSEGV in TrapWebAssemblyOrContinue
681
  // and pass the signal context to V8.
682
  {
683
    struct sigaction sa;
684
5244
    memset(&sa, 0, sizeof(sa));
685
5244
    sa.sa_sigaction = TrapWebAssemblyOrContinue;
686
5244
    sa.sa_flags = SA_SIGINFO;
687
5244
    CHECK_EQ(sigaction(SIGSEGV, &sa, nullptr), 0);
688
  }
689
#endif  // defined(_WIN32)
690
5244
  V8::EnableWebAssemblyTrapHandler(false);
691
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
692
693
  // Raise the open file descriptor limit.
694
  struct rlimit lim;
695

5244
  if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
696
    // Do a binary search for the limit.
697
    rlim_t min = lim.rlim_cur;
698
    rlim_t max = 1 << 20;
699
    // But if there's a defined upper bound, don't search, just set it.
700
    if (lim.rlim_max != RLIM_INFINITY) {
701
      min = lim.rlim_max;
702
      max = lim.rlim_max;
703
    }
704
    do {
705
      lim.rlim_cur = min + (max - min) / 2;
706
      if (setrlimit(RLIMIT_NOFILE, &lim)) {
707
        max = lim.rlim_cur;
708
      } else {
709
        min = lim.rlim_cur;
710
      }
711
    } while (min + 1 < max);
712
  }
713
#endif  // __POSIX__
714
#ifdef _WIN32
715
  for (int fd = 0; fd <= 2; ++fd) {
716
    auto handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
717
    if (handle == INVALID_HANDLE_VALUE ||
718
        GetFileType(handle) == FILE_TYPE_UNKNOWN) {
719
      // Ignore _close result. If it fails or not depends on used Windows
720
      // version. We will just check _open result.
721
      _close(fd);
722
      if (fd != _open("nul", _O_RDWR))
723
        ABORT();
724
    }
725
  }
726
#endif  // _WIN32
727
5244
}
728
729
730
// Safe to call more than once and from signal handlers.
731
9847
void ResetStdio() {
732
9847
  uv_tty_reset_mode();
733
#ifdef __POSIX__
734
39388
  for (auto& s : stdio) {
735
29541
    const int fd = &s - stdio;
736
737
    struct stat tmp;
738
29541
    if (-1 == fstat(fd, &tmp)) {
739
      CHECK_EQ(errno, EBADF);  // Program closed file descriptor.
740
6
      continue;
741
    }
742
743
29541
    bool is_same_file =
744

29541
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
745
29541
    if (!is_same_file) continue;  // Program reopened file descriptor.
746
747
    int flags;
748
    do
749
29535
      flags = fcntl(fd, F_GETFL);
750

29535
    while (flags == -1 && errno == EINTR);  // NOLINT
751
29535
    CHECK_NE(flags, -1);
752
753
    // Restore the O_NONBLOCK flag if it changed.
754
29535
    if (O_NONBLOCK & (flags ^ s.flags)) {
755
1218
      flags &= ~O_NONBLOCK;
756
1218
      flags |= s.flags & O_NONBLOCK;
757
758
      int err;
759
      do
760
1218
        err = fcntl(fd, F_SETFL, flags);
761

1218
      while (err == -1 && errno == EINTR);  // NOLINT
762
1218
      CHECK_NE(err, -1);
763
    }
764
765
29535
    if (s.isatty) {
766
      sigset_t sa;
767
      int err;
768
769
      // We might be a background job that doesn't own the TTY so block SIGTTOU
770
      // before making the tcsetattr() call, otherwise that signal suspends us.
771
228
      sigemptyset(&sa);
772
228
      sigaddset(&sa, SIGTTOU);
773
774
228
      CHECK_EQ(0, pthread_sigmask(SIG_BLOCK, &sa, nullptr));
775
      do
776
228
        err = tcsetattr(fd, TCSANOW, &s.termios);
777

228
      while (err == -1 && errno == EINTR);  // NOLINT
778
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
779
780
      // Normally we expect err == 0. But if macOS App Sandbox is enabled,
781
      // tcsetattr will fail with err == -1 and errno == EPERM.
782


228
      CHECK_IMPLIES(err != 0, err == -1 && errno == EPERM);
783
    }
784
  }
785
#endif  // __POSIX__
786
9847
}
787
788
789
10370
int ProcessGlobalArgs(std::vector<std::string>* args,
790
                      std::vector<std::string>* exec_args,
791
                      std::vector<std::string>* errors,
792
                      OptionEnvvarSettings settings) {
793
  // Parse a few arguments which are specific to Node.
794
20740
  std::vector<std::string> v8_args;
795
796
20740
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
797
10370
  options_parser::Parse(
798
      args,
799
      exec_args,
800
      &v8_args,
801
      per_process::cli_options.get(),
802
      settings,
803
      errors);
804
805
10370
  if (!errors->empty()) return 9;
806
807
20640
  std::string revert_error;
808
10320
  for (const std::string& cve : per_process::cli_options->security_reverts) {
809
1
    Revert(cve.c_str(), &revert_error);
810
1
    if (!revert_error.empty()) {
811
1
      errors->emplace_back(std::move(revert_error));
812
1
      return 12;
813
    }
814
  }
815
816
20637
  if (per_process::cli_options->disable_proto != "delete" &&
817

20637
      per_process::cli_options->disable_proto != "throw" &&
818
10317
      per_process::cli_options->disable_proto != "") {
819
    errors->emplace_back("invalid mode passed to --disable-proto");
820
    return 12;
821
  }
822
823
  // TODO(aduh95): remove this when the harmony-import-assertions flag
824
  // is removed in V8.
825
20638
  if (std::find(v8_args.begin(), v8_args.end(),
826
10319
                "--no-harmony-import-assertions") == v8_args.end()) {
827
10319
    v8_args.emplace_back("--harmony-import-assertions");
828
  }
829
830
20638
  auto env_opts = per_process::cli_options->per_isolate->per_env;
831
20638
  if (std::find(v8_args.begin(), v8_args.end(),
832

20620
                "--abort-on-uncaught-exception") != v8_args.end() ||
833
10319
      std::find(v8_args.begin(), v8_args.end(),
834
20620
                "--abort_on_uncaught_exception") != v8_args.end()) {
835
21
    env_opts->abort_on_uncaught_exception = true;
836
  }
837
838
#ifdef __POSIX__
839
  // Block SIGPROF signals when sleeping in epoll_wait/kevent/etc.  Avoids the
840
  // performance penalty of frequent EINTR wakeups when the profiler is running.
841
  // Only do this for v8.log profiling, as it breaks v8::CpuProfiler users.
842
10319
  if (std::find(v8_args.begin(), v8_args.end(), "--prof") != v8_args.end()) {
843
2
    uv_loop_configure(uv_default_loop(), UV_LOOP_BLOCK_SIGNAL, SIGPROF);
844
  }
845
#endif
846
847
20638
  std::vector<char*> v8_args_as_char_ptr(v8_args.size());
848
10319
  if (v8_args.size() > 0) {
849
31093
    for (size_t i = 0; i < v8_args.size(); ++i)
850
20774
      v8_args_as_char_ptr[i] = &v8_args[i][0];
851
10319
    int argc = v8_args.size();
852
10319
    V8::SetFlagsFromCommandLine(&argc, &v8_args_as_char_ptr[0], true);
853
10319
    v8_args_as_char_ptr.resize(argc);
854
  }
855
856
  // Anything that's still in v8_argv is not a V8 or a node option.
857
10320
  for (size_t i = 1; i < v8_args_as_char_ptr.size(); i++)
858
1
    errors->push_back("bad option: " + std::string(v8_args_as_char_ptr[i]));
859
860
10319
  if (v8_args_as_char_ptr.size() > 1) return 9;
861
862
10318
  return 0;
863
}
864
865
static std::atomic_bool init_called{false};
866
867
8
int InitializeNodeWithArgs(std::vector<std::string>* argv,
868
                           std::vector<std::string>* exec_argv,
869
                           std::vector<std::string>* errors) {
870
8
  return InitializeNodeWithArgs(argv, exec_argv, errors,
871
8
                                ProcessFlags::kNoFlags);
872
}
873
874
5252
int InitializeNodeWithArgs(std::vector<std::string>* argv,
875
                           std::vector<std::string>* exec_argv,
876
                           std::vector<std::string>* errors,
877
                           ProcessFlags::Flags flags) {
878
  // Make sure InitializeNodeWithArgs() is called only once.
879
5252
  CHECK(!init_called.exchange(true));
880
881
  // Initialize node_start_time to get relative uptime.
882
5252
  per_process::node_start_time = uv_hrtime();
883
884
  // Register built-in modules
885
5252
  binding::RegisterBuiltinModules();
886
887
  // Make inherited handles noninheritable.
888
5252
  if (!(flags & ProcessFlags::kEnableStdioInheritance))
889
5252
    uv_disable_stdio_inheritance();
890
891
  // Cache the original command line to be
892
  // used in diagnostic reports.
893
5252
  per_process::cli_options->cmdline = *argv;
894
895
#if defined(NODE_V8_OPTIONS)
896
  // Should come before the call to V8::SetFlagsFromCommandLine()
897
  // so the user can disable a flag --foo at run-time by passing
898
  // --no_foo from the command line.
899
  V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1);
900
#endif
901
902
5252
  HandleEnvOptions(per_process::cli_options->per_isolate->per_env);
903
904
#if !defined(NODE_WITHOUT_NODE_OPTIONS)
905
5252
  if (!(flags & ProcessFlags::kDisableNodeOptionsEnv)) {
906
5252
    std::string node_options;
907
908
5252
    if (credentials::SafeGetenv("NODE_OPTIONS", &node_options)) {
909
      std::vector<std::string> env_argv =
910
5135
          ParseNodeOptionsEnvVar(node_options, errors);
911
912
5135
      if (!errors->empty()) return 9;
913
914
      // [0] is expected to be the program name, fill it in from the real argv.
915
5135
      env_argv.insert(env_argv.begin(), argv->at(0));
916
917
5135
      const int exit_code = ProcessGlobalArgs(&env_argv,
918
                                              nullptr,
919
                                              errors,
920
                                              kAllowedInEnvironment);
921
5135
      if (exit_code != 0) return exit_code;
922
    }
923
  }
924
#endif
925
926
5235
  if (!(flags & ProcessFlags::kDisableCLIOptions)) {
927
5235
    const int exit_code = ProcessGlobalArgs(argv,
928
                                            exec_argv,
929
                                            errors,
930
                                            kDisallowedInEnvironment);
931
5235
    if (exit_code != 0) return exit_code;
932
  }
933
934
  // Set the process.title immediately after processing argv if --title is set.
935
5200
  if (!per_process::cli_options->title.empty())
936
2
    uv_set_process_title(per_process::cli_options->title.c_str());
937
938
#if defined(NODE_HAVE_I18N_SUPPORT)
939
5200
  if (!(flags & ProcessFlags::kNoICU)) {
940
    // If the parameter isn't given, use the env variable.
941
5200
    if (per_process::cli_options->icu_data_dir.empty())
942
5200
      credentials::SafeGetenv("NODE_ICU_DATA",
943
5200
                              &per_process::cli_options->icu_data_dir);
944
945
#ifdef NODE_ICU_DEFAULT_DATA_DIR
946
    // If neither the CLI option nor the environment variable was specified,
947
    // fall back to the configured default
948
    if (per_process::cli_options->icu_data_dir.empty()) {
949
      // Check whether the NODE_ICU_DEFAULT_DATA_DIR contains the right data
950
      // file and can be read.
951
      static const char full_path[] =
952
          NODE_ICU_DEFAULT_DATA_DIR "/" U_ICUDATA_NAME ".dat";
953
954
      FILE* f = fopen(full_path, "rb");
955
956
      if (f != nullptr) {
957
        fclose(f);
958
        per_process::cli_options->icu_data_dir = NODE_ICU_DEFAULT_DATA_DIR;
959
      }
960
    }
961
#endif  // NODE_ICU_DEFAULT_DATA_DIR
962
963
    // Initialize ICU.
964
    // If icu_data_dir is empty here, it will load the 'minimal' data.
965
5200
    if (!i18n::InitializeICUDirectory(per_process::cli_options->icu_data_dir)) {
966
      errors->push_back("could not initialize ICU "
967
                        "(check NODE_ICU_DATA or --icu-data-dir parameters)\n");
968
      return 9;
969
    }
970
5200
    per_process::metadata.versions.InitializeIntlVersions();
971
  }
972
973
# ifndef __POSIX__
974
  std::string tz;
975
  if (credentials::SafeGetenv("TZ", &tz) && !tz.empty()) {
976
    i18n::SetDefaultTimeZone(tz.c_str());
977
  }
978
# endif
979
980
#endif  // defined(NODE_HAVE_I18N_SUPPORT)
981
982
  // We should set node_is_initialized here instead of in node::Start,
983
  // otherwise embedders using node::Init to initialize everything will not be
984
  // able to set it and native modules will not load for them.
985
5200
  node_is_initialized = true;
986
5200
  return 0;
987
}
988
989
5244
InitializationResult InitializeOncePerProcess(int argc, char** argv) {
990
5244
  return InitializeOncePerProcess(argc, argv, kDefaultInitialization);
991
}
992
993
5244
InitializationResult InitializeOncePerProcess(
994
  int argc,
995
  char** argv,
996
  InitializationSettingsFlags flags,
997
  ProcessFlags::Flags process_flags) {
998
5244
  uint64_t init_flags = flags;
999
5244
  if (init_flags & kDefaultInitialization) {
1000
5244
    init_flags = init_flags | kInitializeV8 | kInitOpenSSL | kRunPlatformInit;
1001
  }
1002
1003
  // Initialized the enabled list for Debug() calls with system
1004
  // environment variables.
1005
5244
  per_process::enabled_debug_list.Parse(nullptr);
1006
1007
5244
  atexit(ResetStdio);
1008
1009
5244
  if (init_flags & kRunPlatformInit)
1010
5244
    PlatformInit();
1011
1012
5244
  CHECK_GT(argc, 0);
1013
1014
  // Hack around with the argv pointer. Used for process.title = "blah".
1015
5244
  argv = uv_setup_args(argc, argv);
1016
1017
5244
  InitializationResult result;
1018
5244
  result.args = std::vector<std::string>(argv, argv + argc);
1019
10488
  std::vector<std::string> errors;
1020
1021
  // This needs to run *before* V8::Initialize().
1022
  {
1023
5244
    result.exit_code = InitializeNodeWithArgs(
1024
        &(result.args), &(result.exec_args), &errors, process_flags);
1025
5297
    for (const std::string& error : errors)
1026
53
      fprintf(stderr, "%s: %s\n", result.args.at(0).c_str(), error.c_str());
1027
5244
    if (result.exit_code != 0) {
1028
52
      result.early_return = true;
1029
52
      return result;
1030
    }
1031
  }
1032
1033

10383
  if (per_process::cli_options->use_largepages == "on" ||
1034
5191
      per_process::cli_options->use_largepages == "silent") {
1035
1
    int result = node::MapStaticCodeToLargePages();
1036

1
    if (per_process::cli_options->use_largepages == "on" && result != 0) {
1037
      fprintf(stderr, "%s\n", node::LargePagesError(result));
1038
    }
1039
  }
1040
1041
5192
  if (per_process::cli_options->print_version) {
1042
3
    printf("%s\n", NODE_VERSION);
1043
3
    result.exit_code = 0;
1044
3
    result.early_return = true;
1045
3
    return result;
1046
  }
1047
1048
5189
  if (per_process::cli_options->print_bash_completion) {
1049
2
    std::string completion = options_parser::GetBashCompletion();
1050
1
    printf("%s\n", completion.c_str());
1051
1
    result.exit_code = 0;
1052
1
    result.early_return = true;
1053
1
    return result;
1054
  }
1055
1056
5188
  if (per_process::cli_options->print_v8_help) {
1057
    V8::SetFlagsFromString("--help", static_cast<size_t>(6));
1058
    result.exit_code = 0;
1059
    result.early_return = true;
1060
    return result;
1061
  }
1062
1063
5188
  if (init_flags & kInitOpenSSL) {
1064
#if HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
1065
    {
1066
10376
      std::string extra_ca_certs;
1067
5188
      if (credentials::SafeGetenv("NODE_EXTRA_CA_CERTS", &extra_ca_certs))
1068
4
        crypto::UseExtraCaCerts(extra_ca_certs);
1069
    }
1070
    // In the case of FIPS builds we should make sure
1071
    // the random source is properly initialized first.
1072
#if OPENSSL_VERSION_MAJOR >= 3
1073
    // Call OPENSSL_init_crypto to initialize OPENSSL_INIT_LOAD_CONFIG to
1074
    // avoid the default behavior where errors raised during the parsing of the
1075
    // OpenSSL configuration file are not propagated and cannot be detected.
1076
    //
1077
    // If FIPS is configured the OpenSSL configuration file will have an
1078
    // .include pointing to the fipsmodule.cnf file generated by the openssl
1079
    // fipsinstall command. If the path to this file is incorrect no error
1080
    // will be reported.
1081
    //
1082
    // For Node.js this will mean that EntropySource will be called by V8 as
1083
    // part of its initialization process, and EntropySource will in turn call
1084
    // CheckEntropy. CheckEntropy will call RAND_status which will now always
1085
    // return 0, leading to an endless loop and the node process will appear to
1086
    // hang/freeze.
1087
5188
    std::string env_openssl_conf;
1088
5188
    credentials::SafeGetenv("OPENSSL_CONF", &env_openssl_conf);
1089
1090
5188
    bool has_cli_conf = !per_process::cli_options->openssl_config.empty();
1091

5188
    if (has_cli_conf || !env_openssl_conf.empty()) {
1092
      OPENSSL_INIT_SETTINGS* settings = OPENSSL_INIT_new();
1093
      OPENSSL_INIT_set_config_file_flags(settings, CONF_MFLAGS_DEFAULT_SECTION);
1094
      if (has_cli_conf) {
1095
        const char* conf = per_process::cli_options->openssl_config.c_str();
1096
        OPENSSL_INIT_set_config_filename(settings, conf);
1097
      }
1098
      OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, settings);
1099
      OPENSSL_INIT_free(settings);
1100
1101
      if (ERR_peek_error() != 0) {
1102
        result.exit_code = ERR_GET_REASON(ERR_peek_error());
1103
        result.early_return = true;
1104
        fprintf(stderr, "OpenSSL configuration error:\n");
1105
        ERR_print_errors_fp(stderr);
1106
        return result;
1107
      }
1108
    }
1109
#else  // OPENSSL_VERSION_MAJOR < 3
1110
    if (FIPS_mode()) {
1111
      OPENSSL_init();
1112
    }
1113
#endif
1114
5188
  if (!crypto::ProcessFipsOptions()) {
1115
2
      result.exit_code = ERR_GET_REASON(ERR_peek_error());
1116
2
      result.early_return = true;
1117
2
      fprintf(stderr, "OpenSSL error when trying to enable FIPS:\n");
1118
2
      ERR_print_errors_fp(stderr);
1119
2
      return result;
1120
  }
1121
1122
  // V8 on Windows doesn't have a good source of entropy. Seed it from
1123
  // OpenSSL's pool.
1124
5186
  V8::SetEntropySource(crypto::EntropySource);
1125
#endif  // HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
1126
}
1127
5186
  per_process::v8_platform.Initialize(
1128
5186
      static_cast<int>(per_process::cli_options->v8_thread_pool_size));
1129
5186
  if (init_flags & kInitializeV8) {
1130
    V8::Initialize();
1131
  }
1132
1133
5186
  performance::performance_v8_start = PERFORMANCE_NOW();
1134
5186
  per_process::v8_initialized = true;
1135
1136
5186
  return result;
1137
}
1138
1139
4592
void TearDownOncePerProcess() {
1140
4592
  per_process::v8_initialized = false;
1141
4592
  V8::Dispose();
1142
1143
#if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
1144
  RemoveVectoredExceptionHandler(per_process::old_vectored_exception_handler);
1145
#endif
1146
1147
  // uv_run cannot be called from the time before the beforeExit callback
1148
  // runs until the program exits unless the event loop has any referenced
1149
  // handles after beforeExit terminates. This prevents unrefed timers
1150
  // that happen to terminate during shutdown from being run unsafely.
1151
  // Since uv_run cannot be called, uv_async handles held by the platform
1152
  // will never be fully cleaned up.
1153
4592
  per_process::v8_platform.Dispose();
1154
4592
}
1155
1156
5238
int Start(int argc, char** argv) {
1157
9882
  InitializationResult result = InitializeOncePerProcess(argc, argv);
1158
5238
  if (result.early_return) {
1159
58
    return result.exit_code;
1160
  }
1161
1162
5180
  if (per_process::cli_options->build_snapshot) {
1163
    fprintf(stderr,
1164
            "--build-snapshot is not yet supported in the node binary\n");
1165
    return 1;
1166
  }
1167
1168
  {
1169
5180
    bool use_node_snapshot = per_process::cli_options->node_snapshot;
1170
    const SnapshotData* snapshot_data =
1171
5180
        use_node_snapshot ? SnapshotBuilder::GetEmbeddedSnapshotData()
1172
5180
                          : nullptr;
1173
5180
    uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);
1174
1175
5180
    if (snapshot_data != nullptr) {
1176
5178
      native_module::NativeModuleEnv::RefreshCodeCache(
1177
5178
          snapshot_data->code_cache);
1178
    }
1179
    NodeMainInstance main_instance(snapshot_data,
1180
                                   uv_default_loop(),
1181
5180
                                   per_process::v8_platform.Platform(),
1182
                                   result.args,
1183
5180
                                   result.exec_args);
1184
5180
    result.exit_code = main_instance.Run();
1185
  }
1186
1187
4586
  TearDownOncePerProcess();
1188
4586
  return result.exit_code;
1189
}
1190
1191
397
int Stop(Environment* env) {
1192
397
  env->ExitEnv();
1193
397
  return 0;
1194
}
1195
1196
}  // namespace node
1197
1198
#if !HAVE_INSPECTOR
1199
void Initialize() {}
1200
1201
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1202
#endif  // !HAVE_INSPECTOR