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: 29 29 100.0 %
Date: 2019-02-23 22:23:05 Branches: 1 2 50.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
#endif
31
#include "handle_wrap.h"
32
#include "node.h"
33
#include "node_binding.h"
34
#include "node_http2_state.h"
35
#include "node_options.h"
36
#include "req_wrap.h"
37
#include "util.h"
38
#include "uv.h"
39
#include "v8.h"
40
41
#include <stdint.h>
42
#include <functional>
43
#include <list>
44
#include <unordered_map>
45
#include <unordered_set>
46
#include <vector>
47
48
struct nghttp2_rcbuf;
49
50
namespace node {
51
52
namespace contextify {
53
class ContextifyScript;
54
}
55
56
namespace fs {
57
class FileHandleReadWrap;
58
}
59
60
namespace performance {
61
class performance_state;
62
}
63
64
namespace tracing {
65
class AgentWriterHandle;
66
}
67
68
namespace worker {
69
class Worker;
70
}
71
72
namespace loader {
73
class ModuleWrap;
74
75
118
struct PackageConfig {
76
  enum class Exists { Yes, No };
77
  enum class IsValid { Yes, No };
78
  enum class HasMain { Yes, No };
79
80
  Exists exists;
81
  IsValid is_valid;
82
  HasMain has_main;
83
  std::string main;
84
};
85
}  // namespace loader
86
87
// Stat fields buffers contain twice the number of entries in an uv_stat_t
88
// because `fs.StatWatcher` needs room to store 2 `fs.Stats` instances.
89
constexpr size_t kFsStatsFieldsNumber = 14;
90
constexpr size_t kFsStatsBufferLength = kFsStatsFieldsNumber * 2;
91
92
// PER_ISOLATE_* macros: We have a lot of per-isolate properties
93
// and adding and maintaining their getters and setters by hand would be
94
// difficult so let's make the preprocessor generate them for us.
95
//
96
// In each macro, `V` is expected to be the name of a macro or function which
97
// accepts the number of arguments provided in each tuple in the macro body,
98
// typically two. The named function will be invoked against each tuple.
99
//
100
// Make sure that any macro V defined for use with the PER_ISOLATE_* macros is
101
// undefined again after use.
102
103
// Private symbols are per-isolate primitives but Environment proxies them
104
// for the sake of convenience.  Strings should be ASCII-only and have a
105
// "node:" prefix to avoid name clashes with third-party code.
106
#define PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)                              \
107
  V(alpn_buffer_private_symbol, "node:alpnBuffer")                            \
108
  V(arrow_message_private_symbol, "node:arrowMessage")                        \
109
  V(contextify_context_private_symbol, "node:contextify:context")             \
110
  V(contextify_global_private_symbol, "node:contextify:global")               \
111
  V(decorated_private_symbol, "node:decorated")                               \
112
  V(napi_env, "node:napi:env")                                                \
113
  V(napi_wrapper, "node:napi:wrapper")                                        \
114
  V(sab_lifetimepartner_symbol, "node:sharedArrayBufferLifetimePartner")      \
115
116
// Symbols are per-isolate primitives but Environment proxies them
117
// for the sake of convenience.
118
#define PER_ISOLATE_SYMBOL_PROPERTIES(V)                                      \
119
  V(handle_onclose_symbol, "handle_onclose")                                  \
120
  V(oninit_symbol, "oninit")                                                  \
121
  V(owner_symbol, "owner")                                                    \
122
123
// Strings are per-isolate primitives but Environment proxies them
124
// for the sake of convenience.  Strings should be ASCII-only.
125
#define PER_ISOLATE_STRING_PROPERTIES(V)                                       \
126
  V(address_string, "address")                                                 \
127
  V(aliases_string, "aliases")                                                 \
128
  V(args_string, "args")                                                       \
129
  V(asn1curve_string, "asn1Curve")                                             \
130
  V(async_ids_stack_string, "async_ids_stack")                                 \
131
  V(bits_string, "bits")                                                       \
132
  V(buffer_string, "buffer")                                                   \
133
  V(bytes_parsed_string, "bytesParsed")                                        \
134
  V(bytes_read_string, "bytesRead")                                            \
135
  V(bytes_written_string, "bytesWritten")                                      \
136
  V(cached_data_produced_string, "cachedDataProduced")                         \
137
  V(cached_data_rejected_string, "cachedDataRejected")                         \
138
  V(cached_data_string, "cachedData")                                          \
139
  V(change_string, "change")                                                   \
140
  V(channel_string, "channel")                                                 \
141
  V(chunks_sent_since_last_write_string, "chunksSentSinceLastWrite")           \
142
  V(code_string, "code")                                                       \
143
  V(config_string, "config")                                                   \
144
  V(constants_string, "constants")                                             \
145
  V(crypto_dsa_string, "dsa")                                                  \
146
  V(crypto_ec_string, "ec")                                                    \
147
  V(crypto_rsa_string, "rsa")                                                  \
148
  V(cwd_string, "cwd")                                                         \
149
  V(data_string, "data")                                                       \
150
  V(dest_string, "dest")                                                       \
151
  V(destroyed_string, "destroyed")                                             \
152
  V(detached_string, "detached")                                               \
153
  V(dns_a_string, "A")                                                         \
154
  V(dns_aaaa_string, "AAAA")                                                   \
155
  V(dns_cname_string, "CNAME")                                                 \
156
  V(dns_mx_string, "MX")                                                       \
157
  V(dns_naptr_string, "NAPTR")                                                 \
158
  V(dns_ns_string, "NS")                                                       \
159
  V(dns_ptr_string, "PTR")                                                     \
160
  V(dns_soa_string, "SOA")                                                     \
161
  V(dns_srv_string, "SRV")                                                     \
162
  V(dns_txt_string, "TXT")                                                     \
163
  V(duration_string, "duration")                                               \
164
  V(emit_warning_string, "emitWarning")                                        \
165
  V(encoding_string, "encoding")                                               \
166
  V(entries_string, "entries")                                                 \
167
  V(entry_type_string, "entryType")                                            \
168
  V(env_pairs_string, "envPairs")                                              \
169
  V(env_var_settings_string, "envVarSettings")                                 \
170
  V(errno_string, "errno")                                                     \
171
  V(error_string, "error")                                                     \
172
  V(exchange_string, "exchange")                                               \
173
  V(exit_code_string, "exitCode")                                              \
174
  V(expire_string, "expire")                                                   \
175
  V(exponent_string, "exponent")                                               \
176
  V(exports_string, "exports")                                                 \
177
  V(ext_key_usage_string, "ext_key_usage")                                     \
178
  V(external_stream_string, "_externalStream")                                 \
179
  V(family_string, "family")                                                   \
180
  V(fatal_exception_string, "_fatalException")                                 \
181
  V(fd_string, "fd")                                                           \
182
  V(file_string, "file")                                                       \
183
  V(fingerprint256_string, "fingerprint256")                                   \
184
  V(fingerprint_string, "fingerprint")                                         \
185
  V(flags_string, "flags")                                                     \
186
  V(fragment_string, "fragment")                                               \
187
  V(function_string, "function")                                               \
188
  V(get_data_clone_error_string, "_getDataCloneError")                         \
189
  V(get_shared_array_buffer_id_string, "_getSharedArrayBufferId")              \
190
  V(gid_string, "gid")                                                         \
191
  V(handle_string, "handle")                                                   \
192
  V(help_text_string, "helpText")                                              \
193
  V(homedir_string, "homedir")                                                 \
194
  V(host_string, "host")                                                       \
195
  V(hostmaster_string, "hostmaster")                                           \
196
  V(ignore_string, "ignore")                                                   \
197
  V(infoaccess_string, "infoAccess")                                           \
198
  V(inherit_string, "inherit")                                                 \
199
  V(input_string, "input")                                                     \
200
  V(internal_binding_string, "internalBinding")                                \
201
  V(internal_string, "internal")                                               \
202
  V(ipv4_string, "IPv4")                                                       \
203
  V(ipv6_string, "IPv6")                                                       \
204
  V(isclosing_string, "isClosing")                                             \
205
  V(issuer_string, "issuer")                                                   \
206
  V(issuercert_string, "issuerCertificate")                                    \
207
  V(kill_signal_string, "killSignal")                                          \
208
  V(kind_string, "kind")                                                       \
209
  V(library_string, "library")                                                 \
210
  V(mac_string, "mac")                                                         \
211
  V(main_string, "main")                                                       \
212
  V(max_buffer_string, "maxBuffer")                                            \
213
  V(message_port_constructor_string, "MessagePort")                            \
214
  V(message_port_string, "messagePort")                                        \
215
  V(message_string, "message")                                                 \
216
  V(minttl_string, "minttl")                                                   \
217
  V(module_string, "module")                                                   \
218
  V(modulus_string, "modulus")                                                 \
219
  V(name_string, "name")                                                       \
220
  V(netmask_string, "netmask")                                                 \
221
  V(nistcurve_string, "nistCurve")                                             \
222
  V(nsname_string, "nsname")                                                   \
223
  V(ocsp_request_string, "OCSPRequest")                                        \
224
  V(oncertcb_string, "oncertcb")                                               \
225
  V(onchange_string, "onchange")                                               \
226
  V(onclienthello_string, "onclienthello")                                     \
227
  V(oncomplete_string, "oncomplete")                                           \
228
  V(onconnection_string, "onconnection")                                       \
229
  V(ondone_string, "ondone")                                                   \
230
  V(onerror_string, "onerror")                                                 \
231
  V(onexit_string, "onexit")                                                   \
232
  V(onhandshakedone_string, "onhandshakedone")                                 \
233
  V(onhandshakestart_string, "onhandshakestart")                               \
234
  V(onmessage_string, "onmessage")                                             \
235
  V(onnewsession_string, "onnewsession")                                       \
236
  V(onocspresponse_string, "onocspresponse")                                   \
237
  V(onread_string, "onread")                                                   \
238
  V(onreadstart_string, "onreadstart")                                         \
239
  V(onreadstop_string, "onreadstop")                                           \
240
  V(onshutdown_string, "onshutdown")                                           \
241
  V(onsignal_string, "onsignal")                                               \
242
  V(onunpipe_string, "onunpipe")                                               \
243
  V(onwrite_string, "onwrite")                                                 \
244
  V(openssl_error_stack, "opensslErrorStack")                                  \
245
  V(options_string, "options")                                                 \
246
  V(order_string, "order")                                                     \
247
  V(output_string, "output")                                                   \
248
  V(parse_error_string, "Parse Error")                                         \
249
  V(password_string, "password")                                               \
250
  V(path_string, "path")                                                       \
251
  V(pending_handle_string, "pendingHandle")                                    \
252
  V(pid_string, "pid")                                                         \
253
  V(pipe_source_string, "pipeSource")                                          \
254
  V(pipe_string, "pipe")                                                       \
255
  V(pipe_target_string, "pipeTarget")                                          \
256
  V(port1_string, "port1")                                                     \
257
  V(port2_string, "port2")                                                     \
258
  V(port_string, "port")                                                       \
259
  V(preference_string, "preference")                                           \
260
  V(primordials_string, "primordials")                                         \
261
  V(priority_string, "priority")                                               \
262
  V(process_string, "process")                                                 \
263
  V(promise_string, "promise")                                                 \
264
  V(pubkey_string, "pubkey")                                                   \
265
  V(query_string, "query")                                                     \
266
  V(raw_string, "raw")                                                         \
267
  V(read_host_object_string, "_readHostObject")                                \
268
  V(readable_string, "readable")                                               \
269
  V(reason_string, "reason")                                                   \
270
  V(refresh_string, "refresh")                                                 \
271
  V(regexp_string, "regexp")                                                   \
272
  V(rename_string, "rename")                                                   \
273
  V(replacement_string, "replacement")                                         \
274
  V(require_string, "require")                                                 \
275
  V(retry_string, "retry")                                                     \
276
  V(scheme_string, "scheme")                                                   \
277
  V(scopeid_string, "scopeid")                                                 \
278
  V(serial_number_string, "serialNumber")                                      \
279
  V(serial_string, "serial")                                                   \
280
  V(servername_string, "servername")                                           \
281
  V(service_string, "service")                                                 \
282
  V(session_id_string, "sessionId")                                            \
283
  V(shell_string, "shell")                                                     \
284
  V(signal_string, "signal")                                                   \
285
  V(sink_string, "sink")                                                       \
286
  V(size_string, "size")                                                       \
287
  V(sni_context_err_string, "Invalid SNI context")                             \
288
  V(sni_context_string, "sni_context")                                         \
289
  V(source_string, "source")                                                   \
290
  V(stack_string, "stack")                                                     \
291
  V(start_time_string, "startTime")                                            \
292
  V(status_string, "status")                                                   \
293
  V(stdio_string, "stdio")                                                     \
294
  V(subject_string, "subject")                                                 \
295
  V(subjectaltname_string, "subjectaltname")                                   \
296
  V(syscall_string, "syscall")                                                 \
297
  V(target_string, "target")                                                   \
298
  V(thread_id_string, "threadId")                                              \
299
  V(ticketkeycallback_string, "onticketkeycallback")                           \
300
  V(timeout_string, "timeout")                                                 \
301
  V(tls_ticket_string, "tlsTicket")                                            \
302
  V(ttl_string, "ttl")                                                         \
303
  V(type_string, "type")                                                       \
304
  V(uid_string, "uid")                                                         \
305
  V(unknown_string, "<unknown>")                                               \
306
  V(url_string, "url")                                                         \
307
  V(username_string, "username")                                               \
308
  V(valid_from_string, "valid_from")                                           \
309
  V(valid_to_string, "valid_to")                                               \
310
  V(value_string, "value")                                                     \
311
  V(verify_error_string, "verifyError")                                        \
312
  V(version_string, "version")                                                 \
313
  V(weight_string, "weight")                                                   \
314
  V(windows_hide_string, "windowsHide")                                        \
315
  V(windows_verbatim_arguments_string, "windowsVerbatimArguments")             \
316
  V(wrap_string, "wrap")                                                       \
317
  V(writable_string, "writable")                                               \
318
  V(write_host_object_string, "_writeHostObject")                              \
319
  V(write_queue_size_string, "writeQueueSize")                                 \
320
  V(x_forwarded_string, "x-forwarded-for")                                     \
321
  V(zero_return_string, "ZERO_RETURN")
322
323
#define ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V)                            \
324
  V(as_external, v8::External)                                                 \
325
  V(async_hooks_after_function, v8::Function)                                  \
326
  V(async_hooks_before_function, v8::Function)                                 \
327
  V(async_hooks_binding, v8::Object)                                           \
328
  V(async_hooks_destroy_function, v8::Function)                                \
329
  V(async_hooks_init_function, v8::Function)                                   \
330
  V(async_hooks_promise_resolve_function, v8::Function)                        \
331
  V(async_wrap_ctor_template, v8::FunctionTemplate)                            \
332
  V(async_wrap_object_ctor_template, v8::FunctionTemplate)                     \
333
  V(buffer_prototype_object, v8::Object)                                       \
334
  V(coverage_connection, v8::Object)                                           \
335
  V(context, v8::Context)                                                      \
336
  V(crypto_key_object_constructor, v8::Function)                               \
337
  V(domain_callback, v8::Function)                                             \
338
  V(domexception_function, v8::Function)                                       \
339
  V(fd_constructor_template, v8::ObjectTemplate)                               \
340
  V(fdclose_constructor_template, v8::ObjectTemplate)                          \
341
  V(filehandlereadwrap_template, v8::ObjectTemplate)                           \
342
  V(fs_use_promises_symbol, v8::Symbol)                                        \
343
  V(fsreqpromise_constructor_template, v8::ObjectTemplate)                     \
344
  V(handle_wrap_ctor_template, v8::FunctionTemplate)                           \
345
  V(host_import_module_dynamically_callback, v8::Function)                     \
346
  V(host_initialize_import_meta_object_callback, v8::Function)                 \
347
  V(http2ping_constructor_template, v8::ObjectTemplate)                        \
348
  V(http2session_on_altsvc_function, v8::Function)                             \
349
  V(http2session_on_error_function, v8::Function)                              \
350
  V(http2session_on_frame_error_function, v8::Function)                        \
351
  V(http2session_on_goaway_data_function, v8::Function)                        \
352
  V(http2session_on_headers_function, v8::Function)                            \
353
  V(http2session_on_origin_function, v8::Function)                             \
354
  V(http2session_on_ping_function, v8::Function)                               \
355
  V(http2session_on_priority_function, v8::Function)                           \
356
  V(http2session_on_select_padding_function, v8::Function)                     \
357
  V(http2session_on_settings_function, v8::Function)                           \
358
  V(http2session_on_stream_close_function, v8::Function)                       \
359
  V(http2session_on_stream_trailers_function, v8::Function)                    \
360
  V(http2settings_constructor_template, v8::ObjectTemplate)                    \
361
  V(http2stream_constructor_template, v8::ObjectTemplate)                      \
362
  V(internal_binding_loader, v8::Function)                                     \
363
  V(immediate_callback_function, v8::Function)                                 \
364
  V(inspector_console_extension_installer, v8::Function)                       \
365
  V(libuv_stream_wrap_ctor_template, v8::FunctionTemplate)                     \
366
  V(message_port, v8::Object)                                                  \
367
  V(message_event_object_template, v8::ObjectTemplate)                         \
368
  V(message_port_constructor_template, v8::FunctionTemplate)                   \
369
  V(native_module_require, v8::Function)                                       \
370
  V(on_coverage_message_function, v8::Function)                                \
371
  V(performance_entry_callback, v8::Function)                                  \
372
  V(performance_entry_template, v8::Function)                                  \
373
  V(pipe_constructor_template, v8::FunctionTemplate)                           \
374
  V(process_object, v8::Object)                                                \
375
  V(primordials, v8::Object)                                                   \
376
  V(promise_reject_callback, v8::Function)                                     \
377
  V(promise_wrap_template, v8::ObjectTemplate)                                 \
378
  V(sab_lifetimepartner_constructor_template, v8::FunctionTemplate)            \
379
  V(script_context_constructor_template, v8::FunctionTemplate)                 \
380
  V(script_data_constructor_function, v8::Function)                            \
381
  V(secure_context_constructor_template, v8::FunctionTemplate)                 \
382
  V(shutdown_wrap_template, v8::ObjectTemplate)                                \
383
  V(tcp_constructor_template, v8::FunctionTemplate)                            \
384
  V(tick_callback_function, v8::Function)                                      \
385
  V(timers_callback_function, v8::Function)                                    \
386
  V(tls_wrap_constructor_function, v8::Function)                               \
387
  V(trace_category_state_function, v8::Function)                               \
388
  V(tty_constructor_template, v8::FunctionTemplate)                            \
389
  V(udp_constructor_function, v8::Function)                                    \
390
  V(url_constructor_function, v8::Function)                                    \
391
  V(write_wrap_template, v8::ObjectTemplate)
392
393
class Environment;
394
395
class IsolateData {
396
 public:
397
  IsolateData(v8::Isolate* isolate, uv_loop_t* event_loop,
398
              MultiIsolatePlatform* platform = nullptr,
399
              uint32_t* zero_fill_field = nullptr);
400
  ~IsolateData();
401
  inline uv_loop_t* event_loop() const;
402
  inline uint32_t* zero_fill_field() const;
403
  inline MultiIsolatePlatform* platform() const;
404
  inline std::shared_ptr<PerIsolateOptions> options();
405
  inline void set_options(std::shared_ptr<PerIsolateOptions> options);
406
407
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
408
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
409
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
410
#define V(TypeName, PropertyName)                                             \
411
  inline v8::Local<TypeName> PropertyName(v8::Isolate* isolate) const;
412
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
413
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
414
  PER_ISOLATE_STRING_PROPERTIES(VS)
415
#undef V
416
#undef VY
417
#undef VS
418
#undef VP
419
420
  std::unordered_map<nghttp2_rcbuf*, v8::Eternal<v8::String>> http2_static_strs;
421
  inline v8::Isolate* isolate() const;
422
423
 private:
424
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
425
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
426
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
427
#define V(TypeName, PropertyName)                                             \
428
  v8::Eternal<TypeName> PropertyName ## _;
429
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
430
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
431
  PER_ISOLATE_STRING_PROPERTIES(VS)
432
#undef V
433
#undef VY
434
#undef VS
435
#undef VP
436
437
  v8::Isolate* const isolate_;
438
  uv_loop_t* const event_loop_;
439
  uint32_t* const zero_fill_field_;
440
  MultiIsolatePlatform* platform_;
441
  std::shared_ptr<PerIsolateOptions> options_;
442
443
  DISALLOW_COPY_AND_ASSIGN(IsolateData);
444
};
445
446
13357
struct ContextInfo {
447
13357
  explicit ContextInfo(const std::string& name) : name(name) {}
448
  const std::string name;
449
  std::string origin;
450
  bool is_default = false;
451
};
452
453
struct CompileFnEntry {
454
  Environment* env;
455
  uint32_t id;
456
  CompileFnEntry(Environment* env, uint32_t id);
457
};
458
459
// Listing the AsyncWrap provider types first enables us to cast directly
460
// from a provider type to a debug category.
461
#define DEBUG_CATEGORY_NAMES(V)                                                \
462
  NODE_ASYNC_PROVIDER_TYPES(V)                                                 \
463
  V(INSPECTOR_SERVER)                                                          \
464
  V(COVERAGE)
465
466
enum class DebugCategory {
467
#define V(name) name,
468
  DEBUG_CATEGORY_NAMES(V)
469
#undef V
470
  CATEGORY_COUNT
471
};
472
473
class Environment {
474
 public:
475
4036
  class AsyncHooks {
476
   public:
477
    // Reason for both UidFields and Fields are that one is stored as a double*
478
    // and the other as a uint32_t*.
479
    enum Fields {
480
      kInit,
481
      kBefore,
482
      kAfter,
483
      kDestroy,
484
      kPromiseResolve,
485
      kTotals,
486
      kCheck,
487
      kStackLength,
488
      kFieldsCount,
489
    };
490
491
    enum UidFields {
492
      kExecutionAsyncId,
493
      kTriggerAsyncId,
494
      kAsyncIdCounter,
495
      kDefaultTriggerAsyncId,
496
      kUidFieldsCount,
497
    };
498
499
    inline AliasedBuffer<uint32_t, v8::Uint32Array>& fields();
500
    inline AliasedBuffer<double, v8::Float64Array>& async_id_fields();
501
    inline AliasedBuffer<double, v8::Float64Array>& async_ids_stack();
502
503
    inline v8::Local<v8::String> provider_string(int idx);
504
505
    inline void no_force_checks();
506
    inline Environment* env();
507
508
    inline void push_async_ids(double async_id, double trigger_async_id);
509
    inline bool pop_async_id(double async_id);
510
    inline void clear_async_id_stack();  // Used in fatal exceptions.
511
512
    // Used to set the kDefaultTriggerAsyncId in a scope. This is instead of
513
    // passing the trigger_async_id along with other constructor arguments.
514
    class DefaultTriggerAsyncIdScope {
515
     public:
516
      DefaultTriggerAsyncIdScope() = delete;
517
      explicit DefaultTriggerAsyncIdScope(Environment* env,
518
                                          double init_trigger_async_id);
519
      explicit DefaultTriggerAsyncIdScope(AsyncWrap* async_wrap);
520
      ~DefaultTriggerAsyncIdScope();
521
522
     private:
523
      AsyncHooks* async_hooks_;
524
      double old_default_trigger_async_id_;
525
526
      DISALLOW_COPY_AND_ASSIGN(DefaultTriggerAsyncIdScope);
527
    };
528
529
530
   private:
531
    friend class Environment;  // So we can call the constructor.
532
    inline AsyncHooks();
533
    // Keep a list of all Persistent strings used for Provider types.
534
    v8::Eternal<v8::String> providers_[AsyncWrap::PROVIDERS_LENGTH];
535
    // Stores the ids of the current execution context stack.
536
    AliasedBuffer<double, v8::Float64Array> async_ids_stack_;
537
    // Attached to a Uint32Array that tracks the number of active hooks for
538
    // each type.
539
    AliasedBuffer<uint32_t, v8::Uint32Array> fields_;
540
    // Attached to a Float64Array that tracks the state of async resources.
541
    AliasedBuffer<double, v8::Float64Array> async_id_fields_;
542
543
    void grow_async_ids_stack();
544
545
    DISALLOW_COPY_AND_ASSIGN(AsyncHooks);
546
  };
547
548
  class AsyncCallbackScope {
549
   public:
550
    AsyncCallbackScope() = delete;
551
    explicit AsyncCallbackScope(Environment* env);
552
    ~AsyncCallbackScope();
553
554
   private:
555
    Environment* env_;
556
557
    DISALLOW_COPY_AND_ASSIGN(AsyncCallbackScope);
558
  };
559
560
  inline size_t makecallback_depth() const;
561
562
4036
  class ImmediateInfo {
563
   public:
564
    inline AliasedBuffer<uint32_t, v8::Uint32Array>& fields();
565
    inline uint32_t count() const;
566
    inline uint32_t ref_count() const;
567
    inline bool has_outstanding() const;
568
569
    inline void count_inc(uint32_t increment);
570
    inline void count_dec(uint32_t decrement);
571
572
    inline void ref_count_inc(uint32_t increment);
573
    inline void ref_count_dec(uint32_t decrement);
574
575
   private:
576
    friend class Environment;  // So we can call the constructor.
577
    inline explicit ImmediateInfo(v8::Isolate* isolate);
578
579
    enum Fields {
580
      kCount,
581
      kRefCount,
582
      kHasOutstanding,
583
      kFieldsCount
584
    };
585
586
    AliasedBuffer<uint32_t, v8::Uint32Array> fields_;
587
588
    DISALLOW_COPY_AND_ASSIGN(ImmediateInfo);
589
  };
590
591
4036
  class TickInfo {
592
   public:
593
    inline AliasedBuffer<uint8_t, v8::Uint8Array>& fields();
594
    inline bool has_tick_scheduled() const;
595
    inline bool has_rejection_to_warn() const;
596
597
   private:
598
    friend class Environment;  // So we can call the constructor.
599
    inline explicit TickInfo(v8::Isolate* isolate);
600
601
    enum Fields {
602
      kHasTickScheduled = 0,
603
      kHasRejectionToWarn,
604
      kFieldsCount
605
    };
606
607
    AliasedBuffer<uint8_t, v8::Uint8Array> fields_;
608
609
    DISALLOW_COPY_AND_ASSIGN(TickInfo);
610
  };
611
612
  enum Flags {
613
    kNoFlags = 0,
614
    kIsMainThread = 1 << 0,
615
    kOwnsProcessState = 1 << 1,
616
    kOwnsInspector = 1 << 2,
617
  };
618
619
  static inline Environment* GetCurrent(v8::Isolate* isolate);
620
  static inline Environment* GetCurrent(v8::Local<v8::Context> context);
621
  static inline Environment* GetCurrent(
622
      const v8::FunctionCallbackInfo<v8::Value>& info);
623
624
  template <typename T>
625
  static inline Environment* GetCurrent(
626
      const v8::PropertyCallbackInfo<T>& info);
627
628
  static uv_key_t thread_local_env;
629
  static inline Environment* GetThreadLocalEnv();
630
631
  Environment(IsolateData* isolate_data,
632
              v8::Local<v8::Context> context,
633
              Flags flags = Flags(),
634
              uint64_t thread_id = kNoThreadId);
635
  ~Environment();
636
637
  void Start(bool start_profiler_idle_notifier);
638
  v8::MaybeLocal<v8::Object> ProcessCliArgs(
639
      const std::vector<std::string>& args,
640
      const std::vector<std::string>& exec_args);
641
642
  typedef void (*HandleCleanupCb)(Environment* env,
643
                                  uv_handle_t* handle,
644
                                  void* arg);
645
  struct HandleCleanup {
646
    uv_handle_t* handle_;
647
    HandleCleanupCb cb_;
648
    void* arg_;
649
  };
650
651
  void RegisterHandleCleanups();
652
  void CleanupHandles();
653
  void Exit(int code);
654
655
  // Register clean-up cb to be called on environment destruction.
656
  inline void RegisterHandleCleanup(uv_handle_t* handle,
657
                                    HandleCleanupCb cb,
658
                                    void* arg);
659
660
  template <typename T, typename OnCloseCallback>
661
  inline void CloseHandle(T* handle, OnCloseCallback callback);
662
663
  inline void AssignToContext(v8::Local<v8::Context> context,
664
                              const ContextInfo& info);
665
666
  void StartProfilerIdleNotifier();
667
  void StopProfilerIdleNotifier();
668
  inline bool profiler_idle_notifier_started() const;
669
670
  inline v8::Isolate* isolate() const;
671
  inline uv_loop_t* event_loop() const;
672
  inline void TryLoadAddon(
673
      const char* filename,
674
      int flags,
675
      const std::function<bool(binding::DLib*)>& was_loaded);
676
677
  static inline Environment* from_timer_handle(uv_timer_t* handle);
678
  inline uv_timer_t* timer_handle();
679
680
  static inline Environment* from_immediate_check_handle(uv_check_t* handle);
681
  inline uv_check_t* immediate_check_handle();
682
  inline uv_idle_t* immediate_idle_handle();
683
684
  inline void IncreaseWaitingRequestCounter();
685
  inline void DecreaseWaitingRequestCounter();
686
687
  inline AsyncHooks* async_hooks();
688
  inline ImmediateInfo* immediate_info();
689
  inline TickInfo* tick_info();
690
  inline uint64_t timer_base() const;
691
692
  inline IsolateData* isolate_data() const;
693
694
  inline bool printed_error() const;
695
  inline void set_printed_error(bool value);
696
697
  void PrintSyncTrace() const;
698
  inline void set_trace_sync_io(bool value);
699
700
  // This stores whether the --abort-on-uncaught-exception flag was passed
701
  // to Node.
702
  inline bool abort_on_uncaught_exception() const;
703
  inline void set_abort_on_uncaught_exception(bool value);
704
  // This is a pseudo-boolean that keeps track of whether an uncaught exception
705
  // should abort the process or not if --abort-on-uncaught-exception was
706
  // passed to Node. If the flag was not passed, it is ignored.
707
  inline AliasedBuffer<uint32_t, v8::Uint32Array>&
708
  should_abort_on_uncaught_toggle();
709
710
  inline AliasedBuffer<int32_t, v8::Int32Array>& stream_base_state();
711
712
  // The necessary API for async_hooks.
713
  inline double new_async_id();
714
  inline double execution_async_id();
715
  inline double trigger_async_id();
716
  inline double get_default_trigger_async_id();
717
718
  // List of id's that have been destroyed and need the destroy() cb called.
719
  inline std::vector<double>* destroy_async_id_list();
720
721
  std::set<std::string> native_modules_with_cache;
722
  std::set<std::string> native_modules_without_cache;
723
724
  std::unordered_multimap<int, loader::ModuleWrap*> hash_to_module_map;
725
  std::unordered_map<uint32_t, loader::ModuleWrap*> id_to_module_map;
726
  std::unordered_map<uint32_t, contextify::ContextifyScript*>
727
      id_to_script_map;
728
  std::unordered_set<CompileFnEntry*> compile_fn_entries;
729
  std::unordered_map<uint32_t, Persistent<v8::Function>> id_to_function_map;
730
731
  inline uint32_t get_next_module_id();
732
  inline uint32_t get_next_script_id();
733
  inline uint32_t get_next_function_id();
734
735
  std::unordered_map<std::string, const loader::PackageConfig>
736
      package_json_cache;
737
738
  inline double* heap_statistics_buffer() const;
739
  inline void set_heap_statistics_buffer(double* pointer);
740
741
  inline double* heap_space_statistics_buffer() const;
742
  inline void set_heap_space_statistics_buffer(double* pointer);
743
744
  inline char* http_parser_buffer() const;
745
  inline void set_http_parser_buffer(char* buffer);
746
  inline bool http_parser_buffer_in_use() const;
747
  inline void set_http_parser_buffer_in_use(bool in_use);
748
749
  inline http2::Http2State* http2_state() const;
750
  inline void set_http2_state(std::unique_ptr<http2::Http2State> state);
751
752
  inline bool debug_enabled(DebugCategory category) const;
753
  inline void set_debug_enabled(DebugCategory category, bool enabled);
754
  void set_debug_categories(const std::string& cats, bool enabled);
755
756
  inline AliasedBuffer<double, v8::Float64Array>* fs_stats_field_array();
757
  inline AliasedBuffer<uint64_t, v8::BigUint64Array>*
758
      fs_stats_field_bigint_array();
759
760
  inline std::vector<std::unique_ptr<fs::FileHandleReadWrap>>&
761
      file_handle_read_wrap_freelist();
762
763
  inline performance::performance_state* performance_state();
764
  inline std::unordered_map<std::string, uint64_t>* performance_marks();
765
766
  void CollectUVExceptionInfo(v8::Local<v8::Value> context,
767
                              int errorno,
768
                              const char* syscall = nullptr,
769
                              const char* message = nullptr,
770
                              const char* path = nullptr,
771
                              const char* dest = nullptr);
772
773
  // If this flag is set, calls into JS (if they would be observable
774
  // from userland) must be avoided.  This flag does not indicate whether
775
  // calling into JS is allowed from a VM perspective at this point.
776
  inline bool can_call_into_js() const;
777
  inline void set_can_call_into_js(bool can_call_into_js);
778
779
  inline bool has_run_bootstrapping_code() const;
780
  inline void set_has_run_bootstrapping_code(bool has_run_bootstrapping_code);
781
782
  static uint64_t AllocateThreadId();
783
  static constexpr uint64_t kNoThreadId = -1;
784
785
  inline bool is_main_thread() const;
786
  inline bool owns_process_state() const;
787
  inline bool owns_inspector() const;
788
  inline uint64_t thread_id() const;
789
  inline worker::Worker* worker_context() const;
790
  inline void set_worker_context(worker::Worker* context);
791
  inline void add_sub_worker_context(worker::Worker* context);
792
  inline void remove_sub_worker_context(worker::Worker* context);
793
  void stop_sub_worker_contexts();
794
  inline bool is_stopping_worker() const;
795
796
  inline void ThrowError(const char* errmsg);
797
  inline void ThrowTypeError(const char* errmsg);
798
  inline void ThrowRangeError(const char* errmsg);
799
  inline void ThrowErrnoException(int errorno,
800
                                  const char* syscall = nullptr,
801
                                  const char* message = nullptr,
802
                                  const char* path = nullptr);
803
  inline void ThrowUVException(int errorno,
804
                               const char* syscall = nullptr,
805
                               const char* message = nullptr,
806
                               const char* path = nullptr,
807
                               const char* dest = nullptr);
808
809
  inline v8::Local<v8::FunctionTemplate>
810
      NewFunctionTemplate(v8::FunctionCallback callback,
811
                          v8::Local<v8::Signature> signature =
812
                              v8::Local<v8::Signature>(),
813
                          v8::ConstructorBehavior behavior =
814
                              v8::ConstructorBehavior::kAllow,
815
                          v8::SideEffectType side_effect =
816
                              v8::SideEffectType::kHasSideEffect);
817
818
  // Convenience methods for NewFunctionTemplate().
819
  inline void SetMethod(v8::Local<v8::Object> that,
820
                        const char* name,
821
                        v8::FunctionCallback callback);
822
823
  inline void SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
824
                             const char* name,
825
                             v8::FunctionCallback callback);
826
  inline void SetTemplateMethod(v8::Local<v8::FunctionTemplate> that,
827
                                const char* name,
828
                                v8::FunctionCallback callback);
829
830
  // Safe variants denote the function has no side effects.
831
  inline void SetMethodNoSideEffect(v8::Local<v8::Object> that,
832
                                    const char* name,
833
                                    v8::FunctionCallback callback);
834
  inline void SetProtoMethodNoSideEffect(v8::Local<v8::FunctionTemplate> that,
835
                                         const char* name,
836
                                         v8::FunctionCallback callback);
837
  inline void SetTemplateMethodNoSideEffect(
838
      v8::Local<v8::FunctionTemplate> that,
839
      const char* name,
840
      v8::FunctionCallback callback);
841
842
  void BeforeExit(void (*cb)(void* arg), void* arg);
843
  void RunBeforeExitCallbacks();
844
  void AtExit(void (*cb)(void* arg), void* arg);
845
  void RunAtExitCallbacks();
846
847
  // Strings and private symbols are shared across shared contexts
848
  // The getters simply proxy to the per-isolate primitive.
849
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
850
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
851
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
852
#define V(TypeName, PropertyName)                                             \
853
  inline v8::Local<TypeName> PropertyName() const;
854
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
855
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
856
  PER_ISOLATE_STRING_PROPERTIES(VS)
857
#undef V
858
#undef VS
859
#undef VY
860
#undef VP
861
862
#define V(PropertyName, TypeName)                                             \
863
  inline v8::Local<TypeName> PropertyName() const;                            \
864
  inline void set_ ## PropertyName(v8::Local<TypeName> value);
865
  ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V)
