GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.cc Lines: 387 450 86.0 %
Date: 2022-04-21 04:14:52 Branches: 226 339 66.7 %

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

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

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

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


4970
  if (env->options()->has_eval_string && !env->options()->force_repl) {
514
310
    return StartExecution(env, "internal/main/eval_string");
515
  }
516
517
4660
  if (env->options()->syntax_check_only) {
518
36
    return StartExecution(env, "internal/main/check_syntax");
519
  }
520
521
4624
  if (env->options()->test_runner) {
522
5
    return StartExecution(env, "internal/main/test_runner");
523
  }
524
525

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


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

157170
    if (nr == SIGKILL || nr == SIGSTOP)
641
10140
      continue;
642

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

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

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

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

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

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

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

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


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

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

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

10035
  if (per_process::cli_options->use_largepages == "on" ||
1037
5017
      per_process::cli_options->use_largepages == "silent") {
1038
1
    int result = node::MapStaticCodeToLargePages();
1039

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

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