GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/env-inl.h Lines: 569 574 99.1 %
Date: 2020-08-17 22:13:26 Branches: 97 124 78.2 %

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
708176
inline uv_loop_t* IsolateData::event_loop() const {
49
708176
  return event_loop_;
50
}
51
52
674974
inline NodeArrayBufferAllocator* IsolateData::node_allocator() const {
53
674974
  return node_allocator_;
54
}
55
56
45941
inline MultiIsolatePlatform* IsolateData::platform() const {
57
45941
  return platform_;
58
}
59
60
358
inline void IsolateData::set_worker_context(worker::Worker* context) {
61
358
  CHECK_NULL(worker_context_);  // Should be set only once.
62
358
  worker_context_ = context;
63
358
}
64
65
18615
inline worker::Worker* IsolateData::worker_context() const {
66
18615
  return worker_context_;
67
}
68
69
207495
inline v8::Local<v8::String> IsolateData::async_wrap_provider(int index) const {
70
414990
  return async_wrap_providers_[index].Get(isolate_);
71
}
72
73
3932979
inline AliasedUint32Array& AsyncHooks::fields() {
74
3932979
  return fields_;
75
}
76
77
2378056
inline AliasedFloat64Array& AsyncHooks::async_id_fields() {
78
2378056
  return async_id_fields_;
79
}
80
81
387
inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
82
387
  return async_ids_stack_;
83
}
84
85
1096602
v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() {
86
2193204
  if (UNLIKELY(js_execution_async_resources_.IsEmpty())) {
87
387
    js_execution_async_resources_.Reset(
88
774
        env()->isolate(), v8::Array::New(env()->isolate()));
89
  }
90
1096602
  return PersistentToLocal::Strong(js_execution_async_resources_);
91
}
92
93
274
v8::Local<v8::Object> AsyncHooks::native_execution_async_resource(size_t i) {
94
274
  if (i >= native_execution_async_resources_.size()) return {};
95
274
  return PersistentToLocal::Strong(native_execution_async_resources_[i]);
96
}
97
98
207441
inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) {
99
207441
  return env()->isolate_data()->async_wrap_provider(idx);
100
}
101
102
1
inline void AsyncHooks::no_force_checks() {
103
1
  fields_[kCheck] -= 1;
104
1
}
105
106
1354317
inline Environment* AsyncHooks::env() {
107
1354317
  return Environment::ForAsyncHooks(this);
108
}
109
110
// Remember to keep this code aligned with pushAsyncContext() in JS.
111
1082455
inline void AsyncHooks::push_async_context(double async_id,
112
                                           double trigger_async_id,
113
                                           v8::Local<v8::Object> resource) {
114
  // Since async_hooks is experimental, do only perform the check
115
  // when async_hooks is enabled.
116
1082455
  if (fields_[kCheck] > 0) {
117
1082652
    CHECK_GE(async_id, -1);
118
1082652
    CHECK_GE(trigger_async_id, -1);
119
  }
120
121
1082690
  uint32_t offset = fields_[kStackLength];
122
1082705
  if (offset * 2 >= async_ids_stack_.Length())
123
8
    grow_async_ids_stack();
124
1082695
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
125
1082713
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
126
1082708
  fields_[kStackLength] += 1;
127
1082743
  async_id_fields_[kExecutionAsyncId] = async_id;
128
1082726
  async_id_fields_[kTriggerAsyncId] = trigger_async_id;
129
130
#ifdef DEBUG
131
  for (uint32_t i = offset; i < native_execution_async_resources_.size(); i++)
132
    CHECK(native_execution_async_resources_[i].IsEmpty());
133
#endif
134
135
  // When this call comes from JS (as a way of increasing the stack size),
136
  // `resource` will be empty, because JS caches these values anyway, and
137
  // we should avoid creating strong global references that might keep
138
  // these JS resource objects alive longer than necessary.
139
1082715
  if (!resource.IsEmpty()) {
140
1082715
    native_execution_async_resources_.resize(offset + 1);
141
1082680
    native_execution_async_resources_[offset].Reset(env()->isolate(), resource);
142
  }
143
1082727
}
144
145
// Remember to keep this code aligned with popAsyncContext() in JS.
146
1082325
inline bool AsyncHooks::pop_async_context(double async_id) {
147
  // In case of an exception then this may have already been reset, if the
148
  // stack was multiple MakeCallback()'s deep.
149
1082325
  if (fields_[kStackLength] == 0) return false;
150
151
  // Ask for the async_id to be restored as a check that the stack
152
  // hasn't been corrupted.
153
  // Since async_hooks is experimental, do only perform the check
154
  // when async_hooks is enabled.
155

1081317
  if (fields_[kCheck] > 0 && async_id_fields_[kExecutionAsyncId] != async_id) {
156
4
    fprintf(stderr,
157
            "Error: async hook stack has become corrupted ("
158
            "actual: %.f, expected: %.f)\n",
159
            async_id_fields_.GetValue(kExecutionAsyncId),
160
4
            async_id);
161
4
    DumpBacktrace(stderr);
162
4
    fflush(stderr);
163
4
    if (!env()->abort_on_uncaught_exception())
164
4
      exit(1);
165
    fprintf(stderr, "\n");
166
    fflush(stderr);
167
    ABORT_NO_BACKTRACE();
168
  }
169
170
1081310
  uint32_t offset = fields_[kStackLength] - 1;
171
1081308
  async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
172
1081303
  async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
173
1081300
  fields_[kStackLength] = offset;
174
175

2162621
  if (LIKELY(offset < native_execution_async_resources_.size() &&
176
             !native_execution_async_resources_[offset].IsEmpty())) {
177
#ifdef DEBUG
178
    for (uint32_t i = offset + 1;
179
         i < native_execution_async_resources_.size();
180
         i++) {
181
      CHECK(native_execution_async_resources_[i].IsEmpty());
182
    }
183
#endif
184
1081310
    native_execution_async_resources_.resize(offset);
185
2162619
    if (native_execution_async_resources_.size() <
186

1295669
            native_execution_async_resources_.capacity() / 2 &&
187
214356
        native_execution_async_resources_.size() > 16) {
188
      native_execution_async_resources_.shrink_to_fit();
189
    }
190
  }
191
192
2162618
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
193
29810
    v8::HandleScope handle_scope(env()->isolate());
194
44715
    USE(js_execution_async_resources()->Set(
195
        env()->context(),
196
        env()->length_string(),
197
74525
        v8::Integer::NewFromUnsigned(env()->isolate(), offset)));
198
  }