866
#undef V
867
868
#if HAVE_INSPECTOR
869
172689
  inline inspector::Agent* inspector_agent() const {
870
172689
    return inspector_agent_.get();
871
  }
872
873
  inline bool is_in_inspector_console_call() const;
874
  inline void set_is_in_inspector_console_call(bool value);
875
#endif
876
877
  typedef ListHead<HandleWrap, &HandleWrap::handle_wrap_queue_> HandleWrapQueue;
878
  typedef ListHead<ReqWrapBase, &ReqWrapBase::req_wrap_queue_> ReqWrapQueue;
879
880
38989
  inline HandleWrapQueue* handle_wrap_queue() { return &handle_wrap_queue_; }
881
212242
  inline ReqWrapQueue* req_wrap_queue() { return &req_wrap_queue_; }
882
883
  void AddPromiseHook(promise_hook_func fn, void* arg);
884
  bool RemovePromiseHook(promise_hook_func fn, void* arg);
885
1
  inline bool EmitProcessEnvWarning() {
886
1
    bool current_value = emit_env_nonstring_warning_;
887
1
    emit_env_nonstring_warning_ = false;
888
1
    return current_value;
889
  }
890
891
1
  inline bool EmitErrNameWarning() {
892
1
    bool current_value = emit_err_name_warning_;
893
1
    emit_err_name_warning_ = false;
894
1
    return current_value;
895
  }
