GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.cc Lines: 385 448 85.9 %
Date: 2022-04-05 04:14:57 Branches: 224 337 66.5 %

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 "memory_tracker-inl.h"
29
#include "histogram-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_v8_platform-inl.h"
42
#include "node_version.h"
43
44
#if HAVE_OPENSSL
45
#include "allocated_buffer-inl.h"  // Inlined functions needed by node_crypto.h
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
8697
MaybeLocal<Value> ExecuteBootstrapper(Environment* env,
173
                                      const char* id,
174
                                      std::vector<Local<String>>* parameters,
175
                                      std::vector<Local<Value>>* arguments) {
176
8697
  EscapableHandleScope scope(env->isolate());
177
  MaybeLocal<Function> maybe_fn =
178
8697
      NativeModuleEnv::LookupAndCompile(env->context(), id, parameters, env);
179
180
  Local<Function> fn;
181
8697
  if (!maybe_fn.ToLocal(&fn)) {
182
    return MaybeLocal<Value>();
183
  }
184
185
  MaybeLocal<Value> result = fn->Call(env->context(),
186
                                      Undefined(env->isolate()),
187
8697
                                      arguments->size(),
188
26091
                                      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
8459
  if (result.IsEmpty()) {
197
33
    env->async_hooks()->clear_async_id_stack();
198
  }
199
200
8459
  return scope.EscapeMaybe(result);
201
}
202
203
#if HAVE_INSPECTOR
204
5592
int Environment::InitializeInspector(
205
    std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
206
11184
  std::string inspector_path;
207
5592
  bool is_main = !parent_handle;
208
5592
  if (parent_handle) {
209
569
    inspector_path = parent_handle->url();
210
569
    inspector_agent_->SetParentHandle(std::move(parent_handle));
211
  } else {
212
5023
    inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
213
  }
214
215
5592
  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
11184
  inspector_agent_->Start(inspector_path,
220
5592
                          options_->debug_options(),
221
11184
                          inspector_host_port(),
222
                          is_main);
223

5673
  if (options_->debug_options().inspector_enabled &&
224
81
      !inspector_agent_->IsListening()) {
225
5
    return 12;  // Signal internal error
226
  }
227
228
5587
  profiler::StartProfilers(this);
229
230
5587
  if (inspector_agent_->options().break_node_first_line) {
231
1
    inspector_agent_->PauseOnNextJavascriptStatement("Break at bootstrap");
232
  }
233
234
5587
  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
5565
void Environment::InitializeDiagnostics() {
277
5565
  isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
278
      Environment::BuildEmbedderGraph, this);
279
5565
  if (options_->heap_snapshot_near_heap_limit > 0) {
280
1
    isolate_->AddNearHeapLimitCallback(Environment::NearHeapLimitCallback,
281
                                       this);
282
  }
283
5565
  if (options_->trace_uncaught)
284
3
    isolate_->SetCaptureStackTraceForUncaughtExceptions(true);
285
5565
  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
5565
}
297
298
623
MaybeLocal<Value> Environment::BootstrapInternalLoaders() {
299
623
  EscapableHandleScope scope(isolate_);
300
301
  // Create binding loaders
302
  std::vector<Local<String>> loaders_params = {
303
623
      process_string(),
304
623
      FIXED_ONE_BYTE_STRING(isolate_, "getLinkedBinding"),
305
623
      FIXED_ONE_BYTE_STRING(isolate_, "getInternalBinding"),
306
1246
      primordials_string()};
307
  std::vector<Local<Value>> loaders_args = {
308
      process_object(),
309
623
      NewFunctionTemplate(binding::GetLinkedBinding)
310
623
          ->GetFunction(context())
311
          .ToLocalChecked(),
312
623
      NewFunctionTemplate(binding::GetInternalBinding)
313
623
          ->GetFunction(context())
314
          .ToLocalChecked(),
315
4361
      primordials()};
316
317
  // Bootstrap internal loaders
318
  Local<Value> loader_exports;
319
623
  if (!ExecuteBootstrapper(
320
623
           this, "internal/bootstrap/loaders", &loaders_params, &loaders_args)
321
623
           .ToLocal(&loader_exports)) {
322
    return MaybeLocal<Value>();
323
  }
324
623
  CHECK(loader_exports->IsObject());
325
623
  Local<Object> loader_exports_obj = loader_exports.As<Object>();
326
  Local<Value> internal_binding_loader =
327
1246
      loader_exports_obj->Get(context(), internal_binding_string())
328
623
          .ToLocalChecked();
329
623
  CHECK(internal_binding_loader->IsFunction());
330
623
  set_internal_binding_loader(internal_binding_loader.As<Function>());
331
  Local<Value> require =
332
1869
      loader_exports_obj->Get(context(), require_string()).ToLocalChecked();
333
623
  CHECK(require->IsFunction());
334
623
  set_native_module_require(require.As<Function>());
335
336
623
  return scope.Escape(loader_exports);
337
}
338
339
623
MaybeLocal<Value> Environment::BootstrapNode() {
340
623
  EscapableHandleScope scope(isolate_);
341
342
1246
  Local<Object> global = context()->Global();
343
  // TODO(joyeecheung): this can be done in JS land now.
344
1246
  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
623
      process_string(),
350
623
      require_string(),
351
623
      internal_binding_string(),
352
1246
      primordials_string()};
353
  std::vector<Local<Value>> node_args = {
354
      process_object(),
355
      native_module_require(),
356
      internal_binding_loader(),
357
3738
      primordials()};
358
359
  MaybeLocal<Value> result = ExecuteBootstrapper(
360
623
      this, "internal/bootstrap/node", &node_params, &node_args);
361
362
623
  if (result.IsEmpty()) {
363
    return MaybeLocal<Value>();
364
  }
365
366
623
  if (!no_browser_globals()) {
367
    result = ExecuteBootstrapper(
368
623
        this, "internal/bootstrap/browser", &node_params, &node_args);
369
370
623
    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
623
      is_main_thread() ? "internal/bootstrap/switches/is_main_thread"
378
623
                       : "internal/bootstrap/switches/is_not_main_thread";
379
  result =
380
623
      ExecuteBootstrapper(this, thread_switch_id, &node_params, &node_args);
381
382
623
  if (result.IsEmpty()) {
383
    return MaybeLocal<Value>();
384
  }
385
386
  auto process_state_switch_id =
387
623
      owns_process_state()
388
623
          ? "internal/bootstrap/switches/does_own_process_state"
389
623
          : "internal/bootstrap/switches/does_not_own_process_state";
390
  result = ExecuteBootstrapper(
391
623
      this, process_state_switch_id, &node_params, &node_args);
392
393
623
  if (result.IsEmpty()) {
394
    return MaybeLocal<Value>();
395
  }
396
397
623
  Local<String> env_string = FIXED_ONE_BYTE_STRING(isolate_, "env");
398
  Local<Object> env_var_proxy;
399
1869
  if (!CreateEnvVarProxy(context(), isolate_).ToLocal(&env_var_proxy) ||
400

2492
      process_object()->Set(context(), env_string, env_var_proxy).IsNothing()) {
401
    return MaybeLocal<Value>();
402
  }
403
404
623
  return scope.EscapeMaybe(result);
405
}
406
407
623
MaybeLocal<Value> Environment::RunBootstrapping() {
408
623
  EscapableHandleScope scope(isolate_);
409
410
623
  CHECK(!has_run_bootstrapping_code());
411
412
1246
  if (BootstrapInternalLoaders().IsEmpty()) {
413
    return MaybeLocal<Value>();
414
  }
415
416
  Local<Value> result;
417
1246
  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
623
  CHECK(req_wrap_queue()->IsEmpty());
426
623
  CHECK(handle_wrap_queue()->IsEmpty());
427
428
623
  DoneBootstrapping();
429
430
623
  return scope.Escape(result);
431
}
432
433
5556
void MarkBootstrapComplete(const FunctionCallbackInfo<Value>& args) {
434
5556
  Environment* env = Environment::GetCurrent(args);
435
5556
  env->performance_state()->Mark(
436
      performance::NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE);
437
5556
}
438
439
static
440
5565
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
441
5565
  EscapableHandleScope scope(env->isolate());
442
5565
  CHECK_NOT_NULL(main_script_id);
443
444
  std::vector<Local<String>> parameters = {
445
5565
      env->process_string(),
446
5565
      env->require_string(),
447
5565
      env->internal_binding_string(),
448
5565
      env->primordials_string(),
449
10894
      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
5565
      env->NewFunctionTemplate(MarkBootstrapComplete)
457
5565
          ->GetFunction(env->context())
458
33390
          .ToLocalChecked()};
459
460
  return scope.EscapeMaybe(
461
10894
      ExecuteBootstrapper(env, main_script_id, &parameters, &arguments));
462
}
463
464
5565
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
465
  InternalCallbackScope callback_scope(
466
      env,
467
      Object::New(env->isolate()),
468
      { 1, 0 },
469
10892
      InternalCallbackScope::kSkipAsyncHooks);
