GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 482 514 93.8 %
Date: 2022-11-20 04:28:36 Branches: 217 280 77.5 %

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_external_reference.h"
7
#include "node_internals.h"
8
#if HAVE_OPENSSL
9
#include "openssl/opensslv.h"
10
#endif
11
12
#include <errno.h>
13
#include <sstream>
14
#include <limits>
15
#include <algorithm>
16
#include <cstdlib>  // strtoul, errno
17
18
using v8::Boolean;
19
using v8::Context;
20
using v8::FunctionCallbackInfo;
21
using v8::Integer;
22
using v8::Isolate;
23
using v8::Local;
24
using v8::Map;
25
using v8::Number;
26
using v8::Object;
27
using v8::Undefined;
28
using v8::Value;
29
30
namespace node {
31
32
namespace per_process {
33
Mutex cli_options_mutex;
34
std::shared_ptr<PerProcessOptions> cli_options{new PerProcessOptions()};
35
}  // namespace per_process
36
37
11838
void DebugOptions::CheckOptions(std::vector<std::string>* errors,
38
                                std::vector<std::string>* argv) {
39
#if !NODE_USE_V8_PLATFORM && !HAVE_INSPECTOR
40
  if (inspector_enabled) {
41
    errors->push_back("Inspector is not available when Node is compiled "
42
                      "--without-v8-platform and --without-inspector.");
43
  }
44
#endif
45
46
11838
  if (deprecated_debug) {
47
4
    errors->push_back("[DEP0062]: `node --debug` and `node --debug-brk` "
48
                      "are invalid. Please use `node --inspect` and "
49
                      "`node --inspect-brk` instead.");
50
  }
51
52
  std::vector<std::string> destinations =
53
23676
      SplitString(inspect_publish_uid_string, ',');
54
11838
  inspect_publish_uid.console = false;
55
11838
  inspect_publish_uid.http = false;
56
35512
  for (const std::string& destination : destinations) {
57
23674
    if (destination == "stderr") {
58
11837
      inspect_publish_uid.console = true;
59
11837
    } else if (destination == "http") {
60
11837
      inspect_publish_uid.http = true;
61
    } else {
62
      errors->push_back("--inspect-publish-uid destination can be "
63
                        "stderr or http");
64
    }
65
  }
66
11838
}
67
68
11239
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors,
69
                                     std::vector<std::string>* argv) {
70
#if HAVE_OPENSSL
71

11239
  if (use_openssl_ca && use_bundled_ca) {
72
1
    errors->push_back("either --use-openssl-ca or --use-bundled-ca can be "
73
                      "used, not both");
74
  }
75
76
  // Any value less than 2 disables use of the secure heap.
77
11239
  if (secure_heap >= 2) {
78
2
    if ((secure_heap & (secure_heap - 1)) != 0)
79
1
      errors->push_back("--secure-heap must be a power of 2");
80
2
    secure_heap_min =
81
6
        std::min({
82
2
            secure_heap,
83
2
            secure_heap_min,
84
            static_cast<int64_t>(std::numeric_limits<int>::max())});
85
2
    secure_heap_min = std::max(static_cast<int64_t>(2), secure_heap_min);
86
2
    if ((secure_heap_min & (secure_heap_min - 1)) != 0)
87
1
      errors->push_back("--secure-heap-min must be a power of 2");
88
  }
89
#endif  // HAVE_OPENSSL
90
91
11241
  if (use_largepages != "off" &&
92

11241
      use_largepages != "on" &&
93
1
      use_largepages != "silent") {
94
1
    errors->push_back("invalid value for --use-largepages");
95
  }
96
11239
  per_isolate->CheckOptions(errors, argv);
97
11239
}
98
99
11838
void PerIsolateOptions::CheckOptions(std::vector<std::string>* errors,
100
                                     std::vector<std::string>* argv) {
101
11838
  per_env->CheckOptions(errors, argv);
102
11838
}
103
104
11838
void EnvironmentOptions::CheckOptions(std::vector<std::string>* errors,
105
                                      std::vector<std::string>* argv) {
106

11838
  if (has_policy_integrity_string && experimental_policy.empty()) {
107
    errors->push_back("--policy-integrity requires "
108
                      "--experimental-policy be enabled");
109
  }
110

11838
  if (has_policy_integrity_string && experimental_policy_integrity.empty()) {
111
1
    errors->push_back("--policy-integrity cannot be empty");
112
  }
113
114
11838
  if (!module_type.empty()) {
115

58
    if (module_type != "commonjs" && module_type != "module") {
116
      errors->push_back("--input-type must be \"module\" or \"commonjs\"");
117
    }
118
  }
119
120

11838
  if (syntax_check_only && has_eval_string) {
121
4
    errors->push_back("either --check or --eval can be used, not both");
122
  }
123
124
11858
  if (!unhandled_rejections.empty() &&
125
39
      unhandled_rejections != "warn-with-error-code" &&
126
36
      unhandled_rejections != "throw" &&
127
32
      unhandled_rejections != "strict" &&
128

11873
      unhandled_rejections != "warn" &&
129
10
      unhandled_rejections != "none") {
130
1
    errors->push_back("invalid value for --unhandled-rejections");
131
  }
132
133

11838
  if (tls_min_v1_3 && tls_max_v1_2) {
134
1
    errors->push_back("either --tls-min-v1.3 or --tls-max-v1.2 can be "
135
                      "used, not both");
136
  }
137
138
11838
  if (heap_snapshot_near_heap_limit < 0) {
139
    errors->push_back("--heapsnapshot-near-heap-limit must not be negative");
140
  }
141
142
11838
  if (test_runner) {
143
19
    if (syntax_check_only) {
144
1
      errors->push_back("either --test or --check can be used, not both");
145
    }
146
147
19
    if (has_eval_string) {
148
2
      errors->push_back("either --test or --eval can be used, not both");
149
    }
150
151
19
    if (force_repl) {
152
1
      errors->push_back("either --test or --interactive can be used, not both");
153
    }
154
155
19
    if (watch_mode_paths.size() > 0) {
156
      errors->push_back(
157
          "--watch-path cannot be used in combination with --test");
158
    }
159
160
#ifndef ALLOW_ATTACHING_DEBUGGER_IN_TEST_RUNNER
161
    debug_options_.allow_attaching_debugger = false;
162
#endif
163
  }
164
165
11838
  if (watch_mode) {
166
13
    if (syntax_check_only) {
167
      errors->push_back("either --watch or --check can be used, not both");
168
13
    } else if (has_eval_string) {
169
      errors->push_back("either --watch or --eval can be used, not both");
170
13
    } else if (force_repl) {
171
      errors->push_back("either --watch or --interactive "
172
                        "can be used, not both");
173

13
    } else if (argv->size() < 1 || (*argv)[1].empty()) {
174
      errors->push_back("--watch requires specifying a file");
175
    }
176
177
#ifndef ALLOW_ATTACHING_DEBUGGER_IN_WATCH_MODE
178
    debug_options_.allow_attaching_debugger = false;
179
#endif
180
  }
181
182
#if HAVE_INSPECTOR
183
11838
  if (!cpu_prof) {
184
11827
    if (!cpu_prof_name.empty()) {
185
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
186
    }
187
11827
    if (!cpu_prof_dir.empty()) {
188
1
      errors->push_back("--cpu-prof-dir must be used with --cpu-prof");
189
    }
190
    // We can't catch the case where the value passed is the default value,
191
    // then the option just becomes a noop which is fine.
192
11827
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
193
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
194
    }
195
  }
