GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 448 477 93.9 %
Date: 2022-01-29 04:14:08 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

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


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

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

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

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


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

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

1416960
             .FromMaybe(false) ||
1038
1416960
        !info->Set(context,
1039
                   env->env_var_settings_string(),
1040
                   Integer::New(isolate,
1041
2125440
                                static_cast<int>(option_info.env_setting)))
1042

1416960
             .FromMaybe(false) ||
1043
1416960
        !info->Set(context,
1044
                   env->type_string(),
1045
2125440
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1046

1416960
             .FromMaybe(false) ||
1047
1416960
        !info->Set(context,
1048
                   env->default_is_true_string(),
1049
2125440
                   Boolean::New(isolate, option_info.default_is_true))
1050

1416960
             .FromMaybe(false) ||
1051

3542400
        info->Set(context, env->value_string(), value).IsNothing() ||
1052

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

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

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

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

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