GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env-inl.h Lines: 646 662 97.6 %
Date: 2021-11-06 03:13:44 Branches: 115 146 78.8 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#ifndef SRC_ENV_INL_H_
23
#define SRC_ENV_INL_H_
24
25
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
26
27
#include "aliased_buffer.h"
28
#include "allocated_buffer-inl.h"
29
#include "callback_queue-inl.h"
30
#include "env.h"
31
#include "node.h"
32
#include "util-inl.h"
33
#include "uv.h"
34
#include "v8.h"
35
#include "node_perf_common.h"
36
#include "node_context_data.h"
37
38
#include <cstddef>
39
#include <cstdint>
40
41
#include <utility>
42
43
namespace node {
44
45
inline v8::Isolate* IsolateData::isolate() const {
46
  return isolate_;
47
}
48
49
921733
inline uv_loop_t* IsolateData::event_loop() const {
50
921733
  return event_loop_;
51
}
52
53
103818
inline NodeArrayBufferAllocator* IsolateData::node_allocator() const {
54
103818
  return node_allocator_;
55
}
56
57
55930
inline MultiIsolatePlatform* IsolateData::platform() const {
58
55930
  return platform_;
59
}
60
61
578
inline void IsolateData::set_worker_context(worker::Worker* context) {
62
578
  CHECK_NULL(worker_context_);  // Should be set only once.
63
578
  worker_context_ = context;
64
578
}
65
66
13915
inline worker::Worker* IsolateData::worker_context() const {
67
13915
  return worker_context_;
68
}
69
70
203833
inline v8::Local<v8::String> IsolateData::async_wrap_provider(int index) const {
71
203833
  return async_wrap_providers_[index].Get(isolate_);
72
}
73
74
3015384
inline AliasedUint32Array& AsyncHooks::fields() {
75
3015384
  return fields_;
76
}
77
78
1693808
inline AliasedFloat64Array& AsyncHooks::async_id_fields() {
79
1693808
  return async_id_fields_;
80
}
81
82
622
inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
83
622
  return async_ids_stack_;
84
}
85
86
800856
v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() {
87
800856
  if (UNLIKELY(js_execution_async_resources_.IsEmpty())) {
88
622
    js_execution_async_resources_.Reset(
89
1244
        env()->isolate(), v8::Array::New(env()->isolate()));
90
  }
91
800856
  return PersistentToLocal::Strong(js_execution_async_resources_);
92
}
93
94
2402
v8::Local<v8::Object> AsyncHooks::native_execution_async_resource(size_t i) {
95
2402
  if (i >= native_execution_async_resources_.size()) return {};
96
2402
  return PersistentToLocal::Strong(native_execution_async_resources_[i]);
97
}
98
99
16814
inline void AsyncHooks::SetJSPromiseHooks(v8::Local<v8::Function> init,
100
                                          v8::Local<v8::Function> before,
101
                                          v8::Local<v8::Function> after,
102
                                          v8::Local<v8::Function> resolve) {
103
16814
  js_promise_hooks_[0].Reset(env()->isolate(), init);
104
16814
  js_promise_hooks_[1].Reset(env()->isolate(), before);
105
16814
  js_promise_hooks_[2].Reset(env()->isolate(), after);
106
16814
  js_promise_hooks_[3].Reset(env()->isolate(), resolve);
107
33952
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
108
17138
    if (it->IsEmpty()) {
109
      it = contexts_.erase(it);
110
      it--;
111
      continue;
112
    }
113
34276
    PersistentToLocal::Weak(env()->isolate(), *it)
114
17138
        ->SetPromiseHooks(init, before, after, resolve);
115
  }
116
16814
}
117
118
203485
inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) {
119
203485
  return env()->isolate_data()->async_wrap_provider(idx);
120
}
121
122
1
inline void AsyncHooks::no_force_checks() {
123
1
  fields_[kCheck] -= 1;
124
1
}
125
126
1180025
inline Environment* AsyncHooks::env() {
127
1180025
  return Environment::ForAsyncHooks(this);
128
}
129
130
// Remember to keep this code aligned with pushAsyncContext() in JS.
131
775687
inline void AsyncHooks::push_async_context(double async_id,
132
                                           double trigger_async_id,
133
                                           v8::Local<v8::Object> resource) {
134
  // Since async_hooks is experimental, do only perform the check
135
  // when async_hooks is enabled.
136
775687
  if (fields_[kCheck] > 0) {
137
775684
    CHECK_GE(async_id, -1);
138
775684
    CHECK_GE(trigger_async_id, -1);
139
  }
140
141
775687
  uint32_t offset = fields_[kStackLength];
142
775687
  if (offset * 2 >= async_ids_stack_.Length())
143
4
    grow_async_ids_stack();
144
775687
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
145
775687
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
146
775687
  fields_[kStackLength] += 1;
147
775687
  async_id_fields_[kExecutionAsyncId] = async_id;
148
775687
  async_id_fields_[kTriggerAsyncId] = trigger_async_id;
149
150
#ifdef DEBUG
151
  for (uint32_t i = offset; i < native_execution_async_resources_.size(); i++)
152
    CHECK(native_execution_async_resources_[i].IsEmpty());
153
#endif
154
155
  // When this call comes from JS (as a way of increasing the stack size),
156
  // `resource` will be empty, because JS caches these values anyway, and
157
  // we should avoid creating strong global references that might keep
158
  // these JS resource objects alive longer than necessary.
159
775687
  if (!resource.IsEmpty()) {
160
775683
    native_execution_async_resources_.resize(offset + 1);
161
775683
    native_execution_async_resources_[offset].Reset(env()->isolate(), resource);
162
  }
163
775687
}
164
165
// Remember to keep this code aligned with popAsyncContext() in JS.
166
775298
inline bool AsyncHooks::pop_async_context(double async_id) {
167
  // In case of an exception then this may have already been reset, if the
168
  // stack was multiple MakeCallback()'s deep.
169
775298
  if (fields_[kStackLength] == 0) return false;
170
171
  // Ask for the async_id to be restored as a check that the stack
172
  // hasn't been corrupted.
173
  // Since async_hooks is experimental, do only perform the check
174
  // when async_hooks is enabled.
175

774260
  if (fields_[kCheck] > 0 && async_id_fields_[kExecutionAsyncId] != async_id) {
176
4
    fprintf(stderr,
177
            "Error: async hook stack has become corrupted ("
178
            "actual: %.f, expected: %.f)\n",
179
            async_id_fields_.GetValue(kExecutionAsyncId),
180
            async_id);
181
4
    DumpBacktrace(stderr);
182
4
    fflush(stderr);
183
4
    if (!env()->abort_on_uncaught_exception())
184
4
      exit(1);
185
    fprintf(stderr, "\n");
186
    fflush(stderr);
187
    ABORT_NO_BACKTRACE();
188
  }
189
190
774256
  uint32_t offset = fields_[kStackLength] - 1;
191
774256
  async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
192
774256
  async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
193
774256
  fields_[kStackLength] = offset;
194
195
1548512
  if (LIKELY(offset < native_execution_async_resources_.size() &&
196

1548512
             !native_execution_async_resources_[offset].IsEmpty())) {
197
#ifdef DEBUG
198
    for (uint32_t i = offset + 1;
199
         i < native_execution_async_resources_.size();
200
         i++) {
201
      CHECK(native_execution_async_resources_[i].IsEmpty());
202
    }
203
#endif
204
774256
    native_execution_async_resources_.resize(offset);
205
774256
    if (native_execution_async_resources_.size() <
206

993361
            native_execution_async_resources_.capacity() / 2 &&
207
219105
        native_execution_async_resources_.size() > 16) {
208
      native_execution_async_resources_.shrink_to_fit();
209
    }
210
  }
211
212
1548512
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
213
25978
    v8::HandleScope handle_scope(env()->isolate());
214
51956
    USE(js_execution_async_resources()->Set(
215
        env()->context(),
216
        env()->length_string(),
217
103912
        v8::Integer::NewFromUnsigned(env()->isolate(), offset)));
218
  }
