GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node.cc Lines: 357 427 83.6 %
Date: 2020-08-17 22:13:26 Branches: 212 321 66.0 %

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

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

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

1548
  if (!CreateEnvVarProxy(context(), isolate_).ToLocal(&env_var_proxy) ||
378
1548
      process_object()->Set(context(), env_string, env_var_proxy).IsNothing()) {
379
    return MaybeLocal<Value>();
380
  }
381
382
387
  return scope.EscapeMaybe(result);
383
}
384
385
386
MaybeLocal<Value> Environment::RunBootstrapping() {
386
386
  EscapableHandleScope scope(isolate_);
387
388
386
  CHECK(!has_run_bootstrapping_code());
389
390
773
  if (BootstrapInternalLoaders().IsEmpty()) {
391
    return MaybeLocal<Value>();
392
  }
393
394
  Local<Value> result;
395
774
  if (!BootstrapNode().ToLocal(&result)) {
396
    return MaybeLocal<Value>();
397
  }
398
399
  // Make sure that no request or handle is created during bootstrap -
400
  // if necessary those should be done in pre-execution.
401
  // Usually, doing so would trigger the checks present in the ReqWrap and
402
  // HandleWrap classes, so this is only a consistency check.
403
387
  CHECK(req_wrap_queue()->IsEmpty());
404
387
  CHECK(handle_wrap_queue()->IsEmpty());
405
406
387
  set_has_run_bootstrapping_code(true);
407
408
387
  return scope.Escape(result);
409
}
410
411
4742
void MarkBootstrapComplete(const FunctionCallbackInfo<Value>& args) {
412
4742
  Environment* env = Environment::GetCurrent(args);
413
4742
  env->performance_state()->Mark(
414
4742
      performance::NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE);
415
4742
}
416
417
static
418
4750
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
419
4750
  EscapableHandleScope scope(env->isolate());
420
4750
  CHECK_NOT_NULL(main_script_id);
421
422
  std::vector<Local<String>> parameters = {
423
      env->process_string(),
424
      env->require_string(),
425
      env->internal_binding_string(),
426
      env->primordials_string(),
427
9216
      FIXED_ONE_BYTE_STRING(env->isolate(), "markBootstrapComplete")};
428
429
  std::vector<Local<Value>> arguments = {
430
      env->process_object(),
431
      env->native_module_require(),
432
      env->internal_binding_loader(),
433
      env->primordials(),
434
9500
      env->NewFunctionTemplate(MarkBootstrapComplete)
435
14250
          ->GetFunction(env->context())
436
28216
          .ToLocalChecked()};
437
438
  return scope.EscapeMaybe(
439
9216
      ExecuteBootstrapper(env, main_script_id, &parameters, &arguments));
440
}
441
442
4750
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
443
  InternalCallbackScope callback_scope(
444
      env,
445
      Object::New(env->isolate()),
446
      { 1, 0 },
447
9214
      InternalCallbackScope::kSkipAsyncHooks);
448
449
4750
  if (cb != nullptr) {
450
18
    EscapableHandleScope scope(env->isolate());
451
452
36
    if (StartExecution(env, "internal/bootstrap/environment").IsEmpty())
453
      return {};
454
455
    StartExecutionCallbackInfo info = {
456
      env->process_object(),
457
      env->native_module_require(),
458
18
    };
459
460
34
    return scope.EscapeMaybe(cb(info));
461
  }
462
463
4732
  if (env->worker_context() != nullptr) {
464
342
    return StartExecution(env, "internal/main/worker_thread");
465
  }
466
467
8496
  std::string first_argv;
468
4390
  if (env->argv().size() > 1) {
469
4054
    first_argv = env->argv()[1];
470
  }
471
472
4390
  if (first_argv == "inspect") {
473
3
    return StartExecution(env, "internal/main/inspect");
474
  }
475
476
4387
  if (per_process::cli_options->print_help) {
477
1
    return StartExecution(env, "internal/main/print_help");
478
  }
479
480
481
4386
  if (env->options()->prof_process) {
482
1
    return StartExecution(env, "internal/main/prof_process");
483
  }
484
485
  // -e/--eval without -i/--interactive
486


4385
  if (env->options()->has_eval_string && !env->options()->force_repl) {
487
310
    return StartExecution(env, "internal/main/eval_string");
488
  }
489
490
4075
  if (env->options()->syntax_check_only) {
491
34
    return StartExecution(env, "internal/main/check_syntax");
492
  }
