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-03-02 22:23:06 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 <cstdint>
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,
398
              uv_loop_t* event_loop,
399
              MultiIsolatePlatform* platform = nullptr,
400
              ArrayBufferAllocator* node_allocator = nullptr);
401
  ~IsolateData();
402
  inline uv_loop_t* event_loop() 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
  inline bool uses_node_allocator() const;
408
  inline v8::ArrayBuffer::Allocator* allocator() const;
409
  inline ArrayBufferAllocator* node_allocator() const;
410
411
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
412
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
413
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
414
#define V(TypeName, PropertyName)                                             \
415
  inline v8::Local<TypeName> PropertyName(v8::Isolate* isolate) const;
416
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
417
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
418
  PER_ISOLATE_STRING_PROPERTIES(VS)
419
#undef V
420
#undef VY
421
#undef VS
422
#undef VP
423
424
  std::unordered_map<nghttp2_rcbuf*, v8::Eternal<v8::String>> http2_static_strs;
425
  inline v8::Isolate* isolate() const;
426
427
 private:
428
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
429
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
430
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
431
#define V(TypeName, PropertyName)                                             \
432
  v8::Eternal<TypeName> PropertyName ## _;
433
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
434
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
435
  PER_ISOLATE_STRING_PROPERTIES(VS)
436
#undef V
437
#undef VY
438
#undef VS
439
#undef VP
440
441
  v8::Isolate* const isolate_;
442
  uv_loop_t* const event_loop_;
443
  v8::ArrayBuffer::Allocator* const allocator_;
444
  ArrayBufferAllocator* const node_allocator_;
445
  const bool uses_node_allocator_;
446
  MultiIsolatePlatform* platform_;
447
  std::shared_ptr<PerIsolateOptions> options_;
448
449
  DISALLOW_COPY_AND_ASSIGN(IsolateData);
450
};
451
452
13399
struct ContextInfo {
453
13399
  explicit ContextInfo(const std::string& name) : name(name) {}
454
  const std::string name;
455
  std::string origin;
456
  bool is_default = false;
457
};
458
459
struct CompileFnEntry {
460
  Environment* env;
461
  uint32_t id;
462
  CompileFnEntry(Environment* env, uint32_t id);
463
};
464
465
// Listing the AsyncWrap provider types first enables us to cast directly
466
// from a provider type to a debug category.
467
#define DEBUG_CATEGORY_NAMES(V)                                                \
468
  NODE_ASYNC_PROVIDER_TYPES(V)                                                 \
469
  V(INSPECTOR_SERVER)                                                          \
470
  V(COVERAGE)