199
200
1081309
  return fields_[kStackLength] > 0;
201
}
202
203
1644
void AsyncHooks::clear_async_id_stack() {
204
1644
  v8::Isolate* isolate = env()->isolate();
205
3288
  v8::HandleScope handle_scope(isolate);
206
3288
  if (!js_execution_async_resources_.IsEmpty()) {
207
3771
    USE(PersistentToLocal::Strong(js_execution_async_resources_)->Set(
208
        env()->context(),
209
        env()->length_string(),
210
6285
        v8::Integer::NewFromUnsigned(isolate, 0)));
211
  }
212
1644
  native_execution_async_resources_.clear();
213
1644
  native_execution_async_resources_.shrink_to_fit();
214
215
1644
  async_id_fields_[kExecutionAsyncId] = 0;
216
1644
  async_id_fields_[kTriggerAsyncId] = 0;
217
1644
  fields_[kStackLength] = 0;
218
1644
}
219
220
// The DefaultTriggerAsyncIdScope(AsyncWrap*) constructor is defined in
221
// async_wrap-inl.h to avoid a circular dependency.
222
223
485476
inline AsyncHooks::DefaultTriggerAsyncIdScope ::DefaultTriggerAsyncIdScope(
224
485476
    Environment* env, double default_trigger_async_id)
225
485476
    : async_hooks_(env->async_hooks()) {
226
485476
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
227
485476
    CHECK_GE(default_trigger_async_id, 0);
228
  }
229
230
485476
  old_default_trigger_async_id_ =
231
970952
    async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
232
485476
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
233
485476
    default_trigger_async_id;
