GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env-inl.h Lines: 646 662 97.6 %
Date: 2021-10-01 04:12:33 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
958418
inline uv_loop_t* IsolateData::event_loop() const {
50
958418
  return event_loop_;
51
}
52
53
163518
inline NodeArrayBufferAllocator* IsolateData::node_allocator() const {
54
163518
  return node_allocator_;
55
}
56
57
56209
inline MultiIsolatePlatform* IsolateData::platform() const {
58
56209
  return platform_;
59
}
60
61
582
inline void IsolateData::set_worker_context(worker::Worker* context) {
62
582
  CHECK_NULL(worker_context_);  // Should be set only once.
63
582
  worker_context_ = context;
64
582
}
65
66
14030
inline worker::Worker* IsolateData::worker_context() const {
67
14030
  return worker_context_;
68
}
69
70
202475
inline v8::Local<v8::String> IsolateData::async_wrap_provider(int index) const {
71
202475
  return async_wrap_providers_[index].Get(isolate_);
72
}
73
74
3000869
inline AliasedUint32Array& AsyncHooks::fields() {
75
3000869
  return fields_;
76
}
77
78
1688278
inline AliasedFloat64Array& AsyncHooks::async_id_fields() {
79
1688278
  return async_id_fields_;
80
}
81
82
622
inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
83
622
  return async_ids_stack_;
84
}
85
86
797710
v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() {
87
797710
  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
797710
  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
202127
inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) {
119
202127
  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
1106989
inline Environment* AsyncHooks::env() {
127
1106989
  return Environment::ForAsyncHooks(this);
128
}
129
130
// Remember to keep this code aligned with pushAsyncContext() in JS.
131
772209
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
772209
  if (fields_[kCheck] > 0) {
137
772206
    CHECK_GE(async_id, -1);
138
772206
    CHECK_GE(trigger_async_id, -1);
139
  }
140
141
772209
  uint32_t offset = fields_[kStackLength];
142
772209
  if (offset * 2 >= async_ids_stack_.Length())
143
4
    grow_async_ids_stack();
144
772209
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
145
772209
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
146
772209
  fields_[kStackLength] += 1;
147
772209
  async_id_fields_[kExecutionAsyncId] = async_id;
148
772209
  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
772209
  if (!resource.IsEmpty()) {
160
772205
    native_execution_async_resources_.resize(offset + 1);
161
772205
    native_execution_async_resources_[offset].Reset(env()->isolate(), resource);
162
  }
163
772209
}
164
165
// Remember to keep this code aligned with popAsyncContext() in JS.
166
771844
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
771844
  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

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

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

989726
            native_execution_async_resources_.capacity() / 2 &&
207
218923
        native_execution_async_resources_.size() > 16) {
208
      native_execution_async_resources_.shrink_to_fit();
209
    }
210
  }
211
212
1541606
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
213
26285
    v8::HandleScope handle_scope(env()->isolate());
214
52570
    USE(js_execution_async_resources()->Set(
215
        env()->context(),
216
        env()->length_string(),
217
105140
        v8::Integer::NewFromUnsigned(env()->isolate(), offset)));
218
  }
219
220
770803
  return fields_[kStackLength] > 0;