471
472
enum class DebugCategory {
473
#define V(name) name,
474
  DEBUG_CATEGORY_NAMES(V)
475
#undef V
476
  CATEGORY_COUNT
477
};
478
479
// A unique-pointer-ish object that is compatible with the JS engine's
480
// ArrayBuffer::Allocator.
481
struct AllocatedBuffer {
482
 public:
483
  explicit inline AllocatedBuffer(Environment* env = nullptr);
484
  inline AllocatedBuffer(Environment* env, uv_buf_t buf);
485
  inline ~AllocatedBuffer();
486
  inline void Resize(size_t len);
487
488
  inline uv_buf_t release();
489
  inline char* data();
490
  inline const char* data() const;
491
  inline size_t size() const;
492
  inline void clear();
493
494
  inline v8::MaybeLocal<v8::Object> ToBuffer();
495
  inline v8::Local<v8::ArrayBuffer> ToArrayBuffer();
496
497
  inline AllocatedBuffer(AllocatedBuffer&& other);
498
  inline AllocatedBuffer& operator=(AllocatedBuffer&& other);
499
  AllocatedBuffer(const AllocatedBuffer& other) = delete;
500
  AllocatedBuffer& operator=(const AllocatedBuffer& other) = delete;
501
502
 private:
503
  Environment* env_;
504
  // We do not pass this to libuv directly, but uv_buf_t is a convenient way
505
  // to represent a chunk of memory, and plays nicely with other parts of core.
506
  uv_buf_t buffer_;
507
508
  friend class Environment;
509
};
510
511
class Environment {
512
 public:
513
4049
  class AsyncHooks {
514
   public:
515
    // Reason for both UidFields and Fields are that one is stored as a double*
516
    // and the other as a uint32_t*.
517
    enum Fields {
518
      kInit,
519
      kBefore,
520
      kAfter,
521
      kDestroy,
522
      kPromiseResolve,
523
      kTotals,
524
      kCheck,
525
      kStackLength,
526
      kFieldsCount,
527
    };
528
529
    enum UidFields {
530
      kExecutionAsyncId,
531
      kTriggerAsyncId,
532
      kAsyncIdCounter,
533
      kDefaultTriggerAsyncId,
534
      kUidFieldsCount,
535
    };
536
537
    inline AliasedBuffer<uint32_t, v8::Uint32Array>& fields();
538
    inline AliasedBuffer<double, v8::Float64Array>& async_id_fields();
539
    inline AliasedBuffer<double, v8::Float64Array>& async_ids_stack();
540
541
    inline v8::Local<v8::String> provider_string(int idx);
542
543
    inline void no_force_checks();
544
    inline Environment* env();
545
546
    inline void push_async_ids(double async_id, double trigger_async_id);
547
    inline bool pop_async_id(double async_id);
548
    inline void clear_async_id_stack();  // Used in fatal exceptions.
549
550
    // Used to set the kDefaultTriggerAsyncId in a scope. This is instead of
551
    // passing the trigger_async_id along with other constructor arguments.
552
    class DefaultTriggerAsyncIdScope {
553
     public:
554
      DefaultTriggerAsyncIdScope() = delete;
555
      explicit DefaultTriggerAsyncIdScope(Environment* env,
556
                                          double init_trigger_async_id);
557
      explicit DefaultTriggerAsyncIdScope(AsyncWrap* async_wrap);
558
      ~DefaultTriggerAsyncIdScope();
559
560
     private:
561
      AsyncHooks* async_hooks_;
562
      double old_default_trigger_async_id_;
563
564
      DISALLOW_COPY_AND_ASSIGN(DefaultTriggerAsyncIdScope);
565
    };
566
567
568
   private:
569
    friend class Environment;  // So we can call the constructor.
570
    inline AsyncHooks();
571
    // Keep a list of all Persistent strings used for Provider types.
572
    v8::Eternal<v8::String> providers_[AsyncWrap::PROVIDERS_LENGTH];
573
    // Stores the ids of the current execution context stack.
574
    AliasedBuffer<double, v8::Float64Array> async_ids_stack_;
575
    // Attached to a Uint32Array that tracks the number of active hooks for
576
    // each type.
577
    AliasedBuffer<uint32_t, v8::Uint32Array> fields_;
578
    // Attached to a Float64Array that tracks the state of async resources.
579
    AliasedBuffer<double, v8::Float64Array> async_id_fields_;
580
581
    void grow_async_ids_stack();
582
583
    DISALLOW_COPY_AND_ASSIGN(AsyncHooks);
584
  };
585
586
  class AsyncCallbackScope {
587
   public:
588
    AsyncCallbackScope() = delete;
589
    explicit AsyncCallbackScope(Environment* env);
590
    ~AsyncCallbackScope();
591
592
   private:
593
    Environment* env_;
594
595
    DISALLOW_COPY_AND_ASSIGN(AsyncCallbackScope);
596
  };
597
598
  inline size_t makecallback_depth() const;
599
600
4049
  class ImmediateInfo {
601
   public:
602
    inline AliasedBuffer<uint32_t, v8::Uint32Array>& fields();
603
    inline uint32_t count() const;
604
    inline uint32_t ref_count() const;
605
    inline bool has_outstanding() const;
606
607
    inline void count_inc(uint32_t increment);
608
    inline void count_dec(uint32_t decrement);
609
610
    inline void ref_count_inc(uint32_t increment);
611
    inline void ref_count_dec(uint32_t decrement);
612
613
   private:
614
    friend class Environment;  // So we can call the constructor.
615
    inline explicit ImmediateInfo(v8::Isolate* isolate);
616
617
    enum Fields {
618
      kCount,
619
      kRefCount,
620
      kHasOutstanding,
621
      kFieldsCount
622
    };
623
624
    AliasedBuffer<uint32_t, v8::Uint32Array> fields_;
625
626
    DISALLOW_COPY_AND_ASSIGN(ImmediateInfo);
627
  };
628
629
4049
  class TickInfo {
630
   public:
631
    inline AliasedBuffer<uint8_t, v8::Uint8Array>& fields();
632
    inline bool has_tick_scheduled() const;
633
    inline bool has_rejection_to_warn() const;
634
635
   private:
636
    friend class Environment;  // So we can call the constructor.
637
    inline explicit TickInfo(v8::Isolate* isolate);
638
639
    enum Fields {
640
      kHasTickScheduled = 0,
641
      kHasRejectionToWarn,
642
      kFieldsCount
643
    };
644
645
    AliasedBuffer<uint8_t, v8::Uint8Array> fields_;
646
647
    DISALLOW_COPY_AND_ASSIGN(TickInfo);
648
  };
649
650
  enum Flags {
651
    kNoFlags = 0,
652
    kIsMainThread = 1 << 0,
653
    kOwnsProcessState = 1 << 1,
654
    kOwnsInspector = 1 << 2,
655
  };
656
657
  static inline Environment* GetCurrent(v8::Isolate* isolate);
658
  static inline Environment* GetCurrent(v8::Local<v8::Context> context);
659
  static inline Environment* GetCurrent(
660
      const v8::FunctionCallbackInfo<v8::Value>& info);
661
662
  template <typename T>
663
  static inline Environment* GetCurrent(
664
      const v8::PropertyCallbackInfo<T>& info);
665
666
  static uv_key_t thread_local_env;
667
  static inline Environment* GetThreadLocalEnv();
668
669
  Environment(IsolateData* isolate_data,
670
              v8::Local<v8::Context> context,
671
              Flags flags = Flags(),
672
              uint64_t thread_id = kNoThreadId);
673
  ~Environment();
674
675
  void Start(bool start_profiler_idle_notifier);
676
  v8::MaybeLocal<v8::Object> ProcessCliArgs(
677
      const std::vector<std::string>& args,
678
      const std::vector<std::string>& exec_args);
679
  inline const std::vector<std::string>& exec_argv();
680
681
  typedef void (*HandleCleanupCb)(Environment* env,
682
                                  uv_handle_t* handle,
683
                                  void* arg);
684
  struct HandleCleanup {
685
    uv_handle_t* handle_;
686
    HandleCleanupCb cb_;
687
    void* arg_;
688
  };
689
690
  void RegisterHandleCleanups();
691
  void CleanupHandles();
692
  void Exit(int code);
693
694
  // Register clean-up cb to be called on environment destruction.
695
  inline void RegisterHandleCleanup(uv_handle_t* handle,
696
                                    HandleCleanupCb cb,
697
                                    void* arg);
698
699
  template <typename T, typename OnCloseCallback>
700
  inline void CloseHandle(T* handle, OnCloseCallback callback);
701
702
  inline void AssignToContext(v8::Local<v8::Context> context,
703
                              const ContextInfo& info);
704
705
  void StartProfilerIdleNotifier();
706
  void StopProfilerIdleNotifier();
707
  inline bool profiler_idle_notifier_started() const;
708
709
  inline v8::Isolate* isolate() const;
710
  inline uv_loop_t* event_loop() const;
711
  inline void TryLoadAddon(
712
      const char* filename,
713
      int flags,
714
      const std::function<bool(binding::DLib*)>& was_loaded);
715
716
  static inline Environment* from_timer_handle(uv_timer_t* handle);
717
  inline uv_timer_t* timer_handle();
718
719
  static inline Environment* from_immediate_check_handle(uv_check_t* handle);
720
  inline uv_check_t* immediate_check_handle();
721
  inline uv_idle_t* immediate_idle_handle();
722
723
  inline void IncreaseWaitingRequestCounter();
724
  inline void DecreaseWaitingRequestCounter();
725
726
  inline AsyncHooks* async_hooks();
727
  inline ImmediateInfo* immediate_info();
728
  inline TickInfo* tick_info();
729
  inline uint64_t timer_base() const;
730
731
  inline IsolateData* isolate_data() const;
732
733
  // Utilites that allocate memory using the Isolate's ArrayBuffer::Allocator.
734
  // In particular, using AllocateManaged() will provide a RAII-style object
735
  // with easy conversion to `Buffer` and `ArrayBuffer` objects.
736
  inline AllocatedBuffer AllocateManaged(size_t size, bool checked = true);
737
  inline char* Allocate(size_t size);
738
  inline char* AllocateUnchecked(size_t size);
739
  char* Reallocate(char* data, size_t old_size, size_t size);
740
  inline void Free(char* data, size_t size);
741
742
  inline bool printed_error() const;
743
  inline void set_printed_error(bool value);
744
745
  void PrintSyncTrace() const;
746
  inline void set_trace_sync_io(bool value);
747
748
  // This stores whether the --abort-on-uncaught-exception flag was passed
749
  // to Node.
750
  inline bool abort_on_uncaught_exception() const;
751
  inline void set_abort_on_uncaught_exception(bool value);
752
  // This is a pseudo-boolean that keeps track of whether an uncaught exception
753
  // should abort the process or not if --abort-on-uncaught-exception was
754
  // passed to Node. If the flag was not passed, it is ignored.
755
  inline AliasedBuffer<uint32_t, v8::Uint32Array>&
756
  should_abort_on_uncaught_toggle();
757
758
  inline AliasedBuffer<int32_t, v8::Int32Array>& stream_base_state();
759
760
  // The necessary API for async_hooks.
761
  inline double new_async_id();
762
  inline double execution_async_id();
763
  inline double trigger_async_id();
764
  inline double get_default_trigger_async_id();
765
766
  // List of id's that have been destroyed and need the destroy() cb called.
767
  inline std::vector<double>* destroy_async_id_list();
768
769
  std::set<std::string> native_modules_with_cache;
770
  std::set<std::string> native_modules_without_cache;
771
772
  std::unordered_multimap<int, loader::ModuleWrap*> hash_to_module_map;
773
  std::unordered_map<uint32_t, loader::ModuleWrap*> id_to_module_map;
774
  std::unordered_map<uint32_t, contextify::ContextifyScript*>
775
      id_to_script_map;
776
  std::unordered_set<CompileFnEntry*> compile_fn_entries;
777
  std::unordered_map<uint32_t, Persistent<v8::Function>> id_to_function_map;
778
779
  inline uint32_t get_next_module_id();
780
  inline uint32_t get_next_script_id();
781
  inline uint32_t get_next_function_id();
782
783
  std::unordered_map<std::string, const loader::PackageConfig>
784
      package_json_cache;
785
786
  inline double* heap_statistics_buffer() const;
787
  inline void set_heap_statistics_buffer(double* pointer);
788
789
  inline double* heap_space_statistics_buffer() const;
790
  inline void set_heap_space_statistics_buffer(double* pointer);
791
792
  inline char* http_parser_buffer() const;
793
  inline void set_http_parser_buffer(char* buffer);
794
  inline bool http_parser_buffer_in_use() const;
795
  inline void set_http_parser_buffer_in_use(bool in_use);
796
797
  inline http2::Http2State* http2_state() const;
798
  inline void set_http2_state(std::unique_ptr<http2::Http2State> state);
799
800
  inline bool debug_enabled(DebugCategory category) const;
801
  inline void set_debug_enabled(DebugCategory category, bool enabled);
802
  void set_debug_categories(const std::string& cats, bool enabled);
803
804
  inline AliasedBuffer<double, v8::Float64Array>* fs_stats_field_array();
805
  inline AliasedBuffer<uint64_t, v8::BigUint64Array>*
806
      fs_stats_field_bigint_array();
807
808
  inline std::vector<std::unique_ptr<fs::FileHandleReadWrap>>&
809
      file_handle_read_wrap_freelist();
810
811
  inline performance::performance_state* performance_state();
812
  inline std::unordered_map<std::string, uint64_t>* performance_marks();
813
814
  void CollectUVExceptionInfo(v8::Local<v8::Value> context,
815
                              int errorno,
816
                              const char* syscall = nullptr,
817
                              const char* message = nullptr,
818
                              const char* path = nullptr,
819
                              const char* dest = nullptr);
820
821
  // If this flag is set, calls into JS (if they would be observable
822
  // from userland) must be avoided.  This flag does not indicate whether
823
  // calling into JS is allowed from a VM perspective at this point.
824
  inline bool can_call_into_js() const;
825
  inline void set_can_call_into_js(bool can_call_into_js);
826
827
  inline bool has_run_bootstrapping_code() const;
828
  inline void set_has_run_bootstrapping_code(bool has_run_bootstrapping_code);
829
830
  static uint64_t AllocateThreadId();
831
  static constexpr uint64_t kNoThreadId = -1;
832
833
  inline bool is_main_thread() const;
834
  inline bool owns_process_state() const;
835
  inline bool owns_inspector() const;
836
  inline uint64_t thread_id() const;
837
  inline worker::Worker* worker_context() const;
838
  inline void set_worker_context(worker::Worker* context);
839
  inline void add_sub_worker_context(worker::Worker* context);
840
  inline void remove_sub_worker_context(worker::Worker* context);
841
  void stop_sub_worker_contexts();
842
  inline bool is_stopping_worker() const;
843
844
  inline void ThrowError(const char* errmsg);
845
  inline void ThrowTypeError(const char* errmsg);
846
  inline void ThrowRangeError(const char* errmsg);
847
  inline void ThrowErrnoException(int errorno,
848
                                  const char* syscall = nullptr,
849
                                  const char* message = nullptr,
850
                                  const char* path = nullptr);
851
  inline void ThrowUVException(int errorno,
852
                               const char* syscall = nullptr,
853
                               const char* message = nullptr,
854
                               const char* path = nullptr,
855
                               const char* dest = nullptr);
856
857
  inline v8::Local<v8::FunctionTemplate>
858
      NewFunctionTemplate(v8::FunctionCallback callback,
859
                          v8::Local<v8::Signature> signature =
860
                              v8::Local<v8::Signature>(),
861
                          v8::ConstructorBehavior behavior =
862
                              v8::ConstructorBehavior::kAllow,
863
                          v8::SideEffectType side_effect =
864
                              v8::SideEffectType::kHasSideEffect);
865
866
  // Convenience methods for NewFunctionTemplate().
867
  inline void SetMethod(v8::Local<v8::Object> that,
868
                        const char* name,
869
                        v8::FunctionCallback callback);
870
871
  inline void SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
872
                             const char* name,
873
                             v8::FunctionCallback callback);
