GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env-inl.h Lines: 661 673 98.2 %
Date: 2022-06-20 04:16:14 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 "callback_queue-inl.h"
29
#include "env.h"
30
#include "node.h"
31
#include "node_context_data.h"
32
#include "node_internals.h"
33
#include "node_perf_common.h"
34
#include "util-inl.h"
35
#include "uv.h"
36
#include "v8-fast-api-calls.h"
37
#include "v8.h"
38
39
#include <cstddef>
40
#include <cstdint>
41
42
#include <utility>
43
44
namespace node {
45
46
107408
NoArrayBufferZeroFillScope::NoArrayBufferZeroFillScope(
47
107408
    IsolateData* isolate_data)
48
107408
    : node_allocator_(isolate_data->node_allocator()) {
49
107408
  if (node_allocator_ != nullptr) node_allocator_->zero_fill_field()[0] = 0;
50
107408
}
51
52
214816
NoArrayBufferZeroFillScope::~NoArrayBufferZeroFillScope() {
53
107408
  if (node_allocator_ != nullptr) node_allocator_->zero_fill_field()[0] = 1;
54
107408
}
55
56
inline v8::Isolate* IsolateData::isolate() const {
57
  return isolate_;
58
}
59
60
1231415
inline uv_loop_t* IsolateData::event_loop() const {
61
1231415
  return event_loop_;
62
}
63
64
114430
inline NodeArrayBufferAllocator* IsolateData::node_allocator() const {
65
114430
  return node_allocator_;
66
}
67
68
58684
inline MultiIsolatePlatform* IsolateData::platform() const {
69
58684
  return platform_;
70
}
71
72
1224
inline void IsolateData::set_worker_context(worker::Worker* context) {
73
1224
  CHECK_NULL(worker_context_);  // Should be set only once.
74
1224
  worker_context_ = context;
75
1224
}
76
77
19898
inline worker::Worker* IsolateData::worker_context() const {
78
19898
  return worker_context_;
79
}
80
81
219994
inline v8::Local<v8::String> IsolateData::async_wrap_provider(int index) const {
82
219994
  return async_wrap_providers_[index].Get(isolate_);
83
}
84
85
2667938
inline AliasedUint32Array& AsyncHooks::fields() {
86
2667938
  return fields_;
87
}
88
89
1736626
inline AliasedFloat64Array& AsyncHooks::async_id_fields() {
90
1736626
  return async_id_fields_;
91
}
92
93
1269
inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
94
1269
  return async_ids_stack_;
95
}
96
97
823827
v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() {
98
823827
  if (UNLIKELY(js_execution_async_resources_.IsEmpty())) {
99
1269
    js_execution_async_resources_.Reset(
100
2538
        env()->isolate(), v8::Array::New(env()->isolate()));
101
  }
102
823827
  return PersistentToLocal::Strong(js_execution_async_resources_);
103
}
104
105
2403
v8::Local<v8::Object> AsyncHooks::native_execution_async_resource(size_t i) {
106
2403
  if (i >= native_execution_async_resources_.size()) return {};
107
2403
  return native_execution_async_resources_[i];
108
}
109
110
15870
inline void AsyncHooks::SetJSPromiseHooks(v8::Local<v8::Function> init,
111
                                          v8::Local<v8::Function> before,
112
                                          v8::Local<v8::Function> after,
113
                                          v8::Local<v8::Function> resolve) {
114
15870
  js_promise_hooks_[0].Reset(env()->isolate(), init);
115
15870
  js_promise_hooks_[1].Reset(env()->isolate(), before);
116
15870
  js_promise_hooks_[2].Reset(env()->isolate(), after);
117
15870
  js_promise_hooks_[3].Reset(env()->isolate(), resolve);
118
32073
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
119
16203
    if (it->IsEmpty()) {
120
      contexts_.erase(it--);
121
      continue;
122
    }
123
32406
    PersistentToLocal::Weak(env()->isolate(), *it)
124
16203
        ->SetPromiseHooks(init, before, after, resolve);
125
  }
