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