234
485476
}
235
236
970950
inline AsyncHooks::DefaultTriggerAsyncIdScope ::~DefaultTriggerAsyncIdScope() {
237
485475
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
238
970950
    old_default_trigger_async_id_;
239
485475
}
240
241
1354464
Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) {
242
1354464
  return ContainerOf(&Environment::async_hooks_, hooks);
243
}
244
245
1071721
inline size_t Environment::async_callback_scope_depth() const {
246
1071721
  return async_callback_scope_depth_;
247
}
248
249
1081355
inline void Environment::PushAsyncCallbackScope() {
250
1081355
  async_callback_scope_depth_++;
251
1081355
}
252
253
1081279
inline void Environment::PopAsyncCallbackScope() {
254
1081279
  async_callback_scope_depth_--;
255
1081279
}
256
257
387
inline AliasedUint32Array& ImmediateInfo::fields() {
258
387
  return fields_;
259
}
260
261
402658
inline uint32_t ImmediateInfo::count() const {
262
402658
  return fields_[kCount];
263
}
264
265
477629
inline uint32_t ImmediateInfo::ref_count() const {
266
477629
  return fields_[kRefCount];
267
}
268
269
30981
inline bool ImmediateInfo::has_outstanding() const {
270
30981
  return fields_[kHasOutstanding] == 1;
271
}
272
273
32677
inline void ImmediateInfo::ref_count_inc(uint32_t increment) {
274
32677
  fields_[kRefCount] += increment;
275
32677
}
276
277
414922
inline void ImmediateInfo::ref_count_dec(uint32_t decrement) {
278
414922
  fields_[kRefCount] -= decrement;
279
414941
}
280
281
387
inline AliasedUint8Array& TickInfo::fields() {
282
387
  return fields_;
283
}
284
285
2012869
inline bool TickInfo::has_tick_scheduled() const {
286
2012869
  return fields_[kHasTickScheduled] == 1;
287
}
288
289
588495
inline bool TickInfo::has_rejection_to_warn() const {
290
588495
  return fields_[kHasRejectionToWarn] == 1;
291
}
292
293
5350
inline void Environment::AssignToContext(v8::Local<v8::Context> context,
294
                                         const ContextInfo& info) {
295
5350
  context->SetAlignedPointerInEmbedderData(
296
5350
      ContextEmbedderIndex::kEnvironment, this);
297
  // Used by Environment::GetCurrent to know that we are on a node context.
298
10700
  context->SetAlignedPointerInEmbedderData(
299
5350
    ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr);
300
  // Used to retrieve bindings
301
5350
  context->SetAlignedPointerInEmbedderData(
302
10700
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
303
304
#if HAVE_INSPECTOR
305
5350
  inspector_agent()->ContextCreated(context, info);
306
#endif  // HAVE_INSPECTOR
307
5350
}
308
309
1090215
inline Environment* Environment::GetCurrent(v8::Isolate* isolate) {
310
1090215
  if (UNLIKELY(!isolate->InContext())) return nullptr;
311
2179266
  v8::HandleScope handle_scope(isolate);
312
1089828
  return GetCurrent(isolate->GetCurrentContext());
313
}
314
315
6785271
inline Environment* Environment::GetCurrent(v8::Local<v8::Context> context) {
316
6785271
  if (UNLIKELY(context.IsEmpty())) {
317
1
    return nullptr;
318
  }
319
6785270
  if (UNLIKELY(context->GetNumberOfEmbedderDataFields() <=
320
               ContextEmbedderIndex::kContextTag)) {
321
11
    return nullptr;
322
  }
323
13570710
  if (UNLIKELY(context->GetAlignedPointerFromEmbedderData(
324
                   ContextEmbedderIndex::kContextTag) !=
325
               Environment::kNodeContextTagPtr)) {
326
    return nullptr;
327
  }
328
  return static_cast<Environment*>(
329
6785355
      context->GetAlignedPointerFromEmbedderData(
330
6785355
          ContextEmbedderIndex::kEnvironment));
331
}
332
333
4153388
inline Environment* Environment::GetCurrent(
334
    const v8::FunctionCallbackInfo<v8::Value>& info) {
335
4153388
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
336
}
337
338
template <typename T>
339
1232834
inline Environment* Environment::GetCurrent(
340
    const v8::PropertyCallbackInfo<T>& info) {
341
1232834
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
342
}
343
344
template <typename T, typename U>
345
inline T* Environment::GetBindingData(const v8::PropertyCallbackInfo<U>& info) {
346
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
347
}
348
349
template <typename T>
350
536850
inline T* Environment::GetBindingData(
351
    const v8::FunctionCallbackInfo<v8::Value>& info) {
352
536850
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
353
}
354
355
template <typename T>
356
536851
inline T* Environment::GetBindingData(v8::Local<v8::Context> context) {
357
  BindingDataStore* map = static_cast<BindingDataStore*>(
358
536851
      context->GetAlignedPointerFromEmbedderData(
359
536851
          ContextEmbedderIndex::kBindingListIndex));
360
  DCHECK_NOT_NULL(map);
361
536851
  auto it = map->find(T::binding_data_name);
362
536851
  if (UNLIKELY(it == map->end())) return nullptr;
363
536851
  T* result = static_cast<T*>(it->second.get());
364
  DCHECK_NOT_NULL(result);
365
  DCHECK_EQ(result->env(), GetCurrent(context));
366
536851
  return result;
367
}
368
369
template <typename T>
370
6232
inline T* Environment::AddBindingData(
371
    v8::Local<v8::Context> context,
372
    v8::Local<v8::Object> target) {
373
  DCHECK_EQ(GetCurrent(context), this);
374
  // This won't compile if T is not a BaseObject subclass.
375
12464
  BaseObjectPtr<T> item = MakeDetachedBaseObject<T>(this, target);
376
  BindingDataStore* map = static_cast<BindingDataStore*>(
377
6232
      context->GetAlignedPointerFromEmbedderData(
378
6232
          ContextEmbedderIndex::kBindingListIndex));
379
  DCHECK_NOT_NULL(map);
380
6232
  auto result = map->emplace(T::binding_data_name, item);
381
6232
  CHECK(result.second);
382
  DCHECK_EQ(GetBindingData<T>(context), item.get());
383
12464
  return item.get();
384
}
385
386
1
inline Environment* Environment::GetThreadLocalEnv() {
387
1
  return static_cast<Environment*>(uv_key_get(&thread_local_env));
388
}
389
390
29733801
inline v8::Isolate* Environment::isolate() const {
391
29733801
  return isolate_;
392
}
393
394
5193
inline Environment* Environment::from_timer_handle(uv_timer_t* handle) {
395
5193
  return ContainerOf(&Environment::timer_handle_, handle);
396
}
397
398
21630
inline uv_timer_t* Environment::timer_handle() {
399
21630
  return &timer_handle_;
400
}
401
402
402646
inline Environment* Environment::from_immediate_check_handle(
403
    uv_check_t* handle) {
404
402646
  return ContainerOf(&Environment::immediate_check_handle_, handle);
405
}
406
407
19000
inline uv_check_t* Environment::immediate_check_handle() {
408
19000
  return &immediate_check_handle_;
409
}
410
411
443810
inline uv_idle_t* Environment::immediate_idle_handle() {
412
443810
  return &immediate_idle_handle_;
413
}
414
415
19000
inline void Environment::RegisterHandleCleanup(uv_handle_t* handle,
416
                                               HandleCleanupCb cb,
417
                                               void* arg) {
418
19000
  handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg});
