GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_options.cc Lines: 504 534 94.4 %
Date: 2020-05-27 22:15:15 Branches: 171 230 74.3 %

Line Branch Exec Source
1
#include "node_options.h"  // NOLINT(build/include_inline)
2
#include "node_options-inl.h"
3
4
#include "env-inl.h"
5
#include "node_binding.h"
6
#include "node_internals.h"
7
8
#include <errno.h>
9
#include <sstream>
10
#include <cstdlib>  // strtoul, errno
11
12
using v8::Boolean;
13
using v8::Context;
14
using v8::FunctionCallbackInfo;
15
using v8::Integer;
16
using v8::Isolate;
17
using v8::Local;
18
using v8::Map;
19
using v8::Number;
20
using v8::Object;
21
using v8::String;
22
using v8::Undefined;
23
using v8::Value;
24
25
namespace node {
26
27
namespace per_process {
28
4326
Mutex cli_options_mutex;
29
4326
std::shared_ptr<PerProcessOptions> cli_options{new PerProcessOptions()};
30
}  // namespace per_process
31
32
8613
void DebugOptions::CheckOptions(std::vector<std::string>* errors) {
33
#if !NODE_USE_V8_PLATFORM && !HAVE_INSPECTOR
34
  if (inspector_enabled) {
35
    errors->push_back("Inspector is not available when Node is compiled "
36
                      "--without-v8-platform and --without-inspector.");
37
  }
38
#endif
39
40
8613
  if (deprecated_debug) {
41
8
    errors->push_back("[DEP0062]: `node --debug` and `node --debug-brk` "
42
                      "are invalid. Please use `node --inspect` and "
43
4
                      "`node --inspect-brk` instead.");
44
  }
45
46
  std::vector<std::string> destinations =
47
17226
      SplitString(inspect_publish_uid_string, ',');
48
8613
  inspect_publish_uid.console = false;
49
8613
  inspect_publish_uid.http = false;
50
25837
  for (const std::string& destination : destinations) {
51
17224
    if (destination == "stderr") {
52
8612
      inspect_publish_uid.console = true;
53
8612
    } else if (destination == "http") {
54
8612
      inspect_publish_uid.http = true;
55
    } else {
56
      errors->push_back("--inspect-publish-uid destination can be "
57
                        "stderr or http");
58
    }
59
  }
60
8613
}
61
62
8530
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
63
#if HAVE_OPENSSL
64

8530
  if (use_openssl_ca && use_bundled_ca) {
65
2
    errors->push_back("either --use-openssl-ca or --use-bundled-ca can be "
66
1
                      "used, not both");
67
  }
68
#endif
69

17062
  if (use_largepages != "off" &&
70

8531
      use_largepages != "on" &&
71
1
      use_largepages != "silent") {
72
1
    errors->push_back("invalid value for --use-largepages");
73
  }
74
8530
  per_isolate->CheckOptions(errors);
75
8530
}
76
77
8613
void PerIsolateOptions::CheckOptions(std::vector<std::string>* errors) {
78
8613
  per_env->CheckOptions(errors);
79
8613
}
80
81
8613
void EnvironmentOptions::CheckOptions(std::vector<std::string>* errors) {
82

8613
  if (has_policy_integrity_string && experimental_policy.empty()) {
83
    errors->push_back("--policy-integrity requires "
84
                      "--experimental-policy be enabled");
85
  }
86

8613
  if (has_policy_integrity_string && experimental_policy_integrity.empty()) {
87
1
    errors->push_back("--policy-integrity cannot be empty");
88
  }
89
90
8613
  if (!module_type.empty()) {
91

16
    if (module_type != "commonjs" && module_type != "module") {
92
      errors->push_back("--input-type must be \"module\" or \"commonjs\"");
93
    }
94
  }
95
96
8613
  if (!es_module_specifier_resolution.empty()) {
97
6
    if (!experimental_specifier_resolution.empty()) {
98
2
      errors->push_back(
99
        "bad option: cannot use --es-module-specifier-resolution"
100
1
        " and --experimental-specifier-resolution at the same time");
101
    } else {
102
5
      experimental_specifier_resolution = es_module_specifier_resolution;
103

5
      if (experimental_specifier_resolution != "node" &&
104
          experimental_specifier_resolution != "explicit") {
105
        errors->push_back(
106
          "invalid value for --es-module-specifier-resolution");
107
      }
108
    }
109
8607
  } else if (!experimental_specifier_resolution.empty()) {
110

1
    if (experimental_specifier_resolution != "node" &&
111
        experimental_specifier_resolution != "explicit") {
112
      errors->push_back(
113
        "invalid value for --experimental-specifier-resolution");
114
    }
115
  }
116
117

8613
  if (syntax_check_only && has_eval_string) {
118
4
    errors->push_back("either --check or --eval can be used, not both");
119
  }
120
121

17237
  if (!unhandled_rejections.empty() &&
122
20
      unhandled_rejections != "strict" &&
123

8629
      unhandled_rejections != "warn" &&
124
7
      unhandled_rejections != "none") {
125
1
    errors->push_back("invalid value for --unhandled-rejections");
126
  }
127
128

8613
  if (tls_min_v1_3 && tls_max_v1_2) {
129
2
    errors->push_back("either --tls-min-v1.3 or --tls-max-v1.2 can be "
130
1
                      "used, not both");
131
  }
132
133
#if HAVE_INSPECTOR
134
8613
  if (!cpu_prof) {
135
8604
    if (!cpu_prof_name.empty()) {
136
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
137
    }
138
8604
    if (!cpu_prof_dir.empty()) {
139
1
      errors->push_back("--cpu-prof-dir must be used with --cpu-prof");
140
    }
141
    // We can't catch the case where the value passed is the default value,
142
    // then the option just becomes a noop which is fine.
143
8604
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
144
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
145
    }
146
  }
