GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage/nodes/benchmark/out/../src/env-inl.h Lines: 413 417 99.0 %
Date: 2019-01-07 12:15:22 Branches: 65 90 72.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 "env.h"
29
#include "node.h"
30
#include "util-inl.h"
31
#include "uv.h"
32
#include "v8.h"
33
#include "node_perf_common.h"
34
#include "node_context_data.h"
35
#include "node_worker.h"
36
37
#include <stddef.h>
38
#include <stdint.h>
39
40
namespace node {
41
42
inline v8::Isolate* IsolateData::isolate() const {
43
  return isolate_;
44
}
45
46
1048543
inline uv_loop_t* IsolateData::event_loop() const {
47
1048543
  return event_loop_;
48
}
49
50
3661
inline uint32_t* IsolateData::zero_fill_field() const {
51
3661
  return zero_fill_field_;
52
}
53
54
946
inline MultiIsolatePlatform* IsolateData::platform() const {
55
946
  return platform_;
56
}
57
58
3685
inline Environment::AsyncHooks::AsyncHooks()
59
    : async_ids_stack_(env()->isolate(), 16 * 2),
60
      fields_(env()->isolate(), kFieldsCount),
61
154770
      async_id_fields_(env()->isolate(), kUidFieldsCount) {
62
3685
  v8::HandleScope handle_scope(env()->isolate());
63
64
  // Always perform async_hooks checks, not just when async_hooks is enabled.
65
  // TODO(AndreasMadsen): Consider removing this for LTS releases.
66
  // See discussion in https://github.com/nodejs/node/pull/15454
67
  // When removing this, do it by reverting the commit. Otherwise the test
68
  // and flag changes won't be included.
69
3685
  fields_[kCheck] = 1;
70
71
  // kDefaultTriggerAsyncId should be -1, this indicates that there is no
72
  // specified default value and it should fallback to the executionAsyncId.
73
  // 0 is not used as the magic value, because that indicates a missing context
74
  // which is different from a default context.
75
3685
  async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
76
77
  // kAsyncIdCounter should start at 1 because that'll be the id the execution
78
  // context during bootstrap (code that runs before entering uv_run()).
79
3685
  async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
80
81
  // Create all the provider strings that will be passed to JS. Place them in
82
  // an array so the array index matches the PROVIDER id offset. This way the
83
  // strings can be retrieved quickly.
84
#define V(Provider)                                                           \
85
  providers_[AsyncWrap::PROVIDER_ ## Provider].Set(                           \
86
      env()->isolate(),                                                       \
87
      v8::String::NewFromOneByte(                                             \
88
        env()->isolate(),                                                     \
89
        reinterpret_cast<const uint8_t*>(#Provider),                          \
90
        v8::NewStringType::kInternalized,                                     \
91
        sizeof(#Provider) - 1).ToLocalChecked());
92
305855
  NODE_ASYNC_PROVIDER_TYPES(V)
93
#undef V
94
3685
}
95
96
inline AliasedBuffer<uint32_t, v8::Uint32Array>&
97
3075353
Environment::AsyncHooks::fields() {
98
3075353
  return fields_;
99
}
100
101
inline AliasedBuffer<double, v8::Float64Array>&
102
2479640
Environment::AsyncHooks::async_id_fields() {
103
2479640
  return async_id_fields_;
104
}
105
106
inline AliasedBuffer<double, v8::Float64Array>&
107
3661
Environment::AsyncHooks::async_ids_stack() {
108
3661
  return async_ids_stack_;
109
}
110
111
268155
inline v8::Local<v8::String> Environment::AsyncHooks::provider_string(int idx) {
112
536310
  return providers_[idx].Get(env()->isolate());
113
}
114
115
1
inline void Environment::AsyncHooks::no_force_checks() {
116
1
  fields_[kCheck] -= 1;
117
1
}
118
119
585093
inline Environment* Environment::AsyncHooks::env() {
120
585093
  return Environment::ForAsyncHooks(this);
121
}
122
123
// Remember to keep this code aligned with pushAsyncIds() in JS.
124
741506
inline void Environment::AsyncHooks::push_async_ids(double async_id,
125
                                                    double trigger_async_id) {
126
  // Since async_hooks is experimental, do only perform the check
127
  // when async_hooks is enabled.
128
741506
  if (fields_[kCheck] > 0) {
129
741504
    CHECK_GE(async_id, -1);
130
741504
    CHECK_GE(trigger_async_id, -1);
131
  }
132
133
741508
  uint32_t offset = fields_[kStackLength];
134
741506
  if (offset * 2 >= async_ids_stack_.Length())
135
8
    grow_async_ids_stack();
136
741508
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
137
741509
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
138
741507
  fields_[kStackLength] += 1;
139
741506
  async_id_fields_[kExecutionAsyncId] = async_id;
140
741508
  async_id_fields_[kTriggerAsyncId] = trigger_async_id;
141
741506
}
142
143
// Remember to keep this code aligned with popAsyncIds() in JS.
144
741222
inline bool Environment::AsyncHooks::pop_async_id(double async_id) {
145
  // In case of an exception then this may have already been reset, if the
146
  // stack was multiple MakeCallback()'s deep.
147
741222
  if (fields_[kStackLength] == 0) return false;
148
149
  // Ask for the async_id to be restored as a check that the stack
150
  // hasn't been corrupted.
151
  // Since async_hooks is experimental, do only perform the check
152
  // when async_hooks is enabled.
153


741097
  if (fields_[kCheck] > 0 && async_id_fields_[kExecutionAsyncId] != async_id) {
154
    fprintf(stderr,
155
            "Error: async hook stack has become corrupted ("
156
            "actual: %.f, expected: %.f)\n",
157
            async_id_fields_.GetValue(kExecutionAsyncId),
158
4
            async_id);
159
4
    DumpBacktrace(stderr);
160
4
    fflush(stderr);
161
4
    if (!env()->abort_on_uncaught_exception())
162
4
      exit(1);
163
    fprintf(stderr, "\n");
164
    fflush(stderr);
165
    ABORT_NO_BACKTRACE();
166
  }
167
168
741094
  uint32_t offset = fields_[kStackLength] - 1;
169
741094
  async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
170
741094
  async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
171
741093
  fields_[kStackLength] = offset;
172
173
741093
  return fields_[kStackLength] > 0;
174
}
175
176
// Keep in sync with clearAsyncIdStack in lib/internal/async_hooks.js.
177
10
inline void Environment::AsyncHooks::clear_async_id_stack() {
178
10
  async_id_fields_[kExecutionAsyncId] = 0;
179
10
  async_id_fields_[kTriggerAsyncId] = 0;
180
10
  fields_[kStackLength] = 0;
181
10
}
182
183
// The DefaultTriggerAsyncIdScope(AsyncWrap*) constructor is defined in
184
// async_wrap-inl.h to avoid a circular dependency.
185
186
457533
inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope
187
  ::DefaultTriggerAsyncIdScope(Environment* env,
188
                               double default_trigger_async_id)
189
457533
    : async_hooks_(env->async_hooks()) {
190
457533
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
191
457533
    CHECK_GE(default_trigger_async_id, 0);
192
  }
193
194
915066
  old_default_trigger_async_id_ =
195
915066
    async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
196
915066
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
197
457533
    default_trigger_async_id;
198
457533
}
199
200
457532
inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope
201
  ::~DefaultTriggerAsyncIdScope() {
202
915064
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
203
457532
    old_default_trigger_async_id_;
204
457532
}
205
206
207
585093
Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) {
208
585093
  return ContainerOf(&Environment::async_hooks_, hooks);
209
}
210
211
212
771455
inline Environment::AsyncCallbackScope::AsyncCallbackScope(Environment* env)
213
771455
    : env_(env) {
214
771455
  env_->makecallback_cntr_++;
215
771455
}
216
217
771371
inline Environment::AsyncCallbackScope::~AsyncCallbackScope() {
218
771371
  env_->makecallback_cntr_--;
219
771371
}
220
221
738136
inline size_t Environment::makecallback_depth() const {
222
738136
  return makecallback_cntr_;
223
}
224
225
3685
inline Environment::ImmediateInfo::ImmediateInfo(v8::Isolate* isolate)
226
3685
    : fields_(isolate, kFieldsCount) {}
227
228
inline AliasedBuffer<uint32_t, v8::Uint32Array>&
229
3661
    Environment::ImmediateInfo::fields() {
230
3661
  return fields_;
231
}
232
233
479429
inline uint32_t Environment::ImmediateInfo::count() const {
234
479429
  return fields_[kCount];
235
}
236
237
79033
inline uint32_t Environment::ImmediateInfo::ref_count() const {
238
79033
  return fields_[kRefCount];
239
}
240
241
52889
inline bool Environment::ImmediateInfo::has_outstanding() const {
242
52889
  return fields_[kHasOutstanding] == 1;
243
}
244
245
48850
inline void Environment::ImmediateInfo::count_inc(uint32_t increment) {
246
48850
  fields_[kCount] += increment;
247
48850
}
248
249
45590
inline void Environment::ImmediateInfo::count_dec(uint32_t decrement) {
250
45590
  fields_[kCount] -= decrement;
251
45590
}
252
253
26160
inline void Environment::ImmediateInfo::ref_count_inc(uint32_t increment) {
254
26160
  fields_[kRefCount] += increment;
255
26160
}
256
257
45590
inline void Environment::ImmediateInfo::ref_count_dec(uint32_t decrement) {
258
45590
  fields_[kRefCount] -= decrement;
259
45590
}
260
261
3685
inline Environment::TickInfo::TickInfo(v8::Isolate* isolate)
262
3685
    : fields_(isolate, kFieldsCount) {}
263
264
3661
inline AliasedBuffer<uint8_t, v8::Uint8Array>& Environment::TickInfo::fields() {
265
3661
  return fields_;
266
}
267
268
1320063
inline bool Environment::TickInfo::has_tick_scheduled() const {
269
1320063
  return fields_[kHasTickScheduled] == 1;
270
}
271
272
277184
inline bool Environment::TickInfo::has_rejection_to_warn() const {
273
277184
  return fields_[kHasRejectionToWarn] == 1;
274
}
275
276
4082
inline void Environment::AssignToContext(v8::Local<v8::Context> context,
277
                                         const ContextInfo& info) {
278
  context->SetAlignedPointerInEmbedderData(
279
4082
      ContextEmbedderIndex::kEnvironment, this);
280
  // Used by EnvPromiseHook to know that we are on a node context.
281
  context->SetAlignedPointerInEmbedderData(
282
8164
    ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr);
283
#if HAVE_INSPECTOR
284
4082
  inspector_agent()->ContextCreated(context, info);
285
#endif  // HAVE_INSPECTOR
286
4082
}
287
288
754187
inline Environment* Environment::GetCurrent(v8::Isolate* isolate) {
289
754187
  return GetCurrent(isolate->GetCurrentContext());
290
}
291
292
927204
inline Environment* Environment::GetCurrent(v8::Local<v8::Context> context) {
293


3708808
  if (UNLIKELY(context.IsEmpty() ||
294
      context->GetNumberOfEmbedderDataFields() <
295
          ContextEmbedderIndex::kContextTag ||
296
      context->GetAlignedPointerFromEmbedderData(
297
          ContextEmbedderIndex::kContextTag) !=
298
          Environment::kNodeContextTagPtr)) {
299
7
    return nullptr;
300
  }
301
302
  return static_cast<Environment*>(
303
      context->GetAlignedPointerFromEmbedderData(
304
1854398
          ContextEmbedderIndex::kEnvironment));
305
}
306
307
2968498
inline Environment* Environment::GetCurrent(
308
    const v8::FunctionCallbackInfo<v8::Value>& info) {
309
5936996
  CHECK(info.Data()->IsExternal());
310
8905524
  return static_cast<Environment*>(info.Data().As<v8::External>()->Value());
311
}
312
313
template <typename T>
314
2360
inline Environment* Environment::GetCurrent(
315
    const v8::PropertyCallbackInfo<T>& info) {
316

4720
  CHECK(info.Data()->IsExternal());
317
  return static_cast<Environment*>(
318
7080
      info.Data().template As<v8::External>()->Value());
319
}
320
321
8
inline Environment* Environment::GetThreadLocalEnv() {
322
8
  return static_cast<Environment*>(uv_key_get(&thread_local_env));
323
}
324
325
119
inline bool Environment::profiler_idle_notifier_started() const {
326
119
  return profiler_idle_notifier_started_;
327
}
328
329
21295287
inline v8::Isolate* Environment::isolate() const {
330
21295287
  return isolate_;
331
}
332
333
2433
inline Environment* Environment::from_timer_handle(uv_timer_t* handle) {
334
2433
  return ContainerOf(&Environment::timer_handle_, handle);
335
}
336
337
15861
inline uv_timer_t* Environment::timer_handle() {
338
15861
  return &timer_handle_;
339
}
340
341
479429
inline Environment* Environment::from_immediate_check_handle(
342
    uv_check_t* handle) {
343
479429
  return ContainerOf(&Environment::immediate_check_handle_, handle);
344
}
345
346
14740
inline uv_check_t* Environment::immediate_check_handle() {
347
14740
  return &immediate_check_handle_;
348
}
349
350
82479
inline uv_idle_t* Environment::immediate_idle_handle() {
351
82479
  return &immediate_idle_handle_;
352
}
353
354
18425
inline void Environment::RegisterHandleCleanup(uv_handle_t* handle,
355
                                               HandleCleanupCb cb,
356
                                               void* arg) {
357
18425
  handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg});
358
18425
}
359
360
template <typename T, typename OnCloseCallback>
361
17028
inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) {
362
17028
  handle_cleanup_waiting_++;
363
  static_assert(sizeof(T) >= sizeof(uv_handle_t), "T is a libuv handle");
364
  static_assert(offsetof(T, data) == offsetof(uv_handle_t, data),
365
                "T is a libuv handle");
366
  static_assert(offsetof(T, close_cb) == offsetof(uv_handle_t, close_cb),
367
                "T is a libuv handle");
368
  struct CloseData {
369
    Environment* env;
370
    OnCloseCallback callback;
371
    void* original_data;
372
  };
373
17028
  handle->data = new CloseData { this, callback, handle->data };
374
68112
  uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
375
17028
    std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) };
