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: 2019-10-06 22:30:00 Branches: 14 26 53.8 %

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



164424
  class NativeImmediateCallbackImpl final : public NativeImmediateCallback {
1404
   public:
1405
    NativeImmediateCallbackImpl(Fn&& callback,
1406
                                v8::Global<v8::Object>&& keep_alive,
1407
                                bool refed);
1408
    void Call(Environment* env) override;
1409
1410
   private:
1411
    Fn callback_;
1412
    v8::Global<v8::Object> keep_alive_;
1413
  };
1414
1415
  std::unique_ptr<NativeImmediateCallback> native_immediate_callbacks_head_;
1416
  NativeImmediateCallback* native_immediate_callbacks_tail_ = nullptr;
1417
1418
  void RunAndClearNativeImmediates();
1419
  static void CheckImmediate(uv_check_t* handle);
1420
1421
  // Use an unordered_set, so that we have efficient insertion and removal.
1422
  std::unordered_set<CleanupHookCallback,
1423
                     CleanupHookCallback::Hash,
1424
                     CleanupHookCallback::Equal> cleanup_hooks_;
1425
  uint64_t cleanup_hook_counter_ = 0;
1426
  bool started_cleanup_ = false;
1427
1428
  // A custom async abstraction (a pair of async handle and a state variable)
1429
  // Used by embedders to shutdown running Node instance.
1430
  AsyncRequest thread_stopper_;
1431
1432
  typedef std::unordered_set<std::shared_ptr<v8::ArrayBuffer::Allocator>>
1433
      ArrayBufferAllocatorList;
1434
  ArrayBufferAllocatorList* keep_alive_allocators_ = nullptr;
1435
1436
  template <typename T>
1437
  void ForEachBaseObject(T&& iterator);
1438
1439
#define V(PropertyName, TypeName) v8::Global<TypeName> PropertyName ## _;
1440
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1441
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1442
#undef V
1443
1444
  v8::Global<v8::Context> context_;
1445
};
1446
1447
}  // namespace node
1448
1449
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1450
1451
#endif  // SRC_ENV_H_