221
}
222
223
1980
void AsyncHooks::clear_async_id_stack() {
224
1980
  v8::Isolate* isolate = env()->isolate();
225
1980
  v8::HandleScope handle_scope(isolate);
226
1980
  if (!js_execution_async_resources_.IsEmpty()) {
227
2716
    USE(PersistentToLocal::Strong(js_execution_async_resources_)->Set(
228
        env()->context(),
229
        env()->length_string(),
230
5432
        v8::Integer::NewFromUnsigned(isolate, 0)));
231
  }
232
1980
  native_execution_async_resources_.clear();
233
1980
  native_execution_async_resources_.shrink_to_fit();
234
235
1980
  async_id_fields_[kExecutionAsyncId] = 0;
236
1980
  async_id_fields_[kTriggerAsyncId] = 0;
237
1980
  fields_[kStackLength] = 0;
238
1980
}
239
240
6050
inline void AsyncHooks::AddContext(v8::Local<v8::Context> ctx) {
241
23804
  ctx->SetPromiseHooks(
242
6050
    js_promise_hooks_[0].IsEmpty() ?
243
6050
      v8::Local<v8::Function>() :
244
198
      PersistentToLocal::Strong(js_promise_hooks_[0]),
245
6050
    js_promise_hooks_[1].IsEmpty() ?
246
6050
      v8::Local<v8::Function>() :
247
198
      PersistentToLocal::Strong(js_promise_hooks_[1]),
248
6050
    js_promise_hooks_[2].IsEmpty() ?
249
6050
      v8::Local<v8::Function>() :
250
198
      PersistentToLocal::Strong(js_promise_hooks_[2]),
251
6050
    js_promise_hooks_[3].IsEmpty() ?
252
6050
      v8::Local<v8::Function>() :
253
      PersistentToLocal::Strong(js_promise_hooks_[3]));
254
255
6050
  size_t id = contexts_.size();
256
6050
  contexts_.resize(id + 1);
257
6050
  contexts_[id].Reset(env()->isolate(), ctx);
258
6050
  contexts_[id].SetWeak();
259
6050
}
260
261
482
inline void AsyncHooks::RemoveContext(v8::Local<v8::Context> ctx) {
262
482
  v8::Isolate* isolate = env()->isolate();
263
964
  v8::HandleScope handle_scope(isolate);
264
4100
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
265
3618
    if (it->IsEmpty()) {
266
61
      it = contexts_.erase(it);
267
61
      it--;
268
61
      continue;
269
    }
270
    v8::Local<v8::Context> saved_context =
271
3557
      PersistentToLocal::Weak(isolate, *it);
272
3557
    if (saved_context == ctx) {
273
      it->Reset();
274
      contexts_.erase(it);
275
      break;
276
    }
277
  }
278
482
}
279
280
// The DefaultTriggerAsyncIdScope(AsyncWrap*) constructor is defined in
281
// async_wrap-inl.h to avoid a circular dependency.
282
283
259195
inline AsyncHooks::DefaultTriggerAsyncIdScope ::DefaultTriggerAsyncIdScope(
284
259195
    Environment* env, double default_trigger_async_id)
285
259195
    : async_hooks_(env->async_hooks()) {
286
259195
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
287
259195
    CHECK_GE(default_trigger_async_id, 0);
288
  }
289
290
259195
  old_default_trigger_async_id_ =
291
259195
    async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
292
259195
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
293
259195
    default_trigger_async_id;
