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: 556 562 98.9 %
Date: 2020-06-24 22:13:30 Branches: 79 102 77.5 %

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
708094
inline uv_loop_t* IsolateData::event_loop() const {
49
708094
  return event_loop_;
50
}
51
52
inline bool IsolateData::uses_node_allocator() const {
53
  return uses_node_allocator_;
54
}
55
56
inline v8::ArrayBuffer::Allocator* IsolateData::allocator() const {
57
  return allocator_;
58
}
59
60
675338
inline NodeArrayBufferAllocator* IsolateData::node_allocator() const {
61
675338
  return node_allocator_;
62
}
63
64
45810
inline MultiIsolatePlatform* IsolateData::platform() const {
65
45810
  return platform_;
66
}
67
68
350
inline void IsolateData::set_worker_context(worker::Worker* context) {
69
350
  CHECK_NULL(worker_context_);  // Should be set only once.
70
350
  worker_context_ = context;
71
350
}
72
73
22613
inline worker::Worker* IsolateData::worker_context() const {
74
22613
  return worker_context_;
75
}
76
77
183498
inline v8::Local<v8::String> IsolateData::async_wrap_provider(int index) const {
78
366996
  return async_wrap_providers_[index].Get(isolate_);
79
}
80
81
4703
inline AsyncHooks::AsyncHooks()
82
    : async_ids_stack_(env()->isolate(), 16 * 2),
83
      fields_(env()->isolate(), kFieldsCount),
84
4703
      async_id_fields_(env()->isolate(), kUidFieldsCount) {
85
4703
  clear_async_id_stack();
86
87
  // Always perform async_hooks checks, not just when async_hooks is enabled.
88
  // TODO(AndreasMadsen): Consider removing this for LTS releases.
89
  // See discussion in https://github.com/nodejs/node/pull/15454
90
  // When removing this, do it by reverting the commit. Otherwise the test
91
  // and flag changes won't be included.
92
4703
  fields_[kCheck] = 1;
93
94
  // kDefaultTriggerAsyncId should be -1, this indicates that there is no
95
  // specified default value and it should fallback to the executionAsyncId.
96
  // 0 is not used as the magic value, because that indicates a missing context
97
  // which is different from a default context.
98
4703
  async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
99
100
  // kAsyncIdCounter should start at 1 because that'll be the id the execution
101
  // context during bootstrap (code that runs before entering uv_run()).
102
4703
  async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
103
4703
}
104
2807610
inline AliasedUint32Array& AsyncHooks::fields() {
105
2807610
  return fields_;
106
}
107
108
2209048
inline AliasedFloat64Array& AsyncHooks::async_id_fields() {
109
2209048
  return async_id_fields_;
110
}
111
112
4703
inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
113
4703
  return async_ids_stack_;
