GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 451 480 94.0 %
Date: 2022-02-21 04:14:21 Branches: 204 264 77.3 %

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

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

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

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

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

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

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

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

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

10413
  if (tls_min_v1_3 && tls_max_v1_2) {
137
1
    errors->push_back("either --tls-min-v1.3 or --tls-max-v1.2 can be "
138
                      "used, not both");
139
  }
140
141
10413
  if (heap_snapshot_near_heap_limit < 0) {
142
    errors->push_back("--heap-snapshot-near-heap-limit must not be negative");
143
  }
144
145
#if HAVE_INSPECTOR
146
10413
  if (!cpu_prof) {
147
10402
    if (!cpu_prof_name.empty()) {
148
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
149
    }
150
10402
    if (!cpu_prof_dir.empty()) {
151
1
      errors->push_back("--cpu-prof-dir must be used with --cpu-prof");
152
    }
153
    // We can't catch the case where the value passed is the default value,
154
    // then the option just becomes a noop which is fine.
155
10402
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
156
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
157
    }
158
  }
159
160


10413
  if (cpu_prof && cpu_prof_dir.empty() && !diagnostic_dir.empty()) {
161
1
      cpu_prof_dir = diagnostic_dir;
162
    }
163
164
10413
  if (!heap_prof) {
165
10402
    if (!heap_prof_name.empty()) {
166
1
      errors->push_back("--heap-prof-name must be used with --heap-prof");
167
    }
168
10402
    if (!heap_prof_dir.empty()) {
169
1
      errors->push_back("--heap-prof-dir must be used with --heap-prof");
170
    }
171
    // We can't catch the case where the value passed is the default value,
172
    // then the option just becomes a noop which is fine.
173
10402
    if (heap_prof_interval != kDefaultHeapProfInterval) {
174
1
      errors->push_back("--heap-prof-interval must be used with --heap-prof");
175
    }
176
  }
177
178


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


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
858
4
    return host.substr(1, host.size() - 2);
859
  else
860
108
    return host;
861
}
862
863
100
inline int ParseAndValidatePort(const std::string& port,
864
                                std::vector<std::string>* errors) {
865
  char* endptr;
866
100
  errno = 0;
867
  const unsigned long result =                 // NOLINT(runtime/int)
868
100
    strtoul(port.c_str(), &endptr, 10);
869

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

100
      (result != 0 && result < 1024) || result > 65535) {
871
    errors->push_back(" must be 0 or in range 1024 to 65535.");
872
  }
873
100
  return static_cast<int>(result);