470
471
5565
  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
5543
  if (env->worker_context() != nullptr) {
486
567
    return StartExecution(env, "internal/main/worker_thread");
487
  }
488
489
9716
  std::string first_argv;
490
4976
  if (env->argv().size() > 1) {
491
4638
    first_argv = env->argv()[1];
492
  }
493
494
4976
  if (first_argv == "inspect") {
495
34
    return StartExecution(env, "internal/main/inspect");
496
  }
497
498
4942
  if (per_process::cli_options->build_snapshot) {
499
    return StartExecution(env, "internal/main/mksnapshot");
500
  }
501
502
4942
  if (per_process::cli_options->print_help) {
503
1
    return StartExecution(env, "internal/main/print_help");
504
  }
505
506
507
4941
  if (env->options()->prof_process) {
508
1
    return StartExecution(env, "internal/main/prof_process");
509
  }
510
511
  // -e/--eval without -i/--interactive
512


4940
  if (env->options()->has_eval_string && !env->options()->force_repl) {
513
306
    return StartExecution(env, "internal/main/eval_string");
514
  }
515
516
4634
  if (env->options()->syntax_check_only) {
517
36
    return StartExecution(env, "internal/main/check_syntax");
518
  }
519
520

4598
  if (!first_argv.empty() && first_argv != "-") {
521
4555
    return StartExecution(env, "internal/main/run_main_module");
522
  }
