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