GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_options.cc Lines: 443 470 94.3 %
Date: 2021-08-24 04:12:49 Branches: 200 256 78.1 %

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

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

9683
      use_largepages != "on" &&
86
1
      use_largepages != "silent") {
87
1
    errors->push_back("invalid value for --use-largepages");
88
  }
89
9681
  per_isolate->CheckOptions(errors);
90
9681
}
91
92
10183
void PerIsolateOptions::CheckOptions(std::vector<std::string>* errors) {
93
10183
  per_env->CheckOptions(errors);
94
10183
}
95
96
10183
void EnvironmentOptions::CheckOptions(std::vector<std::string>* errors) {
97

10183
  if (has_policy_integrity_string && experimental_policy.empty()) {
98
    errors->push_back("--policy-integrity requires "
99
                      "--experimental-policy be enabled");
100
  }
101

10183
  if (has_policy_integrity_string && experimental_policy_integrity.empty()) {
102
1
    errors->push_back("--policy-integrity cannot be empty");
103
  }
104
105
10183
  if (!module_type.empty()) {
106

20
    if (module_type != "commonjs" && module_type != "module") {
107
      errors->push_back("--input-type must be \"module\" or \"commonjs\"");
108
    }
109
  }
110
111
10183
  if (!experimental_specifier_resolution.empty()) {
112

10
    if (experimental_specifier_resolution != "node" &&
113
        experimental_specifier_resolution != "explicit") {
114
      errors->push_back(
115
        "invalid value for --experimental-specifier-resolution");
116
    }
117
  }
118
119

10183
  if (syntax_check_only && has_eval_string) {
120
4
    errors->push_back("either --check or --eval can be used, not both");
121
  }
122
123
10203
  if (!unhandled_rejections.empty() &&
124
39
      unhandled_rejections != "warn-with-error-code" &&
125
36
      unhandled_rejections != "throw" &&
126
32
      unhandled_rejections != "strict" &&
127

10218
      unhandled_rejections != "warn" &&
128
10
      unhandled_rejections != "none") {
129
1
    errors->push_back("invalid value for --unhandled-rejections");
130
  }
131
132

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


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


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


112
  if (!host.empty() && host.front() == '[' && host.back() == ']')
826
4
    return host.substr(1, host.size() - 2);
827
  else
828
108
    return host;
829
}
830
831
100
inline int ParseAndValidatePort(const std::string& port,
832
                                std::vector<std::string>* errors) {
833
  char* endptr;
834
100
  errno = 0;
835
  const unsigned long result =                 // NOLINT(runtime/int)
836
100
    strtoul(port.c_str(), &endptr, 10);
837

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

100
      (result != 0 && result < 1024) || result > 65535) {
839
    errors->push_back(" must be 0 or in range 1024 to 65535.");
840
  }
841
100
  return static_cast<int>(result);
