GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 481 514 93.6 %
Date: 2022-09-21 04:23:13 Branches: 218 282 77.3 %

Line Branch Exec Source
1
#include "node_options.h"  // NOLINT(build/include_inline)
2
#include "node_options-inl.h"
3
4
#include "env-inl.h"
5
#include "node_binding.h"
6
#include "node_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
11637
void DebugOptions::CheckOptions(std::vector<std::string>* errors) {
38
#if !NODE_USE_V8_PLATFORM && !HAVE_INSPECTOR
39
  if (inspector_enabled) {
40
    errors->push_back("Inspector is not available when Node is compiled "
41
                      "--without-v8-platform and --without-inspector.");
42
  }
43
#endif
44
45
11637
  if (deprecated_debug) {
46
4
    errors->push_back("[DEP0062]: `node --debug` and `node --debug-brk` "
47
                      "are invalid. Please use `node --inspect` and "
48
                      "`node --inspect-brk` instead.");
49
  }
50
51
  std::vector<std::string> destinations =
52
23274
      SplitString(inspect_publish_uid_string, ',');
53
11637
  inspect_publish_uid.console = false;
54
11637
  inspect_publish_uid.http = false;
55
34909
  for (const std::string& destination : destinations) {
56
23272
    if (destination == "stderr") {
57
11636
      inspect_publish_uid.console = true;
58
11636
    } else if (destination == "http") {
59
11636
      inspect_publish_uid.http = true;
60
    } else {
61
      errors->push_back("--inspect-publish-uid destination can be "
62
                        "stderr or http");
63
    }
64
  }
65
11637
}
66
67
11056
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
68
#if HAVE_OPENSSL
69

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

11058
      use_largepages != "on" &&
91
1
      use_largepages != "silent") {
92
1
    errors->push_back("invalid value for --use-largepages");
93
  }
94
11056
  per_isolate->CheckOptions(errors);
95
11056
}
96
97
11637
void PerIsolateOptions::CheckOptions(std::vector<std::string>* errors) {
98
11637
  per_env->CheckOptions(errors);
99
11637
}
100
101
11637
void EnvironmentOptions::CheckOptions(std::vector<std::string>* errors) {
102

11637
  if (has_policy_integrity_string && experimental_policy.empty()) {
103
    errors->push_back("--policy-integrity requires "
104
                      "--experimental-policy be enabled");
105
  }
106

11637
  if (has_policy_integrity_string && experimental_policy_integrity.empty()) {
107
1
    errors->push_back("--policy-integrity cannot be empty");
108
  }
109
110
11637
  if (!module_type.empty()) {
111

61
    if (module_type != "commonjs" && module_type != "module") {
112
      errors->push_back("--input-type must be \"module\" or \"commonjs\"");
113
    }
114
  }
115
116
11637
  if (!experimental_specifier_resolution.empty()) {
117

9
    if (experimental_specifier_resolution != "node" &&
118
        experimental_specifier_resolution != "explicit") {
119
      errors->push_back(
120
        "invalid value for --experimental-specifier-resolution");
121
    }
122
  }
123
124

11637
  if (syntax_check_only && has_eval_string) {
125
4
    errors->push_back("either --check or --eval can be used, not both");
126
  }
127
128
11657
  if (!unhandled_rejections.empty() &&
129
39
      unhandled_rejections != "warn-with-error-code" &&
130
36
      unhandled_rejections != "throw" &&
131
32
      unhandled_rejections != "strict" &&
132

11672
      unhandled_rejections != "warn" &&
133
10
      unhandled_rejections != "none") {
134
1
    errors->push_back("invalid value for --unhandled-rejections");
135
  }
136
137

11637
  if (tls_min_v1_3 && tls_max_v1_2) {
138
1
    errors->push_back("either --tls-min-v1.3 or --tls-max-v1.2 can be "
139
                      "used, not both");
140
  }
141
142
11637
  if (heap_snapshot_near_heap_limit < 0) {
143
    errors->push_back("--heapsnapshot-near-heap-limit must not be negative");
144
  }
145
146
11637
  if (test_runner) {
147
14
    if (syntax_check_only) {
148
1
      errors->push_back("either --test or --check can be used, not both");
149
    }
150
151
14
    if (has_eval_string) {
152
2
      errors->push_back("either --test or --eval can be used, not both");
153
    }
154
155
14
    if (force_repl) {
156
1
      errors->push_back("either --test or --interactive can be used, not both");
157
    }
158
159
14
    if (watch_mode) {
160
      // TODO(MoLow): Support (incremental?) watch mode within test runner
161
      errors->push_back("either --test or --watch can be used, not both");
162
    }
163
164
#ifndef ALLOW_ATTACHING_DEBUGGER_IN_TEST_RUNNER
165
    debug_options_.allow_attaching_debugger = false;
166
#endif
167
  }
168
169
11637
  if (watch_mode) {
170
11
    if (syntax_check_only) {
171
      errors->push_back("either --watch or --check can be used, not both");
172
    }
173
174
11
    if (has_eval_string) {
175
      errors->push_back("either --watch or --eval can be used, not both");
176
    }
177
178
11
    if (force_repl) {
179
      errors->push_back("either --watch or --interactive "
180
                        "can be used, not both");
181
    }
182
183
#ifndef ALLOW_ATTACHING_DEBUGGER_IN_WATCH_MODE
184
    debug_options_.allow_attaching_debugger = false;
185
#endif
186
  }
187
188
#if HAVE_INSPECTOR
189
11637
  if (!cpu_prof) {
190
11626
    if (!cpu_prof_name.empty()) {
191
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
192
    }
193
11626
    if (!cpu_prof_dir.empty()) {
194
1
      errors->push_back("--cpu-prof-dir must be used with --cpu-prof");
195
    }
196
    // We can't catch the case where the value passed is the default value,
197
    // then the option just becomes a noop which is fine.
198
11626
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
199
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
200
    }
201
  }
