GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env-inl.h Lines: 628 644 97.5 %
Date: 2021-09-17 04:12:37 Branches: 110 138 79.7 %

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 "util-inl.h"
32
#include "uv.h"
33
#include "v8.h"
34
#include "node_perf_common.h"
35
#include "node_context_data.h"
36
37
#include <cstddef>
38
#include <cstdint>
39
40
#include <utility>
41
42
namespace node {
43
44
inline v8::Isolate* IsolateData::isolate() const {
45
  return isolate_;
46
}
47
48
922360
inline uv_loop_t* IsolateData::event_loop() const {
49
922360
  return event_loop_;
50
}
51
52
165173
inline NodeArrayBufferAllocator* IsolateData::node_allocator() const {
53
165173
  return node_allocator_;
54
}
55
56
56012
inline MultiIsolatePlatform* IsolateData::platform() const {
57
56012
  return platform_;
58
}
59
60
570
inline void IsolateData::set_worker_context(worker::Worker* context) {
61
570
  CHECK_NULL(worker_context_);  // Should be set only once.
62
570
  worker_context_ = context;
63
570
}
64
65
13796
inline worker::Worker* IsolateData::worker_context() const {
66
13796
  return worker_context_;
67
}
68
69
201541
inline v8::Local<v8::String> IsolateData::async_wrap_provider(int index) const {
70
201541
  return async_wrap_providers_[index].Get(isolate_);
71
}
72
73
3000460
inline AliasedUint32Array& AsyncHooks::fields() {
74
3000460
  return fields_;
75
}
76
77
1683794
inline AliasedFloat64Array& AsyncHooks::async_id_fields() {
78
1683794
  return async_id_fields_;
79
}
80
81
610
inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
82
610
  return async_ids_stack_;
83
}
84
85
798592
v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() {
86
798592
  if (UNLIKELY(js_execution_async_resources_.IsEmpty())) {
87
610
    js_execution_async_resources_.Reset(
88
1220
        env()->isolate(), v8::Array::New(env()->isolate()));
89
  }
90
798592
  return PersistentToLocal::Strong(js_execution_async_resources_);
91
}
92
93
2402
v8::Local<v8::Object> AsyncHooks::native_execution_async_resource(size_t i) {
94
2402
  if (i >= native_execution_async_resources_.size()) return {};
95
2402
  return PersistentToLocal::Strong(native_execution_async_resources_[i]);
96
}
97
98
2982
inline void AsyncHooks::SetJSPromiseHooks(v8::Local<v8::Function> init,
99
                                          v8::Local<v8::Function> before,
100
                                          v8::Local<v8::Function> after,
101
                                          v8::Local<v8::Function> resolve) {
102
2982
  js_promise_hooks_[0].Reset(env()->isolate(), init);
103
2982
  js_promise_hooks_[1].Reset(env()->isolate(), before);
104
2982
  js_promise_hooks_[2].Reset(env()->isolate(), after);
105
2982
  js_promise_hooks_[3].Reset(env()->isolate(), resolve);
106
6072
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
107
3090
    if (it->IsEmpty()) {
108
      it = contexts_.erase(it);
109
      it--;
110
      continue;
111
    }
112
6180
    PersistentToLocal::Weak(env()->isolate(), *it)
113
3090
        ->SetPromiseHooks(init, before, after, resolve);
114
  }
