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: 566 573 98.8 %
Date: 2020-07-19 22:14:24 Branches: 96 124 77.4 %

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
867988
inline uv_loop_t* IsolateData::event_loop() const {
49
867988
  return event_loop_;
50
}
51
52
737928
inline NodeArrayBufferAllocator* IsolateData::node_allocator() const {
53
737928
  return node_allocator_;
54
}
55
56
46901
inline MultiIsolatePlatform* IsolateData::platform() const {
57
46901
  return platform_;
58
}
59
60
355
inline void IsolateData::set_worker_context(worker::Worker* context) {
61
355
  CHECK_NULL(worker_context_);  // Should be set only once.
62
355
  worker_context_ = context;
63
355
}
64
65
19666
inline worker::Worker* IsolateData::worker_context() const {
66
19666
  return worker_context_;
67
}
68
69
193431
inline v8::Local<v8::String> IsolateData::async_wrap_provider(int index) const {
70
386862
  return async_wrap_providers_[index].Get(isolate_);
71
}
72
73
4187157
inline AliasedUint32Array& AsyncHooks::fields() {
74
4187157
  return fields_;
75
}
76
77
2755812
inline AliasedFloat64Array& AsyncHooks::async_id_fields() {
78
2755812
  return async_id_fields_;
79
}
80
81
384
inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
82
384
  return async_ids_stack_;
83
}
84
85
884821
v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() {
86
1769642
  if (UNLIKELY(js_execution_async_resources_.IsEmpty())) {
87
384
    js_execution_async_resources_.Reset(
88
768
        env()->isolate(), v8::Array::New(env()->isolate()));
89
  }
90
884821
  return PersistentToLocal::Strong(js_execution_async_resources_);
91
}
92
93
488
v8::Local<v8::Object> AsyncHooks::native_execution_async_resource(size_t i) {
94
488
  if (i >= native_execution_async_resources_.size()) return {};
95
488
  return PersistentToLocal::Strong(native_execution_async_resources_[i]);
96
}
97
98
193377
inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) {
99
193377
  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
1130583
inline Environment* AsyncHooks::env() {
107
1130583
  return Environment::ForAsyncHooks(this);
108
}
109
110
// Remember to keep this code aligned with pushAsyncContext() in JS.
111
869926
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
869926
  if (fields_[kCheck] > 0) {
117
869949
    CHECK_GE(async_id, -1);
118
869949
    CHECK_GE(trigger_async_id, -1);
119
  }
120
121
869957
  uint32_t offset = fields_[kStackLength];
122
869953
  if (offset * 2 >= async_ids_stack_.Length())
123
4
    grow_async_ids_stack();
124
869951
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
125
869953
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
126
869953
  fields_[kStackLength] += 1;
127
869955
  async_id_fields_[kExecutionAsyncId] = async_id;
128
869954
  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
869947
  if (!resource.IsEmpty()) {
140
869947
    native_execution_async_resources_.resize(offset + 1);
141
869835
    native_execution_async_resources_[offset].Reset(env()->isolate(), resource);
142
  }
143
869949
}
144
145
// Remember to keep this code aligned with popAsyncContext() in JS.
146
869517
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
869517
  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

868822
  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
868817
  uint32_t offset = fields_[kStackLength] - 1;
171
868819
  async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
172
868817
  async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
173
868817
  fields_[kStackLength] = offset;
174
175

1737634
  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
868815
    native_execution_async_resources_.resize(offset);
185
1737634
    if (native_execution_async_resources_.size() <
186

945429
            native_execution_async_resources_.capacity() / 2 &&
187
76612
        native_execution_async_resources_.size() > 16) {
188
      native_execution_async_resources_.shrink_to_fit();
189
    }
190
  }
191
192
1737633
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
193
31244
    v8::HandleScope handle_scope(env()->isolate());
194
46866
    USE(js_execution_async_resources()->Set(
195
        env()->context(),
196
        env()->length_string(),
197
78109
        v8::Integer::NewFromUnsigned(env()->isolate(), offset)));
198
  }
199
200
868815
  return fields_[kStackLength] > 0;
