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