874
  inline void SetTemplateMethod(v8::Local<v8::FunctionTemplate> that,
875
                                const char* name,
876
                                v8::FunctionCallback callback);
877
878
  // Safe variants denote the function has no side effects.
879
  inline void SetMethodNoSideEffect(v8::Local<v8::Object> that,
880
                                    const char* name,
881
                                    v8::FunctionCallback callback);
882
  inline void SetProtoMethodNoSideEffect(v8::Local<v8::FunctionTemplate> that,
883
                                         const char* name,
884
                                         v8::FunctionCallback callback);
885
  inline void SetTemplateMethodNoSideEffect(
886
      v8::Local<v8::FunctionTemplate> that,
887
      const char* name,
888
      v8::FunctionCallback callback);
889
890
  void BeforeExit(void (*cb)(void* arg), void* arg);
891
  void RunBeforeExitCallbacks();
892
  void AtExit(void (*cb)(void* arg), void* arg);
893
  void RunAtExitCallbacks();
894
895
  // Strings and private symbols are shared across shared contexts
896
  // The getters simply proxy to the per-isolate primitive.
897
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
898
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
899
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
900
#define V(TypeName, PropertyName)                                             \
901
  inline v8::Local<TypeName> PropertyName() const;
902
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
903
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
904
  PER_ISOLATE_STRING_PROPERTIES(VS)