201
}
202
203
1640
void AsyncHooks::clear_async_id_stack() {
204
1640
  v8::Isolate* isolate = env()->isolate();
205
3280
  v8::HandleScope handle_scope(isolate);
206
3280
  if (!js_execution_async_resources_.IsEmpty()) {
207
3768
    USE(PersistentToLocal::Strong(js_execution_async_resources_)->Set(
208
        env()->context(),
209
        env()->length_string(),
210
6280
        v8::Integer::NewFromUnsigned(isolate, 0)));
211
  }
212
1640
  native_execution_async_resources_.clear();
213
1640
  native_execution_async_resources_.shrink_to_fit();
214
215
1640
  async_id_fields_[kExecutionAsyncId] = 0;
216
1640
  async_id_fields_[kTriggerAsyncId] = 0;
217
1640
  fields_[kStackLength] = 0;
218
1640
}
219
220
// The DefaultTriggerAsyncIdScope(AsyncWrap*) constructor is defined in
221
// async_wrap-inl.h to avoid a circular dependency.
222
223
639900
inline AsyncHooks::DefaultTriggerAsyncIdScope ::DefaultTriggerAsyncIdScope(
224
639900
    Environment* env, double default_trigger_async_id)
225
639900
    : async_hooks_(env->async_hooks()) {
226
639900
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
227
639900
    CHECK_GE(default_trigger_async_id, 0);
228
  }
229
230
639900
  old_default_trigger_async_id_ =
231
1279800
    async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
232
639900
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
233
639900
    default_trigger_async_id;