896
897
  typedef void (*native_immediate_callback)(Environment* env, void* data);
898
  // cb will be called as cb(env, data) on the next event loop iteration.
899
  // obj will be kept alive between now and after the callback has run.
900
  inline void SetImmediate(native_immediate_callback cb,
901
                           void* data,
902
                           v8::Local<v8::Object> obj = v8::Local<v8::Object>());
903
  inline void SetUnrefImmediate(native_immediate_callback cb,
904
                                void* data,
905
                                v8::Local<v8::Object> obj =
906
                                    v8::Local<v8::Object>());
907
  // This needs to be available for the JS-land setImmediate().
908
  void ToggleImmediateRef(bool ref);
909
910
8072
  class TrackingTraceStateObserver :
911
      public v8::TracingController::TraceStateObserver {
912
   public:
913
4405
    explicit TrackingTraceStateObserver(Environment* env) : env_(env) {}
914
915
102
    void OnTraceEnabled() override {
916
102
      UpdateTraceCategoryState();
917
102
    }
918
919
32
    void OnTraceDisabled() override {
920
32
      UpdateTraceCategoryState();
921
32
    }
922
923
   private:
924
    void UpdateTraceCategoryState();
925
926
    Environment* env_;
927
  };
928
929
  class ShouldNotAbortOnUncaughtScope {
930
   public:
931
    explicit inline ShouldNotAbortOnUncaughtScope(Environment* env);
932
    inline void Close();
933
    inline ~ShouldNotAbortOnUncaughtScope();
934
935
   private:
936
    Environment* env_;
937
  };
