GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.cc Lines: 387 446 86.8 %
Date: 2021-11-08 04:13:55 Branches: 221 331 66.8 %

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
7956
MaybeLocal<Value> ExecuteBootstrapper(Environment* env,
173
                                      const char* id,
174
                                      std::vector<Local<String>>* parameters,
175
                                      std::vector<Local<Value>>* arguments) {
176
7956
  EscapableHandleScope scope(env->isolate());
177
  MaybeLocal<Function> maybe_fn =
178
7956
      NativeModuleEnv::LookupAndCompile(env->context(), id, parameters, env);
179
180
  Local<Function> fn;
181
7956
  if (!maybe_fn.ToLocal(&fn)) {
182
    return MaybeLocal<Value>();
183
  }
184
185
  MaybeLocal<Value> result = fn->Call(env->context(),
186
                                      Undefined(env->isolate()),
187
7956
                                      arguments->size(),
188
23868
                                      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
7706
  if (result.IsEmpty()) {
197
33
    env->async_hooks()->clear_async_id_stack();
198
  }
199
200
7706
  return scope.EscapeMaybe(result);
201
}
202
203
#if HAVE_INSPECTOR
204
5482
int Environment::InitializeInspector(
205
    std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
206
10964
  std::string inspector_path;
207
5482
  bool is_main = !parent_handle;
208
5482
  if (parent_handle) {
209
568
    inspector_path = parent_handle->url();
210
568
    inspector_agent_->SetParentHandle(std::move(parent_handle));
211
  } else {
212
4914
    inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
213
  }
214
215
5482
  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
10964
  inspector_agent_->Start(inspector_path,
220
5482
                          options_->debug_options(),
221
10964
                          inspector_host_port(),
222
                          is_main);
223

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

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


4833
  if (env->options()->has_eval_string && !env->options()->force_repl) {
500
296
    return StartExecution(env, "internal/main/eval_string");
501
  }
502
503
4537
  if (env->options()->syntax_check_only) {
504
34
    return StartExecution(env, "internal/main/check_syntax");
505
  }
506
507

4503
  if (!first_argv.empty() && first_argv != "-") {
508
4461
    return StartExecution(env, "internal/main/run_main_module");
509
  }
510
511


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

152675
    if (nr == SIGKILL || nr == SIGSTOP)
623
9850
      continue;
624

142825
    act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
625
142825
    CHECK_EQ(0, sigaction(nr, &act, nullptr));
626
  }
627
#endif  // !NODE_SHARED_MODE
628
629
  // Record the state of the stdio file descriptors so we can restore it
630
  // on exit.  Needs to happen before installing signal handlers because
631
  // they make use of that information.
632
19700
  for (auto& s : stdio) {
633
14775
    const int fd = &s - stdio;
634
    int err;
635
636
    do
637
14775
      s.flags = fcntl(fd, F_GETFL);
638

14775
    while (s.flags == -1 && errno == EINTR);  // NOLINT
639
14775
    CHECK_NE(s.flags, -1);
640
641
14775
    if (uv_guess_handle(fd) != UV_TTY) continue;
642
120
    s.isatty = true;
643
644
    do
645
120
      err = tcgetattr(fd, &s.termios);
646

120
    while (err == -1 && errno == EINTR);  // NOLINT
647
120
    CHECK_EQ(err, 0);
648
  }
649
650
4925
  RegisterSignalHandler(SIGINT, SignalExit, true);
651
4925
  RegisterSignalHandler(SIGTERM, SignalExit, true);
652
653
#if NODE_USE_V8_WASM_TRAP_HANDLER
654
#if defined(_WIN32)
655
  {
656
    constexpr ULONG first = TRUE;
657
    per_process::old_vectored_exception_handler =
658
        AddVectoredExceptionHandler(first, TrapWebAssemblyOrContinue);
659
  }
660
#else
661
  // Tell V8 to disable emitting WebAssembly
662
  // memory bounds checks. This means that we have
663
  // to catch the SIGSEGV in TrapWebAssemblyOrContinue
664
  // and pass the signal context to V8.
665
  {
666
    struct sigaction sa;
667
4925
    memset(&sa, 0, sizeof(sa));
668
4925
    sa.sa_sigaction = TrapWebAssemblyOrContinue;
669
4925
    sa.sa_flags = SA_SIGINFO;
670
4925
    CHECK_EQ(sigaction(SIGSEGV, &sa, nullptr), 0);
671
  }
672
#endif  // defined(_WIN32)
673
4925
  V8::EnableWebAssemblyTrapHandler(false);
674
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
675
676
  // Raise the open file descriptor limit.
677
  struct rlimit lim;
678

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

27969
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
728
27969
    if (!is_same_file) continue;  // Program reopened file descriptor.
729
730
    int flags;
731
    do
732
27963
      flags = fcntl(fd, F_GETFL);
733

27963
    while (flags == -1 && errno == EINTR);  // NOLINT
734
27963
    CHECK_NE(flags, -1);
735
736
    // Restore the O_NONBLOCK flag if it changed.
737
27963
    if (O_NONBLOCK & (flags ^ s.flags)) {
738
905
      flags &= ~O_NONBLOCK;
739
905
      flags |= s.flags & O_NONBLOCK;
740
741
      int err;
742
      do
743
905
        err = fcntl(fd, F_SETFL, flags);
744

905
      while (err == -1 && errno == EINTR);  // NOLINT
745
905
      CHECK_NE(err, -1);
746
    }
747
748
27963
    if (s.isatty) {
749
      sigset_t sa;
750
      int err;
751
752
      // We might be a background job that doesn't own the TTY so block SIGTTOU
753
      // before making the tcsetattr() call, otherwise that signal suspends us.
754
228
      sigemptyset(&sa);
755
228
      sigaddset(&sa, SIGTTOU);
756
757
228
      CHECK_EQ(0, pthread_sigmask(SIG_BLOCK, &sa, nullptr));
758
      do
759
228
        err = tcsetattr(fd, TCSANOW, &s.termios);
760

228
      while (err == -1 && errno == EINTR);  // NOLINT
761
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
762
763
      // Normally we expect err == 0. But if macOS App Sandbox is enabled,
764
      // tcsetattr will fail with err == -1 and errno == EPERM.
765


228
      CHECK_IMPLIES(err != 0, err == -1 && errno == EPERM);
766
    }
767
  }