905
#undef V
906
#undef VS
907
#undef VY
908
#undef VP
909
910
#define V(PropertyName, TypeName)                                             \
911
  inline v8::Local<TypeName> PropertyName() const;                            \
912
  inline void set_ ## PropertyName(v8::Local<TypeName> value);
913
  ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V)
914
#undef V
915
916
#if HAVE_INSPECTOR
917
172936
  inline inspector::Agent* inspector_agent() const {
918
172936
    return inspector_agent_.get();
919
  }
920
921
  inline bool is_in_inspector_console_call() const;
922
  inline void set_is_in_inspector_console_call(bool value);
923
#endif
924
925
  typedef ListHead<HandleWrap, &HandleWrap::handle_wrap_queue_> HandleWrapQueue;
926
  typedef ListHead<ReqWrapBase, &ReqWrapBase::req_wrap_queue_> ReqWrapQueue;
927
928
38729
  inline HandleWrapQueue* handle_wrap_queue() { return &handle_wrap_queue_; }
929
211220
  inline ReqWrapQueue* req_wrap_queue() { return &req_wrap_queue_; }
930
931
  void AddPromiseHook(promise_hook_func fn, void* arg);
932
  bool RemovePromiseHook(promise_hook_func fn, void* arg);
933
1
  inline bool EmitProcessEnvWarning() {
934
1
    bool current_value = emit_env_nonstring_warning_;
935
1
    emit_env_nonstring_warning_ = false;
936
1
    return current_value;
937
  }