938
939
  inline bool inside_should_not_abort_on_uncaught_scope() const;
940
941
  static inline Environment* ForAsyncHooks(AsyncHooks* hooks);
942
943
  v8::Local<v8::Value> GetNow();
944
  void ScheduleTimer(int64_t duration);
945
  void ToggleTimerRef(bool ref);
946
947
  inline void AddCleanupHook(void (*fn)(void*), void* arg);
948
  inline void RemoveCleanupHook(void (*fn)(void*), void* arg);
949
  void RunCleanup();
950
951
  static void BuildEmbedderGraph(v8::Isolate* isolate,
952
                                 v8::EmbedderGraph* graph,
953
                                 void* data);
954
955
  inline std::shared_ptr<EnvironmentOptions> options();
956
  inline std::shared_ptr<HostPort> inspector_host_port();
957
958
  enum class ExecutionMode {
959
    kDefault,
960
    kInspect,              // node inspect
961
    kDebug,                // node debug
962
    kPrintHelp,            // node --help
963
    kPrintBashCompletion,  // node --completion-bash
964
    kProfProcess,          // node --prof-process
965
    kEvalString,           // node --eval without --interactive
966
    kCheckSyntax,          // node --check (incompatible with --eval)
967
    kRepl,
968
    kEvalStdin,
969
    kRunMainModule
970
  };
