GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env-inl.h Lines: 646 662 97.6 %
Date: 2021-10-07 04:12:46 Branches: 114 146 78.1 %

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
958111
inline uv_loop_t* IsolateData::event_loop() const {
50
958111
  return event_loop_;
51
}
52
53
160788
inline NodeArrayBufferAllocator* IsolateData::node_allocator() const {
54
160788
  return node_allocator_;
55
}
56
57
56124
inline MultiIsolatePlatform* IsolateData::platform() const {
58
56124
  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
13914
inline worker::Worker* IsolateData::worker_context() const {
67
13914
  return worker_context_;
68
}
69
70
202628
inline v8::Local<v8::String> IsolateData::async_wrap_provider(int index) const {
71
202628
  return async_wrap_providers_[index].Get(isolate_);
72
}
73
74
2990632
inline AliasedUint32Array& AsyncHooks::fields() {
75
2990632
  return fields_;
76
}
77
78
1686589
inline AliasedFloat64Array& AsyncHooks::async_id_fields() {
79
1686589
  return async_id_fields_;
80
}
81
82
618
inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
83
618
  return async_ids_stack_;
84
}
85
86
793731
v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() {
87
793731
  if (UNLIKELY(js_execution_async_resources_.IsEmpty())) {
88
618
    js_execution_async_resources_.Reset(
89
1236
        env()->isolate(), v8::Array::New(env()->isolate()));
90
  }
91
793731
  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
2983
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
2983
  js_promise_hooks_[0].Reset(env()->isolate(), init);
104
2983
  js_promise_hooks_[1].Reset(env()->isolate(), before);
105
2983
  js_promise_hooks_[2].Reset(env()->isolate(), after);
106
2983
  js_promise_hooks_[3].Reset(env()->isolate(), resolve);
107
6074
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
108
3091
    if (it->IsEmpty()) {
109
      it = contexts_.erase(it);
110
      it--;
111
      continue;
112
    }
113
6182
    PersistentToLocal::Weak(env()->isolate(), *it)
114
3091
        ->SetPromiseHooks(init, before, after, resolve);
115
  }
116
2983
}
117
118
202280
inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) {
119
202280
  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
1100832
inline Environment* AsyncHooks::env() {
127
1100832
  return Environment::ForAsyncHooks(this);
128
}
129
130
// Remember to keep this code aligned with pushAsyncContext() in JS.
131
769038
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
769038
  if (fields_[kCheck] > 0) {
137
769035
    CHECK_GE(async_id, -1);
138
769035
    CHECK_GE(trigger_async_id, -1);
139
  }
140
141
769038
  uint32_t offset = fields_[kStackLength];
142
769038
  if (offset * 2 >= async_ids_stack_.Length())
143
4
    grow_async_ids_stack();
144
769038
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
145
769038
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
146
769038
  fields_[kStackLength] += 1;
147
769038
  async_id_fields_[kExecutionAsyncId] = async_id;
148
769038
  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
769038
  if (!resource.IsEmpty()) {
160
769034
    native_execution_async_resources_.resize(offset + 1);
161
769034
    native_execution_async_resources_[offset].Reset(env()->isolate(), resource);
162
  }
163
769038
}
164
165
// Remember to keep this code aligned with popAsyncContext() in JS.
166
768666
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
768666
  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

767629
  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
767625
  uint32_t offset = fields_[kStackLength] - 1;
191
767625
  async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
192
767625
  async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
193
767625
  fields_[kStackLength] = offset;
194
195
1535250
  if (LIKELY(offset < native_execution_async_resources_.size() &&
196

1535250
             !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
767625
    native_execution_async_resources_.resize(offset);
205
767625
    if (native_execution_async_resources_.size() <
206

985529
            native_execution_async_resources_.capacity() / 2 &&
207
217904
        native_execution_async_resources_.size() > 16) {
208
      native_execution_async_resources_.shrink_to_fit();
209
    }
210
  }
211
212
1535250
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
213
25488
    v8::HandleScope handle_scope(env()->isolate());
214
50976
    USE(js_execution_async_resources()->Set(
215
        env()->context(),
216
        env()->length_string(),
217
101952
        v8::Integer::NewFromUnsigned(env()->isolate(), offset)));
218
  }
219
220
767625
  return fields_[kStackLength] > 0;