294
259195
}
295
296
518388
inline AsyncHooks::DefaultTriggerAsyncIdScope ::~DefaultTriggerAsyncIdScope() {
297
259194
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
298
259194
    old_default_trigger_async_id_;
299
259194
}
300
301
1106989
Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) {
302
1106989
  return ContainerOf(&Environment::async_hooks_, hooks);
303
}
304
305
771877
inline size_t Environment::async_callback_scope_depth() const {
306
771877
  return async_callback_scope_depth_;
307
}
308
309
783827
inline void Environment::PushAsyncCallbackScope() {
310
783827
  async_callback_scope_depth_++;
311
783827
}
312
313
783340
inline void Environment::PopAsyncCallbackScope() {
314
783340
  async_callback_scope_depth_--;
315
783340
}
316
317
622
inline AliasedUint32Array& ImmediateInfo::fields() {
318
622
  return fields_;
319
}
320
321
172643
inline uint32_t ImmediateInfo::count() const {
322
172643
  return fields_[kCount];
323
}
324
325
261053
inline uint32_t ImmediateInfo::ref_count() const {
326
261053
  return fields_[kRefCount];
327
}
328
329
41099
inline bool ImmediateInfo::has_outstanding() const {
330
41099
  return fields_[kHasOutstanding] == 1;
331
}
332
333
33298
inline void ImmediateInfo::ref_count_inc(uint32_t increment) {
334
33298
  fields_[kRefCount] += increment;
335
33298
}
336
337
187596
inline void ImmediateInfo::ref_count_dec(uint32_t decrement) {
338
187596
  fields_[kRefCount] -= decrement;
339
187596
}
340
341
622
inline AliasedUint8Array& TickInfo::fields() {
342
622
  return fields_;
343
}
344
345
1377094
inline bool TickInfo::has_tick_scheduled() const {
346
1377094
  return fields_[kHasTickScheduled] == 1;
347
}
348
349
507148
inline bool TickInfo::has_rejection_to_warn() const {
350
507148
  return fields_[kHasRejectionToWarn] == 1;
351
}
352
353
6050
inline void Environment::AssignToContext(v8::Local<v8::Context> context,
354
                                         const ContextInfo& info) {
355
6050
  context->SetAlignedPointerInEmbedderData(
356
      ContextEmbedderIndex::kEnvironment, this);
357
  // Used by Environment::GetCurrent to know that we are on a node context.
358
6050
  context->SetAlignedPointerInEmbedderData(
359
    ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr);
360
  // Used to retrieve bindings
361
12100
  context->SetAlignedPointerInEmbedderData(
362
6050
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
363
364
#if HAVE_INSPECTOR
365
6050
  inspector_agent()->ContextCreated(context, info);
366
#endif  // HAVE_INSPECTOR
367
368
6050
  this->async_hooks()->AddContext(context);
369
6050
}
370
371
826601
inline Environment* Environment::GetCurrent(v8::Isolate* isolate) {
372
826601
  if (UNLIKELY(!isolate->InContext())) return nullptr;
373
1651010
  v8::HandleScope handle_scope(isolate);
374
825505
  return GetCurrent(isolate->GetCurrentContext());
375
}
376
377
6067515
inline Environment* Environment::GetCurrent(v8::Local<v8::Context> context) {
378
6067515
  if (UNLIKELY(context.IsEmpty())) {
379
1
    return nullptr;
380
  }
381
6067514
  if (UNLIKELY(context->GetNumberOfEmbedderDataFields() <=
382
6067514
               ContextEmbedderIndex::kContextTag)) {
383
11
    return nullptr;
384
  }
385
6067503
  if (UNLIKELY(context->GetAlignedPointerFromEmbedderData(
386
                   ContextEmbedderIndex::kContextTag) !=
387
6067503
               Environment::kNodeContextTagPtr)) {
388
    return nullptr;
389
  }
390
  return static_cast<Environment*>(
391
6067503
      context->GetAlignedPointerFromEmbedderData(
392
6067503
          ContextEmbedderIndex::kEnvironment));
393
}
394
395
3550308
inline Environment* Environment::GetCurrent(
396
    const v8::FunctionCallbackInfo<v8::Value>& info) {
397
3550308
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
398
}
399
400
template <typename T>
401
2606202
inline Environment* Environment::GetCurrent(
402
    const v8::PropertyCallbackInfo<T>& info) {
403
2606202
  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
745555
inline T* Environment::GetBindingData(
413
    const v8::FunctionCallbackInfo<v8::Value>& info) {
414
745555
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
415
}
416
417
template <typename T>
418
745557
inline T* Environment::GetBindingData(v8::Local<v8::Context> context) {
419
  BindingDataStore* map = static_cast<BindingDataStore*>(
420
745557
      context->GetAlignedPointerFromEmbedderData(
421
          ContextEmbedderIndex::kBindingListIndex));
422
  DCHECK_NOT_NULL(map);
423
745557
  auto it = map->find(T::type_name);
424
745557
  if (UNLIKELY(it == map->end())) return nullptr;
425
745557
  T* result = static_cast<T*>(it->second.get());
426
  DCHECK_NOT_NULL(result);
427
  DCHECK_EQ(result->env(), GetCurrent(context));
428
745557
  return result;
429
}
430
431
template <typename T>
432
17452
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
34904
  BaseObjectPtr<T> item = MakeDetachedBaseObject<T>(this, target);
438
  BindingDataStore* map = static_cast<BindingDataStore*>(
439
17452
      context->GetAlignedPointerFromEmbedderData(
440
          ContextEmbedderIndex::kBindingListIndex));
441
  DCHECK_NOT_NULL(map);
442
17452
  auto result = map->emplace(T::type_name, item);
443
17452
  CHECK(result.second);
444
  DCHECK_EQ(GetBindingData<T>(context), item.get());
445
17452
  return item.get();
446
}
447
448
24606661
inline v8::Isolate* Environment::isolate() const {
449
24606661
  return isolate_;
450
}
451
452
6754
inline Environment* Environment::from_timer_handle(uv_timer_t* handle) {
453
6754
  return ContainerOf(&Environment::timer_handle_, handle);
454
}
455
456
26579
inline uv_timer_t* Environment::timer_handle() {
457
26579
  return &timer_handle_;
458
}
459
460
172643
inline Environment* Environment::from_immediate_check_handle(
461
    uv_check_t* handle) {
462
172643
  return ContainerOf(&Environment::immediate_check_handle_, handle);
463
}
464
465
21736
inline uv_check_t* Environment::immediate_check_handle() {
466
21736
  return &immediate_check_handle_;
467
}
468
469
215927
inline uv_idle_t* Environment::immediate_idle_handle() {
470
215927
  return &immediate_idle_handle_;
471
}
472
473
32604
inline void Environment::RegisterHandleCleanup(uv_handle_t* handle,
474
                                               HandleCleanupCb cb,
475
                                               void* arg) {
476
32604
  handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg});
