GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 473 502 94.2 %
Date: 2022-08-02 04:16:51 Branches: 214 274 78.1 %

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
11188
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
11188
  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
22376
      SplitString(inspect_publish_uid_string, ',');
53
11188
  inspect_publish_uid.console = false;
54
11188
  inspect_publish_uid.http = false;
55
33562
  for (const std::string& destination : destinations) {
56
22374
    if (destination == "stderr") {
57
11187
      inspect_publish_uid.console = true;
58
11187
    } else if (destination == "http") {
59
11187
      inspect_publish_uid.http = true;
60
    } else {
61
      errors->push_back("--inspect-publish-uid destination can be "
62
                        "stderr or http");
63
    }
64
  }
65
11188
}
66
67
10602
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
68
#if HAVE_OPENSSL
69

10602
  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
10602
  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
10604
  if (use_largepages != "off" &&
90

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

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

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

59
    if (module_type != "commonjs" && module_type != "module") {
112
      errors->push_back("--input-type must be \"module\" or \"commonjs\"");
113
    }
114
  }
115
116
11188
  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

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

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

11188
  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
11188
  if (heap_snapshot_near_heap_limit < 0) {
143
    errors->push_back("--heap-snapshot-near-heap-limit must not be negative");
144
  }
145
146
11188
  if (test_runner) {
147
15
    if (syntax_check_only) {
148
1
      errors->push_back("either --test or --check can be used, not both");
149
    }
150
151
15
    if (has_eval_string) {
152
2
      errors->push_back("either --test or --eval can be used, not both");
153
    }
154
155
15
    if (force_repl) {
156
1
      errors->push_back("either --test or --interactive can be used, not both");
157
    }
158
159
15
    if (debug_options_.inspector_enabled) {
160
2
      errors->push_back("the inspector cannot be used with --test");
161
    }
162
  }
163
164
#if HAVE_INSPECTOR
165
11188
  if (!cpu_prof) {
166
11177
    if (!cpu_prof_name.empty()) {
167
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
168
    }
169
11177
    if (!cpu_prof_dir.empty()) {
170
1
      errors->push_back("--cpu-prof-dir must be used with --cpu-prof");
171
    }
172
    // We can't catch the case where the value passed is the default value,
173
    // then the option just becomes a noop which is fine.
174
11177
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
175
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
176
    }
177
  }
178
179


11188
  if (cpu_prof && cpu_prof_dir.empty() && !diagnostic_dir.empty()) {
180
1
      cpu_prof_dir = diagnostic_dir;
181
    }