419
19000
}
420
421
template <typename T, typename OnCloseCallback>
422
21196
inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) {
423
21196
  handle_cleanup_waiting_++;
424
  static_assert(sizeof(T) >= sizeof(uv_handle_t), "T is a libuv handle");
425
  static_assert(offsetof(T, data) == offsetof(uv_handle_t, data),
426
                "T is a libuv handle");
427
  static_assert(offsetof(T, close_cb) == offsetof(uv_handle_t, close_cb),
428
                "T is a libuv handle");
429
  struct CloseData {
430
    Environment* env;
431
    OnCloseCallback callback;
432
    void* original_data;
433
  };
434
21196
  handle->data = new CloseData { this, callback, handle->data };
435
84785
  uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
436
42394
    std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) };
437
21197
    data->env->handle_cleanup_waiting_--;
438
21197
    handle->data = data->original_data;
439
21197
    data->callback(reinterpret_cast<T*>(handle));
440
21196
  });
441
21195
}
442
443
79401
void Environment::IncreaseWaitingRequestCounter() {
444
79401
  request_waiting_++;
445
79401
}
446
447
79395
void Environment::DecreaseWaitingRequestCounter() {
448
79395
  request_waiting_--;
449
79395
  CHECK_GE(request_waiting_, 0);
450
79395
}
451
452
703400
inline uv_loop_t* Environment::event_loop() const {
453
703400
  return isolate_data()->event_loop();
454
}
455
456
157
inline void Environment::TryLoadAddon(
457
    const char* filename,
458
    int flags,
459
    const std::function<bool(binding::DLib*)>& was_loaded) {
460
157
  loaded_addons_.emplace_back(filename, flags);
461
157
  if (!was_loaded(&loaded_addons_.back())) {
462
8
    loaded_addons_.pop_back();
463
  }
464
157
}
465
466
#if HAVE_INSPECTOR
467
40475
inline bool Environment::is_in_inspector_console_call() const {
468
40475
  return is_in_inspector_console_call_;
469
}
470
471
80948
inline void Environment::set_is_in_inspector_console_call(bool value) {
472
80948
  is_in_inspector_console_call_ = value;
473
80948
}
474
#endif
475
476
6481769
inline AsyncHooks* Environment::async_hooks() {
477
6481769
  return &async_hooks_;
478
}
479
480
1359285
inline ImmediateInfo* Environment::immediate_info() {
481
1359285
  return &immediate_info_;
482
}
483
484
1006854
inline TickInfo* Environment::tick_info() {
485
1006854
  return &tick_info_;
486
}
487
488
49437
inline uint64_t Environment::timer_base() const {
489
49437
  return timer_base_;
490
}
491
492
1244650
inline std::shared_ptr<KVStore> Environment::env_vars() {
493
1244650
  return env_vars_;
494
}
495
496
5118
inline void Environment::set_env_vars(std::shared_ptr<KVStore> env_vars) {
497
5118
  env_vars_ = env_vars;
498
5118
}
499
500
14
inline bool Environment::printed_error() const {
501
14
  return printed_error_;
502
}
503
504
14
inline void Environment::set_printed_error(bool value) {
505
14
  printed_error_ = value;
506
14
}
507
508
8016
inline void Environment::set_trace_sync_io(bool value) {
509
8016
  trace_sync_io_ = value;
510
8016
}
511
512
65
inline bool Environment::abort_on_uncaught_exception() const {
513
65
  return options_->abort_on_uncaught_exception;
514
}
515
516
346
inline void Environment::set_abort_on_uncaught_exception(bool value) {
517
346
  options_->abort_on_uncaught_exception = value;
518
346
}
519
520
417
inline AliasedUint32Array& Environment::should_abort_on_uncaught_toggle() {
521
417
  return should_abort_on_uncaught_toggle_;
522
}
523
524
1298803
inline AliasedInt32Array& Environment::stream_base_state() {
525
1298803
  return stream_base_state_;
526
}
527
528
32056
inline uint32_t Environment::get_next_module_id() {
529
32056
  return module_id_counter_++;
530
}
531
1954
inline uint32_t Environment::get_next_script_id() {
532
1954
  return script_id_counter_++;
533
}
534
25798
inline uint32_t Environment::get_next_function_id() {
535
25798
  return function_id_counter_++;
536
}
537
538
65855
ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope(
539
65855
    Environment* env)
540
65855
    : env_(env) {
541
65855
  env_->PushShouldNotAbortOnUncaughtScope();
542
65856
}
543
544
131709
ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() {
545
65854
  Close();
546
65855
}
547
548
66035
void ShouldNotAbortOnUncaughtScope::Close() {
549
66035
  if (env_ != nullptr) {
550
65854
    env_->PopShouldNotAbortOnUncaughtScope();
551
65855
    env_ = nullptr;
552
  }
553
66036
}
554
555
65855
inline void Environment::PushShouldNotAbortOnUncaughtScope() {
556
65855
  should_not_abort_scope_counter_++;
557
65855
}
558
559
65855
inline void Environment::PopShouldNotAbortOnUncaughtScope() {
560
65855
  should_not_abort_scope_counter_--;
561
65855
}
562
563
1
inline bool Environment::inside_should_not_abort_on_uncaught_scope() const {
564
1
  return should_not_abort_scope_counter_ > 0;
565
}
566
567
333922
inline std::vector<double>* Environment::destroy_async_id_list() {
568
333922
  return &destroy_async_id_list_;
569
}
570
571
208025
inline double Environment::new_async_id() {
572
208025
  async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
573
208025
  return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
574
}
575
576
237336
inline double Environment::execution_async_id() {
577
237336
  return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId];
