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

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

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

5220
      process_object()->Set(context(), env_string, env_var_proxy).IsNothing()) {
391
    return MaybeLocal<Value>();
392
  }
393
394
1305
  return scope.EscapeMaybe(result);
395
}
396
397
1305
MaybeLocal<Value> Environment::RunBootstrapping() {
398
1305
  EscapableHandleScope scope(isolate_);
399
400
1305
  CHECK(!has_run_bootstrapping_code());
401
402
2610
  if (BootstrapInternalLoaders().IsEmpty()) {
403
    return MaybeLocal<Value>();
404
  }
405
406
  Local<Value> result;
407
2610
  if (!BootstrapNode().ToLocal(&result)) {
408
    return MaybeLocal<Value>();
409
  }
410
411
  // Make sure that no request or handle is created during bootstrap -
412
  // if necessary those should be done in pre-execution.
413
  // Usually, doing so would trigger the checks present in the ReqWrap and
414
  // HandleWrap classes, so this is only a consistency check.
415
1305
  CHECK(req_wrap_queue()->IsEmpty());
416
1305
  CHECK(handle_wrap_queue()->IsEmpty());
417
418
1305
  DoneBootstrapping();
419
420
1305
  return scope.Escape(result);
421
}
422
423
6544
void MarkBootstrapComplete(const FunctionCallbackInfo<Value>& args) {
424
6544
  Environment* env = Environment::GetCurrent(args);
425
6544
  env->performance_state()->Mark(
426
      performance::NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE);
427
6544
}
428
429
static
430
6553
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
431
6553
  EscapableHandleScope scope(env->isolate());
432
6553
  CHECK_NOT_NULL(main_script_id);
433
434
  std::vector<Local<String>> parameters = {
435
6553
      env->process_string(),
436
6553
      env->require_string(),
437
6553
      env->internal_binding_string(),
438
6553
      env->primordials_string(),
439
12866
      FIXED_ONE_BYTE_STRING(env->isolate(), "markBootstrapComplete")};
440
441
  std::vector<Local<Value>> arguments = {
442
      env->process_object(),
443
      env->native_module_require(),
444
      env->internal_binding_loader(),
445
      env->primordials(),
446
6553
      env->NewFunctionTemplate(MarkBootstrapComplete)
447
6553
          ->GetFunction(env->context())
448
39318
          .ToLocalChecked()};
449
450
  return scope.EscapeMaybe(
451
12866
      ExecuteBootstrapper(env, main_script_id, &parameters, &arguments));
452
}
453
454
6553
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
455
  InternalCallbackScope callback_scope(
456
      env,
457
      Object::New(env->isolate()),
458
      { 1, 0 },
459
12864
      InternalCallbackScope::kSkipAsyncHooks);
460
461
6553
  if (cb != nullptr) {
462
22
    EscapableHandleScope scope(env->isolate());
463
464
44
    if (StartExecution(env, "internal/bootstrap/environment").IsEmpty())
465
      return {};
466
467
    StartExecutionCallbackInfo info = {
468
22
      env->process_object(),
469
22
      env->native_module_require(),
470
    };
471
472
42
    return scope.EscapeMaybe(cb(info));
473
  }
474
475
  // TODO(joyeecheung): move these conditions into JS land and let the
476
  // deserialize main function take precedence. For workers, we need to
477
  // move the pre-execution part into a different file that can be
478
  // reused when dealing with user-defined main functions.
479
13062
  if (!env->snapshot_deserialize_main().IsEmpty()) {
480
    return env->RunSnapshotDeserializeMain();
481
  }
482
483
6531
  if (env->worker_context() != nullptr) {
484
1248
    return StartExecution(env, "internal/main/worker_thread");
485
  }
486
487
10326
  std::string first_argv;
488
5283
  if (env->argv().size() > 1) {
489
4787
    first_argv = env->argv()[1];
490
  }
491
492
5283
  if (first_argv == "inspect") {
493
38
    return StartExecution(env, "internal/main/inspect");
494
  }
495
496
5245
  if (per_process::cli_options->build_snapshot) {
497
    return StartExecution(env, "internal/main/mksnapshot");
498
  }
499
500
5245
  if (per_process::cli_options->print_help) {
501
1
    return StartExecution(env, "internal/main/print_help");
502
  }
503
504
505
5244
  if (env->options()->prof_process) {
506
1
    return StartExecution(env, "internal/main/prof_process");
507
  }
508
509
  // -e/--eval without -i/--interactive
510


5243
  if (env->options()->has_eval_string && !env->options()->force_repl) {
511
461
    return StartExecution(env, "internal/main/eval_string");
512
  }