971
972
12384
  inline ExecutionMode execution_mode() { return execution_mode_; }
973
974
353
  inline void set_execution_mode(ExecutionMode mode) { execution_mode_ = mode; }
975
976
 private:
977
  inline void CreateImmediate(native_immediate_callback cb,
978
                              void* data,
979
                              v8::Local<v8::Object> obj,
980
                              bool ref);
981
982
  inline void ThrowError(v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
983
                         const char* errmsg);
984
985
  ExecutionMode execution_mode_ = ExecutionMode::kDefault;
986
  std::list<binding::DLib> loaded_addons_;
987
  v8::Isolate* const isolate_;
988
  IsolateData* const isolate_data_;
989
  uv_timer_t timer_handle_;
990
  uv_check_t immediate_check_handle_;
991
  uv_idle_t immediate_idle_handle_;
992
  uv_prepare_t idle_prepare_handle_;
993
  uv_check_t idle_check_handle_;
994
  bool profiler_idle_notifier_started_ = false;
995
996
  AsyncHooks async_hooks_;
997
  ImmediateInfo immediate_info_;
998
  TickInfo tick_info_;
999
  const uint64_t timer_base_;
1000
  bool printed_error_ = false;
1001
  bool abort_on_uncaught_exception_ = false;
1002
  bool emit_env_nonstring_warning_ = true;
