GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 468 497 94.2 %
Date: 2022-04-26 04:15:06 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
10576
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
10576
  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
21152
      SplitString(inspect_publish_uid_string, ',');
53
10576
  inspect_publish_uid.console = false;
54
10576
  inspect_publish_uid.http = false;
55
31726
  for (const std::string& destination : destinations) {
56
21150
    if (destination == "stderr") {
57
10575
      inspect_publish_uid.console = true;
58
10575
    } else if (destination == "http") {
59
10575
      inspect_publish_uid.http = true;
60
    } else {
61
      errors->push_back("--inspect-publish-uid destination can be "
62
                        "stderr or http");
63
    }
64
  }
65
10576
}
66
67
10030
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
68
#if HAVE_OPENSSL
69

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

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

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

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

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

12
    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

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

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

10576
  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
10576
  if (heap_snapshot_near_heap_limit < 0) {
143
    errors->push_back("--heap-snapshot-near-heap-limit must not be negative");
144
  }
145
146
10576
  if (test_runner) {
147
11
    if (syntax_check_only) {
148
1
      errors->push_back("either --test or --check can be used, not both");
149
    }
150
151
11
    if (has_eval_string) {
152
2
      errors->push_back("either --test or --eval can be used, not both");
153
    }
154
155
11
    if (force_repl) {
156
1
      errors->push_back("either --test or --interactive can be used, not both");
157
    }
158
159
11
    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
10576
  if (!cpu_prof) {
166
10565
    if (!cpu_prof_name.empty()) {
167
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
168
    }
169
10565
    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
10565
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
175
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
176
    }
177
  }
178
179


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


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


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
890
4
    return host.substr(1, host.size() - 2);
891
  else
892
108
    return host;
893
}
894
895
100
inline int ParseAndValidatePort(const std::string& port,
896
                                std::vector<std::string>* errors) {
897
  char* endptr;
898
100
  errno = 0;
899
  const unsigned long result =                 // NOLINT(runtime/int)
900
100
    strtoul(port.c_str(), &endptr, 10);
901

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

100
      (result != 0 && result < 1024) || result > 65535) {
903
    errors->push_back(" must be 0 or in range 1024 to 65535.");
904
  }
905
100
  return static_cast<int>(result);
