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 426 83.8 %
Date: 2020-05-27 22:15:15 Branches: 217 321 67.6 %

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

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

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

18376
  if (!CreateEnvVarProxy(context(), isolate_).ToLocal(&env_var_proxy) ||
378
18376
      process_object()->Set(context(), env_string, env_var_proxy).IsNothing()) {
379
    return MaybeLocal<Value>();
380
  }
381
382
4594
  return scope.EscapeMaybe(result);
383
}
384
385
4592
MaybeLocal<Value> Environment::RunBootstrapping() {
386
4592
  EscapableHandleScope scope(isolate_);
387
388
4593
  CHECK(!has_run_bootstrapping_code());
389
390
9187
  if (BootstrapInternalLoaders().IsEmpty()) {
391
    return MaybeLocal<Value>();
392
  }
393
394
  Local<Value> result;
395
9188
  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
4594
  CHECK(req_wrap_queue()->IsEmpty());
404
4594
  CHECK(handle_wrap_queue()->IsEmpty());
405
406
4594
  set_has_run_bootstrapping_code(true);
407
408
4594
  return scope.Escape(result);
409
}
410
411
4552
void MarkBootstrapComplete(const FunctionCallbackInfo<Value>& args) {
412
4552
  Environment* env = Environment::GetCurrent(args);
413
4552
  env->performance_state()->Mark(
414
4552
      performance::NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE);
415
4552
}
416
417
static
418
4570
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
419
4570
  EscapableHandleScope scope(env->isolate());
420
4570
  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
8895
      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
9140
      env->NewFunctionTemplate(MarkBootstrapComplete)
435
13710
          ->GetFunction(env->context())
436
27175
          .ToLocalChecked()};
437
438
  return scope.EscapeMaybe(
439
8895
      ExecuteBootstrapper(env, main_script_id, &parameters, &arguments));
440
}
441
442
4570
MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
443
  InternalCallbackScope callback_scope(
444
      env,
445
      Object::New(env->isolate()),
446
      { 1, 0 },
447
8893
      InternalCallbackScope::kSkipAsyncHooks);
448
449
4570
  if (cb != nullptr) {
450
12
    EscapableHandleScope scope(env->isolate());
451
452
24
    if (StartExecution(env, "internal/bootstrap/environment").IsEmpty())
453
      return {};
454
455
    StartExecutionCallbackInfo info = {
456
      env->process_object(),
457
      env->native_module_require(),
458
12
    };
459
460
22
    return scope.EscapeMaybe(cb(info));
461
  }
462
463
  // To allow people to extend Node in different ways, this hook allows
464
  // one to drop a file lib/_third_party_main.js into the build
465
  // directory which will be executed instead of Node's normal loading.
466
4558
  if (NativeModuleEnv::Exists("_third_party_main")) {
467
    return StartExecution(env, "internal/main/run_third_party_main");
468
  }
469
470
4558
  if (env->worker_context() != nullptr) {
471
300
    return StartExecution(env, "internal/main/worker_thread");
472
  }
473
474
8271
  std::string first_argv;
475
4258
  if (env->argv().size() > 1) {
476
3928
    first_argv = env->argv()[1];
477
  }
478
479

4258
  if (first_argv == "inspect" || first_argv == "debug") {
480
4
    return StartExecution(env, "internal/main/inspect");
481
  }
482
483
4254
  if (per_process::cli_options->print_help) {
484
1
    return StartExecution(env, "internal/main/print_help");
485
  }
486
487
488
4253
  if (env->options()->prof_process) {
489
1
    return StartExecution(env, "internal/main/prof_process");
490
  }
491
492
  // -e/--eval without -i/--interactive
493


4252
  if (env->options()->has_eval_string && !env->options()->force_repl) {
494
305
    return StartExecution(env, "internal/main/eval_string");
495
  }
496
497
3947
  if (env->options()->syntax_check_only) {
498
34
    return StartExecution(env, "internal/main/check_syntax");
499
  }
500
501

3913
  if (!first_argv.empty() && first_argv != "-") {
502
3877
    return StartExecution(env, "internal/main/run_main_module");
503
  }
504
505


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

133889
    if (nr == SIGKILL || nr == SIGSTOP)
