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