376
17028
    data->env->handle_cleanup_waiting_--;
377
17028
    handle->data = data->original_data;
378
17028
    data->callback(reinterpret_cast<T*>(handle));
379
51084
  });
380
17028
}
381
382
180791
void Environment::IncreaseWaitingRequestCounter() {
383
180791
  request_waiting_++;
384
180791
}
385
386
180787
void Environment::DecreaseWaitingRequestCounter() {
387
180787
  request_waiting_--;
388
180787
  CHECK_GE(request_waiting_, 0);
389
180787
}
390
391
1044854
inline uv_loop_t* Environment::event_loop() const {
392
1044854
  return isolate_data()->event_loop();
393
}
394
395
117
inline void Environment::TryLoadAddon(
396
    const char* filename,
397
    int flags,
398
    std::function<bool(binding::DLib*)> was_loaded) {
399
117
  loaded_addons_.emplace_back(filename, flags);
400
117
  if (!was_loaded(&loaded_addons_.back())) {
401
6
    loaded_addons_.pop_back();
402
  }
403
117
}
404
405
6394463
inline Environment::AsyncHooks* Environment::async_hooks() {
406
6394463
  return &async_hooks_;
407
}
408
409
781202
inline Environment::ImmediateInfo* Environment::immediate_info() {
410
781202
  return &immediate_info_;
411
}
412
413
663697
inline Environment::TickInfo* Environment::tick_info() {
414
663697
  return &tick_info_;
415
}
416
417
213543
inline uint64_t Environment::timer_base() const {
418
213543
  return timer_base_;
419
}
420
421
10
inline bool Environment::printed_error() const {
422
10
  return printed_error_;
423
}
424
425
10
inline void Environment::set_printed_error(bool value) {
426
10
  printed_error_ = value;
427
10
}
428
429
3212
inline void Environment::set_trace_sync_io(bool value) {
430
3212
  options_->trace_sync_io = value;
431
3212
}
432
433
3677
inline bool Environment::abort_on_uncaught_exception() const {
434
3677
  return options_->abort_on_uncaught_exception;
435
}
436
437
119
inline void Environment::set_abort_on_uncaught_exception(bool value) {
438
119
  options_->abort_on_uncaught_exception = value;
439
119
}
440
441
inline AliasedBuffer<uint32_t, v8::Uint32Array>&
442
3692
Environment::should_abort_on_uncaught_toggle() {
443
3692
  return should_abort_on_uncaught_toggle_;
444
}
445
446
inline AliasedBuffer<uint8_t, v8::Uint8Array>&
447
3757
Environment::trace_category_state() {
448
3757
  return trace_category_state_;
449
}
450
451
inline AliasedBuffer<int32_t, v8::Int32Array>&
452
1318337
Environment::stream_base_state() {
453
1318337
  return stream_base_state_;
454
}
455
456
256
inline uint32_t Environment::get_next_module_id() {
457
256
  return module_id_counter_++;
458
}
459
42626
inline uint32_t Environment::get_next_script_id() {
460
42626
  return script_id_counter_++;
461
}
462
463
42966
Environment::ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope(
464
    Environment* env)