493
494

4041
  if (!first_argv.empty() && first_argv != "-") {
495
4004
    return StartExecution(env, "internal/main/run_main_module");
496
  }
497
498


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

137981
    if (nr == SIGKILL || nr == SIGSTOP)
602
8902
      continue;
603

129079
    act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
604
129079
    CHECK_EQ(0, sigaction(nr, &act, nullptr));
605
  }
606
#endif  // !NODE_SHARED_MODE
607
608
  // Record the state of the stdio file descriptors so we can restore it
609
  // on exit.  Needs to happen before installing signal handlers because
610
  // they make use of that information.
611
17804
  for (auto& s : stdio) {
612
13353
    const int fd = &s - stdio;
613
    int err;
614
615
    do
616
13353
      s.flags = fcntl(fd, F_GETFL);
617

13353
    while (s.flags == -1 && errno == EINTR);  // NOLINT
618
13353
    CHECK_NE(s.flags, -1);
619
620
13353
    if (uv_guess_handle(fd) != UV_TTY) continue;
621
120
    s.isatty = true;
622
623
    do
624
120
      err = tcgetattr(fd, &s.termios);
625

120
    while (err == -1 && errno == EINTR);  // NOLINT
626
120
    CHECK_EQ(err, 0);
627
  }
628
629
4451
  RegisterSignalHandler(SIGINT, SignalExit, true);
630
4451
  RegisterSignalHandler(SIGTERM, SignalExit, true);
631
632
#if NODE_USE_V8_WASM_TRAP_HANDLER
633
  // Tell V8 to disable emitting WebAssembly
634
  // memory bounds checks. This means that we have
635
  // to catch the SIGSEGV in TrapWebAssemblyOrContinue
636
  // and pass the signal context to V8.
637
  {
638
    struct sigaction sa;
639
4451
    memset(&sa, 0, sizeof(sa));
640
4451
    sa.sa_sigaction = TrapWebAssemblyOrContinue;
641
4451
    CHECK_EQ(sigaction(SIGSEGV, &sa, nullptr), 0);
642
  }
643
4451
  V8::EnableWebAssemblyTrapHandler(false);
644
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
645
646
  // Raise the open file descriptor limit.
647
  struct rlimit lim;
648

4451
  if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
649
    // Do a binary search for the limit.
650
    rlim_t min = lim.rlim_cur;
651
    rlim_t max = 1 << 20;
652
    // But if there's a defined upper bound, don't search, just set it.
653
    if (lim.rlim_max != RLIM_INFINITY) {
654
      min = lim.rlim_max;
655
      max = lim.rlim_max;
656
    }
657
    do {
658
      lim.rlim_cur = min + (max - min) / 2;
659
      if (setrlimit(RLIMIT_NOFILE, &lim)) {
660
        max = lim.rlim_cur;
661
      } else {
662
        min = lim.rlim_cur;
663
      }
664
    } while (min + 1 < max);
665
  }
666
#endif  // __POSIX__
667
#ifdef _WIN32
668
  for (int fd = 0; fd <= 2; ++fd) {
669
    auto handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
670
    if (handle == INVALID_HANDLE_VALUE ||
671
        GetFileType(handle) == FILE_TYPE_UNKNOWN) {
672
      // Ignore _close result. If it fails or not depends on used Windows
673
      // version. We will just check _open result.
674
      _close(fd);
675
      if (fd != _open("nul", _O_RDWR))
676
        ABORT();
677
    }
678
  }