578
}
579
580
59834
inline double Environment::trigger_async_id() {
581
59834
  return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId];
582
}
583
584
208022
inline double Environment::get_default_trigger_async_id() {
585
  double default_trigger_async_id =
586
208022
    async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
587
  // If defaultTriggerAsyncId isn't set, use the executionAsyncId
588
208022
  if (default_trigger_async_id < 0)
589
166828
    default_trigger_async_id = execution_async_id();
590
208022
  return default_trigger_async_id;
591
}
592
593
49429
inline std::shared_ptr<EnvironmentOptions> Environment::options() {
594
49429
  return options_;
595
}
596
597
13770
inline const std::vector<std::string>& Environment::argv() {
598
13770
  return argv_;
599
}
600
601
5274
inline const std::vector<std::string>& Environment::exec_argv() {
602
5274
  return exec_argv_;
603
}
604
605
9500
inline const std::string& Environment::exec_path() const {
606
9500
  return exec_path_;
607
}
608
609
#if HAVE_INSPECTOR
610
4744
inline void Environment::set_coverage_directory(const char* dir) {
611
4744
  coverage_directory_ = std::string(dir);
612
4744
}
613
614
4763
inline void Environment::set_coverage_connection(
615
    std::unique_ptr<profiler::V8CoverageConnection> connection) {
616
4763
  CHECK_NULL(coverage_connection_);
617
4762
  std::swap(coverage_connection_, connection);
618
4763
}
619
620
14288
inline profiler::V8CoverageConnection* Environment::coverage_connection() {
621
14288
  return coverage_connection_.get();
622
}
623
624
4724
inline const std::string& Environment::coverage_directory() const {
625
4724
  return coverage_directory_;
626
}
627
628
12
inline void Environment::set_cpu_profiler_connection(
629
    std::unique_ptr<profiler::V8CpuProfilerConnection> connection) {
630
12
  CHECK_NULL(cpu_profiler_connection_);
631
12
  std::swap(cpu_profiler_connection_, connection);
632
12
}
633
634
inline profiler::V8CpuProfilerConnection*
635
4784
Environment::cpu_profiler_connection() {
636
4784
  return cpu_profiler_connection_.get();
637
}
638
639
12
inline void Environment::set_cpu_prof_interval(uint64_t interval) {
640
12
  cpu_prof_interval_ = interval;
641
12
}
642
643
12
inline uint64_t Environment::cpu_prof_interval() const {
644
12
  return cpu_prof_interval_;
645
}
646
647
12
inline void Environment::set_cpu_prof_name(const std::string& name) {
648
12
  cpu_prof_name_ = name;
649
12
}
650
651
12
inline const std::string& Environment::cpu_prof_name() const {
652
12
  return cpu_prof_name_;
653
}
654
655
12
inline void Environment::set_cpu_prof_dir(const std::string& dir) {
656
12
  cpu_prof_dir_ = dir;
657
12
}
658
659
12
inline const std::string& Environment::cpu_prof_dir() const {
660
12
  return cpu_prof_dir_;
661
}
662
663
12
inline void Environment::set_heap_profiler_connection(
664
    std::unique_ptr<profiler::V8HeapProfilerConnection> connection) {
665
12
  CHECK_NULL(heap_profiler_connection_);
666
12
  std::swap(heap_profiler_connection_, connection);
667
12
}
668
669
inline profiler::V8HeapProfilerConnection*
670
4772
Environment::heap_profiler_connection() {
671
4772
  return heap_profiler_connection_.get();
672
}
673
674
12
inline void Environment::set_heap_prof_name(const std::string& name) {
675
12
  heap_prof_name_ = name;
676
12
}
677
678
12
inline const std::string& Environment::heap_prof_name() const {
679
12
  return heap_prof_name_;
680
}
681
682
12
inline void Environment::set_heap_prof_dir(const std::string& dir) {
683
12
  heap_prof_dir_ = dir;
684
12
}
685
686
12
inline const std::string& Environment::heap_prof_dir() const {
687
12
  return heap_prof_dir_;
688
}
689
690
12
inline void Environment::set_heap_prof_interval(uint64_t interval) {
691
12
  heap_prof_interval_ = interval;
692
12
}
693
694
12
inline uint64_t Environment::heap_prof_interval() const {
695
12
  return heap_prof_interval_;
696
}
697
698
#endif  // HAVE_INSPECTOR
699
700
inline
701
9652
std::shared_ptr<ExclusiveAccess<HostPort>> Environment::inspector_host_port() {
702
9652
  return inspector_host_port_;
703
}
704
705
51615
inline std::shared_ptr<PerIsolateOptions> IsolateData::options() {
706
51615
  return options_;
707
}
708
709
40
inline void IsolateData::set_options(
710
    std::shared_ptr<PerIsolateOptions> options) {
711
40
  options_ = std::move(options);
712
40
}
713
714
template <typename Fn>
715
54683
void Environment::SetImmediate(Fn&& cb, CallbackFlags::Flags flags) {
716
109366
  auto callback = native_immediates_.CreateCallback(std::move(cb), flags);
717
54683
  native_immediates_.Push(std::move(callback));
718
719


54683
  if (flags & CallbackFlags::kRefed) {
720


32677
    if (immediate_info()->ref_count() == 0)
721
24823
      ToggleImmediateRef(true);
722
32677
    immediate_info()->ref_count_inc(1);
723
  }
724
54683
}
725
726
template <typename Fn>
727
1224
void Environment::SetImmediateThreadsafe(Fn&& cb, CallbackFlags::Flags flags) {
728
  auto callback = native_immediates_threadsafe_.CreateCallback(
729
2448
      std::move(cb), flags);
730
  {
731
2448
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
732
1224
    native_immediates_threadsafe_.Push(std::move(callback));
733

1224
    if (task_queues_async_initialized_)
734
882
      uv_async_send(&task_queues_async_);
735
  }
736
1224
}
737
738
template <typename Fn>
739
6590
void Environment::RequestInterrupt(Fn&& cb) {
740
  auto callback = native_immediates_interrupts_.CreateCallback(
741
13181
      std::move(cb), CallbackFlags::kRefed);
742
  {
743
13182
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
744
6591
    native_immediates_interrupts_.Push(std::move(callback));
745
6591
    if (task_queues_async_initialized_)
746
1709
      uv_async_send(&task_queues_async_);
747
  }
748
6591
  RequestInterruptFromV8();
749
6591
}
750
751
3834961
inline bool Environment::can_call_into_js() const {
752

3834961
  return can_call_into_js_ && !is_stopping();
753
}
754
755
893
inline void Environment::set_can_call_into_js(bool can_call_into_js) {
756
893
  can_call_into_js_ = can_call_into_js;
757
893
}
758
759
1369646
inline bool Environment::has_run_bootstrapping_code() const {
760
1369646
  return has_run_bootstrapping_code_;
761
}
762
763
4777
inline void Environment::set_has_run_bootstrapping_code(bool value) {
764
4777
  has_run_bootstrapping_code_ = value;
765
4777
}
766
767
19
inline bool Environment::has_serialized_options() const {
768
19
  return has_serialized_options_;
769
}
770
771
4750
inline void Environment::set_has_serialized_options(bool value) {
772
4750
  has_serialized_options_ = value;
773
4750
}
774
775
13538
inline bool Environment::is_main_thread() const {
776
13538
  return worker_context() == nullptr;
777
}
778
779
4750
inline bool Environment::should_not_register_esm_loader() const {
780
4750
  return flags_ & EnvironmentFlags::kNoRegisterESMLoader;
781
}
782
783
15250
inline bool Environment::owns_process_state() const {
784
15250
  return flags_ & EnvironmentFlags::kOwnsProcessState;
785
}
786
787
4775
inline bool Environment::owns_inspector() const {
788
4775
  return flags_ & EnvironmentFlags::kOwnsInspector;
789
}
790
791
88833
inline bool Environment::tracks_unmanaged_fds() const {
792
88833
  return flags_ & EnvironmentFlags::kTrackUnmanagedFds;
793
}
794
795
2
bool Environment::filehandle_close_warning() const {
796
2
  return emit_filehandle_warning_;
797
}
798
799
2
void Environment::set_filehandle_close_warning(bool on) {
800
2
  emit_filehandle_warning_ = on;
801
2
}
802
803
181
bool Environment::emit_insecure_umask_warning() const {
804
181
  return emit_insecure_umask_warning_;
805
}
806
807
5
void Environment::set_emit_insecure_umask_warning(bool on) {
808
5
  emit_insecure_umask_warning_ = on;
809
5
}
810
811
13
void Environment::set_source_maps_enabled(bool on) {
812
13
  source_maps_enabled_ = on;
813
13
}
814
815
921
bool Environment::source_maps_enabled() const {
816
921
  return source_maps_enabled_;
817
}
818
819
9191
inline uint64_t Environment::thread_id() const {
820
9191
  return thread_id_;
821
}
822
823
18615
inline worker::Worker* Environment::worker_context() const {
824
18615
  return isolate_data()->worker_context();
825
}
826
827
560
inline void Environment::add_sub_worker_context(worker::Worker* context) {
828
560
  sub_worker_contexts_.insert(context);
829
560
}
830
831
586
inline void Environment::remove_sub_worker_context(worker::Worker* context) {
832
586
  sub_worker_contexts_.erase(context);
833
586
}
834
835
template <typename Fn>
836
22
inline void Environment::ForEachWorker(Fn&& iterator) {
837
22
  for (worker::Worker* w : sub_worker_contexts_) iterator(w);
838
22
}
839
840
1104
inline void Environment::add_refs(int64_t diff) {
841
1104
  task_queues_async_refs_ += diff;
842
1104
  CHECK_GE(task_queues_async_refs_, 0);
843
1104
  if (task_queues_async_refs_ == 0)
844
145
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
845
  else
846
959
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
847
1104
}
848
849
5916233
inline bool Environment::is_stopping() const {
850
5916233
  return is_stopping_.load();
851
}
852
853
4403
inline void Environment::set_stopping(bool value) {
854
4403
  is_stopping_.store(value);
855
4403
}
856
857
1
inline std::list<node_module>* Environment::extra_linked_bindings() {
858
1
  return &extra_linked_bindings_;
859
}
860
861
3
inline node_module* Environment::extra_linked_bindings_head() {
862
4
  return extra_linked_bindings_.size() > 0 ?
863
4
      &extra_linked_bindings_.front() : nullptr;
864
}
865
866
3
inline const Mutex& Environment::extra_linked_bindings_mutex() const {
867
3
  return extra_linked_bindings_mutex_;
868
}
869
870
38718
inline performance::PerformanceState* Environment::performance_state() {
871
38718
  return performance_state_.get();
872
}
873
874
inline std::unordered_map<std::string, uint64_t>*
875
49
    Environment::performance_marks() {
876
49
  return &performance_marks_;
877
}
878
879
5122521
inline IsolateData* Environment::isolate_data() const {
880
5122521
  return isolate_data_;
881
}
882
883
std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>*
884
642014
    Environment::released_allocated_buffers() {
885
642014
  return &released_allocated_buffers_;
886
}
887
888
706
inline void Environment::ThrowError(const char* errmsg) {
889
706
  ThrowError(v8::Exception::Error, errmsg);
890
706
}
891
892
2
inline void Environment::ThrowTypeError(const char* errmsg) {
893
2
  ThrowError(v8::Exception::TypeError, errmsg);
894
2
}
895
896
inline void Environment::ThrowRangeError(const char* errmsg) {
897
  ThrowError(v8::Exception::RangeError, errmsg);
898
}
899
900
708
inline void Environment::ThrowError(
901
    v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
902
    const char* errmsg) {
903
1416
  v8::HandleScope handle_scope(isolate());
904
708
  isolate()->ThrowException(fun(OneByteString(isolate(), errmsg)));
905
708
}
906
907
3
inline void Environment::ThrowErrnoException(int errorno,
908
                                             const char* syscall,
909
                                             const char* message,
910
                                             const char* path) {
911
  isolate()->ThrowException(
912
3
      ErrnoException(isolate(), errorno, syscall, message, path));
913
3
}
914
915
14
inline void Environment::ThrowUVException(int errorno,
916
                                          const char* syscall,
917
                                          const char* message,
918
                                          const char* path,
919
                                          const char* dest) {
920
  isolate()->ThrowException(
921
14
      UVException(isolate(), errorno, syscall, message, path, dest));
922
14
}
923
924
inline v8::Local<v8::FunctionTemplate>
925
1069075
    Environment::NewFunctionTemplate(v8::FunctionCallback callback,
926
                                     v8::Local<v8::Signature> signature,
927
                                     v8::ConstructorBehavior behavior,
928
                                     v8::SideEffectType side_effect_type) {
929
  return v8::FunctionTemplate::New(isolate(), callback, v8::Local<v8::Value>(),
930
1069075
                                   signature, 0, behavior, side_effect_type);
931
}
932
933
376522
inline void Environment::SetMethod(v8::Local<v8::Object> that,
934
                                   const char* name,
935
                                   v8::FunctionCallback callback) {
936
376522
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
937
  v8::Local<v8::Function> function =
938
753178
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
939
                          v8::ConstructorBehavior::kThrow,
940
376588
                          v8::SideEffectType::kHasSideEffect)
