GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.cc Lines: 397 455 87.3 %
Date: 2022-07-23 04:17:00 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
13054
MaybeLocal<Value> ExecuteBootstrapper(Environment* env,
172
                                      const char* id,
173
                                      std::vector<Local<String>>* parameters,
174
                                      std::vector<Local<Value>>* arguments) {
175
13054
  EscapableHandleScope scope(env->isolate());
176
  MaybeLocal<Function> maybe_fn =
177
13054
      NativeModuleLoader::LookupAndCompile(env->context(), id, parameters, env);
178
179
  Local<Function> fn;
180
13054
  if (!maybe_fn.ToLocal(&fn)) {
181
    return MaybeLocal<Value>();
182
  }
183
184
  MaybeLocal<Value> result = fn->Call(env->context(),
185
                                      Undefined(env->isolate()),
186
13054
                                      arguments->size(),
187
39162
                                      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
12810
  if (result.IsEmpty()) {
196
33
    env->async_hooks()->clear_async_id_stack();
197
  }
198
199
12810
  return scope.EscapeMaybe(result);
200
}
201
202
#if HAVE_INSPECTOR
203
6559
int Environment::InitializeInspector(
204
    std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
205
13118
  std::string inspector_path;
206
6559
  bool is_main = !parent_handle;
207
6559
  if (parent_handle) {
208
1246
    inspector_path = parent_handle->url();
209
1246
    inspector_agent_->SetParentHandle(std::move(parent_handle));
210
  } else {
211
5313
    inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
212
  }
213
214
6559
  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
13118
  inspector_agent_->Start(inspector_path,
219
6559
                          options_->debug_options(),
220
13118
                          inspector_host_port(),
221
                          is_main);
222

6640
  if (options_->debug_options().inspector_enabled &&
223
81
      !inspector_agent_->IsListening()) {
224
5
    return 12;  // Signal internal error
225
  }
226
227
6554
  profiler::StartProfilers(this);
228
229
6554
  if (inspector_agent_->options().break_node_first_line) {
230
1
    inspector_agent_->PauseOnNextJavascriptStatement("Break at bootstrap");
231
  }
232
233
6554
  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
6532
void Environment::InitializeDiagnostics() {
276
6532
  isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
277
      Environment::BuildEmbedderGraph, this);
278
6532
  if (options_->heap_snapshot_near_heap_limit > 0) {
279
1
    isolate_->AddNearHeapLimitCallback(Environment::NearHeapLimitCallback,
280
                                       this);
281
  }
282
6532
  if (options_->trace_uncaught)
283
3
    isolate_->SetCaptureStackTraceForUncaughtExceptions(true);
284
6532
  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
6532
}
292
293
1301
MaybeLocal<Value> Environment::BootstrapInternalLoaders() {
294
1301
  EscapableHandleScope scope(isolate_);
295
296
  // Create binding loaders
297
  std::vector<Local<String>> loaders_params = {
298
1301
      process_string(),
299
1301
      FIXED_ONE_BYTE_STRING(isolate_, "getLinkedBinding"),
300
1301
      FIXED_ONE_BYTE_STRING(isolate_, "getInternalBinding"),
301
2602
      primordials_string()};
302
  std::vector<Local<Value>> loaders_args = {
303
      process_object(),
304
1301
      NewFunctionTemplate(binding::GetLinkedBinding)
305
1301
          ->GetFunction(context())
306
          .ToLocalChecked(),
307
1301
      NewFunctionTemplate(binding::GetInternalBinding)
308
1301
          ->GetFunction(context())
309
          .ToLocalChecked(),
310
9107
      primordials()};
311
312
  // Bootstrap internal loaders
313
  Local<Value> loader_exports;
314
1301
  if (!ExecuteBootstrapper(
315
1301
           this, "internal/bootstrap/loaders", &loaders_params, &loaders_args)
316
1301
           .ToLocal(&loader_exports)) {
317
    return MaybeLocal<Value>();
318
  }
319
1301
  CHECK(loader_exports->IsObject());
320
1301
  Local<Object> loader_exports_obj = loader_exports.As<Object>();
321
  Local<Value> internal_binding_loader =
322
2602
      loader_exports_obj->Get(context(), internal_binding_string())
323
1301
          .ToLocalChecked();
324
1301
  CHECK(internal_binding_loader->IsFunction());
325
1301
  set_internal_binding_loader(internal_binding_loader.As<Function>());
326
  Local<Value> require =
327
3903
      loader_exports_obj->Get(context(), require_string()).ToLocalChecked();
328
1301
  CHECK(require->IsFunction());
329
1301
  set_native_module_require(require.As<Function>());
330
331
1301
  return scope.Escape(loader_exports);
332
}
333
334
1301
MaybeLocal<Value> Environment::BootstrapNode() {
335
1301
  EscapableHandleScope scope(isolate_);
336
337
  // process, require, internalBinding, primordials
338
  std::vector<Local<String>> node_params = {
339
1301
      process_string(),
340
1301
      require_string(),
341
1301
      internal_binding_string(),
342
2602
      primordials_string()};
343
  std::vector<Local<Value>> node_args = {
344
      process_object(),
345
      native_module_require(),
346
      internal_binding_loader(),
347
7806
      primordials()};
348
349
  MaybeLocal<Value> result = ExecuteBootstrapper(
350
1301
      this, "internal/bootstrap/node", &node_params, &node_args);
351
352
1301
  if (result.IsEmpty()) {
353
    return MaybeLocal<Value>();
354
  }
355
356
1301
  if (!no_browser_globals()) {
357
    result = ExecuteBootstrapper(
358
1301
        this, "internal/bootstrap/browser", &node_params, &node_args);
359
360
1301
    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
1301
      is_main_thread() ? "internal/bootstrap/switches/is_main_thread"
368
1301
                       : "internal/bootstrap/switches/is_not_main_thread";
369
  result =
370
1301
      ExecuteBootstrapper(this, thread_switch_id, &node_params, &node_args);
371
372
1301
  if (result.IsEmpty()) {
373
    return MaybeLocal<Value>();
374
  }
375
376
  auto process_state_switch_id =
377
1301
      owns_process_state()
378
1301
          ? "internal/bootstrap/switches/does_own_process_state"
379
1301
          : "internal/bootstrap/switches/does_not_own_process_state";
380
  result = ExecuteBootstrapper(
381
1301
      this, process_state_switch_id, &node_params, &node_args);
382
383
1301
  if (result.IsEmpty()) {
384
    return MaybeLocal<Value>();
385
  }
386
387
1301
  Local<String> env_string = FIXED_ONE_BYTE_STRING(isolate_, "env");
388
  Local<Object> env_var_proxy;
389
3903
  if (!CreateEnvVarProxy(context(), isolate_).ToLocal(&env_var_proxy) ||
390

5204
      process_object()->Set(context(), env_string, env_var_proxy).IsNothing()) {
391
    return MaybeLocal<Value>();
392
  }
393
394
1301
  return scope.EscapeMaybe(result);
395
}
396
397
1301
MaybeLocal<Value> Environment::RunBootstrapping() {
398
1301
  EscapableHandleScope scope(isolate_);
399
400
1301
  CHECK(!has_run_bootstrapping_code());
401
402
2602
  if (BootstrapInternalLoaders().IsEmpty()) {
403
    return MaybeLocal<Value>();
404
  }
405
406
  Local<Value> result;
407
2602
  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
1301
  CHECK(req_wrap_queue()->IsEmpty());
416
1301
  CHECK(handle_wrap_queue()->IsEmpty());
417
418
1301
  DoneBootstrapping();
419
420
1301
  return scope.Escape(result);
421
}
422
423
6523
void MarkBootstrapComplete(const FunctionCallbackInfo<Value>& args) {
424
6523
  Environment* env = Environment::GetCurrent(args);
425
6523
  env->performance_state()->Mark(
426
      performance::NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE);
427
6523
}
428
429
static
430
6532
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
431
6532
  EscapableHandleScope scope(env->isolate());
432
6532
  CHECK_NOT_NULL(main_script_id);
433
434
  std::vector<Local<String>> parameters = {
435
6532
      env->process_string(),
436
6532
      env->require_string(),
437
6532
      env->internal_binding_string(),
438
6532
      env->primordials_string(),
439
12822
      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
6532
      env->NewFunctionTemplate(MarkBootstrapComplete)
447
6532
          ->GetFunction(env->context())
448
39192
          .ToLocalChecked()};
449
450
  return scope.EscapeMaybe(
451
12822
      ExecuteBootstrapper(env, main_script_id, &parameters, &arguments));
452
}
453
454
6532
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
455
  InternalCallbackScope callback_scope(
456
      env,
457
      Object::New(env->isolate()),
458
      { 1, 0 },
459
12820
      InternalCallbackScope::kSkipAsyncHooks);
460
461
6532
  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
13020
  if (!env->snapshot_deserialize_main().IsEmpty()) {
480
    return env->RunSnapshotDeserializeMain();
481
  }
482
483
6510
  if (env->worker_context() != nullptr) {
484
1244
    return StartExecution(env, "internal/main/worker_thread");
485
  }
486
487
10290
  std::string first_argv;
488
5266
  if (env->argv().size() > 1) {
489
4771
    first_argv = env->argv()[1];
490
  }
491
492
5266
  if (first_argv == "inspect") {
493
38
    return StartExecution(env, "internal/main/inspect");
494
  }
495
496
5228
  if (per_process::cli_options->build_snapshot) {
497
    return StartExecution(env, "internal/main/mksnapshot");
498
  }
499
500
5228
  if (per_process::cli_options->print_help) {
501
1
    return StartExecution(env, "internal/main/print_help");
502
  }
503
504
505
5227
  if (env->options()->prof_process) {
506
1
    return StartExecution(env, "internal/main/prof_process");
507
  }
508
509
  // -e/--eval without -i/--interactive
510


5226
  if (env->options()->has_eval_string && !env->options()->force_repl) {
511
460
    return StartExecution(env, "internal/main/eval_string");
512
  }
513
514
4766
  if (env->options()->syntax_check_only) {
515
36
    return StartExecution(env, "internal/main/check_syntax");
516
  }
517
518
4730
  if (env->options()->test_runner) {
519
7
    return StartExecution(env, "internal/main/test_runner");
520
  }
521
522

4723
  if (!first_argv.empty() && first_argv != "-") {
523
4678
    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
29529
void RegisterSignalHandler(int signal,
569
                           sigaction_cb handler,
570
                           bool reset_handler) {
571
29529
  CHECK_NOT_NULL(handler);
572
#if NODE_USE_V8_WASM_TRAP_HANDLER
573
29529
  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
29525
  memset(&sa, 0, sizeof(sa));
582
29525
  sa.sa_sigaction = handler;
583
29525
  sa.sa_flags = reset_handler ? SA_RESETHAND : 0;
584
29525
  sigfillset(&sa.sa_mask);
585
29525
  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
5330
inline void PlatformInit() {
600
#ifdef __POSIX__
601
#if HAVE_INSPECTOR
602
  sigset_t sigmask;
603
5330
  sigemptyset(&sigmask);
604
5330
  sigaddset(&sigmask, SIGUSR1);
605
5330
  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
21320
  for (auto& s : stdio) {
610
15990
    const int fd = &s - stdio;
611
15990
    if (fstat(fd, &s.stat) == 0)
612
15988
      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
5330
  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
5330
  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
170560
  for (unsigned nr = 1; nr < kMaxSignal; nr += 1) {
637

165230
    if (nr == SIGKILL || nr == SIGSTOP)
638
10660
      continue;
639

154570
    act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
640
154570
    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
21320
  for (auto& s : stdio) {
648
15990
    const int fd = &s - stdio;
649
    int err;
650
651
    do
652
15990
      s.flags = fcntl(fd, F_GETFL);
653

15990
    while (s.flags == -1 && errno == EINTR);  // NOLINT
654
15990
    CHECK_NE(s.flags, -1);
655
656
15990
    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
5330
  RegisterSignalHandler(SIGINT, SignalExit, true);
666
5330
  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
5330
    memset(&sa, 0, sizeof(sa));
683
5330
    sa.sa_sigaction = TrapWebAssemblyOrContinue;
684
5330
    sa.sa_flags = SA_SIGINFO;
685
5330
    CHECK_EQ(sigaction(SIGSEGV, &sa, nullptr), 0);
686
  }
687
#endif  // defined(_WIN32)
688
5330
  V8::EnableWebAssemblyTrapHandler(false);
689
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
690
691
  // Raise the open file descriptor limit.
692
  struct rlimit lim;
693

5330
  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
5330
}
726
727
728
// Safe to call more than once and from signal handlers.
729
10096
void ResetStdio() {
730
10096
  uv_tty_reset_mode();
731
#ifdef __POSIX__
732
40384
  for (auto& s : stdio) {
733
30288
    const int fd = &s - stdio;
734
735
    struct stat tmp;
736
30288
    if (-1 == fstat(fd, &tmp)) {
737
      CHECK_EQ(errno, EBADF);  // Program closed file descriptor.
738
6
      continue;
739
    }
740
741
30288
    bool is_same_file =
742

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

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

1146
      while (err == -1 && errno == EINTR);  // NOLINT
760
1146
      CHECK_NE(err, -1);
761
    }
762
763
30282
    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
10096
}
785
786
787
10542
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
21084
  std::vector<std::string> v8_args;
793
794
21084
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
795
10542
  options_parser::Parse(
796
      args,
797
      exec_args,
798
      &v8_args,
799
      per_process::cli_options.get(),
800
      settings,
801
      errors);
802
803
10542
  if (!errors->empty()) return 9;
804
805
20984
  std::string revert_error;
806
10492
  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
20981
  if (per_process::cli_options->disable_proto != "delete" &&
815

20981
      per_process::cli_options->disable_proto != "throw" &&
816
10489
      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
20982
  if (std::find(v8_args.begin(), v8_args.end(),
824
10491
                "--no-harmony-import-assertions") == v8_args.end()) {
825
10491
    v8_args.emplace_back("--harmony-import-assertions");
826
  }
827
828
20982
  auto env_opts = per_process::cli_options->per_isolate->per_env;
829
20982
  if (std::find(v8_args.begin(), v8_args.end(),
830

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

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

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