1003
  bool emit_err_name_warning_ = true;
1004
  size_t makecallback_cntr_ = 0;
1005
  std::vector<double> destroy_async_id_list_;
1006
1007
  std::shared_ptr<EnvironmentOptions> options_;
1008
  // options_ contains debug options parsed from CLI arguments,
1009
  // while inspector_host_port_ stores the actual inspector host
1010
  // and port being used. For example the port is -1 by default
1011
  // and can be specified as 0 (meaning any port allocated when the
1012
  // server starts listening), but when the inspector server starts
1013
  // the inspector_host_port_->port() will be the actual port being
1014
  // used.
1015
  std::shared_ptr<HostPort> inspector_host_port_;
1016
1017
  uint32_t module_id_counter_ = 0;
1018
  uint32_t script_id_counter_ = 0;
1019
  uint32_t function_id_counter_ = 0;
1020
1021
  AliasedBuffer<uint32_t, v8::Uint32Array> should_abort_on_uncaught_toggle_;
1022
  int should_not_abort_scope_counter_ = 0;
1023
1024
  std::unique_ptr<TrackingTraceStateObserver> trace_state_observer_;
1025
1026
  AliasedBuffer<int32_t, v8::Int32Array> stream_base_state_;
1027
1028
  std::unique_ptr<performance::performance_state> performance_state_;