465
42966
    : env_(env) {
466
42966
  env_->should_not_abort_scope_counter_++;
467
42966
}
468
469
42965
Environment::ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() {
470
42965
  Close();
471
42966
}
472
473
43285
void Environment::ShouldNotAbortOnUncaughtScope::Close() {
474
43285
  if (env_ != nullptr) {
475
42966
    env_->should_not_abort_scope_counter_--;
476
42966
    env_ = nullptr;
477
  }
478
43285
}
479
480
1
bool Environment::inside_should_not_abort_on_uncaught_scope() const {
481
1
  return should_not_abort_scope_counter_ > 0;
482
}
483
484
201720
inline std::vector<double>* Environment::destroy_async_id_list() {
485
201720
  return &destroy_async_id_list_;
486
}
487
488
268714
inline double Environment::new_async_id() {
489
268714
  async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
490
268714
  return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
491
}
492
493
260167
inline double Environment::execution_async_id() {
494
260167
  return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId];
495
}
496
497
37075
inline double Environment::trigger_async_id() {
498
37075
  return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId];
499
}
500
501
268711
inline double Environment::get_default_trigger_async_id() {
502
  double default_trigger_async_id =
503
268711
    async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
504
  // If defaultTriggerAsyncId isn't set, use the executionAsyncId
505
268711
  if (default_trigger_async_id < 0)
506
222448
    default_trigger_async_id = execution_async_id();
507
268711
  return default_trigger_async_id;
508
}
509
510
411
inline double* Environment::heap_statistics_buffer() const {
511
411
  CHECK_NOT_NULL(heap_statistics_buffer_);
512
411
  return heap_statistics_buffer_;
513
}
514
515
410
inline void Environment::set_heap_statistics_buffer(double* pointer) {
516
410
  CHECK_NULL(heap_statistics_buffer_);  // Should be set only once.
517
410
  heap_statistics_buffer_ = pointer;
518
410
}
519
520
411
inline double* Environment::heap_space_statistics_buffer() const {
521
411
  CHECK_NOT_NULL(heap_space_statistics_buffer_);
522
411
  return heap_space_statistics_buffer_;
523
}
524
525
410
inline void Environment::set_heap_space_statistics_buffer(double* pointer) {
526
410
  CHECK_NULL(heap_space_statistics_buffer_);  // Should be set only once.
527
410
  heap_space_statistics_buffer_ = pointer;
528
410
}
529
530
10747
inline char* Environment::http_parser_buffer() const {
531
10747
  return http_parser_buffer_;
532
}
533
534
260
inline void Environment::set_http_parser_buffer(char* buffer) {
535
260
  CHECK_NULL(http_parser_buffer_);  // Should be set only once.
536
260
  http_parser_buffer_ = buffer;
537
260
}
538
539
3576
inline bool Environment::http_parser_buffer_in_use() const {
540
3576
  return http_parser_buffer_in_use_;
541
}
542
543
7149
inline void Environment::set_http_parser_buffer_in_use(bool in_use) {
544
7149
  http_parser_buffer_in_use_ = in_use;
545
7149
}
546
547
19361
inline http2::Http2State* Environment::http2_state() const {
548
19361
  return http2_state_.get();
549
}
550
551
208
inline void Environment::set_http2_state(
552
    std::unique_ptr<http2::Http2State> buffer) {
553
208
  CHECK(!http2_state_);  // Should be set only once.
554
208
  http2_state_ = std::move(buffer);
555
208
}
556
557
688644
bool Environment::debug_enabled(DebugCategory category) const {
558
  DCHECK_GE(static_cast<int>(category), 0);
559
  DCHECK_LT(static_cast<int>(category),
560
           static_cast<int>(DebugCategory::CATEGORY_COUNT));
561
688644
  return debug_enabled_[static_cast<int>(category)];
562
}
563
564
4
void Environment::set_debug_enabled(DebugCategory category, bool enabled) {
565
  DCHECK_GE(static_cast<int>(category), 0);
566
  DCHECK_LT(static_cast<int>(category),
567
           static_cast<int>(DebugCategory::CATEGORY_COUNT));
568
4
  debug_enabled_[static_cast<int>(category)] = enabled;
569
4
}
570
571
inline AliasedBuffer<double, v8::Float64Array>*
572
176076
Environment::fs_stats_field_array() {
573
176076
  return &fs_stats_field_array_;
574
}
575
576
inline AliasedBuffer<uint64_t, v8::BigUint64Array>*
577
3671
Environment::fs_stats_field_bigint_array() {
578
3671
  return &fs_stats_field_bigint_array_;
579
}
580
581
inline std::vector<std::unique_ptr<fs::FileHandleReadWrap>>&
582
416
Environment::file_handle_read_wrap_freelist() {
583
416
  return file_handle_read_wrap_freelist_;
584
}
585
586
103530
inline std::shared_ptr<EnvironmentOptions> Environment::options() {
587
103530
  return options_;
588
}
589
590
7441
inline std::shared_ptr<HostPort> Environment::inspector_host_port() {
591
7441
  return inspector_host_port_;
592
}
593
594
10910
inline std::shared_ptr<PerIsolateOptions> IsolateData::options() {
595
10910
  return options_;
596
}
597
598
48850
void Environment::CreateImmediate(native_immediate_callback cb,
599
                                  void* data,
600
                                  v8::Local<v8::Object> obj,
601
                                  bool ref) {
602
  native_immediate_callbacks_.push_back({
603
    cb,
604
    data,
605
48850
    std::unique_ptr<Persistent<v8::Object>>(obj.IsEmpty() ?
606
26156
        nullptr : new Persistent<v8::Object>(isolate_, obj)),
607
    ref
608

123856
  });
609
48850
  immediate_info()->count_inc(1);
610
48850
}
611
612
26160
void Environment::SetImmediate(native_immediate_callback cb,
613
                               void* data,
614
                               v8::Local<v8::Object> obj) {
615
26160
  CreateImmediate(cb, data, obj, true);
616
617
26160
  if (immediate_info()->ref_count() == 0)
618
22017
    ToggleImmediateRef(true);
619
26160
  immediate_info()->ref_count_inc(1);
620
26160
}
621
622
22690
void Environment::SetUnrefImmediate(native_immediate_callback cb,
623
                                    void* data,
624
                                    v8::Local<v8::Object> obj) {
625
22690
  CreateImmediate(cb, data, obj, false);
626
22690
}
627
628
2732495
inline bool Environment::can_call_into_js() const {
629

2732495
  return can_call_into_js_ && (is_main_thread() || !is_stopping_worker());
630
}
631
632
3324
inline void Environment::set_can_call_into_js(bool can_call_into_js) {
633
3324
  can_call_into_js_ = can_call_into_js;
634
3324
}
635
636
3671
inline bool Environment::has_run_bootstrapping_code() const {
637
3671
  return has_run_bootstrapping_code_;
638
}
639
640
3671
inline void Environment::set_has_run_bootstrapping_code(bool value) {
641
3671
  has_run_bootstrapping_code_ = value;
642
3671
}
643
644
2774785
inline bool Environment::is_main_thread() const {
645
2774785
  return thread_id_ == 0;
646
}
647
648
521
inline uint64_t Environment::thread_id() const {
649
521
  return thread_id_;
650
}
651
652
119
inline void Environment::set_thread_id(uint64_t id) {
653
119
  thread_id_ = id;
654
119
}
655
656
inline worker::Worker* Environment::worker_context() const {
657
  return worker_context_;
658
}
659
660
119
inline void Environment::set_worker_context(worker::Worker* context) {
661
119
  CHECK_EQ(worker_context_, nullptr);  // Should be set only once.
662
119
  worker_context_ = context;
663
119
}
664
665
118
inline void Environment::add_sub_worker_context(worker::Worker* context) {
666
118
  sub_worker_contexts_.insert(context);
667
118
}
668
669
118
inline void Environment::remove_sub_worker_context(worker::Worker* context) {
670
118
  sub_worker_contexts_.erase(context);
671
118
}
672
673
21735
inline bool Environment::is_stopping_worker() const {
674
21735
  CHECK(!is_main_thread());
675
21735
  return worker_context_->is_stopped();
676
}
677
678
59295
inline performance::performance_state* Environment::performance_state() {
679
59295
  return performance_state_.get();
680
}
681
682
inline std::unordered_map<std::string, uint64_t>*
683
38
    Environment::performance_marks() {
684
38
  return &performance_marks_;
685
}
686
687
4300409
inline IsolateData* Environment::isolate_data() const {
688
4300409
  return isolate_data_;
689
}
690
691
764
inline void Environment::ThrowError(const char* errmsg) {
692
764
  ThrowError(v8::Exception::Error, errmsg);
693
764
}
694
695
5
inline void Environment::ThrowTypeError(const char* errmsg) {
696
5
  ThrowError(v8::Exception::TypeError, errmsg);
697
5
}
698
699
inline void Environment::ThrowRangeError(const char* errmsg) {
700
  ThrowError(v8::Exception::RangeError, errmsg);
701
}
702
703
769
inline void Environment::ThrowError(
704
    v8::Local<v8::Value> (*fun)(v8::Local<v8::String>),
705
    const char* errmsg) {
706
769
  v8::HandleScope handle_scope(isolate());
707
769
  isolate()->ThrowException(fun(OneByteString(isolate(), errmsg)));
708
769
}
709
710
3
inline void Environment::ThrowErrnoException(int errorno,
711
                                             const char* syscall,
712
                                             const char* message,
713
                                             const char* path) {
714
  isolate()->ThrowException(
715
3
      ErrnoException(isolate(), errorno, syscall, message, path));
716
3
}
717
718
14
inline void Environment::ThrowUVException(int errorno,
719
                                          const char* syscall,
720
                                          const char* message,
721
                                          const char* path,
722
                                          const char* dest) {
723
  isolate()->ThrowException(
724
14
      UVException(isolate(), errorno, syscall, message, path, dest));
725
14
}
726
727
inline v8::Local<v8::FunctionTemplate>
728
1249833
    Environment::NewFunctionTemplate(v8::FunctionCallback callback,
729
                                     v8::Local<v8::Signature> signature,
730
                                     v8::ConstructorBehavior behavior,
731
                                     v8::SideEffectType side_effect_type) {
732
1249833
  v8::Local<v8::External> external = as_external();
733
  return v8::FunctionTemplate::New(isolate(), callback, external,
734
1249834
                                   signature, 0, behavior, side_effect_type);
735
}
736
737
520408
inline void Environment::SetMethod(v8::Local<v8::Object> that,
738
                                   const char* name,
739
                                   v8::FunctionCallback callback) {
740
520408
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
741
  v8::Local<v8::Function> function =
742
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
743
                          // TODO(TimothyGu): Investigate if SetMethod is ever
744
                          // used for constructors.
745
                          v8::ConstructorBehavior::kAllow,
746
520408
                          v8::SideEffectType::kHasSideEffect)