938
939
1
  inline bool EmitErrNameWarning() {
940
1
    bool current_value = emit_err_name_warning_;
941
1
    emit_err_name_warning_ = false;
942
1
    return current_value;
943
  }
944
945
  typedef void (*native_immediate_callback)(Environment* env, void* data);
946
  // cb will be called as cb(env, data) on the next event loop iteration.
947
  // obj will be kept alive between now and after the callback has run.
948
  inline void SetImmediate(native_immediate_callback cb,
949
                           void* data,
950
                           v8::Local<v8::Object> obj = v8::Local<v8::Object>());
951
  inline void SetUnrefImmediate(native_immediate_callback cb,
952
                                void* data,
953
                                v8::Local<v8::Object> obj =
954
                                    v8::Local<v8::Object>());
955
  // This needs to be available for the JS-land setImmediate().
956
  void ToggleImmediateRef(bool ref);
957
958
8098
  class TrackingTraceStateObserver :
959
      public v8::TracingController::TraceStateObserver {
960
   public:
961
4417
    explicit TrackingTraceStateObserver(Environment* env) : env_(env) {}
962
963
102
    void OnTraceEnabled() override {
964
102
      UpdateTraceCategoryState();
965
102
    }
966
967
32
    void OnTraceDisabled() override {
968
32
      UpdateTraceCategoryState();
969
32
    }
970
971
   private:
972
    void UpdateTraceCategoryState();
973
974
    Environment* env_;
975
  };