1029
  std::unordered_map<std::string, uint64_t> performance_marks_;
1030
1031
  bool has_run_bootstrapping_code_ = false;
1032
  bool can_call_into_js_ = true;
1033
  Flags flags_;
1034
  uint64_t thread_id_;
1035
  std::unordered_set<worker::Worker*> sub_worker_contexts_;
1036
1037
  static void* const kNodeContextTagPtr;
1038
  static int const kNodeContextTag;
1039
1040
#if HAVE_INSPECTOR
1041
  std::unique_ptr<inspector::Agent> inspector_agent_;
1042
  bool is_in_inspector_console_call_ = false;
1043
#endif
1044
1045
  // handle_wrap_queue_ and req_wrap_queue_ needs to be at a fixed offset from
1046
  // the start of the class because it is used by
1047
  // src/node_postmortem_metadata.cc to calculate offsets and generate debug
1048
  // symbols for Environment, which assumes that the position of members in
1049
  // memory are predictable. For more information please refer to
1050
  // `doc/guides/node-postmortem-support.md`
1051
  friend int GenDebugSymbols();
1052
  HandleWrapQueue handle_wrap_queue_;
1053
  ReqWrapQueue req_wrap_queue_;
1054
  std::list<HandleCleanup> handle_cleanup_queue_;
