GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 451 480 94.0 %
Date: 2022-03-03 04:14:50 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
10421
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
10421
  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
20842
      SplitString(inspect_publish_uid_string, ',');
52
10421
  inspect_publish_uid.console = false;
53
10421
  inspect_publish_uid.http = false;
54
31261
  for (const std::string& destination : destinations) {
55
20840
    if (destination == "stderr") {
56
10420
      inspect_publish_uid.console = true;
57
10420
    } else if (destination == "http") {
58
10420
      inspect_publish_uid.http = true;
59
    } else {
60
      errors->push_back("--inspect-publish-uid destination can be "
61
                        "stderr or http");
62
    }
63
  }
64
10421
}
65
66
9889
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
67
#if HAVE_OPENSSL
68

9889
  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
9889
  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
9891
  if (use_largepages != "off" &&
89

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

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

10421
  if (has_policy_integrity_string && experimental_policy_integrity.empty()) {
106
1
    errors->push_back("--policy-integrity cannot be empty");
107
  }
108
109
10421
  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
10421
  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

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

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

10421
  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
10421
  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
10421
  if (!cpu_prof) {
147
10410
    if (!cpu_prof_name.empty()) {
148
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
149
    }
150
10410
    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
10410
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
156
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
157
    }
158
  }
159
160


10421
  if (cpu_prof && cpu_prof_dir.empty() && !diagnostic_dir.empty()) {
161
1
      cpu_prof_dir = diagnostic_dir;
162
    }
163
164
10421
  if (!heap_prof) {
165
10410
    if (!heap_prof_name.empty()) {
166
1
      errors->push_back("--heap-prof-name must be used with --heap-prof");
167
    }
168
10410
    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
10410
    if (heap_prof_interval != kDefaultHeapProfInterval) {
174
1
      errors->push_back("--heap-prof-interval must be used with --heap-prof");
175
    }
176
  }
177
178


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


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

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

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

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


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

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

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

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

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

1458292
             .FromMaybe(false) ||
1058

3645730
        info->Set(context, env->value_string(), value).IsNothing() ||
1059

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

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

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

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

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