182
183
11188
  if (!heap_prof) {
184
11177
    if (!heap_prof_name.empty()) {
185
1
      errors->push_back("--heap-prof-name must be used with --heap-prof");
186
    }
187
11177
    if (!heap_prof_dir.empty()) {
188
1
      errors->push_back("--heap-prof-dir must be used with --heap-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
11177
    if (heap_prof_interval != kDefaultHeapProfInterval) {
193
1
      errors->push_back("--heap-prof-interval must be used with --heap-prof");
194
    }
195
  }
196
197


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


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
910
4
    return host.substr(1, host.size() - 2);
911
  else
912
108
    return host;
913
}
914
915
100
inline int ParseAndValidatePort(const std::string& port,
916
                                std::vector<std::string>* errors) {
917
  char* endptr;
918
100
  errno = 0;
919
  const unsigned long result =                 // NOLINT(runtime/int)
920
100
    strtoul(port.c_str(), &endptr, 10);
921

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

100
      (result != 0 && result < 1024) || result > 65535) {
923
    errors->push_back(" must be 0 or in range 1024 to 65535.");
924
  }
925
100
  return static_cast<int>(result);
926
}
927
928
100
HostPort SplitHostPort(const std::string& arg,
929
                      std::vector<std::string>* errors) {
930
  // remove_brackets only works if no port is specified
931
  // so if it has an effect only an IPv6 address was specified.
932
200
  std::string host = RemoveBrackets(arg);
933
100
  if (host.length() < arg.length())
934
    return HostPort{host, DebugOptions::kDefaultInspectorPort};
935
936
100
  size_t colon = arg.rfind(':');
937
100
  if (colon == std::string::npos) {
938
    // Either a port number or a host name.  Assume that
939
    // if it's not all decimal digits, it's a host name.
940
390
    for (char c : arg) {
941

302
      if (c < '0' || c > '9') {
942
        return HostPort{arg, DebugOptions::kDefaultInspectorPort};
943
      }
944
    }
945
88
    return HostPort { "", ParseAndValidatePort(arg, errors) };
946
  }
947
  // Host and port found:
948
24
  return HostPort { RemoveBrackets(arg.substr(0, colon)),
949
12
                    ParseAndValidatePort(arg.substr(colon + 1), errors) };
950
}
951
952
1
std::string GetBashCompletion() {
953
2
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
954
1
  const auto& parser = _ppop_instance;
955
956
2
  std::ostringstream out;
957
958
  out << "_node_complete() {\n"
959
         "  local cur_word options\n"
960
         "  cur_word=\"${COMP_WORDS[COMP_CWORD]}\"\n"
961
         "  if [[ \"${cur_word}\" == -* ]] ; then\n"
962
1
         "    COMPREPLY=( $(compgen -W '";
963
964
140
  for (const auto& item : parser.options_) {
965
139
    if (item.first[0] != '[') {
966
136
      out << item.first << " ";
967
    }
968
  }
969
23
  for (const auto& item : parser.aliases_) {
970
22
    if (item.first[0] != '[') {
971
22
      out << item.first << " ";
972
    }
973
  }
974
1
  if (parser.aliases_.size() > 0) {
975
1
    out.seekp(-1, out.cur);  // Strip the trailing space
976
  }
977
978
  out << "' -- \"${cur_word}\") )\n"
979
         "    return 0\n"
980
         "  else\n"
981
         "    COMPREPLY=( $(compgen -f \"${cur_word}\") )\n"
982
         "    return 0\n"
983
         "  fi\n"
984
         "}\n"
985
         "complete -o filenames -o nospace -o bashdefault "
986
1
         "-F _node_complete node node_g";
987
1
  return out.str();
988
}
989
990
// Return a map containing all the options and their metadata as well
991
// as the aliases
992
void GetCLIOptions(const FunctionCallbackInfo<Value>& args) {
993
7155
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
994
7155
  Environment* env = Environment::GetCurrent(args);
995
7155
  if (!env->has_run_bootstrapping_code()) {
996
    // No code because this is an assertion.
997
    return env->ThrowError(
998
        "Should not query options before bootstrapping is done");
999
  }
1000
7155
  env->set_has_serialized_options(true);
1001
1002
7155
  Isolate* isolate = env->isolate();
1003
7155
  Local<Context> context = env->context();
1004
1005
  // Temporarily act as if the current Environment's/IsolateData's options were
1006
  // the default options, i.e. like they are the ones we'd access for global
1007
  // options parsing, so that all options are available from the main parser.
1008
7155
  auto original_per_isolate = per_process::cli_options->per_isolate;
1009
7155
  per_process::cli_options->per_isolate = env->isolate_data()->options();
1010
7155
  auto original_per_env = per_process::cli_options->per_isolate->per_env;
1011
7155
  per_process::cli_options->per_isolate->per_env = env->options();
1012
7155
  auto on_scope_leave = OnScopeLeave([&]() {
1013
7155
    per_process::cli_options->per_isolate->per_env = original_per_env;
1014
7155
    per_process::cli_options->per_isolate = original_per_isolate;
1015
7155
  });
1016
1017
7155
  Local<Map> options = Map::New(isolate);
1018
7155
  if (options
1019
14310
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1020
7155
          .IsNothing()) {
1021
    return;
1022
  }
1023
1024
1001700
  for (const auto& item : _ppop_instance.options_) {
1025
    Local<Value> value;
1026
994545
    const auto& option_info = item.second;
1027
994545
    auto field = option_info.field;
1028
994545
    PerProcessOptions* opts = per_process::cli_options.get();
1029


994545
    switch (option_info.type) {
1030
157410
      case kNoOp:
1031
      case kV8Option:
1032
        // Special case for --abort-on-uncaught-exception which is also
1033
        // respected by Node.js internals
1034
157410
        if (item.first == "--abort-on-uncaught-exception") {
1035
7155
          value = Boolean::New(
1036
7155
            isolate, original_per_env->abort_on_uncaught_exception);
1037
        } else {
1038
150255
          value = Undefined(isolate);
1039
        }
1040
157410
        break;
1041
550935
      case kBoolean:
1042
1101870
        value = Boolean::New(isolate,
1043
1101870
                             *_ppop_instance.Lookup<bool>(field, opts));
1044
550935
        break;
1045
28620
      case kInteger:
1046
57240
        value = Number::New(
1047
            isolate,
1048
57240
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1049
28620
        break;
1050
21465
      case kUInteger:
1051
42930
        value = Number::New(
1052
            isolate,
1053
42930
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1054
21465
        break;
1055
193185
      case kString:
1056
386370
        if (!ToV8Value(context,
1057
386370
                       *_ppop_instance.Lookup<std::string>(field, opts))
1058
193185
                 .ToLocal(&value)) {
1059
          return;
1060
        }
1061
193185
        break;
1062
35775
      case kStringList:
1063
71550
        if (!ToV8Value(context,
1064
71550
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1065
35775
                 .ToLocal(&value)) {
1066
          return;
1067
        }
1068
35775
        break;
1069
7155
      case kHostPort: {
1070
        const HostPort& host_port =
1071
7155
          *_ppop_instance.Lookup<HostPort>(field, opts);
1072
7155
        Local<Object> obj = Object::New(isolate);
1073
        Local<Value> host;
1074
7155
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1075

35775
            obj->Set(context, env->host_string(), host).IsNothing() ||
1076
7155
            obj->Set(context,
1077
                     env->port_string(),
1078
28620
                     Integer::New(isolate, host_port.port()))
1079
7155
                .IsNothing()) {
1080
          return;
1081
        }
1082
7155
        value = obj;
1083
7155
        break;
1084
      }
1085
      default:
1086
        UNREACHABLE();
1087
    }
1088
994545
    CHECK(!value.IsEmpty());
1089
1090
994545
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1091
994545
    Local<Object> info = Object::New(isolate);
1092
    Local<Value> help_text;
1093
994545
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1094
1989090
        !info->Set(context, env->help_text_string(), help_text)
1095

1989090
             .FromMaybe(false) ||
1096
1989090
        !info->Set(context,
1097
                   env->env_var_settings_string(),
1098
                   Integer::New(isolate,
1099
2983635
                                static_cast<int>(option_info.env_setting)))
1100

1989090
             .FromMaybe(false) ||
1101
1989090
        !info->Set(context,
1102
                   env->type_string(),
1103
2983635
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1104

1989090
             .FromMaybe(false) ||
1105
1989090
        !info->Set(context,
1106
                   env->default_is_true_string(),
1107
2983635
                   Boolean::New(isolate, option_info.default_is_true))
1108

1989090
             .FromMaybe(false) ||
1109

4972725
        info->Set(context, env->value_string(), value).IsNothing() ||
1110

2983635
        options->Set(context, name, info).IsEmpty()) {
1111
      return;
1112
    }
1113
  }
1114
1115
  Local<Value> aliases;
1116
14310
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1117
1118
7155
  if (aliases.As<Object>()
1119
14310
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1120
7155
          .IsNothing()) {
1121
    return;
1122
  }
1123
1124
7155
  Local<Object> ret = Object::New(isolate);
1125
28620
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1126

28620
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1127
    return;
1128
  }
1129
1130
14310
  args.GetReturnValue().Set(ret);
1131
}
1132
1133
6561
void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
1134
6561
  Environment* env = Environment::GetCurrent(args);
1135
6561
  if (!env->has_run_bootstrapping_code()) {
1136
    // No code because this is an assertion.
1137
    return env->ThrowError(
1138
        "Should not query options before bootstrapping is done");
1139
  }
1140
6561
  Isolate* isolate = args.GetIsolate();
1141
6561
  Local<Context> context = env->context();
1142
6561
  Local<Object> ret = Object::New(isolate);
1143
1144
13122
  if (ret->Set(context,
1145
           FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1146
19683
           Boolean::New(isolate, env->should_not_register_esm_loader()))
1147
6561
      .IsNothing()) return;
1148
1149
13122
  if (ret->Set(context,
1150
           FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"),
1151
19683
           Boolean::New(isolate, env->no_global_search_paths()))
1152
6561
      .IsNothing()) return;
1153
1154
13122
  args.GetReturnValue().Set(ret);
1155
}
1156
1157
1303
void Initialize(Local<Object> target,
1158
                Local<Value> unused,
1159
                Local<Context> context,
1160
                void* priv) {
1161
1303
  Environment* env = Environment::GetCurrent(context);
1162
1303
  Isolate* isolate = env->isolate();
1163
1303
  SetMethodNoSideEffect(context, target, "getCLIOptions", GetCLIOptions);
1164
1303
  SetMethodNoSideEffect(
1165
      context, target, "getEmbedderOptions", GetEmbedderOptions);
1166
1167
1303
  Local<Object> env_settings = Object::New(isolate);
1168
3909
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment);
1169
3909
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvironment);
1170
  target