115
2982
}
116
117
201193
inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) {
118
201193
  return env()->isolate_data()->async_wrap_provider(idx);
119
}
120
121
1
inline void AsyncHooks::no_force_checks() {
122
1
  fields_[kCheck] -= 1;
123
1
}
124
125
1106301
inline Environment* AsyncHooks::env() {
126
1106301
  return Environment::ForAsyncHooks(this);
127
}
128
129
// Remember to keep this code aligned with pushAsyncContext() in JS.
130
773334
inline void AsyncHooks::push_async_context(double async_id,
131
                                           double trigger_async_id,
132
                                           v8::Local<v8::Object> resource) {
133
  // Since async_hooks is experimental, do only perform the check
134
  // when async_hooks is enabled.
135
773334
  if (fields_[kCheck] > 0) {
136
773331
    CHECK_GE(async_id, -1);
137
773331
    CHECK_GE(trigger_async_id, -1);
138
  }
139
140
773334
  uint32_t offset = fields_[kStackLength];
141
773334
  if (offset * 2 >= async_ids_stack_.Length())
142
4
    grow_async_ids_stack();
143
773334
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
144
773334
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
145
773334
  fields_[kStackLength] += 1;
146
773334
  async_id_fields_[kExecutionAsyncId] = async_id;
147
773334
  async_id_fields_[kTriggerAsyncId] = trigger_async_id;
148
149
#ifdef DEBUG
150
  for (uint32_t i = offset; i < native_execution_async_resources_.size(); i++)
151
    CHECK(native_execution_async_resources_[i].IsEmpty());
152
#endif
153
154
  // When this call comes from JS (as a way of increasing the stack size),
155
  // `resource` will be empty, because JS caches these values anyway, and
156
  // we should avoid creating strong global references that might keep
157
  // these JS resource objects alive longer than necessary.
158
773334
  if (!resource.IsEmpty()) {
159
773330
    native_execution_async_resources_.resize(offset + 1);
160
773330
    native_execution_async_resources_[offset].Reset(env()->isolate(), resource);
161
  }
162
773334
}
163
164
// Remember to keep this code aligned with popAsyncContext() in JS.
165
772946
inline bool AsyncHooks::pop_async_context(double async_id) {
166
  // In case of an exception then this may have already been reset, if the
167
  // stack was multiple MakeCallback()'s deep.
168
772946
  if (fields_[kStackLength] == 0) return false;
169
170
  // Ask for the async_id to be restored as a check that the stack
171
  // hasn't been corrupted.
172
  // Since async_hooks is experimental, do only perform the check
173
  // when async_hooks is enabled.
174

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

1543806
             !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
771903
    native_execution_async_resources_.resize(offset);
204
771903
    if (native_execution_async_resources_.size() <
205

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

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

463569
  return a.fn_ == b.fn_ && a.arg_ == b.arg_;
1143
}
1144
1145
467
BaseObject* CleanupHookCallback::GetBaseObject() const {
1146
467
  if (fn_ == BaseObject::DeleteMe)
1147
440
    return static_cast<BaseObject*>(arg_);
1148
  else
1149
27
    return nullptr;
1150
}
1151
1152
template <typename T>
1153
44
void Environment::ForEachBaseObject(T&& iterator) {
1154
978
  for (const auto& hook : cleanup_hooks_) {
1155
934
    BaseObject* obj = hook.GetBaseObject();
1156
934
    if (obj != nullptr)
1157
880
      iterator(obj);
1158
  }
1159
}
1160
1161
template <typename T>
1162
6
void Environment::ForEachBindingData(T&& iterator) {
1163
  BindingDataStore* map = static_cast<BindingDataStore*>(
1164
12
      context()->GetAlignedPointerFromEmbedderData(
1165
          ContextEmbedderIndex::kBindingListIndex));
1166
  DCHECK_NOT_NULL(map);
1167
24
  for (auto& it : *map) {
1168
18
    iterator(it.first, it.second);
1169
  }
1170
6
}
1171
1172
656083
void Environment::modify_base_object_count(int64_t delta) {
1173
656083
  base_object_count_ += delta;
1174
656083
}
1175
1176
14
int64_t Environment::base_object_created_after_bootstrap() const {
1177
14
  return base_object_count_ - base_object_created_by_bootstrap_;
1178
}
1179
1180
2
int64_t Environment::base_object_count() const {
1181
2
  return base_object_count_;
1182
}
1183
1184
17
void Environment::set_main_utf16(std::unique_ptr<v8::String::Value> str) {
1185
17
  CHECK(!main_utf16_);
1186
17
  main_utf16_ = std::move(str);
1187
17
}
1188
1189
557
void Environment::set_process_exit_handler(
1190
    std::function<void(Environment*, int)>&& handler) {
1191
557
  process_exit_handler_ = std::move(handler);
1192
557
}
1193
1194
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1195
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1196
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1197
#define V(TypeName, PropertyName)                                             \
1198
  inline                                                                      \
1199
  v8::Local<TypeName> IsolateData::PropertyName() const {                     \
1200
    return PropertyName ## _ .Get(isolate_);                                  \
1201
  }
1202
41887
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1203
836363
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1204
6032051
  PER_ISOLATE_STRING_PROPERTIES(VS)
1205
#undef V
1206
#undef VS
1207
#undef VY
1208
#undef VP
1209
1210
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1211
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1212
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1213
#define V(TypeName, PropertyName)                                             \
1214
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1215
    return isolate_data()->PropertyName();                                    \
1216
  }
1217
41887
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1218
719212
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1219
8665724
  PER_ISOLATE_STRING_PROPERTIES(VS)
1220
#undef V
1221
#undef VS
1222
#undef VY
1223
#undef VP
1224
1225
#define V(PropertyName, TypeName)                                             \
1226
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1227
    return PersistentToLocal::Strong(PropertyName ## _);                      \
1228
  }                                                                           \
1229
  inline void Environment::set_ ## PropertyName(v8::Local<TypeName> value) {  \
1230
    PropertyName ## _.Reset(isolate(), value);                                \
1231
  }
1232
1219146
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1233
3114124
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1234
#undef V
1235
1236
6744426
v8::Local<v8::Context> Environment::context() const {
1237
6744426
  return PersistentToLocal::Strong(context_);
1238
}
1239
1240
}  // namespace node
1241
1242
// These two files depend on each other. Including base_object-inl.h after this
1243
// file is the easiest way to avoid issues with that circular dependency.
1244
#include "base_object-inl.h"
1245
1246
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1247
1248
#endif  // SRC_ENV_INL_H_