147
148
8613
  if (!heap_prof) {
149
8604
    if (!heap_prof_name.empty()) {
150
1
      errors->push_back("--heap-prof-name must be used with --heap-prof");
151
    }
152
8604
    if (!heap_prof_dir.empty()) {
153
1
      errors->push_back("--heap-prof-dir must be used with --heap-prof");
154
    }
155
    // We can't catch the case where the value passed is the default value,
156
    // then the option just becomes a noop which is fine.
157
8604
    if (heap_prof_interval != kDefaultHeapProfInterval) {
158
1
      errors->push_back("--heap-prof-interval must be used with --heap-prof");
159
    }
160
  }
161
8613
  debug_options_.CheckOptions(errors);
162
#endif  // HAVE_INSPECTOR
163
8613
}
164
165
namespace options_parser {
166
167
4326
class DebugOptionsParser : public OptionsParser<DebugOptions> {
168
 public:
169
  DebugOptionsParser();
170
};
171
172
4326
class EnvironmentOptionsParser : public OptionsParser<EnvironmentOptions> {
173
 public:
174
  EnvironmentOptionsParser();
175
4326
  explicit EnvironmentOptionsParser(const DebugOptionsParser& dop)
176
4326
    : EnvironmentOptionsParser() {
177
4326
    Insert(dop, &EnvironmentOptions::get_debug_options);
178
4326
  }
179
};
180
181
4326
class PerIsolateOptionsParser : public OptionsParser<PerIsolateOptions> {
182
 public:
183
  PerIsolateOptionsParser() = delete;
184
  explicit PerIsolateOptionsParser(const EnvironmentOptionsParser& eop);
185
};
186
187
4326
class PerProcessOptionsParser : public OptionsParser<PerProcessOptions> {
188
 public:
189
  PerProcessOptionsParser() = delete;
190
  explicit PerProcessOptionsParser(const PerIsolateOptionsParser& iop);
191
};
192
193
#if HAVE_INSPECTOR
194
4326
const DebugOptionsParser _dop_instance{};
195
4326
const EnvironmentOptionsParser _eop_instance{_dop_instance};
196
197
// This Parse is not dead code. It is used by embedders (e.g., Electron).
198
template <>
199
void Parse(
200
  StringVector* const args, StringVector* const exec_args,
201
  StringVector* const v8_args,
202
  DebugOptions* const options,
203
  OptionEnvvarSettings required_env_settings, StringVector* const errors) {
204
  _dop_instance.Parse(
205
    args, exec_args, v8_args, options, required_env_settings, errors);
206
}
207
#else
208
const EnvironmentOptionsParser _eop_instance{};
209
#endif  // HAVE_INSPECTOR
210
4326
const PerIsolateOptionsParser _piop_instance{_eop_instance};
211
4326
const PerProcessOptionsParser _ppop_instance{_piop_instance};
212
213
template <>
214
83
void Parse(
215
  StringVector* const args, StringVector* const exec_args,
216
  StringVector* const v8_args,
217
  PerIsolateOptions* const options,
218
  OptionEnvvarSettings required_env_settings, StringVector* const errors) {
219
  _piop_instance.Parse(
220
83
    args, exec_args, v8_args, options, required_env_settings, errors);
221
83
}
222
223
template <>
224
8530
void Parse(
225
  StringVector* const args, StringVector* const exec_args,
226
  StringVector* const v8_args,
227
  PerProcessOptions* const options,
228
  OptionEnvvarSettings required_env_settings, StringVector* const errors) {
229
  _ppop_instance.Parse(
230
8530
    args, exec_args, v8_args, options, required_env_settings, errors);
231
8530
}
232
233
// XXX: If you add an option here, please also add it to doc/node.1 and
234
// doc/api/cli.md
235
// TODO(addaleax): Make that unnecessary.
236
237
4326
DebugOptionsParser::DebugOptionsParser() {
238
4326
  AddOption("--inspect-port",
239
            "set host:port for inspector",
240
            &DebugOptions::host_port,
241
4326
            kAllowedInEnvironment);
242
4326
  AddAlias("--debug-port", "--inspect-port");
243
244
4326
  AddOption("--inspect",
245
            "activate inspector on host:port (default: 127.0.0.1:9229)",
246
            &DebugOptions::inspector_enabled,
247
4326
            kAllowedInEnvironment);
248
4326
  AddAlias("--inspect=", { "--inspect-port", "--inspect" });
249
250
4326
  AddOption("--debug", "", &DebugOptions::deprecated_debug);
251
4326
  AddAlias("--debug=", "--debug");
252
4326
  AddOption("--debug-brk", "", &DebugOptions::deprecated_debug);
253
4326
  AddAlias("--debug-brk=", "--debug-brk");
254
255
4326
  AddOption("--inspect-brk",
256
            "activate inspector on host:port and break at start of user script",
257
            &DebugOptions::break_first_line,
258
4326
            kAllowedInEnvironment);
259
4326
  Implies("--inspect-brk", "--inspect");
260
4326
  AddAlias("--inspect-brk=", { "--inspect-port", "--inspect-brk" });
261
262
4326
  AddOption("--inspect-brk-node", "", &DebugOptions::break_node_first_line);
263
4326
  Implies("--inspect-brk-node", "--inspect");
264
4326
  AddAlias("--inspect-brk-node=", { "--inspect-port", "--inspect-brk-node" });
265
266
4326
  AddOption("--inspect-publish-uid",
267
            "comma separated list of destinations for inspector uid"
268
            "(default: stderr,http)",
269
            &DebugOptions::inspect_publish_uid_string,
270
4326
            kAllowedInEnvironment);
271
4326
}
272
273
4326
EnvironmentOptionsParser::EnvironmentOptionsParser() {
274
4326
  AddOption("--enable-source-maps",
275
            "experimental Source Map V3 support",
276
            &EnvironmentOptions::enable_source_maps,
277
4326
            kAllowedInEnvironment);
278
4326
  AddOption("--experimental-json-modules",
279
            "experimental JSON interop support for the ES Module loader",
280
            &EnvironmentOptions::experimental_json_modules,
281
4326
            kAllowedInEnvironment);
282
4326
  AddOption("--experimental-loader",
283
            "use the specified module as a custom loader",
284
            &EnvironmentOptions::userland_loader,
285
4326
            kAllowedInEnvironment);
286
4326
  AddAlias("--loader", "--experimental-loader");
287
4326
  AddOption("--experimental-modules",
288
            "",
289
            &EnvironmentOptions::experimental_modules,
290
4326
            kAllowedInEnvironment);
291
4326
  AddOption("--experimental-wasm-modules",
292
            "experimental ES Module support for webassembly modules",
293
            &EnvironmentOptions::experimental_wasm_modules,
294
4326
            kAllowedInEnvironment);
295
4326
  AddOption("--experimental-import-meta-resolve",
296
            "experimental ES Module import.meta.resolve() support",
297
            &EnvironmentOptions::experimental_import_meta_resolve,
298
4326
            kAllowedInEnvironment);
299
4326
  AddOption("--experimental-policy",
300
            "use the specified file as a "
301
            "security policy",
302
            &EnvironmentOptions::experimental_policy,
303
4326
            kAllowedInEnvironment);
304
4326
  AddOption("[has_policy_integrity_string]",
305
            "",
306
4326
            &EnvironmentOptions::has_policy_integrity_string);
307
4326
  AddOption("--policy-integrity",
308
            "ensure the security policy contents match "
309
            "the specified integrity",
310
            &EnvironmentOptions::experimental_policy_integrity,
311
4326
            kAllowedInEnvironment);
312
4326
  Implies("--policy-integrity", "[has_policy_integrity_string]");
313
4326
  AddOption("--experimental-repl-await",
314
            "experimental await keyword support in REPL",
315
            &EnvironmentOptions::experimental_repl_await,
316
4326
            kAllowedInEnvironment);
317
4326
  AddOption("--experimental-vm-modules",
318
            "experimental ES Module support in vm module",
319
            &EnvironmentOptions::experimental_vm_modules,
320
4326
            kAllowedInEnvironment);
321
4326
  AddOption("--experimental-worker", "", NoOp{}, kAllowedInEnvironment);
322
4326
  AddOption("--experimental-report", "", NoOp{}, kAllowedInEnvironment);
323
4326
  AddOption("--experimental-wasi-unstable-preview1",
324
            "experimental WASI support",
325
            &EnvironmentOptions::experimental_wasi,
326
4326
            kAllowedInEnvironment);
327
4326
  AddOption("--expose-internals", "", &EnvironmentOptions::expose_internals);
328
4326
  AddOption("--frozen-intrinsics",
329
            "experimental frozen intrinsics support",
330
            &EnvironmentOptions::frozen_intrinsics,
331
4326
            kAllowedInEnvironment);
332
4326
  AddOption("--heapsnapshot-signal",
333
            "Generate heap snapshot on specified signal",
334
            &EnvironmentOptions::heap_snapshot_signal,
335
4326
            kAllowedInEnvironment);
336
4326
  AddOption("--http-parser", "", NoOp{}, kAllowedInEnvironment);
337
4326
  AddOption("--insecure-http-parser",
338
            "use an insecure HTTP parser that accepts invalid HTTP headers",
339
            &EnvironmentOptions::insecure_http_parser,
340
4326
            kAllowedInEnvironment);
341
4326
  AddOption("--input-type",
342
            "set module type for string input",
343
            &EnvironmentOptions::module_type,
344
4326
            kAllowedInEnvironment);
345
4326
  AddOption("--experimental-specifier-resolution",
346
            "Select extension resolution algorithm for es modules; "
347
            "either 'explicit' (default) or 'node'",
348
            &EnvironmentOptions::experimental_specifier_resolution,
349
4326
            kAllowedInEnvironment);
350
4326
  AddOption("--es-module-specifier-resolution",
351
            "",
352
            &EnvironmentOptions::es_module_specifier_resolution,
353
4326
            kAllowedInEnvironment);
354
4326
  AddOption("--no-deprecation",
355
            "silence deprecation warnings",
356
            &EnvironmentOptions::no_deprecation,
357
4326
            kAllowedInEnvironment);
358
4326
  AddOption("--no-force-async-hooks-checks",
359
            "disable checks for async_hooks",
360
            &EnvironmentOptions::no_force_async_hooks_checks,
361
4326
            kAllowedInEnvironment);
362
4326
  AddOption("--no-warnings",
363
            "silence all process warnings",
364
            &EnvironmentOptions::no_warnings,
365
4326
            kAllowedInEnvironment);
366
4326
  AddOption("--force-context-aware",
367
            "disable loading non-context-aware addons",
368
            &EnvironmentOptions::force_context_aware,
369
4326
            kAllowedInEnvironment);
370
4326
  AddOption("--pending-deprecation",
371
            "emit pending deprecation warnings",
372
            &EnvironmentOptions::pending_deprecation,
373
4326
            kAllowedInEnvironment);
374
4326
  AddOption("--preserve-symlinks",
375
            "preserve symbolic links when resolving",
376
            &EnvironmentOptions::preserve_symlinks,
377
4326
            kAllowedInEnvironment);
378
4326
  AddOption("--preserve-symlinks-main",
379
            "preserve symbolic links when resolving the main module",
380
            &EnvironmentOptions::preserve_symlinks_main,
381
4326
            kAllowedInEnvironment);
382
4326
  AddOption("--prof-process",
383
            "process V8 profiler output generated using --prof",
384
4326
            &EnvironmentOptions::prof_process);
385
  // Options after --prof-process are passed through to the prof processor.
386
4326
  AddAlias("--prof-process", { "--prof-process", "--" });
387
#if HAVE_INSPECTOR
388
4326
  AddOption("--cpu-prof",
389
            "Start the V8 CPU profiler on start up, and write the CPU profile "
390
            "to disk before exit. If --cpu-prof-dir is not specified, write "
391
            "the profile to the current working directory.",
392
4326
            &EnvironmentOptions::cpu_prof);
393
4326
  AddOption("--cpu-prof-name",
394
            "specified file name of the V8 CPU profile generated with "
395
            "--cpu-prof",
396
4326
            &EnvironmentOptions::cpu_prof_name);
397
4326
  AddOption("--cpu-prof-interval",
398
            "specified sampling interval in microseconds for the V8 CPU "
399
            "profile generated with --cpu-prof. (default: 1000)",
400
4326
            &EnvironmentOptions::cpu_prof_interval);
401
4326
  AddOption("--cpu-prof-dir",
402
            "Directory where the V8 profiles generated by --cpu-prof will be "
403
            "placed. Does not affect --prof.",
404
4326
            &EnvironmentOptions::cpu_prof_dir);
405
4326
  AddOption(
406
      "--heap-prof",
407
      "Start the V8 heap profiler on start up, and write the heap profile "
408
      "to disk before exit. If --heap-prof-dir is not specified, write "
409
      "the profile to the current working directory.",
410
4326
      &EnvironmentOptions::heap_prof);
411
4326
  AddOption("--heap-prof-name",
412
            "specified file name of the V8 heap profile generated with "
413
            "--heap-prof",
414
4326
            &EnvironmentOptions::heap_prof_name);
415
4326
  AddOption("--heap-prof-dir",
416
            "Directory where the V8 heap profiles generated by --heap-prof "
417
            "will be placed.",
418
4326
            &EnvironmentOptions::heap_prof_dir);
419
4326
  AddOption("--heap-prof-interval",
420
            "specified sampling interval in bytes for the V8 heap "
421
            "profile generated with --heap-prof. (default: 512 * 1024)",
422
4326
            &EnvironmentOptions::heap_prof_interval);
423
#endif  // HAVE_INSPECTOR
424
4326
  AddOption("--max-http-header-size",
425
            "set the maximum size of HTTP headers (default: 16384 (16KB))",
426
            &EnvironmentOptions::max_http_header_size,
427
4326
            kAllowedInEnvironment);
428
4326
  AddOption("--redirect-warnings",
429
            "write warnings to file instead of stderr",
430
            &EnvironmentOptions::redirect_warnings,
431
4326
            kAllowedInEnvironment);
432
4326
  AddOption("--test-udp-no-try-send", "",  // For testing only.
433
4326
            &EnvironmentOptions::test_udp_no_try_send);
434
4326
  AddOption("--throw-deprecation",
435
            "throw an exception on deprecations",
436
            &EnvironmentOptions::throw_deprecation,
437
4326
            kAllowedInEnvironment);
438
4326
  AddOption("--trace-atomics-wait",
439
            "trace Atomics.wait() operations",
440
            &EnvironmentOptions::trace_atomics_wait,
441
4326
            kAllowedInEnvironment);
442
4326
  AddOption("--trace-deprecation",
443
            "show stack traces on deprecations",
444
            &EnvironmentOptions::trace_deprecation,
445
4326
            kAllowedInEnvironment);
446
4326
  AddOption("--trace-exit",
447
            "show stack trace when an environment exits",
448
            &EnvironmentOptions::trace_exit,
449
4326
            kAllowedInEnvironment);
450
4326
  AddOption("--trace-sync-io",
451
            "show stack trace when use of sync IO is detected after the "
452
            "first tick",
453
            &EnvironmentOptions::trace_sync_io,
454
4326
            kAllowedInEnvironment);
455
4326
  AddOption("--trace-tls",
456
            "prints TLS packet trace information to stderr",
457
            &EnvironmentOptions::trace_tls,
458
4326
            kAllowedInEnvironment);
459
4326
  AddOption("--trace-uncaught",
460
            "show stack traces for the `throw` behind uncaught exceptions",
461
            &EnvironmentOptions::trace_uncaught,
462
4326
            kAllowedInEnvironment);
463
4326
  AddOption("--trace-warnings",
464
            "show stack traces on process warnings",
465
            &EnvironmentOptions::trace_warnings,
466
4326
            kAllowedInEnvironment);
467
4326
  AddOption("--unhandled-rejections",
468
            "define unhandled rejections behavior. Options are 'strict' (raise "
469
            "an error), 'warn' (enforce warnings) or 'none' (silence warnings)",
470
            &EnvironmentOptions::unhandled_rejections,
471
4326
            kAllowedInEnvironment);
472
473
4326
  AddOption("--check",
474
            "syntax check script without executing",
475
4326
            &EnvironmentOptions::syntax_check_only);
476
4326
  AddAlias("-c", "--check");
477
  // This option is only so that we can tell --eval with an empty string from
478
  // no eval at all. Having it not start with a dash makes it inaccessible
479
  // from the parser itself, but available for using Implies().
480
  // TODO(addaleax): When moving --help over to something generated from the
481
  // programmatic descriptions, this will need some special care.
482
  // (See also [ssl_openssl_cert_store] below.)
483
4326
  AddOption("[has_eval_string]", "", &EnvironmentOptions::has_eval_string);
484
4326
  AddOption("--eval", "evaluate script", &EnvironmentOptions::eval_string);
485
4326
  Implies("--eval", "[has_eval_string]");
486
4326
  AddOption("--print",
487
            "evaluate script and print result",
488
4326
            &EnvironmentOptions::print_eval);
489
4326
  AddAlias("-e", "--eval");
490
4326
  AddAlias("--print <arg>", "-pe");
491
4326
  AddAlias("-pe", { "--print", "--eval" });
492
4326
  AddAlias("-p", "--print");
493
4326
  AddOption("--require",
494
            "module to preload (option can be repeated)",
495
            &EnvironmentOptions::preload_modules,
496
4326
            kAllowedInEnvironment);
497
4326
  AddAlias("-r", "--require");
498
4326
  AddOption("--interactive",
499
            "always enter the REPL even if stdin does not appear "
500
            "to be a terminal",
501
4326
            &EnvironmentOptions::force_repl);
502
4326
  AddAlias("-i", "--interactive");
503
504
4326
  AddOption("--napi-modules", "", NoOp{}, kAllowedInEnvironment);
505
506
4326
  AddOption("--tls-keylog",
507
            "log TLS decryption keys to named file for traffic analysis",
508
4326
            &EnvironmentOptions::tls_keylog, kAllowedInEnvironment);
509
510
4326
  AddOption("--tls-min-v1.0",
511
            "set default TLS minimum to TLSv1.0 (default: TLSv1.2)",
512
            &EnvironmentOptions::tls_min_v1_0,
513
4326
            kAllowedInEnvironment);
514
4326
  AddOption("--tls-min-v1.1",
515
            "set default TLS minimum to TLSv1.1 (default: TLSv1.2)",
516
            &EnvironmentOptions::tls_min_v1_1,
517
4326
            kAllowedInEnvironment);
518
4326
  AddOption("--tls-min-v1.2",
519
            "set default TLS minimum to TLSv1.2 (default: TLSv1.2)",
520
            &EnvironmentOptions::tls_min_v1_2,
521
4326
            kAllowedInEnvironment);
522
4326
  AddOption("--tls-min-v1.3",
523
            "set default TLS minimum to TLSv1.3 (default: TLSv1.2)",
524
            &EnvironmentOptions::tls_min_v1_3,
525
4326
            kAllowedInEnvironment);
526
4326
  AddOption("--tls-max-v1.2",
527
            "set default TLS maximum to TLSv1.2 (default: TLSv1.3)",
528
            &EnvironmentOptions::tls_max_v1_2,
529
4326
            kAllowedInEnvironment);
530
  // Current plan is:
531
  // - 11.x and below: TLS1.3 is opt-in with --tls-max-v1.3
532
  // - 12.x: TLS1.3 is opt-out with --tls-max-v1.2
533
  // In either case, support both options they are uniformly available.
534
4326
  AddOption("--tls-max-v1.3",
535
            "set default TLS maximum to TLSv1.3 (default: TLSv1.3)",
536
            &EnvironmentOptions::tls_max_v1_3,
537
4326
            kAllowedInEnvironment);
538
4326
}
539
540
4326
PerIsolateOptionsParser::PerIsolateOptionsParser(
541
4326
  const EnvironmentOptionsParser& eop) {
542
4326
  AddOption("--track-heap-objects",
543
            "track heap object allocations for heap snapshots",
544
            &PerIsolateOptions::track_heap_objects,
545
4326
            kAllowedInEnvironment);
546
4326
  AddOption("--no-node-snapshot",
547
            "",  // It's a debug-only option.
548
            &PerIsolateOptions::no_node_snapshot,
549
4326
            kAllowedInEnvironment);
550
551
  // Explicitly add some V8 flags to mark them as allowed in NODE_OPTIONS.
552
4326
  AddOption("--abort-on-uncaught-exception",
553
            "aborting instead of exiting causes a core file to be generated "
554
            "for analysis",
555
4326
            V8Option{},
556
4326
            kAllowedInEnvironment);
557
4326
  AddOption("--interpreted-frames-native-stack",
558
            "help system profilers to translate JavaScript interpreted frames",
559
4326
            V8Option{}, kAllowedInEnvironment);
560
4326
  AddOption("--max-old-space-size", "", V8Option{}, kAllowedInEnvironment);
561
4326
  AddOption("--perf-basic-prof", "", V8Option{}, kAllowedInEnvironment);
562
4326
  AddOption("--perf-basic-prof-only-functions",
563
            "",
564
4326
            V8Option{},
565
4326
            kAllowedInEnvironment);
566
4326
  AddOption("--perf-prof", "", V8Option{}, kAllowedInEnvironment);
567
4326
  AddOption("--perf-prof-unwinding-info",
568
            "",
569
4326
            V8Option{},
570
4326
            kAllowedInEnvironment);
571
4326
  AddOption("--stack-trace-limit", "", V8Option{}, kAllowedInEnvironment);
572
4326
  AddOption("--disallow-code-generation-from-strings",
573
            "disallow eval and friends",
574
4326
            V8Option{},
575
4326
            kAllowedInEnvironment);
576
4326
  AddOption("--huge-max-old-generation-size",
577
             "increase default maximum heap size on machines with 16GB memory "
578
             "or more",
579
4326
             V8Option{},
580
4326
             kAllowedInEnvironment);
581
4326
  AddOption("--jitless",
582
             "disable runtime allocation of executable memory",
583
4326
             V8Option{},
584
4326
             kAllowedInEnvironment);
585
4326
  AddOption("--report-uncaught-exception",
586
            "generate diagnostic report on uncaught exceptions",
587
            &PerIsolateOptions::report_uncaught_exception,
588
4326
            kAllowedInEnvironment);
589
4326
  AddOption("--report-on-signal",
590
            "generate diagnostic report upon receiving signals",
591
            &PerIsolateOptions::report_on_signal,
592
4326
            kAllowedInEnvironment);
593
4326
  AddOption("--report-signal",
594
            "causes diagnostic report to be produced on provided signal,"
595
            " unsupported in Windows. (default: SIGUSR2)",
596
            &PerIsolateOptions::report_signal,
597
4326
            kAllowedInEnvironment);
598
4326
  Implies("--report-signal", "--report-on-signal");
599
600
4326
  AddOption("--experimental-top-level-await",
601
            "enable experimental support for ECMAScript Top-Level Await",
602
            &PerIsolateOptions::experimental_top_level_await,
603
4326
            kAllowedInEnvironment);
604
4326
  AddOption("--harmony-top-level-await", "", V8Option{});
605
4326
  Implies("--experimental-top-level-await", "--harmony-top-level-await");
606
4326
  Implies("--harmony-top-level-await", "--experimental-top-level-await");
607
608
4326
  Insert(eop, &PerIsolateOptions::get_per_env_options);
609
4326
}
610
611
4326
PerProcessOptionsParser::PerProcessOptionsParser(
612
4326
  const PerIsolateOptionsParser& iop) {
613
4326
  AddOption("--title",
614
            "the process title to use on startup",
615
            &PerProcessOptions::title,
616
4326
            kAllowedInEnvironment);
617
4326
  AddOption("--trace-event-categories",
618
            "comma separated list of trace event categories to record",
619
            &PerProcessOptions::trace_event_categories,
620
4326
            kAllowedInEnvironment);
621
4326
  AddOption("--trace-event-file-pattern",
622
            "Template string specifying the filepath for the trace-events "
623
            "data, it supports ${rotation} and ${pid}.",
624
            &PerProcessOptions::trace_event_file_pattern,
625
4326
            kAllowedInEnvironment);
626
17304
  AddAlias("--trace-events-enabled", {
627
12978
    "--trace-event-categories", "v8,node,node.async_hooks" });
628
4326
  AddOption("--v8-pool-size",
629
            "set V8's thread pool size",
630
            &PerProcessOptions::v8_thread_pool_size,
631
4326
            kAllowedInEnvironment);
632
4326
  AddOption("--zero-fill-buffers",
633
            "automatically zero-fill all newly allocated Buffer and "
634
            "SlowBuffer instances",
635
            &PerProcessOptions::zero_fill_all_buffers,
636
4326
            kAllowedInEnvironment);
637
4326
  AddOption("--debug-arraybuffer-allocations",
638
            "", /* undocumented, only for debugging */
639
            &PerProcessOptions::debug_arraybuffer_allocations,
640
4326
            kAllowedInEnvironment);
641
4326
  AddOption("--disable-proto",
642
            "disable Object.prototype.__proto__",
643
            &PerProcessOptions::disable_proto,
644
4326
            kAllowedInEnvironment);
645
646
  // 12.x renamed this inadvertently, so alias it for consistency within the
647
  // release line, while using the original name for consistency with older
648
  // release lines.
649
4326
  AddOption("--security-revert", "", &PerProcessOptions::security_reverts);
650
4326
  AddAlias("--security-reverts", "--security-revert");
651
4326
  AddOption("--completion-bash",
652
            "print source-able bash completion script",
653
4326
            &PerProcessOptions::print_bash_completion);
654
4326
  AddOption("--help",
655
            "print node command line options",
656
4326
            &PerProcessOptions::print_help);
657
4326
  AddAlias("-h", "--help");
658
4326
  AddOption(
659
4326
      "--version", "print Node.js version", &PerProcessOptions::print_version);
660
4326
  AddAlias("-v", "--version");
661
4326
  AddOption("--v8-options",
662
            "print V8 command line options",
663
4326
            &PerProcessOptions::print_v8_help);
664
4326
  AddOption("--report-compact",
665
            "output compact single-line JSON",
666
            &PerProcessOptions::report_compact,
667
4326
            kAllowedInEnvironment);
668
4326
  AddOption("--report-directory",
669
            "define custom report pathname."
670
            " (default: current working directory of Node.js process)",
671
            &PerProcessOptions::report_directory,
672
4326
            kAllowedInEnvironment);
673
4326
  AddOption("--report-filename",
674
            "define custom report file name."
675
            " (default: YYYYMMDD.HHMMSS.PID.SEQUENCE#.txt)",
676
            &PerProcessOptions::report_filename,
677
4326
            kAllowedInEnvironment);
678
4326
  AddOption("--report-on-fatalerror",
679
              "generate diagnostic report on fatal (internal) errors",
680
              &PerProcessOptions::report_on_fatalerror,
681
4326
              kAllowedInEnvironment);
682
683
#ifdef NODE_HAVE_I18N_SUPPORT
684
4326
  AddOption("--icu-data-dir",
685
            "set ICU data load path to dir (overrides NODE_ICU_DATA)"
686
#ifndef NODE_HAVE_SMALL_ICU
687
            " (note: linked-in ICU data is present)\n"
688
#endif
689
            ,
690
            &PerProcessOptions::icu_data_dir,
691
4326
            kAllowedInEnvironment);
692
#endif
693
694
#if HAVE_OPENSSL
695
4326
  AddOption("--openssl-config",
696
            "load OpenSSL configuration from the specified file "
697
            "(overrides OPENSSL_CONF)",
698
            &PerProcessOptions::openssl_config,
699
4326
            kAllowedInEnvironment);
700
4326
  AddOption("--tls-cipher-list",
701
            "use an alternative default TLS cipher list",
702
            &PerProcessOptions::tls_cipher_list,
703
4326
            kAllowedInEnvironment);
704
4326
  AddOption("--use-openssl-ca",
705
            "use OpenSSL's default CA store"
706
#if defined(NODE_OPENSSL_CERT_STORE)
707
            " (default)"
708
#endif
709
            ,
710
            &PerProcessOptions::use_openssl_ca,
711
4326
            kAllowedInEnvironment);
712
4326
  AddOption("--use-bundled-ca",
713
            "use bundled CA store"
714
#if !defined(NODE_OPENSSL_CERT_STORE)
715
            " (default)"
716
#endif
717
            ,
718
            &PerProcessOptions::use_bundled_ca,
719
4326
            kAllowedInEnvironment);
720
  // Similar to [has_eval_string] above, except that the separation between
721
  // this and use_openssl_ca only exists for option validation after parsing.
722
  // This is not ideal.
723
4326
  AddOption("[ssl_openssl_cert_store]",
724
            "",
725
4326
            &PerProcessOptions::ssl_openssl_cert_store);
726
4326
  Implies("--use-openssl-ca", "[ssl_openssl_cert_store]");
727
4326
  ImpliesNot("--use-bundled-ca", "[ssl_openssl_cert_store]");
728
#if NODE_FIPS_MODE
729
  AddOption("--enable-fips",
730
            "enable FIPS crypto at startup",
731
            &PerProcessOptions::enable_fips_crypto,
732
            kAllowedInEnvironment);
733
  AddOption("--force-fips",
734
            "force FIPS crypto (cannot be disabled)",
735
            &PerProcessOptions::force_fips_crypto,
736
            kAllowedInEnvironment);
737
#endif
738
#endif
739
4326
  AddOption("--use-largepages",
740
            "Map the Node.js static code to large pages. Options are "
741
            "'off' (the default value, meaning do not map), "
742
            "'on' (map and ignore failure, reporting it to stderr), "
743
            "or 'silent' (map and silently ignore failure)",
744
            &PerProcessOptions::use_largepages,
745
4326
            kAllowedInEnvironment);
746
747
4326
  AddOption("--trace-sigint",
748
            "enable printing JavaScript stacktrace on SIGINT",
749
            &PerProcessOptions::trace_sigint,
750
4326
            kAllowedInEnvironment);
751
752
4326
  Insert(iop, &PerProcessOptions::get_per_isolate_options);
753
4326
}
754
755
112
inline std::string RemoveBrackets(const std::string& host) {
756


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
757
4
    return host.substr(1, host.size() - 2);
758
  else
759
108
    return host;
760
}
761
762
100
inline int ParseAndValidatePort(const std::string& port,
763
                                std::vector<std::string>* errors) {
764
  char* endptr;
765
100
  errno = 0;
766
  const unsigned long result =                 // NOLINT(runtime/int)
767
100
    strtoul(port.c_str(), &endptr, 10);
768

100
  if (errno != 0 || *endptr != '\0'||
769

63
      (result != 0 && result < 1024) || result > 65535) {
770
    errors->push_back(" must be 0 or in range 1024 to 65535.");
771
  }
772
100
  return static_cast<int>(result);
773
}
774
775
100
HostPort SplitHostPort(const std::string& arg,
776
                      std::vector<std::string>* errors) {
777
  // remove_brackets only works if no port is specified
778
  // so if it has an effect only an IPv6 address was specified.
779
200
  std::string host = RemoveBrackets(arg);
780
100
  if (host.length() < arg.length())
781
    return HostPort{host, DebugOptions::kDefaultInspectorPort};
782
783
100
  size_t colon = arg.rfind(':');
784
100
  if (colon == std::string::npos) {
785
    // Either a port number or a host name.  Assume that
786
    // if it's not all decimal digits, it's a host name.
787
390
    for (char c : arg) {
788

302
      if (c < '0' || c > '9') {
789
        return HostPort{arg, DebugOptions::kDefaultInspectorPort};
790
      }
791
    }
792
88
    return HostPort { "", ParseAndValidatePort(arg, errors) };
793
  }
794
  // Host and port found:
795
24
  return HostPort { RemoveBrackets(arg.substr(0, colon)),
796
12
                    ParseAndValidatePort(arg.substr(colon + 1), errors) };
797
}
798
799
1
std::string GetBashCompletion() {
800
2
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
801
1
  const auto& parser = _ppop_instance;
802
803
2
  std::ostringstream out;
804
805
  out << "_node_complete() {\n"
806
         "  local cur_word options\n"
807
         "  cur_word=\"${COMP_WORDS[COMP_CWORD]}\"\n"
808
         "  if [[ \"${cur_word}\" == -* ]] ; then\n"
809
1
         "    COMPREPLY=( $(compgen -W '";
810
811
114
  for (const auto& item : parser.options_) {
812
113
    if (item.first[0] != '[') {
813
110
      out << item.first << " ";
814
    }
815
  }
816
20
  for (const auto& item : parser.aliases_) {
817
19
    if (item.first[0] != '[') {
818
19
      out << item.first << " ";
819
    }
820
  }
821
1
  if (parser.aliases_.size() > 0) {
822
1
    out.seekp(-1, out.cur);  // Strip the trailing space
823
  }
824
825
  out << "' -- \"${cur_word}\") )\n"
826
         "    return 0\n"
827
         "  else\n"
828
         "    COMPREPLY=( $(compgen -f \"${cur_word}\") )\n"
829
         "    return 0\n"
830
         "  fi\n"
831
         "}\n"
832
1
         "complete -F _node_complete node node_g";
833
2
  return out.str();
834
}
835
836
// Return a map containing all the options and their metadata as well
837
// as the aliases
838
4570
void GetOptions(const FunctionCallbackInfo<Value>& args) {
839
9140
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
840
4570
  Environment* env = Environment::GetCurrent(args);
841
4570
  if (!env->has_run_bootstrapping_code()) {
842
    // No code because this is an assertion.
843
    return env->ThrowError(
844
        "Should not query options before bootstrapping is done");
845
  }
846
4570
  env->set_has_serialized_options(true);
847
848
4570
  Isolate* isolate = env->isolate();
849
4570
  Local<Context> context = env->context();
850
851
  // Temporarily act as if the current Environment's/IsolateData's options were
852
  // the default options, i.e. like they are the ones we'd access for global
853
  // options parsing, so that all options are available from the main parser.
854
9140
  auto original_per_isolate = per_process::cli_options->per_isolate;
855
4570
  per_process::cli_options->per_isolate = env->isolate_data()->options();
856
9140
  auto original_per_env = per_process::cli_options->per_isolate->per_env;
857
4570
  per_process::cli_options->per_isolate->per_env = env->options();
858
4570
  auto on_scope_leave = OnScopeLeave([&]() {
859
4570
    per_process::cli_options->per_isolate->per_env = original_per_env;
860
4570
    per_process::cli_options->per_isolate = original_per_isolate;
861
13710
  });
862
863
4570
  Local<Map> options = Map::New(isolate);
864
520980
  for (const auto& item : _ppop_instance.options_) {
865
    Local<Value> value;
866
516410
    const auto& option_info = item.second;
867
1032820
    auto field = option_info.field;
868
516410
    PerProcessOptions* opts = per_process::cli_options.get();
869


516410
    switch (option_info.type) {
870
      case kNoOp:
871
      case kV8Option:
872
        // Special case for --abort-on-uncaught-exception which is also
873
        // respected by Node.js internals
874
73120
        if (item.first == "--abort-on-uncaught-exception") {
875
4570
          value = Boolean::New(
876
9140
            isolate, original_per_env->abort_on_uncaught_exception);
877
        } else {
878
68550
          value = Undefined(isolate);
879
        }
880
73120
        break;
881
      case kBoolean:
882
287910
        value = Boolean::New(isolate,
883
575820
                             *_ppop_instance.Lookup<bool>(field, opts));
884
287910
        break;
885
      case kInteger:
886
4570
        value = Number::New(isolate,
887
9140
                            *_ppop_instance.Lookup<int64_t>(field, opts));
888
4570
        break;
889
      case kUInteger:
890
13710
        value = Number::New(isolate,
891
27420
                            *_ppop_instance.Lookup<uint64_t>(field, opts));
892
13710
        break;
893
      case kString:
894
370170
        if (!ToV8Value(context,
895
246780
                       *_ppop_instance.Lookup<std::string>(field, opts))
896
123390
                 .ToLocal(&value)) {
897
          return;
898
        }
899
123390
        break;
900
      case kStringList:
901
27420
        if (!ToV8Value(context,
902
18280
                       *_ppop_instance.Lookup<StringVector>(field, opts))
903
9140
                 .ToLocal(&value)) {
904
          return;
905
        }
906
9140
        break;
907
      case kHostPort: {
908
        const HostPort& host_port =
909
4570
          *_ppop_instance.Lookup<HostPort>(field, opts);
910
4570
        Local<Object> obj = Object::New(isolate);
911
        Local<Value> host;
912

22850
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
913

22850
            obj->Set(context, env->host_string(), host).IsNothing() ||
914
9140
            obj->Set(context,
915
                     env->port_string(),
916
18280
                     Integer::New(isolate, host_port.port()))
917
4570
                .IsNothing()) {
918
          return;
919
        }
920
4570
        value = obj;
921
4570
        break;
922
      }
923
      default:
924
        UNREACHABLE();
925
    }
926
516410
    CHECK(!value.IsEmpty());
927
928
1032820
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
929
516410
    Local<Object> info = Object::New(isolate);
930
    Local<Value> help_text;
931

2582050
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
932
2065640
        !info->Set(context, env->help_text_string(), help_text)
933
2065640
             .FromMaybe(false) ||
934
1549230
        !info->Set(context,
935
                   env->env_var_settings_string(),
936
                   Integer::New(isolate,
937
2065640
                                static_cast<int>(option_info.env_setting)))
938
2065640
             .FromMaybe(false) ||
939
1549230
        !info->Set(context,
940
                   env->type_string(),
941
2065640
                   Integer::New(isolate, static_cast<int>(option_info.type)))
942
2065640
             .FromMaybe(false) ||
943

3098460
        info->Set(context, env->value_string(), value).IsNothing() ||
944
1549230
        options->Set(context, name, info).IsEmpty()) {
945
      return;
946
    }
947
  }