1171
1303
      ->Set(
1172
2606
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1173
      .Check();
1174
1175
1303
  Local<Object> types = Object::New(isolate);
1176
3909
  NODE_DEFINE_CONSTANT(types, kNoOp);
1177
3909
  NODE_DEFINE_CONSTANT(types, kV8Option);
1178
3909
  NODE_DEFINE_CONSTANT(types, kBoolean);
1179
3909
  NODE_DEFINE_CONSTANT(types, kInteger);
1180
3909
  NODE_DEFINE_CONSTANT(types, kUInteger);
1181
3909
  NODE_DEFINE_CONSTANT(types, kString);
1182
3909
  NODE_DEFINE_CONSTANT(types, kHostPort);
1183
3909
  NODE_DEFINE_CONSTANT(types, kStringList);
1184
2606
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1185
      .Check();
1186
1303
}
1187
1188
5300
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1189
5300
  registry->Register(GetCLIOptions);
1190
5300
  registry->Register(GetEmbedderOptions);
1191
5300
}
1192
}  // namespace options_parser
1193
1194
5368
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1195
5368
  HandleEnvOptions(env_options, [](const char* name) {
1196
21472
    std::string text;
1197

21472
    return credentials::SafeGetenv(name, &text) ? text : "";
1198
  });
1199
5368
}
1200
1201
5663
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1202
                      std::function<std::string(const char*)> opt_getter) {
1203
5663
  env_options->pending_deprecation =
1204
11326
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1205
1206
5663
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1207
1208
5663
  env_options->preserve_symlinks_main =
1209
11326
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1210
1211
5663
  if (env_options->redirect_warnings.empty())
1212
5663
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1213
5663
}
1214
1215
5545
std::vector<std::string> ParseNodeOptionsEnvVar(
1216
    const std::string& node_options, std::vector<std::string>* errors) {
1217
5545
  std::vector<std::string> env_argv;
1218
1219
5545
  bool is_in_string = false;
1220
5545
  bool will_start_new_arg = true;
1221
8149
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1222
2604
    char c = node_options.at(index);
1223
1224
    // Backslashes escape the following character
1225

2604
    if (c == '\\' && is_in_string) {
1226
      if (index + 1 == node_options.size()) {
1227
        errors->push_back("invalid value for NODE_OPTIONS "
1228
                          "(invalid escape)\n");
1229
        return env_argv;
1230
      } else {
1231
        c = node_options.at(++index);
1232
      }
1233

2604
    } else if (c == ' ' && !is_in_string) {
1234
32
      will_start_new_arg = true;
1235
32
      continue;
1236
2572
    } else if (c == '"') {
1237
4
      is_in_string = !is_in_string;
1238
4
      continue;
1239
    }
1240
1241
2568
    if (will_start_new_arg) {
1242
108
      env_argv.emplace_back(std::string(1, c));
1243
108
      will_start_new_arg = false;
1244
    } else {
1245
2460
      env_argv.back() += c;
1246
    }
1247
  }
1248
1249
5545
  if (is_in_string) {
1250
    errors->push_back("invalid value for NODE_OPTIONS "
1251
                      "(unterminated string)\n");
1252
  }
1253
5545
  return env_argv;
1254
}
1255
}  // namespace node
1256
1257
5368
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1258
5300
NODE_MODULE_EXTERNAL_REFERENCE(options,
1259
                               node::options_parser::RegisterExternalReferences)