219
220
774256
  return fields_[kStackLength] > 0;
221
}
222
223
1991
void AsyncHooks::clear_async_id_stack() {
224
1991
  v8::Isolate* isolate = env()->isolate();
225
1991
  v8::HandleScope handle_scope(isolate);
226
1991
  if (!js_execution_async_resources_.IsEmpty()) {
227
2738
    USE(PersistentToLocal::Strong(js_execution_async_resources_)->Set(
228
        env()->context(),
229
        env()->length_string(),
230
5476
        v8::Integer::NewFromUnsigned(isolate, 0)));
231
  }
232
1991
  native_execution_async_resources_.clear();
233
1991
  native_execution_async_resources_.shrink_to_fit();
234
235
1991
  async_id_fields_[kExecutionAsyncId] = 0;
236
1991
  async_id_fields_[kTriggerAsyncId] = 0;
237
1991
  fields_[kStackLength] = 0;
238
1991
}
239
240
6043
inline void AsyncHooks::AddContext(v8::Local<v8::Context> ctx) {
241
23776
  ctx->SetPromiseHooks(
242
6043
    js_promise_hooks_[0].IsEmpty() ?
243
6043
      v8::Local<v8::Function>() :
244
198
      PersistentToLocal::Strong(js_promise_hooks_[0]),
245
6043
    js_promise_hooks_[1].IsEmpty() ?
246
6043
      v8::Local<v8::Function>() :
247
198
      PersistentToLocal::Strong(js_promise_hooks_[1]),
248
6043
    js_promise_hooks_[2].IsEmpty() ?
249
6043
      v8::Local<v8::Function>() :
250
198
      PersistentToLocal::Strong(js_promise_hooks_[2]),
251
6043
    js_promise_hooks_[3].IsEmpty() ?
252
6043
      v8::Local<v8::Function>() :
253
      PersistentToLocal::Strong(js_promise_hooks_[3]));
254
255
6043
  size_t id = contexts_.size();
256
6043
  contexts_.resize(id + 1);
257
6043
  contexts_[id].Reset(env()->isolate(), ctx);
258
6043
  contexts_[id].SetWeak();
259
6043
}
260
261
513
inline void AsyncHooks::RemoveContext(v8::Local<v8::Context> ctx) {
262
513
  v8::Isolate* isolate = env()->isolate();
263
1026
  v8::HandleScope handle_scope(isolate);
264
5065
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
265
4552
    if (it->IsEmpty()) {
266
61
      it = contexts_.erase(it);
267
61
      it--;
268
61
      continue;
269
    }
270
    v8::Local<v8::Context> saved_context =
271
4491
      PersistentToLocal::Weak(isolate, *it);
272
4491
    if (saved_context == ctx) {
273
      it->Reset();
274
      contexts_.erase(it);
275
      break;
276
    }
277
  }
278
513
}
279
280
// The DefaultTriggerAsyncIdScope(AsyncWrap*) constructor is defined in
281
// async_wrap-inl.h to avoid a circular dependency.
282
283
258972
inline AsyncHooks::DefaultTriggerAsyncIdScope ::DefaultTriggerAsyncIdScope(
284
258972
    Environment* env, double default_trigger_async_id)
285
258972
    : async_hooks_(env->async_hooks()) {
286
258972
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
287
258972
    CHECK_GE(default_trigger_async_id, 0);
288
  }
289
290
258972
  old_default_trigger_async_id_ =
291
258972
    async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
292
258972
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
293
258972
    default_trigger_async_id;
