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: 316 400 79.0 %
Date: 2019-02-01 22:03:38 Branches: 39 90 43.3 %

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
257489
inline uv_loop_t* IsolateData::event_loop() const {
47
257489
  return event_loop_;
48
}
49
50
164
inline uint32_t* IsolateData::zero_fill_field() const {
51
164
  return zero_fill_field_;
52
}
53
54
295
inline MultiIsolatePlatform* IsolateData::platform() const {
55
295
  return platform_;
56
}
57
58
164
inline Environment::AsyncHooks::AsyncHooks()
59
    : async_ids_stack_(env()->isolate(), 16 * 2),
60
      fields_(env()->isolate(), kFieldsCount),
61
6888
      async_id_fields_(env()->isolate(), kUidFieldsCount) {
62
164
  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
164
  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
164
  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
164
  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
13612
  NODE_ASYNC_PROVIDER_TYPES(V)
93
#undef V
94
164
}
95
96
inline AliasedBuffer<uint32_t, v8::Uint32Array>&
97
520553
Environment::AsyncHooks::fields() {
98
520553
  return fields_;
99
}
100
101
inline AliasedBuffer<double, v8::Float64Array>&
102
414371
Environment::AsyncHooks::async_id_fields() {
103
414371
  return async_id_fields_;
104
}
105
106
inline AliasedBuffer<double, v8::Float64Array>&
107
164
Environment::AsyncHooks::async_ids_stack() {
108
164
  return async_ids_stack_;
109
}
110
111
8386
inline v8::Local<v8::String> Environment::AsyncHooks::provider_string(int idx) {
112
16772
  return providers_[idx].Get(env()->isolate());
113
}
114
115
inline void Environment::AsyncHooks::no_force_checks() {
116
  fields_[kCheck] -= 1;
117
}
118
119
116128
inline Environment* Environment::AsyncHooks::env() {
120
116128
  return Environment::ForAsyncHooks(this);
121
}
122
123
// Remember to keep this code aligned with pushAsyncIds() in JS.
124
107746
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
107746
  if (fields_[kCheck] > 0) {
129
107746
    CHECK_GE(async_id, -1);
130
107746
    CHECK_GE(trigger_async_id, -1);
131
  }
132
133
107746
  uint32_t offset = fields_[kStackLength];
134
107746
  if (offset * 2 >= async_ids_stack_.Length())
135
    grow_async_ids_stack();
136
107746
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
137
107746
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
138
107746
  fields_[kStackLength] += 1;
139
107746
  async_id_fields_[kExecutionAsyncId] = async_id;
140
107746
  async_id_fields_[kTriggerAsyncId] = trigger_async_id;
141
107746
}
142
143
// Remember to keep this code aligned with popAsyncIds() in JS.
144
107745
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
107745
  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


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


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

1842
  CHECK(info.Data()->IsExternal());
317
  return static_cast<Environment*>(
318
2763
      info.Data().template As<v8::External>()->Value());
319
}
320
321
inline Environment* Environment::GetThreadLocalEnv() {
322
  return static_cast<Environment*>(uv_key_get(&thread_local_env));
323
}
324
325
inline bool Environment::profiler_idle_notifier_started() const {
326
  return profiler_idle_notifier_started_;
327
}
328
329
5872755
inline v8::Isolate* Environment::isolate() const {
330
5872755
  return isolate_;
331
}
332
333
82
inline Environment* Environment::from_timer_handle(uv_timer_t* handle) {
334
82
  return ContainerOf(&Environment::timer_handle_, handle);
335
}
336
337
673
inline uv_timer_t* Environment::timer_handle() {
338
673
  return &timer_handle_;
339
}
340
341
5460
inline Environment* Environment::from_immediate_check_handle(
342
    uv_check_t* handle) {
343
5460
  return ContainerOf(&Environment::immediate_check_handle_, handle);
344
}
345
346
656
inline uv_check_t* Environment::immediate_check_handle() {
347
656
  return &immediate_check_handle_;
348
}
349
350
2609
inline uv_idle_t* Environment::immediate_idle_handle() {
351
2609
  return &immediate_idle_handle_;
352
}
353
354
820
inline void Environment::RegisterHandleCleanup(uv_handle_t* handle,
355
                                               HandleCleanupCb cb,
356
                                               void* arg) {
357
820
  handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg});
358
820
}
359
360
template <typename T, typename OnCloseCallback>
361
798
inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) {
362
798
  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
798
  handle->data = new CloseData { this, callback, handle->data };
374
3192
  uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) {
375
798
    std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) };