679
#endif  // _WIN32
680
4451
}
681
682
683
// Safe to call more than once and from signal handlers.
684
8393
void ResetStdio() {
685
8393
  uv_tty_reset_mode();
686
#ifdef __POSIX__
687
33572
  for (auto& s : stdio) {
688
25179
    const int fd = &s - stdio;
689
690
    struct stat tmp;
691
25179
    if (-1 == fstat(fd, &tmp)) {
692
      CHECK_EQ(errno, EBADF);  // Program closed file descriptor.
693
6
      continue;
694
    }
695
696
    bool is_same_file =
697

25179
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
698
25179
    if (!is_same_file) continue;  // Program reopened file descriptor.
699
700
    int flags;
701
    do
702
25173
      flags = fcntl(fd, F_GETFL);
703

25173
    while (flags == -1 && errno == EINTR);  // NOLINT
704
25173
    CHECK_NE(flags, -1);
705
706
    // Restore the O_NONBLOCK flag if it changed.
707
25173
    if (O_NONBLOCK & (flags ^ s.flags)) {
708
741
      flags &= ~O_NONBLOCK;
709
741
      flags |= s.flags & O_NONBLOCK;
710
711
      int err;
712
      do
713
741
        err = fcntl(fd, F_SETFL, flags);
714

741
      while (err == -1 && errno == EINTR);  // NOLINT
715
741
      CHECK_NE(err, -1);
716
    }
717
718
25173
    if (s.isatty) {
719
      sigset_t sa;
720
      int err;
721
722
      // We might be a background job that doesn't own the TTY so block SIGTTOU
723
      // before making the tcsetattr() call, otherwise that signal suspends us.
724
228
      sigemptyset(&sa);
725
228
      sigaddset(&sa, SIGTTOU);
726
727
228
      CHECK_EQ(0, pthread_sigmask(SIG_BLOCK, &sa, nullptr));
728
      do
729
228
        err = tcsetattr(fd, TCSANOW, &s.termios);
730

228
      while (err == -1 && errno == EINTR);  // NOLINT
731
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
732
733
      // Normally we expect err == 0. But if macOS App Sandbox is enabled,
734
      // tcsetattr will fail with err == -1 and errno == EPERM.
735


228
      CHECK_IMPLIES(err != 0, err == -1 && errno == EPERM);
736
    }
737
  }
738
#endif  // __POSIX__
739
8393
}
740
741
742
8793
int ProcessGlobalArgs(std::vector<std::string>* args,
743
                      std::vector<std::string>* exec_args,
744
                      std::vector<std::string>* errors,
745
                      OptionEnvvarSettings settings) {
746
  // Parse a few arguments which are specific to Node.
747
17586
  std::vector<std::string> v8_args;
748
749
17586
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
750
8793
  options_parser::Parse(
751
      args,
752
      exec_args,
753
      &v8_args,
754
      per_process::cli_options.get(),
755
      settings,
756
8793
      errors);
757
758
8793
  if (!errors->empty()) return 9;
759
760
17500
  std::string revert_error;
761
8750
  for (const std::string& cve : per_process::cli_options->security_reverts) {
762
1
    Revert(cve.c_str(), &revert_error);
763
1
    if (!revert_error.empty()) {
764
1
      errors->emplace_back(std::move(revert_error));
765
1
      return 12;
766
    }
767
  }
768
769

26246
  if (per_process::cli_options->disable_proto != "delete" &&
770

17496
      per_process::cli_options->disable_proto != "throw" &&
771
8747
      per_process::cli_options->disable_proto != "") {
772
    errors->emplace_back("invalid mode passed to --disable-proto");
773
    return 12;
774
  }
775
776
  // TODO(mylesborins): remove this when the harmony-top-level-await flag
777
  // is removed in V8
778
17498
  if (std::find(v8_args.begin(), v8_args.end(),
779
17498
                "--no-harmony-top-level-await") == v8_args.end()) {
780
8747
    v8_args.push_back("--harmony-top-level-await");
781
  }
782
783
17498
  auto env_opts = per_process::cli_options->per_isolate->per_env;
784
34996
  if (std::find(v8_args.begin(), v8_args.end(),
785

34978
                "--abort-on-uncaught-exception") != v8_args.end() ||
786
17480
      std::find(v8_args.begin(), v8_args.end(),
787
26211
                "--abort_on_uncaught_exception") != v8_args.end()) {
788
21
    env_opts->abort_on_uncaught_exception = true;
789
  }
790
791
#ifdef __POSIX__
792
  // Block SIGPROF signals when sleeping in epoll_wait/kevent/etc.  Avoids the
793
  // performance penalty of frequent EINTR wakeups when the profiler is running.
794
  // Only do this for v8.log profiling, as it breaks v8::CpuProfiler users.
795
8749
  if (std::find(v8_args.begin(), v8_args.end(), "--prof") != v8_args.end()) {
796
2
    uv_loop_configure(uv_default_loop(), UV_LOOP_BLOCK_SIGNAL, SIGPROF);
797
  }
798
#endif
799
800
17498
  std::vector<char*> v8_args_as_char_ptr(v8_args.size());
801
8749
  if (v8_args.size() > 0) {
802
26414
    for (size_t i = 0; i < v8_args.size(); ++i)
803
17665
      v8_args_as_char_ptr[i] = &v8_args[i][0];
804
8749
    int argc = v8_args.size();
805
8749
    V8::SetFlagsFromCommandLine(&argc, &v8_args_as_char_ptr[0], true);
806
8749
    v8_args_as_char_ptr.resize(argc);
807
  }
808
809
  // Anything that's still in v8_argv is not a V8 or a node option.
810
8762
  for (size_t i = 1; i < v8_args_as_char_ptr.size(); i++)
811
13
    errors->push_back("bad option: " + std::string(v8_args_as_char_ptr[i]));
812
813
8749
  if (v8_args_as_char_ptr.size() > 1) return 9;
814
815
8738
  return 0;
816
}
817
818
static std::atomic_bool init_called{false};
819
820
4459
int InitializeNodeWithArgs(std::vector<std::string>* argv,
821
                           std::vector<std::string>* exec_argv,
822
                           std::vector<std::string>* errors) {
823
  // Make sure InitializeNodeWithArgs() is called only once.
824
4459
  CHECK(!init_called.exchange(true));
825
826
  // Initialize node_start_time to get relative uptime.
827
4459
  per_process::node_start_time = uv_hrtime();
828
829
  // Register built-in modules
830
4459
  binding::RegisterBuiltinModules();
831
832
  // Make inherited handles noninheritable.
833
4459
  uv_disable_stdio_inheritance();
834
835
  // Cache the original command line to be
836
  // used in diagnostic reports.
837
4459
  per_process::cli_options->cmdline = *argv;
838
839
#if defined(NODE_V8_OPTIONS)
840
  // Should come before the call to V8::SetFlagsFromCommandLine()
841
  // so the user can disable a flag --foo at run-time by passing
842
  // --no_foo from the command line.
843
  V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1);
