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