GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.h Lines: 40 40 100.0 %
Date: 2022-06-17 04:15:42 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 ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(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(messaging_deserialize_create_object, v8::Function)                         \
547
  V(message_port, v8::Object)                                                  \
548
  V(native_module_require, v8::Function)                                       \
549
  V(performance_entry_callback, v8::Function)                                  \
550
  V(performance_entry_template, v8::Function)                                  \
551
  V(prepare_stack_trace_callback, v8::Function)                                \
552
  V(process_object, v8::Object)                                                \
553
  V(primordials, v8::Object)                                                   \
554
  V(primordials_safe_map_prototype_object, v8::Object)                         \
555
  V(primordials_safe_set_prototype_object, v8::Object)                         \
556
  V(primordials_safe_weak_map_prototype_object, v8::Object)                    \
557
  V(primordials_safe_weak_set_prototype_object, v8::Object)                    \
558
  V(promise_hook_handler, v8::Function)                                        \
559
  V(promise_reject_callback, v8::Function)                                     \
560
  V(script_data_constructor_function, v8::Function)                            \
561
  V(source_map_cache_getter, v8::Function)                                     \
562
  V(tick_callback_function, v8::Function)                                      \
563
  V(timers_callback_function, v8::Function)                                    \
564
  V(tls_wrap_constructor_function, v8::Function)                               \
565
  V(trace_category_state_function, v8::Function)                               \
566
  V(udp_constructor_function, v8::Function)                                    \
567
  V(url_constructor_function, v8::Function)                                    \
568
  V(wasm_streaming_compilation_impl, v8::Function)                             \
569
  V(wasm_streaming_object_constructor, v8::Function)
570
571
class Environment;
572
573
typedef size_t SnapshotIndex;
574
class NODE_EXTERN_PRIVATE IsolateData : public MemoryRetainer {
575
 public:
576
  IsolateData(v8::Isolate* isolate,
577
              uv_loop_t* event_loop,
578
              MultiIsolatePlatform* platform = nullptr,
579
              ArrayBufferAllocator* node_allocator = nullptr,
580
              const std::vector<size_t>* indexes = nullptr);
581
24
  SET_MEMORY_INFO_NAME(IsolateData)
582
24
  SET_SELF_SIZE(IsolateData)
583
  void MemoryInfo(MemoryTracker* tracker) const override;
584
  std::vector<size_t> Serialize(v8::SnapshotCreator* creator);
585
586
  inline uv_loop_t* event_loop() const;
587
  inline MultiIsolatePlatform* platform() const;
588
  inline std::shared_ptr<PerIsolateOptions> options();
589
  inline void set_options(std::shared_ptr<PerIsolateOptions> options);
590
591
  inline NodeArrayBufferAllocator* node_allocator() const;
592
593
  inline worker::Worker* worker_context() const;
594
  inline void set_worker_context(worker::Worker* context);
595
596
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
597
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
598
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
599
#define V(TypeName, PropertyName)                                             \
600
  inline v8::Local<TypeName> PropertyName() const;
601
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
602
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
603
  PER_ISOLATE_STRING_PROPERTIES(VS)
604
#undef V
605
#undef VY
606
#undef VS
607
#undef VP
608
  inline v8::Local<v8::String> async_wrap_provider(int index) const;
609
610
  size_t max_young_gen_size = 1;
611
  std::unordered_map<const char*, v8::Eternal<v8::String>> static_str_map;
612
613
  inline v8::Isolate* isolate() const;
614
  IsolateData(const IsolateData&) = delete;
615
  IsolateData& operator=(const IsolateData&) = delete;
616
  IsolateData(IsolateData&&) = delete;
617
  IsolateData& operator=(IsolateData&&) = delete;
618
619
 private:
620
  void DeserializeProperties(const std::vector<size_t>* indexes);
621
  void CreateProperties();
622
623
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
624
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
625
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
626
#define V(TypeName, PropertyName)                                             \
627
  v8::Eternal<TypeName> PropertyName ## _;
628
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
629
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
630
  PER_ISOLATE_STRING_PROPERTIES(VS)
631
#undef V
632
#undef VY
633
#undef VS
634
#undef VP
635
  // Keep a list of all Persistent strings used for AsyncWrap Provider types.
636
  std::array<v8::Eternal<v8::String>, AsyncWrap::PROVIDERS_LENGTH>
637
      async_wrap_providers_;
638
639
  v8::Isolate* const isolate_;
640
  uv_loop_t* const event_loop_;
641
  NodeArrayBufferAllocator* const node_allocator_;
642
  MultiIsolatePlatform* platform_;
643
  std::shared_ptr<PerIsolateOptions> options_;
644
  worker::Worker* worker_context_ = nullptr;
645
};
646
647
struct ContextInfo {
648
12710
  explicit ContextInfo(const std::string& name) : name(name) {}
649
  const std::string name;
650
  std::string origin;
651
  bool is_default = false;
652
};
653
654
class EnabledDebugList;
655
656
class KVStore {
657
 public:
658
6307
  KVStore() = default;
659
11422
  virtual ~KVStore() = default;
660
  KVStore(const KVStore&) = delete;
661
  KVStore& operator=(const KVStore&) = delete;
662
  KVStore(KVStore&&) = delete;
663
  KVStore& operator=(KVStore&&) = delete;
664
665
  virtual v8::MaybeLocal<v8::String> Get(v8::Isolate* isolate,
666
                                         v8::Local<v8::String> key) const = 0;
667
  virtual v8::Maybe<std::string> Get(const char* key) const = 0;
668
  virtual void Set(v8::Isolate* isolate,
669
                   v8::Local<v8::String> key,
670
                   v8::Local<v8::String> value) = 0;
671
  virtual int32_t Query(v8::Isolate* isolate,
672
                        v8::Local<v8::String> key) const = 0;
673
  virtual int32_t Query(const char* key) const = 0;
674
  virtual void Delete(v8::Isolate* isolate, v8::Local<v8::String> key) = 0;
675
  virtual v8::Local<v8::Array> Enumerate(v8::Isolate* isolate) const = 0;
676
677
  virtual std::shared_ptr<KVStore> Clone(v8::Isolate* isolate) const;
678
  virtual v8::Maybe<bool> AssignFromObject(v8::Local<v8::Context> context,
679
                                           v8::Local<v8::Object> entries);
680
681
  static std::shared_ptr<KVStore> CreateMapKVStore();
682
};
683
684
namespace per_process {
685
extern std::shared_ptr<KVStore> system_environment;
686
}
687
688
struct EnvSerializeInfo;
689
690
class AsyncHooks : public MemoryRetainer {
691
 public:
692
24
  SET_MEMORY_INFO_NAME(AsyncHooks)
693
24
  SET_SELF_SIZE(AsyncHooks)
694
  void MemoryInfo(MemoryTracker* tracker) const override;
695
696
  // Reason for both UidFields and Fields are that one is stored as a double*
697
  // and the other as a uint32_t*.
698
  enum Fields {
699
    kInit,
700
    kBefore,
701
    kAfter,
702
    kDestroy,
703
    kPromiseResolve,
704
    kTotals,
705
    kCheck,
706
    kStackLength,
707
    kUsesExecutionAsyncResource,
708
    kFieldsCount,
709
  };
710
711
  enum UidFields {
712
    kExecutionAsyncId,
713
    kTriggerAsyncId,
714
    kAsyncIdCounter,
715
    kDefaultTriggerAsyncId,
716
    kUidFieldsCount,
717
  };
718
719
  inline AliasedUint32Array& fields();
720
  inline AliasedFloat64Array& async_id_fields();
721
  inline AliasedFloat64Array& async_ids_stack();
722
  inline v8::Local<v8::Array> js_execution_async_resources();
723
  // Returns the native executionAsyncResource value at stack index `index`.
724
  // Resources provided on the JS side are not stored on the native stack,
725
  // in which case an empty `Local<>` is returned.
726
  // The `js_execution_async_resources` array contains the value in that case.
727
  inline v8::Local<v8::Object> native_execution_async_resource(size_t index);
728
729
  inline void SetJSPromiseHooks(v8::Local<v8::Function> init,
730
                                v8::Local<v8::Function> before,
731
                                v8::Local<v8::Function> after,
732
                                v8::Local<v8::Function> resolve);
733
734
  inline v8::Local<v8::String> provider_string(int idx);
735
736
  inline void no_force_checks();
737
  inline Environment* env();
738
739
  // NB: This call does not take (co-)ownership of `execution_async_resource`.
740
  // The lifetime of the `v8::Local<>` pointee must last until
741
  // `pop_async_context()` or `clear_async_id_stack()` are called.
742
  inline void push_async_context(double async_id, double trigger_async_id,
743
      v8::Local<v8::Object> execution_async_resource);
744
  inline bool pop_async_context(double async_id);
745
  inline void clear_async_id_stack();  // Used in fatal exceptions.
746
747
  inline void AddContext(v8::Local<v8::Context> ctx);
748
  inline void RemoveContext(v8::Local<v8::Context> ctx);
749
750
  AsyncHooks(const AsyncHooks&) = delete;
751
  AsyncHooks& operator=(const AsyncHooks&) = delete;
752
  AsyncHooks(AsyncHooks&&) = delete;
753
  AsyncHooks& operator=(AsyncHooks&&) = delete;
754
21816
  ~AsyncHooks() = default;
755
756
  // Used to set the kDefaultTriggerAsyncId in a scope. This is instead of
757
  // passing the trigger_async_id along with other constructor arguments.
758
  class DefaultTriggerAsyncIdScope {
759
   public:
760
    DefaultTriggerAsyncIdScope() = delete;
761
    explicit DefaultTriggerAsyncIdScope(Environment* env,
762
                                        double init_trigger_async_id);
763
    explicit DefaultTriggerAsyncIdScope(AsyncWrap* async_wrap);
764
    ~DefaultTriggerAsyncIdScope();
765
766
    DefaultTriggerAsyncIdScope(const DefaultTriggerAsyncIdScope&) = delete;
767
    DefaultTriggerAsyncIdScope& operator=(const DefaultTriggerAsyncIdScope&) =
768
        delete;
769
    DefaultTriggerAsyncIdScope(DefaultTriggerAsyncIdScope&&) = delete;
770
    DefaultTriggerAsyncIdScope& operator=(DefaultTriggerAsyncIdScope&&) =
771
        delete;
772
773
   private:
774
    AsyncHooks* async_hooks_;
775
    double old_default_trigger_async_id_;
776
  };
777
778
  struct SerializeInfo {
779
    AliasedBufferIndex async_ids_stack;
780
    AliasedBufferIndex fields;
781
    AliasedBufferIndex async_id_fields;
782
    SnapshotIndex js_execution_async_resources;
783
    std::vector<SnapshotIndex> native_execution_async_resources;
784
  };
785
786
  SerializeInfo Serialize(v8::Local<v8::Context> context,
787
                          v8::SnapshotCreator* creator);
788
  void Deserialize(v8::Local<v8::Context> context);
789
790
 private:
791
  friend class Environment;  // So we can call the constructor.
792
  explicit AsyncHooks(v8::Isolate* isolate, const SerializeInfo* info);
793
794
  [[noreturn]] void FailWithCorruptedAsyncStack(double expected_async_id);
795
796
  // Stores the ids of the current execution context stack.
797
  AliasedFloat64Array async_ids_stack_;
798
  // Attached to a Uint32Array that tracks the number of active hooks for
799
  // each type.
800
  AliasedUint32Array fields_;
801
  // Attached to a Float64Array that tracks the state of async resources.
802
  AliasedFloat64Array async_id_fields_;
803
804
  void grow_async_ids_stack();
805
806
  v8::Global<v8::Array> js_execution_async_resources_;
807
  std::vector<v8::Local<v8::Object>> native_execution_async_resources_;
808
809
  // Non-empty during deserialization
810
  const SerializeInfo* info_ = nullptr;
811
812
  std::vector<v8::Global<v8::Context>> contexts_;
813
814
  std::array<v8::Global<v8::Function>, 4> js_promise_hooks_;
815
};
816
817
class ImmediateInfo : public MemoryRetainer {
818
 public:
819
  inline AliasedUint32Array& fields();
820
  inline uint32_t count() const;
821
  inline uint32_t ref_count() const;
822
  inline bool has_outstanding() const;
823
  inline void ref_count_inc(uint32_t increment);
824
  inline void ref_count_dec(uint32_t decrement);
825
826
  ImmediateInfo(const ImmediateInfo&) = delete;
827
  ImmediateInfo& operator=(const ImmediateInfo&) = delete;
828
  ImmediateInfo(ImmediateInfo&&) = delete;
829
  ImmediateInfo& operator=(ImmediateInfo&&) = delete;
830
10908
  ~ImmediateInfo() = default;
831
832
24
  SET_MEMORY_INFO_NAME(ImmediateInfo)
833
24
  SET_SELF_SIZE(ImmediateInfo)
834
  void MemoryInfo(MemoryTracker* tracker) const override;
835
836
  struct SerializeInfo {
837
    AliasedBufferIndex fields;
838
  };
839
  SerializeInfo Serialize(v8::Local<v8::Context> context,
840
                          v8::SnapshotCreator* creator);
841
  void Deserialize(v8::Local<v8::Context> context);
842
843
 private:
844
  friend class Environment;  // So we can call the constructor.
845
  explicit ImmediateInfo(v8::Isolate* isolate, const SerializeInfo* info);
846
847
  enum Fields { kCount, kRefCount, kHasOutstanding, kFieldsCount };
848
849
  AliasedUint32Array fields_;
850
};
851
852
class TickInfo : public MemoryRetainer {
853
 public:
854
  inline AliasedUint8Array& fields();
855
  inline bool has_tick_scheduled() const;
856
  inline bool has_rejection_to_warn() const;
857
858
24
  SET_MEMORY_INFO_NAME(TickInfo)
859
24
  SET_SELF_SIZE(TickInfo)
860
  void MemoryInfo(MemoryTracker* tracker) const override;
861
862
  TickInfo(const TickInfo&) = delete;
863
  TickInfo& operator=(const TickInfo&) = delete;
864
  TickInfo(TickInfo&&) = delete;
865
  TickInfo& operator=(TickInfo&&) = delete;
866
10908
  ~TickInfo() = default;
867
868
  struct SerializeInfo {
869
    AliasedBufferIndex fields;
870
  };
871
  SerializeInfo Serialize(v8::Local<v8::Context> context,
872
                          v8::SnapshotCreator* creator);
873
  void Deserialize(v8::Local<v8::Context> context);
874
875
 private:
876
  friend class Environment;  // So we can call the constructor.
877
  explicit TickInfo(v8::Isolate* isolate, const SerializeInfo* info);
878
879
  enum Fields { kHasTickScheduled = 0, kHasRejectionToWarn, kFieldsCount };
880
881
  AliasedUint8Array fields_;
882
};
883
884
class TrackingTraceStateObserver :
885
    public v8::TracingController::TraceStateObserver {
886
 public:
887
6050
  explicit TrackingTraceStateObserver(Environment* env) : env_(env) {}
888
889
87
  void OnTraceEnabled() override {
890
87
    UpdateTraceCategoryState();
891
87
  }
892
893
34
  void OnTraceDisabled() override {
894
34
    UpdateTraceCategoryState();
895
34
  }
896
897
 private:
898
  void UpdateTraceCategoryState();
899
900
  Environment* env_;
901
};
902
903
class ShouldNotAbortOnUncaughtScope {
904
 public:
905
  explicit inline ShouldNotAbortOnUncaughtScope(Environment* env);
906
  inline void Close();
907
  inline ~ShouldNotAbortOnUncaughtScope();
908
  ShouldNotAbortOnUncaughtScope(const ShouldNotAbortOnUncaughtScope&) = delete;
909
  ShouldNotAbortOnUncaughtScope& operator=(
910
      const ShouldNotAbortOnUncaughtScope&) = delete;
911
  ShouldNotAbortOnUncaughtScope(ShouldNotAbortOnUncaughtScope&&) = delete;
912
  ShouldNotAbortOnUncaughtScope& operator=(ShouldNotAbortOnUncaughtScope&&) =
913
      delete;
914
915
 private:
916
  Environment* env_;
917
};
918
919
class CleanupHookCallback {
920
 public:
921
  typedef void (*Callback)(void*);
922
923
2869360
  CleanupHookCallback(Callback fn,
924
                      void* arg,
925
                      uint64_t insertion_order_counter)
926
2869360
      : fn_(fn), arg_(arg), insertion_order_counter_(insertion_order_counter) {}
927
928
  // Only hashes `arg_`, since that is usually enough to identify the hook.
929
  struct Hash {
930
    inline size_t operator()(const CleanupHookCallback& cb) const;
931
  };
932
933
  // Compares by `fn_` and `arg_` being equal.
934
  struct Equal {
935
    inline bool operator()(const CleanupHookCallback& a,
936
                           const CleanupHookCallback& b) const;
937
  };
938
939
  inline BaseObject* GetBaseObject() const;
940
941
 private:
942
  friend class Environment;
943
  Callback fn_;
944
  void* arg_;
945
946
  // We keep track of the insertion order for these objects, so that we can
947
  // call the callbacks in reverse order when we are cleaning up.
948
  uint64_t insertion_order_counter_;
949
};
950
951
struct PropInfo {
952
  std::string name;     // name for debugging
953
  size_t id;            // In the list - in case there are any empty entries
954
  SnapshotIndex index;  // In the snapshot
955
};
956
957
typedef void (*DeserializeRequestCallback)(v8::Local<v8::Context> context,
958
                                           v8::Local<v8::Object> holder,
959
                                           int index,
960
                                           InternalFieldInfo* info);
961
struct DeserializeRequest {
962
  DeserializeRequestCallback cb;
963
  v8::Global<v8::Object> holder;
964
  int index;
965
  InternalFieldInfo* info = nullptr;  // Owned by the request
966
967
  // Move constructor
968
41584
  DeserializeRequest(DeserializeRequest&& other) = default;
969
};
970
971
struct EnvSerializeInfo {
972
  std::vector<PropInfo> bindings;
973
  std::vector<std::string> native_modules;
974
  AsyncHooks::SerializeInfo async_hooks;
975
  TickInfo::SerializeInfo tick_info;
976
  ImmediateInfo::SerializeInfo immediate_info;
977
  performance::PerformanceState::SerializeInfo performance_state;
978
  AliasedBufferIndex stream_base_state;
979
  AliasedBufferIndex should_abort_on_uncaught_toggle;
980
981
  std::vector<PropInfo> persistent_templates;
982
  std::vector<PropInfo> persistent_values;
983
984
  SnapshotIndex context;
985
  friend std::ostream& operator<<(std::ostream& o, const EnvSerializeInfo& i);
986
};
987
988
struct SnapshotData {
989
  // The result of v8::SnapshotCreator::CreateBlob() during the snapshot
990
  // building process.
991
  v8::StartupData v8_snapshot_blob_data;
992
993
  static const size_t kNodeBaseContextIndex = 0;
994
  static const size_t kNodeMainContextIndex = kNodeBaseContextIndex + 1;
995
996
  std::vector<size_t> isolate_data_indices;
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
1007
class Environment : public MemoryRetainer {
1008
 public:
1009
  Environment(const Environment&) = delete;
1010
  Environment& operator=(const Environment&) = delete;
1011
  Environment(Environment&&) = delete;
1012
  Environment& operator=(Environment&&) = delete;
1013
1014
24
  SET_MEMORY_INFO_NAME(Environment)
1015
1016
  inline size_t SelfSize() const override;
1017
48
  bool IsRootNode() const override { return true; }
1018
  void MemoryInfo(MemoryTracker* tracker) const override;
1019
1020
  EnvSerializeInfo Serialize(v8::SnapshotCreator* creator);
1021
  void CreateProperties();
1022
  void DeserializeProperties(const EnvSerializeInfo* info);
1023
1024
  void PrintInfoForSnapshotIfDebug();
1025
  void PrintAllBaseObjects();
1026
  void VerifyNoStrongBaseObjects();
1027
  void EnqueueDeserializeRequest(DeserializeRequestCallback cb,
1028
                                 v8::Local<v8::Object> holder,
1029
                                 int index,
1030
                                 InternalFieldInfo* info);
1031
  void RunDeserializeRequests();
1032
  // Should be called before InitializeInspector()
1033
  void InitializeDiagnostics();
1034
1035
  std::string GetCwd();
1036
1037
#if HAVE_INSPECTOR
1038
  // If the environment is created for a worker, pass parent_handle and
1039
  // the ownership if transferred into the Environment.
1040
  int InitializeInspector(
1041
      std::unique_ptr<inspector::ParentInspectorHandle> parent_handle);
1042
#endif
1043
1044
  v8::MaybeLocal<v8::Value> BootstrapInternalLoaders();
1045
  v8::MaybeLocal<v8::Value> BootstrapNode();
1046
  v8::MaybeLocal<v8::Value> RunBootstrapping();
1047
1048
  inline size_t async_callback_scope_depth() const;
1049
  inline void PushAsyncCallbackScope();
1050
  inline void PopAsyncCallbackScope();
1051
1052
  static inline Environment* GetCurrent(v8::Isolate* isolate);
1053
  static inline Environment* GetCurrent(v8::Local<v8::Context> context);
1054
  static inline Environment* GetCurrent(
1055
      const v8::FunctionCallbackInfo<v8::Value>& info);
1056
1057
  template <typename T>
1058
  static inline Environment* GetCurrent(
1059
      const v8::PropertyCallbackInfo<T>& info);
1060
1061
  // Methods created using SetMethod(), SetPrototypeMethod(), etc. inside
1062
  // this scope can access the created T* object using
1063
  // GetBindingData<T>(args) later.
1064
  template <typename T>
1065
  T* AddBindingData(v8::Local<v8::Context> context,
1066
                    v8::Local<v8::Object> target);
1067
  template <typename T, typename U>
1068
  static inline T* GetBindingData(const v8::PropertyCallbackInfo<U>& info);
1069
  template <typename T>
1070
  static inline T* GetBindingData(
1071
      const v8::FunctionCallbackInfo<v8::Value>& info);
1072
  template <typename T>
1073
  static inline T* GetBindingData(v8::Local<v8::Context> context);
1074
1075
  typedef std::unordered_map<
1076
      FastStringKey,
1077
      BaseObjectPtr<BaseObject>,
1078
      FastStringKey::Hash> BindingDataStore;
1079
1080
  // Create an Environment without initializing a main Context. Use
1081
  // InitializeMainContext() to initialize a main context for it.
1082
  Environment(IsolateData* isolate_data,
1083
              v8::Isolate* isolate,
1084
              const std::vector<std::string>& args,
1085
              const std::vector<std::string>& exec_args,
1086
              const EnvSerializeInfo* env_info,
1087
              EnvironmentFlags::Flags flags,
1088
              ThreadId thread_id);
1089
  void InitializeMainContext(v8::Local<v8::Context> context,
1090
                             const EnvSerializeInfo* env_info);
1091
  // Create an Environment and initialize the provided main context for it.
1092
  Environment(IsolateData* isolate_data,
1093
              v8::Local<v8::Context> context,
1094
              const std::vector<std::string>& args,
1095
              const std::vector<std::string>& exec_args,
1096
              const EnvSerializeInfo* env_info,
1097
              EnvironmentFlags::Flags flags,
1098
              ThreadId thread_id);
1099
  ~Environment() override;
1100
1101
  void InitializeLibuv();
1102
  inline const std::vector<std::string>& exec_argv();
1103
  inline const std::vector<std::string>& argv();
1104
  const std::string& exec_path() const;
1105
1106
  typedef void (*HandleCleanupCb)(Environment* env,
1107
                                  uv_handle_t* handle,
1108
                                  void* arg);
1109
  struct HandleCleanup {
1110
    uv_handle_t* handle_;
1111
    HandleCleanupCb cb_;
1112
    void* arg_;
1113
  };
1114
1115
  void RegisterHandleCleanups();
1116
  void CleanupHandles();
1117
  void Exit(int code);
1118
  void ExitEnv();
1119
1120
  // Register clean-up cb to be called on environment destruction.
1121
  inline void RegisterHandleCleanup(uv_handle_t* handle,
1122
                                    HandleCleanupCb cb,
1123
                                    void* arg);
1124
1125
  template <typename T, typename OnCloseCallback>
1126
  inline void CloseHandle(T* handle, OnCloseCallback callback);
1127
1128
  inline void AssignToContext(v8::Local<v8::Context> context,
1129
                              const ContextInfo& info);
1130
1131
  void StartProfilerIdleNotifier();
1132
1133
  inline v8::Isolate* isolate() const;
1134
  inline uv_loop_t* event_loop() const;
1135
  inline void TryLoadAddon(
1136
      const char* filename,
1137
      int flags,
1138
      const std::function<bool(binding::DLib*)>& was_loaded);
1139
1140
  static inline Environment* from_timer_handle(uv_timer_t* handle);
1141
  inline uv_timer_t* timer_handle();
1142
1143
  static inline Environment* from_immediate_check_handle(uv_check_t* handle);
1144
  inline uv_check_t* immediate_check_handle();
1145
  inline uv_idle_t* immediate_idle_handle();
1146
1147
  inline void IncreaseWaitingRequestCounter();
1148
  inline void DecreaseWaitingRequestCounter();
1149
1150
  inline AsyncHooks* async_hooks();
1151
  inline ImmediateInfo* immediate_info();
1152
  inline TickInfo* tick_info();
1153
  inline uint64_t timer_base() const;
1154
  inline std::shared_ptr<KVStore> env_vars();
1155
  inline void set_env_vars(std::shared_ptr<KVStore> env_vars);
1156
1157
  inline IsolateData* isolate_data() const;
1158
1159
  inline bool printed_error() const;
1160
  inline void set_printed_error(bool value);
1161
1162
  void PrintSyncTrace() const;
1163
  inline void set_trace_sync_io(bool value);
1164
1165
  inline void set_force_context_aware(bool value);
1166
  inline bool force_context_aware() const;
1167
1168
  // This stores whether the --abort-on-uncaught-exception flag was passed
1169
  // to Node.
1170
  inline bool abort_on_uncaught_exception() const;
1171
  inline void set_abort_on_uncaught_exception(bool value);
1172
  // This is a pseudo-boolean that keeps track of whether an uncaught exception
1173
  // should abort the process or not if --abort-on-uncaught-exception was
1174
  // passed to Node. If the flag was not passed, it is ignored.
1175
  inline AliasedUint32Array& should_abort_on_uncaught_toggle();
1176
1177
  inline AliasedInt32Array& stream_base_state();
1178
1179
  // The necessary API for async_hooks.
1180
  inline double new_async_id();
1181
  inline double execution_async_id();
1182
  inline double trigger_async_id();
1183
  inline double get_default_trigger_async_id();
1184
1185
  // List of id's that have been destroyed and need the destroy() cb called.
1186
  inline std::vector<double>* destroy_async_id_list();
1187
1188
  std::set<struct node_module*> internal_bindings;
1189
  std::set<std::string> native_modules_with_cache;
1190
  std::set<std::string> native_modules_without_cache;
1191
  // This is only filled during deserialization. We use a vector since
1192
  // it's only used for tests.
1193
  std::vector<std::string> native_modules_in_snapshot;
1194
1195
  std::unordered_multimap<int, loader::ModuleWrap*> hash_to_module_map;
1196
  std::unordered_map<uint32_t, loader::ModuleWrap*> id_to_module_map;
1197
  std::unordered_map<uint32_t, contextify::ContextifyScript*>
1198
      id_to_script_map;
1199
  std::unordered_map<uint32_t, contextify::CompiledFnEntry*> id_to_function_map;
1200
1201
  inline uint32_t get_next_module_id();
1202
  inline uint32_t get_next_script_id();
1203
  inline uint32_t get_next_function_id();
1204
1205
1369932
  EnabledDebugList* enabled_debug_list() { return &enabled_debug_list_; }
1206
1207
  inline performance::PerformanceState* performance_state();
1208
1209
  void CollectUVExceptionInfo(v8::Local<v8::Value> context,
1210
                              int errorno,
1211
                              const char* syscall = nullptr,
1212
                              const char* message = nullptr,
1213
                              const char* path = nullptr,
1214
                              const char* dest = nullptr);
1215
1216
  // If this flag is set, calls into JS (if they would be observable
1217
  // from userland) must be avoided.  This flag does not indicate whether
1218
  // calling into JS is allowed from a VM perspective at this point.
1219
  inline bool can_call_into_js() const;
1220
  inline void set_can_call_into_js(bool can_call_into_js);
1221
1222
  // Increase or decrease a counter that manages whether this Environment
1223
  // keeps the event loop alive on its own or not. The counter starts out at 0,
1224
  // meaning it does not, and any positive value will make it keep the event
1225
  // loop alive.
1226
  // This is used by Workers to manage their own .ref()/.unref() implementation,
1227
  // as Workers aren't directly associated with their own libuv handles.
1228
  inline void add_refs(int64_t diff);
1229
1230
  inline bool has_run_bootstrapping_code() const;
1231
  inline void DoneBootstrapping();
1232
1233
  inline bool has_serialized_options() const;
1234
  inline void set_has_serialized_options(bool has_serialized_options);
1235
1236
  inline bool is_main_thread() const;
1237
  inline bool no_native_addons() const;
1238
  inline bool should_not_register_esm_loader() const;
1239
  inline bool should_create_inspector() const;
1240
  inline bool owns_process_state() const;
1241
  inline bool owns_inspector() const;
1242
  inline bool tracks_unmanaged_fds() const;
1243
  inline bool hide_console_windows() const;
1244
  inline bool no_global_search_paths() const;
1245
  inline bool no_browser_globals() const;
1246
  inline uint64_t thread_id() const;
1247
  inline worker::Worker* worker_context() const;
1248
  Environment* worker_parent_env() const;
1249
  inline void add_sub_worker_context(worker::Worker* context);
1250
  inline void remove_sub_worker_context(worker::Worker* context);
1251
  void stop_sub_worker_contexts();
1252
  template <typename Fn>
1253
  inline void ForEachWorker(Fn&& iterator);
1254
  inline bool is_stopping() const;
1255
  inline void set_stopping(bool value);
1256
  inline std::list<node_module>* extra_linked_bindings();
1257
  inline node_module* extra_linked_bindings_head();
1258
  inline node_module* extra_linked_bindings_tail();
1259
  inline const Mutex& extra_linked_bindings_mutex() const;
1260
1261
  inline bool filehandle_close_warning() const;
1262
  inline void set_filehandle_close_warning(bool on);
1263
1264
  inline void set_source_maps_enabled(bool on);
1265
  inline bool source_maps_enabled() const;
1266
1267
  inline void ThrowError(const char* errmsg);
1268
  inline void ThrowTypeError(const char* errmsg);
1269
  inline void ThrowRangeError(const char* errmsg);
1270
  inline void ThrowErrnoException(int errorno,
1271
                                  const char* syscall = nullptr,
1272
                                  const char* message = nullptr,
1273
                                  const char* path = nullptr);
1274
  inline void ThrowUVException(int errorno,
1275
                               const char* syscall = nullptr,
1276
                               const char* message = nullptr,
1277
                               const char* path = nullptr,
1278
                               const char* dest = nullptr);
1279
1280
  inline v8::Local<v8::FunctionTemplate> NewFunctionTemplate(
1281
      v8::FunctionCallback callback,
1282
      v8::Local<v8::Signature> signature = v8::Local<v8::Signature>(),
1283
      v8::ConstructorBehavior behavior = v8::ConstructorBehavior::kAllow,
1284
      v8::SideEffectType side_effect = v8::SideEffectType::kHasSideEffect,
1285
      const v8::CFunction* c_function = nullptr);
1286
1287
  // Convenience methods for NewFunctionTemplate().
1288
  inline void SetMethod(v8::Local<v8::Object> that,
1289
                        const char* name,
1290
                        v8::FunctionCallback callback);
1291
1292
  inline void SetFastMethod(v8::Local<v8::Object> that,
1293
                            const char* name,
1294
                            v8::FunctionCallback slow_callback,
1295
                            const v8::CFunction* c_function);
1296
1297
  inline void SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
1298
                             const char* name,
1299
                             v8::FunctionCallback callback);
1300
1301
  inline void SetInstanceMethod(v8::Local<v8::FunctionTemplate> that,
1302
                                const char* name,
1303
                                v8::FunctionCallback callback);
1304
1305
1306
  // Safe variants denote the function has no side effects.
1307
  inline void SetMethodNoSideEffect(v8::Local<v8::Object> that,
1308
                                    const char* name,
1309
                                    v8::FunctionCallback callback);
1310
  inline void SetProtoMethodNoSideEffect(v8::Local<v8::FunctionTemplate> that,
1311
                                         const char* name,
1312
                                         v8::FunctionCallback callback);
1313
1314
  enum class SetConstructorFunctionFlag {
1315
    NONE,
1316
    SET_CLASS_NAME,
1317
  };
1318
1319
  inline void SetConstructorFunction(v8::Local<v8::Object> that,
1320
                          const char* name,
1321
                          v8::Local<v8::FunctionTemplate> tmpl,
1322
                          SetConstructorFunctionFlag flag =
1323
                              SetConstructorFunctionFlag::SET_CLASS_NAME);
1324
1325
  inline void SetConstructorFunction(v8::Local<v8::Object> that,
1326
                          v8::Local<v8::String> name,
1327
                          v8::Local<v8::FunctionTemplate> tmpl,
1328
                          SetConstructorFunctionFlag flag =
1329
                              SetConstructorFunctionFlag::SET_CLASS_NAME);
1330
1331
  void AtExit(void (*cb)(void* arg), void* arg);
1332
  void RunAtExitCallbacks();
1333
1334
  void RunWeakRefCleanup();
1335
1336
  // Strings and private symbols are shared across shared contexts
1337
  // The getters simply proxy to the per-isolate primitive.
1338
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1339
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1340
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1341
#define V(TypeName, PropertyName)                                             \
1342
  inline v8::Local<TypeName> PropertyName() const;
1343
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1344
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1345
  PER_ISOLATE_STRING_PROPERTIES(VS)
1346
#undef V
1347
#undef VS
1348
#undef VY
1349
#undef VP
1350
1351
#define V(PropertyName, TypeName)                                             \
1352
  inline v8::Local<TypeName> PropertyName() const;                            \
1353
  inline void set_ ## PropertyName(v8::Local<TypeName> value);
1354
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1355
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1356
#undef V
1357
1358
  inline v8::Local<v8::Context> context() const;
1359
1360
#if HAVE_INSPECTOR
1361
76801
  inline inspector::Agent* inspector_agent() const {
1362
76801
    return inspector_agent_.get();
1363
  }
1364
1365
  inline bool is_in_inspector_console_call() const;
1366
  inline void set_is_in_inspector_console_call(bool value);
1367
#endif
1368
1369
  typedef ListHead<HandleWrap, &HandleWrap::handle_wrap_queue_> HandleWrapQueue;
1370
  typedef ListHead<ReqWrapBase, &ReqWrapBase::req_wrap_queue_> ReqWrapQueue;
1371
1372
59150
  inline HandleWrapQueue* handle_wrap_queue() { return &handle_wrap_queue_; }
1373
79927
  inline ReqWrapQueue* req_wrap_queue() { return &req_wrap_queue_; }
1374
1375
1
  inline bool EmitProcessEnvWarning() {
1376
1
    bool current_value = emit_env_nonstring_warning_;
1377
1
    emit_env_nonstring_warning_ = false;
1378
1
    return current_value;
1379
  }
1380
1381
1
  inline bool EmitErrNameWarning() {
1382
1
    bool current_value = emit_err_name_warning_;
1383
1
    emit_err_name_warning_ = false;
1384
1
    return current_value;
1385
  }
1386
1387
  // cb will be called as cb(env) on the next event loop iteration.
1388
  // Unlike the JS setImmediate() function, nested SetImmediate() calls will
1389
  // be run without returning control to the event loop, similar to nextTick().
1390
  template <typename Fn>
1391
  inline void SetImmediate(
1392
      Fn&& cb, CallbackFlags::Flags flags = CallbackFlags::kRefed);
1393
  template <typename Fn>
1394
  // This behaves like SetImmediate() but can be called from any thread.
1395
  inline void SetImmediateThreadsafe(
1396
      Fn&& cb, CallbackFlags::Flags flags = CallbackFlags::kRefed);
1397
  // This behaves like V8's Isolate::RequestInterrupt(), but also accounts for
1398
  // the event loop (i.e. combines the V8 function with SetImmediate()).
1399
  // The passed callback may not throw exceptions.
1400
  // This function can be called from any thread.
1401
  template <typename Fn>
1402
  inline void RequestInterrupt(Fn&& cb);
1403
  // This needs to be available for the JS-land setImmediate().
1404
  void ToggleImmediateRef(bool ref);
1405
1406
  inline void PushShouldNotAbortOnUncaughtScope();
1407
  inline void PopShouldNotAbortOnUncaughtScope();
1408
  inline bool inside_should_not_abort_on_uncaught_scope() const;
1409
1410
  static inline Environment* ForAsyncHooks(AsyncHooks* hooks);
1411
1412
  v8::Local<v8::Value> GetNow();
1413
  void ScheduleTimer(int64_t duration);
1414
  void ToggleTimerRef(bool ref);
1415
1416
  using CleanupCallback = CleanupHookCallback::Callback;
1417
  inline void AddCleanupHook(CleanupCallback cb, void* arg);
1418
  inline void RemoveCleanupHook(CleanupCallback cb, void* arg);
1419
  void RunCleanup();
1420
1421
  static size_t NearHeapLimitCallback(void* data,
1422
                                      size_t current_heap_limit,
1423
                                      size_t initial_heap_limit);
1424
  static void BuildEmbedderGraph(v8::Isolate* isolate,
1425
                                 v8::EmbedderGraph* graph,
1426
                                 void* data);
1427
1428
  inline std::shared_ptr<EnvironmentOptions> options();
1429
  inline std::shared_ptr<ExclusiveAccess<HostPort>> inspector_host_port();
1430
1431
  // The BaseObject count is a debugging helper that makes sure that there are
1432
  // no memory leaks caused by BaseObjects staying alive longer than expected
1433
  // (in particular, no circular BaseObjectPtr references).
1434
  inline void modify_base_object_count(int64_t delta);
1435
  inline int64_t base_object_created_after_bootstrap() const;
1436
  inline int64_t base_object_count() const;
1437
1438
3
  inline int32_t stack_trace_limit() const { return 10; }
1439
1440
#if HAVE_INSPECTOR
1441
  void set_coverage_connection(
1442
      std::unique_ptr<profiler::V8CoverageConnection> connection);
1443
  profiler::V8CoverageConnection* coverage_connection();
1444
1445
  inline void set_coverage_directory(const char* directory);
1446
  inline const std::string& coverage_directory() const;
1447
1448
  void set_cpu_profiler_connection(
1449
      std::unique_ptr<profiler::V8CpuProfilerConnection> connection);
1450
  profiler::V8CpuProfilerConnection* cpu_profiler_connection();
1451
1452
  inline void set_cpu_prof_name(const std::string& name);
1453
  inline const std::string& cpu_prof_name() const;
1454
1455
  inline void set_cpu_prof_interval(uint64_t interval);
1456
  inline uint64_t cpu_prof_interval() const;
1457
1458
  inline void set_cpu_prof_dir(const std::string& dir);
1459
  inline const std::string& cpu_prof_dir() const;
1460
1461
  void set_heap_profiler_connection(
1462
      std::unique_ptr<profiler::V8HeapProfilerConnection> connection);
1463
  profiler::V8HeapProfilerConnection* heap_profiler_connection();
1464
1465
  inline void set_heap_prof_name(const std::string& name);
1466
  inline const std::string& heap_prof_name() const;
1467
1468
  inline void set_heap_prof_dir(const std::string& dir);
1469
  inline const std::string& heap_prof_dir() const;
1470
1471
  inline void set_heap_prof_interval(uint64_t interval);
1472
  inline uint64_t heap_prof_interval() const;
1473
1474
#endif  // HAVE_INSPECTOR
1475
1476
  inline void set_main_utf16(std::unique_ptr<v8::String::Value>);
1477
  inline void set_process_exit_handler(
1478
      std::function<void(Environment*, int)>&& handler);
1479
1480
  void RunAndClearNativeImmediates(bool only_refed = false);
1481
  void RunAndClearInterrupts();
1482
1483
  inline uv_buf_t allocate_managed_buffer(const size_t suggested_size);
1484
  inline std::unique_ptr<v8::BackingStore> release_managed_buffer(
1485
      const uv_buf_t& buf);
1486
1487
  void AddUnmanagedFd(int fd);
1488
  void RemoveUnmanagedFd(int fd);
1489
1490
  template <typename T>
1491
  void ForEachBindingData(T&& iterator);
1492
1493
 private:
1494
  inline void ThrowError(v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
1495
                         const char* errmsg);
1496
1497
  std::list<binding::DLib> loaded_addons_;
1498
  v8::Isolate* const isolate_;
1499
  IsolateData* const isolate_data_;
1500
  uv_timer_t timer_handle_;
1501
  uv_check_t immediate_check_handle_;
1502
  uv_idle_t immediate_idle_handle_;
1503
  uv_prepare_t idle_prepare_handle_;
1504
  uv_check_t idle_check_handle_;
1505
  uv_async_t task_queues_async_;
1506
  int64_t task_queues_async_refs_ = 0;
1507
1508
  AsyncHooks async_hooks_;
1509
  ImmediateInfo immediate_info_;
1510
  TickInfo tick_info_;
1511
  const uint64_t timer_base_;
1512
  std::shared_ptr<KVStore> env_vars_;
1513
  bool printed_error_ = false;
1514
  bool trace_sync_io_ = false;
1515
  bool emit_env_nonstring_warning_ = true;
1516
  bool emit_err_name_warning_ = true;
1517
  bool emit_filehandle_warning_ = true;
1518
  bool source_maps_enabled_ = false;
1519
1520
  size_t async_callback_scope_depth_ = 0;
1521
  std::vector<double> destroy_async_id_list_;
1522
1523
#if HAVE_INSPECTOR
1524
  std::unique_ptr<profiler::V8CoverageConnection> coverage_connection_;
1525
  std::unique_ptr<profiler::V8CpuProfilerConnection> cpu_profiler_connection_;
1526
  std::string coverage_directory_;
1527
  std::string cpu_prof_dir_;
1528
  std::string cpu_prof_name_;
1529
  uint64_t cpu_prof_interval_;
1530
  std::unique_ptr<profiler::V8HeapProfilerConnection> heap_profiler_connection_;
1531
  std::string heap_prof_dir_;
1532
  std::string heap_prof_name_;
1533
  uint64_t heap_prof_interval_;
1534
#endif  // HAVE_INSPECTOR
1535
1536
  std::shared_ptr<EnvironmentOptions> options_;
1537
  // options_ contains debug options parsed from CLI arguments,
1538
  // while inspector_host_port_ stores the actual inspector host
1539
  // and port being used. For example the port is -1 by default
1540
  // and can be specified as 0 (meaning any port allocated when the
1541
  // server starts listening), but when the inspector server starts
1542
  // the inspector_host_port_->port() will be the actual port being
1543
  // used.
1544
  std::shared_ptr<ExclusiveAccess<HostPort>> inspector_host_port_;
1545
  std::vector<std::string> exec_argv_;
1546
  std::vector<std::string> argv_;
1547
  std::string exec_path_;
1548
1549
  bool is_processing_heap_limit_callback_ = false;
1550
  int64_t heap_limit_snapshot_taken_ = 0;
1551
1552
  uint32_t module_id_counter_ = 0;
1553
  uint32_t script_id_counter_ = 0;
1554
  uint32_t function_id_counter_ = 0;
1555
1556
  AliasedUint32Array should_abort_on_uncaught_toggle_;
1557
  int should_not_abort_scope_counter_ = 0;
1558
1559
  std::unique_ptr<TrackingTraceStateObserver> trace_state_observer_;
1560
1561
  AliasedInt32Array stream_base_state_;
1562
1563
  uint64_t environment_start_time_;
1564
  std::unique_ptr<performance::PerformanceState> performance_state_;
1565
1566
  bool has_run_bootstrapping_code_ = false;
1567
  bool has_serialized_options_ = false;
1568
1569
  std::atomic_bool can_call_into_js_ { true };
1570
  uint64_t flags_;
1571
  uint64_t thread_id_;
1572
  std::unordered_set<worker::Worker*> sub_worker_contexts_;
1573
1574
  static void* const kNodeContextTagPtr;
1575
  static int const kNodeContextTag;
1576
1577
#if HAVE_INSPECTOR
1578
  std::unique_ptr<inspector::Agent> inspector_agent_;
1579
  bool is_in_inspector_console_call_ = false;
1580
#endif
1581
1582
  std::list<DeserializeRequest> deserialize_requests_;
1583
1584
  // handle_wrap_queue_ and req_wrap_queue_ needs to be at a fixed offset from
1585
  // the start of the class because it is used by
1586
  // src/node_postmortem_metadata.cc to calculate offsets and generate debug
1587
  // symbols for Environment, which assumes that the position of members in
1588
  // memory are predictable. For more information please refer to
1589
  // `doc/contributing/node-postmortem-support.md`
1590
  friend int GenDebugSymbols();
1591
  HandleWrapQueue handle_wrap_queue_;
1592
  ReqWrapQueue req_wrap_queue_;
1593
  std::list<HandleCleanup> handle_cleanup_queue_;
1594
  int handle_cleanup_waiting_ = 0;
1595
  int request_waiting_ = 0;
1596
1597
  EnabledDebugList enabled_debug_list_;
1598
1599
  std::list<node_module> extra_linked_bindings_;
1600
  Mutex extra_linked_bindings_mutex_;
1601
1602
  static void RunTimers(uv_timer_t* handle);
1603
1604
  struct ExitCallback {
1605
    void (*cb_)(void* arg);
1606
    void* arg_;
1607
  };
1608
1609
  std::list<ExitCallback> at_exit_functions_;
1610
1611
  typedef CallbackQueue<void, Environment*> NativeImmediateQueue;
1612
  NativeImmediateQueue native_immediates_;
1613
  Mutex native_immediates_threadsafe_mutex_;
1614
  NativeImmediateQueue native_immediates_threadsafe_;
1615
  NativeImmediateQueue native_immediates_interrupts_;
1616
  // Also guarded by native_immediates_threadsafe_mutex_. This can be used when
1617
  // trying to post tasks from other threads to an Environment, as the libuv
1618
  // handle for the immediate queues (task_queues_async_) may not be initialized
1619
  // yet or already have been destroyed.
1620
  bool task_queues_async_initialized_ = false;
1621
1622
  std::atomic<Environment**> interrupt_data_ {nullptr};
1623
  void RequestInterruptFromV8();
1624
  static void CheckImmediate(uv_check_t* handle);
1625
1626
  BindingDataStore bindings_;
1627
1628
  // Use an unordered_set, so that we have efficient insertion and removal.
1629
  std::unordered_set<CleanupHookCallback,
1630
                     CleanupHookCallback::Hash,
1631
                     CleanupHookCallback::Equal> cleanup_hooks_;
1632
  uint64_t cleanup_hook_counter_ = 0;
1633
  bool started_cleanup_ = false;
1634
1635
  int64_t base_object_count_ = 0;
1636
  int64_t base_object_created_by_bootstrap_ = 0;
1637
  std::atomic_bool is_stopping_ { false };
1638
1639
  std::unordered_set<int> unmanaged_fds_;
1640
1641
  std::function<void(Environment*, int)> process_exit_handler_ {
1642
      DefaultProcessExitHandler };
1643
1644
  template <typename T>
1645
  void ForEachBaseObject(T&& iterator);
1646
1647
#define V(PropertyName, TypeName) v8::Global<TypeName> PropertyName ## _;
1648
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1649
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1650
#undef V
1651
1652
  v8::Global<v8::Context> context_;
1653
1654
  // Keeps the main script source alive is one was passed to LoadEnvironment().
1655
  // We should probably find a way to just use plain `v8::String`s created from
1656
  // the source passed to LoadEnvironment() directly instead.
1657
  std::unique_ptr<v8::String::Value> main_utf16_;
1658
1659
  // Used by allocate_managed_buffer() and release_managed_buffer() to keep
1660
  // track of the BackingStore for a given pointer.
1661
  std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>
1662
      released_allocated_buffers_;
1663
};
1664
1665
}  // namespace node
1666
1667
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1668
1669
#endif  // SRC_ENV_H_