976
977
  class ShouldNotAbortOnUncaughtScope {
978
   public:
979
    explicit inline ShouldNotAbortOnUncaughtScope(Environment* env);
980
    inline void Close();
981
    inline ~ShouldNotAbortOnUncaughtScope();
982
983
   private:
984
    Environment* env_;
985
  };
986
987
  inline bool inside_should_not_abort_on_uncaught_scope() const;
988
989
  static inline Environment* ForAsyncHooks(AsyncHooks* hooks);
990
991
  v8::Local<v8::Value> GetNow();
992
  void ScheduleTimer(int64_t duration);
993
  void ToggleTimerRef(bool ref);
994
995
  inline void AddCleanupHook(void (*fn)(void*), void* arg);
996
  inline void RemoveCleanupHook(void (*fn)(void*), void* arg);
997
  void RunCleanup();
998
999
  static void BuildEmbedderGraph(v8::Isolate* isolate,
1000
                                 v8::EmbedderGraph* graph,
1001
                                 void* data);
1002
1003
  inline std::shared_ptr<EnvironmentOptions> options();
1004
  inline std::shared_ptr<HostPort> inspector_host_port();
1005
1006
  enum class ExecutionMode {
1007
    kDefault,
1008
    kInspect,              // node inspect
1009
    kDebug,                // node debug
1010
    kPrintHelp,            // node --help
1011
    kPrintBashCompletion,  // node --completion-bash
1012
    kProfProcess,          // node --prof-process
1013
    kEvalString,           // node --eval without --interactive
1014
    kCheckSyntax,          // node --check (incompatible with --eval)
1015
    kRepl,
1016
    kEvalStdin,
1017
    kRunMainModule
1018
  };