234
639900
}
235
236
1279798
inline AsyncHooks::DefaultTriggerAsyncIdScope ::~DefaultTriggerAsyncIdScope() {
237
639899
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
238
1279798
    old_default_trigger_async_id_;
239
639899
}
240
241
1130564
Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) {
242
1130564
  return ContainerOf(&Environment::async_hooks_, hooks);
243
}
244
245
869332
inline size_t Environment::async_callback_scope_depth() const {
246
869332
  return async_callback_scope_depth_;
247
}
248
249
870121
inline void Environment::PushAsyncCallbackScope() {
250
870121
  async_callback_scope_depth_++;
251
870121
}
252
253
869740
inline void Environment::PopAsyncCallbackScope() {
254
869740
  async_callback_scope_depth_--;
255
869740
}
256
257
384
inline AliasedUint32Array& ImmediateInfo::fields() {
258
384
  return fields_;
259
}
260
261
456926
inline uint32_t ImmediateInfo::count() const {
262
456926
  return fields_[kCount];
263
}
264
265
536866
inline uint32_t ImmediateInfo::ref_count() const {
266
536866
  return fields_[kRefCount];
267
}
268
269
32304
inline bool ImmediateInfo::has_outstanding() const {
270
32304
  return fields_[kHasOutstanding] == 1;
271
}
272
273
34581
inline void ImmediateInfo::ref_count_inc(uint32_t increment) {
274
34581
  fields_[kRefCount] += increment;
275
34581
}
276
277
470581
inline void ImmediateInfo::ref_count_dec(uint32_t decrement) {
278
470581
  fields_[kRefCount] -= decrement;
279
470592
}
280
281
384
inline AliasedUint8Array& TickInfo::fields() {
282
384
  return fields_;
283
}
284
285
1372279
inline bool TickInfo::has_tick_scheduled() const {
286
1372279
  return fields_[kHasTickScheduled] == 1;
287
}
288
289
199357
inline bool TickInfo::has_rejection_to_warn() const {
290
199357
  return fields_[kHasRejectionToWarn] == 1;
291
}
292
293
5901
inline void Environment::AssignToContext(v8::Local<v8::Context> context,
294
                                         const ContextInfo& info) {
295
5901
  context->SetAlignedPointerInEmbedderData(
296
5901
      ContextEmbedderIndex::kEnvironment, this);
297
  // Used by Environment::GetCurrent to know that we are on a node context.
298
11802
  context->SetAlignedPointerInEmbedderData(
299
5901
    ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr);
300
  // Used to retrieve bindings
301
5901
  context->SetAlignedPointerInEmbedderData(
302
11802
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
303
304
#if HAVE_INSPECTOR
305
5901
  inspector_agent()->ContextCreated(context, info);
306
#endif  // HAVE_INSPECTOR
307
5901
}
308
309
887990
inline Environment* Environment::GetCurrent(v8::Isolate* isolate) {
310
887990
  if (UNLIKELY(!isolate->InContext())) return nullptr;
311
1774635
  v8::HandleScope handle_scope(isolate);
312
887318
  return GetCurrent(isolate->GetCurrentContext());
313
}
314
315
7239843
inline Environment* Environment::GetCurrent(v8::Local<v8::Context> context) {
316
7239843
  if (UNLIKELY(context.IsEmpty())) {
317
1
    return nullptr;
318
  }
319
7239842
  if (UNLIKELY(context->GetNumberOfEmbedderDataFields() <=
320
               ContextEmbedderIndex::kContextTag)) {
321
11
    return nullptr;
322
  }
323
14479726
  if (UNLIKELY(context->GetAlignedPointerFromEmbedderData(
324
                   ContextEmbedderIndex::kContextTag) !=
325
               Environment::kNodeContextTagPtr)) {
326
    return nullptr;
327
  }
328
  return static_cast<Environment*>(
329
7239863
      context->GetAlignedPointerFromEmbedderData(
330
7239863
          ContextEmbedderIndex::kEnvironment));
331
}
332
333
4557456
inline Environment* Environment::GetCurrent(
334
    const v8::FunctionCallbackInfo<v8::Value>& info) {
335
4557456
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
336
}
337
338
template <typename T>
339
1533135
inline Environment* Environment::GetCurrent(
340
    const v8::PropertyCallbackInfo<T>& info) {
341
1533135
  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
569195
inline T* Environment::GetBindingData(
351
    const v8::FunctionCallbackInfo<v8::Value>& info) {
352
569195
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
353
}
354
355
template <typename T>
356
569196
inline T* Environment::GetBindingData(v8::Local<v8::Context> context) {
357
  BindingDataStore* map = static_cast<BindingDataStore*>(
358
569196
      context->GetAlignedPointerFromEmbedderData(
359
569196
          ContextEmbedderIndex::kBindingListIndex));
360
  DCHECK_NOT_NULL(map);
361
569196
  auto it = map->find(T::binding_data_name);
362
569196
  if (UNLIKELY(it == map->end())) return nullptr;
363
569196
  T* result = static_cast<T*>(it->second.get());
364
  DCHECK_NOT_NULL(result);
365
  DCHECK_EQ(result->env(), GetCurrent(context));
366
569196
  return result;
367
}
368
369
template <typename T>
370
7348
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
14696
  BaseObjectPtr<T> item = MakeDetachedBaseObject<T>(this, target);
376
  BindingDataStore* map = static_cast<BindingDataStore*>(
377
7348
      context->GetAlignedPointerFromEmbedderData(
378
7348
          ContextEmbedderIndex::kBindingListIndex));
379
  DCHECK_NOT_NULL(map);
380
7348
  auto result = map->emplace(T::binding_data_name, item);
381
7348
  CHECK(result.second);
382
  DCHECK_EQ(GetBindingData<T>(context), item.get());
383
14696
  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
32196995
inline v8::Isolate* Environment::isolate() const {
391
32196995
  return isolate_;
392
}
393
394
4685
inline Environment* Environment::from_timer_handle(uv_timer_t* handle) {
395
4685
  return ContainerOf(&Environment::timer_handle_, handle);
396
}
397
398
23025
inline uv_timer_t* Environment::timer_handle() {
399
23025
  return &timer_handle_;
400
}
401
402
456924
inline Environment* Environment::from_immediate_check_handle(
403
    uv_check_t* handle) {
404
456924
  return ContainerOf(&Environment::immediate_check_handle_, handle);
405
}
406
407
21108
inline uv_check_t* Environment::immediate_check_handle() {
408
21108
  return &immediate_check_handle_;
409
}
410
411
498580
inline uv_idle_t* Environment::immediate_idle_handle() {
412
498580
  return &immediate_idle_handle_;
413
}
414
415
21108
inline void Environment::RegisterHandleCleanup(uv_handle_t* handle,
416
                                               HandleCleanupCb cb,
417
                                               void* arg) {
418
21108
  handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg});
419
21108
}
420
421
template <typename T, typename OnCloseCallback>
422
23661
inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) {
423
23661
  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
23661
  handle->data = new CloseData { this, callback, handle->data };
435
94643
  uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
436
47315
    std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) };
437
23659
    data->env->handle_cleanup_waiting_--;
438
23659
    handle->data = data->original_data;
439
23659
    data->callback(reinterpret_cast<T*>(handle));
440
23659
  });