221
}
222
223
1983
void AsyncHooks::clear_async_id_stack() {
224
1983
  v8::Isolate* isolate = env()->isolate();
225
1983
  v8::HandleScope handle_scope(isolate);
226
1983
  if (!js_execution_async_resources_.IsEmpty()) {
227
2730
    USE(PersistentToLocal::Strong(js_execution_async_resources_)->Set(
228
        env()->context(),
229
        env()->length_string(),
230
5460
        v8::Integer::NewFromUnsigned(isolate, 0)));
231
  }
232
1983
  native_execution_async_resources_.clear();
233
1983
  native_execution_async_resources_.shrink_to_fit();
234
235
1983
  async_id_fields_[kExecutionAsyncId] = 0;
236
1983
  async_id_fields_[kTriggerAsyncId] = 0;
237
1983
  fields_[kStackLength] = 0;
238
1983
}
239
240
6069
inline void AsyncHooks::AddContext(v8::Local<v8::Context> ctx) {
241
23880
  ctx->SetPromiseHooks(
242
6069
    js_promise_hooks_[0].IsEmpty() ?
243
6069
      v8::Local<v8::Function>() :
244
198
      PersistentToLocal::Strong(js_promise_hooks_[0]),
245
6069
    js_promise_hooks_[1].IsEmpty() ?
246
6069
      v8::Local<v8::Function>() :
247
198
      PersistentToLocal::Strong(js_promise_hooks_[1]),
248
6069
    js_promise_hooks_[2].IsEmpty() ?
249
6069
      v8::Local<v8::Function>() :
250
198
      PersistentToLocal::Strong(js_promise_hooks_[2]),
251
6069
    js_promise_hooks_[3].IsEmpty() ?
252
6069
      v8::Local<v8::Function>() :
253
      PersistentToLocal::Strong(js_promise_hooks_[3]));
254
255
6069
  size_t id = contexts_.size();
256
6069
  contexts_.resize(id + 1);
257
6069
  contexts_[id].Reset(env()->isolate(), ctx);
258
6069
  contexts_[id].SetWeak();
259
6069
}
260
261
503
inline void AsyncHooks::RemoveContext(v8::Local<v8::Context> ctx) {
262
503
  v8::Isolate* isolate = env()->isolate();
263
1006
  v8::HandleScope handle_scope(isolate);
264
4545
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
265
4042
    if (it->IsEmpty()) {
266
61
      it = contexts_.erase(it);
267
61
      it--;
268
61
      continue;
269
    }
270
    v8::Local<v8::Context> saved_context =
271
3981
      PersistentToLocal::Weak(isolate, *it);
272
3981
    if (saved_context == ctx) {
273
      it->Reset();
274
      contexts_.erase(it);
275
      break;
276
    }
277
  }
278
503
}
279
280
// The DefaultTriggerAsyncIdScope(AsyncWrap*) constructor is defined in
281
// async_wrap-inl.h to avoid a circular dependency.
282
283
258459
inline AsyncHooks::DefaultTriggerAsyncIdScope ::DefaultTriggerAsyncIdScope(
284
258459
    Environment* env, double default_trigger_async_id)
285
258459
    : async_hooks_(env->async_hooks()) {
286
258459
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
287
258459
    CHECK_GE(default_trigger_async_id, 0);
288
  }
289
290
258459
  old_default_trigger_async_id_ =
291
258459
    async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
292
258459
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
293
258459
    default_trigger_async_id;
