GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 475 504 94.2 %
Date: 2022-08-12 04:19:25 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
11234
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
11234
  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
22468
      SplitString(inspect_publish_uid_string, ',');
53
11234
  inspect_publish_uid.console = false;
54
11234
  inspect_publish_uid.http = false;
55
33700
  for (const std::string& destination : destinations) {
56
22466
    if (destination == "stderr") {
57
11233
      inspect_publish_uid.console = true;
58
11233
    } else if (destination == "http") {
59
11233
      inspect_publish_uid.http = true;
60
    } else {
61
      errors->push_back("--inspect-publish-uid destination can be "
62
                        "stderr or http");
63
    }
64
  }
65
11234
}
66
67
10684
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
68
#if HAVE_OPENSSL
69

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

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

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

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

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

9
    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

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

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

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


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


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


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
922
4
    return host.substr(1, host.size() - 2);
923
  else
924
108
    return host;
925
}
926
927
100
inline int ParseAndValidatePort(const std::string& port,
928
                                std::vector<std::string>* errors) {
929
  char* endptr;
930
100
  errno = 0;
931
  const unsigned long result =                 // NOLINT(runtime/int)
932
100
    strtoul(port.c_str(), &endptr, 10);
933

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

100
      (result != 0 && result < 1024) || result > 65535) {
935
    errors->push_back(" must be 0 or in range 1024 to 65535.");
936
  }
937
100
  return static_cast<int>(result);
