GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env-inl.h Lines: 656 672 97.6 %
Date: 2021-12-02 04:14:02 Branches: 115 146 78.8 %

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

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

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

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

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

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