513
514
4782
  if (env->options()->syntax_check_only) {
515
36
    return StartExecution(env, "internal/main/check_syntax");
516
  }
517
518
4746
  if (env->options()->test_runner) {
519
9
    return StartExecution(env, "internal/main/test_runner");
520
  }
521
522

4737
  if (!first_argv.empty() && first_argv != "-") {
523
4692
    return StartExecution(env, "internal/main/run_main_module");
524
  }
525
526


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

165757
    if (nr == SIGKILL || nr == SIGSTOP)
638
10694
      continue;
639

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

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

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

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

30390
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
743
30390
    if (!is_same_file) continue;  // Program reopened file descriptor.
744
745
    int flags;
746
    do
747
30384
      flags = fcntl(fd, F_GETFL);
748

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

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

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


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

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

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

10589
  if (per_process::cli_options->use_largepages == "on" ||
1025
5294
      per_process::cli_options->use_largepages == "silent") {
1026
1
    int result = node::MapStaticCodeToLargePages();
1027

1
    if (per_process::cli_options->use_largepages == "on" && result != 0) {
1028
      fprintf(stderr, "%s\n", node::LargePagesError(result));
1029
    }
1030
  }
1031
1032
5295
  if (per_process::cli_options->print_version) {
1033
3
    printf("%s\n", NODE_VERSION);
1034
3
    result.exit_code = 0;
1035
3
    result.early_return = true;
1036
3
    return result;
1037
  }
1038
1039
5292
  if (per_process::cli_options->print_bash_completion) {
1040
2
    std::string completion = options_parser::GetBashCompletion();
1041
1
    printf("%s\n", completion.c_str());
1042
1
    result.exit_code = 0;
1043
1
    result.early_return = true;
1044
1
    return result;
1045
  }
1046
1047
5291
  if (per_process::cli_options->print_v8_help) {
1048
    V8::SetFlagsFromString("--help", static_cast<size_t>(6));
1049
    result.exit_code = 0;
1050
    result.early_return = true;
1051
    return result;
1052
  }
1053
1054
5291
  if (init_flags & kInitOpenSSL) {
1055
#if HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
1056
    {
1057
10582
      std::string extra_ca_certs;
1058
5291
      if (credentials::SafeGetenv("NODE_EXTRA_CA_CERTS", &extra_ca_certs))
1059
4
        crypto::UseExtraCaCerts(extra_ca_certs);
1060
    }
1061
    // In the case of FIPS builds we should make sure
1062
    // the random source is properly initialized first.
1063
#if OPENSSL_VERSION_MAJOR >= 3
1064
    // Call OPENSSL_init_crypto to initialize OPENSSL_INIT_LOAD_CONFIG to
1065
    // avoid the default behavior where errors raised during the parsing of the
1066
    // OpenSSL configuration file are not propagated and cannot be detected.
1067
    //
1068
    // If FIPS is configured the OpenSSL configuration file will have an
1069
    // .include pointing to the fipsmodule.cnf file generated by the openssl
1070
    // fipsinstall command. If the path to this file is incorrect no error
1071
    // will be reported.
1072
    //
1073
    // For Node.js this will mean that EntropySource will be called by V8 as
1074
    // part of its initialization process, and EntropySource will in turn call
1075
    // CheckEntropy. CheckEntropy will call RAND_status which will now always
1076
    // return 0, leading to an endless loop and the node process will appear to
1077
    // hang/freeze.
1078
1079
    // Passing NULL as the config file will allow the default openssl.cnf file
1080
    // to be loaded, but the default section in that file will not be used,
1081
    // instead only the section that matches the value of conf_section_name
1082
    // will be read from the default configuration file.
1083
5291
    const char* conf_file = nullptr;
1084
    // To allow for using the previous default where the 'openssl_conf' appname
1085
    // was used, the command line option 'openssl-shared-config' can be used to
1086
    // force the old behavior.
1087
5291
    if (per_process::cli_options->openssl_shared_config) {
1088
      conf_section_name = "openssl_conf";
1089
    }
1090
    // Use OPENSSL_CONF environment variable is set.
1091
5291
    std::string env_openssl_conf;
1092
5291
    credentials::SafeGetenv("OPENSSL_CONF", &env_openssl_conf);
1093
5291
    if (!env_openssl_conf.empty()) {
1094
1
      conf_file = env_openssl_conf.c_str();
1095
    }
1096
    // Use --openssl-conf command line option if specified.
1097
5291
    if (!per_process::cli_options->openssl_config.empty()) {
1098
      conf_file = per_process::cli_options->openssl_config.c_str();
1099
    }
1100
1101
5291
    OPENSSL_INIT_SETTINGS* settings = OPENSSL_INIT_new();
1102
5291
    OPENSSL_INIT_set_config_filename(settings, conf_file);
1103
5291
    OPENSSL_INIT_set_config_appname(settings, conf_section_name);
1104
5291
    OPENSSL_INIT_set_config_file_flags(settings,
1105
                                       CONF_MFLAGS_IGNORE_MISSING_FILE);
1106
1107
5291
    OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, settings);