844
#endif
845
846
4459
  HandleEnvOptions(per_process::cli_options->per_isolate->per_env);
847
848
#if !defined(NODE_WITHOUT_NODE_OPTIONS)
849
8918
  std::string node_options;
850
851
4459
  if (credentials::SafeGetenv("NODE_OPTIONS", &node_options)) {
852
    std::vector<std::string> env_argv =
853
8685
        ParseNodeOptionsEnvVar(node_options, errors);
854
855
4351
    if (!errors->empty()) return 9;
856
857
    // [0] is expected to be the program name, fill it in from the real argv.
858
4351
    env_argv.insert(env_argv.begin(), argv->at(0));
859
860
    const int exit_code = ProcessGlobalArgs(&env_argv,
861
                                            nullptr,
862
                                            errors,
863
4351
                                            kAllowedInEnvironment);
864

4351
    if (exit_code != 0) return exit_code;
865
  }
866
#endif
867
868
  const int exit_code = ProcessGlobalArgs(argv,
869
                                          exec_argv,
870
                                          errors,
871
4442
                                          kDisallowedInEnvironment);
872
4442
  if (exit_code != 0) return exit_code;
873
874
  // Set the process.title immediately after processing argv if --title is set.
875
4404
  if (!per_process::cli_options->title.empty())
876
2
    uv_set_process_title(per_process::cli_options->title.c_str());
877
878
#if defined(NODE_HAVE_I18N_SUPPORT)
879
  // If the parameter isn't given, use the env variable.
880
4404
  if (per_process::cli_options->icu_data_dir.empty())
881
4404
    credentials::SafeGetenv("NODE_ICU_DATA",
882
8808
                            &per_process::cli_options->icu_data_dir);
883
884
#ifdef NODE_ICU_DEFAULT_DATA_DIR
885
  // If neither the CLI option nor the environment variable was specified,
886
  // fall back to the configured default
887
  if (per_process::cli_options->icu_data_dir.empty()) {
888
    // Check whether the NODE_ICU_DEFAULT_DATA_DIR contains the right data
889
    // file and can be read.
890
    static const char full_path[] =
891
        NODE_ICU_DEFAULT_DATA_DIR "/" U_ICUDATA_NAME ".dat";
892
893
    FILE* f = fopen(full_path, "rb");
894
895
    if (f != nullptr) {
896
      fclose(f);
897
      per_process::cli_options->icu_data_dir = NODE_ICU_DEFAULT_DATA_DIR;
898
    }
899
  }
900
#endif  // NODE_ICU_DEFAULT_DATA_DIR
901
902
  // Initialize ICU.