523
524


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

156054
    if (nr == SIGKILL || nr == SIGSTOP)
636
10068
      continue;
637

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

15102
    while (s.flags == -1 && errno == EINTR);  // NOLINT
652
15102
    CHECK_NE(s.flags, -1);
653
654
15102
    if (uv_guess_handle(fd) != UV_TTY) continue;
655
120
    s.isatty = true;
656
657
    do
658
120
      err = tcgetattr(fd, &s.termios);
659

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

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

28344
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
741
28344
    if (!is_same_file) continue;  // Program reopened file descriptor.
742
743
    int flags;
744
    do
745
28338
      flags = fcntl(fd, F_GETFL);
746

28338
    while (flags == -1 && errno == EINTR);  // NOLINT
747
28338
    CHECK_NE(flags, -1);
748
749
    // Restore the O_NONBLOCK flag if it changed.
750
28338
    if (O_NONBLOCK & (flags ^ s.flags)) {
751
956
      flags &= ~O_NONBLOCK;
752
956
      flags |= s.flags & O_NONBLOCK;
753
754
      int err;
755
      do
756
956
        err = fcntl(fd, F_SETFL, flags);
757

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

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


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

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

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

9975
  if (per_process::cli_options->use_largepages == "on" ||
1032
4987
      per_process::cli_options->use_largepages == "silent") {
1033
1
    int result = node::MapStaticCodeToLargePages();
1034

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

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