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