GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.h Lines: 43 43 100.0 %
Date: 2022-08-02 04:16:51 Branches: 1 2 50.0 %

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