938
}
939
940
100
HostPort SplitHostPort(const std::string& arg,
941
                      std::vector<std::string>* errors) {
942
  // remove_brackets only works if no port is specified
943
  // so if it has an effect only an IPv6 address was specified.
944
200
  std::string host = RemoveBrackets(arg);
945
100
  if (host.length() < arg.length())
946
    return HostPort{host, DebugOptions::kDefaultInspectorPort};
947
948
100
  size_t colon = arg.rfind(':');
949
100
  if (colon == std::string::npos) {
950
    // Either a port number or a host name.  Assume that
951
    // if it's not all decimal digits, it's a host name.
952
390
    for (char c : arg) {
953

302
      if (c < '0' || c > '9') {
954
        return HostPort{arg, DebugOptions::kDefaultInspectorPort};
955
      }
956
    }
957
88
    return HostPort { "", ParseAndValidatePort(arg, errors) };
958
  }
959
  // Host and port found:
960
24
  return HostPort { RemoveBrackets(arg.substr(0, colon)),
961
12
                    ParseAndValidatePort(arg.substr(colon + 1), errors) };
962
}
963
964
1
std::string GetBashCompletion() {
965
2
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
966
1
  const auto& parser = _ppop_instance;
967
968
2
  std::ostringstream out;
969
970
  out << "_node_complete() {\n"
971
         "  local cur_word options\n"
972
         "  cur_word=\"${COMP_WORDS[COMP_CWORD]}\"\n"
973
         "  if [[ \"${cur_word}\" == -* ]] ; then\n"
974
1
         "    COMPREPLY=( $(compgen -W '";
975
976
142
  for (const auto& item : parser.options_) {
977
141
    if (item.first[0] != '[') {
978
138
      out << item.first << " ";
979
    }
980
  }
981
23
  for (const auto& item : parser.aliases_) {
982
22
    if (item.first[0] != '[') {
983
22
      out << item.first << " ";
984
    }
985
  }
986
1
  if (parser.aliases_.size() > 0) {
987
1
    out.seekp(-1, out.cur);  // Strip the trailing space
988
  }
989
990
  out << "' -- \"${cur_word}\") )\n"
991
         "    return 0\n"
992
         "  else\n"
993
         "    COMPREPLY=( $(compgen -f \"${cur_word}\") )\n"
994
         "    return 0\n"
995
         "  fi\n"
996
         "}\n"
997
         "complete -o filenames -o nospace -o bashdefault "
998
1
         "-F _node_complete node node_g";
999
1
  return out.str();
1000
}
1001
1002
// Return a map containing all the options and their metadata as well
1003
// as the aliases
1004
void GetCLIOptions(const FunctionCallbackInfo<Value>& args) {
1005
6664
  Mutex::ScopedLock lock(per_process::cli_options_mutex);
1006
6664
  Environment* env = Environment::GetCurrent(args);
1007
6664
  if (!env->has_run_bootstrapping_code()) {
1008
    // No code because this is an assertion.
1009
    return env->ThrowError(
1010
        "Should not query options before bootstrapping is done");
1011
  }
1012
6664
  env->set_has_serialized_options(true);
1013
1014
6664
  Isolate* isolate = env->isolate();
1015
6664
  Local<Context> context = env->context();
1016
1017
  // Temporarily act as if the current Environment's/IsolateData's options were
1018
  // the default options, i.e. like they are the ones we'd access for global
1019
  // options parsing, so that all options are available from the main parser.
1020
6664
  auto original_per_isolate = per_process::cli_options->per_isolate;
1021
6664
  per_process::cli_options->per_isolate = env->isolate_data()->options();
1022
6664
  auto original_per_env = per_process::cli_options->per_isolate->per_env;
1023
6664
  per_process::cli_options->per_isolate->per_env = env->options();
1024
6664
  auto on_scope_leave = OnScopeLeave([&]() {
1025
6664
    per_process::cli_options->per_isolate->per_env = original_per_env;
1026
6664
    per_process::cli_options->per_isolate = original_per_isolate;
1027
6664
  });
1028
1029
6664
  Local<Map> options = Map::New(isolate);
1030
6664
  if (options
1031
13328
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1032
6664
          .IsNothing()) {
1033
    return;
1034
  }
1035
1036
946288
  for (const auto& item : _ppop_instance.options_) {
1037
    Local<Value> value;
1038
939624
    const auto& option_info = item.second;
1039
939624
    auto field = option_info.field;
1040
939624
    PerProcessOptions* opts = per_process::cli_options.get();
1041


939624
    switch (option_info.type) {
1042
146608
      case kNoOp:
1043
      case kV8Option:
1044
        // Special case for --abort-on-uncaught-exception which is also
1045
        // respected by Node.js internals
1046
146608
        if (item.first == "--abort-on-uncaught-exception") {
1047
6664
          value = Boolean::New(
1048
6664
            isolate, original_per_env->abort_on_uncaught_exception);
1049
        } else {
1050
139944
          value = Undefined(isolate);
1051
        }
1052
146608
        break;
1053
519792
      case kBoolean:
1054
1039584
        value = Boolean::New(isolate,
1055
1039584
                             *_ppop_instance.Lookup<bool>(field, opts));
1056
519792
        break;
1057
26656
      case kInteger:
1058
53312
        value = Number::New(
1059
            isolate,
1060
53312
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1061
26656
        break;
1062
19992
      case kUInteger:
1063
39984
        value = Number::New(
1064
            isolate,
1065
39984
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1066
19992
        break;
1067
186592
      case kString:
1068
373184
        if (!ToV8Value(context,
1069
373184
                       *_ppop_instance.Lookup<std::string>(field, opts))
1070
186592
                 .ToLocal(&value)) {
1071
          return;
1072
        }
1073
186592
        break;
1074
33320
      case kStringList:
1075
66640
        if (!ToV8Value(context,
1076
66640
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1077
33320
                 .ToLocal(&value)) {
1078
          return;
1079
        }
1080
33320
        break;
1081
6664
      case kHostPort: {
1082
        const HostPort& host_port =
1083
6664
          *_ppop_instance.Lookup<HostPort>(field, opts);
1084
6664
        Local<Object> obj = Object::New(isolate);
1085
        Local<Value> host;
1086
6664
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1087

33320
            obj->Set(context, env->host_string(), host).IsNothing() ||
1088
6664
            obj->Set(context,
1089
                     env->port_string(),
1090
26656
                     Integer::New(isolate, host_port.port()))
1091
6664
                .IsNothing()) {
1092
          return;
1093
        }
1094
6664
        value = obj;
1095
6664
        break;
1096
      }
1097
      default:
1098
        UNREACHABLE();
1099
    }
1100
939624
    CHECK(!value.IsEmpty());
1101
1102
939624
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1103
939624
    Local<Object> info = Object::New(isolate);
1104
    Local<Value> help_text;
1105
939624
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1106
1879248
        !info->Set(context, env->help_text_string(), help_text)
1107

1879248
             .FromMaybe(false) ||
1108
1879248
        !info->Set(context,
1109
                   env->env_var_settings_string(),
1110
                   Integer::New(isolate,
1111
2818872
                                static_cast<int>(option_info.env_setting)))
1112

1879248
             .FromMaybe(false) ||
1113
1879248
        !info->Set(context,
1114
                   env->type_string(),
1115
2818872
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1116

1879248
             .FromMaybe(false) ||
1117
1879248
        !info->Set(context,
1118
                   env->default_is_true_string(),
1119
2818872
                   Boolean::New(isolate, option_info.default_is_true))
1120

1879248
             .FromMaybe(false) ||
1121

4698120
        info->Set(context, env->value_string(), value).IsNothing() ||
1122

2818872
        options->Set(context, name, info).IsEmpty()) {
1123
      return;
1124
    }
1125
  }
1126
1127
  Local<Value> aliases;
1128
13328
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1129
1130
6664
  if (aliases.As<Object>()
1131
13328
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1132
6664
          .IsNothing()) {
1133
    return;
1134
  }
1135
1136
6664
  Local<Object> ret = Object::New(isolate);
1137
26656
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1138

26656
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1139
    return;
1140
  }
1141
1142
13328
  args.GetReturnValue().Set(ret);
1143
}
1144
1145
6062
void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
1146
6062
  Environment* env = Environment::GetCurrent(args);
1147
6062
  if (!env->has_run_bootstrapping_code()) {
1148
    // No code because this is an assertion.
1149
    return env->ThrowError(
1150
        "Should not query options before bootstrapping is done");
1151
  }
1152
6062
  Isolate* isolate = args.GetIsolate();
1153
6062
  Local<Context> context = env->context();
1154
6062
  Local<Object> ret = Object::New(isolate);
1155
1156
12124
  if (ret->Set(context,
1157
           FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1158
18186
           Boolean::New(isolate, env->should_not_register_esm_loader()))
1159
6062
      .IsNothing()) return;
1160
1161
12124
  if (ret->Set(context,
1162
           FIXED_ONE_BYTE_STRING(env->isolate(), "noGlobalSearchPaths"),
1163
18186
           Boolean::New(isolate, env->no_global_search_paths()))
1164
6062
      .IsNothing()) return;
1165
1166
12124
  args.GetReturnValue().Set(ret);
1167
}
1168
1169
771
void Initialize(Local<Object> target,
1170
                Local<Value> unused,
1171
                Local<Context> context,
1172
                void* priv) {
1173
771
  Environment* env = Environment::GetCurrent(context);
1174
771
  Isolate* isolate = env->isolate();
1175
771
  SetMethodNoSideEffect(context, target, "getCLIOptions", GetCLIOptions);
1176
771
  SetMethodNoSideEffect(
1177
      context, target, "getEmbedderOptions", GetEmbedderOptions);
1178
1179
771
  Local<Object> env_settings = Object::New(isolate);
1180
2313
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment);
1181
2313
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvironment);
1182
  target
