GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 453 486 93.2 %
Date: 2022-04-01 04:15:00 Branches: 200 264 75.8 %

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

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

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

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

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

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

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

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

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

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


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


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


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

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

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

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


776424
    switch (option_info.type) {
985
123522
      case kNoOp:
986
      case kV8Option:
987
        // Special case for --abort-on-uncaught-exception which is also
988
        // respected by Node.js internals
989
123522
        if (item.first == "--abort-on-uncaught-exception") {
990
5882
          value = Boolean::New(
991
5882
            isolate, original_per_env->abort_on_uncaught_exception);
992
        } else {
993
117640
          value = Undefined(isolate);
994
        }
995
123522
        break;
996
423504
      case kBoolean:
997
847008
        value = Boolean::New(isolate,
998
847008
                             *_ppop_instance.Lookup<bool>(field, opts));
999
423504
        break;
1000
23528
      case kInteger:
1001
47056
        value = Number::New(
1002
            isolate,
1003
47056
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1004
23528
        break;
1005
17646
      case kUInteger:
1006
35292
        value = Number::New(
1007
            isolate,
1008
35292
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1009
17646
        break;
1010
164696
      case kString:
1011
329392
        if (!ToV8Value(context,
1012
329392
                       *_ppop_instance.Lookup<std::string>(field, opts))
1013
164696
                 .ToLocal(&value)) {
1014
          return;
1015
        }
1016
164696
        break;
1017
17646
      case kStringList:
1018
35292
        if (!ToV8Value(context,
1019
35292
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1020
17646
                 .ToLocal(&value)) {
1021
          return;
1022
        }
1023
17646
        break;
1024
5882
      case kHostPort: {
1025
        const HostPort& host_port =
1026
5882
          *_ppop_instance.Lookup<HostPort>(field, opts);
1027
5882
        Local<Object> obj = Object::New(isolate);
1028
        Local<Value> host;
1029
5882
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1030

29410
            obj->Set(context, env->host_string(), host).IsNothing() ||
1031
5882
            obj->Set(context,
1032
                     env->port_string(),
1033
23528
                     Integer::New(isolate, host_port.port()))
1034
5882
                .IsNothing()) {
1035
          return;
1036
        }
1037
5882
        value = obj;
1038
5882
        break;
1039
      }
1040
      default:
1041
        UNREACHABLE();
1042
    }
1043
776424
    CHECK(!value.IsEmpty());
1044
1045
776424
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1046
776424
    Local<Object> info = Object::New(isolate);
1047
    Local<Value> help_text;
1048
776424
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1049
1552848
        !info->Set(context, env->help_text_string(), help_text)
1050

1552848
             .FromMaybe(false) ||
1051
1552848
        !info->Set(context,
1052
                   env->env_var_settings_string(),
1053
                   Integer::New(isolate,
1054
2329272
                                static_cast<int>(option_info.env_setting)))
1055

1552848
             .FromMaybe(false) ||
1056
1552848
        !info->Set(context,
1057
                   env->type_string(),
1058
2329272
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1059

1552848
             .FromMaybe(false) ||
1060
1552848
        !info->Set(context,
1061
                   env->default_is_true_string(),
1062
2329272
                   Boolean::New(isolate, option_info.default_is_true))
1063

1552848
             .FromMaybe(false) ||
1064

3882120
        info->Set(context, env->value_string(), value).IsNothing() ||
1065

2329272
        options->Set(context, name, info).IsEmpty()) {
1066
      return;
1067
    }
1068
  }
1069
1070
  Local<Value> aliases;
1071
11764
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1072
1073
5882
  if (aliases.As<Object>()
1074
11764
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1075
5882
          .IsNothing()) {
1076
    return;
1077
  }
1078
1079
5882
  Local<Object> ret = Object::New(isolate);
1080
23528
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1081

23528
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1082
    return;
1083
  }
1084
1085
11764
  args.GetReturnValue().Set(ret);
1086
}
1087
1088
5489
void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
1089
5489
  Environment* env = Environment::GetCurrent(args);
1090
5489
  if (!env->has_run_bootstrapping_code()) {
1091
    // No code because this is an assertion.
1092
    return env->ThrowError(
1093
        "Should not query options before bootstrapping is done");
1094
  }
1095
5489
  Isolate* isolate = args.GetIsolate();
1096
5489
  Local<Context> context = env->context();
1097
5489
  Local<Object> ret = Object::New(isolate);