477
32604
}
478
479
template <typename T, typename OnCloseCallback>
480
34261
inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) {
481
34109
  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
34185
  handle->data = new CloseData { this, callback, handle->data };
493
34489
  uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
494
68218
    std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) };
495
34185
    data->env->handle_cleanup_waiting_--;
496
34185
    handle->data = data->original_data;
497
34185
    data->callback(reinterpret_cast<T*>(handle));
498
  });
499
34185
}
500
501
87443
void Environment::IncreaseWaitingRequestCounter() {
502
87443
  request_waiting_++;
503
87443
}
504
505
87431
void Environment::DecreaseWaitingRequestCounter() {
506
87431
  request_waiting_--;
507
87431
  CHECK_GE(request_waiting_, 0);
508
87431
}
509
510
952951
inline uv_loop_t* Environment::event_loop() const {
511
952951
  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
44449
inline bool Environment::is_in_inspector_console_call() const {
526
44449
  return is_in_inspector_console_call_;
527
}
528
529
88896
inline void Environment::set_is_in_inspector_console_call(bool value) {
530
88896
  is_in_inspector_console_call_ = value;
531
88896
}
532
#endif
533
534
5126725
inline AsyncHooks* Environment::async_hooks() {
535
5126725
  return &async_hooks_;
536
}
537
538
696311
inline ImmediateInfo* Environment::immediate_info() {
539
696311
  return &immediate_info_;
540
}
541
542
689189
inline TickInfo* Environment::tick_info() {
543
689189
  return &tick_info_;
544
}
545
546
58375
inline uint64_t Environment::timer_base() const {
547
58375
  return timer_base_;
548
}
549
550
1317866
inline std::shared_ptr<KVStore> Environment::env_vars() {
551
1317866
  return env_vars_;
552
}
553
554
6033
inline void Environment::set_env_vars(std::shared_ptr<KVStore> env_vars) {
555
6033
  env_vars_ = env_vars;
556
6033
}
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
9926
inline void Environment::set_trace_sync_io(bool value) {
567
9926
  trace_sync_io_ = value;
568
9926
}
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
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
302260
inline AliasedInt32Array& Environment::stream_base_state() {
591
302260
  return stream_base_state_;
592
}
593
594
45205
inline uint32_t Environment::get_next_module_id() {
595
45205
  return module_id_counter_++;
596
}
597
3185
inline uint32_t Environment::get_next_script_id() {
598
3185
  return script_id_counter_++;
599
}
600
32382
inline uint32_t Environment::get_next_function_id() {
601
32382
  return function_id_counter_++;
602
}
603
604
93228
ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope(
605
93228
    Environment* env)
606
93228
    : env_(env) {
607
93228
  env_->PushShouldNotAbortOnUncaughtScope();
608
93228
}
609
610
186452
ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() {
611
93226
  Close();
612
93226
}
613
614
93417
void ShouldNotAbortOnUncaughtScope::Close() {
615
93417
  if (env_ != nullptr) {
616
93226
    env_->PopShouldNotAbortOnUncaughtScope();
617
93226
    env_ = nullptr;
618
  }
619
93417
}
620
621
93228
inline void Environment::PushShouldNotAbortOnUncaughtScope() {
622
93228
  should_not_abort_scope_counter_++;
623
93228
}
624
625
93226
inline void Environment::PopShouldNotAbortOnUncaughtScope() {
626
93226
  should_not_abort_scope_counter_--;
627
93226
}
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
404037
inline std::vector<double>* Environment::destroy_async_id_list() {
634
404037
  return &destroy_async_id_list_;
635
}
636
637
202680
inline double Environment::new_async_id() {
638
202680
  async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
639
202680
  return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
640
}
641
642
234213
inline double Environment::execution_async_id() {
643
234213
  return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId];
644
}
645
646
67822
inline double Environment::trigger_async_id() {
647
67822
  return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId];
