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: 350 403 86.8 %
Date: 2020-02-19 22:14:06 Branches: 207 304 68.1 %

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_revert.h"
39
#include "node_v8_platform-inl.h"
40
#include "node_version.h"
41
42
#if HAVE_OPENSSL
43
#include "node_crypto.h"
44
#endif
45
46
#if defined(NODE_HAVE_I18N_SUPPORT)
47
#include "node_i18n.h"
48
#endif
49
50
#if HAVE_INSPECTOR
51
#include "inspector_agent.h"
52
#include "inspector_io.h"
53
#endif
54
55
#if defined HAVE_DTRACE || defined HAVE_ETW
56
#include "node_dtrace.h"
57
#endif
58
59
#if NODE_USE_V8_PLATFORM
60
#include "libplatform/libplatform.h"
61
#endif  // NODE_USE_V8_PLATFORM
62
#include "v8-profiler.h"
63
64
#if HAVE_INSPECTOR
65
#include "inspector/worker_inspector.h"  // ParentInspectorHandle
66
#endif
67
68
#ifdef NODE_ENABLE_LARGE_CODE_PAGES
69
#include "large_pages/node_large_page.h"
70
#endif
71
72
#ifdef NODE_REPORT
73
#include "node_report.h"
74
#endif
75
76
#if defined(__APPLE__) || defined(__linux__)
77
#define NODE_USE_V8_WASM_TRAP_HANDLER 1
78
#else
79
#define NODE_USE_V8_WASM_TRAP_HANDLER 0
80
#endif
81
82
#if NODE_USE_V8_WASM_TRAP_HANDLER
83
#include <atomic>
84
#include "v8-wasm-trap-handler-posix.h"
85
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
86
87
// ========== global C headers ==========
88
89
#include <fcntl.h>  // _O_RDWR
90
#include <sys/types.h>
91
92
#if defined(NODE_HAVE_I18N_SUPPORT)
93
#include <unicode/uvernum.h>
94
#include <unicode/utypes.h>
95
#endif
96
97
98
#if defined(LEAK_SANITIZER)
99
#include <sanitizer/lsan_interface.h>
100
#endif
101
102
#if defined(_MSC_VER)
103
#include <direct.h>
104
#include <io.h>
105
#define STDIN_FILENO 0
106
#else
107
#include <pthread.h>
108
#include <sys/resource.h>  // getrlimit, setrlimit
109
#include <termios.h>       // tcgetattr, tcsetattr
110
#include <unistd.h>        // STDIN_FILENO, STDERR_FILENO
111
#endif
112
113
// ========== global C++ headers ==========
114
115
#include <cerrno>
116
#include <climits>  // PATH_MAX
117
#include <csignal>
118
#include <cstdio>
119
#include <cstdlib>
120
#include <cstring>
121
122
#include <string>
123
#include <vector>
124
125
namespace node {
126
127
using native_module::NativeModuleEnv;
128
129
using v8::EscapableHandleScope;
130
using v8::Function;
131
using v8::FunctionCallbackInfo;
132
using v8::HandleScope;
133
using v8::Isolate;
134
using v8::Local;
135
using v8::Maybe;
136
using v8::MaybeLocal;
137
using v8::Object;
138
using v8::String;
139
using v8::Undefined;
140
using v8::V8;
141
using v8::Value;
142
143
namespace per_process {
144
145
// node_revert.h
146
// Bit flag used to track security reverts.
147
unsigned int reverted_cve = 0;
148
149
// util.h
150
// Tells whether the per-process V8::Initialize() is called and
151
// if it is safe to call v8::Isolate::GetCurrent().
152
bool v8_initialized = false;
153
154
// node_internals.h
155
// process-relative uptime base in nanoseconds, initialized in node::Start()
156
uint64_t node_start_time;
157
// Tells whether --prof is passed.
158
bool v8_is_profiling = false;
159
160
// node_v8_platform-inl.h
161
4186
struct V8Platform v8_platform;
162
}  // namespace per_process
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
21885
MaybeLocal<Value> ExecuteBootstrapper(Environment* env,
172
                                      const char* id,
173
                                      std::vector<Local<String>>* parameters,
174
                                      std::vector<Local<Value>>* arguments) {
175
21885
  EscapableHandleScope scope(env->isolate());
176
  MaybeLocal<Function> maybe_fn =
177
21885
      NativeModuleEnv::LookupAndCompile(env->context(), id, parameters, env);
178
179
21885
  if (maybe_fn.IsEmpty()) {
180
    return MaybeLocal<Value>();
181
  }
182
183
21885
  Local<Function> fn = maybe_fn.ToLocalChecked();
184
  MaybeLocal<Value> result = fn->Call(env->context(),
185
                                      Undefined(env->isolate()),
186
21885
                                      arguments->size(),
187
87540
                                      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
21647
  if (result.IsEmpty()) {
196
29
    env->async_hooks()->clear_async_id_stack();
197
  }
198
199
21647
  return scope.EscapeMaybe(result);
200
}
201
202
#if HAVE_INSPECTOR
203
4352
int Environment::InitializeInspector(
204
    std::unique_ptr<inspector::ParentInspectorHandle> parent_handle) {
205
8704
  std::string inspector_path;
206
4352
  if (parent_handle) {
207
    DCHECK(!is_main_thread());
208
228
    inspector_path = parent_handle->url();
209
228
    inspector_agent_->SetParentHandle(std::move(parent_handle));
210
  } else {
211
4124
    inspector_path = argv_.size() > 1 ? argv_[1].c_str() : "";
212
  }
213
214
4352
  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
8704
  inspector_agent_->Start(inspector_path,
219
                          options_->debug_options(),
220
8704
                          inspector_host_port(),
221
8704
                          is_main_thread());
222

4430
  if (options_->debug_options().inspector_enabled &&
223
78
      !inspector_agent_->IsListening()) {
224
5
    return 12;  // Signal internal error
225
  }
226
227
4347
  profiler::StartProfilers(this);
228
229
4347
  if (inspector_agent_->options().break_node_first_line) {
230
    inspector_agent_->PauseOnNextJavascriptStatement("Break at bootstrap");
231
  }
232
233
4347
  return 0;
234
}
235
#endif  // HAVE_INSPECTOR && NODE_USE_V8_PLATFORM
236
237
4352
void Environment::InitializeDiagnostics() {
238
4352
  isolate_->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
239
4352
      Environment::BuildEmbedderGraph, this);
240
4352
  if (options_->trace_uncaught)
241
3
    isolate_->SetCaptureStackTraceForUncaughtExceptions(true);
242
243
#if defined HAVE_DTRACE || defined HAVE_ETW
244
  InitDTrace(this);
245
#endif
246
4352
}
247
248
4377
MaybeLocal<Value> Environment::BootstrapInternalLoaders() {
249
4377
  EscapableHandleScope scope(isolate_);
250
251
  // Create binding loaders
252
  std::vector<Local<String>> loaders_params = {
253
      process_string(),
254
4377
      FIXED_ONE_BYTE_STRING(isolate_, "getLinkedBinding"),
255
4377
      FIXED_ONE_BYTE_STRING(isolate_, "getInternalBinding"),
256
17508
      primordials_string()};
257
  std::vector<Local<Value>> loaders_args = {
258
      process_object(),
259
8754
      NewFunctionTemplate(binding::GetLinkedBinding)
260
13131
          ->GetFunction(context())
261
          .ToLocalChecked(),
262
8754
      NewFunctionTemplate(binding::GetInternalBinding)
263
13131
          ->GetFunction(context())
264
          .ToLocalChecked(),
265
17508
      primordials()};
266
267
  // Bootstrap internal loaders
268
  Local<Value> loader_exports;
269
8754
  if (!ExecuteBootstrapper(
270
           this, "internal/bootstrap/loaders", &loaders_params, &loaders_args)
271
4377
           .ToLocal(&loader_exports)) {
272
    return MaybeLocal<Value>();
273
  }
274
4377
  CHECK(loader_exports->IsObject());
275
4377
  Local<Object> loader_exports_obj = loader_exports.As<Object>();
276
  Local<Value> internal_binding_loader =
277
17508
      loader_exports_obj->Get(context(), internal_binding_string())
278
4377
          .ToLocalChecked();
279
4377
  CHECK(internal_binding_loader->IsFunction());
280
4377
  set_internal_binding_loader(internal_binding_loader.As<Function>());
281
  Local<Value> require =
282
17508
      loader_exports_obj->Get(context(), require_string()).ToLocalChecked();
283
4377
  CHECK(require->IsFunction());
284
4377
  set_native_module_require(require.As<Function>());
285
286
4377
  return scope.Escape(loader_exports);
287
}
288
289
4377
MaybeLocal<Value> Environment::BootstrapNode() {
290
4377
  EscapableHandleScope scope(isolate_);
291
292
8754
  Local<Object> global = context()->Global();
293
  // TODO(joyeecheung): this can be done in JS land now.
294
17508
  global->Set(context(), FIXED_ONE_BYTE_STRING(isolate_, "global"), global)
295
      .Check();
296
297
  // process, require, internalBinding, primordials
298
  std::vector<Local<String>> node_params = {
299
      process_string(),
300
      require_string(),
301
      internal_binding_string(),
302
8754
      primordials_string()};
303
  std::vector<Local<Value>> node_args = {
304
      process_object(),
305
      native_module_require(),
306
      internal_binding_loader(),
307
26262
      primordials()};
308
309
  MaybeLocal<Value> result = ExecuteBootstrapper(
310
4377
      this, "internal/bootstrap/node", &node_params, &node_args);
311
312
4377
  if (result.IsEmpty()) {
313
    return scope.EscapeMaybe(result);
314
  }
315
316
  auto thread_switch_id =
317
4377
      is_main_thread() ? "internal/bootstrap/switches/is_main_thread"
318
4377
                       : "internal/bootstrap/switches/is_not_main_thread";
319
  result =
320
4377
      ExecuteBootstrapper(this, thread_switch_id, &node_params, &node_args);
321
322
4377
  if (result.IsEmpty()) {
323
    return scope.EscapeMaybe(result);
324
  }
325
326
  auto process_state_switch_id =
327
4377
      owns_process_state()
328
4377
          ? "internal/bootstrap/switches/does_own_process_state"
329
4377
          : "internal/bootstrap/switches/does_not_own_process_state";
330
  result = ExecuteBootstrapper(
331
4377
      this, process_state_switch_id, &node_params, &node_args);
332
333
4377
  if (result.IsEmpty()) {
334
    return scope.EscapeMaybe(result);
335
  }
336
337
4377
  Local<String> env_string = FIXED_ONE_BYTE_STRING(isolate_, "env");
338
  Local<Object> env_var_proxy;
339
17508
  if (!CreateEnvVarProxy(context(), isolate_, as_callback_data())
340

13131
           .ToLocal(&env_var_proxy) ||
341
17508
      process_object()->Set(context(), env_string, env_var_proxy).IsNothing()) {
342
    return MaybeLocal<Value>();
343
  }
344
345
4377
  return scope.EscapeMaybe(result);
346
}
347
348
4377
MaybeLocal<Value> Environment::RunBootstrapping() {
349
4377
  EscapableHandleScope scope(isolate_);
350
351
4377
  CHECK(!has_run_bootstrapping_code());
352
353
8754
  if (BootstrapInternalLoaders().IsEmpty()) {
354
    return MaybeLocal<Value>();
355
  }
356
357
  Local<Value> result;
358
8754
  if (!BootstrapNode().ToLocal(&result)) {
359
    return MaybeLocal<Value>();
360
  }
361
362
  // Make sure that no request or handle is created during bootstrap -
363
  // if necessary those should be done in pre-execution.
364
  // Usually, doing so would trigger the checks present in the ReqWrap and
365
  // HandleWrap classes, so this is only a consistency check.
366
4377
  CHECK(req_wrap_queue()->IsEmpty());
367
4377
  CHECK(handle_wrap_queue()->IsEmpty());
368
369
4377
  set_has_run_bootstrapping_code(true);
370
371
4377
  return scope.Escape(result);
372
}
373
374
4362
void MarkBootstrapComplete(const FunctionCallbackInfo<Value>& args) {
375
4362
  Environment* env = Environment::GetCurrent(args);
376
4362
  env->performance_state()->Mark(
377
4362
      performance::NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE);
378
4362
}
379
380
4351
MaybeLocal<Value> StartExecution(Environment* env, const char* main_script_id) {
381
4351
  EscapableHandleScope scope(env->isolate());
382
4351
  CHECK_NOT_NULL(main_script_id);
383
384
  std::vector<Local<String>> parameters = {
385
      env->process_string(),
386
      env->require_string(),
387
      env->internal_binding_string(),
388
      env->primordials_string(),
389
8464
      FIXED_ONE_BYTE_STRING(env->isolate(), "markBootstrapComplete")};
390
391
  std::vector<Local<Value>> arguments = {
392
      env->process_object(),
393
      env->native_module_require(),
394
      env->internal_binding_loader(),
395
      env->primordials(),
396
8702
      env->NewFunctionTemplate(MarkBootstrapComplete)
397
13053
          ->GetFunction(env->context())
398
25868
          .ToLocalChecked()};
399
400
  return scope.EscapeMaybe(
401
8464
      ExecuteBootstrapper(env, main_script_id, &parameters, &arguments));
402
}
403
404
4123
MaybeLocal<Value> StartMainThreadExecution(Environment* env) {
405
  // To allow people to extend Node in different ways, this hook allows
406
  // one to drop a file lib/_third_party_main.js into the build
407
  // directory which will be executed instead of Node's normal loading.
408
4123
  if (NativeModuleEnv::Exists("_third_party_main")) {
409
    return StartExecution(env, "internal/main/run_third_party_main");
410
  }
411
412
8008
  std::string first_argv;
413
4123
  if (env->argv().size() > 1) {
414
3798
    first_argv = env->argv()[1];
415
  }
416
417

4123
  if (first_argv == "inspect" || first_argv == "debug") {
418
4
    return StartExecution(env, "internal/main/inspect");
419
  }
420
421
4119
  if (per_process::cli_options->print_help) {
422
1
    return StartExecution(env, "internal/main/print_help");
423
  }
424
425
426
4118
  if (env->options()->prof_process) {
427
1
    return StartExecution(env, "internal/main/prof_process");
428
  }
429
430
  // -e/--eval without -i/--interactive
431


4117
  if (env->options()->has_eval_string && !env->options()->force_repl) {
432
299
    return StartExecution(env, "internal/main/eval_string");
433
  }
434
435
3818
  if (env->options()->syntax_check_only) {
436
34
    return StartExecution(env, "internal/main/check_syntax");
437
  }
438
439

3784
  if (!first_argv.empty() && first_argv != "-") {
440
3748
    return StartExecution(env, "internal/main/run_main_module");
441
  }
442
443


36
  if (env->options()->force_repl || uv_guess_handle(STDIN_FILENO) == UV_TTY) {
444
19
    return StartExecution(env, "internal/main/repl");
445
  }
446
447
17
  return StartExecution(env, "internal/main/eval_stdin");
448
}
449
450
4123
void LoadEnvironment(Environment* env) {
451
4123
  CHECK(env->is_main_thread());
452
  // TODO(joyeecheung): Not all of the execution modes in
453
  // StartMainThreadExecution() make sense for embedders. Pick the
454
  // useful ones out, and allow embedders to customize the entry
455
  // point more directly without using _third_party_main.js
456
4123
  USE(StartMainThreadExecution(env));
457
3885
}
458
459
#ifdef __POSIX__
460
typedef void (*sigaction_cb)(int signo, siginfo_t* info, void* ucontext);
461
#endif
462
#if NODE_USE_V8_WASM_TRAP_HANDLER
463
4186
static std::atomic<sigaction_cb> previous_sigsegv_action;
464
465
6
void TrapWebAssemblyOrContinue(int signo, siginfo_t* info, void* ucontext) {
466
6
  if (!v8::TryHandleWebAssemblyTrapPosix(signo, info, ucontext)) {
467
6
    sigaction_cb prev = previous_sigsegv_action.load();
468
6
    if (prev != nullptr) {
469
6
      prev(signo, info, ucontext);
470
    } else {
471
      // Reset to the default signal handler, i.e. cause a hard crash.
472
      struct sigaction sa;
473
      memset(&sa, 0, sizeof(sa));
474
      sa.sa_handler = SIG_DFL;
475
      CHECK_EQ(sigaction(signo, &sa, nullptr), 0);
476
477
      ResetStdio();
478
      raise(signo);
479
    }
480
  }
481
6
}
482
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
483
484
#ifdef __POSIX__
485
12744
void RegisterSignalHandler(int signal,
486
                           sigaction_cb handler,
487
                           bool reset_handler) {
488
12744
  CHECK_NOT_NULL(handler);
489
#if NODE_USE_V8_WASM_TRAP_HANDLER
490
12744
  if (signal == SIGSEGV) {
491
4
    CHECK(previous_sigsegv_action.is_lock_free());
492
4
    CHECK(!reset_handler);
493
4
    previous_sigsegv_action.store(handler);
494
4
    return;
495
  }
496
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
497
  struct sigaction sa;
498
12740
  memset(&sa, 0, sizeof(sa));
499
12740
  sa.sa_sigaction = handler;
500
12740
  sa.sa_flags = reset_handler ? SA_RESETHAND : 0;
501
12740
  sigfillset(&sa.sa_mask);
502
12740
  CHECK_EQ(sigaction(signal, &sa, nullptr), 0);
503
}
504
505
#endif  // __POSIX__
506
507
#ifdef __POSIX__
508
static struct {
509
  int flags;
510
  bool isatty;
511
  struct stat stat;
512
  struct termios termios;
513
} stdio[1 + STDERR_FILENO];
514
#endif  // __POSIX__
515
516
517
4184
inline void PlatformInit() {
518
#ifdef __POSIX__
519
#if HAVE_INSPECTOR
520
  sigset_t sigmask;
521
4184
  sigemptyset(&sigmask);
522
4184
  sigaddset(&sigmask, SIGUSR1);
523
4184
  const int err = pthread_sigmask(SIG_SETMASK, &sigmask, nullptr);
524
#endif  // HAVE_INSPECTOR
525
526
  // Make sure file descriptors 0-2 are valid before we start logging anything.
527
16736
  for (auto& s : stdio) {
528
12552
    const int fd = &s - stdio;
529
12552
    if (fstat(fd, &s.stat) == 0)
530
12550
      continue;
531
    // Anything but EBADF means something is seriously wrong.  We don't
532
    // have to special-case EINTR, fstat() is not interruptible.
533
2
    if (errno != EBADF)
534
      ABORT();
535
2
    if (fd != open("/dev/null", O_RDWR))
536
      ABORT();
537
2
    if (fstat(fd, &s.stat) != 0)
538
      ABORT();
539
  }
540
541
#if HAVE_INSPECTOR
542
4184
  CHECK_EQ(err, 0);
543
#endif  // HAVE_INSPECTOR
544
545
  // TODO(addaleax): NODE_SHARED_MODE does not really make sense here.
546
#ifndef NODE_SHARED_MODE
547
  // Restore signal dispositions, the parent process may have changed them.
548
  struct sigaction act;
549
4184
  memset(&act, 0, sizeof(act));
550
551
  // The hard-coded upper limit is because NSIG is not very reliable; on Linux,
552
  // it evaluates to 32, 34 or 64, depending on whether RT signals are enabled.
553
  // Counting up to SIGRTMIN doesn't work for the same reason.
554
133888
  for (unsigned nr = 1; nr < kMaxSignal; nr += 1) {
555

129704
    if (nr == SIGKILL || nr == SIGSTOP)
556
8368
      continue;
557

121336
    act.sa_handler = (nr == SIGPIPE || nr == SIGXFSZ) ? SIG_IGN : SIG_DFL;
558
121336
    CHECK_EQ(0, sigaction(nr, &act, nullptr));
559
  }
560
#endif  // !NODE_SHARED_MODE
561
562
  // Record the state of the stdio file descriptors so we can restore it
563
  // on exit.  Needs to happen before installing signal handlers because
564
  // they make use of that information.
565
16736
  for (auto& s : stdio) {
566
12552
    const int fd = &s - stdio;
567
    int err;
568
569
    do
570
12552
      s.flags = fcntl(fd, F_GETFL);
571

12552
    while (s.flags == -1 && errno == EINTR);  // NOLINT
572
12552
    CHECK_NE(s.flags, -1);
573
574
12552
    if (uv_guess_handle(fd) != UV_TTY) continue;
575
120
    s.isatty = true;
576
577
    do
578
120
      err = tcgetattr(fd, &s.termios);
579

120
    while (err == -1 && errno == EINTR);  // NOLINT
580
120
    CHECK_EQ(err, 0);
581
  }
582
583
4184
  RegisterSignalHandler(SIGINT, SignalExit, true);
584
4184
  RegisterSignalHandler(SIGTERM, SignalExit, true);
585
586
#if NODE_USE_V8_WASM_TRAP_HANDLER
587
  // Tell V8 to disable emitting WebAssembly
588
  // memory bounds checks. This means that we have
589
  // to catch the SIGSEGV in TrapWebAssemblyOrContinue
590
  // and pass the signal context to V8.
591
  {
592
    struct sigaction sa;
593
4184
    memset(&sa, 0, sizeof(sa));
594
4184
    sa.sa_sigaction = TrapWebAssemblyOrContinue;
595
4184
    CHECK_EQ(sigaction(SIGSEGV, &sa, nullptr), 0);
596
  }
597
4184
  V8::EnableWebAssemblyTrapHandler(false);
598
#endif  // NODE_USE_V8_WASM_TRAP_HANDLER
599
600
  // Raise the open file descriptor limit.
601
  struct rlimit lim;
602

4184
  if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
603
    // Do a binary search for the limit.
604
    rlim_t min = lim.rlim_cur;
605
    rlim_t max = 1 << 20;
606
    // But if there's a defined upper bound, don't search, just set it.
607
    if (lim.rlim_max != RLIM_INFINITY) {
608
      min = lim.rlim_max;
609
      max = lim.rlim_max;
610
    }
611
    do {
612
      lim.rlim_cur = min + (max - min) / 2;
613
      if (setrlimit(RLIMIT_NOFILE, &lim)) {
614
        max = lim.rlim_cur;
615
      } else {
616
        min = lim.rlim_cur;
617
      }
618
    } while (min + 1 < max);
619
  }
620
#endif  // __POSIX__
621
#ifdef _WIN32
622
  for (int fd = 0; fd <= 2; ++fd) {
623
    auto handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
624
    if (handle == INVALID_HANDLE_VALUE ||
625
        GetFileType(handle) == FILE_TYPE_UNKNOWN) {
626
      // Ignore _close result. If it fails or not depends on used Windows
627
      // version. We will just check _open result.
628
      _close(fd);
629
      if (fd != _open("nul", _O_RDWR))
630
        ABORT();
631
    }
632
  }
633
#endif  // _WIN32
634
4184
}
635
636
637
// Safe to call more than once and from signal handlers.
638
7917
void ResetStdio() {
639
7917
  uv_tty_reset_mode();
640
#ifdef __POSIX__
641
31668
  for (auto& s : stdio) {
642
23751
    const int fd = &s - stdio;
643
644
    struct stat tmp;
645
23751
    if (-1 == fstat(fd, &tmp)) {
646
      CHECK_EQ(errno, EBADF);  // Program closed file descriptor.
647
6
      continue;
648
    }
649
650
    bool is_same_file =
651

23751
        (s.stat.st_dev == tmp.st_dev && s.stat.st_ino == tmp.st_ino);
652
23751
    if (!is_same_file) continue;  // Program reopened file descriptor.
653
654
    int flags;
655
    do
656
23745
      flags = fcntl(fd, F_GETFL);
657

23745
    while (flags == -1 && errno == EINTR);  // NOLINT
658
23745
    CHECK_NE(flags, -1);
659
660
    // Restore the O_NONBLOCK flag if it changed.
661
23745
    if (O_NONBLOCK & (flags ^ s.flags)) {
662
772
      flags &= ~O_NONBLOCK;
663
772
      flags |= s.flags & O_NONBLOCK;
664
665
      int err;
666
      do
667
772
        err = fcntl(fd, F_SETFL, flags);
668

772
      while (err == -1 && errno == EINTR);  // NOLINT
669
772
      CHECK_NE(err, -1);
670
    }
671
672
23745
    if (s.isatty) {
673
      sigset_t sa;
674
      int err;
675
676
      // We might be a background job that doesn't own the TTY so block SIGTTOU
677
      // before making the tcsetattr() call, otherwise that signal suspends us.
678
228
      sigemptyset(&sa);
679
228
      sigaddset(&sa, SIGTTOU);
680
681
228
      CHECK_EQ(0, pthread_sigmask(SIG_BLOCK, &sa, nullptr));
682
      do
683
228
        err = tcsetattr(fd, TCSANOW, &s.termios);
684

228
      while (err == -1 && errno == EINTR);  // NOLINT
685
228
      CHECK_EQ(0, pthread_sigmask(SIG_UNBLOCK, &sa, nullptr));
686
228
      CHECK_EQ(0, err);
687
    }
688
  }
689
#endif  // __POSIX__
690
7917
}
691
692
693
8257
int ProcessGlobalArgs(std::vector<std::string>* args,
694
                      std::vector<std::string>* exec_args,
695
                      std::vector<std::string>* errors,
696
                      OptionEnvvarSettings settings) {
697
  // Parse a few arguments which are specific to Node.
698
16514
  std::vector<std::string> v8_args;
699
700
16514
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
701
8257
  options_parser::Parse(
702
      args,
703
      exec_args,
704
      &v8_args,
705
      per_process::cli_options.get(),
706
      settings,
707
8257
      errors);
708
709
8257
  if (!errors->empty()) return 9;
710
711
16430
  std::string revert_error;
712
8215
  for (const std::string& cve : per_process::cli_options->security_reverts) {
713
1
    Revert(cve.c_str(), &revert_error);
714
1
    if (!revert_error.empty()) {
715
1
      errors->emplace_back(std::move(revert_error));
716
1
      return 12;
717
    }
718
  }
719
720
16428
  auto env_opts = per_process::cli_options->per_isolate->per_env;
721
32856
  if (std::find(v8_args.begin(), v8_args.end(),
722

32839
                "--abort-on-uncaught-exception") != v8_args.end() ||
723
16411
      std::find(v8_args.begin(), v8_args.end(),
724
24608
                "--abort_on_uncaught_exception") != v8_args.end()) {
725
20
    env_opts->abort_on_uncaught_exception = true;
726
  }
727
728
  // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
729
  // manually?  That would give us a little more control over its runtime
730
  // behavior but it could also interfere with the user's intentions in ways
731
  // we fail to anticipate.  Dillema.
732
8214
  if (std::find(v8_args.begin(), v8_args.end(), "--prof") != v8_args.end()) {
733
2
    per_process::v8_is_profiling = true;
734
  }
735
736
#ifdef __POSIX__
737
  // Block SIGPROF signals when sleeping in epoll_wait/kevent/etc.  Avoids the
738
  // performance penalty of frequent EINTR wakeups when the profiler is running.
739
  // Only do this for v8.log profiling, as it breaks v8::CpuProfiler users.
740
8214
  if (per_process::v8_is_profiling) {
741
2
    uv_loop_configure(uv_default_loop(), UV_LOOP_BLOCK_SIGNAL, SIGPROF);
742
  }
743
#endif
744
745
16428
  std::vector<char*> v8_args_as_char_ptr(v8_args.size());
746
8214
  if (v8_args.size() > 0) {
747
16581
    for (size_t i = 0; i < v8_args.size(); ++i)
748
8367
      v8_args_as_char_ptr[i] = &v8_args[i][0];
749
8214
    int argc = v8_args.size();
750
8214
    V8::SetFlagsFromCommandLine(&argc, &v8_args_as_char_ptr[0], true);
751
8214
    v8_args_as_char_ptr.resize(argc);
752
  }
753
754
  // Anything that's still in v8_argv is not a V8 or a node option.
755
8227
  for (size_t i = 1; i < v8_args_as_char_ptr.size(); i++)
756
13
    errors->push_back("bad option: " + std::string(v8_args_as_char_ptr[i]));
757
758
8214
  if (v8_args_as_char_ptr.size() > 1) return 9;
759
760
8203
  return 0;
761
}
762
763
static std::atomic_bool init_called{false};
764
765
4185
int InitializeNodeWithArgs(std::vector<std::string>* argv,
766
                           std::vector<std::string>* exec_argv,
767
                           std::vector<std::string>* errors) {
768
  // Make sure InitializeNodeWithArgs() is called only once.
769
4185
  CHECK(!init_called.exchange(true));
770
771
  // Initialize node_start_time to get relative uptime.
772
4185
  per_process::node_start_time = uv_hrtime();
773
774
  // Register built-in modules
775
4185
  binding::RegisterBuiltinModules();
776
777
  // Make inherited handles noninheritable.
778
4185
  uv_disable_stdio_inheritance();
779
780
#ifdef NODE_REPORT
781
  // Cache the original command line to be
782
  // used in diagnostic reports.
783
4185
  per_process::cli_options->cmdline = *argv;
784
#endif  //  NODE_REPORT
785
786
#if defined(NODE_V8_OPTIONS)
787
  // Should come before the call to V8::SetFlagsFromCommandLine()
788
  // so the user can disable a flag --foo at run-time by passing
789
  // --no_foo from the command line.
790
  V8::SetFlagsFromString(NODE_V8_OPTIONS, sizeof(NODE_V8_OPTIONS) - 1);
791
#endif
792
793
4185
  HandleEnvOptions(per_process::cli_options->per_isolate->per_env);
794
795
#if !defined(NODE_WITHOUT_NODE_OPTIONS)
796
8370
  std::string node_options;
797
798
4185
  if (credentials::SafeGetenv("NODE_OPTIONS", &node_options)) {
799
    std::vector<std::string> env_argv =
800
8159
        ParseNodeOptionsEnvVar(node_options, errors);
801
802
4087
    if (!errors->empty()) return 9;
803
804
    // [0] is expected to be the program name, fill it in from the real argv.
805
4087
    env_argv.insert(env_argv.begin(), argv->at(0));
806
807
    const int exit_code = ProcessGlobalArgs(&env_argv,
808
                                            nullptr,
809
                                            errors,
810
4087
                                            kAllowedInEnvironment);
811

4087
    if (exit_code != 0) return exit_code;
812
  }
813
#endif
814
815
  const int exit_code = ProcessGlobalArgs(argv,
816
                                          exec_argv,
817
                                          errors,
818
4170
                                          kDisallowedInEnvironment);
819
4170
  if (exit_code != 0) return exit_code;
820
821
  // Set the process.title immediately after processing argv if --title is set.
822
4131
  if (!per_process::cli_options->title.empty())
823
2
    uv_set_process_title(per_process::cli_options->title.c_str());
824
825
#if defined(NODE_HAVE_I18N_SUPPORT)
826
  // If the parameter isn't given, use the env variable.
827
4131
  if (per_process::cli_options->icu_data_dir.empty())
828
4131
    credentials::SafeGetenv("NODE_ICU_DATA",
829
8262
                            &per_process::cli_options->icu_data_dir);
830
831
#ifdef NODE_ICU_DEFAULT_DATA_DIR
832
  // If neither the CLI option nor the environment variable was specified,
833
  // fall back to the configured default
834
  if (per_process::cli_options->icu_data_dir.empty()) {
835
    // Check whether the NODE_ICU_DEFAULT_DATA_DIR contains the right data
836
    // file and can be read.
837
    static const char full_path[] =
838
        NODE_ICU_DEFAULT_DATA_DIR "/" U_ICUDATA_NAME ".dat";
839
840
    FILE* f = fopen(full_path, "rb");
841
842
    if (f != nullptr) {
843
      fclose(f);
844
      per_process::cli_options->icu_data_dir = NODE_ICU_DEFAULT_DATA_DIR;
845
    }
846
  }
847
#endif  // NODE_ICU_DEFAULT_DATA_DIR
848
849
  // Initialize ICU.
850
  // If icu_data_dir is empty here, it will load the 'minimal' data.
851
4131
  if (!i18n::InitializeICUDirectory(per_process::cli_options->icu_data_dir)) {
852
    errors->push_back("could not initialize ICU "
853
                      "(check NODE_ICU_DATA or --icu-data-dir parameters)\n");
854
    return 9;
855
  }
856
4131
  per_process::metadata.versions.InitializeIntlVersions();
857
#endif
858
859
4131
  NativeModuleEnv::InitializeCodeCache();
860
861
  // We should set node_is_initialized here instead of in node::Start,
862
  // otherwise embedders using node::Init to initialize everything will not be
863
  // able to set it and native modules will not load for them.
864
4131
  node_is_initialized = true;
865
4131
  return 0;
866
}
867
868
// TODO(addaleax): Deprecate and eventually remove this.
869
1
void Init(int* argc,
870
          const char** argv,
871
          int* exec_argc,
872
          const char*** exec_argv) {
873
2
  std::vector<std::string> argv_(argv, argv + *argc);  // NOLINT
874
2
  std::vector<std::string> exec_argv_;
875
2
  std::vector<std::string> errors;
876
877
  // This (approximately) duplicates some logic that has been moved to
878
  // node::Start(), with the difference that here we explicitly call `exit()`.
879
1
  int exit_code = InitializeNodeWithArgs(&argv_, &exec_argv_, &errors);
880
881
1
  for (const std::string& error : errors)
882
    fprintf(stderr, "%s: %s\n", argv_.at(0).c_str(), error.c_str());
883
1
  if (exit_code != 0) exit(exit_code);
884
885
1
  if (per_process::cli_options->print_version) {
886
    printf("%s\n", NODE_VERSION);
887
    exit(0);
888
  }
889
890
1
  if (per_process::cli_options->print_bash_completion) {
891
    std::string completion = options_parser::GetBashCompletion();
892
    printf("%s\n", completion.c_str());
893
    exit(0);
894
  }
895
896
1
  if (per_process::cli_options->print_v8_help) {
897
    // Doesn't return.
898
    V8::SetFlagsFromString("--help", static_cast<size_t>(6));
899
    UNREACHABLE();
900
  }
901
902
1
  *argc = argv_.size();
903
1
  *exec_argc = exec_argv_.size();
904
  // These leak memory, because, in the original code of this function, no
905
  // extra allocations were visible. This should be okay because this function
906
  // is only supposed to be called once per process, though.
907
1
  *exec_argv = Malloc<const char*>(*exec_argc);
908
1
  for (int i = 0; i < *exec_argc; ++i)
909
    (*exec_argv)[i] = strdup(exec_argv_[i].c_str());
910
2
  for (int i = 0; i < *argc; ++i)
911
1
    argv[i] = strdup(argv_[i].c_str());
912
1
}
913
914
4184
InitializationResult InitializeOncePerProcess(int argc, char** argv) {
915
4184
  atexit(ResetStdio);
916
4184
  PlatformInit();
917
918
4184
  CHECK_GT(argc, 0);
919
920
  // Hack around with the argv pointer. Used for process.title = "blah".
921
4184
  argv = uv_setup_args(argc, argv);
922
923
4184
  InitializationResult result;
924
4184
  result.args = std::vector<std::string>(argv, argv + argc);
925
8366
  std::vector<std::string> errors;
926
927
  // This needs to run *before* V8::Initialize().
928
  {
929
4184
    result.exit_code =
930
4184
        InitializeNodeWithArgs(&(result.args), &(result.exec_args), &errors);
931
4240
    for (const std::string& error : errors)
932
56
      fprintf(stderr, "%s: %s\n", result.args.at(0).c_str(), error.c_str());
933
4184
    if (result.exit_code != 0) {
934
54
      result.early_return = true;
935
54
      return result;
936
    }
937
  }
938
939
#if defined(NODE_ENABLE_LARGE_CODE_PAGES) && NODE_ENABLE_LARGE_CODE_PAGES
940

8259
  if (per_process::cli_options->use_largepages == "on" ||
941
4129
      per_process::cli_options->use_largepages == "silent") {
942
1
    if (node::IsLargePagesEnabled()) {
943
      if (node::MapStaticCodeToLargePages() != 0 &&
944
          per_process::cli_options->use_largepages != "silent") {
945
        fprintf(stderr,
946
                "Mapping code to large pages failed. Reverting to default page "
947
                "size.\n");
948
      }
949
1
    } else if (per_process::cli_options->use_largepages != "silent") {
950
1
      fprintf(stderr, "Large pages are not enabled.\n");
951
    }
952
  }
953
#else
954
  if (per_process::cli_options->use_largepages == "on") {
955
    fprintf(stderr, "Mapping to large pages is not supported.\n");
956
  }
957
#endif  // NODE_ENABLE_LARGE_CODE_PAGES
958
959
4130
  if (per_process::cli_options->print_version) {
960
3
    printf("%s\n", NODE_VERSION);
961
3
    result.exit_code = 0;
962
3
    result.early_return = true;
963
3
    return result;
964
  }
965
966
4127
  if (per_process::cli_options->print_bash_completion) {
967
1
    std::string completion = options_parser::GetBashCompletion();
968
1
    printf("%s\n", completion.c_str());
969
1
    exit(0);
970
  }
971
972
4126
  if (per_process::cli_options->print_v8_help) {
973
    // Doesn't return.
974
1
    V8::SetFlagsFromString("--help", static_cast<size_t>(6));
975
    UNREACHABLE();
976
  }
977
978
#if HAVE_OPENSSL
979
  {
980
8250
    std::string extra_ca_certs;
981
4125
    if (credentials::SafeGetenv("NODE_EXTRA_CA_CERTS", &extra_ca_certs))
982
3
      crypto::UseExtraCaCerts(extra_ca_certs);
983
  }
984
#ifdef NODE_FIPS_MODE
985
  // In the case of FIPS builds we should make sure
986
  // the random source is properly initialized first.
987
  OPENSSL_init();
988
#endif  // NODE_FIPS_MODE
989
  // V8 on Windows doesn't have a good source of entropy. Seed it from
990
  // OpenSSL's pool.
991
4125
  V8::SetEntropySource(crypto::EntropySource);
992
#endif  // HAVE_OPENSSL
993
994
4125
  per_process::v8_platform.Initialize(
995
8250
      per_process::cli_options->v8_thread_pool_size);
996
4125
  V8::Initialize();
997
4125
  performance::performance_v8_start = PERFORMANCE_NOW();
998
4125
  per_process::v8_initialized = true;
999
4125
  return result;
1000
}
1001
1002
3720
void TearDownOncePerProcess() {
1003
3720
  per_process::v8_initialized = false;
1004
3720
  V8::Dispose();
1005
1006
  // uv_run cannot be called from the time before the beforeExit callback
1007
  // runs until the program exits unless the event loop has any referenced
1008
  // handles after beforeExit terminates. This prevents unrefed timers
1009
  // that happen to terminate during shutdown from being run unsafely.
1010
  // Since uv_run cannot be called, uv_async handles held by the platform
1011
  // will never be fully cleaned up.
1012
3720
  per_process::v8_platform.Dispose();
1013
3720
}
1014
1015
4183
int Start(int argc, char** argv) {
1016
7959
  InitializationResult result = InitializeOncePerProcess(argc, argv);
1017
4181
  if (result.early_return) {
1018
57
    return result.exit_code;
1019
  }
1020
1021
  {
1022
7843
    Isolate::CreateParams params;
1023
4124
    const std::vector<size_t>* indexes = nullptr;
1024
7843
    std::vector<intptr_t> external_references;
1025
1026
    bool force_no_snapshot =
1027
4124
        per_process::cli_options->per_isolate->no_node_snapshot;
1028
4124
    if (!force_no_snapshot) {
1029
4123
      v8::StartupData* blob = NodeMainInstance::GetEmbeddedSnapshotBlob();
1030
4123
      if (blob != nullptr) {
1031
        // TODO(joyeecheung): collect external references and set it in
1032
        // params.external_references.
1033
4123
        external_references.push_back(reinterpret_cast<intptr_t>(nullptr));
1034
4123
        params.external_references = external_references.data();
1035
4123
        params.snapshot_blob = blob;
1036
4123
        indexes = NodeMainInstance::GetIsolateDataIndexes();
1037
      }
1038
    }
1039
1040
    NodeMainInstance main_instance(&params,
1041
                                   uv_default_loop(),
1042
4124
                                   per_process::v8_platform.Platform(),
1043
                                   result.args,
1044
                                   result.exec_args,
1045
7843
                                   indexes);
1046
4124
    result.exit_code = main_instance.Run();
1047
  }
1048
1049
3719
  TearDownOncePerProcess();
1050
3719
  return result.exit_code;
1051
}
1052
1053
61
int Stop(Environment* env) {
1054
61
  env->ExitEnv();
1055
61
  return 0;
1056
}
1057
1058

12558
}  // namespace node
1059
1060
#if !HAVE_INSPECTOR
1061
void Initialize() {}
1062
1063
NODE_MODULE_CONTEXT_AWARE_INTERNAL(inspector, Initialize)
1064
#endif  // !HAVE_INSPECTOR