941
753178
          ->GetFunction(context)
942
376588
          .ToLocalChecked();
943
  // kInternalized strings are created in the old space.
944
376588
  const v8::NewStringType type = v8::NewStringType::kInternalized;
945
  v8::Local<v8::String> name_string =
946
753180
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
947
753182
  that->Set(context, name_string, function).Check();
948
376590
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
949
376591
}
950
951
46246
inline void Environment::SetMethodNoSideEffect(v8::Local<v8::Object> that,
952
                                               const char* name,
953
                                               v8::FunctionCallback callback) {
954
46246
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
955
  v8::Local<v8::Function> function =
956
92494
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
957
                          v8::ConstructorBehavior::kThrow,
958
46246
                          v8::SideEffectType::kHasNoSideEffect)
959
92494
          ->GetFunction(context)
960
46246
          .ToLocalChecked();
961
  // kInternalized strings are created in the old space.
962
46246
  const v8::NewStringType type = v8::NewStringType::kInternalized;
963
  v8::Local<v8::String> name_string =
964
92493
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
965
92495
  that->Set(context, name_string, function).Check();
966
46248
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
967
46248
}
968
969
454879
inline void Environment::SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
970
                                        const char* name,
971
                                        v8::FunctionCallback callback) {
972
454879
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
973
  v8::Local<v8::FunctionTemplate> t =
974
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
975
454879
                          v8::SideEffectType::kHasSideEffect);