114
}
115
116
1328225
inline v8::Local<v8::Array> AsyncHooks::execution_async_resources() {
117
1328225
  return PersistentToLocal::Strong(execution_async_resources_);
118
}
119
120
183445
inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) {
121
183445
  return env()->isolate_data()->async_wrap_provider(idx);
122
}
123
124
1
inline void AsyncHooks::no_force_checks() {
125
1
  fields_[kCheck] -= 1;
126
1
}
127
128
2188095
inline Environment* AsyncHooks::env() {
129
2188095
  return Environment::ForAsyncHooks(this);
130
}
131
132
// Remember to keep this code aligned with pushAsyncContext() in JS.
133
662293
inline void AsyncHooks::push_async_context(double async_id,
134
                                           double trigger_async_id,
135
                                           v8::Local<v8::Value> resource) {
136
1324588
  v8::HandleScope handle_scope(env()->isolate());
137
138
  // Since async_hooks is experimental, do only perform the check
139
  // when async_hooks is enabled.
140
662296
  if (fields_[kCheck] > 0) {
141
662258
    CHECK_GE(async_id, -1);
142
662258
    CHECK_GE(trigger_async_id, -1);
143
  }
144
145
662297
  uint32_t offset = fields_[kStackLength];
146
662295
  if (offset * 2 >= async_ids_stack_.Length())
147
4
    grow_async_ids_stack();
148
662266
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
149
662298
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
150
662297
  fields_[kStackLength] += 1;
151
662295
  async_id_fields_[kExecutionAsyncId] = async_id;
152
662299
  async_id_fields_[kTriggerAsyncId] = trigger_async_id;
153
154
662294
  auto resources = execution_async_resources();
155
1324589
  USE(resources->Set(env()->context(), offset, resource));
156
662302
}
157
158
// Remember to keep this code aligned with popAsyncContext() in JS.
159
661901
inline bool AsyncHooks::pop_async_context(double async_id) {
160
  // In case of an exception then this may have already been reset, if the
161
  // stack was multiple MakeCallback()'s deep.
162
661901
  if (fields_[kStackLength] == 0) return false;
163
164
  // Ask for the async_id to be restored as a check that the stack
165
  // hasn't been corrupted.
166
  // Since async_hooks is experimental, do only perform the check
167
  // when async_hooks is enabled.
168

661255
  if (fields_[kCheck] > 0 && async_id_fields_[kExecutionAsyncId] != async_id) {
169
4
    fprintf(stderr,
170
            "Error: async hook stack has become corrupted ("
171
            "actual: %.f, expected: %.f)\n",
172
            async_id_fields_.GetValue(kExecutionAsyncId),
173
4
            async_id);
174
4
    DumpBacktrace(stderr);
175
4
    fflush(stderr);
176
4
    if (!env()->abort_on_uncaught_exception())
177
4
      exit(1);
178
    fprintf(stderr, "\n");
179
    fflush(stderr);
180
    ABORT_NO_BACKTRACE();
181
  }
182
183
661246
  uint32_t offset = fields_[kStackLength] - 1;
184
661248
  async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
185
661250
  async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
186
661249
  fields_[kStackLength] = offset;
187
188
661246
  auto resources = execution_async_resources();
189
1322490
  USE(resources->Delete(env()->context(), offset));
190
191
661251
  return fields_[kStackLength] > 0;
192
}
193
194
// Keep in sync with clearAsyncIdStack in lib/internal/async_hooks.js.
195
4744
inline void AsyncHooks::clear_async_id_stack() {
196
4744
  auto isolate = env()->isolate();
197
9488
  v8::HandleScope handle_scope(isolate);
198
9488
  execution_async_resources_.Reset(isolate, v8::Array::New(isolate));
199
200
4744
  async_id_fields_[kExecutionAsyncId] = 0;
201
4744
  async_id_fields_[kTriggerAsyncId] = 0;
202
4744
  fields_[kStackLength] = 0;
203
4744
}
204
205
// The DefaultTriggerAsyncIdScope(AsyncWrap*) constructor is defined in
206
// async_wrap-inl.h to avoid a circular dependency.
207
208
474278
inline AsyncHooks::DefaultTriggerAsyncIdScope ::DefaultTriggerAsyncIdScope(
209
474278
    Environment* env, double default_trigger_async_id)
210
474278
    : async_hooks_(env->async_hooks()) {
211
474278
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
212
474278
    CHECK_GE(default_trigger_async_id, 0);
213
  }
214
215
474278
  old_default_trigger_async_id_ =
216
948556
    async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
217
474278
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
218
474278
    default_trigger_async_id;