842
}
843
844
100
HostPort SplitHostPort(const std::string& arg,
845
                      std::vector<std::string>* errors) {
846
  // remove_brackets only works if no port is specified
847
  // so if it has an effect only an IPv6 address was specified.
848
200
  std::string host = RemoveBrackets(arg);
849
100
  if (host.length() < arg.length())
850
    return HostPort{host, DebugOptions::kDefaultInspectorPort};
851
852
100
  size_t colon = arg.rfind(':');
853
100
  if (colon == std::string::npos) {
854
    // Either a port number or a host name.  Assume that
855
    // if it's not all decimal digits, it's a host name.
856
390
    for (char c : arg) {
857

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


671832
    switch (option_info.type) {
946
102942
      case kNoOp:
947
      case kV8Option:
948
        // Special case for --abort-on-uncaught-exception which is also
949
        // respected by Node.js internals
950
102942
        if (item.first == "--abort-on-uncaught-exception") {
951
5418
          value = Boolean::New(
952
5418
            isolate, original_per_env->abort_on_uncaught_exception);
953
        } else {
954
97524
          value = Undefined(isolate);
955
        }
956
102942
        break;
957
357588
      case kBoolean:
958
715176
        value = Boolean::New(isolate,
959
715176
                             *_ppop_instance.Lookup<bool>(field, opts));
960
357588
        break;
961
21672
      case kInteger:
962
43344
        value = Number::New(
963
            isolate,
964
43344
            static_cast<double>(*_ppop_instance.Lookup<int64_t>(field, opts)));
965
21672
        break;
966
16254
      case kUInteger:
967
32508
        value = Number::New(
968
            isolate,
969
32508
            static_cast<double>(*_ppop_instance.Lookup<uint64_t>(field, opts)));
970
16254
        break;
971
151704
      case kString:
972
303408
        if (!ToV8Value(context,
973
303408
                       *_ppop_instance.Lookup<std::string>(field, opts))
974
151704
                 .ToLocal(&value)) {
975
          return;
976
        }
977
151704
        break;
978
16254
      case kStringList:
979
32508
        if (!ToV8Value(context,
980
32508
                       *_ppop_instance.Lookup<StringVector>(field, opts))
981
16254
                 .ToLocal(&value)) {
982
          return;
983
        }
984
16254
        break;
985
5418
      case kHostPort: {
986
        const HostPort& host_port =
987
5418
          *_ppop_instance.Lookup<HostPort>(field, opts);
988
5418
        Local<Object> obj = Object::New(isolate);
989
        Local<Value> host;
990
5418
        if (!ToV8Value(context, host_port.host()).ToLocal(&host) ||
991

27090
            obj->Set(context, env->host_string(), host).IsNothing() ||
992
5418
            obj->Set(context,
993
                     env->port_string(),
994
21672
                     Integer::New(isolate, host_port.port()))
995
5418
                .IsNothing()) {
996
          return;
997
        }
998
5418
        value = obj;
999
5418
        break;
1000
      }
1001
      default:
1002
        UNREACHABLE();
1003
    }
1004
671832
    CHECK(!value.IsEmpty());
1005
1006
671832
    Local<Value> name = ToV8Value(context, item.first).ToLocalChecked();
1007
671832
    Local<Object> info = Object::New(isolate);
1008
    Local<Value> help_text;
1009
671832
    if (!ToV8Value(context, option_info.help_text).ToLocal(&help_text) ||
1010
1343664
        !info->Set(context, env->help_text_string(), help_text)
1011

1343664
             .FromMaybe(false) ||
1012
1343664
        !info->Set(context,
1013
                   env->env_var_settings_string(),
1014
                   Integer::New(isolate,
1015
2015496
                                static_cast<int>(option_info.env_setting)))
1016

1343664
             .FromMaybe(false) ||
1017
1343664
        !info->Set(context,
1018
                   env->type_string(),
1019
2015496
                   Integer::New(isolate, static_cast<int>(option_info.type)))
1020

1343664
             .FromMaybe(false) ||
1021
1343664
        !info->Set(context,
1022
                   env->default_is_true_string(),
1023
2015496
                   Boolean::New(isolate, option_info.default_is_true))
1024

1343664
             .FromMaybe(false) ||
1025

3359160
        info->Set(context, env->value_string(), value).IsNothing() ||
1026

2015496
        options->Set(context, name, info).IsEmpty()) {
1027
      return;
1028
    }
1029
  }
1030
1031
  Local<Value> aliases;
1032
10836
  if (!ToV8Value(context, _ppop_instance.aliases_).ToLocal(&aliases)) return;
1033
1034
5418
  if (aliases.As<Object>()
1035
10836
          ->SetPrototype(context, env->primordials_safe_map_prototype_object())
1036
5418
          .IsNothing()) {
1037
    return;
1038
  }
1039
1040
5418
  Local<Object> ret = Object::New(isolate);
1041
21672
  if (ret->Set(context, env->options_string(), options).IsNothing() ||
1042

21672
      ret->Set(context, env->aliases_string(), aliases).IsNothing()) {
1043
    return;
1044
  }
1045
1046
10836
  args.GetReturnValue().Set(ret);
1047
}
1048
1049
5403
void Initialize(Local<Object> target,
1050
                Local<Value> unused,
1051
                Local<Context> context,
1052
                void* priv) {
1053
5403
  Environment* env = Environment::GetCurrent(context);
1054
5403
  Isolate* isolate = env->isolate();
1055
5403
  env->SetMethodNoSideEffect(target, "getOptions", GetOptions);
1056
1057
5403
  Local<Object> env_settings = Object::New(isolate);
1058
16209
  NODE_DEFINE_CONSTANT(env_settings, kAllowedInEnvironment);
1059
16209
  NODE_DEFINE_CONSTANT(env_settings, kDisallowedInEnvironment);
1060
  target
1061
5403
      ->Set(
1062
16209
          context, FIXED_ONE_BYTE_STRING(isolate, "envSettings"), env_settings)
1063
      .Check();
1064
1065
  target
1066
5403
      ->Set(context,
1067
            FIXED_ONE_BYTE_STRING(env->isolate(), "shouldNotRegisterESMLoader"),
1068
16209
            Boolean::New(isolate, env->should_not_register_esm_loader()))
1069
      .Check();
1070
1071
5403
  Local<Object> types = Object::New(isolate);
1072
16209
  NODE_DEFINE_CONSTANT(types, kNoOp);
1073
16209
  NODE_DEFINE_CONSTANT(types, kV8Option);
1074
16209
  NODE_DEFINE_CONSTANT(types, kBoolean);
1075
16209
  NODE_DEFINE_CONSTANT(types, kInteger);
1076
16209
  NODE_DEFINE_CONSTANT(types, kUInteger);
1077
16209
  NODE_DEFINE_CONSTANT(types, kString);
1078
16209
  NODE_DEFINE_CONSTANT(types, kHostPort);
1079
16209
  NODE_DEFINE_CONSTANT(types, kStringList);
1080
10806
  target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types)
1081
      .Check();
1082
5403
}
1083
1084
}  // namespace options_parser
1085
1086
4906
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options) {
1087
4906
  HandleEnvOptions(env_options, [](const char* name) {
1088
19624
    std::string text;
1089

19624
    return credentials::SafeGetenv(name, &text) ? text : "";
1090
  });
1091
4906
}
1092
1093
5159
void HandleEnvOptions(std::shared_ptr<EnvironmentOptions> env_options,
1094
                      std::function<std::string(const char*)> opt_getter) {
1095
5159
  env_options->pending_deprecation =
1096
10318
      opt_getter("NODE_PENDING_DEPRECATION") == "1";
1097
1098
5159
  env_options->preserve_symlinks = opt_getter("NODE_PRESERVE_SYMLINKS") == "1";
1099
1100
5159
  env_options->preserve_symlinks_main =
1101
10318
      opt_getter("NODE_PRESERVE_SYMLINKS_MAIN") == "1";
1102
1103
5159
  if (env_options->redirect_warnings.empty())
1104
5159
    env_options->redirect_warnings = opt_getter("NODE_REDIRECT_WARNINGS");
1105
5159
}
1106
1107
5044
std::vector<std::string> ParseNodeOptionsEnvVar(
1108
    const std::string& node_options, std::vector<std::string>* errors) {
1109
5044
  std::vector<std::string> env_argv;
1110
1111
5044
  bool is_in_string = false;
1112
5044
  bool will_start_new_arg = true;
1113
7606
  for (std::string::size_type index = 0; index < node_options.size(); ++index) {
1114
2562
    char c = node_options.at(index);
1115
1116
    // Backslashes escape the following character
1117

2562
    if (c == '\\' && is_in_string) {
1118
      if (index + 1 == node_options.size()) {
1119
        errors->push_back("invalid value for NODE_OPTIONS "
1120
                          "(invalid escape)\n");
1121
        return env_argv;
1122
      } else {
1123
        c = node_options.at(++index);
1124
      }
1125

2562
    } else if (c == ' ' && !is_in_string) {
1126
32
      will_start_new_arg = true;
1127
32
      continue;
1128
2530
    } else if (c == '"') {
1129
4
      is_in_string = !is_in_string;
1130
4
      continue;
1131
    }
1132
1133
2526
    if (will_start_new_arg) {
1134
107
      env_argv.emplace_back(std::string(1, c));
1135
107
      will_start_new_arg = false;
1136
    } else {
1137
2419
      env_argv.back() += c;
1138
    }
1139
  }
1140
1141
5044
  if (is_in_string) {
1142
    errors->push_back("invalid value for NODE_OPTIONS "
1143
                      "(unterminated string)\n");
1144
  }
1145
5044
  return env_argv;
1146
}
1147
}  // namespace node
1148
1149
4906
NODE_MODULE_CONTEXT_AWARE_INTERNAL(options, node::options_parser::Initialize)