648
}
649
650
202677
inline double Environment::get_default_trigger_async_id() {
651
  double default_trigger_async_id =
652
202677
    async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
653
  // If defaultTriggerAsyncId isn't set, use the executionAsyncId
654
202677
  if (default_trigger_async_id < 0)
655
166366
    default_trigger_async_id = execution_async_id();
656
202677
  return default_trigger_async_id;
657
}
658
659
60959
inline std::shared_ptr<EnvironmentOptions> Environment::options() {
660
60959
  return options_;
661
}
662
663
15617
inline const std::vector<std::string>& Environment::argv() {
664
15617
  return argv_;
665
}
666
667
5984
inline const std::vector<std::string>& Environment::exec_argv() {
668
5984
  return exec_argv_;
669
}
670
671
10868
inline const std::string& Environment::exec_path() const {
672
10868
  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
5429
inline void Environment::set_coverage_directory(const char* dir) {
693
5429
  coverage_directory_ = std::string(dir);
694
5429
}
695
696
5452
inline void Environment::set_coverage_connection(
697
    std::unique_ptr<profiler::V8CoverageConnection> connection) {
698
5452
  CHECK_NULL(coverage_connection_);
699
5452
  std::swap(coverage_connection_, connection);
700
5452
}
701
702
16355
inline profiler::V8CoverageConnection* Environment::coverage_connection() {
703
16355
  return coverage_connection_.get();
704
}
705
706
5414
inline const std::string& Environment::coverage_directory() const {
707
5414
  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
5468
Environment::cpu_profiler_connection() {
718
5468
  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
5456
Environment::heap_profiler_connection() {
753
5456
  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
11074
std::shared_ptr<ExclusiveAccess<HostPort>> Environment::inspector_host_port() {
784
11074
  return inspector_host_port_;
785
}
786
787
102796
inline std::shared_ptr<PerIsolateOptions> IsolateData::options() {
788
102796
  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
90298
void Environment::SetImmediate(Fn&& cb, CallbackFlags::Flags flags) {
798
180596
  auto callback = native_immediates_.CreateCallback(std::move(cb), flags);
799
90298
  native_immediates_.Push(std::move(callback));
800
801
90298
  if (flags & CallbackFlags::kRefed) {
802
66582
    if (immediate_info()->ref_count() == 0)
803
50024
      ToggleImmediateRef(true);
804
66582
    immediate_info()->ref_count_inc(1);
805
  }
806
90298
}
807
808
template <typename Fn>
809
2730
void Environment::SetImmediateThreadsafe(Fn&& cb, CallbackFlags::Flags flags) {
810
5460
  auto callback = native_immediates_threadsafe_.CreateCallback(
811
2730
      std::move(cb), flags);
812
  {
813
5460
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
814
2730
    native_immediates_threadsafe_.Push(std::move(callback));
815
2730
    if (task_queues_async_initialized_)
816
2044
      uv_async_send(&task_queues_async_);
817
  }
818
2730
}
819
820
template <typename Fn>
821
9232
void Environment::RequestInterrupt(Fn&& cb) {
822
18464
  auto callback = native_immediates_interrupts_.CreateCallback(
823
9232
      std::move(cb), CallbackFlags::kRefed);
824
  {
825
18464
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
826
9232
    native_immediates_interrupts_.Push(std::move(callback));
827
9232
    if (task_queues_async_initialized_)
828
3650
      uv_async_send(&task_queues_async_);
829
  }
830
9232
  RequestInterruptFromV8();
831
9232
}
832
833
2906525
inline bool Environment::can_call_into_js() const {
834

2906525
  return can_call_into_js_ && !is_stopping();
835
}
836
837
1218
inline void Environment::set_can_call_into_js(bool can_call_into_js) {
838
1218
  can_call_into_js_ = can_call_into_js;
839
1218
}
840
841
1449442
inline bool Environment::has_run_bootstrapping_code() const {
842
1449442
  return has_run_bootstrapping_code_;
843
}
844
845
5467
inline void Environment::DoneBootstrapping() {
846
5467
  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
5467
  base_object_created_by_bootstrap_ = base_object_count_;
851
5467
}
852
853
19
inline bool Environment::has_serialized_options() const {
854
19
  return has_serialized_options_;
855
}
856
857
5450
inline void Environment::set_has_serialized_options(bool value) {
858
5450
  has_serialized_options_ = value;
859
5450
}
860
861
8041
inline bool Environment::is_main_thread() const {
862
8041
  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
5434
inline bool Environment::should_not_register_esm_loader() const {
871
5434
  return flags_ & EnvironmentFlags::kNoRegisterESMLoader;
872
}
873
874
13943
inline bool Environment::owns_process_state() const {
875
13943
  return flags_ & EnvironmentFlags::kOwnsProcessState;
876
}
877
878
5461
inline bool Environment::owns_inspector() const {
879
5461
  return flags_ & EnvironmentFlags::kOwnsInspector;
880
}
881
882
114158
inline bool Environment::tracks_unmanaged_fds() const {
883
114158
  return flags_ & EnvironmentFlags::kTrackUnmanagedFds;
884
}
885
886
2607
inline bool Environment::hide_console_windows() const {
887
2607
  return flags_ & EnvironmentFlags::kHideConsoleWindows;
888
}
889
890
6239
inline bool Environment::no_global_search_paths() const {
891
12478
  return (flags_ & EnvironmentFlags::kNoGlobalSearchPaths) ||
892
12478
         !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
5297
void Environment::set_source_maps_enabled(bool on) {
904
5297
  source_maps_enabled_ = on;
905
5297
}
906
907
874
bool Environment::source_maps_enabled() const {
908
874
  return source_maps_enabled_;
909
}
910
911
6688
inline uint64_t Environment::thread_id() const {
912
6688
  return thread_id_;
913
}
914
915
14030
inline worker::Worker* Environment::worker_context() const {
916
14030
  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
829
inline void Environment::remove_sub_worker_context(worker::Worker* context) {
924
829
  sub_worker_contexts_.erase(context);
925
829
}
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
4388307
inline bool Environment::is_stopping() const {
942
4388307
  return is_stopping_.load();
943
}
944
945
5155
inline void Environment::set_stopping(bool value) {
946
5155
  is_stopping_.store(value);
947
5155
}
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
40443
inline performance::PerformanceState* Environment::performance_state() {
968
40443
  return performance_state_.get();
969
}
970
971
6537786
inline IsolateData* Environment::isolate_data() const {
972
6537786
  return isolate_data_;
973
}
974
975
455
inline uv_buf_t Environment::allocate_managed_buffer(
976
    const size_t suggested_size) {
977
910
  NoArrayBufferZeroFillScope no_zero_fill_scope(isolate_data());
978
  std::unique_ptr<v8::BackingStore> bs =
979
455
      v8::ArrayBuffer::NewBackingStore(isolate(), suggested_size);
980
455
  uv_buf_t buf = uv_buf_init(static_cast<char*>(bs->Data()), bs->ByteLength());
981
455
  released_allocated_buffers()->emplace(buf.base, std::move(bs));
982
455
  return buf;
983
}
984
985
455
inline std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer(
986
    const uv_buf_t& buf) {
987
455
  std::unique_ptr<v8::BackingStore> bs;
988
455
  if (buf.base != nullptr) {
989
455
    auto map = released_allocated_buffers();
990
455
    auto it = map->find(buf.base);
991
455
    CHECK_NE(it, map->end());
992
455
    bs = std::move(it->second);
993
455
    map->erase(it);
994
  }
995
455
  return bs;
996
}
997
998
std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>*
999
132154
    Environment::released_allocated_buffers() {
1000
132154
  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
1470307
    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
1470307
                                   signature, 0, behavior, side_effect_type);
1046
}
1047
1048
256209
inline void Environment::SetMethod(v8::Local<v8::Object> that,
1049
                                   const char* name,
1050
                                   v8::FunctionCallback callback) {
1051
256209
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
1052
  v8::Local<v8::Function> function =
1053
256209
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
1054
                          v8::ConstructorBehavior::kThrow,
1055
256209
                          v8::SideEffectType::kHasSideEffect)
1056
256209
          ->GetFunction(context)
1057
256209
          .ToLocalChecked();
1058
  // kInternalized strings are created in the old space.
1059
256209
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1060
  v8::Local<v8::String> name_string =
1061
512418
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1062
512418
  that->Set(context, name_string, function).Check();
1063
256209
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
1064
256209
}
1065
1066
116483
inline void Environment::SetMethodNoSideEffect(v8::Local<v8::Object> that,
1067
                                               const char* name,
1068
                                               v8::FunctionCallback callback) {
1069
116483
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
1070
  v8::Local<v8::Function> function =
1071
116483
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
1072
                          v8::ConstructorBehavior::kThrow,
1073
116483
                          v8::SideEffectType::kHasNoSideEffect)
1074
116483
          ->GetFunction(context)
1075
116483
          .ToLocalChecked();
1076
  // kInternalized strings are created in the old space.
1077
116483
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1078
  v8::Local<v8::String> name_string =
1079
232966
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1080
232966
  that->Set(context, name_string, function).Check();
1081
116483
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
1082
116483
}
1083
1084
727975
inline void Environment::SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
1085
                                        const char* name,
1086
                                        v8::FunctionCallback callback) {
1087
727975
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
1088
  v8::Local<v8::FunctionTemplate> t =
1089
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
1090
727975
                          v8::SideEffectType::kHasSideEffect);
1091
  // kInternalized strings are created in the old space.
1092
727975
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1093
  v8::Local<v8::String> name_string =
1094
1455950
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1095
1455950
  that->PrototypeTemplate()->Set(name_string, t);
1096
727975
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
1097
727975
}
1098
1099
119818
inline void Environment::SetProtoMethodNoSideEffect(
1100
    v8::Local<v8::FunctionTemplate> that,
1101
    const char* name,
1102
    v8::FunctionCallback callback) {
1103
119818
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
1104
  v8::Local<v8::FunctionTemplate> t =
1105
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
1106
119818
                          v8::SideEffectType::kHasNoSideEffect);
1107
  // kInternalized strings are created in the old space.
1108
119818
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1109
  v8::Local<v8::String> name_string =
1110
239636
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1111
239636
  that->PrototypeTemplate()->Set(name_string, t);
1112
119818
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
1113
119818
}
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
186131
inline void Environment::SetConstructorFunction(
1131
    v8::Local<v8::Object> that,
1132
    const char* name,
1133
    v8::Local<v8::FunctionTemplate> tmpl,
1134
    SetConstructorFunctionFlag flag) {
1135
186131
  SetConstructorFunction(that, OneByteString(isolate(), name), tmpl, flag);
1136
186131
}
1137
1138
196593
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
196593
  if (LIKELY(flag == SetConstructorFunctionFlag::SET_CLASS_NAME))
1144
191359
    tmpl->SetClassName(name);
1145
196593
  that->Set(
1146
      context(),
1147
      name,
1148
393186
      tmpl->GetFunction(context()).ToLocalChecked()).Check();
1149
196593
}
1150
1151
366230
void Environment::AddCleanupHook(CleanupCallback fn, void* arg) {
1152
732460
  auto insertion_info = cleanup_hooks_.emplace(CleanupHookCallback {
1153
366230
    fn, arg, cleanup_hook_counter_++
1154
366230
  });
1155
  // Make sure there was no existing element with these values.
1156
366230
  CHECK_EQ(insertion_info.second, true);
1157
366230
}
1158
1159
352561
void Environment::RemoveCleanupHook(CleanupCallback fn, void* arg) {
1160
352561
  CleanupHookCallback search { fn, arg, 0 };
1161
352561
  cleanup_hooks_.erase(search);
1162
352561
}
1163
1164
940422
size_t CleanupHookCallback::Hash::operator()(
1165
    const CleanupHookCallback& cb) const {
1166
940422
  return std::hash<void*>()(cb.arg_);
1167
}
1168
1169
467645
bool CleanupHookCallback::Equal::operator()(
1170
    const CleanupHookCallback& a, const CleanupHookCallback& b) const {
1171

467645
  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
660518
void Environment::modify_base_object_count(int64_t delta) {
1202
660518
  base_object_count_ += delta;
1203
660518
}
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
569
void Environment::set_process_exit_handler(
1219
    std::function<void(Environment*, int)>&& handler) {
1220
569
  process_exit_handler_ = std::move(handler);
1221
569
}
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
41434
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1232
837885
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1233
6153925
  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
41434
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1247
719913
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1248
8842045
  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
1228400
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1262
3141323
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1263
#undef V
1264
1265
6817101
v8::Local<v8::Context> Environment::context() const {
1266
6817101
  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_