GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 448 477 93.9 %
Date: 2022-02-01 04:14:12 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
10366
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
10366
  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
20732
      SplitString(inspect_publish_uid_string, ',');
52
10366
  inspect_publish_uid.console = false;
53
10366
  inspect_publish_uid.http = false;
54
31096
  for (const std::string& destination : destinations) {
55
20730
    if (destination == "stderr") {
56
10365
      inspect_publish_uid.console = true;
57
10365
    } else if (destination == "http") {
58
10365
      inspect_publish_uid.http = true;
59
    } else {
60
      errors->push_back("--inspect-publish-uid destination can be "
61
                        "stderr or http");
62
    }
63
  }
64
10366
}
65
66
9840
void PerProcessOptions::CheckOptions(std::vector<std::string>* errors) {
67
#if HAVE_OPENSSL
68

9840
  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
9840
  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
9842
  if (use_largepages != "off" &&
89

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

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

10366
  if (has_policy_integrity_string && experimental_policy_integrity.empty()) {
106
1
    errors->push_back("--policy-integrity cannot be empty");
107
  }
108
109
10366
  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
10366
  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

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

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

10366
  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
10366
  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
10366
  if (!cpu_prof) {
147
10355
    if (!cpu_prof_name.empty()) {
148
1
      errors->push_back("--cpu-prof-name must be used with --cpu-prof");
149
    }
150
10355
    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
10355
    if (cpu_prof_interval != kDefaultCpuProfInterval) {
156
1
      errors->push_back("--cpu-prof-interval must be used with --cpu-prof");
157
    }
158
  }
159
160


10366
  if (cpu_prof && cpu_prof_dir.empty() && !diagnostic_dir.empty()) {
161
1
      cpu_prof_dir = diagnostic_dir;
162
    }
163
164
10366
  if (!heap_prof) {
165
10355
    if (!heap_prof_name.empty()) {
166
1
      errors->push_back("--heap-prof-name must be used with --heap-prof");
167
    }
168
10355
    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
10355
    if (heap_prof_interval != kDefaultHeapProfInterval) {
174
1
      errors->push_back("--heap-prof-interval must be used with --heap-prof");
175
    }
176
  }
177
178


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


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
846
4
    return host.substr(1, host.size() - 2);
847
  else
848
108
    return host;
849
}
850
851
100
inline int ParseAndValidatePort(const std::string& port,
852
                                std::vector<std::string>* errors) {
853
  char* endptr;
854
100
  errno = 0;
855
  const unsigned long result =                 // NOLINT(runtime/int)
856
100
    strtoul(port.c_str(), &endptr, 10);
857

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

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

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


707840
    switch (option_info.type) {
966
116130
      case kNoOp:
967
      case kV8Option:
968
        // Special case for --abort-on-uncaught-exception which is also
969
        // respected by Node.js internals
970
116130
        if (item.first == "--abort-on-uncaught-exception") {
971
5530
          value = Boolean::New(
972
5530
            isolate, original_per_env->abort_on_uncaught_exception);
973
        } else {
974
110600
          value = Undefined(isolate);
975
        }
976
116130
        break;
977
376040
      case kBoolean:
978
752080
        value = Boolean::New(isolate,
979
752080
                             *_ppop_instance.Lookup<bool>(field, opts));
980
376040
        break;
981
22120
      case kInteger:
982
44240
        value = Number::New(
983
            isolate,
984
44240
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
985
22120
        break;
986
16590
      case kUInteger:
987
33180
        value = Number::New(
988
            isolate,
989
33180
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
990
16590
        break;
991
154840
      case kString:
992
309680
        if (!ToV8Value(context,
993
309680
                       *_ppop_instance.Lookup<std::string>(field, opts))
994
154840
                 .ToLocal(&value)) {
995
          return;
996
        }
997
154840
        break;
998
16590
      case kStringList:
999
33180
        if (!ToV8Value(context,
1000
33180
                       *_ppop_instance.Lookup<StringVector>(field, opts))
1001
16590
                 .ToLocal(&value)) {
1002
          return;
1003
        }
1004
16590
        break;
1005
5530
      case kHostPort: {
1006
        const HostPort& host_port =
1007
5530
          *_ppop_instance.Lookup<HostPort>(field, opts);
1008
5530
        Local<Object> obj = Object::New(isolate);
1009
        Local<Value> host;
1010
5530
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
1011

27650
            obj->Set(context, env->host_string(), host).IsNothing() ||
1012
5530
            obj->Set(context,
1013
                     env->port_string(),
1014
22120
                     Integer::New(isolate, host_port.port()))
1015
5530
                .IsNothing()) {
1016
          return;
1017
        }
1018
5530
        value = obj;
1019
5530
        break;
1020
      }
1021
      default:
1022
        UNREACHABLE();
1023
    }
1024
707840
    CHECK(!value.IsEmpty());
1025
1026
707840
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1027
707840
    Local<Object> info = Object::New(isolate);
1028
    Local<Value> help_text;
1029
707840
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1030
1415680
        !info->Set(context, env->help_text_string(), help_text)
1031

1415680
             .FromMaybe(false) ||
1032
1415680
        !info->Set(context,
1033
                   env->env_var_settings_string(),
1034
                   Integer::New(isolate,
1035
2123520
                                static_cast<int>(option_info.env_setting)))
1036

1415680
             .FromMaybe(false) ||
1037
1415680
        !info->Set(context,
1038
                   env->type_string(),
1039
2123520
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1040

1415680
             .FromMaybe(false) ||
1041
1415680
        !info->Set(context,
1042
                   env->default_is_true_string(),
1043
2123520
                   Boolean::New(isolate, option_info.default_is_true))
1044

1415680
             .FromMaybe(false) ||
1045

3539200
        info->Set(context, env->value_string(), value).IsNothing() ||
1046

2123520
        options->Set(context, name, info).IsEmpty()) {
1047
      return;
1048
    }
1049
  }
1050
1051
  Local<Value> aliases;
1052
11060
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1053
1054
5530
  if (aliases.As<Object>()
1055
11060
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1056
5530
          .IsNothing()) {
1057
    return;
1058
  }
1059
1060
5530
  Local<Object> ret = Object::New(isolate);
1061
22120
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1062

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

19944
    return credentials::SafeGetenv(name, &text) ? text : "";
1129
  });