202
203


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


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


165
  if (!host.empty() && host.front() == '[' && host.back() == ']')
955
8
    return host.substr(1, host.size() - 2);
956
  else
957
157
    return host;
958
}
959
960
145
inline int ParseAndValidatePort(const std::string& port,
961
                                std::vector<std::string>* errors) {
962
  char* endptr;
963
145
  errno = 0;
964
  const unsigned long result =                 // NOLINT(runtime/int)
965
145
    strtoul(port.c_str(), &endptr, 10);
966

145
  if (errno != 0 || *endptr != '\0'||
967

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

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


990990
    switch (option_info.type) {
1075
152460
      case kNoOp:
1076
      case kV8Option:
1077
        // Special case for --abort-on-uncaught-exception which is also
1078
        // respected by Node.js internals
1079
152460
        if (item.first == "--abort-on-uncaught-exception") {
1080
6930
          value = Boolean::New(
1081
6930
            isolate, original_per_env->abort_on_uncaught_exception);
1082
        } else {
1083
145530
          value = Undefined(isolate);
1084
        }
1085
152460
        break;
1086
547470
      case kBoolean:
1087
1094940
        value = Boolean::New(isolate,
1088
1094940
                             *_ppop_instance.Lookup<bool>(field, opts));
1089
547470
        break;
1090
27720
      case kInteger:
1091
55440
        value = Number::New(
1092
            isolate,
1093
55440
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1094
27720
        break;
1095
20790
      case kUInteger:
1096
41580
        value = Number::New(
1097
            isolate,
1098
41580
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1099
20790
        break;
1100
194040
      case kString:
1101
388080
        if (!ToV8Value(context,
1102
388080
                       *_ppop_instance.Lookup<std::string>(field, opts))
1103
194040
                 .ToLocal(&value)) {
1104
          return;
1105
        }
1106
194040
        break;
1107
41580
      case kStringList:
1108
83160
        if (!ToV8Value(context,
1109
83160
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1110
41580
                 .ToLocal(&value)) {
1111
          return;
1112
        }
1113
41580
        break;
1114
6930
      case kHostPort: {
1115
        const HostPort& host_port =
1116
6930
          *_ppop_instance.Lookup<HostPort>(field, opts);
1117
6930
        Local<Object> obj = Object::New(isolate);
1118
        Local<Value> host;
1119
6930
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1120

34650
            obj->Set(context, env->host_string(), host).IsNothing() ||
1121
6930
            obj->Set(context,
1122
                     env->port_string(),
1123
27720
                     Integer::New(isolate, host_port.port()))
1124
6930
                .IsNothing()) {
1125
          return;
1126
        }
1127
6930
        value = obj;
1128
6930
        break;
1129
      }
1130
      default:
1131
        UNREACHABLE();
1132
    }
1133
990990
    CHECK(!value.IsEmpty());
1134
1135
990990
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1136
990990
    Local<Object> info = Object::New(isolate);
1137
    Local<Value> help_text;
1138
990990
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1139
1981980
        !info->Set(context, env->help_text_string(), help_text)
1140

1981980
             .FromMaybe(false) ||
1141
1981980
        !info->Set(context,
1142
                   env->env_var_settings_string(),
1143
                   Integer::New(isolate,
1144
2972970
                                static_cast<int>(option_info.env_setting)))
1145

1981980
             .FromMaybe(false) ||
1146
1981980
        !info->Set(context,
1147
                   env->type_string(),
1148
2972970
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1149

1981980
             .FromMaybe(false) ||
1150
1981980
        !info->Set(context,
1151
                   env->default_is_true_string(),
1152
2972970
                   Boolean::New(isolate, option_info.default_is_true))
1153

1981980
             .FromMaybe(false) ||
1154

4954950
        info->Set(context, env->value_string(), value).IsNothing() ||
1155

2972970
        options->Set(context, name, info).IsEmpty()) {
1156
      return;
1157
    }
1158
  }
1159
1160
  Local<Value> aliases;
1161
13860
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1162
1163
6930
  if (aliases.As<Object>()
1164
13860
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1165
6930
          .IsNothing()) {
1166
    return;
1167
  }
1168
1169
6930
  Local<Object> ret = Object::New(isolate);
1170
27720
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1171

27720
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1172
    return;
1173
  }
1174
1175
13860
  args.GetReturnValue().Set(ret);
1176
}
1177
1178
6256
void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
1179
6256
  Environment* env = Environment::GetCurrent(args);
1180
6256
  if (!env->has_run_bootstrapping_code()) {
1181
    // No code because this is an assertion.
1182
    return env->ThrowError(
1183
        "Should not query options before bootstrapping is done");
1184
  }
1185
6256
  Isolate* isolate = args.GetIsolate();
1186
6256
  Local<Context> context = env->context();
1187
6256
  Local<Object> ret = Object::New(isolate);
1188
1189
12512
  if (ret->Set(context,
1190
           FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1191
18768
           Boolean::New(isolate, env->should_not_register_esm_loader()))
1192
6256
      .IsNothing()) return;
1193
1194
12512
  if (ret->Set(context,
1195
           FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"),
1196
18768
           Boolean::New(isolate, env->no_global_search_paths()))
1197
6256
      .IsNothing()) return;
1198
1199
12512
  args.GetReturnValue().Set(ret);
1200
}
1201
1202
784
void Initialize(Local<Object> target,
1203
                Local<Value> unused,
1204
                Local<Context> context,
1205
                void* priv) {
1206
784
  Environment* env = Environment::GetCurrent(context);
1207
784
  Isolate* isolate = env->isolate();
1208
784
  SetMethodNoSideEffect(context, target, "getCLIOptions", GetCLIOptions);
1209
784
  SetMethodNoSideEffect(
1210
      context, target, "getEmbedderOptions", GetEmbedderOptions);
1211
1212
784
  Local<Object> env_settings = Object::New(isolate);
1213
2352
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment);
1214
2352
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvironment);
1215
  target