294
258972
}
295
296
517942
inline AsyncHooks::DefaultTriggerAsyncIdScope ::~DefaultTriggerAsyncIdScope() {
297
258971
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
298
258971
    old_default_trigger_async_id_;
299
258971
}
300
301
1180025
Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) {
302
1180025
  return ContainerOf(&Environment::async_hooks_, hooks);
303
}
304
305
775327
inline size_t Environment::async_callback_scope_depth() const {
306
775327
  return async_callback_scope_depth_;
307
}
308
309
787167
inline void Environment::PushAsyncCallbackScope() {
310
787167
  async_callback_scope_depth_++;
311
787167
}
312
313
786653
inline void Environment::PopAsyncCallbackScope() {
314
786653
  async_callback_scope_depth_--;
315
786653
}
316
317
622
inline AliasedUint32Array& ImmediateInfo::fields() {
318
622
  return fields_;
319
}
320
321
176386
inline uint32_t ImmediateInfo::count() const {
322
176386
  return fields_[kCount];
323
}
324
325
265251
inline uint32_t ImmediateInfo::ref_count() const {
326
265251
  return fields_[kRefCount];
327
}
328
329
41639
inline bool ImmediateInfo::has_outstanding() const {
330
41639
  return fields_[kHasOutstanding] == 1;
331
}
332
333
33285
inline void ImmediateInfo::ref_count_inc(uint32_t increment) {
334
33285
  fields_[kRefCount] += increment;
335
33285
}
336
337
191267
inline void ImmediateInfo::ref_count_dec(uint32_t decrement) {
338
191267
  fields_[kRefCount] -= decrement;
339
191267
}
340
341
622
inline AliasedUint8Array& TickInfo::fields() {
342
622
  return fields_;
343
}
344
345
1383984
inline bool TickInfo::has_tick_scheduled() const {
346
1383984
  return fields_[kHasTickScheduled] == 1;
347
}
348
349
509054
inline bool TickInfo::has_rejection_to_warn() const {
350
509054
  return fields_[kHasRejectionToWarn] == 1;
351
}
352
353
6043
inline void Environment::AssignToContext(v8::Local<v8::Context> context,
354
                                         const ContextInfo& info) {
355
6043
  context->SetAlignedPointerInEmbedderData(
356
      ContextEmbedderIndex::kEnvironment, this);
357
  // Used by Environment::GetCurrent to know that we are on a node context.
358
6043
  context->SetAlignedPointerInEmbedderData(
359
    ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr);
360
  // Used to retrieve bindings
361
12086
  context->SetAlignedPointerInEmbedderData(
362
6043
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
363
364
#if HAVE_INSPECTOR
365
6043
  inspector_agent()->ContextCreated(context, info);
366
#endif  // HAVE_INSPECTOR
367
368
6043
  this->async_hooks()->AddContext(context);
369
6043
}
370
371
828186
inline Environment* Environment::GetCurrent(v8::Isolate* isolate) {
372
828186
  if (UNLIKELY(!isolate->InContext())) return nullptr;
373
1654348
  v8::HandleScope handle_scope(isolate);
374
827174
  return GetCurrent(isolate->GetCurrentContext());
375
}
376
377
5762669
inline Environment* Environment::GetCurrent(v8::Local<v8::Context> context) {
378
5762669
  if (UNLIKELY(context.IsEmpty())) {
379
1
    return nullptr;
380
  }
381
5762668
  if (UNLIKELY(context->GetNumberOfEmbedderDataFields() <=
382
5762668
               ContextEmbedderIndex::kContextTag)) {
383
11
    return nullptr;
384
  }
385
11525314
  if (UNLIKELY(context->GetAlignedPointerFromEmbedderData(
386
                   ContextEmbedderIndex::kContextTag) !=
387
5762657
               Environment::kNodeContextTagPtr)) {
388
    return nullptr;
389
  }
390
  return static_cast<Environment*>(
391
5762657
      context->GetAlignedPointerFromEmbedderData(
392
5762657
          ContextEmbedderIndex::kEnvironment));
393
}
394
395
3552639
inline Environment* Environment::GetCurrent(
396
    const v8::FunctionCallbackInfo<v8::Value>& info) {
397
3552639
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
398
}
399
400
template <typename T>
401
1988088
inline Environment* Environment::GetCurrent(
402
    const v8::PropertyCallbackInfo<T>& info) {
403
1988088
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
404
}
405
406
template <typename T, typename U>
407
inline T* Environment::GetBindingData(const v8::PropertyCallbackInfo<U>& info) {
408
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
409
}
410
411
template <typename T>
412
709955
inline T* Environment::GetBindingData(
413
    const v8::FunctionCallbackInfo<v8::Value>& info) {
414
709955
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
415
}
416
417
template <typename T>
418
709957
inline T* Environment::GetBindingData(v8::Local<v8::Context> context) {
419
  BindingDataStore* map = static_cast<BindingDataStore*>(
420
709957
      context->GetAlignedPointerFromEmbedderData(
421
          ContextEmbedderIndex::kBindingListIndex));
422
  DCHECK_NOT_NULL(map);
423
709957
  auto it = map->find(T::type_name);
424
709957
  if (UNLIKELY(it == map->end())) return nullptr;
425
709957
  T* result = static_cast<T*>(it->second.get());
426
  DCHECK_NOT_NULL(result);
427
  DCHECK_EQ(result->env(), GetCurrent(context));
428
709957
  return result;
429
}
430
431
template <typename T>
432
17340
inline T* Environment::AddBindingData(
433
    v8::Local<v8::Context> context,
434
    v8::Local<v8::Object> target) {
435
  DCHECK_EQ(GetCurrent(context), this);
436
  // This won't compile if T is not a BaseObject subclass.
437
34680
  BaseObjectPtr<T> item = MakeDetachedBaseObject<T>(this, target);
438
  BindingDataStore* map = static_cast<BindingDataStore*>(
439
17340
      context->GetAlignedPointerFromEmbedderData(
440
          ContextEmbedderIndex::kBindingListIndex));
441
  DCHECK_NOT_NULL(map);
442
17340
  auto result = map->emplace(T::type_name, item);
443
17340
  CHECK(result.second);
444
  DCHECK_EQ(GetBindingData<T>(context), item.get());
445
17340
  return item.get();
446
}
447
448
24198616
inline v8::Isolate* Environment::isolate() const {
449
24198616
  return isolate_;
450
}
451
452
5909
inline Environment* Environment::from_timer_handle(uv_timer_t* handle) {
453
5909
  return ContainerOf(&Environment::timer_handle_, handle);
454
}
455
456
25601
inline uv_timer_t* Environment::timer_handle() {
457
25601
  return &timer_handle_;
458
}
459
460
176386
inline Environment* Environment::from_immediate_check_handle(
461
    uv_check_t* handle) {
462
176386
  return ContainerOf(&Environment::immediate_check_handle_, handle);
463
}
464
465
21568
inline uv_check_t* Environment::immediate_check_handle() {
466
21568
  return &immediate_check_handle_;
467
}
468
469
219652
inline uv_idle_t* Environment::immediate_idle_handle() {
470
219652
  return &immediate_idle_handle_;
471
}
472
473
32352
inline void Environment::RegisterHandleCleanup(uv_handle_t* handle,
474
                                               HandleCleanupCb cb,
475
                                               void* arg) {
476
32352
  handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg});