874
}
875
876
100
HostPort SplitHostPort(const std::string& arg,
877
                      std::vector<std::string>* errors) {
878
  // remove_brackets only works if no port is specified
879
  // so if it has an effect only an IPv6 address was specified.
880
200
  std::string host = RemoveBrackets(arg);
881
100
  if (host.length() < arg.length())
882
    return HostPort{host, DebugOptions::kDefaultInspectorPort};
883
884
100
  size_t colon = arg.rfind(':');
885
100
  if (colon == std::string::npos) {
886
    // Either a port number or a host name.  Assume that
887
    // if it's not all decimal digits, it's a host name.
888
390
    for (char c : arg) {
889

302
      if (c < '0' || c > '9') {
890
        return HostPort{arg, DebugOptions::kDefaultInspectorPort};
891
      }
892
    }
893
88
    return HostPort { "", ParseAndValidatePort(arg, errors) };
894
  }
895
  // Host and port found:
896
24
  return HostPort { RemoveBrackets(arg.substr(0, colon)),
897
12
                    ParseAndValidatePort(arg.substr(colon + 1), errors) };
898
}
899
900
1
std::string GetBashCompletion() {
901
2
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
902
1
  const auto& parser = _ppop_instance;
903
904
2
  std::ostringstream out;
905
906
  out << "_node_complete() {\n"
907
         "  local cur_word options\n"
908
         "  cur_word=\"${COMP_WORDS[COMP_CWORD]}\"\n"
909
         "  if [[ \"${cur_word}\" == -* ]] ; then\n"
910
1
         "    COMPREPLY=( $(compgen -W '";
911
912
132
  for (const auto& item : parser.options_) {
913
131
    if (item.first[0] != '[') {
914
128
      out << item.first << " ";
915
    }
916
  }
917
23
  for (const auto& item : parser.aliases_) {
918
22
    if (item.first[0] != '[') {
919
22
      out << item.first << " ";
920
    }
921
  }
922
1
  if (parser.aliases_.size() > 0) {
923
1
    out.seekp(-1, out.cur);  // Strip the trailing space
924
  }
925
926
  out << "' -- \"${cur_word}\") )\n"
927
         "    return 0\n"
928
         "  else\n"
929
         "    COMPREPLY=( $(compgen -f \"${cur_word}\") )\n"
930
         "    return 0\n"
931
         "  fi\n"
932
         "}\n"
933
         "complete -o filenames -o nospace -o bashdefault "
934
1
         "-F _node_complete node node_g";
935
1
  return out.str();
936
}
937
938
// Return a map containing all the options and their metadata as well
939
// as the aliases
940
void GetCLIOptions(const FunctionCallbackInfo<Value>& args) {
941
5557
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
942
5557
  Environment* env = Environment::GetCurrent(args);
943
5557
  if (!env->has_run_bootstrapping_code()) {
944
    // No code because this is an assertion.
945
    return env->ThrowError(
946
        "Should not query options before bootstrapping is done");
947
  }
948
5557
  env->set_has_serialized_options(true);
949
950
5557
  Isolate* isolate = env->isolate();
951
5557
  Local<Context> context = env->context();
952
953
  // Temporarily act as if the current Environment's/IsolateData's options were
954
  // the default options, i.e. like they are the ones we'd access for global
955
  // options parsing, so that all options are available from the main parser.
956
5557
  auto original_per_isolate = per_process::cli_options->per_isolate;
957
5557
  per_process::cli_options->per_isolate = env->isolate_data()->options();
958
5557
  auto original_per_env = per_process::cli_options->per_isolate->per_env;
959
5557
  per_process::cli_options->per_isolate->per_env = env->options();
960
5557
  auto on_scope_leave = OnScopeLeave([&]() {
961
5557
    per_process::cli_options->per_isolate->per_env = original_per_env;
962
5557
    per_process::cli_options->per_isolate = original_per_isolate;
963
5557
  });
964
965
5557
  Local<Map> options = Map::New(isolate);
966
5557
  if (options
967
11114
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
968
5557
          .IsNothing()) {
969
    return;
970
  }
971
972
733524
  for (const auto& item : _ppop_instance.options_) {
973
    Local<Value> value;
974
727967
    const auto& option_info = item.second;
975
727967
    auto field = option_info.field;
976
727967
    PerProcessOptions* opts = per_process::cli_options.get();
977


727967
    switch (option_info.type) {
978
116697
      case kNoOp:
979
      case kV8Option:
980
        // Special case for --abort-on-uncaught-exception which is also
981
        // respected by Node.js internals
982
116697
        if (item.first == "--abort-on-uncaught-exception") {
983
5557
          value = Boolean::New(
984
5557
            isolate, original_per_env->abort_on_uncaught_exception);
985
        } else {
986
111140
          value = Undefined(isolate);
987
        }
988
116697
        break;
989
394547
      case kBoolean:
990
789094
        value = Boolean::New(isolate,
991
789094
                             *_ppop_instance.Lookup<bool>(field, opts));
992
394547
        break;
993
22228
      case kInteger:
994
44456
        value = Number::New(
995
            isolate,
996
44456
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
997
22228
        break;
998
16671
      case kUInteger:
999
33342
        value = Number::New(
1000
            isolate,
1001
33342
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1002
16671
        break;
1003
155596
      case kString:
1004
311192
        if (!ToV8Value(context,
1005
311192
                       *_ppop_instance.Lookup<std::string>(field, opts))
1006
155596
                 .ToLocal(&value)) {
1007
          return;
1008
        }
1009
155596
        break;
1010
16671
      case kStringList:
1011
33342
        if (!ToV8Value(context,
1012
33342
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1013
16671
                 .ToLocal(&value)) {
1014
          return;
1015
        }
1016
16671
        break;
1017
5557
      case kHostPort: {
1018
        const HostPort& host_port =
1019
5557
          *_ppop_instance.Lookup<HostPort>(field, opts);
1020
5557
        Local<Object> obj = Object::New(isolate);
1021
        Local<Value> host;
1022
5557
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1023

27785
            obj->Set(context, env->host_string(), host).IsNothing() ||
1024
5557
            obj->Set(context,
1025
                     env->port_string(),
1026
22228
                     Integer::New(isolate, host_port.port()))
1027
5557
                .IsNothing()) {
1028
          return;
1029
        }
1030
5557
        value = obj;
1031
5557
        break;
1032
      }
1033
      default:
1034
        UNREACHABLE();
1035
    }
1036
727967
    CHECK(!value.IsEmpty());
1037
1038
727967
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1039
727967
    Local<Object> info = Object::New(isolate);
1040
    Local<Value> help_text;
1041
727967
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1042
1455934
        !info->Set(context, env->help_text_string(), help_text)
1043

1455934
             .FromMaybe(false) ||
1044
1455934
        !info->Set(context,
1045
                   env->env_var_settings_string(),
1046
                   Integer::New(isolate,
1047
2183901
                                static_cast<int>(option_info.env_setting)))
1048

1455934
             .FromMaybe(false) ||
1049
1455934
        !info->Set(context,
1050
                   env->type_string(),
1051
2183901
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1052

1455934
             .FromMaybe(false) ||
1053
1455934
        !info->Set(context,
1054
                   env->default_is_true_string(),
1055
2183901
                   Boolean::New(isolate, option_info.default_is_true))
1056

1455934
             .FromMaybe(false) ||
1057

3639835
        info->Set(context, env->value_string(), value).IsNothing() ||
1058

2183901
        options->Set(context, name, info).IsEmpty()) {
1059
      return;
1060
    }
1061
  }
1062
1063
  Local<Value> aliases;
1064
11114
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1065
1066
5557
  if (aliases.As<Object>()
1067
11114
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1068
5557
          .IsNothing()) {
1069
    return;
1070
  }
1071
1072
5557
  Local<Object> ret = Object::New(isolate);
1073
22228
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1074

22228
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1075
    return;
1076
  }
1077
1078
11114
  args.GetReturnValue().Set(ret);
1079
}
1080
1081
5530
void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
1082
5530
  Environment* env = Environment::GetCurrent(args);
1083
5530
  if (!env->has_run_bootstrapping_code()) {
1084
    // No code because this is an assertion.
1085
    return env->ThrowError(
1086
        "Should not query options before bootstrapping is done");
1087
  }
1088
5530
  Isolate* isolate = args.GetIsolate();
1089
5530
  Local<Context> context = env->context();
1090
5530
  Local<Object> ret = Object::New(isolate);
1091
1092
11060
  if (ret->Set(context,
1093
           FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1094
16590
           Boolean::New(isolate, env->should_not_register_esm_loader()))
1095
5530
      .IsNothing()) return;
1096
1097
11060
  if (ret->Set(context,
1098
           FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"),
1099
16590
           Boolean::New(isolate, env->no_global_search_paths()))
1100
5530
      .IsNothing()) return;
1101
1102
11060
  args.GetReturnValue().Set(ret);
1103
}
1104
1105
5532
void Initialize(Local<Object> target,
1106
                Local<Value> unused,
1107
                Local<Context> context,
1108
                void* priv) {
1109
5532
  Environment* env = Environment::GetCurrent(context);
1110
5532
  Isolate* isolate = env->isolate();
1111
5532
  env->SetMethodNoSideEffect(target, "getCLIOptions", GetCLIOptions);
1112
5532
  env->SetMethodNoSideEffect(target, "getEmbedderOptions", GetEmbedderOptions);
1113
1114
5532
  Local<Object> env_settings = Object::New(isolate);
1115
16596
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment);
1116
16596
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvironment);
1117
  target
