GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.h Lines: 41 41 100.0 %
Date: 2022-01-06 04:14:11 Branches: 1 2 50.0 %

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