903
  // If icu_data_dir is empty here, it will load the 'minimal' data.
904
4404
  if (!i18n::InitializeICUDirectory(per_process::cli_options->icu_data_dir)) {
905
    errors->push_back("could not initialize ICU "
906
                      "(check NODE_ICU_DATA or --icu-data-dir parameters)\n");
907
    return 9;
908
  }
909
4404
  per_process::metadata.versions.InitializeIntlVersions();
910
#endif
911
912
4404
  NativeModuleEnv::InitializeCodeCache();
913
914
  // We should set node_is_initialized here instead of in node::Start,
915
  // otherwise embedders using node::Init to initialize everything will not be
916
  // able to set it and native modules will not load for them.
917
4404
  node_is_initialized = true;
918
4404
  return 0;
919
}
920
921
// TODO(addaleax): Deprecate and eventually remove this.
922
void Init(int* argc,
923
          const char** argv,
924
          int* exec_argc,
925
          const char*** exec_argv) {
926
  std::vector<std::string> argv_(argv, argv + *argc);  // NOLINT
927
  std::vector<std::string> exec_argv_;
928
  std::vector<std::string> errors;
929
930
  // This (approximately) duplicates some logic that has been moved to
931
  // node::Start(), with the difference that here we explicitly call `exit()`.
932
  int exit_code = InitializeNodeWithArgs(&argv_, &exec_argv_, &errors);
933
934
  for (const std::string& error : errors)
935
    fprintf(stderr, "%s: %s\n", argv_.at(0).c_str(), error.c_str());
936
  if (exit_code != 0) exit(exit_code);
937
938
  if (per_process::cli_options->print_version) {
939
    printf("%s\n", NODE_VERSION);
940
    exit(0);
941
  }
942
943
  if (per_process::cli_options->print_bash_completion) {
944
    std::string completion = options_parser::GetBashCompletion();
945
    printf("%s\n", completion.c_str());
946
    exit(0);
947
  }
948
949
  if (per_process::cli_options->print_v8_help) {
950
    V8::SetFlagsFromString("--help", static_cast<size_t>(6));
951
    exit(0);
952
  }
953
954
  *argc = argv_.size();
955
  *exec_argc = exec_argv_.size();
956
  // These leak memory, because, in the original code of this function, no
957
  // extra allocations were visible. This should be okay because this function
958
  // is only supposed to be called once per process, though.
959
  *exec_argv = Malloc<const char*>(*exec_argc);
960
  for (int i = 0; i < *exec_argc; ++i)
961
    (*exec_argv)[i] = strdup(exec_argv_[i].c_str());
962
  for (int i = 0; i < *argc; ++i)
963
    argv[i] = strdup(argv_[i].c_str());
964
}
965
966
4451
InitializationResult InitializeOncePerProcess(int argc, char** argv) {
967
  // Initialized the enabled list for Debug() calls with system
968
  // environment variables.
969
4451
  per_process::enabled_debug_list.Parse(nullptr);
970
971
4451
  atexit(ResetStdio);
972
4451
  PlatformInit();
973
974
4451
  CHECK_GT(argc, 0);
975
976
  // Hack around with the argv pointer. Used for process.title = "blah".
977
4451
  argv = uv_setup_args(argc, argv);
978
979
4451
  InitializationResult result;
980
4451
  result.args = std::vector<std::string>(argv, argv + argc);
981
8901
  std::vector<std::string> errors;
982
983
  // This needs to run *before* V8::Initialize().
984
  {
985
4451
    result.exit_code =
986
4451
        InitializeNodeWithArgs(&(result.args), &(result.exec_args), &errors);
987
4508
    for (const std::string& error : errors)
988
57
      fprintf(stderr, "%s: %s\n", result.args.at(0).c_str(), error.c_str());
989
4451
    if (result.exit_code != 0) {
990
55
      result.early_return = true;
991
55
      return result;
992
    }
993
  }
994
995

8791
  if (per_process::cli_options->use_largepages == "on" ||
996
4395
      per_process::cli_options->use_largepages == "silent") {
997
1
    int result = node::MapStaticCodeToLargePages();
998

1
    if (per_process::cli_options->use_largepages == "on" && result != 0) {
999
1
      fprintf(stderr, "%s\n", node::LargePagesError(result));
1000
    }
1001
  }
1002
1003
4396
  if (per_process::cli_options->print_version) {
1004
3
    printf("%s\n", NODE_VERSION);
1005
3
    result.exit_code = 0;
1006
3
    result.early_return = true;
1007
3
    return result;
1008
  }
1009
1010
4393
  if (per_process::cli_options->print_bash_completion) {
1011
2
    std::string completion = options_parser::GetBashCompletion();
1012
1
    printf("%s\n", completion.c_str());
1013
1
    result.exit_code = 0;
1014
1
    result.early_return = true;
1015
1
    return result;
1016
  }
1017
1018
4392
  if (per_process::cli_options->print_v8_help) {
1019
1
    V8::SetFlagsFromString("--help", static_cast<size_t>(6));
1020
    result.exit_code = 0;
1021
    result.early_return = true;
1022
    return result;
1023
  }
1024
1025
#if HAVE_OPENSSL
1026
  {
1027
8782
    std::string extra_ca_certs;
1028
4391
    if (credentials::SafeGetenv("NODE_EXTRA_CA_CERTS", &extra_ca_certs))
1029
4
      crypto::UseExtraCaCerts(extra_ca_certs);
1030
  }
1031
#ifdef NODE_FIPS_MODE
1032
  // In the case of FIPS builds we should make sure
1033
  // the random source is properly initialized first.
1034
  OPENSSL_init();
1035
#endif  // NODE_FIPS_MODE
1036
  // V8 on Windows doesn't have a good source of entropy. Seed it from
1037
  // OpenSSL's pool.
1038
4391
  V8::SetEntropySource(crypto::EntropySource);
1039
#endif  // HAVE_OPENSSL
1040
1041
4391
  per_process::v8_platform.Initialize(
1042
8782
      per_process::cli_options->v8_thread_pool_size);
1043
  V8::Initialize();
1044
4391
  performance::performance_v8_start = PERFORMANCE_NOW();
1045
4391
  per_process::v8_initialized = true;
1046
4391
  return result;
1047
}
1048
1049
3929
void TearDownOncePerProcess() {
1050
3929
  per_process::v8_initialized = false;
1051
3929
  V8::Dispose();
1052
1053
  // uv_run cannot be called from the time before the beforeExit callback
1054
  // runs until the program exits unless the event loop has any referenced
1055
  // handles after beforeExit terminates. This prevents unrefed timers
1056
  // that happen to terminate during shutdown from being run unsafely.
1057
  // Since uv_run cannot be called, uv_async handles held by the platform
1058
  // will never be fully cleaned up.
1059
3929
  per_process::v8_platform.Dispose();
1060
3929
}
1061
1062
4450
int Start(int argc, char** argv) {
1063
8437
  InitializationResult result = InitializeOncePerProcess(argc, argv);
1064
4449
  if (result.early_return) {
1065
59
    return result.exit_code;
1066
  }
1067
1068
  {
1069
8318
    Isolate::CreateParams params;
1070
4390
    const std::vector<size_t>* indexes = nullptr;
1071
4390
    const EnvSerializeInfo* env_info = nullptr;
1072
    bool force_no_snapshot =
1073
4390
        per_process::cli_options->per_isolate->no_node_snapshot;
1074
4390
    if (!force_no_snapshot) {
1075
4389
      v8::StartupData* blob = NodeMainInstance::GetEmbeddedSnapshotBlob();
1076
4389
      if (blob != nullptr) {
1077
4389
        params.snapshot_blob = blob;
1078
4389
        indexes = NodeMainInstance::GetIsolateDataIndexes();
1079
4389
        env_info = NodeMainInstance::GetEnvSerializeInfo();
1080
      }
1081
    }
1082
1083
    NodeMainInstance main_instance(&params,
1084
                                   uv_default_loop(),
1085
4390
                                   per_process::v8_platform.Platform(),
1086
                                   result.args,
1087
                                   result.exec_args,
1088
8318
                                   indexes);
1089
4390
    result.exit_code = main_instance.Run(env_info);
1090
  }
1091
1092
3928
  TearDownOncePerProcess();
1093
3928
  return result.exit_code;
1094
}
1095
1096
91
int Stop(Environment* env) {
1097
91
  env->ExitEnv();
1098
91
  return 0;
1099
}
1100
1101

13380
}  // namespace node
1102
1103
#if !HAVE_INSPECTOR
1104
void Initialize() {}
1105
1106
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1107
#endif  // !HAVE_INSPECTOR