1055
  int handle_cleanup_waiting_ = 0;
1056
  int request_waiting_ = 0;
1057
1058
  double* heap_statistics_buffer_ = nullptr;
1059
  double* heap_space_statistics_buffer_ = nullptr;
1060
1061
  char* http_parser_buffer_ = nullptr;
1062
  bool http_parser_buffer_in_use_ = false;
1063
  std::unique_ptr<http2::Http2State> http2_state_;
1064
1065
  bool debug_enabled_[static_cast<int>(DebugCategory::CATEGORY_COUNT)] = {0};
1066
1067
  AliasedBuffer<double, v8::Float64Array> fs_stats_field_array_;
1068
  AliasedBuffer<uint64_t, v8::BigUint64Array> fs_stats_field_bigint_array_;
1069
1070
  std::vector<std::unique_ptr<fs::FileHandleReadWrap>>
1071
      file_handle_read_wrap_freelist_;
1072
1073
  worker::Worker* worker_context_ = nullptr;
1074
1075
  static void RunTimers(uv_timer_t* handle);
1076
1077
  struct ExitCallback {
1078
    void (*cb_)(void* arg);
1079
    void* arg_;
1080
  };
1081
  std::list<ExitCallback> before_exit_functions_;
1082
1083
  std::list<ExitCallback> at_exit_functions_;
1084
1085
  struct PromiseHookCallback {
1086
    promise_hook_func cb_;
1087
    void* arg_;
1088
    size_t enable_count_;
1089
  };
1090
  std::vector<PromiseHookCallback> promise_hooks_;
1091
1092
157321
  struct NativeImmediateCallback {
1093
    native_immediate_callback cb_;
1094
    void* data_;
1095
    std::unique_ptr<Persistent<v8::Object>> keep_alive_;
1096
    bool refed_;
1097
  };
1098
  std::vector<NativeImmediateCallback> native_immediate_callbacks_;
1099
  void RunAndClearNativeImmediates();
1100
  static void CheckImmediate(uv_check_t* handle);
1101
1102
  struct CleanupHookCallback {
1103
    void (*fn_)(void*);
1104
    void* arg_;
1105
1106
    // We keep track of the insertion order for these objects, so that we can
1107
    // call the callbacks in reverse order when we are cleaning up.
1108
    uint64_t insertion_order_counter_;
1109
1110
    // Only hashes `arg_`, since that is usually enough to identify the hook.
1111
    struct Hash {
1112
      inline size_t operator()(const CleanupHookCallback& cb) const;
1113
    };
1114
1115
    // Compares by `fn_` and `arg_` being equal.
1116
    struct Equal {
1117
      inline bool operator()(const CleanupHookCallback& a,
1118
                             const CleanupHookCallback& b) const;
1119
    };
1120
1121
    inline BaseObject* GetBaseObject() const;
1122
  };
1123
1124
  // Use an unordered_set, so that we have efficient insertion and removal.
1125
  std::unordered_set<CleanupHookCallback,
1126
                     CleanupHookCallback::Hash,
1127
                     CleanupHookCallback::Equal> cleanup_hooks_;
1128
  uint64_t cleanup_hook_counter_ = 0;
1129
1130
  static void EnvPromiseHook(v8::PromiseHookType type,
1131
                             v8::Local<v8::Promise> promise,
1132
                             v8::Local<v8::Value> parent);
1133
1134
  template <typename T>
1135
  void ForEachBaseObject(T&& iterator);
1136
1137
#define V(PropertyName, TypeName) Persistent<TypeName> PropertyName ## _;
1138
  ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V)
1139
#undef V
1140
1141
  DISALLOW_COPY_AND_ASSIGN(Environment);
1142
};
1143
1144
}  // namespace node
1145
1146
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1147
1148
#endif  // SRC_ENV_H_