219
474278
}
220
221
948554
inline AsyncHooks::DefaultTriggerAsyncIdScope ::~DefaultTriggerAsyncIdScope() {
222
474277
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
223
948554
    old_default_trigger_async_id_;
224
474277
}
225
226
2188066
Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) {
227
2188066
  return ContainerOf(&Environment::async_hooks_, hooks);
228
}
229
230
661778
inline size_t Environment::async_callback_scope_depth() const {
231
661778
  return async_callback_scope_depth_;
232
}
233
234
662440
inline void Environment::PushAsyncCallbackScope() {
235
662440
  async_callback_scope_depth_++;
236
662440
}
237
238
662096
inline void Environment::PopAsyncCallbackScope() {
239
662096
  async_callback_scope_depth_--;
240
662096
}
241
242
4703
inline ImmediateInfo::ImmediateInfo(v8::Isolate* isolate)
243
4703
    : fields_(isolate, kFieldsCount) {}
244
245
4703
inline AliasedUint32Array& ImmediateInfo::fields() {
246
4703
  return fields_;
247
}
248
249
401316
inline uint32_t ImmediateInfo::count() const {
250
401316
  return fields_[kCount];
251
}
252
253
473831
inline uint32_t ImmediateInfo::ref_count() const {
254
473831
  return fields_[kRefCount];
255
}
256
257
30309
inline bool ImmediateInfo::has_outstanding() const {
258
30309
  return fields_[kHasOutstanding] == 1;
259
}
260
261
33043
inline void ImmediateInfo::ref_count_inc(uint32_t increment) {
262
33043
  fields_[kRefCount] += increment;
263
33043
}
264
265
411029
inline void ImmediateInfo::ref_count_dec(uint32_t decrement) {
266
411029
  fields_[kRefCount] -= decrement;
267
411036
}
268
269
4703
inline TickInfo::TickInfo(v8::Isolate* isolate)
270
4703
    : fields_(isolate, kFieldsCount) {}