976
  // kInternalized strings are created in the old space.
977
454877
  const v8::NewStringType type = v8::NewStringType::kInternalized;
978
  v8::Local<v8::String> name_string =
979
909756
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
980
909758
  that->PrototypeTemplate()->Set(name_string, t);
981
454879
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
982
454879
}
983
984
45805
inline void Environment::SetProtoMethodNoSideEffect(
985
    v8::Local<v8::FunctionTemplate> that,
986
    const char* name,
987
    v8::FunctionCallback callback) {
988
45805
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
989
  v8::Local<v8::FunctionTemplate> t =
990
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
991
45805
                          v8::SideEffectType::kHasNoSideEffect);
992
  // kInternalized strings are created in the old space.
993
45805
  const v8::NewStringType type = v8::NewStringType::kInternalized;
994
  v8::Local<v8::String> name_string =
995
91610
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
996
91610
  that->PrototypeTemplate()->Set(name_string, t);
997
45805
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
998
45805
}
999
1000
31
inline void Environment::SetInstanceMethod(v8::Local<v8::FunctionTemplate> that,
1001
                                           const char* name,
1002
                                           v8::FunctionCallback callback) {
1003
31
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
1004
  v8::Local<v8::FunctionTemplate> t =
1005
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
1006
31
                          v8::SideEffectType::kHasSideEffect);