747
1561224
          ->GetFunction(context)
748
1040816
          .ToLocalChecked();
749
  // kInternalized strings are created in the old space.
750
520408
  const v8::NewStringType type = v8::NewStringType::kInternalized;
751
  v8::Local<v8::String> name_string =
752
1040816
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
753
1040816
  that->Set(context, name_string, function).FromJust();
754
520408
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
755
520408
}
756
757
243817
inline void Environment::SetMethodNoSideEffect(v8::Local<v8::Object> that,
758
                                               const char* name,
759
                                               v8::FunctionCallback callback) {
760
243817
  v8::Local<v8::Context> context = isolate()->GetCurrentContext();
761
  v8::Local<v8::Function> function =
762
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
763
                          // TODO(TimothyGu): Investigate if SetMethod is ever
764
                          // used for constructors.
765
                          v8::ConstructorBehavior::kAllow,
766
243819
                          v8::SideEffectType::kHasNoSideEffect)
767
731453
          ->GetFunction(context)
768
487636
          .ToLocalChecked();
769
  // kInternalized strings are created in the old space.
770
243819
  const v8::NewStringType type = v8::NewStringType::kInternalized;
771
  v8::Local<v8::String> name_string =
772
487638
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
773
487637
  that->Set(context, name_string, function).FromJust();