477
32352
}
478
479
template <typename T, typename OnCloseCallback>
480
33782
inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) {
481
33630
  handle_cleanup_waiting_++;
482
  static_assert(sizeof(T) >= sizeof(uv_handle_t), "T is a libuv handle");
483
  static_assert(offsetof(T, data) == offsetof(uv_handle_t, data),
484
                "T is a libuv handle");
485
  static_assert(offsetof(T, close_cb) == offsetof(uv_handle_t, close_cb),
486
                "T is a libuv handle");
487
  struct CloseData {
488
    Environment* env;
489
    OnCloseCallback callback;
490
    void* original_data;
491
  };
492
33706
  handle->data = new CloseData { this, callback, handle->data };
493
34010
  uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
494
67260
    std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) };
495
33706
    data->env->handle_cleanup_waiting_--;
496
33706
    handle->data = data->original_data;
497
33706
    data->callback(reinterpret_cast<T*>(handle));
498
  });
499
33706
}
500
501
89045
void Environment::IncreaseWaitingRequestCounter() {
502
89045
  request_waiting_++;
503
89045
}
504
505
89030
void Environment::DecreaseWaitingRequestCounter() {
506
89030
  request_waiting_--;
507
89030
  CHECK_GE(request_waiting_, 0);
508
89030
}
509
510
916304
inline uv_loop_t* Environment::event_loop() const {
511
916304
  return isolate_data()->event_loop();
512
}
513
514
158
inline void Environment::TryLoadAddon(
515
    const char* filename,
516
    int flags,
517
    const std::function<bool(binding::DLib*)>& was_loaded) {
518
158
  loaded_addons_.emplace_back(filename, flags);
519
158
  if (!was_loaded(&loaded_addons_.back())) {
520
8
    loaded_addons_.pop_back();
521
  }
522
158
}
523
524
#if HAVE_INSPECTOR
525
44296
inline bool Environment::is_in_inspector_console_call() const {
526
44296
  return is_in_inspector_console_call_;
527
}
528
529
88590
inline void Environment::set_is_in_inspector_console_call(bool value) {
530
88590
  is_in_inspector_console_call_ = value;
531
88590
}
532
#endif
533
534
5163824
inline AsyncHooks* Environment::async_hooks() {
535
5163824
  return &async_hooks_;
536
}
537
538
708450
inline ImmediateInfo* Environment::immediate_info() {
539
708450
  return &immediate_info_;
540
}
541
542
692633
inline TickInfo* Environment::tick_info() {
543
692633
  return &tick_info_;
544
}
545
546
54177
inline uint64_t Environment::timer_base() const {
547
54177
  return timer_base_;
548
}
549
550
1012497
inline std::shared_ptr<KVStore> Environment::env_vars() {
551
1012497
  return env_vars_;
552
}
553
554
5991
inline void Environment::set_env_vars(std::shared_ptr<KVStore> env_vars) {
555
5991
  env_vars_ = env_vars;
556
5991
}
557
558
18
inline bool Environment::printed_error() const {
559
18
  return printed_error_;
560
}
561
562
18
inline void Environment::set_printed_error(bool value) {
563
18
  printed_error_ = value;
564
18
}
565
566
9800
inline void Environment::set_trace_sync_io(bool value) {
567
9800
  trace_sync_io_ = value;
568
9800
}
569
570
89
inline bool Environment::abort_on_uncaught_exception() const {
571
89
  return options_->abort_on_uncaught_exception;
572
}
573
574
inline void Environment::set_force_context_aware(bool value) {
575
  options_->force_context_aware = value;
576
}
577
578
41
inline bool Environment::force_context_aware() const {
579
41
  return options_->force_context_aware;
580
}
581
582
570
inline void Environment::set_abort_on_uncaught_exception(bool value) {
583
570
  options_->abort_on_uncaught_exception = value;
584
570
}
585
586
652
inline AliasedUint32Array& Environment::should_abort_on_uncaught_toggle() {
587
652
  return should_abort_on_uncaught_toggle_;
588
}
589
590
303266
inline AliasedInt32Array& Environment::stream_base_state() {
591
303266
  return stream_base_state_;
592
}
593
594
45278
inline uint32_t Environment::get_next_module_id() {
595
45278
  return module_id_counter_++;
596
}
597
3491
inline uint32_t Environment::get_next_script_id() {
598
3491
  return script_id_counter_++;
599
}
600
31865
inline uint32_t Environment::get_next_function_id() {
601
31865
  return function_id_counter_++;
602
}
603
604
93664
ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope(
605
93664
    Environment* env)
606
93664
    : env_(env) {
607
93664
  env_->PushShouldNotAbortOnUncaughtScope();
608
93664
}
609
610
187324
ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() {
611
93662
  Close();
612
93662
}
613
614
93854
void ShouldNotAbortOnUncaughtScope::Close() {
615
93854
  if (env_ != nullptr) {
616
93662
    env_->PopShouldNotAbortOnUncaughtScope();
617
93662
    env_ = nullptr;
618
  }
619
93854
}
620
621
93664
inline void Environment::PushShouldNotAbortOnUncaughtScope() {
622
93664
  should_not_abort_scope_counter_++;
623
93664
}
624
625
93662
inline void Environment::PopShouldNotAbortOnUncaughtScope() {
626
93662
  should_not_abort_scope_counter_--;
627
93662
}
628
629
1
inline bool Environment::inside_should_not_abort_on_uncaught_scope() const {
630
1
  return should_not_abort_scope_counter_ > 0;
631
}
632
633
404775
inline std::vector<double>* Environment::destroy_async_id_list() {
634
404775
  return &destroy_async_id_list_;
635
}
636
637
204038
inline double Environment::new_async_id() {
638
204038
  async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
639
204038
  return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
640
}
641
642
236016
inline double Environment::execution_async_id() {
643
236016
  return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId];
