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