294
258459
}
295
296
516916
inline AsyncHooks::DefaultTriggerAsyncIdScope ::~DefaultTriggerAsyncIdScope() {
297
258458
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
298
258458
    old_default_trigger_async_id_;
299
258458
}
300
301
1100832
Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) {
302
1100832
  return ContainerOf(&Environment::async_hooks_, hooks);
303
}
304
305
768697
inline size_t Environment::async_callback_scope_depth() const {
306
768697
  return async_callback_scope_depth_;
307
}
308
309
780461
inline void Environment::PushAsyncCallbackScope() {
310
780461
  async_callback_scope_depth_++;
311
780461
}
312
313
779886
inline void Environment::PopAsyncCallbackScope() {
314
779886
  async_callback_scope_depth_--;
315
779886
}
316
317
618
inline AliasedUint32Array& ImmediateInfo::fields() {
318
618
  return fields_;
319
}
320
321
171650
inline uint32_t ImmediateInfo::count() const {
322
171650
  return fields_[kCount];
323
}
324
325
259278
inline uint32_t ImmediateInfo::ref_count() const {
326
259278
  return fields_[kRefCount];
327
}
328
329
40404
inline bool ImmediateInfo::has_outstanding() const {
330
40404
  return fields_[kHasOutstanding] == 1;
331
}
332
333
33305
inline void ImmediateInfo::ref_count_inc(uint32_t increment) {
334
33305
  fields_[kRefCount] += increment;
335
33305
}
336
337
186510
inline void ImmediateInfo::ref_count_dec(uint32_t decrement) {
338
186510
  fields_[kRefCount] -= decrement;
339
186510
}
340
341
618
inline AliasedUint8Array& TickInfo::fields() {
342
618
  return fields_;
343
}
344
345
1370596
inline bool TickInfo::has_tick_scheduled() const {
346
1370596
  return fields_[kHasTickScheduled] == 1;
347
}
348
349
505185
inline bool TickInfo::has_rejection_to_warn() const {
350
505185
  return fields_[kHasRejectionToWarn] == 1;
351
}
352
353
6069
inline void Environment::AssignToContext(v8::Local<v8::Context> context,
354
                                         const ContextInfo& info) {
355
6069
  context->SetAlignedPointerInEmbedderData(
356
      ContextEmbedderIndex::kEnvironment, this);
357
  // Used by Environment::GetCurrent to know that we are on a node context.
358
6069
  context->SetAlignedPointerInEmbedderData(
359
    ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr);
360
  // Used to retrieve bindings
361
12138
  context->SetAlignedPointerInEmbedderData(
362
6069
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
363
364
#if HAVE_INSPECTOR
365
6069
  inspector_agent()->ContextCreated(context, info);
366
#endif  // HAVE_INSPECTOR
367
368
6069
  this->async_hooks()->AddContext(context);
369
6069
}
370
371
822781
inline Environment* Environment::GetCurrent(v8::Isolate* isolate) {
372
822781
  if (UNLIKELY(!isolate->InContext())) return nullptr;
373
1643278
  v8::HandleScope handle_scope(isolate);
374
821639
  return GetCurrent(isolate->GetCurrentContext());
375
}
376
377
6058546
inline Environment* Environment::GetCurrent(v8::Local<v8::Context> context) {
378
6058546
  if (UNLIKELY(context.IsEmpty())) {
379
1
    return nullptr;
380
  }
381
6058545
  if (UNLIKELY(context->GetNumberOfEmbedderDataFields() <=
382
6058545
               ContextEmbedderIndex::kContextTag)) {
383
11
    return nullptr;
384
  }
385
6058534
  if (UNLIKELY(context->GetAlignedPointerFromEmbedderData(
386
                   ContextEmbedderIndex::kContextTag) !=
387
6058534
               Environment::kNodeContextTagPtr)) {
388
    return nullptr;
389
  }
390
  return static_cast<Environment*>(
391
6058534
      context->GetAlignedPointerFromEmbedderData(
392
6058534
          ContextEmbedderIndex::kEnvironment));
393
}
394
395
3545914
inline Environment* Environment::GetCurrent(
396
    const v8::FunctionCallbackInfo<v8::Value>& info) {
397
3545914
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
398
}
399
400
template <typename T>
401
2607206
inline Environment* Environment::GetCurrent(
402
    const v8::PropertyCallbackInfo<T>& info) {
403
2607206
  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
745752
inline T* Environment::GetBindingData(
413
    const v8::FunctionCallbackInfo<v8::Value>& info) {
414
745752
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
415
}
416
417
template <typename T>
418
745754
inline T* Environment::GetBindingData(v8::Local<v8::Context> context) {
419
  BindingDataStore* map = static_cast<BindingDataStore*>(
420
745754
      context->GetAlignedPointerFromEmbedderData(
421
          ContextEmbedderIndex::kBindingListIndex));
422
  DCHECK_NOT_NULL(map);
423
745754
  auto it = map->find(T::type_name);
424
745754
  if (UNLIKELY(it == map->end())) return nullptr;
425
745754
  T* result = static_cast<T*>(it->second.get());
426
  DCHECK_NOT_NULL(result);
427
  DCHECK_EQ(result->env(), GetCurrent(context));
428
745754
  return result;
429
}
430
431
template <typename T>
432
17448
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
34896
  BaseObjectPtr<T> item = MakeDetachedBaseObject<T>(this, target);
438
  BindingDataStore* map = static_cast<BindingDataStore*>(
439
17448
      context->GetAlignedPointerFromEmbedderData(
440
          ContextEmbedderIndex::kBindingListIndex));
441
  DCHECK_NOT_NULL(map);
442
17448
  auto result = map->emplace(T::type_name, item);
443
17448
  CHECK(result.second);
444
  DCHECK_EQ(GetBindingData<T>(context), item.get());
445
17448
  return item.get();
446
}
447
448
24550766
inline v8::Isolate* Environment::isolate() const {
449
24550766
  return isolate_;
450
}
451
452
6656
inline Environment* Environment::from_timer_handle(uv_timer_t* handle) {
453
6656
  return ContainerOf(&Environment::timer_handle_, handle);
454
}
455
456
26480
inline uv_timer_t* Environment::timer_handle() {
457
26480
  return &timer_handle_;
458
}
459
460
171650
inline Environment* Environment::from_immediate_check_handle(
461
    uv_check_t* handle) {
462
171650
  return ContainerOf(&Environment::immediate_check_handle_, handle);
463
}
464
465
21728
inline uv_check_t* Environment::immediate_check_handle() {
466
21728
  return &immediate_check_handle_;
467
}
468
469
215018
inline uv_idle_t* Environment::immediate_idle_handle() {
470
215018
  return &immediate_idle_handle_;
471
}
472
473
32592
inline void Environment::RegisterHandleCleanup(uv_handle_t* handle,
474
                                               HandleCleanupCb cb,
475
                                               void* arg) {
476
32592
  handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg});