126
15870
}
127
128
219646
inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) {
129
219646
  return env()->isolate_data()->async_wrap_provider(idx);
130
}
131
132
1
inline void AsyncHooks::no_force_checks() {
133
1
  fields_[kCheck] -= 1;
134
1
}
135
136
433713
inline Environment* AsyncHooks::env() {
137
433713
  return Environment::ForAsyncHooks(this);
138
}
139
140
// Remember to keep this code aligned with pushAsyncContext() in JS.
141
794761
inline void AsyncHooks::push_async_context(double async_id,
142
                                           double trigger_async_id,
143
                                           v8::Local<v8::Object> resource) {
144
  // Since async_hooks is experimental, do only perform the check
145
  // when async_hooks is enabled.
146
794761
  if (fields_[kCheck] > 0) {
147
794758
    CHECK_GE(async_id, -1);
148
794758
    CHECK_GE(trigger_async_id, -1);
149
  }
150
151
794761
  uint32_t offset = fields_[kStackLength];
152
794761
  if (offset * 2 >= async_ids_stack_.Length())
153
4
    grow_async_ids_stack();
154
794761
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
155
794761
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
156
794761
  fields_[kStackLength] += 1;
157
794761
  async_id_fields_[kExecutionAsyncId] = async_id;
158
794761
  async_id_fields_[kTriggerAsyncId] = trigger_async_id;
159
160
#ifdef DEBUG
161
  for (uint32_t i = offset; i < native_execution_async_resources_.size(); i++)
162
    CHECK(native_execution_async_resources_[i].IsEmpty());
163
#endif
164
165
  // When this call comes from JS (as a way of increasing the stack size),
166
  // `resource` will be empty, because JS caches these values anyway.
167
794761
  if (!resource.IsEmpty()) {
168
794757
    native_execution_async_resources_.resize(offset + 1);
169
    // Caveat: This is a v8::Local<> assignment, we do not keep a v8::Global<>!
170
794757
    native_execution_async_resources_[offset] = resource;
171
  }
172
794761
}
173
174
// Remember to keep this code aligned with popAsyncContext() in JS.
175
794375
inline bool AsyncHooks::pop_async_context(double async_id) {
176
  // In case of an exception then this may have already been reset, if the
177
  // stack was multiple MakeCallback()'s deep.
178
794375
  if (UNLIKELY(fields_[kStackLength] == 0)) return false;
179
180
  // Ask for the async_id to be restored as a check that the stack
181
  // hasn't been corrupted.
182
  // Since async_hooks is experimental, do only perform the check
183
  // when async_hooks is enabled.
184
1586649
  if (UNLIKELY(fields_[kCheck] > 0 &&
185

1586649
               async_id_fields_[kExecutionAsyncId] != async_id)) {
186
4
    FailWithCorruptedAsyncStack(async_id);
187
  }
188
189
793322
  uint32_t offset = fields_[kStackLength] - 1;
190
793322
  async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
191
793322
  async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
192
793322
  fields_[kStackLength] = offset;
193
194
1586644
  if (LIKELY(offset < native_execution_async_resources_.size() &&
195

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

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

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

1604394
  return a.fn_ == b.fn_ && a.arg_ == b.arg_;
1203
}
1204
1205
541
BaseObject* CleanupHookCallback::GetBaseObject() const {
1206
541
  if (fn_ == BaseObject::DeleteMe)
1207
513
    return static_cast<BaseObject*>(arg_);
1208
  else
1209
28
    return nullptr;
1210
}
1211
1212
template <typename T>
1213
48
void Environment::ForEachBaseObject(T&& iterator) {
1214
1130
  for (const auto& hook : cleanup_hooks_) {
1215
1082
    BaseObject* obj = hook.GetBaseObject();
1216
1082
    if (obj != nullptr)
1217
1026
      iterator(obj);
1218
  }
1219
}
1220
1221
template <typename T>
1222
6
void Environment::ForEachBindingData(T&& iterator) {
1223
  BindingDataStore* map = static_cast<BindingDataStore*>(
1224
12
      context()->GetAlignedPointerFromEmbedderData(
1225
          ContextEmbedderIndex::kBindingListIndex));
1226
  DCHECK_NOT_NULL(map);
1227
30
  for (auto& it : *map) {
1228
24
    iterator(it.first, it.second);
1229
  }
1230
6
}
1231
1232
2847452
void Environment::modify_base_object_count(int64_t delta) {
1233
2847452
  base_object_count_ += delta;
1234
2847452
}
1235
1236
14
int64_t Environment::base_object_created_after_bootstrap() const {
1237
14
  return base_object_count_ - base_object_created_by_bootstrap_;
1238
}
1239
1240
2
int64_t Environment::base_object_count() const {
1241
2
  return base_object_count_;
1242
}
1243
1244
17
void Environment::set_main_utf16(std::unique_ptr<v8::String::Value> str) {
1245
17
  CHECK(!main_utf16_);
1246
17
  main_utf16_ = std::move(str);
1247
17
}
1248
1249
1215
void Environment::set_process_exit_handler(
1250
    std::function<void(Environment*, int)>&& handler) {
1251
1215
  process_exit_handler_ = std::move(handler);
1252
1215
}
1253
1254
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1255
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1256
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1257
#define V(TypeName, PropertyName)                                             \
1258
  inline                                                                      \
1259
  v8::Local<TypeName> IsolateData::PropertyName() const {                     \
1260
    return PropertyName ## _ .Get(isolate_);                                  \
1261
  }
1262
43781
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1263
966936
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1264
8293211
  PER_ISOLATE_STRING_PROPERTIES(VS)
1265
#undef V
1266
#undef VS
1267
#undef VY
1268
#undef VP
1269
1270
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1271
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1272
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1273
#define V(TypeName, PropertyName)                                             \
1274
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1275
    return isolate_data()->PropertyName();                                    \
1276
  }
1277
43781
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1278
840537
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1279
11934996
  PER_ISOLATE_STRING_PROPERTIES(VS)
1280
#undef V
1281
#undef VS
1282
#undef VY
1283
#undef VP
1284
1285
#define V(PropertyName, TypeName)                                             \
1286
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1287
    return PersistentToLocal::Strong(PropertyName ## _);                      \
1288
  }                                                                           \
1289
  inline void Environment::set_ ## PropertyName(v8::Local<TypeName> value) {  \
1290
    PropertyName ## _.Reset(isolate(), value);                                \
1291
  }
1292
1351418
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1293
6238673
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1294
#undef V
1295
1296
9400406
v8::Local<v8::Context> Environment::context() const {
1297
9400406
  return PersistentToLocal::Strong(context_);
1298
}
1299
1300
}  // namespace node
1301
1302
// These two files depend on each other. Including base_object-inl.h after this
1303
// file is the easiest way to avoid issues with that circular dependency.
1304
#include "base_object-inl.h"
1305
1306
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1307
1308
#endif  // SRC_ENV_INL_H_