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