609
8638
      continue;
610

125251
    act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
611
125251
    CHECK_EQ(0, sigaction(nr, &act, nullptr));
612
  }
613
#endif  // !NODE_SHARED_MODE
614
615
  // Record the state of the stdio file descriptors so we can restore it
616
  // on exit.  Needs to happen before installing signal handlers because
617
  // they make use of that information.
618
17276
  for (auto& s : stdio) {
619
12957
    const int fd = &s - stdio;
620
    int err;
621
622
    do
623
12957
      s.flags = fcntl(fd, F_GETFL);
624

12957
    while (s.flags == -1 && errno == EINTR);  // NOLINT
625
12957
    CHECK_NE(s.flags, -1);
626
627
12957
    if (uv_guess_handle(fd) != UV_TTY) continue;
628
120
    s.isatty = true;
629
630
    do
631
120
      err = tcgetattr(fd, &s.termios);
632

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

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

24486
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
705
24486
    if (!is_same_file) continue;  // Program reopened file descriptor.
706
707
    int flags;
708
    do
709
24480
      flags = fcntl(fd, F_GETFL);
710

24480
    while (flags == -1 && errno == EINTR);  // NOLINT
711
24480
    CHECK_NE(flags, -1);
712
713
    // Restore the O_NONBLOCK flag if it changed.
714
24480
    if (O_NONBLOCK & (flags ^ s.flags)) {
715
745
      flags &= ~O_NONBLOCK;
716
745
      flags |= s.flags & O_NONBLOCK;
717
718
      int err;
719
      do
720
745
        err = fcntl(fd, F_SETFL, flags);
721

745
      while (err == -1 && errno == EINTR);  // NOLINT
722
745
      CHECK_NE(err, -1);
723
    }
724
725
24480
    if (s.isatty) {
726
      sigset_t sa;
727
      int err;
728
729
      // We might be a background job that doesn't own the TTY so block SIGTTOU
730
      // before making the tcsetattr() call, otherwise that signal suspends us.
731
228
      sigemptyset(&sa);
732
228
      sigaddset(&sa, SIGTTOU);
733
734
228
      CHECK_EQ(0, pthread_sigmask(SIG_BLOCK, &sa, nullptr));
735
      do
736
228
        err = tcsetattr(fd, TCSANOW, &s.termios);
737

228
      while (err == -1 && errno == EINTR);  // NOLINT
738
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
739
228
      CHECK_EQ(0, err);
740
    }
741
  }