271
272
4703
inline AliasedUint8Array& TickInfo::fields() {
273
4703
  return fields_;
274
}
275
276
1200362
inline bool TickInfo::has_tick_scheduled() const {
277
1200362
  return fields_[kHasTickScheduled] == 1;
278
}
279
280
183041
inline bool TickInfo::has_rejection_to_warn() const {
281
183041
  return fields_[kHasRejectionToWarn] == 1;
282
}
283
284
5266
inline void Environment::AssignToContext(v8::Local<v8::Context> context,
285
                                         const ContextInfo& info) {
286
5266
  context->SetAlignedPointerInEmbedderData(
287
5266
      ContextEmbedderIndex::kEnvironment, this);
288
  // Used by Environment::GetCurrent to know that we are on a node context.
289
10532
  context->SetAlignedPointerInEmbedderData(
290
5266
    ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr);
291
  // Used to retrieve bindings
292
5266
  context->SetAlignedPointerInEmbedderData(
293
10532
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
294
295
#if HAVE_INSPECTOR
296
5266
  inspector_agent()->ContextCreated(context, info);
297
#endif  // HAVE_INSPECTOR
298
5266
}
299
300
683378
inline Environment* Environment::GetCurrent(v8::Isolate* isolate) {
301
683378
  if (UNLIKELY(!isolate->InContext())) return nullptr;
302
1366953
  v8::HandleScope handle_scope(isolate);
303
683468
  return GetCurrent(isolate->GetCurrentContext());
304
}
305
306
6472560
inline Environment* Environment::GetCurrent(v8::Local<v8::Context> context) {
307
6472560
  if (UNLIKELY(context.IsEmpty())) {
308
1
    return nullptr;
309
  }
310
6472559
  if (UNLIKELY(context->GetNumberOfEmbedderDataFields() <=
311
               ContextEmbedderIndex::kContextTag)) {
312
11
    return nullptr;
313
  }
314
12945162
  if (UNLIKELY(context->GetAlignedPointerFromEmbedderData(
315
                   ContextEmbedderIndex::kContextTag) !=
316
               Environment::kNodeContextTagPtr)) {
317
    return nullptr;
318
  }
319
  return static_cast<Environment*>(
320
6472581
      context->GetAlignedPointerFromEmbedderData(
321
6472581
          ContextEmbedderIndex::kEnvironment));
322
}
323
324
4380983
inline Environment* Environment::GetCurrent(
325
    const v8::FunctionCallbackInfo<v8::Value>& info) {
326
4380983
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
327
}
328
329
template <typename T>
330
1086656
inline Environment* Environment::GetCurrent(
331
    const v8::PropertyCallbackInfo<T>& info) {
332
1086656
  return GetCurrent(info.GetIsolate()->GetCurrentContext());
333
}
334
335
template <typename T, typename U>
336
inline T* Environment::GetBindingData(const v8::PropertyCallbackInfo<U>& info) {
337
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
338
}
339
340
template <typename T>
341
532707
inline T* Environment::GetBindingData(
342
    const v8::FunctionCallbackInfo<v8::Value>& info) {
343
532707
  return GetBindingData<T>(info.GetIsolate()->GetCurrentContext());
344
}
345
346
template <typename T>
347
532711
inline T* Environment::GetBindingData(v8::Local<v8::Context> context) {
348
  BindingDataStore* map = static_cast<BindingDataStore*>(
349
532711
      context->GetAlignedPointerFromEmbedderData(
350
532711
          ContextEmbedderIndex::kBindingListIndex));
351
  DCHECK_NOT_NULL(map);
352
532711
  auto it = map->find(T::binding_data_name);
353
532708
  if (UNLIKELY(it == map->end())) return nullptr;
354
532710
  T* result = static_cast<T*>(it->second.get());
355
  DCHECK_NOT_NULL(result);
356
  DCHECK_EQ(result->env(), GetCurrent(context));
357
532709
  return result;
358
}
359
360
template <typename T>
361
6144
inline T* Environment::AddBindingData(
362
    v8::Local<v8::Context> context,
363
    v8::Local<v8::Object> target) {
364
  DCHECK_EQ(GetCurrent(context), this);
365
  // This won't compile if T is not a BaseObject subclass.
366
12288
  BaseObjectPtr<T> item = MakeDetachedBaseObject<T>(this, target);
367
  BindingDataStore* map = static_cast<BindingDataStore*>(
368
6144
      context->GetAlignedPointerFromEmbedderData(
369
6144
          ContextEmbedderIndex::kBindingListIndex));
370
  DCHECK_NOT_NULL(map);
371
6144
  auto result = map->emplace(T::binding_data_name, item);
372
6144
  CHECK(result.second);
373
  DCHECK_EQ(GetBindingData<T>(context), item.get());
374
12288
  return item.get();
375
}
376
377
1
inline Environment* Environment::GetThreadLocalEnv() {
378
1
  return static_cast<Environment*>(uv_key_get(&thread_local_env));
379
}
380
381
inline bool Environment::profiler_idle_notifier_started() const {
382
  return profiler_idle_notifier_started_;
383
}
384
385
30041056
inline v8::Isolate* Environment::isolate() const {
386
30041056
  return isolate_;
387
}
388
389
4601
inline Environment* Environment::from_timer_handle(uv_timer_t* handle) {
390
4601
  return ContainerOf(&Environment::timer_handle_, handle);
391
}
392
393
20825
inline uv_timer_t* Environment::timer_handle() {
394
20825
  return &timer_handle_;
395
}
396
397
401316
inline Environment* Environment::from_immediate_check_handle(
398
    uv_check_t* handle) {
399
401316
  return ContainerOf(&Environment::immediate_check_handle_, handle);
400
}
401
402
18716
inline uv_check_t* Environment::immediate_check_handle() {
403
18716
  return &immediate_check_handle_;
404
}
405
406
438469
inline uv_idle_t* Environment::immediate_idle_handle() {
407
438469
  return &immediate_idle_handle_;
408
}
409
410
28074
inline void Environment::RegisterHandleCleanup(uv_handle_t* handle,
411
                                               HandleCleanupCb cb,
412
                                               void* arg) {
413
28074
  handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg});