1007
  // kInternalized strings are created in the old space.
1008
31
  const v8::NewStringType type = v8::NewStringType::kInternalized;
1009
  v8::Local<v8::String> name_string =
1010
62
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
1011
62
  that->InstanceTemplate()->Set(name_string, t);
1012
31
  t->SetClassName(name_string);
1013
31
}
1014
1015
650378
void Environment::AddCleanupHook(void (*fn)(void*), void* arg) {
1016
1300757
  auto insertion_info = cleanup_hooks_.emplace(CleanupHookCallback {
1017
650378
    fn, arg, cleanup_hook_counter_++
1018
650378
  });
1019
  // Make sure there was no existing element with these values.
1020
650379
  CHECK_EQ(insertion_info.second, true);
1021
650379
}
1022
1023
638416
void Environment::RemoveCleanupHook(void (*fn)(void*), void* arg) {
1024
638416
  CleanupHookCallback search { fn, arg, 0 };
1025
638414
  cleanup_hooks_.erase(search);
1026
638418
}
1027
1028
1478120
size_t CleanupHookCallback::Hash::operator()(
1029
    const CleanupHookCallback& cb) const {
1030
1478120
  return std::hash<void*>()(cb.arg_);
1031
}
1032
1033
736843
bool CleanupHookCallback::Equal::operator()(
1034
    const CleanupHookCallback& a, const CleanupHookCallback& b) const {
1035

736843
  return a.fn_ == b.fn_ && a.arg_ == b.arg_;
1036
}
1037
1038
367
BaseObject* CleanupHookCallback::GetBaseObject() const {
1039
367
  if (fn_ == BaseObject::DeleteMe)
1040
347
    return static_cast<BaseObject*>(arg_);
1041
  else
1042
20
    return nullptr;
1043
}
1044
1045
template <typename T>
1046
19
void Environment::ForEachBaseObject(T&& iterator) {
1047
386
  for (const auto& hook : cleanup_hooks_) {
1048
367
    BaseObject* obj = hook.GetBaseObject();
1049
367
    if (obj != nullptr)
1050
347
      iterator(obj);
1051
  }
1052
19
}
1053
1054
1277638
void Environment::modify_base_object_count(int64_t delta) {
1055
1277638
  base_object_count_ += delta;
1056
1277638
}
1057
1058
9569
int64_t Environment::base_object_count() const {
1059
9569
  return base_object_count_ - initial_base_object_count_;
1060
}
1061
1062
13
void Environment::set_main_utf16(std::unique_ptr<v8::String::Value> str) {
1063
13
  CHECK(!main_utf16_);
1064
13
  main_utf16_ = std::move(str);
1065
13
}
1066
1067
345
void Environment::set_process_exit_handler(
1068
    std::function<void(Environment*, int)>&& handler) {
1069
345
  process_exit_handler_ = std::move(handler);
1070
345
}
1071
1072
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1073
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1074
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1075
#define V(TypeName, PropertyName)                                             \
1076
  inline                                                                      \
1077
  v8::Local<TypeName> IsolateData::PropertyName() const {                     \
1078
    return PropertyName ## _ .Get(isolate_);                                  \
1079
  }
1080
62230
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1081
541410
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1082
6028500
  PER_ISOLATE_STRING_PROPERTIES(VS)
1083
#undef V
1084
#undef VS
1085
#undef VY
1086
#undef VP
1087
1088
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1089
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1090
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1091
#define V(TypeName, PropertyName)                                             \
1092
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1093
    return isolate_data()->PropertyName();                                    \
1094
  }
1095
31115
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1096
270459
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1097
3009363
  PER_ISOLATE_STRING_PROPERTIES(VS)
1098
#undef V
1099
#undef VS
1100
#undef VY
1101
#undef VP
1102
1103
#define V(PropertyName, TypeName)                                             \
1104
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1105
    return PersistentToLocal::Strong(PropertyName ## _);                      \
1106
  }                                                                           \
1107
  inline void Environment::set_ ## PropertyName(v8::Local<TypeName> value) {  \
1108
    PropertyName ## _.Reset(isolate(), value);                                \
1109
  }
1110
599057
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1111
2525409
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1112
#undef V
1113
1114
9746471
v8::Local<v8::Context> Environment::context() const {
1115
9746471
  return PersistentToLocal::Strong(context_);
1116
}
1117
1118
}  // namespace node
1119
1120
// These two files depend on each other. Including base_object-inl.h after this
1121
// file is the easiest way to avoid issues with that circular dependency.
1122
#include "base_object-inl.h"
1123
1124
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1125
1126
#endif  // SRC_ENV_INL_H_