GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 470 499 94.2 %
Date: 2022-05-31 04:15:47 Branches: 214 274 78.1 %

Line Branch Exec Source
1
#include "node_options.h"  // NOLINT(build/include_inline)
2
#include "node_options-inl.h"
3
4
#include "env-inl.h"
5
#include "node_binding.h"
6
#include "node_external_reference.h"
7
#include "node_internals.h"
8
#if HAVE_OPENSSL
9
#include "openssl/opensslv.h"
10
#endif
11
12
#include <errno.h>
13
#include <sstream>
14
#include <limits>
15
#include <algorithm>
16
#include <cstdlib>  // strtoul, errno
17
18
using v8::Boolean;
19
using v8::Context;
20
using v8::FunctionCallbackInfo;
21
using v8::Integer;
22
using v8::Isolate;
23
using v8::Local;
24
using v8::Map;
25
using v8::Number;
26
using v8::Object;
27
using v8::Undefined;
28
using v8::Value;
29
30
namespace node {
31
32
namespace per_process {
33
Mutex cli_options_mutex;
34
std::shared_ptr<PerProcessOptions> cli_options{new PerProcessOptions()};
35
}  // namespace per_process
36
37
10952
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
10952
  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
21904
      SplitString(inspect_publish_uid_string, ',');
53
10952
  inspect_publish_uid.console = false;
54
10952
  inspect_publish_uid.http = false;
55
32854
  for (const std::string& destination : destinations) {
56
21902
    if (destination == "stderr") {
57
10951
      inspect_publish_uid.console = true;
58
10951
    } else if (destination == "http") {
59
10951
      inspect_publish_uid.http = true;
60
    } else {
61
      errors->push_back("--inspect-publish-uid destination can be "
62
                        "stderr or http");
63
    }
64
  }
65
10952
}
66
67
10404
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
68
#if HAVE_OPENSSL
69

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

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

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

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

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

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

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

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


10952
  if (cpu_prof && cpu_prof_dir.empty() && !diagnostic_dir.empty()) {
180
1
      cpu_prof_dir = diagnostic_dir;
181
    }
182
183
10952
  if (!heap_prof) {
184
10941
    if (!heap_prof_name.empty()) {
185
1
      errors->push_back("--heap-prof-name must be used with --heap-prof");
186
    }
187
10941
    if (!heap_prof_dir.empty()) {
188
1
      errors->push_back("--heap-prof-dir must be used with --heap-prof");
189
    }
190
    // We can't catch the case where the value passed is the default value,
191
    // then the option just becomes a noop which is fine.
192
10941
    if (heap_prof_interval != kDefaultHeapProfInterval) {
193
1
      errors->push_back("--heap-prof-interval must be used with --heap-prof");
194
    }
195
  }
196
197


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


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
898
4
    return host.substr(1, host.size() - 2);
899
  else
900
108
    return host;