414
28074
}
415
416
template <typename T, typename OnCloseCallback>
417
29236
inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) {
418
29236
  handle_cleanup_waiting_++;
419
  static_assert(sizeof(T) >= sizeof(uv_handle_t), "T is a libuv handle");
420
  static_assert(offsetof(T, data) == offsetof(uv_handle_t, data),
421
                "T is a libuv handle");
422
  static_assert(offsetof(T, close_cb) == offsetof(uv_handle_t, close_cb),
423
                "T is a libuv handle");
424
  struct CloseData {
425
    Environment* env;
426
    OnCloseCallback callback;
427
    void* original_data;
428
  };
429
29236
  handle->data = new CloseData { this, callback, handle->data };
430
116939
  uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
431
58472
    std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) };
432
29238
    data->env->handle_cleanup_waiting_--;
433
29238
    handle->data = data->original_data;
434
29237
    data->callback(reinterpret_cast<T*>(handle));
435
29237
  });
436
29237
}
437
438
75780
void Environment::IncreaseWaitingRequestCounter() {
439
75780
  request_waiting_++;
440
75780
}
441
442
75774
void Environment::DecreaseWaitingRequestCounter() {
443
75774
  request_waiting_--;
444
75774
  CHECK_GE(request_waiting_, 0);
445
75774
}
446
447
703389
inline uv_loop_t* Environment::event_loop() const {
448
703389
  return isolate_data()->event_loop();
449
}
450
451
153
inline void Environment::TryLoadAddon(
452
    const char* filename,
453
    int flags,
454
    const std::function<bool(binding::DLib*)>& was_loaded) {
455
153
  loaded_addons_.emplace_back(filename, flags);
456
153
  if (!was_loaded(&loaded_addons_.back())) {
457
8
    loaded_addons_.pop_back();
458
  }
459
153
}
460
461
#if HAVE_INSPECTOR
462
40440
inline bool Environment::is_in_inspector_console_call() const {
463
40440
  return is_in_inspector_console_call_;
464
}
465
466
80878
inline void Environment::set_is_in_inspector_console_call(bool value) {
467
80878
  is_in_inspector_console_call_ = value;
468
80878
}
469
#endif
470
471
4973489
inline AsyncHooks* Environment::async_hooks() {
472
4973489
  return &async_hooks_;
473
}
474
475
1354237
inline ImmediateInfo* Environment::immediate_info() {
476
1354237
  return &immediate_info_;
477
}
478
479
604900
inline TickInfo* Environment::tick_info() {
480
604900
  return &tick_info_;
481
}
482
483
46352
inline uint64_t Environment::timer_base() const {
484
46352
  return timer_base_;
485
}
486
487
1099695
inline std::shared_ptr<KVStore> Environment::env_vars() {
488
1099695
  return env_vars_;
489
}
490
491
5038
inline void Environment::set_env_vars(std::shared_ptr<KVStore> env_vars) {
492
5038
  env_vars_ = env_vars;
493
5038
}
494
495
14
inline bool Environment::printed_error() const {
496
14
  return printed_error_;
497
}
498
499
14
inline void Environment::set_printed_error(bool value) {
500
14
  printed_error_ = value;
501
14
}
502
503
7891
inline void Environment::set_trace_sync_io(bool value) {
504
7891
  trace_sync_io_ = value;
505
7891
}
506
507
27
inline bool Environment::abort_on_uncaught_exception() const {
508
27
  return options_->abort_on_uncaught_exception;
509
}
510
511
inline void Environment::set_abort_on_uncaught_exception(bool value) {
512
  options_->abort_on_uncaught_exception = value;
513
}
514
515
4733
inline AliasedUint32Array& Environment::should_abort_on_uncaught_toggle() {
516
4733
  return should_abort_on_uncaught_toggle_;
517
}
518
519
1297255
inline AliasedInt32Array& Environment::stream_base_state() {
520
1297255
  return stream_base_state_;
521
}
522
523
31470
inline uint32_t Environment::get_next_module_id() {
524
31470
  return module_id_counter_++;
525
}
526
1856
inline uint32_t Environment::get_next_script_id() {
527
1856
  return script_id_counter_++;
528
}
529
25220
inline uint32_t Environment::get_next_function_id() {
530
25220
  return function_id_counter_++;
531
}
532
533
64595
ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope(
534
64595
    Environment* env)
