GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.h Lines: 41 41 100.0 %
Date: 2021-09-20 04:12:42 Branches: 1 2 50.0 %

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 "callback_queue.h"
33
#include "debug_utils.h"
34
#include "handle_wrap.h"
35
#include "node.h"
36
#include "node_binding.h"
37
#include "node_main_instance.h"
38
#include "node_options.h"
39
#include "node_perf_common.h"
40
#include "node_snapshotable.h"
41
#include "req_wrap.h"
42
#include "util.h"
43
#include "uv.h"
44
#include "v8.h"
45
46
#include <array>
47
#include <atomic>
48
#include <cstdint>
49
#include <functional>
50
#include <iostream>
51
#include <list>
52
#include <unordered_map>
53
#include <unordered_set>
54
#include <vector>
55
56
namespace node {
57
58
namespace contextify {
59
class ContextifyScript;
60
class CompiledFnEntry;
61
}
62
63
namespace performance {
64
class PerformanceState;
65
}
66
67
namespace tracing {
68
class AgentWriterHandle;
69
}
70
71
#if HAVE_INSPECTOR
72
namespace profiler {
73
class V8CoverageConnection;
74
class V8CpuProfilerConnection;
75
class V8HeapProfilerConnection;
76
}  // namespace profiler
77
78
namespace inspector {
79
class ParentInspectorHandle;
80
}
81
#endif  // HAVE_INSPECTOR
82
83
namespace worker {
84
class Worker;
85
}
86
87
namespace loader {
88
class ModuleWrap;
89
90
struct PackageConfig {
91
  enum class Exists { Yes, No };
92
  enum class IsValid { Yes, No };
93
  enum class HasMain { Yes, No };
94
  enum class HasName { Yes, No };
95
  enum PackageType : uint32_t { None = 0, CommonJS, Module };
96
97
  const Exists exists;
98
  const IsValid is_valid;
99
  const HasMain has_main;
100
  const std::string main;
101
  const HasName has_name;
102
  const std::string name;
103
  const PackageType type;
104
105
  v8::Global<v8::Value> exports;
106
};
107
}  // namespace loader
108
109
enum class FsStatsOffset {
110
  kDev = 0,
111
  kMode,
112
  kNlink,
113
  kUid,
114
  kGid,
115
  kRdev,
116
  kBlkSize,
117
  kIno,
118
  kSize,
119
  kBlocks,
120
  kATimeSec,
121
  kATimeNsec,
122
  kMTimeSec,
123
  kMTimeNsec,
124
  kCTimeSec,
125
  kCTimeNsec,
126
  kBirthTimeSec,
127
  kBirthTimeNsec,
128
  kFsStatsFieldsNumber
129
};
130
131
// Stat fields buffers contain twice the number of entries in an uv_stat_t
132
// because `fs.StatWatcher` needs room to store 2 `fs.Stats` instances.
133
constexpr size_t kFsStatsBufferLength =
134
    static_cast<size_t>(FsStatsOffset::kFsStatsFieldsNumber) * 2;
135
136
// PER_ISOLATE_* macros: We have a lot of per-isolate properties
137
// and adding and maintaining their getters and setters by hand would be
138
// difficult so let's make the preprocessor generate them for us.
139
//
140
// In each macro, `V` is expected to be the name of a macro or function which
141
// accepts the number of arguments provided in each tuple in the macro body,
142
// typically two. The named function will be invoked against each tuple.
143
//
144
// Make sure that any macro V defined for use with the PER_ISOLATE_* macros is
145
// undefined again after use.
146
147
// Private symbols are per-isolate primitives but Environment proxies them
148
// for the sake of convenience.  Strings should be ASCII-only and have a
149
// "node:" prefix to avoid name clashes with third-party code.
150
#define PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)                              \
151
  V(alpn_buffer_private_symbol, "node:alpnBuffer")                            \
152
  V(arrow_message_private_symbol, "node:arrowMessage")                        \
153
  V(contextify_context_private_symbol, "node:contextify:context")             \
154
  V(contextify_global_private_symbol, "node:contextify:global")               \
155
  V(decorated_private_symbol, "node:decorated")                               \
156
  V(napi_type_tag, "node:napi:type_tag")                                      \
157
  V(napi_wrapper, "node:napi:wrapper")                                        \
158
  V(untransferable_object_private_symbol, "node:untransferableObject")        \
159
160
// Symbols are per-isolate primitives but Environment proxies them
161
// for the sake of convenience.
162
#define PER_ISOLATE_SYMBOL_PROPERTIES(V)                                       \
163
  V(async_id_symbol, "async_id_symbol")                                        \
164
  V(handle_onclose_symbol, "handle_onclose")                                   \
165
  V(no_message_symbol, "no_message_symbol")                                    \
166
  V(messaging_deserialize_symbol, "messaging_deserialize_symbol")              \
167
  V(messaging_transfer_symbol, "messaging_transfer_symbol")                    \
168
  V(messaging_clone_symbol, "messaging_clone_symbol")                          \
169
  V(messaging_transfer_list_symbol, "messaging_transfer_list_symbol")          \
170
  V(oninit_symbol, "oninit")                                                   \
171
  V(owner_symbol, "owner_symbol")                                              \
172
  V(onpskexchange_symbol, "onpskexchange")                                     \
173
  V(trigger_async_id_symbol, "trigger_async_id_symbol")                        \
174
175
// Strings are per-isolate primitives but Environment proxies them
176
// for the sake of convenience.  Strings should be ASCII-only.
177
#define PER_ISOLATE_STRING_PROPERTIES(V)                                       \
178
  V(ack_string, "ack")                                                         \
179
  V(address_string, "address")                                                 \
180
  V(aliases_string, "aliases")                                                 \
181
  V(args_string, "args")                                                       \
182
  V(asn1curve_string, "asn1Curve")                                             \
183
  V(async_ids_stack_string, "async_ids_stack")                                 \
184
  V(bits_string, "bits")                                                       \
185
  V(block_list_string, "blockList")                                            \
186
  V(buffer_string, "buffer")                                                   \
187
  V(bytes_parsed_string, "bytesParsed")                                        \
188
  V(bytes_read_string, "bytesRead")                                            \
189
  V(bytes_written_string, "bytesWritten")                                      \
190
  V(cached_data_produced_string, "cachedDataProduced")                         \
191
  V(cached_data_rejected_string, "cachedDataRejected")                         \
192
  V(cached_data_string, "cachedData")                                          \
193
  V(cache_key_string, "cacheKey")                                              \
194
  V(change_string, "change")                                                   \
195
  V(channel_string, "channel")                                                 \
196
  V(chunks_sent_since_last_write_string, "chunksSentSinceLastWrite")           \
197
  V(clone_unsupported_type_str, "Cannot transfer object of unsupported type.") \
198
  V(code_string, "code")                                                       \
199
  V(commonjs_string, "commonjs")                                               \
200
  V(config_string, "config")                                                   \
201
  V(constants_string, "constants")                                             \
202
  V(crypto_dh_string, "dh")                                                    \
203
  V(crypto_dsa_string, "dsa")                                                  \
204
  V(crypto_ec_string, "ec")                                                    \
205
  V(crypto_ed25519_string, "ed25519")                                          \
206
  V(crypto_ed448_string, "ed448")                                              \
207
  V(crypto_x25519_string, "x25519")                                            \
208
  V(crypto_x448_string, "x448")                                                \
209
  V(crypto_rsa_string, "rsa")                                                  \
210
  V(crypto_rsa_pss_string, "rsa-pss")                                          \
211
  V(cwd_string, "cwd")                                                         \
212
  V(data_string, "data")                                                       \
213
  V(default_is_true_string, "defaultIsTrue")                                   \
214
  V(deserialize_info_string, "deserializeInfo")                                \
215
  V(dest_string, "dest")                                                       \
216
  V(destroyed_string, "destroyed")                                             \
217
  V(detached_string, "detached")                                               \
218
  V(dh_string, "DH")                                                           \
219
  V(divisor_length_string, "divisorLength")                                    \
220
  V(dns_a_string, "A")                                                         \
221
  V(dns_aaaa_string, "AAAA")                                                   \
222
  V(dns_caa_string, "CAA")                                                     \
223
  V(dns_critical_string, "critical")                                           \
224
  V(dns_cname_string, "CNAME")                                                 \
225
  V(dns_mx_string, "MX")                                                       \
226
  V(dns_naptr_string, "NAPTR")                                                 \
227
  V(dns_ns_string, "NS")                                                       \
228
  V(dns_ptr_string, "PTR")                                                     \
229
  V(dns_soa_string, "SOA")                                                     \
230
  V(dns_srv_string, "SRV")                                                     \
231
  V(dns_txt_string, "TXT")                                                     \
232
  V(done_string, "done")                                                       \
233
  V(duration_string, "duration")                                               \
234
  V(ecdh_string, "ECDH")                                                       \
235
  V(emit_string, "emit")                                                       \
236
  V(emit_warning_string, "emitWarning")                                        \
237
  V(empty_object_string, "{}")                                                 \
238
  V(encoding_string, "encoding")                                               \
239
  V(entries_string, "entries")                                                 \
240
  V(entry_type_string, "entryType")                                            \
241
  V(env_pairs_string, "envPairs")                                              \
242
  V(env_var_settings_string, "envVarSettings")                                 \
243
  V(errno_string, "errno")                                                     \
244
  V(error_string, "error")                                                     \
245
  V(exchange_string, "exchange")                                               \
246
  V(exit_code_string, "exitCode")                                              \
247
  V(expire_string, "expire")                                                   \
248
  V(exponent_string, "exponent")                                               \
249
  V(exports_string, "exports")                                                 \
250
  V(ext_key_usage_string, "ext_key_usage")                                     \
251
  V(external_stream_string, "_externalStream")                                 \
252
  V(family_string, "family")                                                   \
253
  V(fatal_exception_string, "_fatalException")                                 \
254
  V(fd_string, "fd")                                                           \
255
  V(fields_string, "fields")                                                   \
256
  V(file_string, "file")                                                       \
257
  V(filename_string, "filename")                                               \
258
  V(fingerprint256_string, "fingerprint256")                                   \
259
  V(fingerprint_string, "fingerprint")                                         \
260
  V(flags_string, "flags")                                                     \
261
  V(flowlabel_string, "flowlabel")                                             \
262
  V(fragment_string, "fragment")                                               \
263
  V(frames_received_string, "framesReceived")                                  \
264
  V(frames_sent_string, "framesSent")                                          \
265
  V(function_string, "function")                                               \
266
  V(get_data_clone_error_string, "_getDataCloneError")                         \
267
  V(get_shared_array_buffer_id_string, "_getSharedArrayBufferId")              \
268
  V(gid_string, "gid")                                                         \
269
  V(h2_string, "h2")                                                           \
270
  V(handle_string, "handle")                                                   \
271
  V(hash_algorithm_string, "hashAlgorithm")                                    \
272
  V(help_text_string, "helpText")                                              \
273
  V(homedir_string, "homedir")                                                 \
274
  V(host_string, "host")                                                       \
275
  V(hostmaster_string, "hostmaster")                                           \
276
  V(http_1_1_string, "http/1.1")                                               \
277
  V(id_string, "id")                                                           \
278
  V(identity_string, "identity")                                               \
279
  V(ignore_string, "ignore")                                                   \
280
  V(infoaccess_string, "infoAccess")                                           \
281
  V(inherit_string, "inherit")                                                 \
282
  V(input_string, "input")                                                     \
283
  V(internal_binding_string, "internalBinding")                                \
284
  V(internal_string, "internal")                                               \
285
  V(ipv4_string, "IPv4")                                                       \
286
  V(ipv6_string, "IPv6")                                                       \
287
  V(isclosing_string, "isClosing")                                             \
288
  V(issuer_string, "issuer")                                                   \
289
  V(issuercert_string, "issuerCertificate")                                    \
290
  V(jwk_crv_string, "crv")                                                     \
291
  V(jwk_d_string, "d")                                                         \
292
  V(jwk_dp_string, "dp")                                                       \
293
  V(jwk_dq_string, "dq")                                                       \
294
  V(jwk_dsa_string, "DSA")                                                     \
295
  V(jwk_e_string, "e")                                                         \
296
  V(jwk_ec_string, "EC")                                                       \
297
  V(jwk_g_string, "g")                                                         \
298
  V(jwk_k_string, "k")                                                         \
299
  V(jwk_p_string, "p")                                                         \
300
  V(jwk_q_string, "q")                                                         \
301
  V(jwk_qi_string, "qi")                                                       \
302
  V(jwk_kty_string, "kty")                                                     \
303
  V(jwk_n_string, "n")                                                         \
304
  V(jwk_oct_string, "oct")                                                     \
305
  V(jwk_okp_string, "OKP")                                                     \
306
  V(jwk_rsa_string, "RSA")                                                     \
307
  V(jwk_x_string, "x")                                                         \
308
  V(jwk_y_string, "y")                                                         \
309
  V(kill_signal_string, "killSignal")                                          \
310
  V(kind_string, "kind")                                                       \
311
  V(length_string, "length")                                                   \
312
  V(library_string, "library")                                                 \
313
  V(mac_string, "mac")                                                         \
314
  V(max_buffer_string, "maxBuffer")                                            \
315
  V(max_concurrent_streams_string, "maxConcurrentStreams")                     \
316
  V(message_port_constructor_string, "MessagePort")                            \
317
  V(message_port_string, "messagePort")                                        \
318
  V(message_string, "message")                                                 \
319
  V(messageerror_string, "messageerror")                                       \
320
  V(mgf1_hash_algorithm_string, "mgf1HashAlgorithm")                           \
321
  V(minttl_string, "minttl")                                                   \
322
  V(module_string, "module")                                                   \
323
  V(modulus_string, "modulus")                                                 \
324
  V(modulus_length_string, "modulusLength")                                    \
325
  V(name_string, "name")                                                       \
326
  V(named_curve_string, "namedCurve")                                          \
327
  V(netmask_string, "netmask")                                                 \
328
  V(next_string, "next")                                                       \
329
  V(nistcurve_string, "nistCurve")                                             \
330
  V(node_string, "node")                                                       \
331
  V(nsname_string, "nsname")                                                   \
332
  V(ocsp_request_string, "OCSPRequest")                                        \
333
  V(oncertcb_string, "oncertcb")                                               \
334
  V(onchange_string, "onchange")                                               \
335
  V(onclienthello_string, "onclienthello")                                     \
336
  V(oncomplete_string, "oncomplete")                                           \
337
  V(onconnection_string, "onconnection")                                       \
338
  V(ondone_string, "ondone")                                                   \
339
  V(onerror_string, "onerror")                                                 \
340
  V(onexit_string, "onexit")                                                   \
341
  V(onhandshakedone_string, "onhandshakedone")                                 \
342
  V(onhandshakestart_string, "onhandshakestart")                               \
343
  V(onkeylog_string, "onkeylog")                                               \
344
  V(onmessage_string, "onmessage")                                             \
345
  V(onnewsession_string, "onnewsession")                                       \
346
  V(onocspresponse_string, "onocspresponse")                                   \
347
  V(onreadstart_string, "onreadstart")                                         \
348
  V(onreadstop_string, "onreadstop")                                           \
349
  V(onshutdown_string, "onshutdown")                                           \
350
  V(onsignal_string, "onsignal")                                               \
351
  V(onunpipe_string, "onunpipe")                                               \
352
  V(onwrite_string, "onwrite")                                                 \
353
  V(openssl_error_stack, "opensslErrorStack")                                  \
354
  V(options_string, "options")                                                 \
355
  V(order_string, "order")                                                     \
356
  V(output_string, "output")                                                   \
357
  V(overlapped_string, "overlapped")                                           \
358
  V(parse_error_string, "Parse Error")                                         \
359
  V(password_string, "password")                                               \
360
  V(path_string, "path")                                                       \
361
  V(pending_handle_string, "pendingHandle")                                    \
362
  V(pid_string, "pid")                                                         \
363
  V(ping_rtt_string, "pingRTT")                                                \
364
  V(pipe_source_string, "pipeSource")                                          \
365
  V(pipe_string, "pipe")                                                       \
366
  V(pipe_target_string, "pipeTarget")                                          \
367
  V(port1_string, "port1")                                                     \
368
  V(port2_string, "port2")                                                     \
369
  V(port_string, "port")                                                       \
370
  V(preference_string, "preference")                                           \
371
  V(primordials_string, "primordials")                                         \
372
  V(priority_string, "priority")                                               \
373
  V(process_string, "process")                                                 \
374
  V(promise_string, "promise")                                                 \
375
  V(psk_string, "psk")                                                         \
376
  V(pubkey_string, "pubkey")                                                   \
377
  V(public_exponent_string, "publicExponent")                                  \
378
  V(query_string, "query")                                                     \
379
  V(rate_string, "rate")                                                       \
380
  V(raw_string, "raw")                                                         \
381
  V(read_host_object_string, "_readHostObject")                                \
382
  V(readable_string, "readable")                                               \
383
  V(reason_string, "reason")                                                   \
384
  V(refresh_string, "refresh")                                                 \
385
  V(regexp_string, "regexp")                                                   \
386
  V(rename_string, "rename")                                                   \
387
  V(replacement_string, "replacement")                                         \
388
  V(require_string, "require")                                                 \
389
  V(retry_string, "retry")                                                     \
390
  V(salt_length_string, "saltLength")                                          \
391
  V(scheme_string, "scheme")                                                   \
392
  V(scopeid_string, "scopeid")                                                 \
393
  V(serial_number_string, "serialNumber")                                      \
394
  V(serial_string, "serial")                                                   \
395
  V(servername_string, "servername")                                           \
396
  V(service_string, "service")                                                 \
397
  V(session_id_string, "sessionId")                                            \
398
  V(shell_string, "shell")                                                     \
399
  V(signal_string, "signal")                                                   \
400
  V(sink_string, "sink")                                                       \
401
  V(size_string, "size")                                                       \
402
  V(sni_context_err_string, "Invalid SNI context")                             \
403
  V(sni_context_string, "sni_context")                                         \
404
  V(source_string, "source")                                                   \
405
  V(stack_string, "stack")                                                     \
406
  V(standard_name_string, "standardName")                                      \
407
  V(start_time_string, "startTime")                                            \
408
  V(state_string, "state")                                                     \
409
  V(stats_string, "stats")                                                     \
410
  V(status_string, "status")                                                   \
411
  V(stdio_string, "stdio")                                                     \
412
  V(stream_average_duration_string, "streamAverageDuration")                   \
413
  V(stream_count_string, "streamCount")                                        \
414
  V(subject_string, "subject")                                                 \
415
  V(subjectaltname_string, "subjectaltname")                                   \
416
  V(syscall_string, "syscall")                                                 \
417
  V(target_string, "target")                                                   \
418
  V(thread_id_string, "threadId")                                              \
419
  V(ticketkeycallback_string, "onticketkeycallback")                           \
420
  V(timeout_string, "timeout")                                                 \
421
  V(time_to_first_byte_string, "timeToFirstByte")                              \
422
  V(time_to_first_byte_sent_string, "timeToFirstByteSent")                     \
423
  V(time_to_first_header_string, "timeToFirstHeader")                          \
424
  V(tls_ticket_string, "tlsTicket")                                            \
425
  V(transfer_string, "transfer")                                               \
426
  V(ttl_string, "ttl")                                                         \
427
  V(type_string, "type")                                                       \
428
  V(uid_string, "uid")                                                         \
429
  V(unknown_string, "<unknown>")                                               \
430
  V(url_special_ftp_string, "ftp:")                                            \
431
  V(url_special_file_string, "file:")                                          \
432
  V(url_special_http_string, "http:")                                          \
433
  V(url_special_https_string, "https:")                                        \
434
  V(url_special_ws_string, "ws:")                                              \
435
  V(url_special_wss_string, "wss:")                                            \
436
  V(url_string, "url")                                                         \
437
  V(username_string, "username")                                               \
438
  V(valid_from_string, "valid_from")                                           \
439
  V(valid_to_string, "valid_to")                                               \
440
  V(value_string, "value")                                                     \
441
  V(verify_error_string, "verifyError")                                        \
442
  V(version_string, "version")                                                 \
443
  V(weight_string, "weight")                                                   \
444
  V(windows_hide_string, "windowsHide")                                        \
445
  V(windows_verbatim_arguments_string, "windowsVerbatimArguments")             \
446
  V(wrap_string, "wrap")                                                       \
447
  V(writable_string, "writable")                                               \
448
  V(write_host_object_string, "_writeHostObject")                              \
449
  V(write_queue_size_string, "writeQueueSize")                                 \
450
  V(x_forwarded_string, "x-forwarded-for")                                     \
451
  V(zero_return_string, "ZERO_RETURN")
452
453
#define ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)                             \
454
  V(async_wrap_ctor_template, v8::FunctionTemplate)                            \
455
  V(async_wrap_object_ctor_template, v8::FunctionTemplate)                     \
456
  V(base_object_ctor_template, v8::FunctionTemplate)                           \
457
  V(binding_data_ctor_template, v8::FunctionTemplate)                          \
458
  V(blob_constructor_template, v8::FunctionTemplate)                           \
459
  V(blocklist_constructor_template, v8::FunctionTemplate)                      \
460
  V(compiled_fn_entry_template, v8::ObjectTemplate)                            \
461
  V(dir_instance_template, v8::ObjectTemplate)                                 \
462
  V(fd_constructor_template, v8::ObjectTemplate)                               \
463
  V(fdclose_constructor_template, v8::ObjectTemplate)                          \
464
  V(filehandlereadwrap_template, v8::ObjectTemplate)                           \
465
  V(fsreqpromise_constructor_template, v8::ObjectTemplate)                     \
466
  V(handle_wrap_ctor_template, v8::FunctionTemplate)                           \
467
  V(histogram_ctor_template, v8::FunctionTemplate)                             \
468
  V(http2settings_constructor_template, v8::ObjectTemplate)                    \
469
  V(http2stream_constructor_template, v8::ObjectTemplate)                      \
470
  V(http2ping_constructor_template, v8::ObjectTemplate)                        \
471
  V(i18n_converter_template, v8::ObjectTemplate)                               \
472
  V(intervalhistogram_constructor_template, v8::FunctionTemplate)              \
473
  V(libuv_stream_wrap_ctor_template, v8::FunctionTemplate)                     \
474
  V(message_port_constructor_template, v8::FunctionTemplate)                   \
475
  V(microtask_queue_ctor_template, v8::FunctionTemplate)                       \
476
  V(pipe_constructor_template, v8::FunctionTemplate)                           \
477
  V(promise_wrap_template, v8::ObjectTemplate)                                 \
478
  V(sab_lifetimepartner_constructor_template, v8::FunctionTemplate)            \
479
  V(script_context_constructor_template, v8::FunctionTemplate)                 \
480
  V(secure_context_constructor_template, v8::FunctionTemplate)                 \
481
  V(shutdown_wrap_template, v8::ObjectTemplate)                                \
482
  V(socketaddress_constructor_template, v8::FunctionTemplate)                  \
483
  V(streambaseoutputstream_constructor_template, v8::ObjectTemplate)           \
484
  V(qlogoutputstream_constructor_template, v8::ObjectTemplate)                 \
485
  V(tcp_constructor_template, v8::FunctionTemplate)                            \
486
  V(tty_constructor_template, v8::FunctionTemplate)                            \
487
  V(write_wrap_template, v8::ObjectTemplate)                                   \
488
  V(worker_heap_snapshot_taker_template, v8::ObjectTemplate)                   \
489
  V(x509_constructor_template, v8::FunctionTemplate)
490
491
#define ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)                                \
492
  V(async_hooks_after_function, v8::Function)                                  \
493
  V(async_hooks_before_function, v8::Function)                                 \
494
  V(async_hooks_callback_trampoline, v8::Function)                             \
495
  V(async_hooks_binding, v8::Object)                                           \
496
  V(async_hooks_destroy_function, v8::Function)                                \
497
  V(async_hooks_init_function, v8::Function)                                   \
498
  V(async_hooks_promise_resolve_function, v8::Function)                        \
499
  V(buffer_prototype_object, v8::Object)                                       \
500
  V(crypto_key_object_constructor, v8::Function)                               \
501
  V(crypto_key_object_handle_constructor, v8::Function)                        \
502
  V(crypto_key_object_private_constructor, v8::Function)                       \
503
  V(crypto_key_object_public_constructor, v8::Function)                        \
504
  V(crypto_key_object_secret_constructor, v8::Function)                        \
505
  V(domexception_function, v8::Function)                                       \
506
  V(enhance_fatal_stack_after_inspector, v8::Function)                         \
507
  V(enhance_fatal_stack_before_inspector, v8::Function)                        \
508
  V(fs_use_promises_symbol, v8::Symbol)                                        \
509
  V(host_import_module_dynamically_callback, v8::Function)                     \
510
  V(host_initialize_import_meta_object_callback, v8::Function)                 \
511
  V(http2session_on_altsvc_function, v8::Function)                             \
512
  V(http2session_on_error_function, v8::Function)                              \
513
  V(http2session_on_frame_error_function, v8::Function)                        \
514
  V(http2session_on_goaway_data_function, v8::Function)                        \
515
  V(http2session_on_headers_function, v8::Function)                            \
516
  V(http2session_on_origin_function, v8::Function)                             \
517
  V(http2session_on_ping_function, v8::Function)                               \
518
  V(http2session_on_priority_function, v8::Function)                           \
519
  V(http2session_on_settings_function, v8::Function)                           \
520
  V(http2session_on_stream_close_function, v8::Function)                       \
521
  V(http2session_on_stream_trailers_function, v8::Function)                    \
522
  V(internal_binding_loader, v8::Function)                                     \
523
  V(immediate_callback_function, v8::Function)                                 \
524
  V(inspector_console_extension_installer, v8::Function)                       \
525
  V(inspector_disable_async_hooks, v8::Function)                               \
526
  V(inspector_enable_async_hooks, v8::Function)                                \
527
  V(messaging_deserialize_create_object, v8::Function)                         \
528
  V(message_port, v8::Object)                                                  \
529
  V(native_module_require, v8::Function)                                       \
530
  V(performance_entry_callback, v8::Function)                                  \
531
  V(performance_entry_template, v8::Function)                                  \
532
  V(prepare_stack_trace_callback, v8::Function)                                \
533
  V(process_object, v8::Object)                                                \
534
  V(primordials, v8::Object)                                                   \
535
  V(primordials_safe_map_prototype_object, v8::Object)                         \
536
  V(primordials_safe_set_prototype_object, v8::Object)                         \
537
  V(primordials_safe_weak_map_prototype_object, v8::Object)                    \
538
  V(primordials_safe_weak_set_prototype_object, v8::Object)                    \
539
  V(promise_hook_handler, v8::Function)                                        \
540
  V(promise_reject_callback, v8::Function)                                     \
541
  V(script_data_constructor_function, v8::Function)                            \
542
  V(source_map_cache_getter, v8::Function)                                     \
543
  V(tick_callback_function, v8::Function)                                      \
544
  V(timers_callback_function, v8::Function)                                    \
545
  V(tls_wrap_constructor_function, v8::Function)                               \
546
  V(trace_category_state_function, v8::Function)                               \
547
  V(udp_constructor_function, v8::Function)                                    \
548
  V(url_constructor_function, v8::Function)
549
550
class Environment;
551
struct AllocatedBuffer;
552
553
typedef size_t SnapshotIndex;
554
class IsolateData : public MemoryRetainer {
555
 public:
556
  IsolateData(v8::Isolate* isolate,
557
              uv_loop_t* event_loop,
558
              MultiIsolatePlatform* platform = nullptr,
559
              ArrayBufferAllocator* node_allocator = nullptr,
560
              const std::vector<size_t>* indexes = nullptr);
561
22
  SET_MEMORY_INFO_NAME(IsolateData)
562
22
  SET_SELF_SIZE(IsolateData)
563
  void MemoryInfo(MemoryTracker* tracker) const override;
564
  std::vector<size_t> Serialize(v8::SnapshotCreator* creator);
565
566
  inline uv_loop_t* event_loop() const;
567
  inline MultiIsolatePlatform* platform() const;
568
  inline std::shared_ptr<PerIsolateOptions> options();
569
  inline void set_options(std::shared_ptr<PerIsolateOptions> options);
570
571
  inline NodeArrayBufferAllocator* node_allocator() const;
572
573
  inline worker::Worker* worker_context() const;
574
  inline void set_worker_context(worker::Worker* context);
575
576
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
577
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
578
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
579
#define V(TypeName, PropertyName)                                             \
580
  inline v8::Local<TypeName> PropertyName() const;
581
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
582
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
583
  PER_ISOLATE_STRING_PROPERTIES(VS)
584
#undef V
585
#undef VY
586
#undef VS
587
#undef VP
588
  inline v8::Local<v8::String> async_wrap_provider(int index) const;
589
590
  size_t max_young_gen_size = 1;
591
  std::unordered_map<const char*, v8::Eternal<v8::String>> static_str_map;
592
593
  inline v8::Isolate* isolate() const;
594
  IsolateData(const IsolateData&) = delete;
595
  IsolateData& operator=(const IsolateData&) = delete;
596
  IsolateData(IsolateData&&) = delete;
597
  IsolateData& operator=(IsolateData&&) = delete;
598
599
 private:
600
  void DeserializeProperties(const std::vector<size_t>* indexes);
601
  void CreateProperties();
602
603
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
604
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
605
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
606
#define V(TypeName, PropertyName)                                             \
607
  v8::Eternal<TypeName> PropertyName ## _;
608
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
609
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
610
  PER_ISOLATE_STRING_PROPERTIES(VS)
611
#undef V
612
#undef VY
613
#undef VS
614
#undef VP
615
  // Keep a list of all Persistent strings used for AsyncWrap Provider types.
616
  std::array<v8::Eternal<v8::String>, AsyncWrap::PROVIDERS_LENGTH>
617
      async_wrap_providers_;
618
619
  v8::Isolate* const isolate_;
620
  uv_loop_t* const event_loop_;
621
  NodeArrayBufferAllocator* const node_allocator_;
622
  MultiIsolatePlatform* platform_;
623
  std::shared_ptr<PerIsolateOptions> options_;
624
  worker::Worker* worker_context_ = nullptr;
625
};
626
627
struct ContextInfo {
628
11509
  explicit ContextInfo(const std::string& name) : name(name) {}
629
  const std::string name;
630
  std::string origin;
631
  bool is_default = false;
632
};
633
634
class EnabledDebugList;
635
636
class KVStore {
637
 public:
638
5740
  KVStore() = default;
639
10334
  virtual ~KVStore() = default;
640
  KVStore(const KVStore&) = delete;
641
  KVStore& operator=(const KVStore&) = delete;
642
  KVStore(KVStore&&) = delete;
643
  KVStore& operator=(KVStore&&) = delete;
644
645
  virtual v8::MaybeLocal<v8::String> Get(v8::Isolate* isolate,
646
                                         v8::Local<v8::String> key) const = 0;
647
  virtual v8::Maybe<std::string> Get(const char* key) const = 0;
648
  virtual void Set(v8::Isolate* isolate,
649
                   v8::Local<v8::String> key,
650
                   v8::Local<v8::String> value) = 0;
651
  virtual int32_t Query(v8::Isolate* isolate,
652
                        v8::Local<v8::String> key) const = 0;
653
  virtual int32_t Query(const char* key) const = 0;
654
  virtual void Delete(v8::Isolate* isolate, v8::Local<v8::String> key) = 0;
655
  virtual v8::Local<v8::Array> Enumerate(v8::Isolate* isolate) const = 0;
656
657
  virtual std::shared_ptr<KVStore> Clone(v8::Isolate* isolate) const;
658
  virtual v8::Maybe<bool> AssignFromObject(v8::Local<v8::Context> context,
659
                                           v8::Local<v8::Object> entries);
660
661
  static std::shared_ptr<KVStore> CreateMapKVStore();
662
};
663
664
namespace per_process {
665
extern std::shared_ptr<KVStore> system_environment;
666
}
667
668
struct EnvSerializeInfo;
669
670
class AsyncHooks : public MemoryRetainer {
671
 public:
672
22
  SET_MEMORY_INFO_NAME(AsyncHooks)
673
22
  SET_SELF_SIZE(AsyncHooks)
674
  void MemoryInfo(MemoryTracker* tracker) const override;
675
676
  // Reason for both UidFields and Fields are that one is stored as a double*
677
  // and the other as a uint32_t*.
678
  enum Fields {
679
    kInit,
680
    kBefore,
681
    kAfter,
682
    kDestroy,
683
    kPromiseResolve,
684
    kTotals,
685
    kCheck,
686
    kStackLength,
687
    kUsesExecutionAsyncResource,
688
    kFieldsCount,
689
  };
690
691
  enum UidFields {
692
    kExecutionAsyncId,
693
    kTriggerAsyncId,
694
    kAsyncIdCounter,
695
    kDefaultTriggerAsyncId,
696
    kUidFieldsCount,
697
  };
698
699
  inline AliasedUint32Array& fields();
700
  inline AliasedFloat64Array& async_id_fields();
701
  inline AliasedFloat64Array& async_ids_stack();
702
  inline v8::Local<v8::Array> js_execution_async_resources();
703
  // Returns the native executionAsyncResource value at stack index `index`.
704
  // Resources provided on the JS side are not stored on the native stack,
705
  // in which case an empty `Local<>` is returned.
706
  // The `js_execution_async_resources` array contains the value in that case.
707
  inline v8::Local<v8::Object> native_execution_async_resource(size_t index);
708
709
  inline void SetJSPromiseHooks(v8::Local<v8::Function> init,
710
                                v8::Local<v8::Function> before,
711
                                v8::Local<v8::Function> after,
712
                                v8::Local<v8::Function> resolve);
713
714
  inline v8::Local<v8::String> provider_string(int idx);
715
716
  inline void no_force_checks();
717
  inline Environment* env();
718
719
  inline void push_async_context(double async_id, double trigger_async_id,
720
      v8::Local<v8::Object> execution_async_resource_);
721
  inline bool pop_async_context(double async_id);
722
  inline void clear_async_id_stack();  // Used in fatal exceptions.
723
724
  inline void AddContext(v8::Local<v8::Context> ctx);
725
  inline void RemoveContext(v8::Local<v8::Context> ctx);
726
727
  AsyncHooks(const AsyncHooks&) = delete;
728
  AsyncHooks& operator=(const AsyncHooks&) = delete;
729
  AsyncHooks(AsyncHooks&&) = delete;
730
  AsyncHooks& operator=(AsyncHooks&&) = delete;
731
19540
  ~AsyncHooks() = default;
732
733
  // Used to set the kDefaultTriggerAsyncId in a scope. This is instead of
734
  // passing the trigger_async_id along with other constructor arguments.
735
  class DefaultTriggerAsyncIdScope {
736
   public:
737
    DefaultTriggerAsyncIdScope() = delete;
738
    explicit DefaultTriggerAsyncIdScope(Environment* env,
739
                                        double init_trigger_async_id);
740
    explicit DefaultTriggerAsyncIdScope(AsyncWrap* async_wrap);
741
    ~DefaultTriggerAsyncIdScope();
742
743
    DefaultTriggerAsyncIdScope(const DefaultTriggerAsyncIdScope&) = delete;
744
    DefaultTriggerAsyncIdScope& operator=(const DefaultTriggerAsyncIdScope&) =
745
        delete;
746
    DefaultTriggerAsyncIdScope(DefaultTriggerAsyncIdScope&&) = delete;
747
    DefaultTriggerAsyncIdScope& operator=(DefaultTriggerAsyncIdScope&&) =
748
        delete;
749
750
   private:
751
    AsyncHooks* async_hooks_;
752
    double old_default_trigger_async_id_;
753
  };
754
755
  struct SerializeInfo {
756
    AliasedBufferIndex async_ids_stack;
757
    AliasedBufferIndex fields;
758
    AliasedBufferIndex async_id_fields;
759
    SnapshotIndex js_execution_async_resources;
760
    std::vector<SnapshotIndex> native_execution_async_resources;
761
  };
762
763
  SerializeInfo Serialize(v8::Local<v8::Context> context,
764
                          v8::SnapshotCreator* creator);
765
  void Deserialize(v8::Local<v8::Context> context);
766
767
 private:
768
  friend class Environment;  // So we can call the constructor.
769
  explicit AsyncHooks(v8::Isolate* isolate, const SerializeInfo* info);
770
771
  // Stores the ids of the current execution context stack.
772
  AliasedFloat64Array async_ids_stack_;
773
  // Attached to a Uint32Array that tracks the number of active hooks for
774
  // each type.
775
  AliasedUint32Array fields_;
776
  // Attached to a Float64Array that tracks the state of async resources.
777
  AliasedFloat64Array async_id_fields_;
778
779
  void grow_async_ids_stack();
780
781
  v8::Global<v8::Array> js_execution_async_resources_;
782
  std::vector<v8::Global<v8::Object>> native_execution_async_resources_;
783
784
  // Non-empty during deserialization
785
  const SerializeInfo* info_ = nullptr;
786
787
  std::vector<v8::Global<v8::Context>> contexts_;
788
789
  std::array<v8::Global<v8::Function>, 4> js_promise_hooks_;
790
};
791
792
class ImmediateInfo : public MemoryRetainer {
793
 public:
794
  inline AliasedUint32Array& fields();
795
  inline uint32_t count() const;
796
  inline uint32_t ref_count() const;
797
  inline bool has_outstanding() const;
798
  inline void ref_count_inc(uint32_t increment);
799
  inline void ref_count_dec(uint32_t decrement);
800
801
  ImmediateInfo(const ImmediateInfo&) = delete;
802
  ImmediateInfo& operator=(const ImmediateInfo&) = delete;
803
  ImmediateInfo(ImmediateInfo&&) = delete;
804
  ImmediateInfo& operator=(ImmediateInfo&&) = delete;
805
9770
  ~ImmediateInfo() = default;
806
807
22
  SET_MEMORY_INFO_NAME(ImmediateInfo)
808
22
  SET_SELF_SIZE(ImmediateInfo)
809
  void MemoryInfo(MemoryTracker* tracker) const override;
810
811
  struct SerializeInfo {
812
    AliasedBufferIndex fields;
813
  };
814
  SerializeInfo Serialize(v8::Local<v8::Context> context,
815
                          v8::SnapshotCreator* creator);
816
  void Deserialize(v8::Local<v8::Context> context);
817
818
 private:
819
  friend class Environment;  // So we can call the constructor.
820
  explicit ImmediateInfo(v8::Isolate* isolate, const SerializeInfo* info);
821
822
  enum Fields { kCount, kRefCount, kHasOutstanding, kFieldsCount };
823
824
  AliasedUint32Array fields_;
825
};
826
827
class TickInfo : public MemoryRetainer {
828
 public:
829
  inline AliasedUint8Array& fields();
830
  inline bool has_tick_scheduled() const;
831
  inline bool has_rejection_to_warn() const;
832
833
22
  SET_MEMORY_INFO_NAME(TickInfo)
834
22
  SET_SELF_SIZE(TickInfo)
835
  void MemoryInfo(MemoryTracker* tracker) const override;
836
837
  TickInfo(const TickInfo&) = delete;
838
  TickInfo& operator=(const TickInfo&) = delete;
839
  TickInfo(TickInfo&&) = delete;
840
  TickInfo& operator=(TickInfo&&) = delete;
841
9770
  ~TickInfo() = default;
842
843
  struct SerializeInfo {
844
    AliasedBufferIndex fields;
845
  };
846
  SerializeInfo Serialize(v8::Local<v8::Context> context,
847
                          v8::SnapshotCreator* creator);
848
  void Deserialize(v8::Local<v8::Context> context);
849
850
 private:
851
  friend class Environment;  // So we can call the constructor.
852
  explicit TickInfo(v8::Isolate* isolate, const SerializeInfo* info);
853
854
  enum Fields { kHasTickScheduled = 0, kHasRejectionToWarn, kFieldsCount };
855
856
  AliasedUint8Array fields_;
857
};
858
859
class TrackingTraceStateObserver :
860
    public v8::TracingController::TraceStateObserver {
861
 public:
862
5458
  explicit TrackingTraceStateObserver(Environment* env) : env_(env) {}
863
864
87
  void OnTraceEnabled() override {
865
87
    UpdateTraceCategoryState();
866
87
  }
867
868
34
  void OnTraceDisabled() override {
869
34
    UpdateTraceCategoryState();
870
34
  }
871
872
 private:
873
  void UpdateTraceCategoryState();
874
875
  Environment* env_;
876
};
877
878
class ShouldNotAbortOnUncaughtScope {
879
 public:
880
  explicit inline ShouldNotAbortOnUncaughtScope(Environment* env);
881
  inline void Close();
882
  inline ~ShouldNotAbortOnUncaughtScope();
883
  ShouldNotAbortOnUncaughtScope(const ShouldNotAbortOnUncaughtScope&) = delete;
884
  ShouldNotAbortOnUncaughtScope& operator=(
885
      const ShouldNotAbortOnUncaughtScope&) = delete;
886
  ShouldNotAbortOnUncaughtScope(ShouldNotAbortOnUncaughtScope&&) = delete;
887
  ShouldNotAbortOnUncaughtScope& operator=(ShouldNotAbortOnUncaughtScope&&) =
888
      delete;
889
890
 private:
891
  Environment* env_;
892
};
893
894
class CleanupHookCallback {
895
 public:
896
  typedef void (*Callback)(void*);
897
898
717326
  CleanupHookCallback(Callback fn,
899
                      void* arg,
900
                      uint64_t insertion_order_counter)
901
717326
      : fn_(fn), arg_(arg), insertion_order_counter_(insertion_order_counter) {}
902
903
  // Only hashes `arg_`, since that is usually enough to identify the hook.
904
  struct Hash {
905
    inline size_t operator()(const CleanupHookCallback& cb) const;
906
  };
907
908
  // Compares by `fn_` and `arg_` being equal.
909
  struct Equal {
910
    inline bool operator()(const CleanupHookCallback& a,
911
                           const CleanupHookCallback& b) const;
912
  };
913
914
  inline BaseObject* GetBaseObject() const;
915
916
 private:
917
  friend class Environment;
918
  Callback fn_;
919
  void* arg_;
920
921
  // We keep track of the insertion order for these objects, so that we can
922
  // call the callbacks in reverse order when we are cleaning up.
923
  uint64_t insertion_order_counter_;
924
};
925
926
struct PropInfo {
927
  std::string name;     // name for debugging
928
  size_t id;            // In the list - in case there are any empty entries
929
  SnapshotIndex index;  // In the snapshot
930
};
931
932
typedef void (*DeserializeRequestCallback)(v8::Local<v8::Context> context,
933
                                           v8::Local<v8::Object> holder,
934
                                           int index,
935
                                           InternalFieldInfo* info);
936
struct DeserializeRequest {
937
  DeserializeRequestCallback cb;
938
  v8::Global<v8::Object> holder;
939
  int index;
940
  InternalFieldInfo* info = nullptr;  // Owned by the request
941
942
  // Move constructor
943
29070
  DeserializeRequest(DeserializeRequest&& other) = default;
944
};
945
946
struct EnvSerializeInfo {
947
  std::vector<PropInfo> bindings;
948
  std::vector<std::string> native_modules;
949
  AsyncHooks::SerializeInfo async_hooks;
950
  TickInfo::SerializeInfo tick_info;
951
  ImmediateInfo::SerializeInfo immediate_info;
952
  performance::PerformanceState::SerializeInfo performance_state;
953
  AliasedBufferIndex stream_base_state;
954
  AliasedBufferIndex should_abort_on_uncaught_toggle;
955
956
  std::vector<PropInfo> persistent_templates;
957
  std::vector<PropInfo> persistent_values;
958
959
  SnapshotIndex context;
960
  friend std::ostream& operator<<(std::ostream& o, const EnvSerializeInfo& i);
961
};
962
963
struct SnapshotData {
964
6
  SnapshotData() { blob.data = nullptr; }
965
  v8::StartupData blob;
966
  std::vector<size_t> isolate_data_indices;
967
  EnvSerializeInfo env_info;
968
};
969
970
class Environment : public MemoryRetainer {
971
 public:
972
  Environment(const Environment&) = delete;
973
  Environment& operator=(const Environment&) = delete;
974
  Environment(Environment&&) = delete;
975
  Environment& operator=(Environment&&) = delete;
976
977
22
  SET_MEMORY_INFO_NAME(Environment)
978
979
  inline size_t SelfSize() const override;
980
44
  bool IsRootNode() const override { return true; }
981
  void MemoryInfo(MemoryTracker* tracker) const override;
982
983
  EnvSerializeInfo Serialize(v8::SnapshotCreator* creator);
984
  void CreateProperties();
985
  void DeserializeProperties(const EnvSerializeInfo* info);
986
987
  void PrintInfoForSnapshotIfDebug();
988
  void PrintAllBaseObjects();
989
  void VerifyNoStrongBaseObjects();
990
  void EnqueueDeserializeRequest(DeserializeRequestCallback cb,
991
                                 v8::Local<v8::Object> holder,
992
                                 int index,
993
                                 InternalFieldInfo* info);
994
  void RunDeserializeRequests();
995
  // Should be called before InitializeInspector()
996
  void InitializeDiagnostics();
997
998
  std::string GetCwd();
999
1000
#if HAVE_INSPECTOR
1001
  // If the environment is created for a worker, pass parent_handle and
1002
  // the ownership if transferred into the Environment.
1003
  int InitializeInspector(
1004
      std::unique_ptr<inspector::ParentInspectorHandle> parent_handle);
1005
#endif
1006
1007
  v8::MaybeLocal<v8::Value> BootstrapInternalLoaders();
1008
  v8::MaybeLocal<v8::Value> BootstrapNode();
1009
  v8::MaybeLocal<v8::Value> RunBootstrapping();
1010
1011
  inline size_t async_callback_scope_depth() const;
1012
  inline void PushAsyncCallbackScope();
1013
  inline void PopAsyncCallbackScope();
1014
1015
  static inline Environment* GetCurrent(v8::Isolate* isolate);
1016
  static inline Environment* GetCurrent(v8::Local<v8::Context> context);
1017
  static inline Environment* GetCurrent(
1018
      const v8::FunctionCallbackInfo<v8::Value>& info);
1019
1020
  template <typename T>
1021
  static inline Environment* GetCurrent(
1022
      const v8::PropertyCallbackInfo<T>& info);
1023
1024
  // Methods created using SetMethod(), SetPrototypeMethod(), etc. inside
1025
  // this scope can access the created T* object using
1026
  // GetBindingData<T>(args) later.
1027
  template <typename T>
1028
  T* AddBindingData(v8::Local<v8::Context> context,
1029
                    v8::Local<v8::Object> target);
1030
  template <typename T, typename U>
1031
  static inline T* GetBindingData(const v8::PropertyCallbackInfo<U>& info);
1032
  template <typename T>
1033
  static inline T* GetBindingData(
1034
      const v8::FunctionCallbackInfo<v8::Value>& info);
1035
  template <typename T>
1036
  static inline T* GetBindingData(v8::Local<v8::Context> context);
1037
1038
  typedef std::unordered_map<
1039
      FastStringKey,
1040
      BaseObjectPtr<BaseObject>,
1041
      FastStringKey::Hash> BindingDataStore;
1042
1043
  // Create an Environment without initializing a main Context. Use
1044
  // InitializeMainContext() to initialize a main context for it.
1045
  Environment(IsolateData* isolate_data,
1046
              v8::Isolate* isolate,
1047
              const std::vector<std::string>& args,
1048
              const std::vector<std::string>& exec_args,
1049
              const EnvSerializeInfo* env_info,
1050
              EnvironmentFlags::Flags flags,
1051
              ThreadId thread_id);
1052
  void InitializeMainContext(v8::Local<v8::Context> context,
1053
                             const EnvSerializeInfo* env_info);
1054
  // Create an Environment and initialize the provided main context for it.
1055
  Environment(IsolateData* isolate_data,
1056
              v8::Local<v8::Context> context,
1057
              const std::vector<std::string>& args,
1058
              const std::vector<std::string>& exec_args,
1059
              const EnvSerializeInfo* env_info,
1060
              EnvironmentFlags::Flags flags,
1061
              ThreadId thread_id);
1062
  ~Environment() override;
1063
1064
  void InitializeLibuv();
1065
  inline const std::vector<std::string>& exec_argv();
1066
  inline const std::vector<std::string>& argv();
1067
  const std::string& exec_path() const;
1068
1069
  typedef void (*HandleCleanupCb)(Environment* env,
1070
                                  uv_handle_t* handle,
1071
                                  void* arg);
1072
  struct HandleCleanup {
1073
    uv_handle_t* handle_;
1074
    HandleCleanupCb cb_;
1075
    void* arg_;
1076
  };
1077
1078
  void RegisterHandleCleanups();
1079
  void CleanupHandles();
1080
  void Exit(int code);
1081
  void ExitEnv();
1082
1083
  // Register clean-up cb to be called on environment destruction.
1084
  inline void RegisterHandleCleanup(uv_handle_t* handle,
1085
                                    HandleCleanupCb cb,
1086
                                    void* arg);
1087
1088
  template <typename T, typename OnCloseCallback>
1089
  inline void CloseHandle(T* handle, OnCloseCallback callback);
1090
1091
  inline void AssignToContext(v8::Local<v8::Context> context,
1092
                              const ContextInfo& info);
1093
1094
  void StartProfilerIdleNotifier();
1095
1096
  inline v8::Isolate* isolate() const;
1097
  inline uv_loop_t* event_loop() const;
1098
  inline void TryLoadAddon(
1099
      const char* filename,
1100
      int flags,
1101
      const std::function<bool(binding::DLib*)>& was_loaded);
1102
1103
  static inline Environment* from_timer_handle(uv_timer_t* handle);
1104
  inline uv_timer_t* timer_handle();
1105
1106
  static inline Environment* from_immediate_check_handle(uv_check_t* handle);
1107
  inline uv_check_t* immediate_check_handle();
1108
  inline uv_idle_t* immediate_idle_handle();
1109
1110
  inline void IncreaseWaitingRequestCounter();
1111
  inline void DecreaseWaitingRequestCounter();
1112
1113
  inline AsyncHooks* async_hooks();
1114
  inline ImmediateInfo* immediate_info();
1115
  inline TickInfo* tick_info();
1116
  inline uint64_t timer_base() const;
1117
  inline std::shared_ptr<KVStore> env_vars();
1118
  inline void set_env_vars(std::shared_ptr<KVStore> env_vars);
1119
1120
  inline IsolateData* isolate_data() const;
1121
1122
  inline bool printed_error() const;
1123
  inline void set_printed_error(bool value);
1124
1125
  void PrintSyncTrace() const;
1126
  inline void set_trace_sync_io(bool value);
1127
1128
  inline void set_force_context_aware(bool value);
1129
  inline bool force_context_aware() const;
1130
1131
  // This stores whether the --abort-on-uncaught-exception flag was passed
1132
  // to Node.
1133
  inline bool abort_on_uncaught_exception() const;
1134
  inline void set_abort_on_uncaught_exception(bool value);
1135
  // This is a pseudo-boolean that keeps track of whether an uncaught exception
1136
  // should abort the process or not if --abort-on-uncaught-exception was
1137
  // passed to Node. If the flag was not passed, it is ignored.
1138
  inline AliasedUint32Array& should_abort_on_uncaught_toggle();
1139
1140
  inline AliasedInt32Array& stream_base_state();
1141
1142
  // The necessary API for async_hooks.
1143
  inline double new_async_id();
1144
  inline double execution_async_id();
1145
  inline double trigger_async_id();
1146
  inline double get_default_trigger_async_id();
1147
1148
  // List of id's that have been destroyed and need the destroy() cb called.
1149
  inline std::vector<double>* destroy_async_id_list();
1150
1151
  std::set<struct node_module*> internal_bindings;
1152
  std::set<std::string> native_modules_with_cache;
1153
  std::set<std::string> native_modules_without_cache;
1154
  // This is only filled during deserialization. We use a vector since
1155
  // it's only used for tests.
1156
  std::vector<std::string> native_modules_in_snapshot;
1157
1158
  std::unordered_multimap<int, loader::ModuleWrap*> hash_to_module_map;
1159
  std::unordered_map<uint32_t, loader::ModuleWrap*> id_to_module_map;
1160
  std::unordered_map<uint32_t, contextify::ContextifyScript*>
1161
      id_to_script_map;
1162
  std::unordered_map<uint32_t, contextify::CompiledFnEntry*> id_to_function_map;
1163
1164
  inline uint32_t get_next_module_id();
1165
  inline uint32_t get_next_script_id();
1166
  inline uint32_t get_next_function_id();
1167
1168
1304536
  EnabledDebugList* enabled_debug_list() { return &enabled_debug_list_; }
1169
1170
  inline performance::PerformanceState* performance_state();
1171
1172
  void CollectUVExceptionInfo(v8::Local<v8::Value> context,
1173
                              int errorno,
1174
                              const char* syscall = nullptr,
1175
                              const char* message = nullptr,
1176
                              const char* path = nullptr,
1177
                              const char* dest = nullptr);
1178
1179
  // If this flag is set, calls into JS (if they would be observable
1180
  // from userland) must be avoided.  This flag does not indicate whether
1181
  // calling into JS is allowed from a VM perspective at this point.
1182
  inline bool can_call_into_js() const;
1183
  inline void set_can_call_into_js(bool can_call_into_js);
1184
1185
  // Increase or decrease a counter that manages whether this Environment
1186
  // keeps the event loop alive on its own or not. The counter starts out at 0,
1187
  // meaning it does not, and any positive value will make it keep the event
1188
  // loop alive.
1189
  // This is used by Workers to manage their own .ref()/.unref() implementation,
1190
  // as Workers aren't directly associated with their own libuv handles.
1191
  inline void add_refs(int64_t diff);
1192
1193
  inline bool has_run_bootstrapping_code() const;
1194
  inline void DoneBootstrapping();
1195
1196
  inline bool has_serialized_options() const;
1197
  inline void set_has_serialized_options(bool has_serialized_options);
1198
1199
  inline bool is_main_thread() const;
1200
  inline bool no_native_addons() const;
1201
  inline bool should_not_register_esm_loader() const;
1202
  inline bool owns_process_state() const;
1203
  inline bool owns_inspector() const;
1204
  inline bool tracks_unmanaged_fds() const;
1205
  inline bool hide_console_windows() const;
1206
  inline bool no_global_search_paths() const;
1207
  inline uint64_t thread_id() const;
1208
  inline worker::Worker* worker_context() const;
1209
  Environment* worker_parent_env() const;
1210
  inline void add_sub_worker_context(worker::Worker* context);
1211
  inline void remove_sub_worker_context(worker::Worker* context);
1212
  void stop_sub_worker_contexts();
1213
  template <typename Fn>
1214
  inline void ForEachWorker(Fn&& iterator);
1215
  inline bool is_stopping() const;
1216
  inline void set_stopping(bool value);
1217
  inline std::list<node_module>* extra_linked_bindings();
1218
  inline node_module* extra_linked_bindings_head();
1219
  inline node_module* extra_linked_bindings_tail();
1220
  inline const Mutex& extra_linked_bindings_mutex() const;
1221
1222
  inline bool filehandle_close_warning() const;
1223
  inline void set_filehandle_close_warning(bool on);
1224
1225
  inline void set_source_maps_enabled(bool on);
1226
  inline bool source_maps_enabled() const;
1227
1228
  inline void ThrowError(const char* errmsg);
1229
  inline void ThrowTypeError(const char* errmsg);
1230
  inline void ThrowRangeError(const char* errmsg);
1231
  inline void ThrowErrnoException(int errorno,
1232
                                  const char* syscall = nullptr,
1233
                                  const char* message = nullptr,
1234
                                  const char* path = nullptr);
1235
  inline void ThrowUVException(int errorno,
1236
                               const char* syscall = nullptr,
1237
                               const char* message = nullptr,
1238
                               const char* path = nullptr,
1239
                               const char* dest = nullptr);
1240
1241
  inline v8::Local<v8::FunctionTemplate>
1242
      NewFunctionTemplate(v8::FunctionCallback callback,
1243
                          v8::Local<v8::Signature> signature =
1244
                              v8::Local<v8::Signature>(),
1245
                          v8::ConstructorBehavior behavior =
1246
                              v8::ConstructorBehavior::kAllow,
1247
                          v8::SideEffectType side_effect =
1248
                              v8::SideEffectType::kHasSideEffect);
1249
1250
  // Convenience methods for NewFunctionTemplate().
1251
  inline void SetMethod(v8::Local<v8::Object> that,
1252
                        const char* name,
1253
                        v8::FunctionCallback callback);
1254
1255
  inline void SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
1256
                             const char* name,
1257
                             v8::FunctionCallback callback);
1258
1259
  inline void SetInstanceMethod(v8::Local<v8::FunctionTemplate> that,
1260
                                const char* name,
1261
                                v8::FunctionCallback callback);
1262
1263
1264
  // Safe variants denote the function has no side effects.
1265
  inline void SetMethodNoSideEffect(v8::Local<v8::Object> that,
1266
                                    const char* name,
1267
                                    v8::FunctionCallback callback);
1268
  inline void SetProtoMethodNoSideEffect(v8::Local<v8::FunctionTemplate> that,
1269
                                         const char* name,
1270
                                         v8::FunctionCallback callback);
1271
1272
  enum class SetConstructorFunctionFlag {
1273
    NONE,
1274
    SET_CLASS_NAME,
1275
  };
1276
1277
  inline void SetConstructorFunction(v8::Local<v8::Object> that,
1278
                          const char* name,
1279
                          v8::Local<v8::FunctionTemplate> tmpl,
1280
                          SetConstructorFunctionFlag flag =
1281
                              SetConstructorFunctionFlag::SET_CLASS_NAME);
1282
1283
  inline void SetConstructorFunction(v8::Local<v8::Object> that,
1284
                          v8::Local<v8::String> name,
1285
                          v8::Local<v8::FunctionTemplate> tmpl,
1286
                          SetConstructorFunctionFlag flag =
1287
                              SetConstructorFunctionFlag::SET_CLASS_NAME);
1288
1289
  void AtExit(void (*cb)(void* arg), void* arg);
1290
  void RunAtExitCallbacks();
1291
1292
  void RunWeakRefCleanup();
1293
1294
  // Strings and private symbols are shared across shared contexts
1295
  // The getters simply proxy to the per-isolate primitive.
1296
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1297
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1298
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1299
#define V(TypeName, PropertyName)                                             \
1300
  inline v8::Local<TypeName> PropertyName() const;
1301
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1302
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1303
  PER_ISOLATE_STRING_PROPERTIES(VS)
1304
#undef V
1305
#undef VS
1306
#undef VY
1307
#undef VP
1308
1309
#define V(PropertyName, TypeName)                                             \
1310
  inline v8::Local<TypeName> PropertyName() const;                            \
1311
  inline void set_ ## PropertyName(v8::Local<TypeName> value);
1312
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1313
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1314
#undef V
1315
1316
  inline v8::Local<v8::Context> context() const;
1317
1318
#if HAVE_INSPECTOR
1319
74313
  inline inspector::Agent* inspector_agent() const {
1320
74313
    return inspector_agent_.get();
1321
  }
1322
1323
  inline bool is_in_inspector_console_call() const;
1324
  inline void set_is_in_inspector_console_call(bool value);
1325
#endif
1326
1327
  typedef ListHead<HandleWrap, &HandleWrap::handle_wrap_queue_> HandleWrapQueue;
1328
  typedef ListHead<ReqWrapBase, &ReqWrapBase::req_wrap_queue_> ReqWrapQueue;
1329
1330
57134
  inline HandleWrapQueue* handle_wrap_queue() { return &handle_wrap_queue_; }
1331
75865
  inline ReqWrapQueue* req_wrap_queue() { return &req_wrap_queue_; }
1332
1333
1
  inline bool EmitProcessEnvWarning() {
1334
1
    bool current_value = emit_env_nonstring_warning_;
1335
1
    emit_env_nonstring_warning_ = false;
1336
1
    return current_value;
1337
  }
1338
1339
1
  inline bool EmitErrNameWarning() {
1340
1
    bool current_value = emit_err_name_warning_;
1341
1
    emit_err_name_warning_ = false;
1342
1
    return current_value;
1343
  }
1344
1345
  // cb will be called as cb(env) on the next event loop iteration.
1346
  // Unlike the JS setImmediate() function, nested SetImmediate() calls will
1347
  // be run without returning control to the event loop, similar to nextTick().
1348
  template <typename Fn>
1349
  inline void SetImmediate(
1350
      Fn&& cb, CallbackFlags::Flags flags = CallbackFlags::kRefed);
1351
  template <typename Fn>
1352
  // This behaves like SetImmediate() but can be called from any thread.
1353
  inline void SetImmediateThreadsafe(
1354
      Fn&& cb, CallbackFlags::Flags flags = CallbackFlags::kRefed);
1355
  // This behaves like V8's Isolate::RequestInterrupt(), but also accounts for
1356
  // the event loop (i.e. combines the V8 function with SetImmediate()).
1357
  // The passed callback may not throw exceptions.
1358
  // This function can be called from any thread.
1359
  template <typename Fn>
1360
  inline void RequestInterrupt(Fn&& cb);
1361
  // This needs to be available for the JS-land setImmediate().
1362
  void ToggleImmediateRef(bool ref);
1363
1364
  inline void PushShouldNotAbortOnUncaughtScope();
1365
  inline void PopShouldNotAbortOnUncaughtScope();
1366
  inline bool inside_should_not_abort_on_uncaught_scope() const;
1367
1368
  static inline Environment* ForAsyncHooks(AsyncHooks* hooks);
1369
1370
  v8::Local<v8::Value> GetNow();
1371
  void ScheduleTimer(int64_t duration);
1372
  void ToggleTimerRef(bool ref);
1373
1374
  using CleanupCallback = CleanupHookCallback::Callback;
1375
  inline void AddCleanupHook(CleanupCallback cb, void* arg);
1376
  inline void RemoveCleanupHook(CleanupCallback cb, void* arg);
1377
  void RunCleanup();
1378
1379
  static size_t NearHeapLimitCallback(void* data,
1380
                                      size_t current_heap_limit,
1381
                                      size_t initial_heap_limit);
1382
  static void BuildEmbedderGraph(v8::Isolate* isolate,
1383
                                 v8::EmbedderGraph* graph,
1384
                                 void* data);
1385
1386
  inline std::shared_ptr<EnvironmentOptions> options();
1387
  inline std::shared_ptr<ExclusiveAccess<HostPort>> inspector_host_port();
1388
1389
  // The BaseObject count is a debugging helper that makes sure that there are
1390
  // no memory leaks caused by BaseObjects staying alive longer than expected
1391
  // (in particular, no circular BaseObjectPtr references).
1392
  inline void modify_base_object_count(int64_t delta);
1393
  inline int64_t base_object_created_after_bootstrap() const;
1394
  inline int64_t base_object_count() const;
1395
1396
3
  inline int32_t stack_trace_limit() const { return 10; }
1397
1398
#if HAVE_INSPECTOR
1399
  void set_coverage_connection(
1400
      std::unique_ptr<profiler::V8CoverageConnection> connection);
1401
  profiler::V8CoverageConnection* coverage_connection();
1402
1403
  inline void set_coverage_directory(const char* directory);
1404
  inline const std::string& coverage_directory() const;
1405
1406
  void set_cpu_profiler_connection(
1407
      std::unique_ptr<profiler::V8CpuProfilerConnection> connection);
1408
  profiler::V8CpuProfilerConnection* cpu_profiler_connection();
1409
1410
  inline void set_cpu_prof_name(const std::string& name);
1411
  inline const std::string& cpu_prof_name() const;
1412
1413
  inline void set_cpu_prof_interval(uint64_t interval);
1414
  inline uint64_t cpu_prof_interval() const;
1415
1416
  inline void set_cpu_prof_dir(const std::string& dir);
1417
  inline const std::string& cpu_prof_dir() const;
1418
1419
  void set_heap_profiler_connection(
1420
      std::unique_ptr<profiler::V8HeapProfilerConnection> connection);
1421
  profiler::V8HeapProfilerConnection* heap_profiler_connection();
1422
1423
  inline void set_heap_prof_name(const std::string& name);
1424
  inline const std::string& heap_prof_name() const;
1425
1426
  inline void set_heap_prof_dir(const std::string& dir);
1427
  inline const std::string& heap_prof_dir() const;
1428
1429
  inline void set_heap_prof_interval(uint64_t interval);
1430
  inline uint64_t heap_prof_interval() const;
1431
1432
#endif  // HAVE_INSPECTOR
1433
1434
  inline void set_main_utf16(std::unique_ptr<v8::String::Value>);
1435
  inline void set_process_exit_handler(
1436
      std::function<void(Environment*, int)>&& handler);
1437
1438
  void RunAndClearNativeImmediates(bool only_refed = false);
1439
  void RunAndClearInterrupts();
1440
1441
  inline std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>*
1442
      released_allocated_buffers();
1443
1444
  void AddUnmanagedFd(int fd);
1445
  void RemoveUnmanagedFd(int fd);
1446
1447
  template <typename T>
1448
  void ForEachBindingData(T&& iterator);
1449
1450
 private:
1451
  inline void ThrowError(v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
1452
                         const char* errmsg);
1453
1454
  std::list<binding::DLib> loaded_addons_;
1455
  v8::Isolate* const isolate_;
1456
  IsolateData* const isolate_data_;
1457
  uv_timer_t timer_handle_;
1458
  uv_check_t immediate_check_handle_;
1459
  uv_idle_t immediate_idle_handle_;
1460
  uv_prepare_t idle_prepare_handle_;
1461
  uv_check_t idle_check_handle_;
1462
  uv_async_t task_queues_async_;
1463
  int64_t task_queues_async_refs_ = 0;
1464
1465
  AsyncHooks async_hooks_;
1466
  ImmediateInfo immediate_info_;
1467
  TickInfo tick_info_;
1468
  const uint64_t timer_base_;
1469
  std::shared_ptr<KVStore> env_vars_;
1470
  bool printed_error_ = false;
1471
  bool trace_sync_io_ = false;
1472
  bool emit_env_nonstring_warning_ = true;
1473
  bool emit_err_name_warning_ = true;
1474
  bool emit_filehandle_warning_ = true;
1475
  bool source_maps_enabled_ = false;
1476
1477
  size_t async_callback_scope_depth_ = 0;
1478
  std::vector<double> destroy_async_id_list_;
1479
1480
#if HAVE_INSPECTOR
1481
  std::unique_ptr<profiler::V8CoverageConnection> coverage_connection_;
1482
  std::unique_ptr<profiler::V8CpuProfilerConnection> cpu_profiler_connection_;
1483
  std::string coverage_directory_;
1484
  std::string cpu_prof_dir_;
1485
  std::string cpu_prof_name_;
1486
  uint64_t cpu_prof_interval_;
1487
  std::unique_ptr<profiler::V8HeapProfilerConnection> heap_profiler_connection_;
1488
  std::string heap_prof_dir_;
1489
  std::string heap_prof_name_;
1490
  uint64_t heap_prof_interval_;
1491
#endif  // HAVE_INSPECTOR
1492
1493
  std::shared_ptr<EnvironmentOptions> options_;
1494
  // options_ contains debug options parsed from CLI arguments,
1495
  // while inspector_host_port_ stores the actual inspector host
1496
  // and port being used. For example the port is -1 by default
1497
  // and can be specified as 0 (meaning any port allocated when the
1498
  // server starts listening), but when the inspector server starts
1499
  // the inspector_host_port_->port() will be the actual port being
1500
  // used.
1501
  std::shared_ptr<ExclusiveAccess<HostPort>> inspector_host_port_;
1502
  std::vector<std::string> exec_argv_;
1503
  std::vector<std::string> argv_;
1504
  std::string exec_path_;
1505
1506
  bool is_processing_heap_limit_callback_ = false;
1507
  int64_t heap_limit_snapshot_taken_ = 0;
1508
1509
  uint32_t module_id_counter_ = 0;
1510
  uint32_t script_id_counter_ = 0;
1511
  uint32_t function_id_counter_ = 0;
1512
1513
  AliasedUint32Array should_abort_on_uncaught_toggle_;
1514
  int should_not_abort_scope_counter_ = 0;
1515
1516
  std::unique_ptr<TrackingTraceStateObserver> trace_state_observer_;
1517
1518
  AliasedInt32Array stream_base_state_;
1519
1520
  uint64_t environment_start_time_;
1521
  std::unique_ptr<performance::PerformanceState> performance_state_;
1522
1523
  bool has_run_bootstrapping_code_ = false;
1524
  bool has_serialized_options_ = false;
1525
1526
  std::atomic_bool can_call_into_js_ { true };
1527
  uint64_t flags_;
1528
  uint64_t thread_id_;
1529
  std::unordered_set<worker::Worker*> sub_worker_contexts_;
1530
1531
  static void* const kNodeContextTagPtr;
1532
  static int const kNodeContextTag;
1533
1534
#if HAVE_INSPECTOR
1535
  std::unique_ptr<inspector::Agent> inspector_agent_;
1536
  bool is_in_inspector_console_call_ = false;
1537
#endif
1538
1539
  std::list<DeserializeRequest> deserialize_requests_;
1540
1541
  // handle_wrap_queue_ and req_wrap_queue_ needs to be at a fixed offset from
1542
  // the start of the class because it is used by
1543
  // src/node_postmortem_metadata.cc to calculate offsets and generate debug
1544
  // symbols for Environment, which assumes that the position of members in
1545
  // memory are predictable. For more information please refer to
1546
  // `doc/guides/node-postmortem-support.md`
1547
  friend int GenDebugSymbols();
1548
  HandleWrapQueue handle_wrap_queue_;
1549
  ReqWrapQueue req_wrap_queue_;
1550
  std::list<HandleCleanup> handle_cleanup_queue_;
1551
  int handle_cleanup_waiting_ = 0;
1552
  int request_waiting_ = 0;
1553
1554
  EnabledDebugList enabled_debug_list_;
1555
1556
  std::list<node_module> extra_linked_bindings_;
1557
  Mutex extra_linked_bindings_mutex_;
1558
1559
  static void RunTimers(uv_timer_t* handle);
1560
1561
  struct ExitCallback {
1562
    void (*cb_)(void* arg);
1563
    void* arg_;
1564
  };
1565
1566
  std::list<ExitCallback> at_exit_functions_;
1567
1568
  typedef CallbackQueue<void, Environment*> NativeImmediateQueue;
1569
  NativeImmediateQueue native_immediates_;
1570
  Mutex native_immediates_threadsafe_mutex_;
1571
  NativeImmediateQueue native_immediates_threadsafe_;
1572
  NativeImmediateQueue native_immediates_interrupts_;
1573
  // Also guarded by native_immediates_threadsafe_mutex_. This can be used when
1574
  // trying to post tasks from other threads to an Environment, as the libuv
1575
  // handle for the immediate queues (task_queues_async_) may not be initialized
1576
  // yet or already have been destroyed.
1577
  bool task_queues_async_initialized_ = false;
1578
1579
  std::atomic<Environment**> interrupt_data_ {nullptr};
1580
  void RequestInterruptFromV8();
1581
  static void CheckImmediate(uv_check_t* handle);
1582
1583
  BindingDataStore bindings_;
1584
1585
  // Use an unordered_set, so that we have efficient insertion and removal.
1586
  std::unordered_set<CleanupHookCallback,
1587
                     CleanupHookCallback::Hash,
1588
                     CleanupHookCallback::Equal> cleanup_hooks_;
1589
  uint64_t cleanup_hook_counter_ = 0;
1590
  bool started_cleanup_ = false;
1591
1592
  int64_t base_object_count_ = 0;
1593
  int64_t base_object_created_by_bootstrap_ = 0;
1594
  std::atomic_bool is_stopping_ { false };
1595
1596
  std::unordered_set<int> unmanaged_fds_;
1597
1598
  std::function<void(Environment*, int)> process_exit_handler_ {
1599
      DefaultProcessExitHandler };
1600
1601
  template <typename T>
1602
  void ForEachBaseObject(T&& iterator);
1603
1604
#define V(PropertyName, TypeName) v8::Global<TypeName> PropertyName ## _;
1605
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1606
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1607
#undef V
1608
1609
  v8::Global<v8::Context> context_;
1610
1611
  // Keeps the main script source alive is one was passed to LoadEnvironment().
1612
  // We should probably find a way to just use plain `v8::String`s created from
1613
  // the source passed to LoadEnvironment() directly instead.
1614
  std::unique_ptr<v8::String::Value> main_utf16_;
1615
1616
  // Used by AllocatedBuffer::release() to keep track of the BackingStore for
1617
  // a given pointer.
1618
  std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>
1619
      released_allocated_buffers_;
1620
};
1621
1622
}  // namespace node
1623
1624
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1625
1626
#endif  // SRC_ENV_H_