1019
1020
12396
  inline ExecutionMode execution_mode() { return execution_mode_; }
1021
1022
353
  inline void set_execution_mode(ExecutionMode mode) { execution_mode_ = mode; }
1023
1024
 private:
1025
  inline void CreateImmediate(native_immediate_callback cb,
1026
                              void* data,
1027
                              v8::Local<v8::Object> obj,
1028
                              bool ref);
1029
1030
  inline void ThrowError(v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
1031
                         const char* errmsg);
1032
1033
  ExecutionMode execution_mode_ = ExecutionMode::kDefault;
1034
  std::list<binding::DLib> loaded_addons_;
1035
  v8::Isolate* const isolate_;
1036
  IsolateData* const isolate_data_;
1037
  uv_timer_t timer_handle_;
1038
  uv_check_t immediate_check_handle_;
1039
  uv_idle_t immediate_idle_handle_;
1040
  uv_prepare_t idle_prepare_handle_;
1041
  uv_check_t idle_check_handle_;
1042
  bool profiler_idle_notifier_started_ = false;
1043
1044
  AsyncHooks async_hooks_;
1045
  ImmediateInfo immediate_info_;
1046
  TickInfo tick_info_;
1047
  const uint64_t timer_base_;
1048
  bool printed_error_ = false;
1049
  bool abort_on_uncaught_exception_ = false;
1050
  bool emit_env_nonstring_warning_ = true;
1051
  bool emit_err_name_warning_ = true;
1052
  size_t makecallback_cntr_ = 0;
1053
  std::vector<double> destroy_async_id_list_;
1054
1055
  std::shared_ptr<EnvironmentOptions> options_;
1056
  // options_ contains debug options parsed from CLI arguments,
1057
  // while inspector_host_port_ stores the actual inspector host
1058
  // and port being used. For example the port is -1 by default
1059
  // and can be specified as 0 (meaning any port allocated when the
1060
  // server starts listening), but when the inspector server starts
1061
  // the inspector_host_port_->port() will be the actual port being
1062
  // used.
1063
  std::shared_ptr<HostPort> inspector_host_port_;
1064
  std::vector<std::string> exec_argv_;
1065
1066
  uint32_t module_id_counter_ = 0;
1067
  uint32_t script_id_counter_ = 0;
1068
  uint32_t function_id_counter_ = 0;
1069
1070
  AliasedBuffer<uint32_t, v8::Uint32Array> should_abort_on_uncaught_toggle_;
1071
  int should_not_abort_scope_counter_ = 0;
1072
1073
  std::unique_ptr<TrackingTraceStateObserver> trace_state_observer_;
1074
1075
  AliasedBuffer<int32_t, v8::Int32Array> stream_base_state_;
1076
1077
  std::unique_ptr<performance::performance_state> performance_state_;
1078
  std::unordered_map<std::string, uint64_t> performance_marks_;
1079
1080
  bool has_run_bootstrapping_code_ = false;
1081
  bool can_call_into_js_ = true;
1082
  Flags flags_;
1083
  uint64_t thread_id_;
1084
  std::unordered_set<worker::Worker*> sub_worker_contexts_;
1085
1086
  static void* const kNodeContextTagPtr;
1087
  static int const kNodeContextTag;
1088
1089
#if HAVE_INSPECTOR
1090
  std::unique_ptr<inspector::Agent> inspector_agent_;
1091
  bool is_in_inspector_console_call_ = false;
1092
#endif
1093
1094
  // handle_wrap_queue_ and req_wrap_queue_ needs to be at a fixed offset from
1095
  // the start of the class because it is used by
1096
  // src/node_postmortem_metadata.cc to calculate offsets and generate debug
1097
  // symbols for Environment, which assumes that the position of members in
1098
  // memory are predictable. For more information please refer to