376
798
    data->env->handle_cleanup_waiting_--;
377
798
    handle->data = data->original_data;
378
798
    data->callback(reinterpret_cast<T*>(handle));
379
2394
  });
380
798
}
381
382
7574
void Environment::IncreaseWaitingRequestCounter() {
383
7574
  request_waiting_++;
384
7574
}
385
386
7574
void Environment::DecreaseWaitingRequestCounter() {
387
7574
  request_waiting_--;
388
7574
  CHECK_GE(request_waiting_, 0);
389
7574
}
390
391
257324
inline uv_loop_t* Environment::event_loop() const {
392
257324
  return isolate_data()->event_loop();
393
}
394
395
59
inline void Environment::TryLoadAddon(
396
    const char* filename,
397
    int flags,
398
    std::function<bool(binding::DLib*)> was_loaded) {
399
59
  loaded_addons_.emplace_back(filename, flags);
400
59
  if (!was_loaded(&loaded_addons_.back())) {
401
    loaded_addons_.pop_back();
402
  }
403
59
}
404
405
1249567
inline Environment::AsyncHooks* Environment::async_hooks() {
406
1249567
  return &async_hooks_;
407
}
408
409
8702
inline Environment::ImmediateInfo* Environment::immediate_info() {
410
8702
  return &immediate_info_;
411
}
412
413
107003
inline Environment::TickInfo* Environment::tick_info() {
414
107003
  return &tick_info_;
415
}
416
417
388
inline uint64_t Environment::timer_base() const {
418
388
  return timer_base_;
419
}
420
421
inline bool Environment::printed_error() const {
422
  return printed_error_;
423
}
424
425
inline void Environment::set_printed_error(bool value) {
426
  printed_error_ = value;
427
}
428
429
154
inline void Environment::set_trace_sync_io(bool value) {
430
154
  options_->trace_sync_io = value;
431
154
}
432
433
165
inline bool Environment::abort_on_uncaught_exception() const {
434
165
  return options_->abort_on_uncaught_exception;
435
}
436
437
inline void Environment::set_abort_on_uncaught_exception(bool value) {
438
  options_->abort_on_uncaught_exception = value;
439
}
440
441
inline AliasedBuffer<uint32_t, v8::Uint32Array>&
442
165
Environment::should_abort_on_uncaught_toggle() {
443
165
  return should_abort_on_uncaught_toggle_;
444
}
445
446
inline AliasedBuffer<uint8_t, v8::Uint8Array>&
447
164
Environment::trace_category_state() {
448
164
  return trace_category_state_;
449
}
450
451
inline AliasedBuffer<int32_t, v8::Int32Array>&
452
3924
Environment::stream_base_state() {
453
3924
  return stream_base_state_;
454
}
455
456
inline uint32_t Environment::get_next_module_id() {
457
  return module_id_counter_++;
458
}
459
10138
inline uint32_t Environment::get_next_script_id() {
460
10138
  return script_id_counter_++;
461
}
462
463
10138
Environment::ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope(
464
    Environment* env)
465
10138
    : env_(env) {
466
10138
  env_->should_not_abort_scope_counter_++;
467
10138
}
468
469
10138
Environment::ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() {
470
10138
  Close();
471
10138
}
472
473
10138
void Environment::ShouldNotAbortOnUncaughtScope::Close() {
474
10138
  if (env_ != nullptr) {
475
10138
    env_->should_not_abort_scope_counter_--;
476
10138
    env_ = nullptr;
477
  }
478
10138
}
479
480
bool Environment::inside_should_not_abort_on_uncaught_scope() const {
481
  return should_not_abort_scope_counter_ > 0;
482
}
483
484
188
inline std::vector<double>* Environment::destroy_async_id_list() {
485
188
  return &destroy_async_id_list_;
486
}
487
488
102469
inline double Environment::new_async_id() {
489
102469
  async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1;
490
102469
  return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter];
491
}
492
493
102360
inline double Environment::execution_async_id() {
494
102360
  return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId];
495
}
496
497
11
inline double Environment::trigger_async_id() {
498
11
  return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId];
