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