644
}
645
646
68144
inline double Environment::trigger_async_id() {
647
68144
  return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId];
648
}
649
650
204035
inline double Environment::get_default_trigger_async_id() {
651
  double default_trigger_async_id =
652
204035
    async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
653
  // If defaultTriggerAsyncId isn't set, use the executionAsyncId
654
204035
  if (default_trigger_async_id < 0)
655
167847
    default_trigger_async_id = execution_async_id();
656
204035
  return default_trigger_async_id;
657
}
658
659
60619
inline std::shared_ptr<EnvironmentOptions> Environment::options() {
660
60619
  return options_;
661
}
662
663
15505
inline const std::vector<std::string>& Environment::argv() {
664
15505
  return argv_;
665
}
666
667
5937
inline const std::vector<std::string>& Environment::exec_argv() {
668
5937
  return exec_argv_;
669
}
670
671
10784
inline const std::string& Environment::exec_path() const {
672
10784
  return exec_path_;
673
}
674
675
10
inline std::string Environment::GetCwd() {
676
  char cwd[PATH_MAX_BYTES];
677
10
  size_t size = PATH_MAX_BYTES;
678
10
  const int err = uv_cwd(cwd, &size);
679
680
10
  if (err == 0) {
681
10
    CHECK_GT(size, 0);
682
10
    return cwd;
683
  }
684
685
  // This can fail if the cwd is deleted. In that case, fall back to
686
  // exec_path.
687
  const std::string& exec_path = exec_path_;
688
  return exec_path.substr(0, exec_path.find_last_of(kPathSeparator));
689
}
690
691
#if HAVE_INSPECTOR
692
5388
inline void Environment::set_coverage_directory(const char* dir) {
693
5388
  coverage_directory_ = std::string(dir);
694
5388
}
695
696
5415
inline void Environment::set_coverage_connection(
697
    std::unique_ptr<profiler::V8CoverageConnection> connection) {
698
5415
  CHECK_NULL(coverage_connection_);
699
5415
  std::swap(coverage_connection_, connection);
700
5415
}
701
702
16243
inline profiler::V8CoverageConnection* Environment::coverage_connection() {
703
16243
  return coverage_connection_.get();
704
}
705
706
5371
inline const std::string& Environment::coverage_directory() const {
707
5371
  return coverage_directory_;
708
}
709
710
12
inline void Environment::set_cpu_profiler_connection(
711
    std::unique_ptr<profiler::V8CpuProfilerConnection> connection) {
712
12
  CHECK_NULL(cpu_profiler_connection_);
713
12
  std::swap(cpu_profiler_connection_, connection);
714
12
}
715
716
inline profiler::V8CpuProfilerConnection*
717
5430
Environment::cpu_profiler_connection() {
718
5430
  return cpu_profiler_connection_.get();
719
}
720
721
12
inline void Environment::set_cpu_prof_interval(uint64_t interval) {
722
12
  cpu_prof_interval_ = interval;
723
12
}
724
725
12
inline uint64_t Environment::cpu_prof_interval() const {
726
12
  return cpu_prof_interval_;
727
}
728
729
12
inline void Environment::set_cpu_prof_name(const std::string& name) {
730
12
  cpu_prof_name_ = name;
731
12
}
732
733
12
inline const std::string& Environment::cpu_prof_name() const {
734
12
  return cpu_prof_name_;
735
}
736
737
12
inline void Environment::set_cpu_prof_dir(const std::string& dir) {
738
12
  cpu_prof_dir_ = dir;
739
12
}
740
741
12
inline const std::string& Environment::cpu_prof_dir() const {
742
12
  return cpu_prof_dir_;
743
}
744
745
6
inline void Environment::set_heap_profiler_connection(
746
    std::unique_ptr<profiler::V8HeapProfilerConnection> connection) {
747
6
  CHECK_NULL(heap_profiler_connection_);
748
6
  std::swap(heap_profiler_connection_, connection);
749
6
}
750
751
inline profiler::V8HeapProfilerConnection*
752
5412
Environment::heap_profiler_connection() {
753
5412
  return heap_profiler_connection_.get();
754
}
755
756
6
inline void Environment::set_heap_prof_name(const std::string& name) {
757
6
  heap_prof_name_ = name;
758
6
}
759
760
6
inline const std::string& Environment::heap_prof_name() const {
761
6
  return heap_prof_name_;
762
}
763
764
6
inline void Environment::set_heap_prof_dir(const std::string& dir) {
765
6
  heap_prof_dir_ = dir;
766
6
}
767
768
6
inline const std::string& Environment::heap_prof_dir() const {
769
6
  return heap_prof_dir_;
770
}
771
772
6
inline void Environment::set_heap_prof_interval(uint64_t interval) {
773
6
  heap_prof_interval_ = interval;
774
6
}
775
776
6
inline uint64_t Environment::heap_prof_interval() const {
777
6
  return heap_prof_interval_;
778
}
779
780
#endif  // HAVE_INSPECTOR
781
782
inline
783
10998
std::shared_ptr<ExclusiveAccess<HostPort>> Environment::inspector_host_port() {
784
10998
  return inspector_host_port_;
785
}
786
787
103332
inline std::shared_ptr<PerIsolateOptions> IsolateData::options() {
788
103332
  return options_;
789
}
790
791
257
inline void IsolateData::set_options(
792
    std::shared_ptr<PerIsolateOptions> options) {
793
257
  options_ = std::move(options);
794
257
}
795
796
template <typename Fn>
797
90395
void Environment::SetImmediate(Fn&& cb, CallbackFlags::Flags flags) {
798
180790
  auto callback = native_immediates_.CreateCallback(std::move(cb), flags);
799
90395
  native_immediates_.Push(std::move(callback));
800
801
90395
  if (flags & CallbackFlags::kRefed) {
802
66556
    if (immediate_info()->ref_count() == 0)
803
50006
      ToggleImmediateRef(true);
804
66556
    immediate_info()->ref_count_inc(1);
805
  }
806
90395
}
807
808
template <typename Fn>
809
3031
void Environment::SetImmediateThreadsafe(Fn&& cb, CallbackFlags::Flags flags) {
810
6062
  auto callback = native_immediates_threadsafe_.CreateCallback(
811
3031
      std::move(cb), flags);
812
  {
813
6062
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
814
3031
    native_immediates_threadsafe_.Push(std::move(callback));
815
3031
    if (task_queues_async_initialized_)
816
2054
      uv_async_send(&task_queues_async_);
817
  }
818
3031
}
819
820
template <typename Fn>
821
9230
void Environment::RequestInterrupt(Fn&& cb) {
822
18460
  auto callback = native_immediates_interrupts_.CreateCallback(
823
9230
      std::move(cb), CallbackFlags::kRefed);
824
  {
825
18460
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
826
9230
    native_immediates_interrupts_.Push(std::move(callback));
827
9230
    if (task_queues_async_initialized_)
828
3684
      uv_async_send(&task_queues_async_);
829
  }
830
9230
  RequestInterruptFromV8();
831
9230
}
832
833
2920412
inline bool Environment::can_call_into_js() const {
834

2920412
  return can_call_into_js_ && !is_stopping();
835
}
836
837
1249
inline void Environment::set_can_call_into_js(bool can_call_into_js) {
838
1249
  can_call_into_js_ = can_call_into_js;
839
1249
}
840
841
1147198
inline bool Environment::has_run_bootstrapping_code() const {
842
1147198
  return has_run_bootstrapping_code_;
843
}
844
845
5429
inline void Environment::DoneBootstrapping() {
846
5429
  has_run_bootstrapping_code_ = true;
847
  // This adjusts the return value of base_object_created_after_bootstrap() so
848
  // that tests that check the count do not have to account for internally
849
  // created BaseObjects.
850
5429
  base_object_created_by_bootstrap_ = base_object_count_;
851
5429
}
852
853
19
inline bool Environment::has_serialized_options() const {
854
19
  return has_serialized_options_;
855
}
856
857
5408
inline void Environment::set_has_serialized_options(bool value) {
858
5408
  has_serialized_options_ = value;
859
5408
}
860
861
7968
inline bool Environment::is_main_thread() const {
862
7968
  return worker_context() == nullptr;
863
}
864
865
965
inline bool Environment::no_native_addons() const {
866
1926
  return (flags_ & EnvironmentFlags::kNoNativeAddons) ||
867
1926
          !options_->allow_native_addons;
868
}
869
870
5390
inline bool Environment::should_not_register_esm_loader() const {
871
5390
  return flags_ & EnvironmentFlags::kNoRegisterESMLoader;
872
}
873
874
13859
inline bool Environment::owns_process_state() const {
875
13859
  return flags_ & EnvironmentFlags::kOwnsProcessState;
876
}
877
878
5423
inline bool Environment::owns_inspector() const {
879
5423
  return flags_ & EnvironmentFlags::kOwnsInspector;
880
}
881
882
103881
inline bool Environment::tracks_unmanaged_fds() const {
883
103881
  return flags_ & EnvironmentFlags::kTrackUnmanagedFds;
884
}
885
886
2582
inline bool Environment::hide_console_windows() const {
887
2582
  return flags_ & EnvironmentFlags::kHideConsoleWindows;
888
}
889
890
6190
inline bool Environment::no_global_search_paths() const {
891
12380
  return (flags_ & EnvironmentFlags::kNoGlobalSearchPaths) ||
892
12380
         !options_->global_search_paths;
893
}
894
895
4
bool Environment::filehandle_close_warning() const {
896
4
  return emit_filehandle_warning_;
897
}
898
899
3
void Environment::set_filehandle_close_warning(bool on) {
900
3
  emit_filehandle_warning_ = on;
901
3
}
902
903
5254
void Environment::set_source_maps_enabled(bool on) {
904
5254
  source_maps_enabled_ = on;
905
5254
}
906
907
900
bool Environment::source_maps_enabled() const {
908
900
  return source_maps_enabled_;
909
}
910
911
6641
inline uint64_t Environment::thread_id() const {
912
6641
  return thread_id_;
913
}
914
915
13915
inline worker::Worker* Environment::worker_context() const {
916
13915
  return isolate_data()->worker_context();
917
}
918
919
797
inline void Environment::add_sub_worker_context(worker::Worker* context) {
920
797
  sub_worker_contexts_.insert(context);
921
797
}
922
923
826
inline void Environment::remove_sub_worker_context(worker::Worker* context) {
924
826
  sub_worker_contexts_.erase(context);
925
826
}
926
927
template <typename Fn>
928
24
inline void Environment::ForEachWorker(Fn&& iterator) {
929
26
  for (worker::Worker* w : sub_worker_contexts_) iterator(w);
930
24
}
931
932
1576
inline void Environment::add_refs(int64_t diff) {
933
1576
  task_queues_async_refs_ += diff;
934
1576
  CHECK_GE(task_queues_async_refs_, 0);
935
1576
  if (task_queues_async_refs_ == 0)
936
173
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
937
  else
938
1403
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
939
1576
}
940
941
4408801
inline bool Environment::is_stopping() const {
942
4408801
  return is_stopping_.load();
943
}
944
945
5094
inline void Environment::set_stopping(bool value) {
946
5094
  is_stopping_.store(value);
947
5094
}
948
949
14
inline std::list<node_module>* Environment::extra_linked_bindings() {
950
14
  return &extra_linked_bindings_;
951
}
952
953
10
inline node_module* Environment::extra_linked_bindings_head() {
954
10
  return extra_linked_bindings_.size() > 0 ?
955
10
      &extra_linked_bindings_.front() : nullptr;
956
}
957
958
9
inline node_module* Environment::extra_linked_bindings_tail() {
959
9
  return extra_linked_bindings_.size() > 0 ?
960
9
      &extra_linked_bindings_.back() : nullptr;
961
}
962
963
19
inline const Mutex& Environment::extra_linked_bindings_mutex() const {
964
19
  return extra_linked_bindings_mutex_;
965
}
966
967
40284
inline performance::PerformanceState* Environment::performance_state() {
968
40284
  return performance_state_.get();
969
}
970
971
6456556
inline IsolateData* Environment::isolate_data() const {
972
6456556
  return isolate_data_;
973
}
974
975
66476
inline uv_buf_t Environment::allocate_managed_buffer(
976
    const size_t suggested_size) {
977
132952
  NoArrayBufferZeroFillScope no_zero_fill_scope(isolate_data());
978
  std::unique_ptr<v8::BackingStore> bs =
979
66476
      v8::ArrayBuffer::NewBackingStore(isolate(), suggested_size);
980
66476
  uv_buf_t buf = uv_buf_init(static_cast<char*>(bs->Data()), bs->ByteLength());
981
66476
  released_allocated_buffers()->emplace(buf.base, std::move(bs));
982
66476
  return buf;
983
}
984
985
81014
inline std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer(
986
    const uv_buf_t& buf) {
987
81014
  std::unique_ptr<v8::BackingStore> bs;
988
81014
  if (buf.base != nullptr) {
989
66476
    auto map = released_allocated_buffers();
990
66476
    auto it = map->find(buf.base);
991
66476
    CHECK_NE(it, map->end());
992
66476
    bs = std::move(it->second);
993
66476
    map->erase(it);
994
  }
995
81014
  return bs;
996
}
997
998
std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>*
999
132952
    Environment::released_allocated_buffers() {
1000
132952
  return &released_allocated_buffers_;
1001
}
1002
1003
8
inline void Environment::ThrowError(const char* errmsg) {
1004
8
  ThrowError(v8::Exception::Error, errmsg);
1005
8
}
1006
1007
inline void Environment::ThrowTypeError(const char* errmsg) {
1008
  ThrowError(v8::Exception::TypeError, errmsg);
1009
}
1010
1011
inline void Environment::ThrowRangeError(const char* errmsg) {
1012
  ThrowError(v8::Exception::RangeError, errmsg);
1013
}
1014
1015
8
inline void Environment::ThrowError(
1016
    v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
1017
    const char* errmsg) {
1018
16
  v8::HandleScope handle_scope(isolate());
1019
8
  isolate()->ThrowException(fun(OneByteString(isolate(), errmsg)));
1020
8
}
1021
1022
7
inline void Environment::ThrowErrnoException(int errorno,
1023
                                             const char* syscall,
1024
                                             const char* message,
1025
                                             const char* path) {
1026
  isolate()->ThrowException(
1027
7
      ErrnoException(isolate(), errorno, syscall, message, path));
1028
7
}
1029
1030
14
inline void Environment::ThrowUVException(int errorno,
1031
                                          const char* syscall,
1032
                                          const char* message,
1033
                                          const char* path,
1034
                                          const char* dest) {
1035
  isolate()->ThrowException(
1036
14
      UVException(isolate(), errorno, syscall, message, path, dest));
1037
14
}
1038
1039
inline v8::Local<v8::FunctionTemplate>
1040
1472978
    Environment::NewFunctionTemplate(v8::FunctionCallback callback,
1041
                                     v8::Local<v8::Signature> signature,
1042
                                     v8::ConstructorBehavior behavior,
1043
                                     v8::SideEffectType side_effect_type) {
1044
  return v8::FunctionTemplate::New(isolate(), callback, v8::Local<v8::Value>(),
1045
1472978
                                   signature, 0, behavior, side_effect_type);
1046
}
1047
1048
255475
inline void Environment::SetMethod(v8::Local<v8::Object> that,
1049
                                   const char* name,
1050
                                   v8::FunctionCallback callback) {
1051
255475
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
1052
  v8::Local<v8::Function> function =
1053
255475
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
1054
                          v8::ConstructorBehavior::kThrow,
1055
255475
                          v8::SideEffectType::kHasSideEffect)
