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: 509 539 94.4 %
Date: 2020-06-24 22:13:30 Branches: 175 234 74.8 %

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::Undefined;
22
using v8::Value;
23
24
namespace node {
25
26
namespace per_process {
27
4399
Mutex cli_options_mutex;
28
4399
std::shared_ptr<PerProcessOptions> cli_options{new PerProcessOptions()};
29
}  // namespace per_process
30
31
8758
void DebugOptions::CheckOptions(std::vector<std::string>* errors) {
32
#if !NODE_USE_V8_PLATFORM && !HAVE_INSPECTOR
33
  if (inspector_enabled) {
34
    errors->push_back("Inspector is not available when Node is compiled "
35
                      "--without-v8-platform and --without-inspector.");
36
  }
37
#endif
38
39
8758
  if (deprecated_debug) {
40
8
    errors->push_back("[DEP0062]: `node --debug` and `node --debug-brk` "
41
                      "are invalid. Please use `node --inspect` and "
42
4
                      "`node --inspect-brk` instead.");
43
  }
44
45
  std::vector<std::string> destinations =
46
17516
      SplitString(inspect_publish_uid_string, ',');
47
8758
  inspect_publish_uid.console = false;
48
8758
  inspect_publish_uid.http = false;
49
26272
  for (const std::string& destination : destinations) {
50
17514
    if (destination == "stderr") {
51
8757
      inspect_publish_uid.console = true;
52
8757
    } else if (destination == "http") {
53
8757
      inspect_publish_uid.http = true;
54
    } else {
55
      errors->push_back("--inspect-publish-uid destination can be "
56
                        "stderr or http");
57
    }
58
  }
59
8758
}
60
61
8675
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
62
#if HAVE_OPENSSL
63

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

17352
  if (use_largepages != "off" &&
69

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

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

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

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

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

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

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

17530
  if (!unhandled_rejections.empty() &&
121
27
      unhandled_rejections != "warn-with-error-code" &&
122
24
      unhandled_rejections != "throw" &&
123
20
      unhandled_rejections != "strict" &&
124

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

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


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

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

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

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


533406
    switch (option_info.type) {
875
      case kNoOp:
876
      case kV8Option:
877
        // Special case for --abort-on-uncaught-exception which is also
878
        // respected by Node.js internals
879
79543
        if (item.first == "--abort-on-uncaught-exception") {
880
4679
          value = Boolean::New(
881
9358
            isolate, original_per_env->abort_on_uncaught_exception);
882
        } else {
883
74864
          value = Undefined(isolate);
884
        }
885
79543
        break;
886
      case kBoolean:
887
294777
        value = Boolean::New(isolate,
888
589554
                             *_ppop_instance.Lookup<bool>(field, opts));
889
294777
        break;
890
      case kInteger:
891
4679
        value = Number::New(isolate,
892
9358
                            *_ppop_instance.Lookup<int64_t>(field, opts));
893
4679
        break;
894
      case kUInteger:
895
14037
        value = Number::New(isolate,
896
28074
                            *_ppop_instance.Lookup<uint64_t>(field, opts));
897
14037
        break;
898
      case kString:
899
378999
        if (!ToV8Value(context,
900
252666
                       *_ppop_instance.Lookup<std::string>(field, opts))
901
126333
                 .ToLocal(&value)) {
902
          return;
903
        }
904
126333
        break;
905
      case kStringList:
906
28074
        if (!ToV8Value(context,
907
18716
                       *_ppop_instance.Lookup<StringVector>(field, opts))
908
9358
                 .ToLocal(&value)) {
909
          return;
910
        }
911
9358
        break;
912
      case kHostPort: {
913
        const HostPort& host_port =
914
4679
          *_ppop_instance.Lookup<HostPort>(field, opts);
915
4679
        Local<Object> obj = Object::New(isolate);
916
        Local<Value> host;
917

23395
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
918

23395
            obj->Set(context, env->host_string(), host).IsNothing() ||
919
9358
            obj->Set(context,
920
                     env->port_string(),
921
18716
                     Integer::New(isolate, host_port.port()))
922
4679
                .IsNothing()) {
923
          return;
924
        }
925
4679
        value = obj;
926
4679
        break;
927
      }
928
      default:
929
        UNREACHABLE();
930
    }
931
533406
    CHECK(!value.IsEmpty());
932
933
1066812
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
934
533406
    Local<Object> info = Object::New(isolate);
935
    Local<Value> help_text;
936

2667030
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
937
2133624
        !info->Set(context, env->help_text_string(), help_text)
938
2133624
             .FromMaybe(false) ||
939
1600218
        !info->Set(context,
940
                   env->env_var_settings_string(),
941
                   Integer::New(isolate,
942
2133624
                                static_cast<int>(option_info.env_setting)))
943
2133624
             .FromMaybe(false) ||
944
1600218
        !info->Set(context,
945
                   env->type_string(),
946
2133624
                   Integer::New(isolate, static_cast<int>(option_info.type)))
947
2133624
             .FromMaybe(false) ||
948

3200436
        info->Set(context, env->value_string(), value).IsNothing() ||
949
1600218
        options->Set(context, name, info).IsEmpty()) {
950
      return;
951
    }
952
  }
953
954
  Local<Value> aliases;
955
9358
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
956
957
4679
  Local<Object> ret = Object::New(isolate);
958

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

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

2681
    if (c == '\\' && is_in_string) {
1029
      if (index + 1 == node_options.size()) {
1030
        errors->push_back("invalid value for NODE_OPTIONS "
1031
                          "(invalid escape)\n");
1032
        return env_argv;
1033
      } else {
1034
        c = node_options.at(++index);
1035
      }
1036

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

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