GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 481 513 93.8 %
Date: 2022-11-09 04:21:35 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
11798
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
11798
  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
23596
      SplitString(inspect_publish_uid_string, ',');
54
11798
  inspect_publish_uid.console = false;
55
11798
  inspect_publish_uid.http = false;
56
35392
  for (const std::string& destination : destinations) {
57
23594
    if (destination == "stderr") {
58
11797
      inspect_publish_uid.console = true;
59
11797
    } else if (destination == "http") {
60
11797
      inspect_publish_uid.http = true;
61
    } else {
62
      errors->push_back("--inspect-publish-uid destination can be "
63
                        "stderr or http");
64
    }
65
  }
66
11798
}
67
68
11205
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors,
69
                                     std::vector<std::string>* argv) {
70
#if HAVE_OPENSSL
71

11205
  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
11205
  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
11207
  if (use_largepages != "off" &&
92

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

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

11798
  if (has_policy_integrity_string && experimental_policy_integrity.empty()) {
111
1
    errors->push_back("--policy-integrity cannot be empty");
112
  }
113
114
11798
  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

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

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

11798
  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
11798
  if (heap_snapshot_near_heap_limit < 0) {
139
    errors->push_back("--heapsnapshot-near-heap-limit must not be negative");
140
  }
141
142
11798
  if (test_runner) {
143
16
    if (syntax_check_only) {
144
1
      errors->push_back("either --test or --check can be used, not both");
145
    }
146
147
16
    if (has_eval_string) {
148
2
      errors->push_back("either --test or --eval can be used, not both");
149
    }
150
151
16
    if (force_repl) {
152
1
      errors->push_back("either --test or --interactive can be used, not both");
153
    }
154
155
16
    if (watch_mode) {
156
      // TODO(MoLow): Support (incremental?) watch mode within test runner
157
      errors->push_back("either --test or --watch can be used, not both");
158
    }
159
160
#ifndef ALLOW_ATTACHING_DEBUGGER_IN_TEST_RUNNER
161
    debug_options_.allow_attaching_debugger = false;
162
#endif
163
  }
164
165
11798
  if (watch_mode) {
166
11
    if (syntax_check_only) {
167
      errors->push_back("either --watch or --check can be used, not both");
168
11
    } else if (has_eval_string) {
169
      errors->push_back("either --watch or --eval can be used, not both");
170
11
    } else if (force_repl) {
171
      errors->push_back("either --watch or --interactive "
172
                        "can be used, not both");
173

11
    } 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
11798
  if (!cpu_prof) {
184
11787
    if (!cpu_prof_name.empty()) {
185
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
186
    }
187
11787
    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
11787
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
193
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
194
    }
195
  }
196
197


11798
  if (cpu_prof && cpu_prof_dir.empty() && !diagnostic_dir.empty()) {
198
1
      cpu_prof_dir = diagnostic_dir;
199
    }
200
201
11798
  if (!heap_prof) {
202
11787
    if (!heap_prof_name.empty()) {
203
1
      errors->push_back("--heap-prof-name must be used with --heap-prof");
204
    }
205
11787
    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
11787
    if (heap_prof_interval != kDefaultHeapProfInterval) {
211
1
      errors->push_back("--heap-prof-interval must be used with --heap-prof");
212
    }
213
  }
214
215


11798
  if (heap_prof && heap_prof_dir.empty() && !diagnostic_dir.empty()) {
216
1
    heap_prof_dir = diagnostic_dir;
217
  }
218
219
11798
  debug_options_.CheckOptions(errors, argv);
220
#endif  // HAVE_INSPECTOR
221
11798
}
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
5672
  explicit EnvironmentOptionsParser(const DebugOptionsParser& dop)
234
5672
    : EnvironmentOptionsParser() {
235
5672
    Insert(dop, &EnvironmentOptions::get_debug_options);
236
5672
  }
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
593
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
593
  _piop_instance.Parse(
278
    args, exec_args, v8_args, options, required_env_settings, errors);
279
593
}
280
281
template <>
282
11205
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
11205
  _ppop_instance.Parse(
288
    args, exec_args, v8_args, options, required_env_settings, errors);