768
#endif  // __POSIX__
769
9323
}
770
771
772
9734
int ProcessGlobalArgs(std::vector<std::string>* args,
773
                      std::vector<std::string>* exec_args,
774
                      std::vector<std::string>* errors,
775
                      OptionEnvvarSettings settings) {
776
  // Parse a few arguments which are specific to Node.
777
19468
  std::vector<std::string> v8_args;
778
779
19468
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
780
9734
  options_parser::Parse(
781
      args,
782
      exec_args,
783
      &v8_args,
784
      per_process::cli_options.get(),
785
      settings,
786
      errors);
787
788
9734
  if (!errors->empty()) return 9;
789
790
19380
  std::string revert_error;
791
9690
  for (const std::string& cve : per_process::cli_options->security_reverts) {
792
1
    Revert(cve.c_str(), &revert_error);
793
1
    if (!revert_error.empty()) {
794
1
      errors->emplace_back(std::move(revert_error));
795
1
      return 12;
796
    }
797
  }
798
799
19377
  if (per_process::cli_options->disable_proto != "delete" &&
800

19377
      per_process::cli_options->disable_proto != "throw" &&
801
9687
      per_process::cli_options->disable_proto != "") {
802
    errors->emplace_back("invalid mode passed to --disable-proto");
803
    return 12;
804
  }
805
806
  // TODO(aduh95): remove this when the harmony-import-assertions flag
807
  // is removed in V8.
808
19378
  if (std::find(v8_args.begin(), v8_args.end(),
809
9689
                "--no-harmony-import-assertions") == v8_args.end()) {
810
9689
    v8_args.push_back("--harmony-import-assertions");
811
  }
812
813
19378
  auto env_opts = per_process::cli_options->per_isolate->per_env;
814
19378
  if (std::find(v8_args.begin(), v8_args.end(),
815

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

9757
  if (per_process::cli_options->use_largepages == "on" ||
1019
4878
      per_process::cli_options->use_largepages == "silent") {
1020
1
    int result = node::MapStaticCodeToLargePages();
1021

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

4875
    if (has_cli_conf || !env_openssl_conf.empty()) {
1077
      OPENSSL_INIT_SETTINGS* settings = OPENSSL_INIT_new();
1078
      OPENSSL_INIT_set_config_file_flags(settings, CONF_MFLAGS_DEFAULT_SECTION);
1079
      if (has_cli_conf) {
1080
        const char* conf = per_process::cli_options->openssl_config.c_str();
1081
        OPENSSL_INIT_set_config_filename(settings, conf);
1082
      }
1083
      OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, settings);
1084
      OPENSSL_INIT_free(settings);
1085
1086
      if (ERR_peek_error() != 0) {
1087
        result.exit_code = ERR_GET_REASON(ERR_peek_error());
1088
        result.early_return = true;
1089
        fprintf(stderr, "OpenSSL configuration error:\n");
1090
        ERR_print_errors_fp(stderr);
1091
        return result;
1092
      }
1093
    }
1094
#else
1095
    if (FIPS_mode()) {
1096
      OPENSSL_init();
1097
    }
1098
#endif
1099
4875
  if (!crypto::ProcessFipsOptions()) {
1100
2
      result.exit_code = ERR_GET_REASON(ERR_peek_error());
1101
2
      result.early_return = true;
1102
2
      fprintf(stderr, "OpenSSL error when trying to enable FIPS:\n");
1103
2
      ERR_print_errors_fp(stderr);
1104
2
      return result;
1105
  }
1106
1107
  // V8 on Windows doesn't have a good source of entropy. Seed it from
1108
  // OpenSSL's pool.
1109
4873
  V8::SetEntropySource(crypto::EntropySource);
1110
#endif  // HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
1111
}
1112
4873
  per_process::v8_platform.Initialize(
1113
4873
      static_cast<int>(per_process::cli_options->v8_thread_pool_size));
1114
4873
  if (init_flags & kInitializeV8) {
1115
    V8::Initialize();
1116
  }
1117
1118
4873
  performance::performance_v8_start = PERFORMANCE_NOW();
1119
4873
  per_process::v8_initialized = true;
1120
1121
4873
  return result;
1122
}
1123
1124
4387
void TearDownOncePerProcess() {
1125
4387
  per_process::v8_initialized = false;
1126
4387
  V8::Dispose();
1127
1128
#if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
1129
  RemoveVectoredExceptionHandler(per_process::old_vectored_exception_handler);
1130
#endif
1131
1132
  // uv_run cannot be called from the time before the beforeExit callback
1133
  // runs until the program exits unless the event loop has any referenced
1134
  // handles after beforeExit terminates. This prevents unrefed timers
1135
  // that happen to terminate during shutdown from being run unsafely.
1136
  // Since uv_run cannot be called, uv_async handles held by the platform
1137
  // will never be fully cleaned up.
1138
4387
  per_process::v8_platform.Dispose();
1139
4387
}
1140
1141
4919
int Start(int argc, char** argv) {
1142
9352
  InitializationResult result = InitializeOncePerProcess(argc, argv);
1143
4919
  if (result.early_return) {
1144
52
    return result.exit_code;
1145
  }
1146
1147
  {
1148
9248
    Isolate::CreateParams params;
1149
4867
    const std::vector<size_t>* indices = nullptr;
1150
4867
    const EnvSerializeInfo* env_info = nullptr;
1151
    bool use_node_snapshot =
1152
4867
        per_process::cli_options->per_isolate->node_snapshot;
1153
4867
    if (use_node_snapshot) {
1154
4866
      v8::StartupData* blob = NodeMainInstance::GetEmbeddedSnapshotBlob();
1155
4866
      if (blob != nullptr) {
1156
4866
        params.snapshot_blob = blob;
1157
4866
        indices = NodeMainInstance::GetIsolateDataIndices();
1158
4866
        env_info = NodeMainInstance::GetEnvSerializeInfo();
1159
      }
1160
    }
1161
4867
    uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);
1162
1163
    NodeMainInstance main_instance(&params,
1164
                                   uv_default_loop(),
1165
4867
                                   per_process::v8_platform.Platform(),
1166
                                   result.args,
1167
                                   result.exec_args,
1168
4867
                                   indices);
1169
4867
    result.exit_code = main_instance.Run(env_info);
1170
  }
1171
1172
4381
  TearDownOncePerProcess();
1173
4381
  return result.exit_code;
1174
}
1175
1176
166
int Stop(Environment* env) {
1177
166
  env->ExitEnv();
1178
166
  return 0;
1179
}
1180
1181
}  // namespace node
1182
1183
#if !HAVE_INSPECTOR
1184
void Initialize() {}
1185
1186
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1187
#endif  // !HAVE_INSPECTOR