1118
5532
      ->Set(
1119
11064
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1120
      .Check();
1121
1122
5532
  Local<Object> types = Object::New(isolate);
1123
16596
  NODE_DEFINE_CONSTANT(types, kNoOp);
1124
16596
  NODE_DEFINE_CONSTANT(types, kV8Option);
1125
16596
  NODE_DEFINE_CONSTANT(types, kBoolean);
1126
16596
  NODE_DEFINE_CONSTANT(types, kInteger);
1127
16596
  NODE_DEFINE_CONSTANT(types, kUInteger);
1128
16596
  NODE_DEFINE_CONSTANT(types, kString);
1129
16596
  NODE_DEFINE_CONSTANT(types, kHostPort);
1130
16596
  NODE_DEFINE_CONSTANT(types, kStringList);
1131
11064
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1132
      .Check();
1133
5532
}
1134
1135
}  // namespace options_parser
1136
1137
5007
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1138
5007
  HandleEnvOptions(env_options, [](const char* name) {
1139
20028
    std::string text;
1140

20028
    return credentials::SafeGetenv(name, &text) ? text : "";
1141
  });
1142
5007
}
1143
1144
5275
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1145
                      std::function<std::string(const char*)> opt_getter) {
1146
5275
  env_options->pending_deprecation =
1147
10550
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1148
1149
5275
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1150
1151
5275
  env_options->preserve_symlinks_main =
1152
10550
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1153
1154
5275
  if (env_options->redirect_warnings.empty())
1155
5275
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1156
5275
}
1157
1158
5158
std::vector<std::string> ParseNodeOptionsEnvVar(
1159
    const std::string& node_options, std::vector<std::string>* errors) {
1160
5158
  std::vector<std::string> env_argv;
1161
1162
5158
  bool is_in_string = false;
1163
5158
  bool will_start_new_arg = true;
1164
7762
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1165
2604
    char c = node_options.at(index);
1166
1167
    // Backslashes escape the following character
1168

2604
    if (c == '\\' && is_in_string) {
1169
      if (index + 1 == node_options.size()) {
1170
        errors->push_back("invalid value for NODE_OPTIONS "
1171
                          "(invalid escape)\n");
1172
        return env_argv;
1173
      } else {
1174
        c = node_options.at(++index);
1175
      }
1176

2604
    } else if (c == ' ' && !is_in_string) {
1177
32
      will_start_new_arg = true;
1178
32
      continue;
1179
2572
    } else if (c == '"') {
1180
4
      is_in_string = !is_in_string;
1181
4
      continue;
1182
    }
1183
1184
2568
    if (will_start_new_arg) {
1185
108
      env_argv.emplace_back(std::string(1, c));
1186
108
      will_start_new_arg = false;
1187
    } else {
1188
2460
      env_argv.back() += c;
1189
    }
1190
  }
1191
1192
5158
  if (is_in_string) {
1193
    errors->push_back("invalid value for NODE_OPTIONS "
1194
                      "(unterminated string)\n");
1195
  }
1196
5158
  return env_argv;
1197
}
1198
}  // namespace node
1199
1200
5007
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)