948
949
  Local<Value> aliases;
950
9140
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
951
952
4570
  Local<Object> ret = Object::New(isolate);
953

22850
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
954
18280
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
955
    return;
956
  }
957
958
9140
  args.GetReturnValue().Set(ret);
959
}
960
961
4570
void Initialize(Local<Object> target,
962
                Local<Value> unused,
963
                Local<Context> context,
964
                void* priv) {
965
4570
  Environment* env = Environment::GetCurrent(context);
966
4570
  Isolate* isolate = env->isolate();
967
4570
  env->SetMethodNoSideEffect(target, "getOptions", GetOptions);
968
969
4570
  Local<Object> env_settings = Object::New(isolate);
970
18280
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment);
971
18280
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvironment);
972
  target
973
9140
      ->Set(
974
13710
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
975
      .Check();
976
977
4570
  Local<Object> types = Object::New(isolate);
978
18280
  NODE_DEFINE_CONSTANT(types, kNoOp);
979
18280
  NODE_DEFINE_CONSTANT(types, kV8Option);
980
18280
  NODE_DEFINE_CONSTANT(types, kBoolean);
981
18280
  NODE_DEFINE_CONSTANT(types, kInteger);
982
18280
  NODE_DEFINE_CONSTANT(types, kUInteger);
983
18280
  NODE_DEFINE_CONSTANT(types, kString);
984
18280
  NODE_DEFINE_CONSTANT(types, kHostPort);
985
18280
  NODE_DEFINE_CONSTANT(types, kStringList);
986
13710
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
987
      .Check();
988
4570
}
989
990
}  // namespace options_parser
991
992
4325
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
993
25950
  HandleEnvOptions(env_options, [](const char* name) {
994
34600
    std::string text;
995

34600
    return credentials::SafeGetenv(name, &text) ? text : "";
996
4325
  });