289
11205
}
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
5672
DebugOptionsParser::DebugOptionsParser() {
296
5672
  AddOption("--inspect-port",
297
            "set host:port for inspector",
298
            &DebugOptions::host_port,
299
            kAllowedInEnvvar);
300
5672
  AddAlias("--debug-port", "--inspect-port");
301
302
5672
  AddOption("--inspect",
303
            "activate inspector on host:port (default: 127.0.0.1:9229)",
304
            &DebugOptions::inspector_enabled,
305
            kAllowedInEnvvar);
306
17016
  AddAlias("--inspect=", { "--inspect-port", "--inspect" });
307
308
5672
  AddOption("--debug", "", &DebugOptions::deprecated_debug);
309
5672
  AddAlias("--debug=", "--debug");
310
5672
  AddOption("--debug-brk", "", &DebugOptions::deprecated_debug);
311
5672
  AddAlias("--debug-brk=", "--debug-brk");
312
313
5672
  AddOption("--inspect-brk",
314
            "activate inspector on host:port and break at start of user script",
315
            &DebugOptions::break_first_line,
316
            kAllowedInEnvvar);
317
5672
  Implies("--inspect-brk", "--inspect");
318
17016
  AddAlias("--inspect-brk=", { "--inspect-port", "--inspect-brk" });
319
320
5672
  AddOption("--inspect-brk-node", "", &DebugOptions::break_node_first_line);
321
5672
  Implies("--inspect-brk-node", "--inspect");
322
17016
  AddAlias("--inspect-brk-node=", { "--inspect-port", "--inspect-brk-node" });
323
324
5672
  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
5672
}
330
331
5672
EnvironmentOptionsParser::EnvironmentOptionsParser() {
332
5672
  AddOption("--conditions",
333
            "additional user conditions for conditional exports and imports",
334
            &EnvironmentOptions::conditions,
335
            kAllowedInEnvvar);
336
5672
  AddAlias("-C", "--conditions");
337
5672
  AddOption("--diagnostic-dir",
338
            "set dir for all output files"
339
            " (default: current working directory)",
340
            &EnvironmentOptions::diagnostic_dir,
341
            kAllowedInEnvvar);
342
5672
  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
5672
  AddOption("--enable-source-maps",
350
            "Source Map V3 support for stack traces",
351
            &EnvironmentOptions::enable_source_maps,
352
            kAllowedInEnvvar);
353
5672
  AddOption("--experimental-abortcontroller", "", NoOp{}, kAllowedInEnvvar);
354
5672
  AddOption("--experimental-fetch",
355
            "experimental Fetch API",
356
            &EnvironmentOptions::experimental_fetch,
357
            kAllowedInEnvvar,
358
            true);
359
5672
  AddOption("--experimental-global-customevent",
360
            "expose experimental CustomEvent on the global scope",
361
            &EnvironmentOptions::experimental_global_customevent,
362
            kAllowedInEnvvar,
363
            true);
364
5672
  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
5672
  AddOption("--experimental-json-modules", "", NoOp{}, kAllowedInEnvvar);
370
5672
  AddOption("--experimental-loader",
371
            "use the specified module as a custom loader",
372
            &EnvironmentOptions::userland_loaders,
373
            kAllowedInEnvvar);
374
5672
  AddAlias("--loader", "--experimental-loader");
375
5672
  AddOption("--experimental-modules", "", NoOp{}, kAllowedInEnvvar);
376
5672
  AddOption("--experimental-network-imports",
377
            "experimental https: support for the ES Module loader",
378
            &EnvironmentOptions::experimental_https_modules,
379
            kAllowedInEnvvar);
380
5672
  AddOption("--experimental-wasm-modules",
381
            "experimental ES Module support for webassembly modules",
382
            &EnvironmentOptions::experimental_wasm_modules,
383
            kAllowedInEnvvar);
384
5672
  AddOption("--experimental-import-meta-resolve",
385
            "experimental ES Module import.meta.resolve() support",
386
            &EnvironmentOptions::experimental_import_meta_resolve,
387
            kAllowedInEnvvar);
388
5672
  AddOption("--experimental-policy",
389
            "use the specified file as a "
390
            "security policy",
391
            &EnvironmentOptions::experimental_policy,
392
            kAllowedInEnvvar);
393
5672
  AddOption("[has_policy_integrity_string]",
394
            "",
395
            &EnvironmentOptions::has_policy_integrity_string);
396
5672
  AddOption("--policy-integrity",
397
            "ensure the security policy contents match "
398
            "the specified integrity",
399
            &EnvironmentOptions::experimental_policy_integrity,
400
            kAllowedInEnvvar);
401
5672
  Implies("--policy-integrity", "[has_policy_integrity_string]");
402
5672
  AddOption("--experimental-repl-await",
403
            "experimental await keyword support in REPL",
404
            &EnvironmentOptions::experimental_repl_await,
405
            kAllowedInEnvvar,
406
            true);
407
5672
  AddOption("--experimental-vm-modules",
408
            "experimental ES Module support in vm module",
409
            &EnvironmentOptions::experimental_vm_modules,
410
            kAllowedInEnvvar);
411
5672
  AddOption("--experimental-worker", "", NoOp{}, kAllowedInEnvvar);
412
5672
  AddOption("--experimental-report", "", NoOp{}, kAllowedInEnvvar);
413
5672
  AddOption("--experimental-wasi-unstable-preview1",
414
            "experimental WASI support",
415
            &EnvironmentOptions::experimental_wasi,
416
            kAllowedInEnvvar);
417
5672
  AddOption("--expose-internals", "", &EnvironmentOptions::expose_internals);
418
5672
  AddOption("--frozen-intrinsics",
419
            "experimental frozen intrinsics support",
420
            &EnvironmentOptions::frozen_intrinsics,
421
            kAllowedInEnvvar);
422
5672
  AddOption("--heapsnapshot-signal",
423
            "Generate heap snapshot on specified signal",
424
            &EnvironmentOptions::heap_snapshot_signal,
425
            kAllowedInEnvvar);
426
5672
  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
5672
  AddOption("--http-parser", "", NoOp{}, kAllowedInEnvvar);
433
5672
  AddOption("--insecure-http-parser",
434
            "use an insecure HTTP parser that accepts invalid HTTP headers",
435
            &EnvironmentOptions::insecure_http_parser,
436
            kAllowedInEnvvar);
437
5672
  AddOption("--input-type",
438
            "set module type for string input",
439
            &EnvironmentOptions::module_type,
440
            kAllowedInEnvvar);
441
5672
  AddOption(
442
      "--experimental-specifier-resolution", "", NoOp{}, kAllowedInEnvvar);
443
5672
  AddAlias("--es-module-specifier-resolution",
444
           "--experimental-specifier-resolution");
445
5672
  AddOption("--deprecation",
446
            "silence deprecation warnings",
447
            &EnvironmentOptions::deprecation,
448
            kAllowedInEnvvar,
449
            true);
450
5672
  AddOption("--force-async-hooks-checks",
451
            "disable checks for async_hooks",
452
            &EnvironmentOptions::force_async_hooks_checks,
453
            kAllowedInEnvvar,
454
            true);
455
5672
  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
5672
  AddOption("--addons",
462
            "disable loading native addons",
463
            &EnvironmentOptions::allow_native_addons,
464
            kAllowedInEnvvar,
465
            true);
466
5672
  AddOption("--global-search-paths",
467
            "disable global module search paths",
468
            &EnvironmentOptions::global_search_paths,
469
            kAllowedInEnvvar,
470
            true);
471
5672
  AddOption("--warnings",
472
            "silence all process warnings",
473
            &EnvironmentOptions::warnings,
474
            kAllowedInEnvvar,
475
            true);
476
5672
  AddOption("--force-context-aware",
477
            "disable loading non-context-aware addons",
478
            &EnvironmentOptions::force_context_aware,
479
            kAllowedInEnvvar);
480
5672
  AddOption("--pending-deprecation",
481
            "emit pending deprecation warnings",
482
            &EnvironmentOptions::pending_deprecation,
483
            kAllowedInEnvvar);
484
5672
  AddOption("--preserve-symlinks",
485
            "preserve symbolic links when resolving",
486
            &EnvironmentOptions::preserve_symlinks,
487
            kAllowedInEnvvar);
488
5672
  AddOption("--preserve-symlinks-main",
489
            "preserve symbolic links when resolving the main module",
490
            &EnvironmentOptions::preserve_symlinks_main,
491
            kAllowedInEnvvar);
492
5672
  AddOption("--prof",
493
            "Generate V8 profiler output.",
494
            V8Option{});
495
5672
  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
17016
  AddAlias("--prof-process", { "--prof-process", "--" });
500
#if HAVE_INSPECTOR
501
5672
  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
5672
  AddOption("--cpu-prof-name",
507
            "specified file name of the V8 CPU profile generated with "
508
            "--cpu-prof",
509
            &EnvironmentOptions::cpu_prof_name);
510
5672
  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
5672
  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
5672
  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
5672
  AddOption("--heap-prof-name",
525
            "specified file name of the V8 heap profile generated with "
526
            "--heap-prof",
527
            &EnvironmentOptions::heap_prof_name);
528
5672
  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
5672
  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
5672
  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
5672
  AddOption("--redirect-warnings",
542
            "write warnings to file instead of stderr",
543
            &EnvironmentOptions::redirect_warnings,
544
            kAllowedInEnvvar);
545
5672
  AddOption("--test",
546
            "launch test runner on startup",
547
            &EnvironmentOptions::test_runner);
548
5672
  AddOption("--test-name-pattern",
549
            "run tests whose name matches this regular expression",
550
            &EnvironmentOptions::test_name_pattern);
551
5672
  AddOption("--test-only",
552
            "run tests with 'only' option set",
553
            &EnvironmentOptions::test_only,
554
            kAllowedInEnvvar);
555
5672
  AddOption("--test-udp-no-try-send", "",  // For testing only.
556
            &EnvironmentOptions::test_udp_no_try_send);
557
5672
  AddOption("--throw-deprecation",
558
            "throw an exception on deprecations",
559
            &EnvironmentOptions::throw_deprecation,
560
            kAllowedInEnvvar);
561
5672
  AddOption("--trace-atomics-wait",
562
            "(deprecated) trace Atomics.wait() operations",
563
            &EnvironmentOptions::trace_atomics_wait,
564
            kAllowedInEnvvar);
565
5672
  AddOption("--trace-deprecation",
566
            "show stack traces on deprecations",
567
            &EnvironmentOptions::trace_deprecation,
568
            kAllowedInEnvvar);
569
5672
  AddOption("--trace-exit",
570
            "show stack trace when an environment exits",
571
            &EnvironmentOptions::trace_exit,
572
            kAllowedInEnvvar);
573
5672
  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
5672
  AddOption("--trace-tls",
579
            "prints TLS packet trace information to stderr",
580
            &EnvironmentOptions::trace_tls,
581
            kAllowedInEnvvar);
582
5672
  AddOption("--trace-uncaught",
583
            "show stack traces for the `throw` behind uncaught exceptions",
584
            &EnvironmentOptions::trace_uncaught,
585
            kAllowedInEnvvar);
586
5672
  AddOption("--trace-warnings",
587
            "show stack traces on process warnings",
588
            &EnvironmentOptions::trace_warnings,
589
            kAllowedInEnvvar);
590
5672
  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
5672
  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
5672
  AddOption("--verify-base-objects",
605
            "", /* undocumented, only for debugging */
606
            &EnvironmentOptions::verify_base_objects,
607
            kAllowedInEnvvar);
608
5672
  AddOption("--watch",
609
            "run in watch mode",
610
            &EnvironmentOptions::watch_mode,
611
            kAllowedInEnvvar);
612
5672
  AddOption("--watch-path",
613
            "path to watch",
614
            &EnvironmentOptions::watch_mode_paths,
615
            kAllowedInEnvvar);
616
5672
  Implies("--watch-path", "--watch");
617
5672
  AddOption("--check",
618
            "syntax check script without executing",
619
            &EnvironmentOptions::syntax_check_only);
620
5672
  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
5672
  AddOption("[has_eval_string]", "", &EnvironmentOptions::has_eval_string);
628
5672
  AddOption("--eval", "evaluate script", &EnvironmentOptions::eval_string);
629
5672
  Implies("--eval", "[has_eval_string]");
630
5672
  AddOption("--print",
631
            "evaluate script and print result",
632
            &EnvironmentOptions::print_eval);
633
5672
  AddAlias("-e", "--eval");
634
5672
  AddAlias("--print <arg>", "-pe");
635
17016
  AddAlias("-pe", { "--print", "--eval" });
636
5672
  AddAlias("-p", "--print");
637
5672
  AddOption("--require",
638
            "CommonJS module to preload (option can be repeated)",
639
            &EnvironmentOptions::preload_cjs_modules,
640
            kAllowedInEnvvar);
641
5672
  AddAlias("-r", "--require");
642
5672
  AddOption("--import",
643
            "ES module to preload (option can be repeated)",
644
            &EnvironmentOptions::preload_esm_modules,
645
            kAllowedInEnvvar);
646
5672
  AddOption("--interactive",
647
            "always enter the REPL even if stdin does not appear "
648
            "to be a terminal",
649
            &EnvironmentOptions::force_repl);
650
5672
  AddAlias("-i", "--interactive");
651
652
5672
  AddOption("--update-assert-snapshot",
653
            "update assert snapshot files",
654
            &EnvironmentOptions::update_assert_snapshot,
655
            kAllowedInEnvvar);
656
657
5672
  AddOption("--napi-modules", "", NoOp{}, kAllowedInEnvvar);
658
659
5672
  AddOption("--tls-keylog",
660
            "log TLS decryption keys to named file for traffic analysis",
661
            &EnvironmentOptions::tls_keylog,
662
            kAllowedInEnvvar);
663
664
5672
  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
5672
  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
5672
  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
5672
  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
5672
  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
5672
  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
5672
}
693
694
5672
PerIsolateOptionsParser::PerIsolateOptionsParser(
695
5672
  const EnvironmentOptionsParser& eop) {
696
5672
  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
5672
  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
5672
  AddOption("--interpreted-frames-native-stack",
708
            "help system profilers to translate JavaScript interpreted frames",
709
            V8Option{},
710
            kAllowedInEnvvar);
711
5672
  AddOption("--max-old-space-size", "", V8Option{}, kAllowedInEnvvar);
712
5672
  AddOption("--perf-basic-prof", "", V8Option{}, kAllowedInEnvvar);
713
5672
  AddOption(
714
      "--perf-basic-prof-only-functions", "", V8Option{}, kAllowedInEnvvar);
715
5672
  AddOption("--perf-prof", "", V8Option{}, kAllowedInEnvvar);
716
5672
  AddOption("--perf-prof-unwinding-info", "", V8Option{}, kAllowedInEnvvar);
717
5672
  AddOption("--stack-trace-limit", "", V8Option{}, kAllowedInEnvvar);
718
5672
  AddOption("--disallow-code-generation-from-strings",
719
            "disallow eval and friends",
720
            V8Option{},
721
            kAllowedInEnvvar);
722
5672
  AddOption("--huge-max-old-generation-size",
723
            "increase default maximum heap size on machines with 16GB memory "
724
            "or more",
725
            V8Option{},
726
            kAllowedInEnvvar);
727
5672
  AddOption("--jitless",
728
            "disable runtime allocation of executable memory",
729
            V8Option{},
730
            kAllowedInEnvvar);
731
5672
  AddOption("--report-uncaught-exception",
732
            "generate diagnostic report on uncaught exceptions",
733
            &PerIsolateOptions::report_uncaught_exception,
734
            kAllowedInEnvvar);
735
5672
  AddOption("--report-on-signal",
736
            "generate diagnostic report upon receiving signals",
737
            &PerIsolateOptions::report_on_signal,
738
            kAllowedInEnvvar);
739
5672
  AddOption("--report-signal",
740
            "causes diagnostic report to be produced on provided signal,"
741
            " unsupported in Windows. (default: SIGUSR2)",
742
            &PerIsolateOptions::report_signal,
743
            kAllowedInEnvvar);
744
5672
  Implies("--report-signal", "--report-on-signal");
745
746
5672
  AddOption("--experimental-top-level-await", "", NoOp{}, kAllowedInEnvvar);
747
748
5672
  AddOption("--experimental-shadow-realm",
749
            "",
750
            &PerIsolateOptions::experimental_shadow_realm,
751
            kAllowedInEnvvar);
752
5672
  AddOption("--harmony-shadow-realm", "", V8Option{});
753
5672
  Implies("--experimental-shadow-realm", "--harmony-shadow-realm");
754
5672
  Implies("--harmony-shadow-realm", "--experimental-shadow-realm");
755
5672
  ImpliesNot("--no-harmony-shadow-realm", "--experimental-shadow-realm");
756
757
5672
  Insert(eop, &PerIsolateOptions::get_per_env_options);
758
5672
}
759
760
5672
PerProcessOptionsParser::PerProcessOptionsParser(
761
5672
  const PerIsolateOptionsParser& iop) {
762
5672
  AddOption("--title",
763
            "the process title to use on startup",
764
            &PerProcessOptions::title,
765
            kAllowedInEnvvar);
766
5672
  AddOption("--trace-event-categories",
767
            "comma separated list of trace event categories to record",
768
            &PerProcessOptions::trace_event_categories,
769
            kAllowedInEnvvar);
770
5672
  AddOption("--trace-event-file-pattern",
771
            "Template string specifying the filepath for the trace-events "
772
            "data, it supports ${rotation} and ${pid}.",
773
            &PerProcessOptions::trace_event_file_pattern,
774
            kAllowedInEnvvar);
775
17016
  AddAlias("--trace-events-enabled", {
776
11344
    "--trace-event-categories", "v8,node,node.async_hooks" });
777
5672
  AddOption("--v8-pool-size",
778
            "set V8's thread pool size",
779
            &PerProcessOptions::v8_thread_pool_size,
780
            kAllowedInEnvvar);
781
5672
  AddOption("--zero-fill-buffers",
782
            "automatically zero-fill all newly allocated Buffer and "
783
            "SlowBuffer instances",
784
            &PerProcessOptions::zero_fill_all_buffers,
785
            kAllowedInEnvvar);
786
5672
  AddOption("--debug-arraybuffer-allocations",
787
            "", /* undocumented, only for debugging */
788
            &PerProcessOptions::debug_arraybuffer_allocations,
789
            kAllowedInEnvvar);
790
5672
  AddOption("--disable-proto",
791
            "disable Object.prototype.__proto__",
792
            &PerProcessOptions::disable_proto,
793
            kAllowedInEnvvar);
794
5672
  AddOption("--build-snapshot",
795
            "Generate a snapshot blob when the process exits."
796
            " Currently only supported in the node_mksnapshot binary.",
797
            &PerProcessOptions::build_snapshot,
798
            kDisallowedInEnvvar);
799
5672
  AddOption("--node-snapshot",
800
            "",  // It's a debug-only option.
801
            &PerProcessOptions::node_snapshot,
802
            kAllowedInEnvvar);
803
5672
  AddOption("--snapshot-blob",
804
            "Path to the snapshot blob that's either the result of snapshot"
805
            "building, or the blob that is used to restore the application "
806
            "state",
807
            &PerProcessOptions::snapshot_blob,
808
            kAllowedInEnvvar);
809
810
  // 12.x renamed this inadvertently, so alias it for consistency within the
811
  // release line, while using the original name for consistency with older
812
  // release lines.
813
5672
  AddOption("--security-revert", "", &PerProcessOptions::security_reverts);
814
5672
  AddAlias("--security-reverts", "--security-revert");
815
5672
  AddOption("--completion-bash",
816
            "print source-able bash completion script",
817
            &PerProcessOptions::print_bash_completion);
818
5672
  AddOption("--help",
819
            "print node command line options",
820
            &PerProcessOptions::print_help);
821
5672
  AddAlias("-h", "--help");
822
5672
  AddOption(
823
      "--version", "print Node.js version", &PerProcessOptions::print_version);
824
5672
  AddAlias("-v", "--version");
825
5672
  AddOption("--v8-options",
826
            "print V8 command line options",
827
            &PerProcessOptions::print_v8_help);
828
5672
  AddOption("--report-compact",
829
            "output compact single-line JSON",
830
            &PerProcessOptions::report_compact,
831
            kAllowedInEnvvar);
832
5672
  AddOption("--report-dir",
833
            "define custom report pathname."
834
            " (default: current working directory)",
835
            &PerProcessOptions::report_directory,
836
            kAllowedInEnvvar);
837
5672
  AddAlias("--report-directory", "--report-dir");
838
5672
  AddOption("--report-filename",
839
            "define custom report file name."
840
            " (default: YYYYMMDD.HHMMSS.PID.SEQUENCE#.txt)",
841
            &PerProcessOptions::report_filename,
842
            kAllowedInEnvvar);
843
5672
  AddOption("--report-on-fatalerror",
844
            "generate diagnostic report on fatal (internal) errors",
845
            &PerProcessOptions::report_on_fatalerror,
846
            kAllowedInEnvvar);
847
848
#ifdef NODE_HAVE_I18N_SUPPORT
849
5672
  AddOption("--icu-data-dir",
850
            "set ICU data load path to dir (overrides NODE_ICU_DATA)"
851
#ifndef NODE_HAVE_SMALL_ICU
852
            " (note: linked-in ICU data is present)"
853
#endif
854
            ,
855
            &PerProcessOptions::icu_data_dir,
856
            kAllowedInEnvvar);
857
#endif
858
859
#if HAVE_OPENSSL
860
5672
  AddOption("--openssl-config",
861
            "load OpenSSL configuration from the specified file "
862
            "(overrides OPENSSL_CONF)",
863
            &PerProcessOptions::openssl_config,
864
            kAllowedInEnvvar);
865
5672
  AddOption("--tls-cipher-list",
866
            "use an alternative default TLS cipher list",
867
            &PerProcessOptions::tls_cipher_list,
868
            kAllowedInEnvvar);
869
5672
  AddOption("--use-openssl-ca",
870
            "use OpenSSL's default CA store"
871
#if defined(NODE_OPENSSL_CERT_STORE)
872
            " (default)"
873
#endif
874
            ,
875
            &PerProcessOptions::use_openssl_ca,
876
            kAllowedInEnvvar);
877
5672
  AddOption("--use-bundled-ca",
878
            "use bundled CA store"
879
#if !defined(NODE_OPENSSL_CERT_STORE)
880
            " (default)"
881
#endif
882
            ,
883
            &PerProcessOptions::use_bundled_ca,
884
            kAllowedInEnvvar);
885
  // Similar to [has_eval_string] above, except that the separation between
886
  // this and use_openssl_ca only exists for option validation after parsing.
887
  // This is not ideal.
888
5672
  AddOption("[ssl_openssl_cert_store]",
889
            "",
890
            &PerProcessOptions::ssl_openssl_cert_store);
891
5672
  Implies("--use-openssl-ca", "[ssl_openssl_cert_store]");
892
5672
  ImpliesNot("--use-bundled-ca", "[ssl_openssl_cert_store]");
893
5672
  AddOption("--enable-fips",
894
            "enable FIPS crypto at startup",
895
            &PerProcessOptions::enable_fips_crypto,
896
            kAllowedInEnvvar);
897
5672
  AddOption("--force-fips",
898
            "force FIPS crypto (cannot be disabled)",
899
            &PerProcessOptions::force_fips_crypto,
900
            kAllowedInEnvvar);
901
5672
  AddOption("--secure-heap",
902
            "total size of the OpenSSL secure heap",
903
            &PerProcessOptions::secure_heap,
904
            kAllowedInEnvvar);
905
5672
  AddOption("--secure-heap-min",
906
            "minimum allocation size from the OpenSSL secure heap",
907
            &PerProcessOptions::secure_heap_min,
908
            kAllowedInEnvvar);
909
#endif  // HAVE_OPENSSL
910
#if OPENSSL_VERSION_MAJOR >= 3
911
5672
  AddOption("--openssl-legacy-provider",
912
            "enable OpenSSL 3.0 legacy provider",
913
            &PerProcessOptions::openssl_legacy_provider,
914
            kAllowedInEnvvar);
915
5672
  AddOption("--openssl-shared-config",
916
            "enable OpenSSL shared configuration",
917
            &PerProcessOptions::openssl_shared_config,
918
            kAllowedInEnvvar);
919
920
#endif  // OPENSSL_VERSION_MAJOR
921
5672
  AddOption("--use-largepages",
922
            "Map the Node.js static code to large pages. Options are "
923
            "'off' (the default value, meaning do not map), "
924
            "'on' (map and ignore failure, reporting it to stderr), "
925
            "or 'silent' (map and silently ignore failure)",
926
            &PerProcessOptions::use_largepages,
927
            kAllowedInEnvvar);
928
929
5672
  AddOption("--trace-sigint",
930
            "enable printing JavaScript stacktrace on SIGINT",
931
            &PerProcessOptions::trace_sigint,
932
            kAllowedInEnvvar);
933
934
5672
  Insert(iop, &PerProcessOptions::get_per_isolate_options);
935
936
5672
  AddOption("--node-memory-debug",
937
            "Run with extra debug checks for memory leaks in Node.js itself",
938
            NoOp{},
939
            kAllowedInEnvvar);
940
5672
  Implies("--node-memory-debug", "--debug-arraybuffer-allocations");
941
5672
  Implies("--node-memory-debug", "--verify-base-objects");
942
5672
}
943
944
168
inline std::string RemoveBrackets(const std::string& host) {
945


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

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

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

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


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

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

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

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

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

2017440
             .FromMaybe(false) ||
1145

5043600
        info->Set(context, env->value_string(), value).IsNothing() ||
1146

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

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

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

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

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