1130
4986
}
1131
1132
5251
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1133
                      std::function<std::string(const char*)> opt_getter) {
1134
5251
  env_options->pending_deprecation =
1135
10502
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1136
1137
5251
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1138
1139
5251
  env_options->preserve_symlinks_main =
1140
10502
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1141
1142
5251
  if (env_options->redirect_warnings.empty())
1143
5251
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1144
5251
}
1145
1146
5135
std::vector<std::string> ParseNodeOptionsEnvVar(
1147
    const std::string& node_options, std::vector<std::string>* errors) {
1148
5135
  std::vector<std::string> env_argv;
1149
1150
5135
  bool is_in_string = false;
1151
5135
  bool will_start_new_arg = true;
1152
7739
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1153
2604
    char c = node_options.at(index);
1154
1155
    // Backslashes escape the following character
1156

2604
    if (c == '\\' && is_in_string) {
1157
      if (index + 1 == node_options.size()) {
1158
        errors->push_back("invalid value for NODE_OPTIONS "
1159
                          "(invalid escape)\n");
1160
        return env_argv;
1161
      } else {
1162
        c = node_options.at(++index);
1163
      }
1164

2604
    } else if (c == ' ' && !is_in_string) {
1165
32
      will_start_new_arg = true;
1166
32
      continue;
1167
2572
    } else if (c == '"') {
1168
4
      is_in_string = !is_in_string;
1169
4
      continue;
1170
    }
1171
1172
2568
    if (will_start_new_arg) {
1173
108
      env_argv.emplace_back(std::string(1, c));
1174
108
      will_start_new_arg = false;
1175
    } else {
1176
2460
      env_argv.back() += c;
1177
    }
1178
  }
1179
1180
5135
  if (is_in_string) {
1181
    errors->push_back("invalid value for NODE_OPTIONS "
1182
                      "(unterminated string)\n");
1183
  }
1184
5135
  return env_argv;
1185
}
1186
}  // namespace node
1187
1188
4986
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)