GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/env.h Lines: 47 47 100.0 %
Date: 2019-08-17 22:35:23 Branches: 14 26 53.8 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#ifndef SRC_ENV_H_
23
#define SRC_ENV_H_
24
25
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
26
27
#include "aliased_buffer.h"
28
#if HAVE_INSPECTOR
29
#include "inspector_agent.h"
30
#include "inspector_profiler.h"
31
#endif
32
#include "handle_wrap.h"
33
#include "node.h"
34
#include "node_binding.h"
35
#include "node_http2_state.h"
36
#include "node_main_instance.h"
37
#include "node_options.h"
38
#include "req_wrap.h"
39
#include "util.h"
40
#include "uv.h"
41
#include "v8.h"
42
43
#include <array>
44
#include <atomic>
45
#include <cstdint>
46
#include <functional>
47
#include <list>
48
#include <unordered_map>
49
#include <unordered_set>
50
#include <vector>
51
52
struct nghttp2_rcbuf;
53
54
namespace node {
55
56
namespace contextify {
57
class ContextifyScript;
58
class CompiledFnEntry;
59
}
60
61
namespace fs {
62
class FileHandleReadWrap;
63
}
64
65
namespace performance {
66
class performance_state;
67
}
68
69
namespace tracing {
70
class AgentWriterHandle;
71
}
72
73
#if HAVE_INSPECTOR
74
namespace profiler {
75
class V8CoverageConnection;
76
class V8CpuProfilerConnection;
77
class V8HeapProfilerConnection;
78
}  // namespace profiler
79
80
namespace inspector {
81
class ParentInspectorHandle;
82
}
83
#endif  // HAVE_INSPECTOR
84
85
namespace worker {
86
class Worker;
87
}
88
89
namespace loader {
90
class ModuleWrap;
91
92
5672
struct PackageConfig {
93
  enum class Exists { Yes, No };
94
  enum class IsValid { Yes, No };
95
  enum class HasMain { Yes, No };
96
  enum PackageType : uint32_t { None = 0, CommonJS, Module };
97
98
  const Exists exists;
99
  const IsValid is_valid;
100
  const HasMain has_main;
101
  const std::string main;
102
  const PackageType type;
103
104
  v8::Global<v8::Value> exports;
105
};
106
}  // namespace loader
107
108
enum class FsStatsOffset {
109
  kDev = 0,
110
  kMode,
111
  kNlink,
112
  kUid,
113
  kGid,
114
  kRdev,
115
  kBlkSize,
116
  kIno,
117
  kSize,
118
  kBlocks,
119
  kATimeSec,
120
  kATimeNsec,
121
  kMTimeSec,
122
  kMTimeNsec,
123
  kCTimeSec,
124
  kCTimeNsec,
125
  kBirthTimeSec,
126
  kBirthTimeNsec,
127
  kFsStatsFieldsNumber
128
};
129
130
// Stat fields buffers contain twice the number of entries in an uv_stat_t
131
// because `fs.StatWatcher` needs room to store 2 `fs.Stats` instances.
132
constexpr size_t kFsStatsBufferLength =
133
    static_cast<size_t>(FsStatsOffset::kFsStatsFieldsNumber) * 2;
134
135
// PER_ISOLATE_* macros: We have a lot of per-isolate properties
136
// and adding and maintaining their getters and setters by hand would be
137
// difficult so let's make the preprocessor generate them for us.
138
//
139
// In each macro, `V` is expected to be the name of a macro or function which
140
// accepts the number of arguments provided in each tuple in the macro body,
141
// typically two. The named function will be invoked against each tuple.
142
//
143
// Make sure that any macro V defined for use with the PER_ISOLATE_* macros is
144
// undefined again after use.
145
146
// Private symbols are per-isolate primitives but Environment proxies them
147
// for the sake of convenience.  Strings should be ASCII-only and have a
148
// "node:" prefix to avoid name clashes with third-party code.
149
#define PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)                              \
150
  V(alpn_buffer_private_symbol, "node:alpnBuffer")                            \
151
  V(arrow_message_private_symbol, "node:arrowMessage")                        \
152
  V(contextify_context_private_symbol, "node:contextify:context")             \
153
  V(contextify_global_private_symbol, "node:contextify:global")               \
154
  V(decorated_private_symbol, "node:decorated")                               \
155
  V(napi_wrapper, "node:napi:wrapper")                                        \
156
  V(sab_lifetimepartner_symbol, "node:sharedArrayBufferLifetimePartner")      \
157
158
// Symbols are per-isolate primitives but Environment proxies them
159
// for the sake of convenience.
160
#define PER_ISOLATE_SYMBOL_PROPERTIES(V)                                      \
161
  V(handle_onclose_symbol, "handle_onclose")                                  \
162
  V(no_message_symbol, "no_message_symbol")                                   \
163
  V(oninit_symbol, "oninit")                                                  \
164
  V(owner_symbol, "owner")                                                    \
165
166
// Strings are per-isolate primitives but Environment proxies them
167
// for the sake of convenience.  Strings should be ASCII-only.
168
#define PER_ISOLATE_STRING_PROPERTIES(V)                                       \
169
  V(address_string, "address")                                                 \
170
  V(aliases_string, "aliases")                                                 \
171
  V(args_string, "args")                                                       \
172
  V(asn1curve_string, "asn1Curve")                                             \
173
  V(async_ids_stack_string, "async_ids_stack")                                 \
174
  V(bits_string, "bits")                                                       \
175
  V(buffer_string, "buffer")                                                   \
176
  V(bytes_parsed_string, "bytesParsed")                                        \
177
  V(bytes_read_string, "bytesRead")                                            \
178
  V(bytes_written_string, "bytesWritten")                                      \
179
  V(cached_data_produced_string, "cachedDataProduced")                         \
180
  V(cached_data_rejected_string, "cachedDataRejected")                         \
181
  V(cached_data_string, "cachedData")                                          \
182
  V(cache_key_string, "cacheKey")                                              \
183
  V(change_string, "change")                                                   \
184
  V(channel_string, "channel")                                                 \
185
  V(chunks_sent_since_last_write_string, "chunksSentSinceLastWrite")           \
186
  V(clone_unsupported_type_str, "Cannot transfer object of unsupported type.") \
187
  V(code_string, "code")                                                       \
188
  V(commonjs_string, "commonjs")                                               \
189
  V(config_string, "config")                                                   \
190
  V(constants_string, "constants")                                             \
191
  V(crypto_dsa_string, "dsa")                                                  \
192
  V(crypto_ec_string, "ec")                                                    \
193
  V(crypto_ed25519_string, "ed25519")                                          \
194
  V(crypto_ed448_string, "ed448")                                              \
195
  V(crypto_x25519_string, "x25519")                                            \
196
  V(crypto_x448_string, "x448")                                                \
197
  V(crypto_rsa_string, "rsa")                                                  \
198
  V(crypto_rsa_pss_string, "rsa-pss")                                          \
199
  V(cwd_string, "cwd")                                                         \
200
  V(data_string, "data")                                                       \
201
  V(dest_string, "dest")                                                       \
202
  V(destroyed_string, "destroyed")                                             \
203
  V(detached_string, "detached")                                               \
204
  V(dns_a_string, "A")                                                         \
205
  V(dns_aaaa_string, "AAAA")                                                   \
206
  V(dns_cname_string, "CNAME")                                                 \
207
  V(dns_mx_string, "MX")                                                       \
208
  V(dns_naptr_string, "NAPTR")                                                 \
209
  V(dns_ns_string, "NS")                                                       \
210
  V(dns_ptr_string, "PTR")                                                     \
211
  V(dns_soa_string, "SOA")                                                     \
212
  V(dns_srv_string, "SRV")                                                     \
213
  V(dns_txt_string, "TXT")                                                     \
214
  V(duration_string, "duration")                                               \
215
  V(emit_warning_string, "emitWarning")                                        \
216
  V(encoding_string, "encoding")                                               \
217
  V(entries_string, "entries")                                                 \
218
  V(entry_type_string, "entryType")                                            \
219
  V(env_pairs_string, "envPairs")                                              \
220
  V(env_var_settings_string, "envVarSettings")                                 \
221
  V(errno_string, "errno")                                                     \
222
  V(error_string, "error")                                                     \
223
  V(exchange_string, "exchange")                                               \
224
  V(exit_code_string, "exitCode")                                              \
225
  V(expire_string, "expire")                                                   \
226
  V(exponent_string, "exponent")                                               \
227
  V(exports_string, "exports")                                                 \
228
  V(ext_key_usage_string, "ext_key_usage")                                     \
229
  V(external_stream_string, "_externalStream")                                 \
230
  V(family_string, "family")                                                   \
231
  V(fatal_exception_string, "_fatalException")                                 \
232
  V(fd_string, "fd")                                                           \
233
  V(fields_string, "fields")                                                   \
234
  V(file_string, "file")                                                       \
235
  V(fingerprint256_string, "fingerprint256")                                   \
236
  V(fingerprint_string, "fingerprint")                                         \
237
  V(flags_string, "flags")                                                     \
238
  V(fragment_string, "fragment")                                               \
239
  V(function_string, "function")                                               \
240
  V(get_data_clone_error_string, "_getDataCloneError")                         \
241
  V(get_shared_array_buffer_id_string, "_getSharedArrayBufferId")              \
242
  V(gid_string, "gid")                                                         \
243
  V(h2_string, "h2")                                                           \
244
  V(handle_string, "handle")                                                   \
245
  V(help_text_string, "helpText")                                              \
246
  V(homedir_string, "homedir")                                                 \
247
  V(host_string, "host")                                                       \
248
  V(hostmaster_string, "hostmaster")                                           \
249
  V(http_1_1_string, "http/1.1")                                               \
250
  V(ignore_string, "ignore")                                                   \
251
  V(infoaccess_string, "infoAccess")                                           \
252
  V(inherit_string, "inherit")                                                 \
253
  V(input_string, "input")                                                     \
254
  V(internal_binding_string, "internalBinding")                                \
255
  V(internal_string, "internal")                                               \
256
  V(ipv4_string, "IPv4")                                                       \
257
  V(ipv6_string, "IPv6")                                                       \
258
  V(isclosing_string, "isClosing")                                             \
259
  V(issuer_string, "issuer")                                                   \
260
  V(issuercert_string, "issuerCertificate")                                    \
261
  V(kill_signal_string, "killSignal")                                          \
262
  V(kind_string, "kind")                                                       \
263
  V(library_string, "library")                                                 \
264
  V(mac_string, "mac")                                                         \
265
  V(main_string, "main")                                                       \
266
  V(max_buffer_string, "maxBuffer")                                            \
267
  V(message_port_constructor_string, "MessagePort")                            \
268
  V(message_port_string, "messagePort")                                        \
269
  V(message_string, "message")                                                 \
270
  V(minttl_string, "minttl")                                                   \
271
  V(module_string, "module")                                                   \
272
  V(modulus_string, "modulus")                                                 \
273
  V(name_string, "name")                                                       \
274
  V(netmask_string, "netmask")                                                 \
275
  V(nistcurve_string, "nistCurve")                                             \
276
  V(nsname_string, "nsname")                                                   \
277
  V(ocsp_request_string, "OCSPRequest")                                        \
278
  V(oncertcb_string, "oncertcb")                                               \
279
  V(onchange_string, "onchange")                                               \
280
  V(onclienthello_string, "onclienthello")                                     \
281
  V(oncomplete_string, "oncomplete")                                           \
282
  V(onconnection_string, "onconnection")                                       \
283
  V(ondone_string, "ondone")                                                   \
284
  V(onerror_string, "onerror")                                                 \
285
  V(onexit_string, "onexit")                                                   \
286
  V(onhandshakedone_string, "onhandshakedone")                                 \
287
  V(onhandshakestart_string, "onhandshakestart")                               \
288
  V(onkeylog_string, "onkeylog")                                               \
289
  V(onmessage_string, "onmessage")                                             \
290
  V(onnewsession_string, "onnewsession")                                       \
291
  V(onocspresponse_string, "onocspresponse")                                   \
292
  V(onreadstart_string, "onreadstart")                                         \
293
  V(onreadstop_string, "onreadstop")                                           \
294
  V(onshutdown_string, "onshutdown")                                           \
295
  V(onsignal_string, "onsignal")                                               \
296
  V(onunpipe_string, "onunpipe")                                               \
297
  V(onwrite_string, "onwrite")                                                 \
298
  V(openssl_error_stack, "opensslErrorStack")                                  \
299
  V(options_string, "options")                                                 \
300
  V(order_string, "order")                                                     \
301
  V(output_string, "output")                                                   \
302
  V(parse_error_string, "Parse Error")                                         \
303
  V(password_string, "password")                                               \
304
  V(path_string, "path")                                                       \
305
  V(pending_handle_string, "pendingHandle")                                    \
306
  V(pid_string, "pid")                                                         \
307
  V(pipe_source_string, "pipeSource")                                          \
308
  V(pipe_string, "pipe")                                                       \
309
  V(pipe_target_string, "pipeTarget")                                          \
310
  V(port1_string, "port1")                                                     \
311
  V(port2_string, "port2")                                                     \
312
  V(port_string, "port")                                                       \
313
  V(preference_string, "preference")                                           \
314
  V(primordials_string, "primordials")                                         \
315
  V(priority_string, "priority")                                               \
316
  V(process_string, "process")                                                 \
317
  V(promise_string, "promise")                                                 \
318
  V(pubkey_string, "pubkey")                                                   \
319
  V(query_string, "query")                                                     \
320
  V(raw_string, "raw")                                                         \
321
  V(read_host_object_string, "_readHostObject")                                \
322
  V(readable_string, "readable")                                               \
323
  V(reason_string, "reason")                                                   \
324
  V(refresh_string, "refresh")                                                 \
325
  V(regexp_string, "regexp")                                                   \
326
  V(rename_string, "rename")                                                   \
327
  V(replacement_string, "replacement")                                         \
328
  V(require_string, "require")                                                 \
329
  V(retry_string, "retry")                                                     \
330
  V(scheme_string, "scheme")                                                   \
331
  V(scopeid_string, "scopeid")                                                 \
332
  V(serial_number_string, "serialNumber")                                      \
333
  V(serial_string, "serial")                                                   \
334
  V(servername_string, "servername")                                           \
335
  V(service_string, "service")                                                 \
336
  V(session_id_string, "sessionId")                                            \
337
  V(shell_string, "shell")                                                     \
338
  V(signal_string, "signal")                                                   \
339
  V(sink_string, "sink")                                                       \
340
  V(size_string, "size")                                                       \
341
  V(sni_context_err_string, "Invalid SNI context")                             \
342
  V(sni_context_string, "sni_context")                                         \
343
  V(source_string, "source")                                                   \
344
  V(stack_string, "stack")                                                     \
345
  V(start_time_string, "startTime")                                            \
346
  V(status_string, "status")                                                   \
347
  V(stdio_string, "stdio")                                                     \
348
  V(subject_string, "subject")                                                 \
349
  V(subjectaltname_string, "subjectaltname")                                   \
350
  V(syscall_string, "syscall")                                                 \
351
  V(target_string, "target")                                                   \
352
  V(thread_id_string, "threadId")                                              \
353
  V(ticketkeycallback_string, "onticketkeycallback")                           \
354
  V(timeout_string, "timeout")                                                 \
355
  V(tls_ticket_string, "tlsTicket")                                            \
356
  V(ttl_string, "ttl")                                                         \
357
  V(type_string, "type")                                                       \
358
  V(uid_string, "uid")                                                         \
359
  V(unknown_string, "<unknown>")                                               \
360
  V(url_string, "url")                                                         \
361
  V(username_string, "username")                                               \
362
  V(valid_from_string, "valid_from")                                           \
363
  V(valid_to_string, "valid_to")                                               \
364
  V(value_string, "value")                                                     \
365
  V(verify_error_string, "verifyError")                                        \
366
  V(version_string, "version")                                                 \
367
  V(weight_string, "weight")                                                   \
368
  V(windows_hide_string, "windowsHide")                                        \
369
  V(windows_verbatim_arguments_string, "windowsVerbatimArguments")             \
370
  V(wrap_string, "wrap")                                                       \
371
  V(writable_string, "writable")                                               \
372
  V(write_host_object_string, "_writeHostObject")                              \
373
  V(write_queue_size_string, "writeQueueSize")                                 \
374
  V(x_forwarded_string, "x-forwarded-for")                                     \
375
  V(zero_return_string, "ZERO_RETURN")
376
377
#define ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)                             \
378
  V(as_callback_data_template, v8::FunctionTemplate)                           \
379
  V(async_wrap_ctor_template, v8::FunctionTemplate)                            \
380
  V(async_wrap_object_ctor_template, v8::FunctionTemplate)                     \
381
  V(compiled_fn_entry_template, v8::ObjectTemplate)                            \
382
  V(fd_constructor_template, v8::ObjectTemplate)                               \
383
  V(fdclose_constructor_template, v8::ObjectTemplate)                          \
384
  V(filehandlereadwrap_template, v8::ObjectTemplate)                           \
385
  V(fsreqpromise_constructor_template, v8::ObjectTemplate)                     \
386
  V(handle_wrap_ctor_template, v8::FunctionTemplate)                           \
387
  V(http2settings_constructor_template, v8::ObjectTemplate)                    \
388
  V(http2stream_constructor_template, v8::ObjectTemplate)                      \
389
  V(http2ping_constructor_template, v8::ObjectTemplate)                        \
390
  V(libuv_stream_wrap_ctor_template, v8::FunctionTemplate)                     \
391
  V(message_event_object_template, v8::ObjectTemplate)                         \
392
  V(message_port_constructor_template, v8::FunctionTemplate)                   \
393
  V(pipe_constructor_template, v8::FunctionTemplate)                           \
394
  V(promise_wrap_template, v8::ObjectTemplate)                                 \
395
  V(sab_lifetimepartner_constructor_template, v8::FunctionTemplate)            \
396
  V(script_context_constructor_template, v8::FunctionTemplate)                 \
397
  V(secure_context_constructor_template, v8::FunctionTemplate)                 \
398
  V(shutdown_wrap_template, v8::ObjectTemplate)                                \
399
  V(streambaseoutputstream_constructor_template, v8::ObjectTemplate)           \
400
  V(tcp_constructor_template, v8::FunctionTemplate)                            \
401
  V(tty_constructor_template, v8::FunctionTemplate)                            \
402
  V(write_wrap_template, v8::ObjectTemplate)
403
404
#define ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)                                \
405
  V(as_callback_data, v8::Object)                                              \
406
  V(async_hooks_after_function, v8::Function)                                  \
407
  V(async_hooks_before_function, v8::Function)                                 \
408
  V(async_hooks_binding, v8::Object)                                           \
409
  V(async_hooks_destroy_function, v8::Function)                                \
410
  V(async_hooks_init_function, v8::Function)                                   \
411
  V(async_hooks_promise_resolve_function, v8::Function)                        \
412
  V(buffer_prototype_object, v8::Object)                                       \
413
  V(crypto_key_object_constructor, v8::Function)                               \
414
  V(domain_callback, v8::Function)                                             \
415
  V(domexception_function, v8::Function)                                       \
416
  V(enhance_fatal_stack_after_inspector, v8::Function)                         \
417
  V(enhance_fatal_stack_before_inspector, v8::Function)                        \
418
  V(fs_use_promises_symbol, v8::Symbol)                                        \
419
  V(host_import_module_dynamically_callback, v8::Function)                     \
420
  V(host_initialize_import_meta_object_callback, v8::Function)                 \
421
  V(http2session_on_altsvc_function, v8::Function)                             \
422
  V(http2session_on_error_function, v8::Function)                              \
423
  V(http2session_on_frame_error_function, v8::Function)                        \
424
  V(http2session_on_goaway_data_function, v8::Function)                        \
425
  V(http2session_on_headers_function, v8::Function)                            \
426
  V(http2session_on_origin_function, v8::Function)                             \
427
  V(http2session_on_ping_function, v8::Function)                               \
428
  V(http2session_on_priority_function, v8::Function)                           \
429
  V(http2session_on_select_padding_function, v8::Function)                     \
430
  V(http2session_on_settings_function, v8::Function)                           \
431
  V(http2session_on_stream_close_function, v8::Function)                       \
432
  V(http2session_on_stream_trailers_function, v8::Function)                    \
433
  V(internal_binding_loader, v8::Function)                                     \
434
  V(immediate_callback_function, v8::Function)                                 \
435
  V(inspector_console_extension_installer, v8::Function)                       \
436
  V(message_port, v8::Object)                                                  \
437
  V(native_module_require, v8::Function)                                       \
438
  V(performance_entry_callback, v8::Function)                                  \
439
  V(performance_entry_template, v8::Function)                                  \
440
  V(prepare_stack_trace_callback, v8::Function)                                \
441
  V(process_object, v8::Object)                                                \
442
  V(primordials, v8::Object)                                                   \
443
  V(promise_reject_callback, v8::Function)                                     \
444
  V(script_data_constructor_function, v8::Function)                            \
445
  V(tick_callback_function, v8::Function)                                      \
446
  V(timers_callback_function, v8::Function)                                    \
447
  V(tls_wrap_constructor_function, v8::Function)                               \
448
  V(trace_category_state_function, v8::Function)                               \
449
  V(udp_constructor_function, v8::Function)                                    \
450
  V(url_constructor_function, v8::Function)
451
452
class Environment;
453
454
9528
class IsolateData : public MemoryRetainer {
455
 public:
456
  IsolateData(v8::Isolate* isolate,
457
              uv_loop_t* event_loop,
458
              MultiIsolatePlatform* platform = nullptr,
459
              ArrayBufferAllocator* node_allocator = nullptr,
460
              const std::vector<size_t>* indexes = nullptr);
461
51
  SET_MEMORY_INFO_NAME(IsolateData)
462
51
  SET_SELF_SIZE(IsolateData)
463
  void MemoryInfo(MemoryTracker* tracker) const override;
464
  std::vector<size_t> Serialize(v8::SnapshotCreator* creator);
465
466
  inline uv_loop_t* event_loop() const;
467
  inline MultiIsolatePlatform* platform() const;
468
  inline std::shared_ptr<PerIsolateOptions> options();
469
  inline void set_options(std::shared_ptr<PerIsolateOptions> options);
470
471
  inline bool uses_node_allocator() const;
472
  inline v8::ArrayBuffer::Allocator* allocator() const;
473
  inline NodeArrayBufferAllocator* node_allocator() const;
474
475
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
476
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
477
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
478
#define V(TypeName, PropertyName)                                             \
479
  inline v8::Local<TypeName> PropertyName(v8::Isolate* isolate) const;
480
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
481
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
482
  PER_ISOLATE_STRING_PROPERTIES(VS)
483
#undef V
484
#undef VY
485
#undef VS
486
#undef VP
487
488
  std::unordered_map<nghttp2_rcbuf*, v8::Eternal<v8::String>> http2_static_strs;
489
  inline v8::Isolate* isolate() const;
490
  IsolateData(const IsolateData&) = delete;
491
  IsolateData& operator=(const IsolateData&) = delete;
492
  IsolateData(IsolateData&&) = delete;
493
  IsolateData& operator=(IsolateData&&) = delete;
494
495
 private:
496
  void DeserializeProperties(const std::vector<size_t>* indexes);
497
  void CreateProperties();
498
499
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
500
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
501
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
502
#define V(TypeName, PropertyName)                                             \
503
  v8::Eternal<TypeName> PropertyName ## _;
504
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
505
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
506
  PER_ISOLATE_STRING_PROPERTIES(VS)
507
#undef V
508
#undef VY
509
#undef VS
510
#undef VP
511
512
  v8::Isolate* const isolate_;
513
  uv_loop_t* const event_loop_;
514
  v8::ArrayBuffer::Allocator* const allocator_;
515
  NodeArrayBufferAllocator* const node_allocator_;
516
  const bool uses_node_allocator_;
517
  MultiIsolatePlatform* platform_;
518
  std::shared_ptr<PerIsolateOptions> options_;
519
};
520
521
10768
struct ContextInfo {
522
10769
  explicit ContextInfo(const std::string& name) : name(name) {}
523
  const std::string name;
524
  std::string origin;
525
  bool is_default = false;
526
};
527
528
// Listing the AsyncWrap provider types first enables us to cast directly
529
// from a provider type to a debug category.
530
#define DEBUG_CATEGORY_NAMES(V)                                                \
531
  NODE_ASYNC_PROVIDER_TYPES(V)                                                 \
532
  V(INSPECTOR_SERVER)                                                          \
533
  V(INSPECTOR_PROFILER)
534
535
enum class DebugCategory {
536
#define V(name) name,
537
  DEBUG_CATEGORY_NAMES(V)
538
#undef V
539
  CATEGORY_COUNT
540
};
541
542
// A unique-pointer-ish object that is compatible with the JS engine's
543
// ArrayBuffer::Allocator.
544
struct AllocatedBuffer {
545
 public:
546
  explicit inline AllocatedBuffer(Environment* env = nullptr);
547
  inline AllocatedBuffer(Environment* env, uv_buf_t buf);
548
  inline ~AllocatedBuffer();
549
  inline void Resize(size_t len);
550
551
  inline uv_buf_t release();
552
  inline char* data();
553
  inline const char* data() const;
554
  inline size_t size() const;
555
  inline void clear();
556
557
  inline v8::MaybeLocal<v8::Object> ToBuffer();
558
  inline v8::Local<v8::ArrayBuffer> ToArrayBuffer();
559
560
  inline AllocatedBuffer(AllocatedBuffer&& other);
561
  inline AllocatedBuffer& operator=(AllocatedBuffer&& other);
562
  AllocatedBuffer(const AllocatedBuffer& other) = delete;
563
  AllocatedBuffer& operator=(const AllocatedBuffer& other) = delete;
564
565
 private:
566
  Environment* env_;
567
  // We do not pass this to libuv directly, but uv_buf_t is a convenient way
568
  // to represent a chunk of memory, and plays nicely with other parts of core.
569
  uv_buf_t buffer_;
570
571
  friend class Environment;
572
};
573
574
class AsyncRequest : public MemoryRetainer {
575
 public:
576
5368
  AsyncRequest() = default;
577
  ~AsyncRequest();
578
579
  AsyncRequest(const AsyncRequest&) = delete;
580
  AsyncRequest& operator=(const AsyncRequest&) = delete;
581
  AsyncRequest(AsyncRequest&&) = delete;
582
  AsyncRequest& operator=(AsyncRequest&&) = delete;
583
584
  void Install(Environment* env, void* data, uv_async_cb target);
585
  void Uninstall();
586
  void Stop();
587
  inline void set_stopped(bool flag);
588
  inline bool is_stopped() const;
589
  uv_async_t* GetHandle();
590
  void MemoryInfo(MemoryTracker* tracker) const override;
591
592
593
55
  SET_MEMORY_INFO_NAME(AsyncRequest)
594
59
  SET_SELF_SIZE(AsyncRequest)
595
596
 private:
597
  Environment* env_;
598
  uv_async_t* async_ = nullptr;
599
  std::atomic_bool stopped_ {true};
600
};
601
602
class KVStore {
603
 public:
604
5226
  KVStore() = default;
605
4823
  virtual ~KVStore() = default;
606
  KVStore(const KVStore&) = delete;
607
  KVStore& operator=(const KVStore&) = delete;
608
  KVStore(KVStore&&) = delete;
609
  KVStore& operator=(KVStore&&) = delete;
610
611
  virtual v8::Local<v8::String> Get(v8::Isolate* isolate,
612
                                    v8::Local<v8::String> key) const = 0;
613
  virtual void Set(v8::Isolate* isolate,
614
                   v8::Local<v8::String> key,
615
                   v8::Local<v8::String> value) = 0;
616
  virtual int32_t Query(v8::Isolate* isolate,
617
                        v8::Local<v8::String> key) const = 0;
618
  virtual void Delete(v8::Isolate* isolate, v8::Local<v8::String> key) = 0;
619
  virtual v8::Local<v8::Array> Enumerate(v8::Isolate* isolate) const = 0;
620
621
  virtual std::shared_ptr<KVStore> Clone(v8::Isolate* isolate) const;
622
  virtual v8::Maybe<bool> AssignFromObject(v8::Local<v8::Context> context,
623
                                           v8::Local<v8::Object> entries);
624
625
  static std::shared_ptr<KVStore> CreateMapKVStore();
626
};
627
628
namespace per_process {
629
extern std::shared_ptr<KVStore> system_environment;
630
}
631
632
class AsyncHooks : public MemoryRetainer {
633
 public:
634
51
  SET_MEMORY_INFO_NAME(AsyncHooks)
635
51
  SET_SELF_SIZE(AsyncHooks)
636
  void MemoryInfo(MemoryTracker* tracker) const override;
637
638
  // Reason for both UidFields and Fields are that one is stored as a double*
639
  // and the other as a uint32_t*.
640
  enum Fields {
641
    kInit,
642
    kBefore,
643
    kAfter,
644
    kDestroy,
645
    kPromiseResolve,
646
    kTotals,
647
    kCheck,
648
    kStackLength,
649
    kFieldsCount,
650
  };
651
652
  enum UidFields {
653
    kExecutionAsyncId,
654
    kTriggerAsyncId,
655
    kAsyncIdCounter,
656
    kDefaultTriggerAsyncId,
657
    kUidFieldsCount,
658
  };
659
660
  inline AliasedUint32Array& fields();
661
  inline AliasedFloat64Array& async_id_fields();
662
  inline AliasedFloat64Array& async_ids_stack();
663
664
  inline v8::Local<v8::String> provider_string(int idx);
665
666
  inline void no_force_checks();
667
  inline Environment* env();
668
669
  inline void push_async_ids(double async_id, double trigger_async_id);
670
  inline bool pop_async_id(double async_id);
671
  inline void clear_async_id_stack();  // Used in fatal exceptions.
672
673
  AsyncHooks(const AsyncHooks&) = delete;
674
  AsyncHooks& operator=(const AsyncHooks&) = delete;
675
  AsyncHooks(AsyncHooks&&) = delete;
676
  AsyncHooks& operator=(AsyncHooks&&) = delete;
677
4754
  ~AsyncHooks() = default;
678
679
  // Used to set the kDefaultTriggerAsyncId in a scope. This is instead of
680
  // passing the trigger_async_id along with other constructor arguments.
681
  class DefaultTriggerAsyncIdScope {
682
   public:
683
    DefaultTriggerAsyncIdScope() = delete;
684
    explicit DefaultTriggerAsyncIdScope(Environment* env,
685
                                        double init_trigger_async_id);
686
    explicit DefaultTriggerAsyncIdScope(AsyncWrap* async_wrap);
687
    ~DefaultTriggerAsyncIdScope();
688
689
    DefaultTriggerAsyncIdScope(const DefaultTriggerAsyncIdScope&) = delete;
690
    DefaultTriggerAsyncIdScope& operator=(const DefaultTriggerAsyncIdScope&) =
691
        delete;
692
    DefaultTriggerAsyncIdScope(DefaultTriggerAsyncIdScope&&) = delete;
693
    DefaultTriggerAsyncIdScope& operator=(DefaultTriggerAsyncIdScope&&) =
694
        delete;
695
696
   private:
697
    AsyncHooks* async_hooks_;
698
    double old_default_trigger_async_id_;
699
  };
700
701
 private:
702
  friend class Environment;  // So we can call the constructor.
703
  inline AsyncHooks();
704
  // Keep a list of all Persistent strings used for Provider types.
705
  std::array<v8::Eternal<v8::String>, AsyncWrap::PROVIDERS_LENGTH> providers_;
706
  // Stores the ids of the current execution context stack.
707
  AliasedFloat64Array async_ids_stack_;
708
  // Attached to a Uint32Array that tracks the number of active hooks for
709
  // each type.
710
  AliasedUint32Array fields_;
711
  // Attached to a Float64Array that tracks the state of async resources.
712
  AliasedFloat64Array async_id_fields_;
713
714
  void grow_async_ids_stack();
715
};
716
717
class AsyncCallbackScope {
718
 public:
719
  AsyncCallbackScope() = delete;
720
  explicit AsyncCallbackScope(Environment* env);
721
  ~AsyncCallbackScope();
722
  AsyncCallbackScope(const AsyncCallbackScope&) = delete;
723
  AsyncCallbackScope& operator=(const AsyncCallbackScope&) = delete;
724
  AsyncCallbackScope(AsyncCallbackScope&&) = delete;
725
  AsyncCallbackScope& operator=(AsyncCallbackScope&&) = delete;
726
727
 private:
728
  Environment* env_;
729
};
730
731
class ImmediateInfo : public MemoryRetainer {
732
 public:
733
  inline AliasedUint32Array& fields();
734
  inline uint32_t count() const;
735
  inline uint32_t ref_count() const;
736
  inline bool has_outstanding() const;
737
  inline void count_inc(uint32_t increment);
738
  inline void count_dec(uint32_t decrement);
739
  inline void ref_count_inc(uint32_t increment);
740
  inline void ref_count_dec(uint32_t decrement);
741
742
  ImmediateInfo(const ImmediateInfo&) = delete;
743
  ImmediateInfo& operator=(const ImmediateInfo&) = delete;
744
  ImmediateInfo(ImmediateInfo&&) = delete;
745
  ImmediateInfo& operator=(ImmediateInfo&&) = delete;
746
4754
  ~ImmediateInfo() = default;
747
748
51
  SET_MEMORY_INFO_NAME(ImmediateInfo)
749
51
  SET_SELF_SIZE(ImmediateInfo)
750
  void MemoryInfo(MemoryTracker* tracker) const override;
751
752
 private:
753
  friend class Environment;  // So we can call the constructor.
754
  inline explicit ImmediateInfo(v8::Isolate* isolate);
755
756
  enum Fields { kCount, kRefCount, kHasOutstanding, kFieldsCount };
757
758
  AliasedUint32Array fields_;
759
};
760
761
class TickInfo : public MemoryRetainer {
762
 public:
763
  inline AliasedUint8Array& fields();
764
  inline bool has_tick_scheduled() const;
765
  inline bool has_rejection_to_warn() const;
766
767
51
  SET_MEMORY_INFO_NAME(TickInfo)
768
51
  SET_SELF_SIZE(TickInfo)
769
  void MemoryInfo(MemoryTracker* tracker) const override;
770
771
  TickInfo(const TickInfo&) = delete;
772
  TickInfo& operator=(const TickInfo&) = delete;
773
  TickInfo(TickInfo&&) = delete;
774
  TickInfo& operator=(TickInfo&&) = delete;
775
4754
  ~TickInfo() = default;
776
777
 private:
778
  friend class Environment;  // So we can call the constructor.
779
  inline explicit TickInfo(v8::Isolate* isolate);
780
781
  enum Fields { kHasTickScheduled = 0, kHasRejectionToWarn, kFieldsCount };
782
783
  AliasedUint8Array fields_;
784
};
785
786
9505
class TrackingTraceStateObserver :
787
    public v8::TracingController::TraceStateObserver {
788
 public:
789
5157
  explicit TrackingTraceStateObserver(Environment* env) : env_(env) {}
790
791
102
  void OnTraceEnabled() override {
792
102
    UpdateTraceCategoryState();
793
102
  }
794
795
32
  void OnTraceDisabled() override {
796
32
    UpdateTraceCategoryState();
797
32
  }
798
799
 private:
800
  void UpdateTraceCategoryState();
801
802
  Environment* env_;
803
};
804
805
class ShouldNotAbortOnUncaughtScope {
806
 public:
807
  explicit inline ShouldNotAbortOnUncaughtScope(Environment* env);
808
  inline void Close();
809
  inline ~ShouldNotAbortOnUncaughtScope();
810
  ShouldNotAbortOnUncaughtScope(const ShouldNotAbortOnUncaughtScope&) = delete;
811
  ShouldNotAbortOnUncaughtScope& operator=(
812
      const ShouldNotAbortOnUncaughtScope&) = delete;
813
  ShouldNotAbortOnUncaughtScope(ShouldNotAbortOnUncaughtScope&&) = delete;
814
  ShouldNotAbortOnUncaughtScope& operator=(ShouldNotAbortOnUncaughtScope&&) =
815
      delete;
816
817
 private:
818
  Environment* env_;
819
};
820
821
class CleanupHookCallback {
822
 public:
823
1478874
  CleanupHookCallback(void (*fn)(void*),
824
                      void* arg,
825
                      uint64_t insertion_order_counter)
826
1478874
      : fn_(fn), arg_(arg), insertion_order_counter_(insertion_order_counter) {}
827
828
  // Only hashes `arg_`, since that is usually enough to identify the hook.
829
  struct Hash {
830
    inline size_t operator()(const CleanupHookCallback& cb) const;
831
  };
832
833
  // Compares by `fn_` and `arg_` being equal.
834
  struct Equal {
835
    inline bool operator()(const CleanupHookCallback& a,
836
                           const CleanupHookCallback& b) const;
837
  };
838
839
  inline BaseObject* GetBaseObject() const;
840
841
 private:
842
  friend class Environment;
843
  void (*fn_)(void*);
844
  void* arg_;
845
846
  // We keep track of the insertion order for these objects, so that we can
847
  // call the callbacks in reverse order when we are cleaning up.
848
  uint64_t insertion_order_counter_;
849
};
850
851
class Environment : public MemoryRetainer {
852
 public:
853
  Environment(const Environment&) = delete;
854
  Environment& operator=(const Environment&) = delete;
855
  Environment(Environment&&) = delete;
856
  Environment& operator=(Environment&&) = delete;
857
858
51
  SET_MEMORY_INFO_NAME(Environment)
859
860
  inline size_t SelfSize() const override;
861
86
  bool IsRootNode() const override { return true; }
862
  void MemoryInfo(MemoryTracker* tracker) const override;
863
864
  void CreateProperties();
865
  // Should be called before InitializeInspector()
866
  void InitializeDiagnostics();
867
#if HAVE_INSPECTOR && NODE_USE_V8_PLATFORM
868
  // If the environment is created for a worker, pass parent_handle and
869
  // the ownership if transferred into the Environment.
870
  int InitializeInspector(inspector::ParentInspectorHandle* parent_handle);
871
#endif
872
873
  v8::MaybeLocal<v8::Value> BootstrapInternalLoaders();
874
  v8::MaybeLocal<v8::Value> BootstrapNode();
875
  v8::MaybeLocal<v8::Value> RunBootstrapping();
876
877
  inline size_t async_callback_scope_depth() const;
878
  inline void PushAsyncCallbackScope();
879
  inline void PopAsyncCallbackScope();
880
881
  enum Flags {
882
    kNoFlags = 0,
883
    kIsMainThread = 1 << 0,
884
    kOwnsProcessState = 1 << 1,
885
    kOwnsInspector = 1 << 2,
886
  };
887
888
  static inline Environment* GetCurrent(v8::Isolate* isolate);
889
  static inline Environment* GetCurrent(v8::Local<v8::Context> context);
890
  static inline Environment* GetCurrent(
891
      const v8::FunctionCallbackInfo<v8::Value>& info);
892
893
  template <typename T>
894
  static inline Environment* GetCurrent(
895
      const v8::PropertyCallbackInfo<T>& info);
896
897
  static inline Environment* GetFromCallbackData(v8::Local<v8::Value> val);
898
899
  static uv_key_t thread_local_env;
900
  static inline Environment* GetThreadLocalEnv();
901
902
  Environment(IsolateData* isolate_data,
903
              v8::Local<v8::Context> context,
904
              const std::vector<std::string>& args,
905
              const std::vector<std::string>& exec_args,
906
              Flags flags = Flags(),
907
              uint64_t thread_id = kNoThreadId);
908
  ~Environment();
909
910
  void InitializeLibuv(bool start_profiler_idle_notifier);
911
  inline const std::vector<std::string>& exec_argv();
912
  inline const std::vector<std::string>& argv();
913
  const std::string& exec_path() const;
914
915
  typedef void (*HandleCleanupCb)(Environment* env,
916
                                  uv_handle_t* handle,
917
                                  void* arg);
918
  struct HandleCleanup {
919
    uv_handle_t* handle_;
920
    HandleCleanupCb cb_;
921
    void* arg_;
922
  };
923
924
  void RegisterHandleCleanups();
925
  void CleanupHandles();
926
  void Exit(int code);
927
  void ExitEnv();
928
929
  // Register clean-up cb to be called on environment destruction.
930
  inline void RegisterHandleCleanup(uv_handle_t* handle,
931
                                    HandleCleanupCb cb,
932
                                    void* arg);
933
934
  template <typename T, typename OnCloseCallback>
935
  inline void CloseHandle(T* handle, OnCloseCallback callback);
936
937
  inline void AssignToContext(v8::Local<v8::Context> context,
938
                              const ContextInfo& info);
939
940
  void StartProfilerIdleNotifier();
941
  void StopProfilerIdleNotifier();
942
  inline bool profiler_idle_notifier_started() const;
943
944
  inline v8::Isolate* isolate() const;
945
  inline uv_loop_t* event_loop() const;
946
  inline void TryLoadAddon(
947
      const char* filename,
948
      int flags,
949
      const std::function<bool(binding::DLib*)>& was_loaded);
950
951
  static inline Environment* from_timer_handle(uv_timer_t* handle);
952
  inline uv_timer_t* timer_handle();
953
954
  static inline Environment* from_immediate_check_handle(uv_check_t* handle);
955
  inline uv_check_t* immediate_check_handle();
956
  inline uv_idle_t* immediate_idle_handle();
957
958
  inline void IncreaseWaitingRequestCounter();
959
  inline void DecreaseWaitingRequestCounter();
960
961
  inline AsyncHooks* async_hooks();
962
  inline ImmediateInfo* immediate_info();
963
  inline TickInfo* tick_info();
964
  inline uint64_t timer_base() const;
965
  inline std::shared_ptr<KVStore> env_vars();
966
  inline void set_env_vars(std::shared_ptr<KVStore> env_vars);
967
968
  inline IsolateData* isolate_data() const;
969
970
  // Utilities that allocate memory using the Isolate's ArrayBuffer::Allocator.
971
  // In particular, using AllocateManaged() will provide a RAII-style object
972
  // with easy conversion to `Buffer` and `ArrayBuffer` objects.
973
  inline AllocatedBuffer AllocateManaged(size_t size, bool checked = true);
974
  inline char* Allocate(size_t size);
975
  inline char* AllocateUnchecked(size_t size);
976
  char* Reallocate(char* data, size_t old_size, size_t size);
977
  inline void Free(char* data, size_t size);
978
979
  inline bool printed_error() const;
980
  inline void set_printed_error(bool value);
981
982
  void PrintSyncTrace() const;
983
  inline void set_trace_sync_io(bool value);
984
985
  // This stores whether the --abort-on-uncaught-exception flag was passed
986
  // to Node.
987
  inline bool abort_on_uncaught_exception() const;
988
  inline void set_abort_on_uncaught_exception(bool value);
989
  // This is a pseudo-boolean that keeps track of whether an uncaught exception
990
  // should abort the process or not if --abort-on-uncaught-exception was
991
  // passed to Node. If the flag was not passed, it is ignored.
992
  inline AliasedUint32Array& should_abort_on_uncaught_toggle();
993
994
  inline AliasedInt32Array& stream_base_state();
995
996
  // The necessary API for async_hooks.
997
  inline double new_async_id();
998
  inline double execution_async_id();
999
  inline double trigger_async_id();
1000
  inline double get_default_trigger_async_id();
1001
1002
  // List of id's that have been destroyed and need the destroy() cb called.
1003
  inline std::vector<double>* destroy_async_id_list();
1004
1005
  std::set<std::string> native_modules_with_cache;
1006
  std::set<std::string> native_modules_without_cache;
1007
1008
  std::unordered_multimap<int, loader::ModuleWrap*> hash_to_module_map;
1009
  std::unordered_map<uint32_t, loader::ModuleWrap*> id_to_module_map;
1010
  std::unordered_map<uint32_t, contextify::ContextifyScript*>
1011
      id_to_script_map;
1012
  std::unordered_map<uint32_t, contextify::CompiledFnEntry*> id_to_function_map;
1013
1014
  inline uint32_t get_next_module_id();
1015
  inline uint32_t get_next_script_id();
1016
  inline uint32_t get_next_function_id();
1017
1018
  std::unordered_map<std::string, const loader::PackageConfig>
1019
      package_json_cache;
1020
1021
  inline double* heap_statistics_buffer() const;
1022
  inline void set_heap_statistics_buffer(double* pointer);
1023
1024
  inline double* heap_space_statistics_buffer() const;
1025
  inline void set_heap_space_statistics_buffer(double* pointer);
1026
1027
  inline double* heap_code_statistics_buffer() const;
1028
  inline void set_heap_code_statistics_buffer(double* pointer);
1029
1030
  inline char* http_parser_buffer() const;
1031
  inline void set_http_parser_buffer(char* buffer);
1032
  inline bool http_parser_buffer_in_use() const;
1033
  inline void set_http_parser_buffer_in_use(bool in_use);
1034
1035
  inline http2::Http2State* http2_state() const;
1036
  inline void set_http2_state(std::unique_ptr<http2::Http2State> state);
1037
1038
  inline bool debug_enabled(DebugCategory category) const;
1039
  inline void set_debug_enabled(DebugCategory category, bool enabled);
1040
  void set_debug_categories(const std::string& cats, bool enabled);
1041
1042
  inline AliasedFloat64Array* fs_stats_field_array();
1043
  inline AliasedBigUint64Array* fs_stats_field_bigint_array();
1044
1045
  inline std::vector<std::unique_ptr<fs::FileHandleReadWrap>>&
1046
      file_handle_read_wrap_freelist();
1047
1048
  inline performance::performance_state* performance_state();
1049
  inline std::unordered_map<std::string, uint64_t>* performance_marks();
1050
1051
  void CollectUVExceptionInfo(v8::Local<v8::Value> context,
1052
                              int errorno,
1053
                              const char* syscall = nullptr,
1054
                              const char* message = nullptr,
1055
                              const char* path = nullptr,
1056
                              const char* dest = nullptr);
1057
1058
  // If this flag is set, calls into JS (if they would be observable
1059
  // from userland) must be avoided.  This flag does not indicate whether
1060
  // calling into JS is allowed from a VM perspective at this point.
1061
  inline bool can_call_into_js() const;
1062
  inline void set_can_call_into_js(bool can_call_into_js);
1063
1064
  inline bool has_run_bootstrapping_code() const;
1065
  inline void set_has_run_bootstrapping_code(bool has_run_bootstrapping_code);
1066
1067
  inline bool has_serialized_options() const;
1068
  inline void set_has_serialized_options(bool has_serialized_options);
1069
1070
  static uint64_t AllocateThreadId();
1071
  static constexpr uint64_t kNoThreadId = -1;
1072
1073
  inline bool is_main_thread() const;
1074
  inline bool owns_process_state() const;
1075
  inline bool owns_inspector() const;
1076
  inline uint64_t thread_id() const;
1077
  inline worker::Worker* worker_context() const;
1078
  inline void set_worker_context(worker::Worker* context);
1079
  inline void add_sub_worker_context(worker::Worker* context);
1080
  inline void remove_sub_worker_context(worker::Worker* context);
1081
  void stop_sub_worker_contexts();
1082
  inline bool is_stopping() const;
1083
1084
  inline void ThrowError(const char* errmsg);
1085
  inline void ThrowTypeError(const char* errmsg);
1086
  inline void ThrowRangeError(const char* errmsg);
1087
  inline void ThrowErrnoException(int errorno,
1088
                                  const char* syscall = nullptr,
1089
                                  const char* message = nullptr,
1090
                                  const char* path = nullptr);
1091
  inline void ThrowUVException(int errorno,
1092
                               const char* syscall = nullptr,
1093
                               const char* message = nullptr,
1094
                               const char* path = nullptr,
1095
                               const char* dest = nullptr);
1096
1097
  inline v8::Local<v8::FunctionTemplate>
1098
      NewFunctionTemplate(v8::FunctionCallback callback,
1099
                          v8::Local<v8::Signature> signature =
1100
                              v8::Local<v8::Signature>(),
1101
                          v8::ConstructorBehavior behavior =
1102
                              v8::ConstructorBehavior::kAllow,
1103
                          v8::SideEffectType side_effect =
1104
                              v8::SideEffectType::kHasSideEffect);
1105
1106
  // Convenience methods for NewFunctionTemplate().
1107
  inline void SetMethod(v8::Local<v8::Object> that,
1108
                        const char* name,
1109
                        v8::FunctionCallback callback);
1110
1111
  inline void SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
1112
                             const char* name,
1113
                             v8::FunctionCallback callback);
1114
1115
  // Safe variants denote the function has no side effects.
1116
  inline void SetMethodNoSideEffect(v8::Local<v8::Object> that,
1117
                                    const char* name,
1118
                                    v8::FunctionCallback callback);
1119
  inline void SetProtoMethodNoSideEffect(v8::Local<v8::FunctionTemplate> that,
1120
                                         const char* name,
1121
                                         v8::FunctionCallback callback);
1122
1123
  void BeforeExit(void (*cb)(void* arg), void* arg);
1124
  void RunBeforeExitCallbacks();
1125
  void AtExit(void (*cb)(void* arg), void* arg);
1126
  void RunAtExitCallbacks();
1127
1128
  // Strings and private symbols are shared across shared contexts
1129
  // The getters simply proxy to the per-isolate primitive.
1130
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1131
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1132
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1133
#define V(TypeName, PropertyName)                                             \
1134
  inline v8::Local<TypeName> PropertyName() const;
1135
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1136
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1137
  PER_ISOLATE_STRING_PROPERTIES(VS)
1138
#undef V
1139
#undef VS
1140
#undef VY
1141
#undef VP
1142
1143
#define V(PropertyName, TypeName)                                             \
1144
  inline v8::Local<TypeName> PropertyName() const;                            \
1145
  inline void set_ ## PropertyName(v8::Local<TypeName> value);
1146
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1147
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1148
#undef V
1149
1150
  inline v8::Local<v8::Context> context() const;
1151
1152
#if HAVE_INSPECTOR
1153
272418
  inline inspector::Agent* inspector_agent() const {
1154
272418
    return inspector_agent_.get();
1155
  }
1156
1157
  inline bool is_in_inspector_console_call() const;
1158
  inline void set_is_in_inspector_console_call(bool value);
1159
#endif
1160
1161
  typedef ListHead<HandleWrap, &HandleWrap::handle_wrap_queue_> HandleWrapQueue;
1162
  typedef ListHead<ReqWrapBase, &ReqWrapBase::req_wrap_queue_> ReqWrapQueue;
1163
1164
88033
  inline HandleWrapQueue* handle_wrap_queue() { return &handle_wrap_queue_; }
1165
116360
  inline ReqWrapQueue* req_wrap_queue() { return &req_wrap_queue_; }
1166
1167
1
  inline bool EmitProcessEnvWarning() {
1168
1
    bool current_value = emit_env_nonstring_warning_;
1169
1
    emit_env_nonstring_warning_ = false;
1170
1
    return current_value;
1171
  }
1172
1173
1
  inline bool EmitErrNameWarning() {
1174
1
    bool current_value = emit_err_name_warning_;
1175
1
    emit_err_name_warning_ = false;
1176
1
    return current_value;
1177
  }
1178
1179
  // cb will be called as cb(env) on the next event loop iteration.
1180
  // keep_alive will be kept alive between now and after the callback has run.
1181
  template <typename Fn>
1182
  inline void SetImmediate(Fn&& cb,
1183
                           v8::Local<v8::Object> keep_alive =
1184
                               v8::Local<v8::Object>());
1185
  template <typename Fn>
1186
  inline void SetUnrefImmediate(Fn&& cb,
1187
                                v8::Local<v8::Object> keep_alive =
1188
                                    v8::Local<v8::Object>());
1189
  // This needs to be available for the JS-land setImmediate().
1190
  void ToggleImmediateRef(bool ref);
1191
1192
  inline void PushShouldNotAbortOnUncaughtScope();
1193
  inline void PopShouldNotAbortOnUncaughtScope();
1194
  inline bool inside_should_not_abort_on_uncaught_scope() const;
1195
1196
  static inline Environment* ForAsyncHooks(AsyncHooks* hooks);
1197
1198
  v8::Local<v8::Value> GetNow();
1199
  void ScheduleTimer(int64_t duration);
1200
  void ToggleTimerRef(bool ref);
1201
1202
  inline void AddCleanupHook(void (*fn)(void*), void* arg);
1203
  inline void RemoveCleanupHook(void (*fn)(void*), void* arg);
1204
  void RunCleanup();
1205
1206
  static void BuildEmbedderGraph(v8::Isolate* isolate,
1207
                                 v8::EmbedderGraph* graph,
1208
                                 void* data);
1209
1210
  inline std::shared_ptr<EnvironmentOptions> options();
1211
  inline std::shared_ptr<HostPort> inspector_host_port();
1212
1213
20691
  inline AsyncRequest* thread_stopper() { return &thread_stopper_; }
1214
1215
#if HAVE_INSPECTOR
1216
  void set_coverage_connection(
1217
      std::unique_ptr<profiler::V8CoverageConnection> connection);
1218
  profiler::V8CoverageConnection* coverage_connection();
1219
1220
  inline void set_coverage_directory(const char* directory);
1221
  inline const std::string& coverage_directory() const;
1222
1223
  void set_cpu_profiler_connection(
1224
      std::unique_ptr<profiler::V8CpuProfilerConnection> connection);
1225
  profiler::V8CpuProfilerConnection* cpu_profiler_connection();
1226
1227
  inline void set_cpu_prof_name(const std::string& name);
1228
  inline const std::string& cpu_prof_name() const;
1229
1230
  inline void set_cpu_prof_interval(uint64_t interval);
1231
  inline uint64_t cpu_prof_interval() const;
1232
1233
  inline void set_cpu_prof_dir(const std::string& dir);
1234
  inline const std::string& cpu_prof_dir() const;
1235
1236
  void set_heap_profiler_connection(
1237
      std::unique_ptr<profiler::V8HeapProfilerConnection> connection);
1238
  profiler::V8HeapProfilerConnection* heap_profiler_connection();
1239
1240
  inline void set_heap_prof_name(const std::string& name);
1241
  inline const std::string& heap_prof_name() const;
1242
1243
  inline void set_heap_prof_dir(const std::string& dir);
1244
  inline const std::string& heap_prof_dir() const;
1245
1246
  inline void set_heap_prof_interval(uint64_t interval);
1247
  inline uint64_t heap_prof_interval() const;
1248
1249
#endif  // HAVE_INSPECTOR
1250
1251
 private:
1252
  template <typename Fn>
1253
  inline void CreateImmediate(Fn&& cb,
1254
                              v8::Local<v8::Object> keep_alive,
1255
                              bool ref);
1256
1257
  inline void ThrowError(v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
1258
                         const char* errmsg);
1259
1260
  std::list<binding::DLib> loaded_addons_;
1261
  v8::Isolate* const isolate_;
1262
  IsolateData* const isolate_data_;
1263
  uv_timer_t timer_handle_;
1264
  uv_check_t immediate_check_handle_;
1265
  uv_idle_t immediate_idle_handle_;
1266
  uv_prepare_t idle_prepare_handle_;
1267
  uv_check_t idle_check_handle_;
1268
  bool profiler_idle_notifier_started_ = false;
1269
1270
  AsyncHooks async_hooks_;
1271
  ImmediateInfo immediate_info_;
1272
  TickInfo tick_info_;
1273
  const uint64_t timer_base_;
1274
  std::shared_ptr<KVStore> env_vars_;
1275
  bool printed_error_ = false;
1276
  bool trace_sync_io_ = false;
1277
  bool emit_env_nonstring_warning_ = true;
1278
  bool emit_err_name_warning_ = true;
1279
  size_t async_callback_scope_depth_ = 0;
1280
  std::vector<double> destroy_async_id_list_;
1281
1282
#if HAVE_INSPECTOR
1283
  std::unique_ptr<profiler::V8CoverageConnection> coverage_connection_;
1284
  std::unique_ptr<profiler::V8CpuProfilerConnection> cpu_profiler_connection_;
1285
  std::string coverage_directory_;
1286
  std::string cpu_prof_dir_;
1287
  std::string cpu_prof_name_;
1288
  uint64_t cpu_prof_interval_;
1289
  std::unique_ptr<profiler::V8HeapProfilerConnection> heap_profiler_connection_;
1290
  std::string heap_prof_dir_;
1291
  std::string heap_prof_name_;
1292
  uint64_t heap_prof_interval_;
1293
#endif  // HAVE_INSPECTOR
1294
1295
  std::shared_ptr<EnvironmentOptions> options_;
1296
  // options_ contains debug options parsed from CLI arguments,
1297
  // while inspector_host_port_ stores the actual inspector host
1298
  // and port being used. For example the port is -1 by default
1299
  // and can be specified as 0 (meaning any port allocated when the
1300
  // server starts listening), but when the inspector server starts
1301
  // the inspector_host_port_->port() will be the actual port being
1302
  // used.
1303
  std::shared_ptr<HostPort> inspector_host_port_;
1304
  std::vector<std::string> exec_argv_;
1305
  std::vector<std::string> argv_;
1306
  std::string exec_path_;
1307
1308
  uint32_t module_id_counter_ = 0;
1309
  uint32_t script_id_counter_ = 0;
1310
  uint32_t function_id_counter_ = 0;
1311
1312
  AliasedUint32Array should_abort_on_uncaught_toggle_;
1313
  int should_not_abort_scope_counter_ = 0;
1314
1315
  std::unique_ptr<TrackingTraceStateObserver> trace_state_observer_;
1316
1317
  AliasedInt32Array stream_base_state_;
1318
1319
  std::unique_ptr<performance::performance_state> performance_state_;
1320
  std::unordered_map<std::string, uint64_t> performance_marks_;
1321
1322
  bool has_run_bootstrapping_code_ = false;
1323
  bool has_serialized_options_ = false;
1324
1325
  bool can_call_into_js_ = true;
1326
  Flags flags_;
1327
  uint64_t thread_id_;
1328
  std::unordered_set<worker::Worker*> sub_worker_contexts_;
1329
1330
  static void* const kNodeContextTagPtr;
1331
  static int const kNodeContextTag;
1332
1333
#if HAVE_INSPECTOR
1334
  std::unique_ptr<inspector::Agent> inspector_agent_;
1335
  bool is_in_inspector_console_call_ = false;
1336
#endif
1337
1338
  // handle_wrap_queue_ and req_wrap_queue_ needs to be at a fixed offset from
1339
  // the start of the class because it is used by
1340
  // src/node_postmortem_metadata.cc to calculate offsets and generate debug
1341
  // symbols for Environment, which assumes that the position of members in
1342
  // memory are predictable. For more information please refer to
1343
  // `doc/guides/node-postmortem-support.md`
1344
  friend int GenDebugSymbols();
1345
  HandleWrapQueue handle_wrap_queue_;
1346
  ReqWrapQueue req_wrap_queue_;
1347
  std::list<HandleCleanup> handle_cleanup_queue_;
1348
  int handle_cleanup_waiting_ = 0;
1349
  int request_waiting_ = 0;
1350
1351
  double* heap_statistics_buffer_ = nullptr;
1352
  double* heap_space_statistics_buffer_ = nullptr;
1353
  double* heap_code_statistics_buffer_ = nullptr;
1354
1355
  char* http_parser_buffer_ = nullptr;
1356
  bool http_parser_buffer_in_use_ = false;
1357
  std::unique_ptr<http2::Http2State> http2_state_;
1358
1359
  bool debug_enabled_[static_cast<int>(DebugCategory::CATEGORY_COUNT)] = {0};
1360
1361
  AliasedFloat64Array fs_stats_field_array_;
1362
  AliasedBigUint64Array fs_stats_field_bigint_array_;
1363
1364
  std::vector<std::unique_ptr<fs::FileHandleReadWrap>>
1365
      file_handle_read_wrap_freelist_;
1366
1367
  worker::Worker* worker_context_ = nullptr;
1368
1369
  static void RunTimers(uv_timer_t* handle);
1370
1371
  struct ExitCallback {
1372
    void (*cb_)(void* arg);
1373
    void* arg_;
1374
  };
1375
  std::list<ExitCallback> before_exit_functions_;
1376
1377
  std::list<ExitCallback> at_exit_functions_;
1378
1379
  class NativeImmediateCallback {
1380
   public:
1381
    explicit inline NativeImmediateCallback(bool refed);
1382
1383
55260
    virtual ~NativeImmediateCallback() = default;
1384
    virtual void Call(Environment* env) = 0;
1385
1386
    inline bool is_refed() const;
1387
    inline std::unique_ptr<NativeImmediateCallback> get_next();
1388
    inline void set_next(std::unique_ptr<NativeImmediateCallback> next);
1389
1390
   private:
1391
    bool refed_;
1392
    std::unique_ptr<NativeImmediateCallback> next_;
1393
  };
1394
1395
  template <typename Fn>
1396



165780
  class NativeImmediateCallbackImpl final : public NativeImmediateCallback {
1397
   public:
1398
    NativeImmediateCallbackImpl(Fn&& callback,
1399
                                v8::Global<v8::Object>&& keep_alive,
1400
                                bool refed);
1401
    void Call(Environment* env) override;
1402
1403
   private:
1404
    Fn callback_;
1405
    v8::Global<v8::Object> keep_alive_;
1406
  };
1407
1408
  std::unique_ptr<NativeImmediateCallback> native_immediate_callbacks_head_;
1409
  NativeImmediateCallback* native_immediate_callbacks_tail_ = nullptr;
1410
1411
  void RunAndClearNativeImmediates();
1412
  static void CheckImmediate(uv_check_t* handle);
1413
1414
  // Use an unordered_set, so that we have efficient insertion and removal.
1415
  std::unordered_set<CleanupHookCallback,
1416
                     CleanupHookCallback::Hash,
1417
                     CleanupHookCallback::Equal> cleanup_hooks_;
1418
  uint64_t cleanup_hook_counter_ = 0;
1419
  bool started_cleanup_ = false;
1420
1421
  // A custom async abstraction (a pair of async handle and a state variable)
1422
  // Used by embedders to shutdown running Node instance.
1423
  AsyncRequest thread_stopper_;
1424
1425
  template <typename T>
1426
  void ForEachBaseObject(T&& iterator);
1427
1428
#define V(PropertyName, TypeName) v8::Global<TypeName> PropertyName ## _;
1429
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1430
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1431
#undef V
1432
1433
  v8::Global<v8::Context> context_;
1434
};
1435
1436
}  // namespace node
1437
1438
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1439
1440
#endif  // SRC_ENV_H_