GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 472 501 94.2 %
Date: 2022-07-28 04:16:57 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
11162
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
11162
  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
22324
      SplitString(inspect_publish_uid_string, ',');
53
11162
  inspect_publish_uid.console = false;
54
11162
  inspect_publish_uid.http = false;
55
33484
  for (const std::string& destination : destinations) {
56
22322
    if (destination == "stderr") {
57
11161
      inspect_publish_uid.console = true;
58
11161
    } else if (destination == "http") {
59
11161
      inspect_publish_uid.http = true;
60
    } else {
61
      errors->push_back("--inspect-publish-uid destination can be "
62
                        "stderr or http");
63
    }
64
  }
65
11162
}
66
67
10576
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
68
#if HAVE_OPENSSL
69

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

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

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

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

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

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

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

11162
  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
11162
  if (heap_snapshot_near_heap_limit < 0) {
143
    errors->push_back("--heap-snapshot-near-heap-limit must not be negative");
144
  }
145
146
11162
  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
11162
  if (!cpu_prof) {
166
11151
    if (!cpu_prof_name.empty()) {
167
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
168
    }
169
11151
    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
11151
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
175
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
176
    }
177
  }
178
179


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


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


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
906
4
    return host.substr(1, host.size() - 2);
907
  else
908
108
    return host;
909
}
910
911
100
inline int ParseAndValidatePort(const std::string& port,
912
                                std::vector<std::string>* errors) {
913
  char* endptr;
914
100
  errno = 0;
915
  const unsigned long result =                 // NOLINT(runtime/int)
916
100
    strtoul(port.c_str(), &endptr, 10);
917

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

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

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


981594
    switch (option_info.type) {
1026
156486
      case kNoOp:
1027
      case kV8Option:
1028
        // Special case for --abort-on-uncaught-exception which is also
1029
        // respected by Node.js internals
1030
156486
        if (item.first == "--abort-on-uncaught-exception") {
1031
7113
          value = Boolean::New(
1032
7113
            isolate, original_per_env->abort_on_uncaught_exception);
1033
        } else {
1034
149373
          value = Undefined(isolate);
1035
        }
1036
156486
        break;
1037
547701
      case kBoolean:
1038
1095402
        value = Boolean::New(isolate,
1039
1095402
                             *_ppop_instance.Lookup<bool>(field, opts));
1040
547701
        break;
1041
28452
      case kInteger:
1042
56904
        value = Number::New(
1043
            isolate,
1044
56904
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
1045
28452
        break;
1046
21339
      case kUInteger:
1047
42678
        value = Number::New(
1048
            isolate,
1049
42678
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
1050
21339
        break;
1051
192051
      case kString:
1052
384102
        if (!ToV8Value(context,
1053
384102
                       *_ppop_instance.Lookup<std::string>(field, opts))
1054
192051
                 .ToLocal(&value)) {
1055
          return;
1056
        }
1057
192051
        break;
1058
28452
      case kStringList:
1059
56904
        if (!ToV8Value(context,
1060
56904
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1061
28452
                 .ToLocal(&value)) {
1062
          return;
1063
        }
1064
28452
        break;
1065
7113
      case kHostPort: {
1066
        const HostPort& host_port =
1067
7113
          *_ppop_instance.Lookup<HostPort>(field, opts);
1068
7113
        Local<Object> obj = Object::New(isolate);
1069
        Local<Value> host;
1070
7113
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1071

35565
            obj->Set(context, env->host_string(), host).IsNothing() ||
1072
7113
            obj->Set(context,
1073
                     env->port_string(),
1074
28452
                     Integer::New(isolate, host_port.port()))
1075
7113
                .IsNothing()) {
1076
          return;
1077
        }
1078
7113
        value = obj;
1079
7113
        break;
1080
      }
1081
      default:
1082
        UNREACHABLE();
1083
    }
1084
981594
    CHECK(!value.IsEmpty());
1085
1086
981594
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1087
981594
    Local<Object> info = Object::New(isolate);
1088
    Local<Value> help_text;
1089
981594
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1090
1963188
        !info->Set(context, env->help_text_string(), help_text)
1091

1963188
             .FromMaybe(false) ||
1092
1963188
        !info->Set(context,
1093
                   env->env_var_settings_string(),
1094
                   Integer::New(isolate,
1095
2944782
                                static_cast<int>(option_info.env_setting)))
1096

1963188
             .FromMaybe(false) ||
1097
1963188
        !info->Set(context,
1098
                   env->type_string(),
1099
2944782
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1100

1963188
             .FromMaybe(false) ||
1101
1963188
        !info->Set(context,
1102
                   env->default_is_true_string(),
1103
2944782
                   Boolean::New(isolate, option_info.default_is_true))
1104

1963188
             .FromMaybe(false) ||
1105

4907970
        info->Set(context, env->value_string(), value).IsNothing() ||
1106

2944782
        options->Set(context, name, info).IsEmpty()) {
1107
      return;
1108
    }
1109
  }
1110
1111
  Local<Value> aliases;
1112
14226
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1113
1114
7113
  if (aliases.As<Object>()
1115
14226
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1116
7113
          .IsNothing()) {
1117
    return;
1118
  }
1119
1120
7113
  Local<Object> ret = Object::New(isolate);
1121
28452
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1122

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

21420
    return credentials::SafeGetenv(name, &text) ? text : "";
1193
  });
1194
5355
}
1195
1196
5650
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1197
                      std::function<std::string(const char*)> opt_getter) {
1198
5650
  env_options->pending_deprecation =
1199
11300
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1200
1201
5650
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1202
1203
5650
  env_options->preserve_symlinks_main =
1204
11300
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1205
1206
5650
  if (env_options->redirect_warnings.empty())
1207
5650
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1208
5650
}
1209
1210
5532
std::vector<std::string> ParseNodeOptionsEnvVar(
1211
    const std::string& node_options, std::vector<std::string>* errors) {
1212
5532
  std::vector<std::string> env_argv;
1213
1214
5532
  bool is_in_string = false;
1215
5532
  bool will_start_new_arg = true;
1216
8136
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1217
2604
    char c = node_options.at(index);
1218
1219
    // Backslashes escape the following character
1220

2604
    if (c == '\\' && is_in_string) {
1221
      if (index + 1 == node_options.size()) {
1222
        errors->push_back("invalid value for NODE_OPTIONS "
1223
                          "(invalid escape)\n");
1224
        return env_argv;
1225
      } else {
1226
        c = node_options.at(++index);
1227
      }
1228

2604
    } else if (c == ' ' && !is_in_string) {
1229
32
      will_start_new_arg = true;
1230
32
      continue;
1231
2572
    } else if (c == '"') {
1232
4
      is_in_string = !is_in_string;
1233
4
      continue;
1234
    }
1235
1236
2568
    if (will_start_new_arg) {
1237
108
      env_argv.emplace_back(std::string(1, c));
1238
108
      will_start_new_arg = false;
1239
    } else {
1240
2460
      env_argv.back() += c;
1241
    }
1242
  }
1243
1244
5532
  if (is_in_string) {
1245
    errors->push_back("invalid value for NODE_OPTIONS "
1246
                      "(unterminated string)\n");
1247
  }
1248
5532
  return env_argv;
1249
}
1250
}  // namespace node
1251
1252
5355
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)
1253
5287
NODE_MODULE_EXTERNAL_REFERENCE(options,
1254
                               node::options_parser::RegisterExternalReferences)