499
}
500
501
102469
inline double Environment::get_default_trigger_async_id() {
502
  double default_trigger_async_id =
503
102469
    async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
504
  // If defaultTriggerAsyncId isn't set, use the executionAsyncId
505
102469
  if (default_trigger_async_id < 0)
506
102349
    default_trigger_async_id = execution_async_id();
507
102469
  return default_trigger_async_id;
508
}
509
510
163
inline double* Environment::heap_statistics_buffer() const {
511
163
  CHECK_NOT_NULL(heap_statistics_buffer_);
512
163
  return heap_statistics_buffer_;
513
}
514
515
163
inline void Environment::set_heap_statistics_buffer(double* pointer) {
516
163
  CHECK_NULL(heap_statistics_buffer_);  // Should be set only once.
517
163
  heap_statistics_buffer_ = pointer;
518
163
}
519
520
163
inline double* Environment::heap_space_statistics_buffer() const {
521
163
  CHECK_NOT_NULL(heap_space_statistics_buffer_);
522
163
  return heap_space_statistics_buffer_;
523
}
524
525
163
inline void Environment::set_heap_space_statistics_buffer(double* pointer) {
526
163
  CHECK_NULL(heap_space_statistics_buffer_);  // Should be set only once.
527
163
  heap_space_statistics_buffer_ = pointer;
528
163
}
529
530
inline char* Environment::http_parser_buffer() const {
531
  return http_parser_buffer_;
532
}
533
534
inline void Environment::set_http_parser_buffer(char* buffer) {
535
  CHECK_NULL(http_parser_buffer_);  // Should be set only once.
536
  http_parser_buffer_ = buffer;
537
}
538
539
inline bool Environment::http_parser_buffer_in_use() const {
540
  return http_parser_buffer_in_use_;
541
}
542
543
inline void Environment::set_http_parser_buffer_in_use(bool in_use) {
544
  http_parser_buffer_in_use_ = in_use;
545
}
546
547
inline http2::Http2State* Environment::http2_state() const {
548
  return http2_state_.get();
549
}
550
551
inline void Environment::set_http2_state(
552
    std::unique_ptr<http2::Http2State> buffer) {
553
  CHECK(!http2_state_);  // Should be set only once.
554
  http2_state_ = std::move(buffer);
555
}
556
557
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
  return debug_enabled_[static_cast<int>(category)];
562
}
563
564
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
  debug_enabled_[static_cast<int>(category)] = enabled;
569
}
570
571
inline AliasedBuffer<double, v8::Float64Array>*
572
29951
Environment::fs_stats_field_array() {
573
29951
  return &fs_stats_field_array_;
574
}
575
576
inline AliasedBuffer<uint64_t, v8::BigUint64Array>*
577
164
Environment::fs_stats_field_bigint_array() {
578
164
  return &fs_stats_field_bigint_array_;
579
}
580
581
inline std::vector<std::unique_ptr<fs::FileHandleReadWrap>>&
582
Environment::file_handle_read_wrap_freelist() {
583
  return file_handle_read_wrap_freelist_;
584
}
585
586
4444
inline std::shared_ptr<EnvironmentOptions> Environment::options() {
587
4444
  return options_;
588
}
589
590
328
inline std::shared_ptr<HostPort> Environment::inspector_host_port() {
591
328
  return inspector_host_port_;
592
}
593
594
497
inline std::shared_ptr<PerIsolateOptions> IsolateData::options() {
595
497
  return options_;
596
}
597
598
inline void IsolateData::set_options(
599
    std::shared_ptr<PerIsolateOptions> options) {
600
  options_ = options;
601
}
602
603
5
void Environment::CreateImmediate(native_immediate_callback cb,
604
                                  void* data,
605
                                  v8::Local<v8::Object> obj,
606
                                  bool ref) {
607
  native_immediate_callbacks_.push_back({
608
    cb,
609
    data,
610
5
    std::unique_ptr<Persistent<v8::Object>>(obj.IsEmpty() ?
611
        nullptr : new Persistent<v8::Object>(isolate_, obj)),
612
    ref
613

10
  });
614
5
  immediate_info()->count_inc(1);
615
5
}
616
617
void Environment::SetImmediate(native_immediate_callback cb,
618
                               void* data,
619
                               v8::Local<v8::Object> obj) {
620
  CreateImmediate(cb, data, obj, true);
621
622
  if (immediate_info()->ref_count() == 0)
623
    ToggleImmediateRef(true);
624
  immediate_info()->ref_count_inc(1);
625
}
626
627
5
void Environment::SetUnrefImmediate(native_immediate_callback cb,
628
                                    void* data,
629
                                    v8::Local<v8::Object> obj) {
630
5
  CreateImmediate(cb, data, obj, false);
631
5
}
632
633
341778
inline bool Environment::can_call_into_js() const {
634

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

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