441
23657
}
442
443
87920
void Environment::IncreaseWaitingRequestCounter() {
444
87920
  request_waiting_++;
445
87920
}
446
447
87879
void Environment::DecreaseWaitingRequestCounter() {
448
87879
  request_waiting_--;
449
87879
  CHECK_GE(request_waiting_, 0);
450
87879
}
451
452
862682
inline uv_loop_t* Environment::event_loop() const {
453
862682
  return isolate_data()->event_loop();
454
}
455
456
153
inline void Environment::TryLoadAddon(
457
    const char* filename,
458
    int flags,
459
    const std::function<bool(binding::DLib*)>& was_loaded) {
460
153
  loaded_addons_.emplace_back(filename, flags);
461
153
  if (!was_loaded(&loaded_addons_.back())) {
462
8
    loaded_addons_.pop_back();
463
  }
464
153
}
465
466
#if HAVE_INSPECTOR
467
41184
inline bool Environment::is_in_inspector_console_call() const {
468
41184
  return is_in_inspector_console_call_;
469
}
470
471
82366
inline void Environment::set_is_in_inspector_console_call(bool value) {
472
82366
  is_in_inspector_console_call_ = value;
473
82366
}
474
#endif
475
476
6201280
inline AsyncHooks* Environment::async_hooks() {
477
6201280
  return &async_hooks_;
478
}
479
480
1531644
inline ImmediateInfo* Environment::immediate_info() {
481
1531644
  return &immediate_info_;
482
}
483
484
686536
inline TickInfo* Environment::tick_info() {
485
686536
  return &tick_info_;
486
}
487
488
166228
inline uint64_t Environment::timer_base() const {
489
166228
  return timer_base_;
490
}
491
492
1548584
inline std::shared_ptr<KVStore> Environment::env_vars() {
493
1548584
  return env_vars_;
494
}
495
496
5643
inline void Environment::set_env_vars(std::shared_ptr<KVStore> env_vars) {
497
5643
  env_vars_ = env_vars;
498
5643
}
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
9027
inline void Environment::set_trace_sync_io(bool value) {
509
9027
  trace_sync_io_ = value;
510
9027
}
511
512
27
inline bool Environment::abort_on_uncaught_exception() const {
513
27
  return options_->abort_on_uncaught_exception;
514
}
515
516
inline void Environment::set_abort_on_uncaught_exception(bool value) {
517
  options_->abort_on_uncaught_exception = value;
518
}
519
520
415
inline AliasedUint32Array& Environment::should_abort_on_uncaught_toggle() {
521
415
  return should_abort_on_uncaught_toggle_;
522
}
523
524
1634602
inline AliasedInt32Array& Environment::stream_base_state() {
525
1634602
  return stream_base_state_;
526
}
527
528
34077
inline uint32_t Environment::get_next_module_id() {
529
34077
  return module_id_counter_++;
530
}
531
1916
inline uint32_t Environment::get_next_script_id() {
532
1916
  return script_id_counter_++;
533
}
534
27029
inline uint32_t Environment::get_next_function_id() {
535
27029
  return function_id_counter_++;
536
}
537
538
69864
ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope(
539
69864
    Environment* env)
540
69864
    : env_(env) {
541
69864
  env_->PushShouldNotAbortOnUncaughtScope();
542
69866
}
543
544
139729
ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() {
545
69864
  Close();
546
69865
}
547
548
70044
void ShouldNotAbortOnUncaughtScope::Close() {
549
70044
  if (env_ != nullptr) {
550
69865
    env_->PopShouldNotAbortOnUncaughtScope();
551
69865
    env_ = nullptr;
552
  }
553
70044
}
554
555
69864
inline void Environment::PushShouldNotAbortOnUncaughtScope() {
556
69864
  should_not_abort_scope_counter_++;
557
69864
}
558
559
69864
inline void Environment::PopShouldNotAbortOnUncaughtScope() {
560
69864
  should_not_abort_scope_counter_--;
561
69864
}
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
199494
inline std::vector<double>* Environment::destroy_async_id_list() {
568
199494
  return &destroy_async_id_list_;
569
}
570
571
193958
inline double Environment::new_async_id() {
572
193958
  async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
573
193958
  return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
574
}
575
576
207712
inline double Environment::execution_async_id() {
577
207712
  return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId];
