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-09-06 22:14:11 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
8794
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
10252
struct ContextInfo {
614
10251
  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
5102
  KVStore() = default;
625
4634
  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
8773
  ~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
4471
  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
4387
  ~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
4387
  ~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
8773
class TrackingTraceStateObserver :
834
    public v8::TracingController::TraceStateObserver {
835
 public:
836
4855
  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
1305011
  CleanupHookCallback(void (*fn)(void*),
871
                      void* arg,
872
                      uint64_t insertion_order_counter)
873
1305011
      : 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
4855
  struct Hash {
877
    inline size_t operator()(const CleanupHookCallback& cb) const;
878
  };
879
880
  // Compares by `fn_` and `arg_` being equal.
881
4855
  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
415259
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
4469
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
  inline void set_force_context_aware(bool value);
1072
  inline bool force_context_aware() const;
1073
1074
  // This stores whether the --abort-on-uncaught-exception flag was passed
1075
  // to Node.
1076
  inline bool abort_on_uncaught_exception() const;
1077
  inline void set_abort_on_uncaught_exception(bool value);
1078
  // This is a pseudo-boolean that keeps track of whether an uncaught exception
1079
  // should abort the process or not if --abort-on-uncaught-exception was
1080
  // passed to Node. If the flag was not passed, it is ignored.
1081
  inline AliasedUint32Array& should_abort_on_uncaught_toggle();
1082
1083
  inline AliasedInt32Array& stream_base_state();
1084
1085
  // The necessary API for async_hooks.
1086
  inline double new_async_id();
1087
  inline double execution_async_id();
1088
  inline double trigger_async_id();
1089
  inline double get_default_trigger_async_id();
1090
1091
  // List of id's that have been destroyed and need the destroy() cb called.
1092
  inline std::vector<double>* destroy_async_id_list();
1093
1094
  std::set<std::string> native_modules_with_cache;
1095
  std::set<std::string> native_modules_without_cache;
1096
  // This is only filled during deserialization. We use a vector since
1097
  // it's only used for tests.
1098
  std::vector<std::string> native_modules_in_snapshot;
1099
1100
  std::unordered_multimap<int, loader::ModuleWrap*> hash_to_module_map;
1101
  std::unordered_map<uint32_t, loader::ModuleWrap*> id_to_module_map;
1102
  std::unordered_map<uint32_t, contextify::ContextifyScript*>
1103
      id_to_script_map;
1104
  std::unordered_map<uint32_t, contextify::CompiledFnEntry*> id_to_function_map;
1105
1106
  inline uint32_t get_next_module_id();
1107
  inline uint32_t get_next_script_id();
1108
  inline uint32_t get_next_function_id();
1109
1110
1268113
  EnabledDebugList* enabled_debug_list() { return &enabled_debug_list_; }
1111
1112
  inline performance::PerformanceState* performance_state();
1113
  inline std::unordered_map<std::string, uint64_t>* performance_marks();
1114
1115
  void CollectUVExceptionInfo(v8::Local<v8::Value> context,
1116
                              int errorno,
1117
                              const char* syscall = nullptr,
1118
                              const char* message = nullptr,
1119
                              const char* path = nullptr,
1120
                              const char* dest = nullptr);
1121
1122
  // If this flag is set, calls into JS (if they would be observable
1123
  // from userland) must be avoided.  This flag does not indicate whether
1124
  // calling into JS is allowed from a VM perspective at this point.
1125
  inline bool can_call_into_js() const;
1126
  inline void set_can_call_into_js(bool can_call_into_js);
1127
1128
  // Increase or decrease a counter that manages whether this Environment
1129
  // keeps the event loop alive on its own or not. The counter starts out at 0,
1130
  // meaning it does not, and any positive value will make it keep the event
1131
  // loop alive.
1132
  // This is used by Workers to manage their own .ref()/.unref() implementation,
1133
  // as Workers aren't directly associated with their own libuv handles.
1134
  inline void add_refs(int64_t diff);
1135
1136
  inline bool has_run_bootstrapping_code() const;
1137
  inline void set_has_run_bootstrapping_code(bool has_run_bootstrapping_code);
1138
1139
  inline bool has_serialized_options() const;
1140
  inline void set_has_serialized_options(bool has_serialized_options);
1141
1142
  inline bool is_main_thread() const;
1143
  inline bool should_not_register_esm_loader() const;
1144
  inline bool owns_process_state() const;
1145
  inline bool owns_inspector() const;
1146
  inline bool tracks_unmanaged_fds() const;
1147
  inline uint64_t thread_id() const;
1148
  inline worker::Worker* worker_context() const;
1149
  Environment* worker_parent_env() const;
1150
  inline void add_sub_worker_context(worker::Worker* context);
1151
  inline void remove_sub_worker_context(worker::Worker* context);
1152
  void stop_sub_worker_contexts();
1153
  template <typename Fn>
1154
  inline void ForEachWorker(Fn&& iterator);
1155
  inline bool is_stopping() const;
1156
  inline void set_stopping(bool value);
1157
  inline std::list<node_module>* extra_linked_bindings();
1158
  inline node_module* extra_linked_bindings_head();
1159
  inline const Mutex& extra_linked_bindings_mutex() const;
1160
1161
  inline bool filehandle_close_warning() const;
1162
  inline void set_filehandle_close_warning(bool on);
1163
  inline bool emit_insecure_umask_warning() const;
1164
  inline void set_emit_insecure_umask_warning(bool on);
1165
1166
  inline void set_source_maps_enabled(bool on);
1167
  inline bool source_maps_enabled() const;
1168
1169
  inline void ThrowError(const char* errmsg);
1170
  inline void ThrowTypeError(const char* errmsg);
1171
  inline void ThrowRangeError(const char* errmsg);
1172
  inline void ThrowErrnoException(int errorno,
1173
                                  const char* syscall = nullptr,
1174
                                  const char* message = nullptr,
1175
                                  const char* path = nullptr);
1176
  inline void ThrowUVException(int errorno,
1177
                               const char* syscall = nullptr,
1178
                               const char* message = nullptr,
1179
                               const char* path = nullptr,
1180
                               const char* dest = nullptr);
1181
1182
  inline v8::Local<v8::FunctionTemplate>
1183
      NewFunctionTemplate(v8::FunctionCallback callback,
1184
                          v8::Local<v8::Signature> signature =
1185
                              v8::Local<v8::Signature>(),
1186
                          v8::ConstructorBehavior behavior =
1187
                              v8::ConstructorBehavior::kAllow,
1188
                          v8::SideEffectType side_effect =
1189
                              v8::SideEffectType::kHasSideEffect);
1190
1191
  // Convenience methods for NewFunctionTemplate().
1192
  inline void SetMethod(v8::Local<v8::Object> that,
1193
                        const char* name,
1194
                        v8::FunctionCallback callback);
1195
1196
  inline void SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
1197
                             const char* name,
1198
                             v8::FunctionCallback callback);
1199
1200
  inline void SetInstanceMethod(v8::Local<v8::FunctionTemplate> that,
1201
                                const char* name,
1202
                                v8::FunctionCallback callback);
1203
1204
1205
  // Safe variants denote the function has no side effects.
1206
  inline void SetMethodNoSideEffect(v8::Local<v8::Object> that,
1207
                                    const char* name,
1208
                                    v8::FunctionCallback callback);
1209
  inline void SetProtoMethodNoSideEffect(v8::Local<v8::FunctionTemplate> that,
1210
                                         const char* name,
1211
                                         v8::FunctionCallback callback);
1212
1213
  void AtExit(void (*cb)(void* arg), void* arg);
1214
  void RunAtExitCallbacks();
1215
1216
  void RunWeakRefCleanup();
1217
1218
  // Strings and private symbols are shared across shared contexts
1219
  // The getters simply proxy to the per-isolate primitive.
1220
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1221
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1222
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1223
#define V(TypeName, PropertyName)                                             \
1224
  inline v8::Local<TypeName> PropertyName() const;
1225
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1226
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1227
  PER_ISOLATE_STRING_PROPERTIES(VS)
1228
#undef V
1229
#undef VS
1230
#undef VY
1231
#undef VP
1232
1233
#define V(PropertyName, TypeName)                                             \
1234
  inline v8::Local<TypeName> PropertyName() const;                            \
1235
  inline void set_ ## PropertyName(v8::Local<TypeName> value);
1236
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1237
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1238
#undef V
1239
1240
  inline v8::Local<v8::Context> context() const;
1241
1242
#if HAVE_INSPECTOR
1243
66967
  inline inspector::Agent* inspector_agent() const {
1244
66967
    return inspector_agent_.get();
1245
  }
1246
1247
  inline bool is_in_inspector_console_call() const;
1248
  inline void set_is_in_inspector_console_call(bool value);
1249
#endif
1250
1251
  typedef ListHead<HandleWrap, &HandleWrap::handle_wrap_queue_> HandleWrapQueue;
1252
  typedef ListHead<ReqWrapBase, &ReqWrapBase::req_wrap_queue_> ReqWrapQueue;
1253
1254
57800
  inline HandleWrapQueue* handle_wrap_queue() { return &handle_wrap_queue_; }
1255
76007
  inline ReqWrapQueue* req_wrap_queue() { return &req_wrap_queue_; }
1256
1257
1
  inline bool EmitProcessEnvWarning() {
1258
1
    bool current_value = emit_env_nonstring_warning_;
1259
1
    emit_env_nonstring_warning_ = false;
1260
1
    return current_value;
1261
  }
1262
1263
1
  inline bool EmitErrNameWarning() {
1264
1
    bool current_value = emit_err_name_warning_;
1265
1
    emit_err_name_warning_ = false;
1266
1
    return current_value;
1267
  }
1268
1269
  // cb will be called as cb(env) on the next event loop iteration.
1270
  // Unlike the JS setImmediate() function, nested SetImmediate() calls will
1271
  // be run without returning control to the event loop, similar to nextTick().
1272
  template <typename Fn>
1273
  inline void SetImmediate(
1274
      Fn&& cb, CallbackFlags::Flags flags = CallbackFlags::kRefed);
1275
  template <typename Fn>
1276
  // This behaves like SetImmediate() but can be called from any thread.
1277
  inline void SetImmediateThreadsafe(
1278
      Fn&& cb, CallbackFlags::Flags flags = CallbackFlags::kRefed);
1279
  // This behaves like V8's Isolate::RequestInterrupt(), but also accounts for
1280
  // the event loop (i.e. combines the V8 function with SetImmediate()).
1281
  // The passed callback may not throw exceptions.
1282
  // This function can be called from any thread.
1283
  template <typename Fn>
1284
  inline void RequestInterrupt(Fn&& cb);
1285
  // This needs to be available for the JS-land setImmediate().
1286
  void ToggleImmediateRef(bool ref);
1287
1288
  inline void PushShouldNotAbortOnUncaughtScope();
1289
  inline void PopShouldNotAbortOnUncaughtScope();
1290
  inline bool inside_should_not_abort_on_uncaught_scope() const;
1291
1292
  static inline Environment* ForAsyncHooks(AsyncHooks* hooks);
1293
1294
  v8::Local<v8::Value> GetNow();
1295
  void ScheduleTimer(int64_t duration);
1296
  void ToggleTimerRef(bool ref);
1297
1298
  inline void AddCleanupHook(void (*fn)(void*), void* arg);
1299
  inline void RemoveCleanupHook(void (*fn)(void*), void* arg);
1300
  void RunCleanup();
1301
1302
  static void BuildEmbedderGraph(v8::Isolate* isolate,
1303
                                 v8::EmbedderGraph* graph,
1304
                                 void* data);
1305
1306
  inline std::shared_ptr<EnvironmentOptions> options();
1307
  inline std::shared_ptr<ExclusiveAccess<HostPort>> inspector_host_port();
1308
1309
  // The BaseObject count is a debugging helper that makes sure that there are
1310
  // no memory leaks caused by BaseObjects staying alive longer than expected
1311
  // (in particular, no circular BaseObjectPtr references).
1312
  inline void modify_base_object_count(int64_t delta);
1313
  inline int64_t base_object_count() const;
1314
1315
3
  inline int32_t stack_trace_limit() const { return 10; }
1316
1317
#if HAVE_INSPECTOR
1318
  void set_coverage_connection(
1319
      std::unique_ptr<profiler::V8CoverageConnection> connection);
1320
  profiler::V8CoverageConnection* coverage_connection();
1321
1322
  inline void set_coverage_directory(const char* directory);
1323
  inline const std::string& coverage_directory() const;
1324
1325
  void set_cpu_profiler_connection(
1326
      std::unique_ptr<profiler::V8CpuProfilerConnection> connection);
1327
  profiler::V8CpuProfilerConnection* cpu_profiler_connection();
1328
1329
  inline void set_cpu_prof_name(const std::string& name);
1330
  inline const std::string& cpu_prof_name() const;
1331
1332
  inline void set_cpu_prof_interval(uint64_t interval);
1333
  inline uint64_t cpu_prof_interval() const;
1334
1335
  inline void set_cpu_prof_dir(const std::string& dir);
1336
  inline const std::string& cpu_prof_dir() const;
1337
1338
  void set_heap_profiler_connection(
1339
      std::unique_ptr<profiler::V8HeapProfilerConnection> connection);
1340
  profiler::V8HeapProfilerConnection* heap_profiler_connection();
1341
1342
  inline void set_heap_prof_name(const std::string& name);
1343
  inline const std::string& heap_prof_name() const;
1344
1345
  inline void set_heap_prof_dir(const std::string& dir);
1346
  inline const std::string& heap_prof_dir() const;
1347
1348
  inline void set_heap_prof_interval(uint64_t interval);
1349
  inline uint64_t heap_prof_interval() const;
1350
1351
#endif  // HAVE_INSPECTOR
1352
1353
  inline void set_main_utf16(std::unique_ptr<v8::String::Value>);
1354
  inline void set_process_exit_handler(
1355
      std::function<void(Environment*, int)>&& handler);
1356
1357
  void RunAndClearNativeImmediates(bool only_refed = false);
1358
  void RunAndClearInterrupts();
1359
1360
  inline std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>*
1361
      released_allocated_buffers();
1362
1363
  void AddUnmanagedFd(int fd);
1364
  void RemoveUnmanagedFd(int fd);
1365
1366
 private:
1367
  inline void ThrowError(v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
1368
                         const char* errmsg);
1369
1370
  std::list<binding::DLib> loaded_addons_;
1371
  v8::Isolate* const isolate_;
1372
  IsolateData* const isolate_data_;
1373
  uv_timer_t timer_handle_;
1374
  uv_check_t immediate_check_handle_;
1375
  uv_idle_t immediate_idle_handle_;
1376
  uv_async_t task_queues_async_;
1377
  int64_t task_queues_async_refs_ = 0;
1378
1379
  AsyncHooks async_hooks_;
1380
  ImmediateInfo immediate_info_;
1381
  TickInfo tick_info_;
1382
  const uint64_t timer_base_;
1383
  std::shared_ptr<KVStore> env_vars_;
1384
  bool printed_error_ = false;
1385
  bool trace_sync_io_ = false;
1386
  bool emit_env_nonstring_warning_ = true;
1387
  bool emit_err_name_warning_ = true;
1388
  bool emit_filehandle_warning_ = true;
1389
  bool emit_insecure_umask_warning_ = true;
1390
  bool source_maps_enabled_ = false;
1391
1392
  size_t async_callback_scope_depth_ = 0;
1393
  std::vector<double> destroy_async_id_list_;
1394
1395
#if HAVE_INSPECTOR
1396
  std::unique_ptr<profiler::V8CoverageConnection> coverage_connection_;
1397
  std::unique_ptr<profiler::V8CpuProfilerConnection> cpu_profiler_connection_;
1398
  std::string coverage_directory_;
1399
  std::string cpu_prof_dir_;
1400
  std::string cpu_prof_name_;
1401
  uint64_t cpu_prof_interval_;
1402
  std::unique_ptr<profiler::V8HeapProfilerConnection> heap_profiler_connection_;
1403
  std::string heap_prof_dir_;
1404
  std::string heap_prof_name_;
1405
  uint64_t heap_prof_interval_;
1406
#endif  // HAVE_INSPECTOR
1407
1408
  std::shared_ptr<EnvironmentOptions> options_;
1409
  // options_ contains debug options parsed from CLI arguments,
1410
  // while inspector_host_port_ stores the actual inspector host
1411
  // and port being used. For example the port is -1 by default
1412
  // and can be specified as 0 (meaning any port allocated when the
1413
  // server starts listening), but when the inspector server starts
1414
  // the inspector_host_port_->port() will be the actual port being
1415
  // used.
1416
  std::shared_ptr<ExclusiveAccess<HostPort>> inspector_host_port_;
1417
  std::vector<std::string> exec_argv_;
1418
  std::vector<std::string> argv_;
1419
  std::string exec_path_;
1420
1421
  uint32_t module_id_counter_ = 0;
1422
  uint32_t script_id_counter_ = 0;
1423
  uint32_t function_id_counter_ = 0;
1424
1425
  AliasedUint32Array should_abort_on_uncaught_toggle_;
1426
  int should_not_abort_scope_counter_ = 0;
1427
1428
  std::unique_ptr<TrackingTraceStateObserver> trace_state_observer_;
1429
1430
  AliasedInt32Array stream_base_state_;
1431
1432
  uint64_t environment_start_time_;
1433
  std::unique_ptr<performance::PerformanceState> performance_state_;
1434
  std::unordered_map<std::string, uint64_t> performance_marks_;
1435
1436
  bool has_run_bootstrapping_code_ = false;
1437
  bool has_serialized_options_ = false;
1438
1439
  std::atomic_bool can_call_into_js_ { true };
1440
  uint64_t flags_;
1441
  uint64_t thread_id_;
1442
  std::unordered_set<worker::Worker*> sub_worker_contexts_;
1443
1444
  static void* const kNodeContextTagPtr;
1445
  static int const kNodeContextTag;
1446
1447
#if HAVE_INSPECTOR
1448
  std::unique_ptr<inspector::Agent> inspector_agent_;
1449
  bool is_in_inspector_console_call_ = false;
1450
#endif
1451
1452
  // handle_wrap_queue_ and req_wrap_queue_ needs to be at a fixed offset from
1453
  // the start of the class because it is used by
1454
  // src/node_postmortem_metadata.cc to calculate offsets and generate debug
1455
  // symbols for Environment, which assumes that the position of members in
1456
  // memory are predictable. For more information please refer to
1457
  // `doc/guides/node-postmortem-support.md`
1458
  friend int GenDebugSymbols();
1459
  HandleWrapQueue handle_wrap_queue_;
1460
  ReqWrapQueue req_wrap_queue_;
1461
  std::list<HandleCleanup> handle_cleanup_queue_;
1462
  int handle_cleanup_waiting_ = 0;
1463
  int request_waiting_ = 0;
1464
1465
  EnabledDebugList enabled_debug_list_;
1466
1467
  std::list<node_module> extra_linked_bindings_;
1468
  Mutex extra_linked_bindings_mutex_;
1469
1470
  static void RunTimers(uv_timer_t* handle);
1471
1472
  struct ExitCallback {
1473
    void (*cb_)(void* arg);
1474
    void* arg_;
1475
  };
1476
1477
  std::list<ExitCallback> at_exit_functions_;
1478
1479
  typedef CallbackQueue<void, Environment*> NativeImmediateQueue;
1480
  NativeImmediateQueue native_immediates_;
1481
  Mutex native_immediates_threadsafe_mutex_;
1482
  NativeImmediateQueue native_immediates_threadsafe_;
1483
  NativeImmediateQueue native_immediates_interrupts_;
1484
  // Also guarded by native_immediates_threadsafe_mutex_. This can be used when
1485
  // trying to post tasks from other threads to an Environment, as the libuv
1486
  // handle for the immediate queues (task_queues_async_) may not be initialized
1487
  // yet or already have been destroyed.
1488
  bool task_queues_async_initialized_ = false;
1489
1490
  std::atomic<Environment**> interrupt_data_ {nullptr};
1491
  void RequestInterruptFromV8();
1492
  static void CheckImmediate(uv_check_t* handle);
1493
1494
  BindingDataStore bindings_;
1495
1496
  // Use an unordered_set, so that we have efficient insertion and removal.
1497
  std::unordered_set<CleanupHookCallback,
1498
                     CleanupHookCallback::Hash,
1499
                     CleanupHookCallback::Equal> cleanup_hooks_;
1500
  uint64_t cleanup_hook_counter_ = 0;
1501
  bool started_cleanup_ = false;
1502
1503
  int64_t base_object_count_ = 0;
1504
  int64_t initial_base_object_count_ = 0;
1505
  std::atomic_bool is_stopping_ { false };
1506
1507
  std::unordered_set<int> unmanaged_fds_;
1508
1509
  std::function<void(Environment*, int)> process_exit_handler_ {
1510
      DefaultProcessExitHandler };
1511
1512
  template <typename T>
1513
  void ForEachBaseObject(T&& iterator);
1514
1515
#define V(PropertyName, TypeName) v8::Global<TypeName> PropertyName ## _;
1516
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1517
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1518
#undef V
1519
1520
  v8::Global<v8::Context> context_;
1521
1522
  // Keeps the main script source alive is one was passed to LoadEnvironment().
1523
  // We should probably find a way to just use plain `v8::String`s created from
1524
  // the source passed to LoadEnvironment() directly instead.
1525
  std::unique_ptr<v8::String::Value> main_utf16_;
1526
1527
  // Used by AllocatedBuffer::release() to keep track of the BackingStore for
1528
  // a given pointer.
1529
  std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>
1530
      released_allocated_buffers_;
1531
};
1532
1533
}  // namespace node
1534
1535
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1536
1537
#endif  // SRC_ENV_H_