196
197


11838
  if (cpu_prof && cpu_prof_dir.empty() && !diagnostic_dir.empty()) {
198
1
      cpu_prof_dir = diagnostic_dir;
199
    }
200
201
11838
  if (!heap_prof) {
202
11827
    if (!heap_prof_name.empty()) {
203
1
      errors->push_back("--heap-prof-name must be used with --heap-prof");
204
    }
205
11827
    if (!heap_prof_dir.empty()) {
206
1
      errors->push_back("--heap-prof-dir must be used with --heap-prof");
207
    }
208
    // We can't catch the case where the value passed is the default value,
209
    // then the option just becomes a noop which is fine.
210
11827
    if (heap_prof_interval != kDefaultHeapProfInterval) {
211
1
      errors->push_back("--heap-prof-interval must be used with --heap-prof");
212
    }
213
  }
214
215


11838
  if (heap_prof && heap_prof_dir.empty() && !diagnostic_dir.empty()) {
216
1
    heap_prof_dir = diagnostic_dir;
217
  }
218
219
11838
  debug_options_.CheckOptions(errors, argv);
220
#endif  // HAVE_INSPECTOR
221
11838
}
222
223
namespace options_parser {
224
225
class DebugOptionsParser : public OptionsParser<DebugOptions> {
226
 public:
227
  DebugOptionsParser();
228
};
229
230
class EnvironmentOptionsParser : public OptionsParser<EnvironmentOptions> {
231
 public:
232
  EnvironmentOptionsParser();
233
5689
  explicit EnvironmentOptionsParser(const DebugOptionsParser& dop)
234
5689
    : EnvironmentOptionsParser() {
235
5689
    Insert(dop, &EnvironmentOptions::get_debug_options);
236
5689
  }
237
};
238
239
class PerIsolateOptionsParser : public OptionsParser<PerIsolateOptions> {
240
 public:
241
  PerIsolateOptionsParser() = delete;
242
  explicit PerIsolateOptionsParser(const EnvironmentOptionsParser& eop);
243
};
244
245
class PerProcessOptionsParser : public OptionsParser<PerProcessOptions> {
246
 public:
247
  PerProcessOptionsParser() = delete;
248
  explicit PerProcessOptionsParser(const PerIsolateOptionsParser& iop);
249
};
250
251
#if HAVE_INSPECTOR
252
const DebugOptionsParser _dop_instance{};
253
const EnvironmentOptionsParser _eop_instance{_dop_instance};
254
255
// This Parse is not dead code. It is used by embedders (e.g., Electron).
256
template <>
257
void Parse(
258
  StringVector* const args, StringVector* const exec_args,
259
  StringVector* const v8_args,
260
  DebugOptions* const options,
261
  OptionEnvvarSettings required_env_settings, StringVector* const errors) {
262
  _dop_instance.Parse(
263
    args, exec_args, v8_args, options, required_env_settings, errors);
264
}
265
#else
266
const EnvironmentOptionsParser _eop_instance{};
267
#endif  // HAVE_INSPECTOR
268
const PerIsolateOptionsParser _piop_instance{_eop_instance};
269
const PerProcessOptionsParser _ppop_instance{_piop_instance};
270
271
template <>
272
599
void Parse(
273
  StringVector* const args, StringVector* const exec_args,
274
  StringVector* const v8_args,
275
  PerIsolateOptions* const options,
276
  OptionEnvvarSettings required_env_settings, StringVector* const errors) {
277
599
  _piop_instance.Parse(
278
    args, exec_args, v8_args, options, required_env_settings, errors);
279
599
}
280
281
template <>
282
11239
void Parse(
283
  StringVector* const args, StringVector* const exec_args,
284
  StringVector* const v8_args,
285
  PerProcessOptions* const options,
286
  OptionEnvvarSettings required_env_settings, StringVector* const errors) {
287
11239
  _ppop_instance.Parse(
288
    args, exec_args, v8_args, options, required_env_settings, errors);
289
11239
}
290
291
// XXX: If you add an option here, please also add it to doc/node.1 and
292
// doc/api/cli.md
293
// TODO(addaleax): Make that unnecessary.
294
295
5689
DebugOptionsParser::DebugOptionsParser() {
296
5689
  AddOption("--inspect-port",
297
            "set host:port for inspector",
298
            &DebugOptions::host_port,
299
            kAllowedInEnvvar);
300
5689
  AddAlias("--debug-port", "--inspect-port");
301
302
5689
  AddOption("--inspect",
303
            "activate inspector on host:port (default: 127.0.0.1:9229)",
304
            &DebugOptions::inspector_enabled,
305
            kAllowedInEnvvar);
306
17067
  AddAlias("--inspect=", { "--inspect-port", "--inspect" });
307
308
5689
  AddOption("--debug", "", &DebugOptions::deprecated_debug);
309
5689
  AddAlias("--debug=", "--debug");
310
5689
  AddOption("--debug-brk", "", &DebugOptions::deprecated_debug);
311
5689
  AddAlias("--debug-brk=", "--debug-brk");
312
313
5689
  AddOption("--inspect-brk",
314
            "activate inspector on host:port and break at start of user script",
315
            &DebugOptions::break_first_line,
316
            kAllowedInEnvvar);
317
5689
  Implies("--inspect-brk", "--inspect");
318
17067
  AddAlias("--inspect-brk=", { "--inspect-port", "--inspect-brk" });
319
320
5689
  AddOption("--inspect-brk-node", "", &DebugOptions::break_node_first_line);
321
5689
  Implies("--inspect-brk-node", "--inspect");
322
17067
  AddAlias("--inspect-brk-node=", { "--inspect-port", "--inspect-brk-node" });
323
324
5689
  AddOption("--inspect-publish-uid",
325
            "comma separated list of destinations for inspector uid"
326
            "(default: stderr,http)",
327
            &DebugOptions::inspect_publish_uid_string,
328
            kAllowedInEnvvar);
329
5689
}
330
331
5689
EnvironmentOptionsParser::EnvironmentOptionsParser() {
332
5689
  AddOption("--conditions",
333
            "additional user conditions for conditional exports and imports",
334
            &EnvironmentOptions::conditions,
335
            kAllowedInEnvvar);
336
5689
  AddAlias("-C", "--conditions");
337
5689
  AddOption("--diagnostic-dir",
338
            "set dir for all output files"
339
            " (default: current working directory)",
340
            &EnvironmentOptions::diagnostic_dir,
341
            kAllowedInEnvvar);
342
5689
  AddOption("--dns-result-order",
343
            "set default value of verbatim in dns.lookup. Options are "
344
            "'ipv4first' (IPv4 addresses are placed before IPv6 addresses) "
345
            "'verbatim' (addresses are in the order the DNS resolver "
346
            "returned)",
347
            &EnvironmentOptions::dns_result_order,
348
            kAllowedInEnvvar);
349
5689
  AddOption("--enable-source-maps",
350
            "Source Map V3 support for stack traces",
351
            &EnvironmentOptions::enable_source_maps,
352
            kAllowedInEnvvar);
353
5689
  AddOption("--experimental-abortcontroller", "", NoOp{}, kAllowedInEnvvar);
354
5689
  AddOption("--experimental-fetch",
355
            "experimental Fetch API",
356
            &EnvironmentOptions::experimental_fetch,
357
            kAllowedInEnvvar,
358
            true);
359
5689
  AddOption("--experimental-global-customevent",
360
            "expose experimental CustomEvent on the global scope",
361
            &EnvironmentOptions::experimental_global_customevent,
362
            kAllowedInEnvvar,
363
            true);
364
5689
  AddOption("--experimental-global-webcrypto",
365
            "expose experimental Web Crypto API on the global scope",
366
            &EnvironmentOptions::experimental_global_web_crypto,
367
            kAllowedInEnvvar,
368
            true);
369
5689
  AddOption("--experimental-json-modules", "", NoOp{}, kAllowedInEnvvar);
370
5689
  AddOption("--experimental-loader",
371
            "use the specified module as a custom loader",
372
            &EnvironmentOptions::userland_loaders,
373
            kAllowedInEnvvar);
374
5689
  AddAlias("--loader", "--experimental-loader");
375
5689
  AddOption("--experimental-modules", "", NoOp{}, kAllowedInEnvvar);
376
5689
  AddOption("--experimental-network-imports",
377
            "experimental https: support for the ES Module loader",
378
            &EnvironmentOptions::experimental_https_modules,
379
            kAllowedInEnvvar);
380
5689
  AddOption("--experimental-wasm-modules",
381
            "experimental ES Module support for webassembly modules",
382
            &EnvironmentOptions::experimental_wasm_modules,
383
            kAllowedInEnvvar);
384
5689
  AddOption("--experimental-import-meta-resolve",
385
            "experimental ES Module import.meta.resolve() support",
386
            &EnvironmentOptions::experimental_import_meta_resolve,
387
            kAllowedInEnvvar);
388
5689
  AddOption("--experimental-policy",
389
            "use the specified file as a "
390
            "security policy",
391
            &EnvironmentOptions::experimental_policy,
392
            kAllowedInEnvvar);
393
5689
  AddOption("[has_policy_integrity_string]",
394
            "",
395
            &EnvironmentOptions::has_policy_integrity_string);
396
5689
  AddOption("--policy-integrity",
397
            "ensure the security policy contents match "
398
            "the specified integrity",
399
            &EnvironmentOptions::experimental_policy_integrity,
400
            kAllowedInEnvvar);
401
5689
  Implies("--policy-integrity", "[has_policy_integrity_string]");
402
5689
  AddOption("--experimental-repl-await",
403
            "experimental await keyword support in REPL",
404
            &EnvironmentOptions::experimental_repl_await,
405
            kAllowedInEnvvar,
406
            true);
407
5689
  AddOption("--experimental-vm-modules",
408
            "experimental ES Module support in vm module",
409
            &EnvironmentOptions::experimental_vm_modules,
410
            kAllowedInEnvvar);
411
5689
  AddOption("--experimental-worker", "", NoOp{}, kAllowedInEnvvar);
412
5689
  AddOption("--experimental-report", "", NoOp{}, kAllowedInEnvvar);
413
5689
  AddOption("--experimental-wasi-unstable-preview1",
414
            "experimental WASI support",
415
            &EnvironmentOptions::experimental_wasi,
416
            kAllowedInEnvvar);
417
5689
  AddOption("--expose-internals", "", &EnvironmentOptions::expose_internals);
418
5689
  AddOption("--frozen-intrinsics",
419
            "experimental frozen intrinsics support",
420
            &EnvironmentOptions::frozen_intrinsics,
421
            kAllowedInEnvvar);
422
5689
  AddOption("--heapsnapshot-signal",
423
            "Generate heap snapshot on specified signal",
424
            &EnvironmentOptions::heap_snapshot_signal,
425
            kAllowedInEnvvar);
426
5689
  AddOption("--heapsnapshot-near-heap-limit",
427
            "Generate heap snapshots whenever V8 is approaching "
428
            "the heap limit. No more than the specified number of "
429
            "heap snapshots will be generated.",
430
            &EnvironmentOptions::heap_snapshot_near_heap_limit,
431
            kAllowedInEnvvar);
432
5689
  AddOption("--http-parser", "", NoOp{}, kAllowedInEnvvar);
433
5689
  AddOption("--insecure-http-parser",
434
            "use an insecure HTTP parser that accepts invalid HTTP headers",
435
            &EnvironmentOptions::insecure_http_parser,
436
            kAllowedInEnvvar);
437
5689
  AddOption("--input-type",
438
            "set module type for string input",
439
            &EnvironmentOptions::module_type,
440
            kAllowedInEnvvar);
441
5689
  AddOption(
442
      "--experimental-specifier-resolution", "", NoOp{}, kAllowedInEnvvar);
443
5689
  AddAlias("--es-module-specifier-resolution",
444
           "--experimental-specifier-resolution");
445
5689
  AddOption("--deprecation",
446
            "silence deprecation warnings",
447
            &EnvironmentOptions::deprecation,
448
            kAllowedInEnvvar,
449
            true);
450
5689
  AddOption("--force-async-hooks-checks",
451
            "disable checks for async_hooks",
452
            &EnvironmentOptions::force_async_hooks_checks,
453
            kAllowedInEnvvar,
454
            true);
455
5689
  AddOption(
456
      "--force-node-api-uncaught-exceptions-policy",
457
      "enforces 'uncaughtException' event on Node API asynchronous callbacks",
458
      &EnvironmentOptions::force_node_api_uncaught_exceptions_policy,
459
      kAllowedInEnvvar,
460
      false);
461
5689
  AddOption("--addons",
462
            "disable loading native addons",
463
            &EnvironmentOptions::allow_native_addons,
464
            kAllowedInEnvvar,
465
            true);
466
5689
  AddOption("--global-search-paths",
467
            "disable global module search paths",
468
            &EnvironmentOptions::global_search_paths,
469
            kAllowedInEnvvar,
470
            true);
471
5689
  AddOption("--warnings",
472
            "silence all process warnings",
473
            &EnvironmentOptions::warnings,
474
            kAllowedInEnvvar,
475
            true);
476
5689
  AddOption("--force-context-aware",
477
            "disable loading non-context-aware addons",
478
            &EnvironmentOptions::force_context_aware,
479
            kAllowedInEnvvar);
480
5689
  AddOption("--pending-deprecation",
481
            "emit pending deprecation warnings",
482
            &EnvironmentOptions::pending_deprecation,
483
            kAllowedInEnvvar);
484
5689
  AddOption("--preserve-symlinks",
485
            "preserve symbolic links when resolving",
486
            &EnvironmentOptions::preserve_symlinks,
487
            kAllowedInEnvvar);
488
5689
  AddOption("--preserve-symlinks-main",
489
            "preserve symbolic links when resolving the main module",
490
            &EnvironmentOptions::preserve_symlinks_main,
491
            kAllowedInEnvvar);
492
5689
  AddOption("--prof",
493
            "Generate V8 profiler output.",
494
            V8Option{});
495
5689
  AddOption("--prof-process",
496
            "process V8 profiler output generated using --prof",
497
            &EnvironmentOptions::prof_process);
498
  // Options after --prof-process are passed through to the prof processor.
499
17067
  AddAlias("--prof-process", { "--prof-process", "--" });
500
#if HAVE_INSPECTOR
501
5689
  AddOption("--cpu-prof",
502
            "Start the V8 CPU profiler on start up, and write the CPU profile "
503
            "to disk before exit. If --cpu-prof-dir is not specified, write "
504
            "the profile to the current working directory.",
505
            &EnvironmentOptions::cpu_prof);
506
5689
  AddOption("--cpu-prof-name",
507
            "specified file name of the V8 CPU profile generated with "
508
            "--cpu-prof",
509
            &EnvironmentOptions::cpu_prof_name);
510
5689
  AddOption("--cpu-prof-interval",
511
            "specified sampling interval in microseconds for the V8 CPU "
512
            "profile generated with --cpu-prof. (default: 1000)",
513
            &EnvironmentOptions::cpu_prof_interval);
514
5689
  AddOption("--cpu-prof-dir",
515
            "Directory where the V8 profiles generated by --cpu-prof will be "
516
            "placed. Does not affect --prof.",
517
            &EnvironmentOptions::cpu_prof_dir);
518
5689
  AddOption(
519
      "--heap-prof",
520
      "Start the V8 heap profiler on start up, and write the heap profile "
521
      "to disk before exit. If --heap-prof-dir is not specified, write "
522
      "the profile to the current working directory.",
523
      &EnvironmentOptions::heap_prof);
524
5689
  AddOption("--heap-prof-name",
525
            "specified file name of the V8 heap profile generated with "
526
            "--heap-prof",
527
            &EnvironmentOptions::heap_prof_name);
528
5689
  AddOption("--heap-prof-dir",
529
            "Directory where the V8 heap profiles generated by --heap-prof "
530
            "will be placed.",
531
            &EnvironmentOptions::heap_prof_dir);
532
5689
  AddOption("--heap-prof-interval",
533
            "specified sampling interval in bytes for the V8 heap "
534
            "profile generated with --heap-prof. (default: 512 * 1024)",
535
            &EnvironmentOptions::heap_prof_interval);
536
#endif  // HAVE_INSPECTOR
537
5689
  AddOption("--max-http-header-size",
538
            "set the maximum size of HTTP headers (default: 16384 (16KB))",
539
            &EnvironmentOptions::max_http_header_size,
540
            kAllowedInEnvvar);
541
5689
  AddOption("--redirect-warnings",
542
            "write warnings to file instead of stderr",
543
            &EnvironmentOptions::redirect_warnings,
544
            kAllowedInEnvvar);
545
5689
  AddOption("--test",
546
            "launch test runner on startup",
547
            &EnvironmentOptions::test_runner);
548
5689
  AddOption("--test-name-pattern",
549
            "run tests whose name matches this regular expression",
550
            &EnvironmentOptions::test_name_pattern);
551
5689
  AddOption("--test-only",
552
            "run tests with 'only' option set",
553
            &EnvironmentOptions::test_only,
554
            kAllowedInEnvvar);
555
5689
  AddOption("--test-udp-no-try-send", "",  // For testing only.
556
            &EnvironmentOptions::test_udp_no_try_send);
557
5689
  AddOption("--throw-deprecation",
558
            "throw an exception on deprecations",
559
            &EnvironmentOptions::throw_deprecation,
560
            kAllowedInEnvvar);
561
5689
  AddOption("--trace-atomics-wait",
562
            "(deprecated) trace Atomics.wait() operations",
563
            &EnvironmentOptions::trace_atomics_wait,
564
            kAllowedInEnvvar);
565
5689
  AddOption("--trace-deprecation",
566
            "show stack traces on deprecations",
567
            &EnvironmentOptions::trace_deprecation,
568
            kAllowedInEnvvar);
569
5689
  AddOption("--trace-exit",
570
            "show stack trace when an environment exits",
571
            &EnvironmentOptions::trace_exit,
572
            kAllowedInEnvvar);
573
5689
  AddOption("--trace-sync-io",
574
            "show stack trace when use of sync IO is detected after the "
575
            "first tick",
576
            &EnvironmentOptions::trace_sync_io,
577
            kAllowedInEnvvar);
578
5689
  AddOption("--trace-tls",
579
            "prints TLS packet trace information to stderr",
580
            &EnvironmentOptions::trace_tls,
581
            kAllowedInEnvvar);
582
5689
  AddOption("--trace-uncaught",
583
            "show stack traces for the `throw` behind uncaught exceptions",
584
            &EnvironmentOptions::trace_uncaught,
585
            kAllowedInEnvvar);
586
5689
  AddOption("--trace-warnings",
587
            "show stack traces on process warnings",
588
            &EnvironmentOptions::trace_warnings,
589
            kAllowedInEnvvar);
590
5689
  AddOption("--extra-info-on-fatal-exception",
591
            "hide extra information on fatal exception that causes exit",
592
            &EnvironmentOptions::extra_info_on_fatal_exception,
593
            kAllowedInEnvvar,
594
            true);
595
5689
  AddOption("--unhandled-rejections",
596
            "define unhandled rejections behavior. Options are 'strict' "
597
            "(always raise an error), 'throw' (raise an error unless "
598
            "'unhandledRejection' hook is set), 'warn' (log a warning), 'none' "
599
            "(silence warnings), 'warn-with-error-code' (log a warning and set "
600
            "exit code 1 unless 'unhandledRejection' hook is set). (default: "
601
            "throw)",
602
            &EnvironmentOptions::unhandled_rejections,
603
            kAllowedInEnvvar);
604
5689
  AddOption("--verify-base-objects",
605
            "", /* undocumented, only for debugging */
606
            &EnvironmentOptions::verify_base_objects,
607
            kAllowedInEnvvar);
608
5689
  AddOption("--watch",
609
            "run in watch mode",
610
            &EnvironmentOptions::watch_mode,
611
            kAllowedInEnvvar);
612
5689
  AddOption("--watch-path",
613
            "path to watch",
614
            &EnvironmentOptions::watch_mode_paths,
615
            kAllowedInEnvvar);
616
5689
  Implies("--watch-path", "--watch");
617
5689
  AddOption("--check",
618
            "syntax check script without executing",
619
            &EnvironmentOptions::syntax_check_only);
620
5689
  AddAlias("-c", "--check");
621
  // This option is only so that we can tell --eval with an empty string from
622
  // no eval at all. Having it not start with a dash makes it inaccessible
623
  // from the parser itself, but available for using Implies().
624
  // TODO(addaleax): When moving --help over to something generated from the
625
  // programmatic descriptions, this will need some special care.
626
  // (See also [ssl_openssl_cert_store] below.)
627
5689
  AddOption("[has_eval_string]", "", &EnvironmentOptions::has_eval_string);
628
5689
  AddOption("--eval", "evaluate script", &EnvironmentOptions::eval_string);
629
5689
  Implies("--eval", "[has_eval_string]");
630
5689
  AddOption("--print",
631
            "evaluate script and print result",
632
            &EnvironmentOptions::print_eval);
633
5689
  AddAlias("-e", "--eval");
634
5689
  AddAlias("--print <arg>", "-pe");
635
17067
  AddAlias("-pe", { "--print", "--eval" });
636
5689
  AddAlias("-p", "--print");
637
5689
  AddOption("--require",
638
            "CommonJS module to preload (option can be repeated)",
639
            &EnvironmentOptions::preload_cjs_modules,
640
            kAllowedInEnvvar);
641
5689
  AddAlias("-r", "--require");
642
5689
  AddOption("--import",
643
            "ES module to preload (option can be repeated)",
644
            &EnvironmentOptions::preload_esm_modules,
645
            kAllowedInEnvvar);
646
5689
  AddOption("--interactive",
647
            "always enter the REPL even if stdin does not appear "
648
            "to be a terminal",
649
            &EnvironmentOptions::force_repl);
650
5689
  AddAlias("-i", "--interactive");
651
652
5689
  AddOption("--update-assert-snapshot",
653
            "update assert snapshot files",
654
            &EnvironmentOptions::update_assert_snapshot,
655
            kAllowedInEnvvar);
656
657
5689
  AddOption("--napi-modules", "", NoOp{}, kAllowedInEnvvar);
658
659
5689
  AddOption("--tls-keylog",
660
            "log TLS decryption keys to named file for traffic analysis",
661
            &EnvironmentOptions::tls_keylog,
662
            kAllowedInEnvvar);
663
664
5689
  AddOption("--tls-min-v1.0",
665
            "set default TLS minimum to TLSv1.0 (default: TLSv1.2)",
666
            &EnvironmentOptions::tls_min_v1_0,
667
            kAllowedInEnvvar);
668
5689
  AddOption("--tls-min-v1.1",
669
            "set default TLS minimum to TLSv1.1 (default: TLSv1.2)",
670
            &EnvironmentOptions::tls_min_v1_1,
671
            kAllowedInEnvvar);
672
5689
  AddOption("--tls-min-v1.2",
673
            "set default TLS minimum to TLSv1.2 (default: TLSv1.2)",
674
            &EnvironmentOptions::tls_min_v1_2,
675
            kAllowedInEnvvar);
676
5689
  AddOption("--tls-min-v1.3",
677
            "set default TLS minimum to TLSv1.3 (default: TLSv1.2)",
678
            &EnvironmentOptions::tls_min_v1_3,
679
            kAllowedInEnvvar);
680
5689
  AddOption("--tls-max-v1.2",
681
            "set default TLS maximum to TLSv1.2 (default: TLSv1.3)",
682
            &EnvironmentOptions::tls_max_v1_2,
683
            kAllowedInEnvvar);
684
  // Current plan is:
685
  // - 11.x and below: TLS1.3 is opt-in with --tls-max-v1.3
686
  // - 12.x: TLS1.3 is opt-out with --tls-max-v1.2
687
  // In either case, support both options they are uniformly available.
688
5689
  AddOption("--tls-max-v1.3",
689
            "set default TLS maximum to TLSv1.3 (default: TLSv1.3)",
690
            &EnvironmentOptions::tls_max_v1_3,
691
            kAllowedInEnvvar);
692
5689
}
693
694
5689
PerIsolateOptionsParser::PerIsolateOptionsParser(
695
5689
  const EnvironmentOptionsParser& eop) {
696
5689
  AddOption("--track-heap-objects",
697
            "track heap object allocations for heap snapshots",
698
            &PerIsolateOptions::track_heap_objects,
699
            kAllowedInEnvvar);
700
701
  // Explicitly add some V8 flags to mark them as allowed in NODE_OPTIONS.
702
5689
  AddOption("--abort-on-uncaught-exception",
703
            "aborting instead of exiting causes a core file to be generated "
704
            "for analysis",
705
            V8Option{},
706
            kAllowedInEnvvar);
707
5689
  AddOption("--interpreted-frames-native-stack",
708
            "help system profilers to translate JavaScript interpreted frames",
709
            V8Option{},
710
            kAllowedInEnvvar);
711
5689
  AddOption("--max-old-space-size", "", V8Option{}, kAllowedInEnvvar);
712
5689
  AddOption("--max-semi-space-size", "", V8Option{}, kAllowedInEnvvar);
713
5689
  AddOption("--perf-basic-prof", "", V8Option{}, kAllowedInEnvvar);
714
5689
  AddOption(
715
      "--perf-basic-prof-only-functions", "", V8Option{}, kAllowedInEnvvar);
716
5689
  AddOption("--perf-prof", "", V8Option{}, kAllowedInEnvvar);
717
5689
  AddOption("--perf-prof-unwinding-info", "", V8Option{}, kAllowedInEnvvar);
718
5689
  AddOption("--stack-trace-limit", "", V8Option{}, kAllowedInEnvvar);
719
5689
  AddOption("--disallow-code-generation-from-strings",
720
            "disallow eval and friends",
721
            V8Option{},
722
            kAllowedInEnvvar);
723
5689
  AddOption("--huge-max-old-generation-size",
724
            "increase default maximum heap size on machines with 16GB memory "
725
            "or more",
726
            V8Option{},
727
            kAllowedInEnvvar);
728
5689
  AddOption("--jitless",
729
            "disable runtime allocation of executable memory",
730
            V8Option{},
731
            kAllowedInEnvvar);
732
5689
  AddOption("--report-uncaught-exception",
733
            "generate diagnostic report on uncaught exceptions",
734
            &PerIsolateOptions::report_uncaught_exception,
735
            kAllowedInEnvvar);
736
5689
  AddOption("--report-on-signal",
737
            "generate diagnostic report upon receiving signals",
738
            &PerIsolateOptions::report_on_signal,
739
            kAllowedInEnvvar);
740
5689
  AddOption("--report-signal",
741
            "causes diagnostic report to be produced on provided signal,"
742
            " unsupported in Windows. (default: SIGUSR2)",
743
            &PerIsolateOptions::report_signal,
744
            kAllowedInEnvvar);
745
5689
  Implies("--report-signal", "--report-on-signal");
746
747
5689
  AddOption("--experimental-top-level-await", "", NoOp{}, kAllowedInEnvvar);
748
749
5689
  AddOption("--experimental-shadow-realm",
750
            "",
751
            &PerIsolateOptions::experimental_shadow_realm,
752
            kAllowedInEnvvar);
753
5689
  AddOption("--harmony-shadow-realm", "", V8Option{});
754
5689
  Implies("--experimental-shadow-realm", "--harmony-shadow-realm");
755
5689
  Implies("--harmony-shadow-realm", "--experimental-shadow-realm");
756
5689
  ImpliesNot("--no-harmony-shadow-realm", "--experimental-shadow-realm");
757
758
5689
  Insert(eop, &PerIsolateOptions::get_per_env_options);
759
5689
}
760
761
5689
PerProcessOptionsParser::PerProcessOptionsParser(
762
5689
  const PerIsolateOptionsParser& iop) {
763
5689
  AddOption("--title",
764
            "the process title to use on startup",
765
            &PerProcessOptions::title,
766
            kAllowedInEnvvar);
767
5689
  AddOption("--trace-event-categories",
768
            "comma separated list of trace event categories to record",
769
            &PerProcessOptions::trace_event_categories,
770
            kAllowedInEnvvar);
771
5689
  AddOption("--trace-event-file-pattern",
772
            "Template string specifying the filepath for the trace-events "
773
            "data, it supports ${rotation} and ${pid}.",
774
            &PerProcessOptions::trace_event_file_pattern,
775
            kAllowedInEnvvar);
776
17067
  AddAlias("--trace-events-enabled", {
777
11378
    "--trace-event-categories", "v8,node,node.async_hooks" });
778
5689
  AddOption("--v8-pool-size",
779
            "set V8's thread pool size",
780
            &PerProcessOptions::v8_thread_pool_size,
781
            kAllowedInEnvvar);
782
5689
  AddOption("--zero-fill-buffers",
783
            "automatically zero-fill all newly allocated Buffer and "
784
            "SlowBuffer instances",
785
            &PerProcessOptions::zero_fill_all_buffers,
786
            kAllowedInEnvvar);
787
5689
  AddOption("--debug-arraybuffer-allocations",
788
            "", /* undocumented, only for debugging */
789
            &PerProcessOptions::debug_arraybuffer_allocations,
790
            kAllowedInEnvvar);
791
5689
  AddOption("--disable-proto",
792
            "disable Object.prototype.__proto__",
793
            &PerProcessOptions::disable_proto,
794
            kAllowedInEnvvar);
795
5689
  AddOption("--build-snapshot",
796
            "Generate a snapshot blob when the process exits."
797
            " Currently only supported in the node_mksnapshot binary.",
798
            &PerProcessOptions::build_snapshot,
799
            kDisallowedInEnvvar);
800
5689
  AddOption("--node-snapshot",
801
            "",  // It's a debug-only option.
802
            &PerProcessOptions::node_snapshot,
803
            kAllowedInEnvvar);
804
5689
  AddOption("--snapshot-blob",
805
            "Path to the snapshot blob that's either the result of snapshot"
806
            "building, or the blob that is used to restore the application "
807
            "state",
808
            &PerProcessOptions::snapshot_blob,
809
            kAllowedInEnvvar);
810
811
  // 12.x renamed this inadvertently, so alias it for consistency within the
812
  // release line, while using the original name for consistency with older
813
  // release lines.
814
5689
  AddOption("--security-revert", "", &PerProcessOptions::security_reverts);
815
5689
  AddAlias("--security-reverts", "--security-revert");
816
5689
  AddOption("--completion-bash",
817
            "print source-able bash completion script",
818
            &PerProcessOptions::print_bash_completion);
819
5689
  AddOption("--help",
820
            "print node command line options",
821
            &PerProcessOptions::print_help);
822
5689
  AddAlias("-h", "--help");
823
5689
  AddOption(
824
      "--version", "print Node.js version", &PerProcessOptions::print_version);
825
5689
  AddAlias("-v", "--version");
826
5689
  AddOption("--v8-options",
827
            "print V8 command line options",
828
            &PerProcessOptions::print_v8_help);
829
5689
  AddOption("--report-compact",
830
            "output compact single-line JSON",
831
            &PerProcessOptions::report_compact,
832
            kAllowedInEnvvar);
833
5689
  AddOption("--report-dir",
834
            "define custom report pathname."
835
            " (default: current working directory)",
836
            &PerProcessOptions::report_directory,
837
            kAllowedInEnvvar);
838
5689
  AddAlias("--report-directory", "--report-dir");
839
5689
  AddOption("--report-filename",
840
            "define custom report file name."
841
            " (default: YYYYMMDD.HHMMSS.PID.SEQUENCE#.txt)",
842
            &PerProcessOptions::report_filename,
843
            kAllowedInEnvvar);
844
5689
  AddOption("--report-on-fatalerror",
845
            "generate diagnostic report on fatal (internal) errors",
846
            &PerProcessOptions::report_on_fatalerror,
847
            kAllowedInEnvvar);
848
849
#ifdef NODE_HAVE_I18N_SUPPORT
850
5689
  AddOption("--icu-data-dir",
851
            "set ICU data load path to dir (overrides NODE_ICU_DATA)"
852
#ifndef NODE_HAVE_SMALL_ICU
853
            " (note: linked-in ICU data is present)"
854
#endif
855
            ,
856
            &PerProcessOptions::icu_data_dir,
857
            kAllowedInEnvvar);
858
#endif
859
860
#if HAVE_OPENSSL
861
5689
  AddOption("--openssl-config",
862
            "load OpenSSL configuration from the specified file "
863
            "(overrides OPENSSL_CONF)",
864
            &PerProcessOptions::openssl_config,
865
            kAllowedInEnvvar);
866
5689
  AddOption("--tls-cipher-list",
867
            "use an alternative default TLS cipher list",
868
            &PerProcessOptions::tls_cipher_list,
869
            kAllowedInEnvvar);
870
5689
  AddOption("--use-openssl-ca",
871
            "use OpenSSL's default CA store"
872
#if defined(NODE_OPENSSL_CERT_STORE)
873
            " (default)"
874
#endif
875
            ,
876
            &PerProcessOptions::use_openssl_ca,
877
            kAllowedInEnvvar);
878
5689
  AddOption("--use-bundled-ca",
879
            "use bundled CA store"
880
#if !defined(NODE_OPENSSL_CERT_STORE)
881
            " (default)"
882
#endif
883
            ,
884
            &PerProcessOptions::use_bundled_ca,
885
            kAllowedInEnvvar);
886
  // Similar to [has_eval_string] above, except that the separation between
887
  // this and use_openssl_ca only exists for option validation after parsing.
888
  // This is not ideal.
889
5689
  AddOption("[ssl_openssl_cert_store]",
890
            "",
891
            &PerProcessOptions::ssl_openssl_cert_store);
892
5689
  Implies("--use-openssl-ca", "[ssl_openssl_cert_store]");
893
5689
  ImpliesNot("--use-bundled-ca", "[ssl_openssl_cert_store]");
894
5689
  AddOption("--enable-fips",
895
            "enable FIPS crypto at startup",
896
            &PerProcessOptions::enable_fips_crypto,
897
            kAllowedInEnvvar);
898
5689
  AddOption("--force-fips",
899
            "force FIPS crypto (cannot be disabled)",
900
            &PerProcessOptions::force_fips_crypto,
901
            kAllowedInEnvvar);
902
5689
  AddOption("--secure-heap",
903
            "total size of the OpenSSL secure heap",
904
            &PerProcessOptions::secure_heap,
905
            kAllowedInEnvvar);
906
5689
  AddOption("--secure-heap-min",
907
            "minimum allocation size from the OpenSSL secure heap",
908
            &PerProcessOptions::secure_heap_min,
909
            kAllowedInEnvvar);
910
#endif  // HAVE_OPENSSL
911
#if OPENSSL_VERSION_MAJOR >= 3
912
5689
  AddOption("--openssl-legacy-provider",
913
            "enable OpenSSL 3.0 legacy provider",
914
            &PerProcessOptions::openssl_legacy_provider,
915
            kAllowedInEnvvar);
916
5689
  AddOption("--openssl-shared-config",
917
            "enable OpenSSL shared configuration",
918
            &PerProcessOptions::openssl_shared_config,
919
            kAllowedInEnvvar);
920
921
#endif  // OPENSSL_VERSION_MAJOR
922
5689
  AddOption("--use-largepages",
923
            "Map the Node.js static code to large pages. Options are "
924
            "'off' (the default value, meaning do not map), "
925
            "'on' (map and ignore failure, reporting it to stderr), "
926
            "or 'silent' (map and silently ignore failure)",
927
            &PerProcessOptions::use_largepages,
928
            kAllowedInEnvvar);
929
930
5689
  AddOption("--trace-sigint",
931
            "enable printing JavaScript stacktrace on SIGINT",
932
            &PerProcessOptions::trace_sigint,
933
            kAllowedInEnvvar);
934
935
5689
  Insert(iop, &PerProcessOptions::get_per_isolate_options);
936
937
5689
  AddOption("--node-memory-debug",
938
            "Run with extra debug checks for memory leaks in Node.js itself",
939
            NoOp{},
940
            kAllowedInEnvvar);
941
5689
  Implies("--node-memory-debug", "--debug-arraybuffer-allocations");
942
5689
  Implies("--node-memory-debug", "--verify-base-objects");
943
5689
}
944
945
168
inline std::string RemoveBrackets(const std::string& host) {
946


168
  if (!host.empty() && host.front() == '[' && host.back() == ']')
947
8
    return host.substr(1, host.size() - 2);
948
  else
949
160
    return host;
950
}
951
952
148
inline int ParseAndValidatePort(const std::string& port,
953
                                std::vector<std::string>* errors) {
954
  char* endptr;
955
148
  errno = 0;
956
  const unsigned long result =                 // NOLINT(runtime/int)
957
148
    strtoul(port.c_str(), &endptr, 10);
958

148
  if (errno != 0 || *endptr != '\0'||
959

148
      (result != 0 && result < 1024) || result > 65535) {
960
    errors->push_back(" must be 0 or in range 1024 to 65535.");
961
  }
962
148
  return static_cast<int>(result);
963
}
964
965
148
HostPort SplitHostPort(const std::string& arg,
966
                      std::vector<std::string>* errors) {
967
  // remove_brackets only works if no port is specified
968
  // so if it has an effect only an IPv6 address was specified.
969
296
  std::string host = RemoveBrackets(arg);
970
148
  if (host.length() < arg.length())
971
    return HostPort{host, DebugOptions::kDefaultInspectorPort};
972
973
148
  size_t colon = arg.rfind(':');
974
148
  if (colon == std::string::npos) {
975
    // Either a port number or a host name.  Assume that
976
    // if it's not all decimal digits, it's a host name.
977
616
    for (char c : arg) {
978

488
      if (c < '0' || c > '9') {
979
        return HostPort{arg, DebugOptions::kDefaultInspectorPort};
980
      }
981
    }
982
128
    return HostPort { "", ParseAndValidatePort(arg, errors) };
983
  }
984
  // Host and port found:
985
40
  return HostPort { RemoveBrackets(arg.substr(0, colon)),
986
20
                    ParseAndValidatePort(arg.substr(colon + 1), errors) };
987
}
988
989
1
std::string GetBashCompletion() {
990
2
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
991
1
  const auto& parser = _ppop_instance;
992
993
2
  std::ostringstream out;
994
995
  out << "_node_complete() {\n"
996
         "  local cur_word options\n"
997
         "  cur_word=\"${COMP_WORDS[COMP_CWORD]}\"\n"
998
         "  if [[ \"${cur_word}\" == -* ]] ; then\n"
999
1
         "    COMPREPLY=( $(compgen -W '";
1000
1001
146
  for (const auto& item : parser.options_) {
1002
145
    if (item.first[0] != '[') {
1003
142
      out << item.first << " ";
1004
    }
1005
  }
1006
23
  for (const auto& item : parser.aliases_) {
1007
22
    if (item.first[0] != '[') {
1008
22
      out << item.first << " ";
1009
    }
1010
  }
1011
1
  if (parser.aliases_.size() > 0) {
1012
1
    out.seekp(-1, out.cur);  // Strip the trailing space
1013
  }
1014
1015
  out << "' -- \"${cur_word}\") )\n"
1016
         "    return 0\n"
1017
         "  else\n"
1018
         "    COMPREPLY=( $(compgen -f \"${cur_word}\") )\n"
1019
         "    return 0\n"
1020
         "  fi\n"
1021
         "}\n"
1022
         "complete -o filenames -o nospace -o bashdefault "
1023
1
         "-F _node_complete node node_g";
1024
1
  return out.str();
1025
}
1026
1027
// Return a map containing all the options and their metadata as well
1028
// as the aliases
1029
void GetCLIOptions(const FunctionCallbackInfo<Value>& args) {
1030
7030
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
1031
7030
  Environment* env = Environment::GetCurrent(args);
1032
7030
  if (!env->has_run_bootstrapping_code()) {
1033
    // No code because this is an assertion.
1034
    return env->ThrowError(
1035
        "Should not query options before bootstrapping is done");
1036
  }
1037
7030
  env->set_has_serialized_options(true);
1038
1039
7030
  Isolate* isolate = env->isolate();
1040
7030
  Local<Context> context = env->context();
1041
1042
  // Temporarily act as if the current Environment's/IsolateData's options were
1043
  // the default options, i.e. like they are the ones we'd access for global
1044
  // options parsing, so that all options are available from the main parser.
1045
7030
  auto original_per_isolate = per_process::cli_options->per_isolate;
1046
7030
  per_process::cli_options->per_isolate = env->isolate_data()->options();
1047
7030
  auto original_per_env = per_process::cli_options->per_isolate->per_env;
1048
7030
  per_process::cli_options->per_isolate->per_env = env->options();
1049
7030
  auto on_scope_leave = OnScopeLeave([&]() {
1050
7030
    per_process::cli_options->per_isolate->per_env = original_per_env;
1051
7030
    per_process::cli_options->per_isolate = original_per_isolate;
1052
7030
  });
1053
1054
7030
  Local<Map> options = Map::New(isolate);
1055
7030
  if (options
1056
14060
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1057
7030
          .IsNothing()) {
1058
    return;
1059
  }
1060
1061
1026380
  for (const auto& item : _ppop_instance.options_) {
1062
    Local<Value> value;
1063
1019350
    const auto& option_info = item.second;
1064
1019350
    auto field = option_info.field;
1065
1019350
    PerProcessOptions* opts = per_process::cli_options.get();
1066


1019350
    switch (option_info.type) {
1067
168720
      case kNoOp:
1068
      case kV8Option:
1069
        // Special case for --abort-on-uncaught-exception which is also
1070
        // respected by Node.js internals
1071
168720
        if (item.first == "--abort-on-uncaught-exception") {
1072
7030
          value = Boolean::New(
1073
7030
            isolate, original_per_env->abort_on_uncaught_exception);
1074
        } else {
1075
161690
          value = Undefined(isolate);
1076
        }
1077
168720
        break;
1078
555370
      case kBoolean:
1079
1110740
        value = Boolean::New(isolate,
1080
1110740
                             *_ppop_instance.Lookup<bool>(field, opts));
1081
555370
        break;
1082
28120
      case kInteger:
1083
56240
        value = Number::New(
1084
            isolate,
1085
56240
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1086
28120
        break;
1087
21090
      case kUInteger:
1088
42180
        value = Number::New(
1089
            isolate,
1090
42180
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1091
21090
        break;
1092
189810
      case kString:
1093
379620
        if (!ToV8Value(context,
1094
379620
                       *_ppop_instance.Lookup<std::string>(field, opts))
1095
189810
                 .ToLocal(&value)) {
1096
          return;
1097
        }
1098
189810
        break;
1099
49210
      case kStringList:
1100
98420
        if (!ToV8Value(context,
1101
98420
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1102
49210
                 .ToLocal(&value)) {
1103
          return;
1104
        }
1105
49210
        break;
1106
7030
      case kHostPort: {
1107
        const HostPort& host_port =
1108
7030
          *_ppop_instance.Lookup<HostPort>(field, opts);
1109
7030
        Local<Object> obj = Object::New(isolate);
1110
        Local<Value> host;
1111
7030
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1112

35150
            obj->Set(context, env->host_string(), host).IsNothing() ||
1113
7030
            obj->Set(context,
1114
                     env->port_string(),
1115
28120
                     Integer::New(isolate, host_port.port()))
1116
7030
                .IsNothing()) {
1117
          return;
1118
        }
1119
7030
        value = obj;
1120
7030
        break;
1121
      }
1122
      default:
1123
        UNREACHABLE();
1124
    }
1125
1019350
    CHECK(!value.IsEmpty());
1126
1127
1019350
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1128
1019350
    Local<Object> info = Object::New(isolate);
1129
    Local<Value> help_text;
1130
1019350
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1131
2038700
        !info->Set(context, env->help_text_string(), help_text)
1132

2038700
             .FromMaybe(false) ||
1133
2038700
        !info->Set(context,
1134
                   env->env_var_settings_string(),
1135
                   Integer::New(isolate,
1136
3058050
                                static_cast<int>(option_info.env_setting)))
1137

2038700
             .FromMaybe(false) ||
1138
2038700
        !info->Set(context,
1139
                   env->type_string(),
1140
3058050
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1141

2038700
             .FromMaybe(false) ||
1142
2038700
        !info->Set(context,
1143
                   env->default_is_true_string(),
1144
3058050
                   Boolean::New(isolate, option_info.default_is_true))
1145

2038700
             .FromMaybe(false) ||
1146

5096750
        info->Set(context, env->value_string(), value).IsNothing() ||
1147

3058050
        options->Set(context, name, info).IsEmpty()) {
1148
      return;
1149
    }
1150
  }
1151
1152
  Local<Value> aliases;
1153
14060
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1154
1155
7030
  if (aliases.As<Object>()
1156
14060
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1157
7030
          .IsNothing()) {
1158
    return;
1159
  }
1160
1161
7030
  Local<Object> ret = Object::New(isolate);
1162
28120
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1163

28120
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1164
    return;
1165
  }
1166
1167
14060
  args.GetReturnValue().Set(ret);
1168
}
1169
1170
6354
void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
1171
6354
  Environment* env = Environment::GetCurrent(args);
1172
6354
  if (!env->has_run_bootstrapping_code()) {
1173
    // No code because this is an assertion.
1174
    return env->ThrowError(
1175
        "Should not query options before bootstrapping is done");
1176
  }
1177
6354
  Isolate* isolate = args.GetIsolate();
1178
6354
  Local<Context> context = env->context();
1179
6354
  Local<Object> ret = Object::New(isolate);
1180
1181
12708
  if (ret->Set(context,
1182
           FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1183
19062
           Boolean::New(isolate, env->should_not_register_esm_loader()))
1184
6354
      .IsNothing()) return;
1185
1186
12708
  if (ret->Set(context,
1187
           FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"),
1188
19062
           Boolean::New(isolate, env->no_global_search_paths()))
1189
6354
      .IsNothing()) return;
1190
1191
12708
  args.GetReturnValue().Set(ret);
1192
}
1193
1194
792
void Initialize(Local<Object> target,
1195
                Local<Value> unused,
1196
                Local<Context> context,
1197
                void* priv) {
1198
792
  Environment* env = Environment::GetCurrent(context);
1199
792
  Isolate* isolate = env->isolate();
1200
792
  SetMethodNoSideEffect(context, target, "getCLIOptions", GetCLIOptions);
1201
792
  SetMethodNoSideEffect(
1202
      context, target, "getEmbedderOptions", GetEmbedderOptions);
1203
1204
792
  Local<Object> env_settings = Object::New(isolate);
1205
2376
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvvar);
1206
2376
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvvar);
1207
  target
