GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 450 479 93.9 %
Date: 2022-02-12 04:14:26 Branches: 204 264 77.3 %

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

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

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

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

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

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

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

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

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

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


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


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


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

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

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

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


720720
    switch (option_info.type) {
974
116424
      case kNoOp:
975
      case kV8Option:
976
        // Special case for --abort-on-uncaught-exception which is also
977
        // respected by Node.js internals
978
116424
        if (item.first == "--abort-on-uncaught-exception") {
979
5544
          value = Boolean::New(
980
5544
            isolate, original_per_env->abort_on_uncaught_exception);
981
        } else {
982
110880
          value = Undefined(isolate);
983
        }
984
116424
        break;
985
388080
      case kBoolean:
986
776160
        value = Boolean::New(isolate,
987
776160
                             *_ppop_instance.Lookup<bool>(field, opts));
988
388080
        break;
989
22176
      case kInteger:
990
44352
        value = Number::New(
991
            isolate,
992
44352
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
993
22176
        break;
994
16632
      case kUInteger:
995
33264
        value = Number::New(
996
            isolate,
997
33264
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
998
16632
        break;
999
155232
      case kString:
1000
310464
        if (!ToV8Value(context,
1001
310464
                       *_ppop_instance.Lookup<std::string>(field, opts))
1002
155232
                 .ToLocal(&value)) {
1003
          return;
1004
        }
1005
155232
        break;
1006
16632
      case kStringList:
1007
33264
        if (!ToV8Value(context,
1008
33264
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1009
16632
                 .ToLocal(&value)) {
1010
          return;
1011
        }
1012
16632
        break;
1013
5544
      case kHostPort: {
1014
        const HostPort& host_port =
1015
5544
          *_ppop_instance.Lookup<HostPort>(field, opts);
1016
5544
        Local<Object> obj = Object::New(isolate);
1017
        Local<Value> host;
1018
5544
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1019

27720
            obj->Set(context, env->host_string(), host).IsNothing() ||
1020
5544
            obj->Set(context,
1021
                     env->port_string(),
1022
22176
                     Integer::New(isolate, host_port.port()))
1023
5544
                .IsNothing()) {
1024
          return;
1025
        }
1026
5544
        value = obj;
1027
5544
        break;
1028
      }
1029
      default:
1030
        UNREACHABLE();
1031
    }
1032
720720
    CHECK(!value.IsEmpty());
1033
1034
720720
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1035
720720
    Local<Object> info = Object::New(isolate);
1036
    Local<Value> help_text;
1037
720720
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1038
1441440
        !info->Set(context, env->help_text_string(), help_text)
1039

1441440
             .FromMaybe(false) ||
1040
1441440
        !info->Set(context,
1041
                   env->env_var_settings_string(),
1042
                   Integer::New(isolate,
1043
2162160
                                static_cast<int>(option_info.env_setting)))
1044

1441440
             .FromMaybe(false) ||
1045
1441440
        !info->Set(context,
1046
                   env->type_string(),
1047
2162160
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1048

1441440
             .FromMaybe(false) ||
1049
1441440
        !info->Set(context,
1050
                   env->default_is_true_string(),
1051
2162160
                   Boolean::New(isolate, option_info.default_is_true))
1052

1441440
             .FromMaybe(false) ||
1053

3603600
        info->Set(context, env->value_string(), value).IsNothing() ||
1054

2162160
        options->Set(context, name, info).IsEmpty()) {
1055
      return;
1056
    }
1057
  }
1058
1059
  Local<Value> aliases;
1060
11088
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1061
1062
5544
  if (aliases.As<Object>()
1063
11088
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1064
5544
          .IsNothing()) {
1065
    return;
1066
  }
1067
1068
5544
  Local<Object> ret = Object::New(isolate);
1069
22176
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1070

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

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

2604
    if (c == '\\' && is_in_string) {
1165
      if (index + 1 == node_options.size()) {
1166
        errors->push_back("invalid value for NODE_OPTIONS "
1167
                          "(invalid escape)\n");
1168
        return env_argv;
1169
      } else {
1170
        c = node_options.at(++index);
1171
      }
1172

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