1108
5291
    OPENSSL_INIT_free(settings);
1109
1110
5291
    if (ERR_peek_error() != 0) {
1111
      result.exit_code = ERR_GET_REASON(ERR_peek_error());
1112
      result.early_return = true;
1113
      fprintf(stderr, "OpenSSL configuration error:\n");
1114
      ERR_print_errors_fp(stderr);
1115
      return result;
1116
    }
1117
#else  // OPENSSL_VERSION_MAJOR < 3
1118
    if (FIPS_mode()) {
1119
      OPENSSL_init();
1120
    }
1121
#endif
1122
5291
  if (!crypto::ProcessFipsOptions()) {
1123
2
      result.exit_code = ERR_GET_REASON(ERR_peek_error());
1124
2
      result.early_return = true;
1125
2
      fprintf(stderr, "OpenSSL error when trying to enable FIPS:\n");
1126
2
      ERR_print_errors_fp(stderr);
1127
2
      return result;
1128
  }
1129
1130
  // V8 on Windows doesn't have a good source of entropy. Seed it from
1131
  // OpenSSL's pool.
1132
5289
  V8::SetEntropySource(crypto::EntropySource);
1133
#endif  // HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL)
1134
}
1135
5289
  per_process::v8_platform.Initialize(
1136
5289
      static_cast<int>(per_process::cli_options->v8_thread_pool_size));
1137
5289
  if (init_flags & kInitializeV8) {
1138
    V8::Initialize();
1139
  }
1140
1141
5289
  performance::performance_v8_start = PERFORMANCE_NOW();
1142
5289
  per_process::v8_initialized = true;
1143
1144
5289
  return result;
1145
}
1146
1147
4768
void TearDownOncePerProcess() {
1148
4768
  per_process::v8_initialized = false;
1149
4768
  V8::Dispose();
1150
1151
#if NODE_USE_V8_WASM_TRAP_HANDLER && defined(_WIN32)
1152
  RemoveVectoredExceptionHandler(per_process::old_vectored_exception_handler);
1153
#endif
1154
1155
  // uv_run cannot be called from the time before the beforeExit callback
1156
  // runs until the program exits unless the event loop has any referenced
1157
  // handles after beforeExit terminates. This prevents unrefed timers
1158
  // that happen to terminate during shutdown from being run unsafely.
1159
  // Since uv_run cannot be called, uv_async handles held by the platform
1160
  // will never be fully cleaned up.
1161
4768
  per_process::v8_platform.Dispose();
1162
4768
}
1163
1164
5341
int Start(int argc, char** argv) {
1165
10161
  InitializationResult result = InitializeOncePerProcess(argc, argv);
1166
5341
  if (result.early_return) {
1167
58
    return result.exit_code;
1168
  }
1169
1170
5283
  if (per_process::cli_options->build_snapshot) {
1171
    fprintf(stderr,
1172
            "--build-snapshot is not yet supported in the node binary\n");
1173
    return 1;
1174
  }
1175
1176
  {
1177
5283
    bool use_node_snapshot = per_process::cli_options->node_snapshot;
1178
    const SnapshotData* snapshot_data =
1179
5283
        use_node_snapshot ? SnapshotBuilder::GetEmbeddedSnapshotData()
1180
5283
                          : nullptr;
1181
5283
    uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);
1182
1183
5283
    if (snapshot_data != nullptr) {
1184
5281
      NativeModuleLoader::RefreshCodeCache(snapshot_data->code_cache);
1185
    }
1186
    NodeMainInstance main_instance(snapshot_data,
1187
                                   uv_default_loop(),
1188
5283
                                   per_process::v8_platform.Platform(),
1189
                                   result.args,
1190
5283
                                   result.exec_args);
1191
5283
    result.exit_code = main_instance.Run();
1192
  }
1193
1194
4762
  TearDownOncePerProcess();
1195
4762
  return result.exit_code;
1196
}
1197
1198
834
int Stop(Environment* env) {
1199
834
  env->ExitEnv();
1200
834
  return 0;
1201
}
1202
1203
}  // namespace node
1204
1205
#if !HAVE_INSPECTOR
1206
void Initialize() {}
1207
1208
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1209
#endif  // !HAVE_INSPECTOR