535
64595
    : env_(env) {
536
64595
  env_->PushShouldNotAbortOnUncaughtScope();
537
64595
}
538
539
129188
ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() {
540
64594
  Close();
541
64594
}
542
543
64774
void ShouldNotAbortOnUncaughtScope::Close() {
544
64774
  if (env_ != nullptr) {
545
64594
    env_->PopShouldNotAbortOnUncaughtScope();
546
64594
    env_ = nullptr;
547
  }
548
64774
}
549
550
64594
inline void Environment::PushShouldNotAbortOnUncaughtScope() {
551
64594
  should_not_abort_scope_counter_++;
552
64594
}
553
554
64594
inline void Environment::PopShouldNotAbortOnUncaughtScope() {
555
64594
  should_not_abort_scope_counter_--;
556
64594
}
557
558
1
inline bool Environment::inside_should_not_abort_on_uncaught_scope() const {
559
1
  return should_not_abort_scope_counter_ > 0;
560
}
561
562
199050
inline std::vector<double>* Environment::destroy_async_id_list() {
563
199050
  return &destroy_async_id_list_;
564
}
565
566
184008
inline double Environment::new_async_id() {
567
184008
  async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
568
184008
  return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
569
}
570
571
191488
inline double Environment::execution_async_id() {
572
191488
  return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId];
573
}
574
575
38003
inline double Environment::trigger_async_id() {
576
38003
  return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId];