1183
771
      ->Set(
1184
1542
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1185
      .Check();
1186
1187
771
  Local<Object> types = Object::New(isolate);
1188
2313
  NODE_DEFINE_CONSTANT(types, kNoOp);
1189
2313
  NODE_DEFINE_CONSTANT(types, kV8Option);
1190
2313
  NODE_DEFINE_CONSTANT(types, kBoolean);
1191
2313
  NODE_DEFINE_CONSTANT(types, kInteger);
1192
2313
  NODE_DEFINE_CONSTANT(types, kUInteger);
1193
2313
  NODE_DEFINE_CONSTANT(types, kString);
1194
2313
  NODE_DEFINE_CONSTANT(types, kHostPort);
1195
2313
  NODE_DEFINE_CONSTANT(types, kStringList);
1196
1542
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1197
      .Check();
1198
771
}
1199
1200
5337
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1201
5337
  registry->Register(GetCLIOptions);
1202
5337
  registry->Register(GetEmbedderOptions);
1203
5337
}
1204
}  // namespace options_parser
1205
1206
5409
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1207
5409
  HandleEnvOptions(env_options, [](const char* name) {
1208
21636
    std::string text;
1209

21636
    return credentials::SafeGetenv(name, &text) ? text : "";
1210
  });
1211
5409
}
1212
1213
5686
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1214
                      std::function<std::string(const char*)> opt_getter) {
1215
5686
  env_options->pending_deprecation =
1216
11372
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1217
1218
5686
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1219
1220
5686
  env_options->preserve_symlinks_main =
1221
11372
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1222
1223
5686
  if (env_options->redirect_warnings.empty())
1224
5686
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1225
5686
}
1226
1227
5568
std::vector<std::string> ParseNodeOptionsEnvVar(
1228
    const std::string& node_options, std::vector<std::string>* errors) {
1229
5568
  std::vector<std::string> env_argv;
1230
1231
5568
  bool is_in_string = false;
1232
5568
  bool will_start_new_arg = true;
1233
8172
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1234
2604
    char c = node_options.at(index);
1235
1236
    // Backslashes escape the following character
1237

2604
    if (c == '\\' && is_in_string) {
1238
      if (index + 1 == node_options.size()) {
1239
        errors->push_back("invalid value for NODE_OPTIONS "
1240
                          "(invalid escape)\n");
1241
        return env_argv;
1242
      } else {
1243
        c = node_options.at(++index);
1244
      }
1245

2604
    } else if (c == ' ' && !is_in_string) {
1246
32
      will_start_new_arg = true;
1247
32
      continue;
1248
2572
    } else if (c == '"') {
1249
4
      is_in_string = !is_in_string;
1250
4
      continue;
1251
    }
1252
1253
2568
    if (will_start_new_arg) {
1254
108
      env_argv.emplace_back(std::string(1, c));
1255
108
      will_start_new_arg = false;
1256
    } else {
1257
2460
      env_argv.back() += c;
1258
    }
1259
  }
1260
1261
5568
  if (is_in_string) {
1262
    errors->push_back("invalid value for NODE_OPTIONS "
1263
                      "(unterminated string)\n");
1264
  }
1265
5568
  return env_argv;
1266
}
1267
}  // namespace node
1268
1269
5409
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1270
5337
NODE_MODULE_EXTERNAL_REFERENCE(options,
1271
                               node::options_parser::RegisterExternalReferences)