774
243818
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
775
243819
}
776
777
323331
inline void Environment::SetProtoMethod(v8::Local<v8::FunctionTemplate> that,
778
                                        const char* name,
779
                                        v8::FunctionCallback callback) {
780
323331
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
781
  v8::Local<v8::FunctionTemplate> t =
782
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
783
323331
                          v8::SideEffectType::kHasSideEffect);
784
  // kInternalized strings are created in the old space.
785
323331
  const v8::NewStringType type = v8::NewStringType::kInternalized;
786
  v8::Local<v8::String> name_string =
787
646662
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
788
646662
  that->PrototypeTemplate()->Set(name_string, t);
789
323331
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
790
323331
}
791
792
35636
inline void Environment::SetProtoMethodNoSideEffect(
793
    v8::Local<v8::FunctionTemplate> that,
794
    const char* name,
795
    v8::FunctionCallback callback) {
796
35636
  v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
797
  v8::Local<v8::FunctionTemplate> t =
798
      NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow,
799
35636
                          v8::SideEffectType::kHasNoSideEffect);
800
  // kInternalized strings are created in the old space.
801
35636
  const v8::NewStringType type = v8::NewStringType::kInternalized;
802
  v8::Local<v8::String> name_string =
803
71272
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
804
71272
  that->PrototypeTemplate()->Set(name_string, t);