477
32592
}
478
479
template <typename T, typename OnCloseCallback>
480
33635
inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) {
481
33483
  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
33559
  handle->data = new CloseData { this, callback, handle->data };
493
33863
  uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
494
66966
    std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) };
495
33559
    data->env->handle_cleanup_waiting_--;
496
33559
    handle->data = data->original_data;
497
33559
    data->callback(reinterpret_cast<T*>(handle));
498
  });
499
33559
}
500
501
87591
void Environment::IncreaseWaitingRequestCounter() {
502
87591
  request_waiting_++;
503
87591
}
504
505
87579
void Environment::DecreaseWaitingRequestCounter() {
506
87579
  request_waiting_--;
507
87579
  CHECK_GE(request_waiting_, 0);
508
87579
}
509
510
952646
inline uv_loop_t* Environment::event_loop() const {
511
952646
  return isolate_data()->event_loop();
512
}
513
514
164
inline void Environment::TryLoadAddon(
515
    const char* filename,
516
    int flags,
517
    const std::function<bool(binding::DLib*)>& was_loaded) {
518
164
  loaded_addons_.emplace_back(filename, flags);
519
164
  if (!was_loaded(&loaded_addons_.back())) {
520
8
    loaded_addons_.pop_back();
521
  }
522
164
}
523
524
#if HAVE_INSPECTOR
525
44456
inline bool Environment::is_in_inspector_console_call() const {
526
44456
  return is_in_inspector_console_call_;
527
}
528
529
88910
inline void Environment::set_is_in_inspector_console_call(bool value) {
530
88910
  is_in_inspector_console_call_ = value;
531
88910
}
532
#endif
533
534
5114444
inline AsyncHooks* Environment::async_hooks() {
535
5114444
  return &async_hooks_;
536
}
537
538
691765
inline ImmediateInfo* Environment::immediate_info() {
539
691765
  return &immediate_info_;
540
}
541
542
685935
inline TickInfo* Environment::tick_info() {
543
685935
  return &tick_info_;
544
}
545
546
57973
inline uint64_t Environment::timer_base() const {
547
57973
  return timer_base_;
548
}
549
550
1318360
inline std::shared_ptr<KVStore> Environment::env_vars() {
551
1318360
  return env_vars_;
552
}
553
554
6027
inline void Environment::set_env_vars(std::shared_ptr<KVStore> env_vars) {
555
6027
  env_vars_ = env_vars;
556
6027
}
557
558
17
inline bool Environment::printed_error() const {
559
17
  return printed_error_;
560
}
561
562
17
inline void Environment::set_printed_error(bool value) {
563
17
  printed_error_ = value;
564
17
}
565
566
9814
inline void Environment::set_trace_sync_io(bool value) {
567
9814
  trace_sync_io_ = value;
568
9814
}
569
570
83
inline bool Environment::abort_on_uncaught_exception() const {
571
83
  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
566
inline void Environment::set_abort_on_uncaught_exception(bool value) {
583
566
  options_->abort_on_uncaught_exception = value;
584
566
}
585
586
648
inline AliasedUint32Array& Environment::should_abort_on_uncaught_toggle() {
587
648
  return should_abort_on_uncaught_toggle_;
588
}
589
590
297820
inline AliasedInt32Array& Environment::stream_base_state() {
591
297820
  return stream_base_state_;
592
}
593
594
45223
inline uint32_t Environment::get_next_module_id() {
595
45223
  return module_id_counter_++;
596
}
597
3021
inline uint32_t Environment::get_next_script_id() {
598
3021
  return script_id_counter_++;
599
}
600
32384
inline uint32_t Environment::get_next_function_id() {
601
32384
  return function_id_counter_++;
602
}
603
604
93100
ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope(
605
93100
    Environment* env)
606
93100
    : env_(env) {
607
93100
  env_->PushShouldNotAbortOnUncaughtScope();
608
93100
}
609
610
186196
ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() {
611
93098
  Close();
612
93098
}
613
614
93289
void ShouldNotAbortOnUncaughtScope::Close() {
615
93289
  if (env_ != nullptr) {
616
93098
    env_->PopShouldNotAbortOnUncaughtScope();
617
93098
    env_ = nullptr;
618
  }
619
93289
}
620
621
93100
inline void Environment::PushShouldNotAbortOnUncaughtScope() {
622
93100
  should_not_abort_scope_counter_++;
623
93100
}
624
625
93098
inline void Environment::PopShouldNotAbortOnUncaughtScope() {
626
93098
  should_not_abort_scope_counter_--;
627
93098
}
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
404156
inline std::vector<double>* Environment::destroy_async_id_list() {
634
404156
  return &destroy_async_id_list_;
635
}
636
637
202833
inline double Environment::new_async_id() {
638
202833
  async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
639
202833
  return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
640
}
641
642
234315
inline double Environment::execution_async_id() {
643
234315
  return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId];
644
}
645
646
67784
inline double Environment::trigger_async_id() {
647
67784
  return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId];