901
}
902
903
100
inline int ParseAndValidatePort(const std::string& port,
904
                                std::vector<std::string>* errors) {
905
  char* endptr;
906
100
  errno = 0;
907
  const unsigned long result =                 // NOLINT(runtime/int)
908
100
    strtoul(port.c_str(), &endptr, 10);
909

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

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

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


891752
    switch (option_info.type) {
1018
144254
      case kNoOp:
1019
      case kV8Option:
1020
        // Special case for --abort-on-uncaught-exception which is also
1021
        // respected by Node.js internals
1022
144254
        if (item.first == "--abort-on-uncaught-exception") {
1023
6557
          value = Boolean::New(
1024
6557
            isolate, original_per_env->abort_on_uncaught_exception);
1025
        } else {
1026
137697
          value = Undefined(isolate);
1027
        }
1028
144254
        break;
1029
491775
      case kBoolean:
1030
983550
        value = Boolean::New(isolate,
1031
983550
                             *_ppop_instance.Lookup<bool>(field, opts));
1032
491775
        break;
1033
26228
      case kInteger:
1034
52456
        value = Number::New(
1035
            isolate,
1036
52456
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1037
26228
        break;
1038
19671
      case kUInteger:
1039
39342
        value = Number::New(
1040
            isolate,
1041
39342
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1042
19671
        break;
1043
177039
      case kString:
1044
354078
        if (!ToV8Value(context,
1045
354078
                       *_ppop_instance.Lookup<std::string>(field, opts))
1046
177039
                 .ToLocal(&value)) {
1047
          return;
1048
        }
1049
177039
        break;
1050
26228
      case kStringList:
1051
52456
        if (!ToV8Value(context,
1052
52456
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1053
26228
                 .ToLocal(&value)) {
1054
          return;
1055
        }
1056
26228
        break;
1057
6557
      case kHostPort: {
1058
        const HostPort& host_port =
1059
6557
          *_ppop_instance.Lookup<HostPort>(field, opts);
1060
6557
        Local<Object> obj = Object::New(isolate);
1061
        Local<Value> host;
1062
6557
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1063

32785
            obj->Set(context, env->host_string(), host).IsNothing() ||
1064
6557
            obj->Set(context,
1065
                     env->port_string(),
1066
26228
                     Integer::New(isolate, host_port.port()))
1067
6557
                .IsNothing()) {
1068
          return;
1069
        }
1070
6557
        value = obj;
1071
6557
        break;
1072
      }
1073
      default:
1074
        UNREACHABLE();
1075
    }
1076
891752
    CHECK(!value.IsEmpty());
1077
1078
891752
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1079
891752
    Local<Object> info = Object::New(isolate);
1080
    Local<Value> help_text;
1081
891752
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1082
1783504
        !info->Set(context, env->help_text_string(), help_text)
1083

1783504
             .FromMaybe(false) ||
1084
1783504
        !info->Set(context,
1085
                   env->env_var_settings_string(),
1086
                   Integer::New(isolate,
1087
2675256
                                static_cast<int>(option_info.env_setting)))
1088

1783504
             .FromMaybe(false) ||
1089
1783504
        !info->Set(context,
1090
                   env->type_string(),
1091
2675256
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1092

1783504
             .FromMaybe(false) ||
1093
1783504
        !info->Set(context,
1094
                   env->default_is_true_string(),
1095
2675256
                   Boolean::New(isolate, option_info.default_is_true))
1096

1783504
             .FromMaybe(false) ||
1097

4458760
        info->Set(context, env->value_string(), value).IsNothing() ||
1098

2675256
        options->Set(context, name, info).IsEmpty()) {
1099
      return;
1100
    }
1101
  }
1102
1103
  Local<Value> aliases;
1104
13114
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1105
1106
6557
  if (aliases.As<Object>()
1107
13114
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1108
6557
          .IsNothing()) {
1109
    return;
1110
  }
1111
1112
6557
  Local<Object> ret = Object::New(isolate);
1113
26228
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1114

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

21076
    return credentials::SafeGetenv(name, &text) ? text : "";
1185
  });
1186
5269
}
1187
1188
5545
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1189
                      std::function<std::string(const char*)> opt_getter) {
1190
5545
  env_options->pending_deprecation =
1191
11090
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1192
1193
5545
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1194
1195
5545
  env_options->preserve_symlinks_main =
1196
11090
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1197
1198
5545
  if (env_options->redirect_warnings.empty())
1199
5545
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1200
5545
}
1201
1202
5427
std::vector<std::string> ParseNodeOptionsEnvVar(
1203
    const std::string& node_options, std::vector<std::string>* errors) {
1204
5427
  std::vector<std::string> env_argv;
1205
1206
5427
  bool is_in_string = false;
1207
5427
  bool will_start_new_arg = true;
1208
8031
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1209
2604
    char c = node_options.at(index);
1210
1211
    // Backslashes escape the following character
1212

2604
    if (c == '\\' && is_in_string) {
1213
      if (index + 1 == node_options.size()) {
1214
        errors->push_back("invalid value for NODE_OPTIONS "
1215
                          "(invalid escape)\n");
1216
        return env_argv;
1217
      } else {
1218
        c = node_options.at(++index);
1219
      }
1220

2604
    } else if (c == ' ' && !is_in_string) {
1221
32
      will_start_new_arg = true;
1222
32
      continue;
1223
2572
    } else if (c == '"') {
1224
4
      is_in_string = !is_in_string;
1225
4
      continue;
1226
    }
1227
1228
2568
    if (will_start_new_arg) {
1229
108
      env_argv.emplace_back(std::string(1, c));
1230
108
      will_start_new_arg = false;
1231
    } else {
1232
2460
      env_argv.back() += c;
1233
    }
1234
  }
1235
1236
5427
  if (is_in_string) {
1237
    errors->push_back("invalid value for NODE_OPTIONS "
1238
                      "(unterminated string)\n");
1239
  }
1240
5427
  return env_argv;
1241
}
1242
}  // namespace node
1243
1244
5269
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1245
5201
NODE_MODULE_EXTERNAL_REFERENCE(options,
1246
                               node::options_parser::RegisterExternalReferences)