906
}
907
908
100
HostPort SplitHostPort(const std::string& arg,
909
                      std::vector<std::string>* errors) {
910
  // remove_brackets only works if no port is specified
911
  // so if it has an effect only an IPv6 address was specified.
912
200
  std::string host = RemoveBrackets(arg);
913
100
  if (host.length() < arg.length())
914
    return HostPort{host, DebugOptions::kDefaultInspectorPort};
915
916
100
  size_t colon = arg.rfind(':');
917
100
  if (colon == std::string::npos) {
918
    // Either a port number or a host name.  Assume that
919
    // if it's not all decimal digits, it's a host name.
920
390
    for (char c : arg) {
921

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


805608
    switch (option_info.type) {
1010
126252
      case kNoOp:
1011
      case kV8Option:
1012
        // Special case for --abort-on-uncaught-exception which is also
1013
        // respected by Node.js internals
1014
126252
        if (item.first == "--abort-on-uncaught-exception") {
1015
6012
          value = Boolean::New(
1016
6012
            isolate, original_per_env->abort_on_uncaught_exception);
1017
        } else {
1018
120240
          value = Undefined(isolate);
1019
        }
1020
126252
        break;
1021
444888
      case kBoolean:
1022
889776
        value = Boolean::New(isolate,
1023
889776
                             *_ppop_instance.Lookup<bool>(field, opts));
1024
444888
        break;
1025
24048
      case kInteger:
1026
48096
        value = Number::New(
1027
            isolate,
1028
48096
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1029
24048
        break;
1030
18036
      case kUInteger:
1031
36072
        value = Number::New(
1032
            isolate,
1033
36072
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1034
18036
        break;
1035
168336
      case kString:
1036
336672
        if (!ToV8Value(context,
1037
336672
                       *_ppop_instance.Lookup<std::string>(field, opts))
1038
168336
                 .ToLocal(&value)) {
1039
          return;
1040
        }
1041
168336
        break;
1042
18036
      case kStringList:
1043
36072
        if (!ToV8Value(context,
1044
36072
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1045
18036
                 .ToLocal(&value)) {
1046
          return;
1047
        }
1048
18036
        break;
1049
6012
      case kHostPort: {
1050
        const HostPort& host_port =
1051
6012
          *_ppop_instance.Lookup<HostPort>(field, opts);
1052
6012
        Local<Object> obj = Object::New(isolate);
1053
        Local<Value> host;
1054
6012
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1055

30060
            obj->Set(context, env->host_string(), host).IsNothing() ||
1056
6012
            obj->Set(context,
1057
                     env->port_string(),
1058
24048
                     Integer::New(isolate, host_port.port()))
1059
6012
                .IsNothing()) {
1060
          return;
1061
        }
1062
6012
        value = obj;
1063
6012
        break;
1064
      }
1065
      default:
1066
        UNREACHABLE();
1067
    }
1068
805608
    CHECK(!value.IsEmpty());
1069
1070
805608
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1071
805608
    Local<Object> info = Object::New(isolate);
1072
    Local<Value> help_text;
1073
805608
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1074
1611216
        !info->Set(context, env->help_text_string(), help_text)
1075

1611216
             .FromMaybe(false) ||
1076
1611216
        !info->Set(context,
1077
                   env->env_var_settings_string(),
1078
                   Integer::New(isolate,
1079
2416824
                                static_cast<int>(option_info.env_setting)))
1080

1611216
             .FromMaybe(false) ||
1081
1611216
        !info->Set(context,
1082
                   env->type_string(),
1083
2416824
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1084

1611216
             .FromMaybe(false) ||
1085
1611216
        !info->Set(context,
1086
                   env->default_is_true_string(),
1087
2416824
                   Boolean::New(isolate, option_info.default_is_true))
1088

1611216
             .FromMaybe(false) ||
1089

4028040
        info->Set(context, env->value_string(), value).IsNothing() ||
1090

2416824
        options->Set(context, name, info).IsEmpty()) {
1091
      return;
1092
    }
1093
  }
1094
1095
  Local<Value> aliases;
1096
12024
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1097
1098
6012
  if (aliases.As<Object>()
1099
12024
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1100
6012
          .IsNothing()) {
1101
    return;
1102
  }
1103
1104
6012
  Local<Object> ret = Object::New(isolate);
1105
24048
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1106

24048
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1107
    return;
1108
  }
1109
1110
12024
  args.GetReturnValue().Set(ret);
1111
}
1112
1113
5607
void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
1114
5607
  Environment* env = Environment::GetCurrent(args);
1115
5607
  if (!env->has_run_bootstrapping_code()) {
1116
    // No code because this is an assertion.
1117
    return env->ThrowError(
1118
        "Should not query options before bootstrapping is done");
1119
  }
1120
5607
  Isolate* isolate = args.GetIsolate();
1121
5607
  Local<Context> context = env->context();
1122
5607
  Local<Object> ret = Object::New(isolate);
1123
1124
11214
  if (ret->Set(context,
1125
           FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1126
16821
           Boolean::New(isolate, env->should_not_register_esm_loader()))
1127
5607
      .IsNothing()) return;
1128
1129
11214
  if (ret->Set(context,
1130
           FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"),
1131
16821
           Boolean::New(isolate, env->no_global_search_paths()))
1132
5607
      .IsNothing()) return;
1133
1134
11214
  args.GetReturnValue().Set(ret);
1135
}
1136
1137
637
void Initialize(Local<Object> target,
1138
                Local<Value> unused,
1139
                Local<Context> context,
1140
                void* priv) {
1141
637
  Environment* env = Environment::GetCurrent(context);
1142
637
  Isolate* isolate = env->isolate();
1143
637
  env->SetMethodNoSideEffect(target, "getCLIOptions", GetCLIOptions);
1144
637
  env->SetMethodNoSideEffect(target, "getEmbedderOptions", GetEmbedderOptions);
1145
1146
637
  Local<Object> env_settings = Object::New(isolate);
1147
1911
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment);
1148
1911
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvironment);
1149
  target