1099
  // `doc/guides/node-postmortem-support.md`
1100
  friend int GenDebugSymbols();
1101
  HandleWrapQueue handle_wrap_queue_;
1102
  ReqWrapQueue req_wrap_queue_;
1103
  std::list<HandleCleanup> handle_cleanup_queue_;
1104
  int handle_cleanup_waiting_ = 0;
1105
  int request_waiting_ = 0;
1106
1107
  double* heap_statistics_buffer_ = nullptr;
1108
  double* heap_space_statistics_buffer_ = nullptr;
1109
1110
  char* http_parser_buffer_ = nullptr;
1111
  bool http_parser_buffer_in_use_ = false;
1112
  std::unique_ptr<http2::Http2State> http2_state_;
1113
1114
  bool debug_enabled_[static_cast<int>(DebugCategory::CATEGORY_COUNT)] = {0};
1115
1116
  AliasedBuffer<double, v8::Float64Array> fs_stats_field_array_;
1117
  AliasedBuffer<uint64_t, v8::BigUint64Array> fs_stats_field_bigint_array_;
1118
1119
  std::vector<std::unique_ptr<fs::FileHandleReadWrap>>
1120
      file_handle_read_wrap_freelist_;
1121
1122
  worker::Worker* worker_context_ = nullptr;
1123
1124
  static void RunTimers(uv_timer_t* handle);
1125
1126
  struct ExitCallback {
1127
    void (*cb_)(void* arg);
1128
    void* arg_;
1129
  };
1130
  std::list<ExitCallback> before_exit_functions_;
1131
1132
  std::list<ExitCallback> at_exit_functions_;
1133
1134
  struct PromiseHookCallback {
1135
    promise_hook_func cb_;
1136
    void* arg_;
1137
    size_t enable_count_;
1138
  };
1139
  std::vector<PromiseHookCallback> promise_hooks_;
1140
1141
315478
  struct NativeImmediateCallback {
1142
    native_immediate_callback cb_;
1143
    void* data_;
1144
    v8::Global<v8::Object> keep_alive_;
1145
    bool refed_;
1146
  };
1147
  std::vector<NativeImmediateCallback> native_immediate_callbacks_;
1148
  void RunAndClearNativeImmediates();
1149
  static void CheckImmediate(uv_check_t* handle);
1150
1151
  struct CleanupHookCallback {
1152
    void (*fn_)(void*);
1153
    void* arg_;
1154
1155
    // We keep track of the insertion order for these objects, so that we can
1156
    // call the callbacks in reverse order when we are cleaning up.
1157
    uint64_t insertion_order_counter_;
1158
1159
    // Only hashes `arg_`, since that is usually enough to identify the hook.
1160
    struct Hash {
1161
      inline size_t operator()(const CleanupHookCallback& cb) const;
1162
    };
1163
1164
    // Compares by `fn_` and `arg_` being equal.
1165
    struct Equal {
1166
      inline bool operator()(const CleanupHookCallback& a,
1167
                             const CleanupHookCallback& b) const;
1168
    };
1169
1170
    inline BaseObject* GetBaseObject() const;
1171
  };
1172
1173
  // Use an unordered_set, so that we have efficient insertion and removal.
1174
  std::unordered_set<CleanupHookCallback,
1175
                     CleanupHookCallback::Hash,
1176
                     CleanupHookCallback::Equal> cleanup_hooks_;
1177
  uint64_t cleanup_hook_counter_ = 0;
1178
  bool started_cleanup_ = false;
1179
1180
  static void EnvPromiseHook(v8::PromiseHookType type,
1181
                             v8::Local<v8::Promise> promise,
1182
                             v8::Local<v8::Value> parent);
1183
1184
  template <typename T>
1185
  void ForEachBaseObject(T&& iterator);
1186
1187
#define V(PropertyName, TypeName) Persistent<TypeName> PropertyName ## _;
1188
  ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V)
1189
#undef V
1190
1191
  DISALLOW_COPY_AND_ASSIGN(Environment);
1192
};
1193
1194
}  // namespace node
1195
1196
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1197
1198
#endif  // SRC_ENV_H_