1216
784
      ->Set(
1217
1568
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1218
      .Check();
1219
1220
784
  Local<Object> types = Object::New(isolate);
1221
2352
  NODE_DEFINE_CONSTANT(types, kNoOp);
1222
2352
  NODE_DEFINE_CONSTANT(types, kV8Option);
1223
2352
  NODE_DEFINE_CONSTANT(types, kBoolean);
1224
2352
  NODE_DEFINE_CONSTANT(types, kInteger);
1225
2352
  NODE_DEFINE_CONSTANT(types, kUInteger);
1226
2352
  NODE_DEFINE_CONSTANT(types, kString);
1227
2352
  NODE_DEFINE_CONSTANT(types, kHostPort);
1228
2352
  NODE_DEFINE_CONSTANT(types, kStringList);
1229
1568
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1230
      .Check();
1231
784
}
1232
1233
5527
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1234
5527
  registry->Register(GetCLIOptions);
1235
5527
  registry->Register(GetEmbedderOptions);
1236
5527
}
1237
}  // namespace options_parser
1238
1239
5597
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1240
5597
  HandleEnvOptions(env_options, [](const char* name) {
1241
22388
    std::string text;
1242

22388
    return credentials::SafeGetenv(name, &text) ? text : "";
1243
  });
1244
5597
}
1245
1246
5890
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1247
                      std::function<std::string(const char*)> opt_getter) {
1248
5890
  env_options->pending_deprecation =
1249
11780
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1250
1251
5890
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1252
1253
5890
  env_options->preserve_symlinks_main =
1254
11780
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1255
1256
5890
  if (env_options->redirect_warnings.empty())
1257
5890
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1258
5890
}
1259
1260
5768
std::vector<std::string> ParseNodeOptionsEnvVar(
1261
    const std::string& node_options, std::vector<std::string>* errors) {
1262
5768
  std::vector<std::string> env_argv;
1263
1264
5768
  bool is_in_string = false;
1265
5768
  bool will_start_new_arg = true;
1266
8372
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1267
2604
    char c = node_options.at(index);
1268
1269
    // Backslashes escape the following character
1270

2604
    if (c == '\\' && is_in_string) {
1271
      if (index + 1 == node_options.size()) {
1272
        errors->push_back("invalid value for NODE_OPTIONS "
1273
                          "(invalid escape)\n");
1274
        return env_argv;
1275
      } else {
1276
        c = node_options.at(++index);
1277
      }
1278

2604
    } else if (c == ' ' && !is_in_string) {
1279
32
      will_start_new_arg = true;
1280
32
      continue;
1281
2572
    } else if (c == '"') {
1282
4
      is_in_string = !is_in_string;
1283
4
      continue;
1284
    }
1285
1286
2568
    if (will_start_new_arg) {
1287
108
      env_argv.emplace_back(std::string(1, c));
1288
108
      will_start_new_arg = false;
1289
    } else {
1290
2460
      env_argv.back() += c;
1291
    }
1292
  }
1293
1294
5768
  if (is_in_string) {
1295
    errors->push_back("invalid value for NODE_OPTIONS "
1296
                      "(unterminated string)\n");
1297
  }
1298
5768
  return env_argv;
1299
}
1300
}  // namespace node
1301
1302
5597
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1303
5527
NODE_MODULE_EXTERNAL_REFERENCE(options,
1304
                               node::options_parser::RegisterExternalReferences)