1150
637
      ->Set(
1151
1274
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1152
      .Check();
1153
1154
637
  Local<Object> types = Object::New(isolate);
1155
1911
  NODE_DEFINE_CONSTANT(types, kNoOp);
1156
1911
  NODE_DEFINE_CONSTANT(types, kV8Option);
1157
1911
  NODE_DEFINE_CONSTANT(types, kBoolean);
1158
1911
  NODE_DEFINE_CONSTANT(types, kInteger);
1159
1911
  NODE_DEFINE_CONSTANT(types, kUInteger);
1160
1911
  NODE_DEFINE_CONSTANT(types, kString);
1161
1911
  NODE_DEFINE_CONSTANT(types, kHostPort);
1162
1911
  NODE_DEFINE_CONSTANT(types, kStringList);
1163
1274
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1164
      .Check();
1165
637
}
1166
1167
5014
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1168
5014
  registry->Register(GetCLIOptions);
1169
5014
  registry->Register(GetEmbedderOptions);
1170
5014
}
1171
}  // namespace options_parser
1172
1173
5082
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1174
5082
  HandleEnvOptions(env_options, [](const char* name) {
1175
20328
    std::string text;
1176

20328
    return credentials::SafeGetenv(name, &text) ? text : "";
1177
  });
1178
5082
}
1179
1180
5357
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1181
                      std::function<std::string(const char*)> opt_getter) {
1182
5357
  env_options->pending_deprecation =
1183
10714
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1184
1185
5357
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1186
1187
5357
  env_options->preserve_symlinks_main =
1188
10714
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1189
1190
5357
  if (env_options->redirect_warnings.empty())
1191
5357
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1192
5357
}
1193
1194
5239
std::vector<std::string> ParseNodeOptionsEnvVar(
1195
    const std::string& node_options, std::vector<std::string>* errors) {
1196
5239
  std::vector<std::string> env_argv;
1197
1198
5239
  bool is_in_string = false;
1199
5239
  bool will_start_new_arg = true;
1200
7843
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1201
2604
    char c = node_options.at(index);
1202
1203
    // Backslashes escape the following character
1204

2604
    if (c == '\\' && is_in_string) {
1205
      if (index + 1 == node_options.size()) {
1206
        errors->push_back("invalid value for NODE_OPTIONS "
1207
                          "(invalid escape)\n");
1208
        return env_argv;
1209
      } else {
1210
        c = node_options.at(++index);
1211
      }
1212

2604
    } else if (c == ' ' && !is_in_string) {
1213
32
      will_start_new_arg = true;
1214
32
      continue;
1215
2572
    } else if (c == '"') {
1216
4
      is_in_string = !is_in_string;
1217
4
      continue;
1218
    }
1219
1220
2568
    if (will_start_new_arg) {
1221
108
      env_argv.emplace_back(std::string(1, c));
1222
108
      will_start_new_arg = false;
1223
    } else {
1224
2460
      env_argv.back() += c;
1225
    }
1226
  }
1227
1228
5239
  if (is_in_string) {
1229
    errors->push_back("invalid value for NODE_OPTIONS "
1230
                      "(unterminated string)\n");
1231
  }
1232
5239
  return env_argv;
1233
}
1234
}  // namespace node
1235
1236
5082
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1237
5014
NODE_MODULE_EXTERNAL_REFERENCE(options,
1238
                               node::options_parser::RegisterExternalReferences)