577
}
578
579
184005
inline double Environment::get_default_trigger_async_id() {
580
  double default_trigger_async_id =
581
184005
    async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
582
  // If defaultTriggerAsyncId isn't set, use the executionAsyncId
583
184005
  if (default_trigger_async_id < 0)
584
152880
    default_trigger_async_id = execution_async_id();
585
184005
  return default_trigger_async_id;
586
}
587
588
48855
inline std::shared_ptr<EnvironmentOptions> Environment::options() {
589
48855
  return options_;
590
}
591
592
13577
inline const std::vector<std::string>& Environment::argv() {
593
13577
  return argv_;
594
}
595
596
5195
inline const std::vector<std::string>& Environment::exec_argv() {
597
5195
  return exec_argv_;
598
}
599
600
9358
inline const std::string& Environment::exec_path() const {
601
9358
  return exec_path_;
602
}
603
604
#if HAVE_INSPECTOR
605
4673
inline void Environment::set_coverage_directory(const char* dir) {
606
4673
  coverage_directory_ = std::string(dir);
607
4673
}
608
609
4693
inline void Environment::set_coverage_connection(
610
    std::unique_ptr<profiler::V8CoverageConnection> connection) {
611
4693
  CHECK_NULL(coverage_connection_);
612
4693
  std::swap(coverage_connection_, connection);
613
4693
}
614
615
14073
inline profiler::V8CoverageConnection* Environment::coverage_connection() {
616
14073
  return coverage_connection_.get();
617
}
618
619
4655
inline const std::string& Environment::coverage_directory() const {
620
4655
  return coverage_directory_;
621
}
622
623
10
inline void Environment::set_cpu_profiler_connection(
624
    std::unique_ptr<profiler::V8CpuProfilerConnection> connection) {
625
10
  CHECK_NULL(cpu_profiler_connection_);
626
10
  std::swap(cpu_profiler_connection_, connection);
627
10
}
628
629
inline profiler::V8CpuProfilerConnection*
630
4707
Environment::cpu_profiler_connection() {
631
4707
  return cpu_profiler_connection_.get();
632
}
633
634
10
inline void Environment::set_cpu_prof_interval(uint64_t interval) {
635
10
  cpu_prof_interval_ = interval;
636
10
}
637
638
10
inline uint64_t Environment::cpu_prof_interval() const {
639
10
  return cpu_prof_interval_;
640
}
641
642
10
inline void Environment::set_cpu_prof_name(const std::string& name) {
643
10
  cpu_prof_name_ = name;
644
10
}
645
646
10
inline const std::string& Environment::cpu_prof_name() const {
647
10
  return cpu_prof_name_;
648
}
649
650
10
inline void Environment::set_cpu_prof_dir(const std::string& dir) {
651
10
  cpu_prof_dir_ = dir;
652
10
}
653
654
10
inline const std::string& Environment::cpu_prof_dir() const {
655
10
  return cpu_prof_dir_;
656
}
657
658
10
inline void Environment::set_heap_profiler_connection(
659
    std::unique_ptr<profiler::V8HeapProfilerConnection> connection) {
660
10
  CHECK_NULL(heap_profiler_connection_);
661
10
  std::swap(heap_profiler_connection_, connection);
662
10
}
663
664
inline profiler::V8HeapProfilerConnection*
665
4697
Environment::heap_profiler_connection() {
666
4697
  return heap_profiler_connection_.get();
667
}
668
669
10
inline void Environment::set_heap_prof_name(const std::string& name) {
670
10
  heap_prof_name_ = name;
671
10
}
672
673
10
inline const std::string& Environment::heap_prof_name() const {
674
10
  return heap_prof_name_;
675
}
676
677
10
inline void Environment::set_heap_prof_dir(const std::string& dir) {
678
10
  heap_prof_dir_ = dir;
679
10
}
680
681
10
inline const std::string& Environment::heap_prof_dir() const {
682
10
  return heap_prof_dir_;
683
}
684
685
10
inline void Environment::set_heap_prof_interval(uint64_t interval) {
686
10
  heap_prof_interval_ = interval;
687
10
}
688
689
10
inline uint64_t Environment::heap_prof_interval() const {
690
10
  return heap_prof_interval_;
691
}
692
693
#endif  // HAVE_INSPECTOR
694
695
inline
696
9507
std::shared_ptr<ExclusiveAccess<HostPort>> Environment::inspector_host_port() {
697
9507
  return inspector_host_port_;
698
}
699
700
50771
inline std::shared_ptr<PerIsolateOptions> IsolateData::options() {
701
50771
  return options_;
702
}
703
704
40
inline void IsolateData::set_options(
705
    std::shared_ptr<PerIsolateOptions> options) {
706
40
  options_ = std::move(options);
707
40
}
708
709
template <typename Fn>
710
55426
void Environment::SetImmediate(Fn&& cb, CallbackFlags::Flags flags) {
711
110852
  auto callback = native_immediates_.CreateCallback(std::move(cb), flags);
712
55426
  native_immediates_.Push(std::move(callback));
713
714


55426
  if (flags & CallbackFlags::kRefed) {
715


33043
    if (immediate_info()->ref_count() == 0)
716
24612
      ToggleImmediateRef(true);
717
33043
    immediate_info()->ref_count_inc(1);
718
  }
719
55426
}
720
721
template <typename Fn>
722
1124
void Environment::SetImmediateThreadsafe(Fn&& cb, CallbackFlags::Flags flags) {
723
  auto callback = native_immediates_threadsafe_.CreateCallback(
724
2248
      std::move(cb), flags);
725
  {
726
2248
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
727
1124
    native_immediates_threadsafe_.Push(std::move(callback));
728

1124
    if (task_queues_async_initialized_)
729
822
      uv_async_send(&task_queues_async_);
730
  }
731
1124
}
732
733
template <typename Fn>
734
6539
void Environment::RequestInterrupt(Fn&& cb) {
735
  auto callback = native_immediates_interrupts_.CreateCallback(
736
13078
      std::move(cb), CallbackFlags::kRefed);
737
  {
738
13078
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
739
6539
    native_immediates_interrupts_.Push(std::move(callback));
740
6539
    if (task_queues_async_initialized_)
741
1718
      uv_async_send(&task_queues_async_);
742
  }
743
6539
  RequestInterruptFromV8();
744
6539
}
745
746
2568099
inline bool Environment::can_call_into_js() const {
747

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

699252
  return a.fn_ == b.fn_ && a.arg_ == b.arg_;
1023
}
1024
1025
367
BaseObject* CleanupHookCallback::GetBaseObject() const {
1026
367
  if (fn_ == BaseObject::DeleteMe)
1027
347
    return static_cast<BaseObject*>(arg_);
1028
  else
1029
20
    return nullptr;
1030
}
1031
1032
template <typename T>
1033
19
void Environment::ForEachBaseObject(T&& iterator) {
1034
386
  for (const auto& hook : cleanup_hooks_) {
1035
367
    BaseObject* obj = hook.GetBaseObject();
1036
367
    if (obj != nullptr)
1037
347
      iterator(obj);
1038
  }
1039
19
}
1040
1041
1203913
void Environment::modify_base_object_count(int64_t delta) {
1042
1203913
  base_object_count_ += delta;
1043
1203913
}
1044
1045
4719
int64_t Environment::base_object_count() const {
1046
4719
  return base_object_count_ - initial_base_object_count_;
1047
}
1048
1049
9
void Environment::set_main_utf16(std::unique_ptr<v8::String::Value> str) {
1050
9
  CHECK(!main_utf16_);
1051
9
  main_utf16_ = std::move(str);
1052
9
}
1053
1054
336
void Environment::set_process_exit_handler(
1055
    std::function<void(Environment*, int)>&& handler) {
1056
336
  process_exit_handler_ = std::move(handler);
1057
336
}
1058
1059
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1060
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1061
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1062
#define V(TypeName, PropertyName)                                             \
1063
  inline                                                                      \