578
}
579
580
46147
inline double Environment::trigger_async_id() {
581
46147
  return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId];
582
}
583
584
193955
inline double Environment::get_default_trigger_async_id() {
585
  double default_trigger_async_id =
586
193955
    async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
587
  // If defaultTriggerAsyncId isn't set, use the executionAsyncId
588
193955
  if (default_trigger_async_id < 0)
589
160951
    default_trigger_async_id = execution_async_id();
590
193955
  return default_trigger_async_id;
591
}
592
593
58111
inline std::shared_ptr<EnvironmentOptions> Environment::options() {
594
58111
  return options_;
595
}
596
597
15358
inline const std::vector<std::string>& Environment::argv() {
598
15358
  return argv_;
599
}
600
601
5801
inline const std::vector<std::string>& Environment::exec_argv() {
602
5801
  return exec_argv_;
603
}
604
605
10554
inline const std::string& Environment::exec_path() const {
606
10554
  return exec_path_;
607
}
608
609
#if HAVE_INSPECTOR
610
5271
inline void Environment::set_coverage_directory(const char* dir) {
611
5271
  coverage_directory_ = std::string(dir);
612
5271
}
613
614
5289
inline void Environment::set_coverage_connection(
615
    std::unique_ptr<profiler::V8CoverageConnection> connection) {
616
5289
  CHECK_NULL(coverage_connection_);
617
5291
  std::swap(coverage_connection_, connection);
618
5291
}
619
620
15868
inline profiler::V8CoverageConnection* Environment::coverage_connection() {
621
15868
  return coverage_connection_.get();
622
}
623
624
5250
inline const std::string& Environment::coverage_directory() const {
625
5250
  return coverage_directory_;
626
}
627
628
10
inline void Environment::set_cpu_profiler_connection(
629
    std::unique_ptr<profiler::V8CpuProfilerConnection> connection) {
630
10
  CHECK_NULL(cpu_profiler_connection_);
631
10
  std::swap(cpu_profiler_connection_, connection);
632
10
}
633
634
inline profiler::V8CpuProfilerConnection*
635
5301
Environment::cpu_profiler_connection() {
636
5301
  return cpu_profiler_connection_.get();
637
}
638
639
10
inline void Environment::set_cpu_prof_interval(uint64_t interval) {
640
10
  cpu_prof_interval_ = interval;
641
10
}
642
643
10
inline uint64_t Environment::cpu_prof_interval() const {
644
10
  return cpu_prof_interval_;
645
}
646
647
10
inline void Environment::set_cpu_prof_name(const std::string& name) {
648
10
  cpu_prof_name_ = name;
649
10
}
650
651
10
inline const std::string& Environment::cpu_prof_name() const {
652
10
  return cpu_prof_name_;
653
}
654
655
10
inline void Environment::set_cpu_prof_dir(const std::string& dir) {
656
10
  cpu_prof_dir_ = dir;
657
10
}
658
659
10
inline const std::string& Environment::cpu_prof_dir() const {
660
10
  return cpu_prof_dir_;
661
}
662
663
10
inline void Environment::set_heap_profiler_connection(
664
    std::unique_ptr<profiler::V8HeapProfilerConnection> connection) {
665
10
  CHECK_NULL(heap_profiler_connection_);
666
10
  std::swap(heap_profiler_connection_, connection);
667
10
}
668
669
inline profiler::V8HeapProfilerConnection*
670
5291
Environment::heap_profiler_connection() {
671
5291
  return heap_profiler_connection_.get();
672
}
673
674
10
inline void Environment::set_heap_prof_name(const std::string& name) {
675
10
  heap_prof_name_ = name;
676
10
}
677
678
10
inline const std::string& Environment::heap_prof_name() const {
679
10
  return heap_prof_name_;
680
}
681
682
10
inline void Environment::set_heap_prof_dir(const std::string& dir) {
683
10
  heap_prof_dir_ = dir;
684
10
}
685
686
10
inline const std::string& Environment::heap_prof_dir() const {
687
10
  return heap_prof_dir_;
688
}
689
690
10
inline void Environment::set_heap_prof_interval(uint64_t interval) {
691
10
  heap_prof_interval_ = interval;
692
10
}
693
694
10
inline uint64_t Environment::heap_prof_interval() const {
695
10
  return heap_prof_interval_;
696
}
697
698
#endif  // HAVE_INSPECTOR
699
700
inline
701
10707
std::shared_ptr<ExclusiveAccess<HostPort>> Environment::inspector_host_port() {
702
10707
  return inspector_host_port_;
703
}
704
705
55758
inline std::shared_ptr<PerIsolateOptions> IsolateData::options() {
706
55758
  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
56935
void Environment::SetImmediate(Fn&& cb, CallbackFlags::Flags flags) {
716
113870
  auto callback = native_immediates_.CreateCallback(std::move(cb), flags);
717
56935
  native_immediates_.Push(std::move(callback));
718
719


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


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

1166
    if (task_queues_async_initialized_)
734
884
      uv_async_send(&task_queues_async_);
735
  }
736
1166
}
737
738
template <typename Fn>
739
7167
void Environment::RequestInterrupt(Fn&& cb) {
740
  auto callback = native_immediates_interrupts_.CreateCallback(
741
14336
      std::move(cb), CallbackFlags::kRefed);
742
  {
743
14337
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
744
7168
    native_immediates_interrupts_.Push(std::move(callback));
745
7169
    if (task_queues_async_initialized_)
746
1752
      uv_async_send(&task_queues_async_);
747
  }
748
7169
  RequestInterruptFromV8();
749
7169
}
750
751
3141458
inline bool Environment::can_call_into_js() const {
752

3141458
  return can_call_into_js_ && !is_stopping();
753
}
754
755
923
inline void Environment::set_can_call_into_js(bool can_call_into_js) {
756
923
  can_call_into_js_ = can_call_into_js;
757
924
}
758
759
1675022
inline bool Environment::has_run_bootstrapping_code() const {
760
1675022
  return has_run_bootstrapping_code_;
761
}
762
763
5304
inline void Environment::set_has_run_bootstrapping_code(bool value) {
764
5304
  has_run_bootstrapping_code_ = value;
765
5304
}
766
767
19
inline bool Environment::has_serialized_options() const {
768
19
  return has_serialized_options_;
769
}
770
771
5277
inline void Environment::set_has_serialized_options(bool value) {
772
5277
  has_serialized_options_ = value;
773
5277
}
774
775
14063
inline bool Environment::is_main_thread() const {
776
14063
  return worker_context() == nullptr;
777
}
778
779
5277
inline bool Environment::should_not_register_esm_loader() const {
780
5277
  return flags_ & EnvironmentFlags::kNoRegisterESMLoader;
781
}
782
783
16324
inline bool Environment::owns_process_state() const {
784
16324
  return flags_ & EnvironmentFlags::kOwnsProcessState;
785
}
786
787
5301
inline bool Environment::owns_inspector() const {
788
5301
  return flags_ & EnvironmentFlags::kOwnsInspector;
789
}
790
791
95668
inline bool Environment::tracks_unmanaged_fds() const {
792
95668
  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
929
bool Environment::source_maps_enabled() const {
816
929
  return source_maps_enabled_;
817
}
818
819
9730
inline uint64_t Environment::thread_id() const {
820
9730
  return thread_id_;
821
}
822
823
19666
inline worker::Worker* Environment::worker_context() const {
824
19666
  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
587
inline void Environment::remove_sub_worker_context(worker::Worker* context) {
832
587
  sub_worker_contexts_.erase(context);
833
587
}
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
144
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
845
  else
846
960
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
847
1104
}
848
849
4701753
inline bool Environment::is_stopping() const {
850
4701753
  return is_stopping_.load();
851
}
852
853
4894
inline void Environment::set_stopping(bool value) {
854
4894
  is_stopping_.store(value);
855
4896
}
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
40289
inline performance::PerformanceState* Environment::performance_state() {
871
40289
  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
5805927
inline IsolateData* Environment::isolate_data() const {
880
5805927
  return isolate_data_;
881
}
882
883
std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>*
884
666104
    Environment::released_allocated_buffers() {
885
666104
  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
13
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
13
      UVException(isolate(), errorno, syscall, message, path, dest));
922
13
}
923
924
inline v8::Local<v8::FunctionTemplate>
925
1177962
    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
1177962
                                   signature, 0, behavior, side_effect_type);