997
4325
}
998
999
4368
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1000
                      std::function<std::string(const char*)> opt_getter) {
1001
8736
  env_options->pending_deprecation =
1002
8736
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1003
1004
4368
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1005
1006
8736
  env_options->preserve_symlinks_main =
1007
8736
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1008
1009
4368
  if (env_options->redirect_warnings.empty())
1010
4368
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1011
4368
}
1012
1013
4264
std::vector<std::string> ParseNodeOptionsEnvVar(
1014
    const std::string& node_options, std::vector<std::string>* errors) {
1015
4264
  std::vector<std::string> env_argv;
1016
1017
4264
  bool is_in_string = false;
1018
4264
  bool will_start_new_arg = true;
1019
6945
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1020
2681
    char c = node_options.at(index);
1021
1022
    // Backslashes escape the following character
1023

2681
    if (c == '\\' && is_in_string) {
1024
      if (index + 1 == node_options.size()) {
1025
        errors->push_back("invalid value for NODE_OPTIONS "
1026
                          "(invalid escape)\n");
1027
        return env_argv;
1028
      } else {
1029
        c = node_options.at(++index);
1030
      }
1031

2681
    } else if (c == ' ' && !is_in_string) {
1032
33
      will_start_new_arg = true;
1033
33
      continue;
1034
2648
    } else if (c == '"') {
1035
4
      is_in_string = !is_in_string;
1036
4
      continue;
1037
    }
1038
1039
2644
    if (will_start_new_arg) {
1040
105
      env_argv.emplace_back(std::string(1, c));
1041
105
      will_start_new_arg = false;
1042
    } else {
1043
2539
      env_argv.back() += c;
1044
    }
1045
  }
1046
1047
4264
  if (is_in_string) {
1048
    errors->push_back("invalid value for NODE_OPTIONS "
1049
                      "(unterminated string)\n");
1050
  }
1051
4264
  return env_argv;
1052
}
1053
}  // namespace node
1054
1055

17303
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)