1056
255475
          ->GetFunction(context)
1057
255475
          .ToLocalChecked();
1058
  // kInternalized strings are created in the old space.
1059
255475
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1060
  v8::Local<v8::String> name_string =
1061
510950
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1062
510950
  that->Set(context, name_string, function).Check();
1063
255475
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
1064
255475
}
1065
1066
121759
inline void Environment::SetMethodNoSideEffect(v8::Local<v8::Object> that,
1067
                                               const char* name,
1068
                                               v8::FunctionCallback callback) {
1069
121759
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
1070
  v8::Local<v8::Function> function =
1071
121759
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
1072
                          v8::ConstructorBehavior::kThrow,
1073
121759
                          v8::SideEffectType::kHasNoSideEffect)
1074
121759
          ->GetFunction(context)
1075
121759
          .ToLocalChecked();
1076
  // kInternalized strings are created in the old space.
1077
121759
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1078
  v8::Local<v8::String> name_string =
1079
243518
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1080
243518
  that->Set(context, name_string, function).Check();
1081
121759
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
1082
121759
}
1083
1084
726850
inline void Environment::SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
1085
                                        const char* name,
1086
                                        v8::FunctionCallback callback) {
1087
726850
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
1088
  v8::Local<v8::FunctionTemplate> t =
1089
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
1090
726850
                          v8::SideEffectType::kHasSideEffect);