931
}
932
933
414403
inline void Environment::SetMethod(v8::Local<v8::Object> that,
934
                                   const char* name,
935
                                   v8::FunctionCallback callback) {
936
414403
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
937
  v8::Local<v8::Function> function =
938
828801
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
939
                          v8::ConstructorBehavior::kThrow,
940
414398
                          v8::SideEffectType::kHasSideEffect)
941
828798
          ->GetFunction(context)
942
414398
          .ToLocalChecked();
943
  // kInternalized strings are created in the old space.
944
414398
  const v8::NewStringType type = v8::NewStringType::kInternalized;
945
  v8::Local<v8::String> name_string =
946
828799
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
947
828803
  that->Set(context, name_string, function).Check();
948
414402
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
949
414403
}
950
951
48535
inline void Environment::SetMethodNoSideEffect(v8::Local<v8::Object> that,
952
                                               const char* name,
953
                                               v8::FunctionCallback callback) {
954
48535
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
955
  v8::Local<v8::Function> function =
956
97069
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
957
                          v8::ConstructorBehavior::kThrow,
958
48534
                          v8::SideEffectType::kHasNoSideEffect)
959
97069
          ->GetFunction(context)
960
48534
          .ToLocalChecked();
961
  // kInternalized strings are created in the old space.
962
48534
  const v8::NewStringType type = v8::NewStringType::kInternalized;