742
#endif  // __POSIX__
743
8162
}
744
745
746
8530
int ProcessGlobalArgs(std::vector<std::string>* args,
747
                      std::vector<std::string>* exec_args,
748
                      std::vector<std::string>* errors,
749
                      OptionEnvvarSettings settings) {
750
  // Parse a few arguments which are specific to Node.
751
17060
  std::vector<std::string> v8_args;
752
753
17060
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
754
8530
  options_parser::Parse(
755
      args,
756
      exec_args,
757
      &v8_args,
758
      per_process::cli_options.get(),
759
      settings,
760
8530
      errors);
761
762
8530
  if (!errors->empty()) return 9;
763
764
16974
  std::string revert_error;
765
8487
  for (const std::string& cve : per_process::cli_options->security_reverts) {
766
1
    Revert(cve.c_str(), &revert_error);
767
1
    if (!revert_error.empty()) {
768
1
      errors->emplace_back(std::move(revert_error));
769
1
      return 12;
770
    }
771
  }
772
773

25457
  if (per_process::cli_options->disable_proto != "delete" &&
774

16970
      per_process::cli_options->disable_proto != "throw" &&
775
8484
      per_process::cli_options->disable_proto != "") {
776
    errors->emplace_back("invalid mode passed to --disable-proto");
777
    return 12;
778
  }
779
780
16972
  auto env_opts = per_process::cli_options->per_isolate->per_env;
781
33944
  if (std::find(v8_args.begin(), v8_args.end(),
782

33927
                "--abort-on-uncaught-exception") != v8_args.end() ||
783
16955
      std::find(v8_args.begin(), v8_args.end(),
784
25424
                "--abort_on_uncaught_exception") != v8_args.end()) {
785
20
    env_opts->abort_on_uncaught_exception = true;
786
  }
787
788
  // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
789
  // manually?  That would give us a little more control over its runtime
790
  // behavior but it could also interfere with the user's intentions in ways
791
  // we fail to anticipate.  Dillema.
792
8486
  if (std::find(v8_args.begin(), v8_args.end(), "--prof") != v8_args.end()) {
793
2
    per_process::v8_is_profiling = true;
794
  }
795
796
#ifdef __POSIX__
797
  // Block SIGPROF signals when sleeping in epoll_wait/kevent/etc.  Avoids the
798
  // performance penalty of frequent EINTR wakeups when the profiler is running.
799
  // Only do this for v8.log profiling, as it breaks v8::CpuProfiler users.
800
8486
  if (per_process::v8_is_profiling) {
801
2
    uv_loop_configure(uv_default_loop(), UV_LOOP_BLOCK_SIGNAL, SIGPROF);
802
  }
803
#endif
804
805
16972
  std::vector<char*> v8_args_as_char_ptr(v8_args.size());
806
8486
  if (v8_args.size() > 0) {
807
17134
    for (size_t i = 0; i < v8_args.size(); ++i)
808
8648
      v8_args_as_char_ptr[i] = &v8_args[i][0];
809
8486
    int argc = v8_args.size();
810
8486
    V8::SetFlagsFromCommandLine(&argc, &v8_args_as_char_ptr[0], true);
811
8486
    v8_args_as_char_ptr.resize(argc);
812
  }
813
814
  // Anything that's still in v8_argv is not a V8 or a node option.
815
8499
  for (size_t i = 1; i < v8_args_as_char_ptr.size(); i++)
816
13
    errors->push_back("bad option: " + std::string(v8_args_as_char_ptr[i]));
817
818
8486
  if (v8_args_as_char_ptr.size() > 1) return 9;
819
820
8475
  return 0;
821
}
822
823
static std::atomic_bool init_called{false};
824
825
4325
int InitializeNodeWithArgs(std::vector<std::string>* argv,
826
                           std::vector<std::string>* exec_argv,
827
                           std::vector<std::string>* errors) {
828
  // Make sure InitializeNodeWithArgs() is called only once.
829
4325
  CHECK(!init_called.exchange(true));
830
831
  // Initialize node_start_time to get relative uptime.
832
4325
  per_process::node_start_time = uv_hrtime();
833
834
  // Register built-in modules
835
4325
  binding::RegisterBuiltinModules();
836
837
  // Make inherited handles noninheritable.
838
4325
  uv_disable_stdio_inheritance();
839
840
  // Cache the original command line to be
841
  // used in diagnostic reports.
842
4325
  per_process::cli_options->cmdline = *argv;
843
844
#if defined(NODE_V8_OPTIONS)
845
  // Should come before the call to V8::SetFlagsFromCommandLine()
846
  // so the user can disable a flag --foo at run-time by passing
847
  // --no_foo from the command line.
848
  V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1);
849
#endif
850
851
4325
  HandleEnvOptions(per_process::cli_options->per_isolate->per_env);
852
853
#if !defined(NODE_WITHOUT_NODE_OPTIONS)
854
8650
  std::string node_options;
855
856
4325
  if (credentials::SafeGetenv("NODE_OPTIONS", &node_options)) {
857
    std::vector<std::string> env_argv =
858
8427
        ParseNodeOptionsEnvVar(node_options, errors);
859
860
4222
    if (!errors->empty()) return 9;
861
862
    // [0] is expected to be the program name, fill it in from the real argv.
863
4222
    env_argv.insert(env_argv.begin(), argv->at(0));
864
865
    const int exit_code = ProcessGlobalArgs(&env_argv,
866
                                            nullptr,
867
                                            errors,
868
4222
                                            kAllowedInEnvironment);
869

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

8527
  if (per_process::cli_options->use_largepages == "on" ||
1002
4263
      per_process::cli_options->use_largepages == "silent") {
1003
1
    int result = node::MapStaticCodeToLargePages();
1004

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

12978
}  // namespace node
1109
1110
#if !HAVE_INSPECTOR
1111
void Initialize() {}
1112
1113
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1114
#endif  // !HAVE_INSPECTOR