648
}
649
650
202830
inline double Environment::get_default_trigger_async_id() {
651
  double default_trigger_async_id =
652
202830
    async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
653
  // If defaultTriggerAsyncId isn't set, use the executionAsyncId
654
202830
  if (default_trigger_async_id < 0)
655
166506
    default_trigger_async_id = execution_async_id();
656
202830
  return default_trigger_async_id;
657
}
658
659
60980
inline std::shared_ptr<EnvironmentOptions> Environment::options() {
660
60980
  return options_;
661
}
662
663
15619
inline const std::vector<std::string>& Environment::argv() {
664
15619
  return argv_;
665
}
666
667
5982
inline const std::vector<std::string>& Environment::exec_argv() {
668
5982
  return exec_argv_;
669
}
670
671
10864
inline const std::string& Environment::exec_path() const {
672
10864
  return exec_path_;
673
}
674
675
11
inline std::string Environment::GetCwd() {
676
  char cwd[PATH_MAX_BYTES];
677
11
  size_t size = PATH_MAX_BYTES;
678
11
  const int err = uv_cwd(cwd, &size);
679
680
11
  if (err == 0) {
681
11
    CHECK_GT(size, 0);
682
11
    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
5427
inline void Environment::set_coverage_directory(const char* dir) {
693
5427
  coverage_directory_ = std::string(dir);
694
5427
}
695
696
5450
inline void Environment::set_coverage_connection(
697
    std::unique_ptr<profiler::V8CoverageConnection> connection) {
698
5450
  CHECK_NULL(coverage_connection_);
699
5450
  std::swap(coverage_connection_, connection);
700
5450
}
701
702
16349
inline profiler::V8CoverageConnection* Environment::coverage_connection() {
703
16349
  return coverage_connection_.get();
704
}
705
706
5411
inline const std::string& Environment::coverage_directory() const {
707
5411
  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
5466
Environment::cpu_profiler_connection() {
718
5466
  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
12
inline void Environment::set_heap_profiler_connection(
746
    std::unique_ptr<profiler::V8HeapProfilerConnection> connection) {
747
12
  CHECK_NULL(heap_profiler_connection_);
748
12
  std::swap(heap_profiler_connection_, connection);
749
12
}
750
751
inline profiler::V8HeapProfilerConnection*
752
5454
Environment::heap_profiler_connection() {
753
5454
  return heap_profiler_connection_.get();
754
}
755
756
12
inline void Environment::set_heap_prof_name(const std::string& name) {
757
12
  heap_prof_name_ = name;
758
12
}
759
760
12
inline const std::string& Environment::heap_prof_name() const {
761
12
  return heap_prof_name_;
762
}
763
764
12
inline void Environment::set_heap_prof_dir(const std::string& dir) {
765
12
  heap_prof_dir_ = dir;
766
12
}
767
768
12
inline const std::string& Environment::heap_prof_dir() const {
769
12
  return heap_prof_dir_;
770
}
771
772
12
inline void Environment::set_heap_prof_interval(uint64_t interval) {
773
12
  heap_prof_interval_ = interval;
774
12
}
775
776
12
inline uint64_t Environment::heap_prof_interval() const {
777
12
  return heap_prof_interval_;
778
}
779
780
#endif  // HAVE_INSPECTOR
781
782
inline
783
11070
std::shared_ptr<ExclusiveAccess<HostPort>> Environment::inspector_host_port() {
784
11070
  return inspector_host_port_;
785
}
786
787
102712
inline std::shared_ptr<PerIsolateOptions> IsolateData::options() {
788
102712
  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
90297
void Environment::SetImmediate(Fn&& cb, CallbackFlags::Flags flags) {
798
180594
  auto callback = native_immediates_.CreateCallback(std::move(cb), flags);
799
90297
  native_immediates_.Push(std::move(callback));
800
801
90297
  if (flags & CallbackFlags::kRefed) {
802
66596
    if (immediate_info()->ref_count() == 0)
803
50038
      ToggleImmediateRef(true);
804
66596
    immediate_info()->ref_count_inc(1);
805
  }
806
90297
}
807
808
template <typename Fn>
809
2568
void Environment::SetImmediateThreadsafe(Fn&& cb, CallbackFlags::Flags flags) {
810
5136
  auto callback = native_immediates_threadsafe_.CreateCallback(
811
2568
      std::move(cb), flags);
812
  {
813
5136
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
814
2568
    native_immediates_threadsafe_.Push(std::move(callback));
815
2568
    if (task_queues_async_initialized_)
816
2063
      uv_async_send(&task_queues_async_);
817
  }
818
2568
}
819
820
template <typename Fn>
821
9272
void Environment::RequestInterrupt(Fn&& cb) {
822
18544
  auto callback = native_immediates_interrupts_.CreateCallback(
823
9272
      std::move(cb), CallbackFlags::kRefed);
824
  {
825
18544
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
826
9272
    native_immediates_interrupts_.Push(std::move(callback));
827
9272
    if (task_queues_async_initialized_)
828
3696
      uv_async_send(&task_queues_async_);
829
  }
830
9272
  RequestInterruptFromV8();
831
9272
}
832
833
2893402
inline bool Environment::can_call_into_js() const {
834

2893402
  return can_call_into_js_ && !is_stopping();
835
}
836
837
1320
inline void Environment::set_can_call_into_js(bool can_call_into_js) {
838
1320
  can_call_into_js_ = can_call_into_js;
839
1320
}
840
841
1450075
inline bool Environment::has_run_bootstrapping_code() const {
842
1450075
  return has_run_bootstrapping_code_;
843
}
844
845
5465
inline void Environment::DoneBootstrapping() {
846
5465
  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
5465
  base_object_created_by_bootstrap_ = base_object_count_;
851
5465
}
852
853
19
inline bool Environment::has_serialized_options() const {
854
19
  return has_serialized_options_;
855
}
856
857
5448
inline void Environment::set_has_serialized_options(bool value) {
858
5448
  has_serialized_options_ = value;
859
5448
}
860
861
7931
inline bool Environment::is_main_thread() const {
862
7931
  return worker_context() == nullptr;
863
}
864
865
976
inline bool Environment::no_native_addons() const {
866
1948
  return (flags_ & EnvironmentFlags::kNoNativeAddons) ||
867
1948
          !options_->allow_native_addons;
868
}
869
870
5432
inline bool Environment::should_not_register_esm_loader() const {
871
5432
  return flags_ & EnvironmentFlags::kNoRegisterESMLoader;
872
}
873
874
13923
inline bool Environment::owns_process_state() const {
875
13923
  return flags_ & EnvironmentFlags::kOwnsProcessState;
876
}
877
878
5459
inline bool Environment::owns_inspector() const {
879
5459
  return flags_ & EnvironmentFlags::kOwnsInspector;
880
}
881
882
114355
inline bool Environment::tracks_unmanaged_fds() const {
883
114355
  return flags_ & EnvironmentFlags::kTrackUnmanagedFds;
884
}
885
886
2609
inline bool Environment::hide_console_windows() const {
887
2609
  return flags_ & EnvironmentFlags::kHideConsoleWindows;
888
}
889
890
6237
inline bool Environment::no_global_search_paths() const {
891
12474
  return (flags_ & EnvironmentFlags::kNoGlobalSearchPaths) ||
892
12474
         !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
5295
void Environment::set_source_maps_enabled(bool on) {
904
5295
  source_maps_enabled_ = on;
905
5295
}
906
907
874
bool Environment::source_maps_enabled() const {
908
874
  return source_maps_enabled_;
909
}
910
911
6677
inline uint64_t Environment::thread_id() const {
912
6677
  return thread_id_;
913
}
914
915
13914
inline worker::Worker* Environment::worker_context() const {
916
13914
  return isolate_data()->worker_context();
917
}
918
919
802
inline void Environment::add_sub_worker_context(worker::Worker* context) {
920
802
  sub_worker_contexts_.insert(context);
921
802
}
922
923
828
inline void Environment::remove_sub_worker_context(worker::Worker* context) {
924
828
  sub_worker_contexts_.erase(context);
925
828
}
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
1588
inline void Environment::add_refs(int64_t diff) {
933
1588
  task_queues_async_refs_ += diff;
934
1588
  CHECK_GE(task_queues_async_refs_, 0);
935
1588
  if (task_queues_async_refs_ == 0)
936
179
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
937
  else
938
1409
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
939
1588
}
940
941
4368386
inline bool Environment::is_stopping() const {
942
4368386
  return is_stopping_.load();
943
}
944
945
5083
inline void Environment::set_stopping(bool value) {
946
5083
  is_stopping_.store(value);
947
5083
}
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
40345
inline performance::PerformanceState* Environment::performance_state() {
968
40345
  return performance_state_.get();
969
}
970
971
6528607
inline IsolateData* Environment::isolate_data() const {
972
6528607
  return isolate_data_;
973
}
974
975
599
inline uv_buf_t Environment::allocate_managed_buffer(
976
    const size_t suggested_size) {
977
1198
  NoArrayBufferZeroFillScope no_zero_fill_scope(isolate_data());
978
  std::unique_ptr<v8::BackingStore> bs =
979
599
      v8::ArrayBuffer::NewBackingStore(isolate(), suggested_size);
980
599
  uv_buf_t buf = uv_buf_init(static_cast<char*>(bs->Data()), bs->ByteLength());
981
599
  released_allocated_buffers()->emplace(buf.base, std::move(bs));
982
599
  return buf;
983
}
984
985
599
inline std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer(
986
    const uv_buf_t& buf) {
987
599
  std::unique_ptr<v8::BackingStore> bs;
988
599
  if (buf.base != nullptr) {
989
599
    auto map = released_allocated_buffers();
990
599
    auto it = map->find(buf.base);
991
599
    CHECK_NE(it, map->end());
992
599
    bs = std::move(it->second);
993
599
    map->erase(it);
994
  }
995
599
  return bs;
996
}
997
998
std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>*
999
129572
    Environment::released_allocated_buffers() {
1000
129572
  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
1469387
    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
1469387
                                   signature, 0, behavior, side_effect_type);
1046
}
1047
1048
255559
inline void Environment::SetMethod(v8::Local<v8::Object> that,
1049
                                   const char* name,
1050
                                   v8::FunctionCallback callback) {
1051
255559
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
1052
  v8::Local<v8::Function> function =
1053
255559
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
1054
                          v8::ConstructorBehavior::kThrow,
1055
255559
                          v8::SideEffectType::kHasSideEffect)
1056
255559
          ->GetFunction(context)
1057
255559
          .ToLocalChecked();
1058
  // kInternalized strings are created in the old space.
1059
255559
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1060
  v8::Local<v8::String> name_string =
1061
511118
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1062
511118
  that->Set(context, name_string, function).Check();
1063
255559
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
1064
255559
}
1065
1066
116249
inline void Environment::SetMethodNoSideEffect(v8::Local<v8::Object> that,
1067
                                               const char* name,
1068
                                               v8::FunctionCallback callback) {
1069
116249
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
1070
  v8::Local<v8::Function> function =
1071
116249
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
1072
                          v8::ConstructorBehavior::kThrow,
1073
116249
                          v8::SideEffectType::kHasNoSideEffect)
1074
116249
          ->GetFunction(context)
1075
116249
          .ToLocalChecked();
1076
  // kInternalized strings are created in the old space.
1077
116249
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1078
  v8::Local<v8::String> name_string =
1079
232498
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1080
232498
  that->Set(context, name_string, function).Check();
1081
116249
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
1082
116249
}
1083
1084
728001
inline void Environment::SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
1085
                                        const char* name,
1086
                                        v8::FunctionCallback callback) {
1087
728001
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
1088
  v8::Local<v8::FunctionTemplate> t =
1089
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
1090
728001
                          v8::SideEffectType::kHasSideEffect);
1091
  // kInternalized strings are created in the old space.
1092
728001
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1093
  v8::Local<v8::String> name_string =
1094
1456002
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1095
1456002
  that->PrototypeTemplate()->Set(name_string, t);
1096
728001
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
1097
728001
}
1098
1099
119784
inline void Environment::SetProtoMethodNoSideEffect(
1100
    v8::Local<v8::FunctionTemplate> that,
1101
    const char* name,
1102
    v8::FunctionCallback callback) {
1103
119784
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
1104
  v8::Local<v8::FunctionTemplate> t =
1105
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
1106
119784
                          v8::SideEffectType::kHasNoSideEffect);
1107
  // kInternalized strings are created in the old space.
1108
119784
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1109
  v8::Local<v8::String> name_string =
1110
239568
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1111
239568
  that->PrototypeTemplate()->Set(name_string, t);
1112
119784
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
1113
119784
}
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
186133
inline void Environment::SetConstructorFunction(
1131
    v8::Local<v8::Object> that,
1132
    const char* name,
1133
    v8::Local<v8::FunctionTemplate> tmpl,
1134
    SetConstructorFunctionFlag flag) {
1135
186133
  SetConstructorFunction(that, OneByteString(isolate(), name), tmpl, flag);
1136
186133
}
1137
1138
196587
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
196587
  if (LIKELY(flag == SetConstructorFunctionFlag::SET_CLASS_NAME))