963
  v8::Local<v8::String> name_string =
964
97069
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
965
97070
  that->Set(context, name_string, function).Check();
966
48535
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
967
48535
}
968
969
504153
inline void Environment::SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
970
                                        const char* name,
971
                                        v8::FunctionCallback callback) {
972
504153
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
973
  v8::Local<v8::FunctionTemplate> t =
974
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
975
504153
                          v8::SideEffectType::kHasSideEffect);
976
  // kInternalized strings are created in the old space.
977
504153
  const v8::NewStringType type = v8::NewStringType::kInternalized;
978
  v8::Local<v8::String> name_string =
979
1008305
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
980
1008305
  that->PrototypeTemplate()->Set(name_string, t);
981
504153
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
982
504153
}
983
984
50150
inline void Environment::SetProtoMethodNoSideEffect(
985
    v8::Local<v8::FunctionTemplate> that,
986
    const char* name,
987
    v8::FunctionCallback callback) {
988
50150
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
989
  v8::Local<v8::FunctionTemplate> t =
990
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
991
50150
                          v8::SideEffectType::kHasNoSideEffect);
992
  // kInternalized strings are created in the old space.
993
50150
  const v8::NewStringType type = v8::NewStringType::kInternalized;
994
  v8::Local<v8::String> name_string =
995
100300
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
996
100300
  that->PrototypeTemplate()->Set(name_string, t);
997
50150
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
998
50150
}
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
635411
void Environment::AddCleanupHook(void (*fn)(void*), void* arg) {
1016
1270825
  auto insertion_info = cleanup_hooks_.emplace(CleanupHookCallback {
1017
635411
    fn, arg, cleanup_hook_counter_++
1018
635413
  });
1019
  // Make sure there was no existing element with these values.
1020
635414
  CHECK_EQ(insertion_info.second, true);
1021
635414
}
1022
1023
622578
void Environment::RemoveCleanupHook(void (*fn)(void*), void* arg) {
1024
622578
  CleanupHookCallback search { fn, arg, 0 };
1025
622574
  cleanup_hooks_.erase(search);
1026
622580
}
1027
1028
1455359
size_t CleanupHookCallback::Hash::operator()(
1029
    const CleanupHookCallback& cb) const {
1030
1455359
  return std::hash<void*>()(cb.arg_);
1031
}
1032
1033
725524
bool CleanupHookCallback::Equal::operator()(
1034
    const CleanupHookCallback& a, const CleanupHookCallback& b) const {
1035

725524
  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
1246403
void Environment::modify_base_object_count(int64_t delta) {
1055
1246403
  base_object_count_ += delta;
1056
1246403
}
1057
1058
10622
int64_t Environment::base_object_count() const {
1059
10622
  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
343
void Environment::set_process_exit_handler(
1068
    std::function<void(Environment*, int)>&& handler) {
1069
343
  process_exit_handler_ = std::move(handler);
1070
343
}
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
65016
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1081
548050
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1082
6957690
  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
32507
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1096
273664
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1097
3474434
  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
627157
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1111
2996559
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1112
#undef V
1113
1114
19171953
v8::Local<v8::Context> Environment::context() const {
1115
19171953
  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_