1091
  // kInternalized strings are created in the old space.
1092
726850
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1093
  v8::Local<v8::String> name_string =
1094
1453700
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1095
1453700
  that->PrototypeTemplate()->Set(name_string, t);
1096
726850
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
1097
726850
}
1098
1099
119512
inline void Environment::SetProtoMethodNoSideEffect(
1100
    v8::Local<v8::FunctionTemplate> that,
1101
    const char* name,
1102
    v8::FunctionCallback callback) {
1103
119512
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
1104
  v8::Local<v8::FunctionTemplate> t =
1105
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
1106
119512
                          v8::SideEffectType::kHasNoSideEffect);
1107
  // kInternalized strings are created in the old space.
1108
119512
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1109
  v8::Local<v8::String> name_string =
1110
239024
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1111
239024
  that->PrototypeTemplate()->Set(name_string, t);
1112
119512
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
1113
119512
}
1114
1115
33
inline void Environment::SetInstanceMethod(v8::Local<v8::FunctionTemplate> that,
1116
                                           const char* name,
1117
                                           v8::FunctionCallback callback) {
1118
33
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
1119
  v8::Local<v8::FunctionTemplate> t =
1120
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
1121
33
                          v8::SideEffectType::kHasSideEffect);
1122
  // kInternalized strings are created in the old space.
