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

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

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

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

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

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

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

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


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


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


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

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

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

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


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

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

1429320
             .FromMaybe(false) ||
1036
1429320
        !info->Set(context,
1037
                   env->env_var_settings_string(),
1038
                   Integer::New(isolate,
1039
2143980
                                static_cast<int>(option_info.env_setting)))
1040

1429320
             .FromMaybe(false) ||
1041
1429320
        !info->Set(context,
1042
                   env->type_string(),
1043
2143980
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1044

1429320
             .FromMaybe(false) ||
1045
1429320
        !info->Set(context,
1046
                   env->default_is_true_string(),
1047
2143980
                   Boolean::New(isolate, option_info.default_is_true))
1048

1429320
             .FromMaybe(false) ||
1049

3573300
        info->Set(context, env->value_string(), value).IsNothing() ||
1050

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

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

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

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

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