1208
792
      ->Set(
1209
1584
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1210
      .Check();
1211
1212
792
  Local<Object> types = Object::New(isolate);
1213
2376
  NODE_DEFINE_CONSTANT(types, kNoOp);
1214
2376
  NODE_DEFINE_CONSTANT(types, kV8Option);
1215
2376
  NODE_DEFINE_CONSTANT(types, kBoolean);
1216
2376
  NODE_DEFINE_CONSTANT(types, kInteger);
1217
2376
  NODE_DEFINE_CONSTANT(types, kUInteger);
1218
2376
  NODE_DEFINE_CONSTANT(types, kString);
1219
2376
  NODE_DEFINE_CONSTANT(types, kHostPort);
1220
2376
  NODE_DEFINE_CONSTANT(types, kStringList);
1221
1584
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1222
      .Check();
1223
792
}
1224
1225
5618
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1226
5618
  registry->Register(GetCLIOptions);
1227
5618
  registry->Register(GetEmbedderOptions);
1228
5618
}
1229
}  // namespace options_parser
1230
1231
5689
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1232
5689
  HandleEnvOptions(env_options, [](const char* name) {
1233
22756
    std::string text;
1234

22756
    return credentials::SafeGetenv(name, &text) ? text : "";
1235
  });
1236
5689
}
1237
1238
5991
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1239
                      std::function<std::string(const char*)> opt_getter) {
1240
5991
  env_options->pending_deprecation =
1241
11982
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1242
1243
5991
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1244
1245
5991
  env_options->preserve_symlinks_main =
1246
11982
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1247
1248
5991
  if (env_options->redirect_warnings.empty())
1249
5991
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1250
5991
}
1251
1252
5869
std::vector<std::string> ParseNodeOptionsEnvVar(
1253
    const std::string& node_options, std::vector<std::string>* errors) {
1254
5869
  std::vector<std::string> env_argv;
1255
1256
5869
  bool is_in_string = false;
1257
5869
  bool will_start_new_arg = true;
1258
8525
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1259
2656
    char c = node_options.at(index);
1260
1261
    // Backslashes escape the following character
1262

2656
    if (c == '\\' && is_in_string) {
1263
      if (index + 1 == node_options.size()) {
1264
        errors->push_back("invalid value for NODE_OPTIONS "
1265
                          "(invalid escape)\n");
1266
        return env_argv;
1267
      } else {
1268
        c = node_options.at(++index);
1269
      }
1270

2656
    } else if (c == ' ' && !is_in_string) {
1271
32
      will_start_new_arg = true;
1272
32
      continue;
1273
2624
    } else if (c == '"') {
1274
4
      is_in_string = !is_in_string;
1275
4
      continue;
1276
    }
1277
1278
2620
    if (will_start_new_arg) {
1279
111
      env_argv.emplace_back(std::string(1, c));
1280
111
      will_start_new_arg = false;
1281
    } else {
1282
2509
      env_argv.back() += c;
1283
    }
1284
  }
1285
1286
5869
  if (is_in_string) {
1287
    errors->push_back("invalid value for NODE_OPTIONS "
1288
                      "(unterminated string)\n");
1289
  }
1290
5869
  return env_argv;
1291
}
1292
}  // namespace node
1293
1294
5689
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1295
5618
NODE_MODULE_EXTERNAL_REFERENCE(options,
1296
                               node::options_parser::RegisterExternalReferences)