1123
33
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1124
  v8::Local<v8::String> name_string =
1125
66
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1126
66
  that->InstanceTemplate()->Set(name_string, t);
1127
33
  t->SetClassName(name_string);
1128
33
}
1129
1130
185867
inline void Environment::SetConstructorFunction(
1131
    v8::Local<v8::Object> that,
1132
    const char* name,
1133
    v8::Local<v8::FunctionTemplate> tmpl,
1134
    SetConstructorFunctionFlag flag) {
1135
185867
  SetConstructorFunction(that, OneByteString(isolate(), name), tmpl, flag);
1136
185867
}
1137
1138
196319
inline void Environment::SetConstructorFunction(
1139
    v8::Local<v8::Object> that,
1140
    v8::Local<v8::String> name,
1141
    v8::Local<v8::FunctionTemplate> tmpl,
1142
    SetConstructorFunctionFlag flag) {
1143
196319
  if (LIKELY(flag == SetConstructorFunctionFlag::SET_CLASS_NAME))
1144
191082
    tmpl->SetClassName(name);
1145
196319
  that->Set(
1146
      context(),
1147
      name,
1148
392638
      tmpl->GetFunction(context()).ToLocalChecked()).Check();
1149
196319
}
1150
1151
367885
void Environment::AddCleanupHook(CleanupCallback fn, void* arg) {
1152
735770
  auto insertion_info = cleanup_hooks_.emplace(CleanupHookCallback {
1153
367885
    fn, arg, cleanup_hook_counter_++
1154
367885
  });
1155
  // Make sure there was no existing element with these values.
1156
367885
  CHECK_EQ(insertion_info.second, true);
1157
367885
}
1158
1159
353484
void Environment::RemoveCleanupHook(CleanupCallback fn, void* arg) {
1160
353484
  CleanupHookCallback search { fn, arg, 0 };
1161
353484
  cleanup_hooks_.erase(search);
1162
353484
}
1163
1164
943451
size_t CleanupHookCallback::Hash::operator()(
1165
    const CleanupHookCallback& cb) const {
1166
943451
  return std::hash<void*>()(cb.arg_);
1167
}
1168
1169
468727
bool CleanupHookCallback::Equal::operator()(
1170
    const CleanupHookCallback& a, const CleanupHookCallback& b) const {
1171

468727
  return a.fn_ == b.fn_ && a.arg_ == b.arg_;
1172
}
1173
1174
467
BaseObject* CleanupHookCallback::GetBaseObject() const {
1175
467
  if (fn_ == BaseObject::DeleteMe)
1176
440
    return static_cast<BaseObject*>(arg_);
1177
  else
1178
27
    return nullptr;
1179
}
1180
1181
template <typename T>
1182
44
void Environment::ForEachBaseObject(T&& iterator) {
1183
978
  for (const auto& hook : cleanup_hooks_) {
1184
934
    BaseObject* obj = hook.GetBaseObject();
1185
934
    if (obj != nullptr)
1186
880
      iterator(obj);
1187
  }
1188
}
1189
1190
template <typename T>
1191
6
void Environment::ForEachBindingData(T&& iterator) {
1192
  BindingDataStore* map = static_cast<BindingDataStore*>(
1193
12
      context()->GetAlignedPointerFromEmbedderData(
1194
          ContextEmbedderIndex::kBindingListIndex));
1195
  DCHECK_NOT_NULL(map);
1196
24
  for (auto& it : *map) {
1197
18
    iterator(it.first, it.second);
1198
  }
1199
6
}
1200
1201
662443
void Environment::modify_base_object_count(int64_t delta) {
1202
662443
  base_object_count_ += delta;
1203
662443
}
1204
1205
14
int64_t Environment::base_object_created_after_bootstrap() const {
1206
14
  return base_object_count_ - base_object_created_by_bootstrap_;
1207
}
1208
1209
2
int64_t Environment::base_object_count() const {
1210
2
  return base_object_count_;
1211
}
1212
1213
17
void Environment::set_main_utf16(std::unique_ptr<v8::String::Value> str) {
1214
17
  CHECK(!main_utf16_);
1215
17
  main_utf16_ = std::move(str);
1216
17
}
1217
1218
565
void Environment::set_process_exit_handler(
1219
    std::function<void(Environment*, int)>&& handler) {
1220
565
  process_exit_handler_ = std::move(handler);
1221
565
}
1222
1223
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1224
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1225
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1226
#define V(TypeName, PropertyName)                                             \
1227
  inline                                                                      \
1228
  v8::Local<TypeName> IsolateData::PropertyName() const {                     \
1229
    return PropertyName ## _ .Get(isolate_);                                  \
1230
  }
1231
42402
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1232
844902
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1233
6168153
  PER_ISOLATE_STRING_PROPERTIES(VS)
1234
#undef V
1235
#undef VS
1236
#undef VY
1237
#undef VP
1238
1239
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1240
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1241
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1242
#define V(TypeName, PropertyName)                                             \
1243
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1244
    return isolate_data()->PropertyName();                                    \
1245
  }
1246
42402
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1247
727743
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1248
8861274
  PER_ISOLATE_STRING_PROPERTIES(VS)
1249
#undef V
1250
#undef VS
1251
#undef VY
1252
#undef VP
1253
1254
#define V(PropertyName, TypeName)                                             \
1255
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1256
    return PersistentToLocal::Strong(PropertyName ## _);                      \
1257
  }                                                                           \
1258
  inline void Environment::set_ ## PropertyName(v8::Local<TypeName> value) {  \
1259
    PropertyName ## _.Reset(isolate(), value);                                \
1260
  }
1261
1225548
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1262
3125384
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1263
#undef V
1264
1265
6531582
v8::Local<v8::Context> Environment::context() const {
1266
6531582
  return PersistentToLocal::Strong(context_);
1267
}
1268
1269
}  // namespace node
1270
1271
// These two files depend on each other. Including base_object-inl.h after this
1272
// file is the easiest way to avoid issues with that circular dependency.
1273
#include "base_object-inl.h"
1274
1275
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1276
1277
#endif  // SRC_ENV_INL_H_