805
35636
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
806
35636
}
807
808
inline void Environment::SetTemplateMethod(v8::Local<v8::FunctionTemplate> that,
809
                                           const char* name,
810
                                           v8::FunctionCallback callback) {
811
  v8::Local<v8::FunctionTemplate> t =
812
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
813
                          v8::ConstructorBehavior::kAllow,
814
                          v8::SideEffectType::kHasSideEffect);
815
  // kInternalized strings are created in the old space.
816
  const v8::NewStringType type = v8::NewStringType::kInternalized;
817
  v8::Local<v8::String> name_string =
818
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
819
  that->Set(name_string, t);
820
  t->SetClassName(name_string);  // NODE_SET_METHOD() compatibility.
821
}
822
823
inline void Environment::SetTemplateMethodNoSideEffect(
824
    v8::Local<v8::FunctionTemplate> that,
825
    const char* name,
826
    v8::FunctionCallback callback) {
827
  v8::Local<v8::FunctionTemplate> t =
828
      NewFunctionTemplate(callback, v8::Local<v8::Signature>(),
829
                          v8::ConstructorBehavior::kAllow,
830
                          v8::SideEffectType::kHasNoSideEffect);
831
  // kInternalized strings are created in the old space.
832
  const v8::NewStringType type = v8::NewStringType::kInternalized;
833
  v8::Local<v8::String> name_string =
834
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
835
  that->Set(name_string, t);
836
  t->SetClassName(name_string);  // NODE_SET_METHOD() compatibility.
837
}
838
839
313098
void Environment::AddCleanupHook(void (*fn)(void*), void* arg) {
840
  auto insertion_info = cleanup_hooks_.emplace(CleanupHookCallback {
841
    fn, arg, cleanup_hook_counter_++
842
313098
  });
843
  // Make sure there was no existing element with these values.
844
313098
  CHECK_EQ(insertion_info.second, true);
845
313098
}
846
847
309252
void Environment::RemoveCleanupHook(void (*fn)(void*), void* arg) {
848
309252
  CleanupHookCallback search { fn, arg, 0 };
849
309252
  cleanup_hooks_.erase(search);
850
309251
}
851
852
692867
size_t Environment::CleanupHookCallback::Hash::operator()(
853
    const CleanupHookCallback& cb) const {
854
692867
  return std::hash<void*>()(cb.arg_);
855
}
856
857
344569
bool Environment::CleanupHookCallback::Equal::operator()(
858
    const CleanupHookCallback& a, const CleanupHookCallback& b) const {
859

344569
  return a.fn_ == b.fn_ && a.arg_ == b.arg_;
860
}
861
862
64
BaseObject* Environment::CleanupHookCallback::GetBaseObject() const {
863
64
  if (fn_ == BaseObject::DeleteMe)
864
64
    return static_cast<BaseObject*>(arg_);
865
  else
866
    return nullptr;
867
}
868
869
template <typename T>
870
33
void Environment::ForEachBaseObject(T&& iterator) {
871
97
  for (const auto& hook : cleanup_hooks_) {
872
64
    BaseObject* obj = hook.GetBaseObject();
873
64
    if (obj != nullptr)
874
64
      iterator(obj);
875
  }
876
33
}
877
878
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
879
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
880
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
881
#define V(TypeName, PropertyName)                                             \
882
  inline                                                                      \