1144
191347
    tmpl->SetClassName(name);
1145
196587
  that->Set(
1146
      context(),
1147
      name,
1148
393174
      tmpl->GetFunction(context()).ToLocalChecked()).Check();
1149
196587
}
1150
1151
365733
void Environment::AddCleanupHook(CleanupCallback fn, void* arg) {
1152
731466
  auto insertion_info = cleanup_hooks_.emplace(CleanupHookCallback {
1153
365733
    fn, arg, cleanup_hook_counter_++
1154
365733
  });
1155
  // Make sure there was no existing element with these values.
1156
365733
  CHECK_EQ(insertion_info.second, true);
1157
365733
}
1158
1159
350534
void Environment::RemoveCleanupHook(CleanupCallback fn, void* arg) {
1160
350534
  CleanupHookCallback search { fn, arg, 0 };
1161
350534
  cleanup_hooks_.erase(search);
1162
350534
}
1163
1164
935192
size_t CleanupHookCallback::Hash::operator()(
1165
    const CleanupHookCallback& cb) const {
1166
935192
  return std::hash<void*>()(cb.arg_);
1167
}
1168
1169
464182
bool CleanupHookCallback::Equal::operator()(
1170
    const CleanupHookCallback& a, const CleanupHookCallback& b) const {
1171

464182
  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
658266
void Environment::modify_base_object_count(int64_t delta) {
1202
658266
  base_object_count_ += delta;
1203
658266
}
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
41561
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1232
829913
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1233
6151711
  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
41561
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1247
712044
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1248
8839050
  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
1227734
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1262
3127874
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1263
#undef V
1264
1265
6796243
v8::Local<v8::Context> Environment::context() const {
1266
6796243
  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_