1064
  v8::Local<TypeName> IsolateData::PropertyName() const {                     \
1065
    return PropertyName ## _ .Get(isolate_);                                  \
1066
  }
1067
48730
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1068
762750
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1069
6195014
  PER_ISOLATE_STRING_PROPERTIES(VS)
1070
#undef V
1071
#undef VS
1072
#undef VY
1073
#undef VP
1074
1075
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
1076
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
1077
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
1078
#define V(TypeName, PropertyName)                                             \
1079
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1080
    return isolate_data()->PropertyName();                                    \
1081
  }
1082
24365
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
1083
381130
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
1084
3093114
  PER_ISOLATE_STRING_PROPERTIES(VS)
1085
#undef V
1086
#undef VS
1087
#undef VY
1088
#undef VP
1089
1090
#define V(PropertyName, TypeName)                                             \
1091
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
1092
    return PersistentToLocal::Strong(PropertyName ## _);                      \
1093
  }                                                                           \
1094
  inline void Environment::set_ ## PropertyName(v8::Local<TypeName> value) {  \
1095
    PropertyName ## _.Reset(isolate(), value);                                \
1096
  }
1097
699066
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1098
2530455
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1099
#undef V
1100
1101
11732741
v8::Local<v8::Context> Environment::context() const {
1102
11732741
  return PersistentToLocal::Strong(context_);
1103
}
1104
1105
}  // namespace node
1106
1107
// These two files depend on each other. Including base_object-inl.h after this
1108
// file is the easiest way to avoid issues with that circular dependency.
1109
#include "base_object-inl.h"
1110
1111
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
1112
1113
#endif  // SRC_ENV_INL_H_