883
  v8::Local<TypeName> IsolateData::PropertyName(v8::Isolate* isolate) const { \
884
    /* Strings are immutable so casting away const-ness here is okay. */      \
885
    return const_cast<IsolateData*>(this)->PropertyName ## _.Get(isolate);    \
886
  }
887
15426
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
888
96496
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
889
6172446
  PER_ISOLATE_STRING_PROPERTIES(VS)
890
#undef V
891
#undef VS
892
#undef VY
893
#undef VP
894
895
#define VP(PropertyName, StringValue) V(v8::Private, PropertyName)
896
#define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName)
897
#define VS(PropertyName, StringValue) V(v8::String, PropertyName)
898
#define V(TypeName, PropertyName)                                             \
899
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
900
    return isolate_data()->PropertyName(isolate());                           \
901
  }
902
7713
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
903
48249
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
904
3086209
  PER_ISOLATE_STRING_PROPERTIES(VS)
905
#undef V
906
#undef VS
907
#undef VY
908
#undef VP
909
910
#define V(PropertyName, TypeName)                                             \
911
  inline v8::Local<TypeName> Environment::PropertyName() const {              \
912
    return PersistentToLocal::Strong(PropertyName ## _);                      \
913
  }                                                                           \
914
  inline void Environment::set_ ## PropertyName(v8::Local<TypeName> value) {  \
915
    PropertyName ## _.Reset(isolate(), value);                                \
916
  }
917
11459324
  ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V)
918
#undef V
919
920
}  // namespace node
921
922
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
923
924
#endif  // SRC_ENV_INL_H_