1098
1099
10978
  if (ret->Set(context,
1100
           FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1101
16467
           Boolean::New(isolate, env->should_not_register_esm_loader()))
1102
5489
      .IsNothing()) return;
1103
1104
10978
  if (ret->Set(context,
1105
           FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"),
1106
16467
           Boolean::New(isolate, env->no_global_search_paths()))
1107
5489
      .IsNothing()) return;
1108
1109
10978
  args.GetReturnValue().Set(ret);
1110
}
1111
1112
621
void Initialize(Local<Object> target,
1113
                Local<Value> unused,
1114
                Local<Context> context,
1115
                void* priv) {
1116
621
  Environment* env = Environment::GetCurrent(context);
1117
621
  Isolate* isolate = env->isolate();
1118
621
  env->SetMethodNoSideEffect(target, "getCLIOptions", GetCLIOptions);
1119
621
  env->SetMethodNoSideEffect(target, "getEmbedderOptions", GetEmbedderOptions);
1120
1121
621
  Local<Object> env_settings = Object::New(isolate);
1122
1863
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment);
1123
1863
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvironment);
1124
  target
1125
621
      ->Set(
1126
1242
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1127
      .Check();
1128
1129
621
  Local<Object> types = Object::New(isolate);
1130
1863
  NODE_DEFINE_CONSTANT(types, kNoOp);
1131
1863
  NODE_DEFINE_CONSTANT(types, kV8Option);
1132
1863
  NODE_DEFINE_CONSTANT(types, kBoolean);
1133
1863
  NODE_DEFINE_CONSTANT(types, kInteger);
1134
1863
  NODE_DEFINE_CONSTANT(types, kUInteger);
1135
1863
  NODE_DEFINE_CONSTANT(types, kString);
1136
1863
  NODE_DEFINE_CONSTANT(types, kHostPort);
1137
1863
  NODE_DEFINE_CONSTANT(types, kStringList);
1138
1242
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1139
      .Check();
1140
621
}
1141
1142
4912
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1143
4912
  registry->Register(GetCLIOptions);
1144
4912
  registry->Register(GetEmbedderOptions);
1145
4912
}
1146
}  // namespace options_parser
1147
1148
4969
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1149
4969
  HandleEnvOptions(env_options, [](const char* name) {
1150
19876
    std::string text;
1151

19876
    return credentials::SafeGetenv(name, &text) ? text : "";
1152
  });
1153
4969
}
1154
1155
5237
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1156
                      std::function<std::string(const char*)> opt_getter) {
1157
5237
  env_options->pending_deprecation =
1158
10474
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1159
1160
5237
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1161
1162
5237
  env_options->preserve_symlinks_main =
1163
10474
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1164
1165
5237
  if (env_options->redirect_warnings.empty())
1166
5237
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1167
5237
}
1168
1169
5120
std::vector<std::string> ParseNodeOptionsEnvVar(
1170
    const std::string& node_options, std::vector<std::string>* errors) {
1171
5120
  std::vector<std::string> env_argv;
1172
1173
5120
  bool is_in_string = false;
1174
5120
  bool will_start_new_arg = true;
1175
7724
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1176
2604
    char c = node_options.at(index);
1177
1178
    // Backslashes escape the following character
1179

2604
    if (c == '\\' && is_in_string) {
1180
      if (index + 1 == node_options.size()) {
1181
        errors->push_back("invalid value for NODE_OPTIONS "
1182
                          "(invalid escape)\n");
1183
        return env_argv;
1184
      } else {
1185
        c = node_options.at(++index);
1186
      }
1187

2604
    } else if (c == ' ' && !is_in_string) {
1188
32
      will_start_new_arg = true;
1189
32
      continue;
1190
2572
    } else if (c == '"') {
1191
4
      is_in_string = !is_in_string;
1192
4
      continue;
1193
    }
1194
1195
2568
    if (will_start_new_arg) {
1196
108
      env_argv.emplace_back(std::string(1, c));
1197
108
      will_start_new_arg = false;
1198
    } else {
1199
2460
      env_argv.back() += c;
1200
    }
1201
  }
1202
1203
5120
  if (is_in_string) {
1204
    errors->push_back("invalid value for NODE_OPTIONS "
1205
                      "(unterminated string)\n");
1206
  }
1207
5120
  return env_argv;
1208
}
1209
}  // namespace node
1210
1211
4969
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1212
4912
NODE_MODULE_EXTERNAL_REFERENCE(options,
1213
                               node::options_parser::RegisterExternalReferences)