GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.cc Lines: 1017 1103 92.2 %
Date: 2022-07-18 04:15:58 Branches: 1137 2096 54.2 %

Line Branch Exec Source
1
#include "env.h"
2
#include "async_wrap.h"
3
#include "base_object-inl.h"
4
#include "debug_utils-inl.h"
5
#include "diagnosticfilename-inl.h"
6
#include "memory_tracker-inl.h"
7
#include "node_buffer.h"
8
#include "node_context_data.h"
9
#include "node_errors.h"
10
#include "node_internals.h"
11
#include "node_options-inl.h"
12
#include "node_process-inl.h"
13
#include "node_v8_platform-inl.h"
14
#include "node_worker.h"
15
#include "req_wrap-inl.h"
16
#include "stream_base.h"
17
#include "tracing/agent.h"
18
#include "tracing/traced_value.h"
19
#include "util-inl.h"
20
#include "v8-profiler.h"
21
22
#include <algorithm>
23
#include <atomic>
24
#include <cinttypes>
25
#include <cstdio>
26
#include <iostream>
27
#include <limits>
28
#include <memory>
29
30
namespace node {
31
32
using errors::TryCatchScope;
33
using v8::Array;
34
using v8::Boolean;
35
using v8::Context;
36
using v8::EmbedderGraph;
37
using v8::EscapableHandleScope;
38
using v8::Function;
39
using v8::FunctionCallbackInfo;
40
using v8::FunctionTemplate;
41
using v8::HandleScope;
42
using v8::HeapSpaceStatistics;
43
using v8::Integer;
44
using v8::Isolate;
45
using v8::Local;
46
using v8::MaybeLocal;
47
using v8::NewStringType;
48
using v8::Number;
49
using v8::Object;
50
using v8::Private;
51
using v8::Script;
52
using v8::SnapshotCreator;
53
using v8::StackTrace;
54
using v8::String;
55
using v8::Symbol;
56
using v8::TracingController;
57
using v8::TryCatch;
58
using v8::Undefined;
59
using v8::Value;
60
using v8::WeakCallbackInfo;
61
using v8::WeakCallbackType;
62
using worker::Worker;
63
64
int const Environment::kNodeContextTag = 0x6e6f64;
65
void* const Environment::kNodeContextTagPtr = const_cast<void*>(
66
    static_cast<const void*>(&Environment::kNodeContextTag));
67
68
15381
void AsyncHooks::SetJSPromiseHooks(Local<Function> init,
69
                                   Local<Function> before,
70
                                   Local<Function> after,
71
                                   Local<Function> resolve) {
72
15381
  js_promise_hooks_[0].Reset(env()->isolate(), init);
73
15381
  js_promise_hooks_[1].Reset(env()->isolate(), before);
74
15381
  js_promise_hooks_[2].Reset(env()->isolate(), after);
75
15381
  js_promise_hooks_[3].Reset(env()->isolate(), resolve);
76
31107
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
77
15726
    if (it->IsEmpty()) {
78
      contexts_.erase(it--);
79
      continue;
80
    }
81
31452
    PersistentToLocal::Weak(env()->isolate(), *it)
82
15726
        ->SetPromiseHooks(init, before, after, resolve);
83
  }
84
15381
}
85
86
// Remember to keep this code aligned with pushAsyncContext() in JS.
87
788735
void AsyncHooks::push_async_context(double async_id,
88
                                    double trigger_async_id,
89
                                    Local<Object> resource) {
90
  // Since async_hooks is experimental, do only perform the check
91
  // when async_hooks is enabled.
92
788735
  if (fields_[kCheck] > 0) {
93
788731
    CHECK_GE(async_id, -1);
94
788731
    CHECK_GE(trigger_async_id, -1);
95
  }
96
97
788735
  uint32_t offset = fields_[kStackLength];
98
788735
  if (offset * 2 >= async_ids_stack_.Length()) grow_async_ids_stack();
99
788735
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
100
788735
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
101
788735
  fields_[kStackLength] += 1;
102
788735
  async_id_fields_[kExecutionAsyncId] = async_id;
103
788735
  async_id_fields_[kTriggerAsyncId] = trigger_async_id;
104
105
#ifdef DEBUG
106
  for (uint32_t i = offset; i < native_execution_async_resources_.size(); i++)
107
    CHECK(native_execution_async_resources_[i].IsEmpty());
108
#endif
109
110
  // When this call comes from JS (as a way of increasing the stack size),
111
  // `resource` will be empty, because JS caches these values anyway.
112
788735
  if (!resource.IsEmpty()) {
113
788731
    native_execution_async_resources_.resize(offset + 1);
114
    // Caveat: This is a v8::Local<> assignment, we do not keep a v8::Global<>!
115
788731
    native_execution_async_resources_[offset] = resource;
116
  }
117
788735
}
118
119
// Remember to keep this code aligned with popAsyncContext() in JS.
120
788331
bool AsyncHooks::pop_async_context(double async_id) {
121
  // In case of an exception then this may have already been reset, if the
122
  // stack was multiple MakeCallback()'s deep.
123
788331
  if (UNLIKELY(fields_[kStackLength] == 0)) return false;
124
125
  // Ask for the async_id to be restored as a check that the stack
126
  // hasn't been corrupted.
127
1574546
  if (UNLIKELY(fields_[kCheck] > 0 &&
128

1574546
               async_id_fields_[kExecutionAsyncId] != async_id)) {
129
4
    FailWithCorruptedAsyncStack(async_id);
130
  }
131
132
787271
  uint32_t offset = fields_[kStackLength] - 1;
133
787271
  async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
134
787271
  async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
135
787271
  fields_[kStackLength] = offset;
136
137
1574542
  if (LIKELY(offset < native_execution_async_resources_.size() &&
138

1574542
             !native_execution_async_resources_[offset].IsEmpty())) {
139
#ifdef DEBUG
140
    for (uint32_t i = offset + 1; i < native_execution_async_resources_.size();
141
         i++) {
142
      CHECK(native_execution_async_resources_[i].IsEmpty());
143
    }
144
#endif
145
787271
    native_execution_async_resources_.resize(offset);
146
787271
    if (native_execution_async_resources_.size() <
147

1019332
            native_execution_async_resources_.capacity() / 2 &&
148
232061
        native_execution_async_resources_.size() > 16) {
149
      native_execution_async_resources_.shrink_to_fit();
150
    }
151
  }
152
153
1574542
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
154
29911
    HandleScope handle_scope(env()->isolate());
155
59822
    USE(js_execution_async_resources()->Set(
156
        env()->context(),
157
        env()->length_string(),
158
119644
        Integer::NewFromUnsigned(env()->isolate(), offset)));
159
  }
160
161
787271
  return fields_[kStackLength] > 0;
162
}
163
164
3316
void AsyncHooks::clear_async_id_stack() {
165
3316
  Isolate* isolate = env()->isolate();
166
3316
  HandleScope handle_scope(isolate);
167
3316
  if (!js_execution_async_resources_.IsEmpty()) {
168
4016
    USE(PersistentToLocal::Strong(js_execution_async_resources_)
169
4016
            ->Set(env()->context(),
170
                  env()->length_string(),
171
8032
                  Integer::NewFromUnsigned(isolate, 0)));
172
  }
173
3316
  native_execution_async_resources_.clear();
174
3316
  native_execution_async_resources_.shrink_to_fit();
175
176
3316
  async_id_fields_[kExecutionAsyncId] = 0;
177
3316
  async_id_fields_[kTriggerAsyncId] = 0;
178
3316
  fields_[kStackLength] = 0;
179
3316
}
180
181
7174
void AsyncHooks::AddContext(Local<Context> ctx) {
182
21522
  ctx->SetPromiseHooks(js_promise_hooks_[0].IsEmpty()
183
7174
                           ? Local<Function>()
184
205
                           : PersistentToLocal::Strong(js_promise_hooks_[0]),
185
7174
                       js_promise_hooks_[1].IsEmpty()
186
7174
                           ? Local<Function>()
187
205
                           : PersistentToLocal::Strong(js_promise_hooks_[1]),
188
7174
                       js_promise_hooks_[2].IsEmpty()
189
7174
                           ? Local<Function>()
190
205
                           : PersistentToLocal::Strong(js_promise_hooks_[2]),
191
7174
                       js_promise_hooks_[3].IsEmpty()
192
7174
                           ? Local<Function>()
193
                           : PersistentToLocal::Strong(js_promise_hooks_[3]));
194
195
7174
  size_t id = contexts_.size();
196
7174
  contexts_.resize(id + 1);
197
7174
  contexts_[id].Reset(env()->isolate(), ctx);
198
7174
  contexts_[id].SetWeak();
199
7174
}
200
201
499
void AsyncHooks::RemoveContext(Local<Context> ctx) {
202
499
  Isolate* isolate = env()->isolate();
203
998
  HandleScope handle_scope(isolate);
204
499
  contexts_.erase(std::remove_if(contexts_.begin(),
205
                                 contexts_.end(),
206
3615
                                 [&](auto&& el) { return el.IsEmpty(); }),
207
998
                  contexts_.end());
208
3542
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
209
3043
    Local<Context> saved_context = PersistentToLocal::Weak(isolate, *it);
210
3043
    if (saved_context == ctx) {
211
      it->Reset();
212
      contexts_.erase(it);
213
      break;
214
    }
215
  }
216
499
}
217
218
244002
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
219
244002
    Environment* env, double default_trigger_async_id)
220
244002
    : async_hooks_(env->async_hooks()) {
221
244002
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
222
244002
    CHECK_GE(default_trigger_async_id, 0);
223
  }
224
225
244002
  old_default_trigger_async_id_ =
226
244002
      async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
227
244002
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
228
244002
      default_trigger_async_id;
229
244002
}
230
231
488002
AsyncHooks::DefaultTriggerAsyncIdScope::~DefaultTriggerAsyncIdScope() {
232
244001
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
233
244001
      old_default_trigger_async_id_;
234
244001
}
235
236
244002
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
237
244002
    AsyncWrap* async_wrap)
238
    : DefaultTriggerAsyncIdScope(async_wrap->env(),
239
244002
                                 async_wrap->get_async_id()) {}
240
241
6
std::vector<size_t> IsolateData::Serialize(SnapshotCreator* creator) {
242
6
  Isolate* isolate = creator->GetIsolate();
243
6
  std::vector<size_t> indexes;
244
12
  HandleScope handle_scope(isolate);
245
  // XXX(joyeecheung): technically speaking, the indexes here should be
246
  // consecutive and we could just return a range instead of an array,
247
  // but that's not part of the V8 API contract so we use an array
248
  // just to be safe.
249
250
#define VP(PropertyName, StringValue) V(Private, PropertyName)
251
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
252
#define VS(PropertyName, StringValue) V(String, PropertyName)
253
#define V(TypeName, PropertyName)                                              \
254
  indexes.push_back(creator->AddData(PropertyName##_.Get(isolate)));
255
54
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
256
78
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
257
1656
  PER_ISOLATE_STRING_PROPERTIES(VS)
258
#undef V
259
#undef VY
260
#undef VS
261
#undef VP
262
354
  for (size_t i = 0; i < AsyncWrap::PROVIDERS_LENGTH; i++)
263
696
    indexes.push_back(creator->AddData(async_wrap_provider(i)));
264
265
6
  return indexes;
266
}
267
268
5255
void IsolateData::DeserializeProperties(const std::vector<size_t>* indexes) {
269
5255
  size_t i = 0;
270
10510
  HandleScope handle_scope(isolate_);
271
272
#define VP(PropertyName, StringValue) V(Private, PropertyName)
273
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
274
#define VS(PropertyName, StringValue) V(String, PropertyName)
275
#define V(TypeName, PropertyName)                                              \
276
  do {                                                                         \
277
    MaybeLocal<TypeName> maybe_field =                                         \
278
        isolate_->GetDataFromSnapshotOnce<TypeName>((*indexes)[i++]);          \
279
    Local<TypeName> field;                                                     \
280
    if (!maybe_field.ToLocal(&field)) {                                        \
281
      fprintf(stderr, "Failed to deserialize " #PropertyName "\n");            \
282
    }                                                                          \
283
    PropertyName##_.Set(isolate_, field);                                      \
284
  } while (0);
285




89335
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
286






131375
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
287









































































































































2895505
  PER_ISOLATE_STRING_PROPERTIES(VS)
288
#undef V
289
#undef VY
290
#undef VS
291
#undef VP
292
293
310045
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
294
    MaybeLocal<String> maybe_field =
295
609580
        isolate_->GetDataFromSnapshotOnce<String>((*indexes)[i++]);
296
    Local<String> field;
297
304790
    if (!maybe_field.ToLocal(&field)) {
298
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
299
    }
300
304790
    async_wrap_providers_[j].Set(isolate_, field);
301
  }
302
5255
}
303
304
1316
void IsolateData::CreateProperties() {
305
  // Create string and private symbol properties as internalized one byte
306
  // strings after the platform is properly initialized.
307
  //
308
  // Internalized because it makes property lookups a little faster and
309
  // because the string is created in the old space straight away.  It's going
310
  // to end up in the old space sooner or later anyway but now it doesn't go
311
  // through v8::Eternal's new space handling first.
312
  //
313
  // One byte because our strings are ASCII and we can safely skip V8's UTF-8
314
  // decoding step.
315
316
1316
  HandleScope handle_scope(isolate_);
317
318
#define V(PropertyName, StringValue)                                           \
319
  PropertyName##_.Set(                                                         \
320
      isolate_,                                                                \
321
      Private::New(isolate_,                                                   \
322
                   String::NewFromOneByte(                                     \
323
                       isolate_,                                               \
324
                       reinterpret_cast<const uint8_t*>(StringValue),          \
325
                       NewStringType::kInternalized,                           \
326
                       sizeof(StringValue) - 1)                                \
327
                       .ToLocalChecked()));
328
11844
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)
329
#undef V
330
#define V(PropertyName, StringValue)                                           \
331
  PropertyName##_.Set(                                                         \
332
      isolate_,                                                                \
333
      Symbol::New(isolate_,                                                    \
334
                  String::NewFromOneByte(                                      \
335
                      isolate_,                                                \
336
                      reinterpret_cast<const uint8_t*>(StringValue),           \
337
                      NewStringType::kInternalized,                            \
338
                      sizeof(StringValue) - 1)                                 \
339
                      .ToLocalChecked()));
340
17108
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
341
#undef V
342
#define V(PropertyName, StringValue)                                           \
343
  PropertyName##_.Set(                                                         \
344
      isolate_,                                                                \
345
      String::NewFromOneByte(isolate_,                                         \
346
                             reinterpret_cast<const uint8_t*>(StringValue),    \
347
                             NewStringType::kInternalized,                     \
348
                             sizeof(StringValue) - 1)                          \
349
          .ToLocalChecked());
350
363216
  PER_ISOLATE_STRING_PROPERTIES(V)
351
#undef V
352
353
  // Create all the provider strings that will be passed to JS. Place them in
354
  // an array so the array index matches the PROVIDER id offset. This way the
355
  // strings can be retrieved quickly.
356
#define V(Provider)                                                           \
357
  async_wrap_providers_[AsyncWrap::PROVIDER_ ## Provider].Set(                \
358
      isolate_,                                                               \
359
      String::NewFromOneByte(                                                 \
360
        isolate_,                                                             \
361
        reinterpret_cast<const uint8_t*>(#Provider),                          \
362
        NewStringType::kInternalized,                                         \
363
        sizeof(#Provider) - 1).ToLocalChecked());
364
77644
  NODE_ASYNC_PROVIDER_TYPES(V)
365
#undef V
366
1316
}
367
368
6571
IsolateData::IsolateData(Isolate* isolate,
369
                         uv_loop_t* event_loop,
370
                         MultiIsolatePlatform* platform,
371
                         ArrayBufferAllocator* node_allocator,
372
6571
                         const std::vector<size_t>* indexes)
373
    : isolate_(isolate),
374
      event_loop_(event_loop),
375
47
      node_allocator_(node_allocator == nullptr ? nullptr
376
6524
                                                : node_allocator->GetImpl()),
377
13142
      platform_(platform) {
378
6571
  options_.reset(
379
6571
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
380
381
6571
  if (indexes == nullptr) {
382
1316
    CreateProperties();
383
  } else {
384
5255
    DeserializeProperties(indexes);
385
  }
386
6571
}
387
388
24
void IsolateData::MemoryInfo(MemoryTracker* tracker) const {
389
#define V(PropertyName, StringValue)                                           \
390
  tracker->TrackField(#PropertyName, PropertyName());
391
24
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
392
393
24
  PER_ISOLATE_STRING_PROPERTIES(V)
394
#undef V
395
396
24
  tracker->TrackField("async_wrap_providers", async_wrap_providers_);
397
398
24
  if (node_allocator_ != nullptr) {
399
24
    tracker->TrackFieldWithSize(
400
        "node_allocator", sizeof(*node_allocator_), "NodeArrayBufferAllocator");
401
  }
402
24
  tracker->TrackFieldWithSize(
403
      "platform", sizeof(*platform_), "MultiIsolatePlatform");
404
  // TODO(joyeecheung): implement MemoryRetainer in the option classes.
405
24
}
406
407
121
void TrackingTraceStateObserver::UpdateTraceCategoryState() {
408

121
  if (!env_->owns_process_state() || !env_->can_call_into_js()) {
409
    // Ideally, we’d have a consistent story that treats all threads/Environment
410
    // instances equally here. However, tracing is essentially global, and this
411
    // callback is called from whichever thread calls `StartTracing()` or
412
    // `StopTracing()`. The only way to do this in a threadsafe fashion
413
    // seems to be only tracking this from the main thread, and only allowing
414
    // these state modifications from the main thread.
415
63
    return;
416
  }
417
418
110
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
419
110
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
420
421
110
  Isolate* isolate = env_->isolate();
422
110
  HandleScope handle_scope(isolate);
423
110
  Local<Function> cb = env_->trace_category_state_function();
424
110
  if (cb.IsEmpty())
425
52
    return;
426
58
  TryCatchScope try_catch(env_);
427
58
  try_catch.SetVerbose(true);
428
116
  Local<Value> args[] = {Boolean::New(isolate, async_hooks_enabled)};
429
116
  USE(cb->Call(env_->context(), Undefined(isolate), arraysize(args), args));
430
}
431
432
7174
void Environment::AssignToContext(Local<v8::Context> context,
433
                                  const ContextInfo& info) {
434
7174
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
435
                                           this);
436
  // Used by Environment::GetCurrent to know that we are on a node context.
437
7174
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kContextTag,
438
                                           Environment::kNodeContextTagPtr);
439
  // Used to retrieve bindings
440
14348
  context->SetAlignedPointerInEmbedderData(
441
7174
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
442
443
#if HAVE_INSPECTOR
444
7174
  inspector_agent()->ContextCreated(context, info);
445
#endif  // HAVE_INSPECTOR
446
447
7174
  this->async_hooks()->AddContext(context);
448
7174
}
449
450
170
void Environment::TryLoadAddon(
451
    const char* filename,
452
    int flags,
453
    const std::function<bool(binding::DLib*)>& was_loaded) {
454
170
  loaded_addons_.emplace_back(filename, flags);
455
170
  if (!was_loaded(&loaded_addons_.back())) {
456
8
    loaded_addons_.pop_back();
457
  }
458
170
}
459
460
11
std::string Environment::GetCwd() {
461
  char cwd[PATH_MAX_BYTES];
462
11
  size_t size = PATH_MAX_BYTES;
463
11
  const int err = uv_cwd(cwd, &size);
464
465
11
  if (err == 0) {
466
11
    CHECK_GT(size, 0);
467
11
    return cwd;
468
  }
469
470
  // This can fail if the cwd is deleted. In that case, fall back to
471
  // exec_path.
472
  const std::string& exec_path = exec_path_;
473
  return exec_path.substr(0, exec_path.find_last_of(kPathSeparator));
474
}
475
476
2945
void Environment::add_refs(int64_t diff) {
477
2945
  task_queues_async_refs_ += diff;
478
2945
  CHECK_GE(task_queues_async_refs_, 0);
479
2945
  if (task_queues_async_refs_ == 0)
480
196
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
481
  else
482
2749
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
483
2945
}
484
485
67152
uv_buf_t Environment::allocate_managed_buffer(const size_t suggested_size) {
486
134304
  NoArrayBufferZeroFillScope no_zero_fill_scope(isolate_data());
487
  std::unique_ptr<v8::BackingStore> bs =
488
67152
      v8::ArrayBuffer::NewBackingStore(isolate(), suggested_size);
489
67152
  uv_buf_t buf = uv_buf_init(static_cast<char*>(bs->Data()), bs->ByteLength());
490
67152
  released_allocated_buffers_.emplace(buf.base, std::move(bs));
491
67152
  return buf;
492
}
493
494
82083
std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer(
495
    const uv_buf_t& buf) {
496
82083
  std::unique_ptr<v8::BackingStore> bs;
497
82083
  if (buf.base != nullptr) {
498
67152
    auto it = released_allocated_buffers_.find(buf.base);
499
67152
    CHECK_NE(it, released_allocated_buffers_.end());
500
67152
    bs = std::move(it->second);
501
67152
    released_allocated_buffers_.erase(it);
502
  }
503
82083
  return bs;
504
}
505
506
1472032
Local<v8::FunctionTemplate> Environment::NewFunctionTemplate(
507
    v8::FunctionCallback callback,
508
    Local<v8::Signature> signature,
509
    v8::ConstructorBehavior behavior,
510
    v8::SideEffectType side_effect_type,
511
    const v8::CFunction* c_function) {
512
  return v8::FunctionTemplate::New(isolate(),
513
                                   callback,
514
                                   Local<v8::Value>(),
515
                                   signature,
516
                                   0,
517
                                   behavior,
518
                                   side_effect_type,
519
1472032
                                   c_function);
520
}
521
522
375887
void Environment::SetMethod(Local<v8::Object> that,
523
                            const char* name,
524
                            v8::FunctionCallback callback) {
525
375887
  Local<v8::Context> context = isolate()->GetCurrentContext();
526
  Local<v8::Function> function =
527
375887
      NewFunctionTemplate(callback,
528
                          Local<v8::Signature>(),
529
                          v8::ConstructorBehavior::kThrow,
530
375887
                          v8::SideEffectType::kHasSideEffect)
531
375887
          ->GetFunction(context)
532
375887
          .ToLocalChecked();
533
  // kInternalized strings are created in the old space.
534
375887
  const v8::NewStringType type = v8::NewStringType::kInternalized;
535
  Local<v8::String> name_string =
536
751774
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
537
751774
  that->Set(context, name_string, function).Check();
538
375887
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
539
375887
}
540
541
2616
void Environment::SetFastMethod(Local<v8::Object> that,
542
                                const char* name,
543
                                v8::FunctionCallback slow_callback,
544
                                const v8::CFunction* c_function) {
545
2616
  Local<v8::Context> context = isolate()->GetCurrentContext();
546
  Local<v8::Function> function =
547
2616
      NewFunctionTemplate(slow_callback,
548
                          Local<v8::Signature>(),
549
                          v8::ConstructorBehavior::kThrow,
550
                          v8::SideEffectType::kHasNoSideEffect,
551
2616
                          c_function)
552
2616
          ->GetFunction(context)
553
2616
          .ToLocalChecked();
554
2616
  const v8::NewStringType type = v8::NewStringType::kInternalized;
555
  Local<v8::String> name_string =
556
5232
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
557
2616
  that->Set(context, name_string, function).Check();
558
2616
}
559
560
113915
void Environment::SetMethodNoSideEffect(Local<v8::Object> that,
561
                                        const char* name,
562
                                        v8::FunctionCallback callback) {
563
113915
  Local<v8::Context> context = isolate()->GetCurrentContext();
564
  Local<v8::Function> function =
565
113915
      NewFunctionTemplate(callback,
566
                          Local<v8::Signature>(),
567
                          v8::ConstructorBehavior::kThrow,
568
113915
                          v8::SideEffectType::kHasNoSideEffect)
569
113915
          ->GetFunction(context)
570
113915
          .ToLocalChecked();
571
  // kInternalized strings are created in the old space.
572
113915
  const v8::NewStringType type = v8::NewStringType::kInternalized;
573
  Local<v8::String> name_string =
574
227830
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
575
227830
  that->Set(context, name_string, function).Check();
576
113915
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
577
113915
}
578
579
673026
void Environment::SetProtoMethod(Local<v8::FunctionTemplate> that,
580
                                 const char* name,
581
                                 v8::FunctionCallback callback) {
582
673026
  Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
583
  Local<v8::FunctionTemplate> t =
584
      NewFunctionTemplate(callback,
585
                          signature,
586
                          v8::ConstructorBehavior::kThrow,
587
673026
                          v8::SideEffectType::kHasSideEffect);
588
  // kInternalized strings are created in the old space.
589
673026
  const v8::NewStringType type = v8::NewStringType::kInternalized;
590
  Local<v8::String> name_string =
591
1346052
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
592
1346052
  that->PrototypeTemplate()->Set(name_string, t);
593
673026
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
594
673026
}
595
596
98449
void Environment::SetProtoMethodNoSideEffect(Local<v8::FunctionTemplate> that,
597
                                             const char* name,
598
                                             v8::FunctionCallback callback) {
599
98449
  Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
600
  Local<v8::FunctionTemplate> t =
601
      NewFunctionTemplate(callback,
602
                          signature,
603
                          v8::ConstructorBehavior::kThrow,
604
98449
                          v8::SideEffectType::kHasNoSideEffect);
605
  // kInternalized strings are created in the old space.
606
98449
  const v8::NewStringType type = v8::NewStringType::kInternalized;
607
  Local<v8::String> name_string =
608
196898
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
609
196898
  that->PrototypeTemplate()->Set(name_string, t);
610
98449
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
611
98449
}
612
613
33
void Environment::SetInstanceMethod(Local<v8::FunctionTemplate> that,
614
                                    const char* name,
615
                                    v8::FunctionCallback callback) {
616
33
  Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
617
  Local<v8::FunctionTemplate> t =
618
      NewFunctionTemplate(callback,
619
                          signature,
620
                          v8::ConstructorBehavior::kThrow,
621
33
                          v8::SideEffectType::kHasSideEffect);
622
  // kInternalized strings are created in the old space.
623
33
  const v8::NewStringType type = v8::NewStringType::kInternalized;
624
  Local<v8::String> name_string =
625
66
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
626
66
  that->InstanceTemplate()->Set(name_string, t);
627
33
  t->SetClassName(name_string);
628
33
}
629
630
134518
void Environment::SetConstructorFunction(Local<v8::Object> that,
631
                                         const char* name,
632
                                         Local<v8::FunctionTemplate> tmpl,
633
                                         SetConstructorFunctionFlag flag) {
634
134518
  SetConstructorFunction(that, OneByteString(isolate(), name), tmpl, flag);
635
134518
}
636
637
141058
void Environment::SetConstructorFunction(Local<v8::Object> that,
638
                                         Local<v8::String> name,
639
                                         Local<v8::FunctionTemplate> tmpl,
640
                                         SetConstructorFunctionFlag flag) {
641
141058
  if (LIKELY(flag == SetConstructorFunctionFlag::SET_CLASS_NAME))
642
126700
    tmpl->SetClassName(name);
643
282116
  that->Set(context(), name, tmpl->GetFunction(context()).ToLocalChecked())
644
      .Check();
645
141058
}
646
647
1308
void Environment::CreateProperties() {
648
2616
  HandleScope handle_scope(isolate_);
649
1308
  Local<Context> ctx = context();
650
651
  {
652
1308
    Context::Scope context_scope(ctx);
653
1308
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
654
2616
    templ->InstanceTemplate()->SetInternalFieldCount(
655
        BaseObject::kInternalFieldCount);
656
1308
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
657
658
1308
    set_binding_data_ctor_template(templ);
659
  }
660
661
  // Store primordials setup by the per-context script in the environment.
662
  Local<Object> per_context_bindings =
663
2616
      GetPerContextExports(ctx).ToLocalChecked();
664
  Local<Value> primordials =
665
3924
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
666
1308
  CHECK(primordials->IsObject());
667
1308
  set_primordials(primordials.As<Object>());
668
669
  Local<String> prototype_string =
670
1308
      FIXED_ONE_BYTE_STRING(isolate(), "prototype");
671
672
#define V(EnvPropertyName, PrimordialsPropertyName)                            \
673
  {                                                                            \
674
    Local<Value> ctor =                                                        \
675
        primordials.As<Object>()                                               \
676
            ->Get(ctx,                                                         \
677
                  FIXED_ONE_BYTE_STRING(isolate(), PrimordialsPropertyName))   \
678
            .ToLocalChecked();                                                 \
679
    CHECK(ctor->IsObject());                                                   \
680
    Local<Value> prototype =                                                   \
681
        ctor.As<Object>()->Get(ctx, prototype_string).ToLocalChecked();        \
682
    CHECK(prototype->IsObject());                                              \
683
    set_##EnvPropertyName(prototype.As<Object>());                             \
684
  }
685
686

7848
  V(primordials_safe_map_prototype_object, "SafeMap");
687

7848
  V(primordials_safe_set_prototype_object, "SafeSet");
688

7848
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
689

7848
  V(primordials_safe_weak_set_prototype_object, "SafeWeakSet");
690
#undef V
691
692
  Local<Object> process_object =
693
1308
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
694
1308
  set_process_object(process_object);
695
1308
}
696
697
6563
std::string GetExecPath(const std::vector<std::string>& argv) {
698
  char exec_path_buf[2 * PATH_MAX];
699
6563
  size_t exec_path_len = sizeof(exec_path_buf);
700
6563
  std::string exec_path;
701
6563
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
702
6563
    exec_path = std::string(exec_path_buf, exec_path_len);
703
  } else {
704
    exec_path = argv[0];
705
  }
706
707
  // On OpenBSD process.execPath will be relative unless we
708
  // get the full path before process.execPath is used.
709
#if defined(__OpenBSD__)
710
  uv_fs_t req;
711
  req.ptr = nullptr;
712
  if (0 ==
713
      uv_fs_realpath(nullptr, &req, exec_path.c_str(), nullptr)) {
714
    CHECK_NOT_NULL(req.ptr);
715
    exec_path = std::string(static_cast<char*>(req.ptr));
716
  }
717
  uv_fs_req_cleanup(&req);
718
#endif
719
720
6563
  return exec_path;
721
}
722
723
6563
Environment::Environment(IsolateData* isolate_data,
724
                         Isolate* isolate,
725
                         const std::vector<std::string>& args,
726
                         const std::vector<std::string>& exec_args,
727
                         const EnvSerializeInfo* env_info,
728
                         EnvironmentFlags::Flags flags,
729
6563
                         ThreadId thread_id)
730
    : isolate_(isolate),
731
      isolate_data_(isolate_data),
732
      async_hooks_(isolate, MAYBE_FIELD_PTR(env_info, async_hooks)),
733
      immediate_info_(isolate, MAYBE_FIELD_PTR(env_info, immediate_info)),
734
      tick_info_(isolate, MAYBE_FIELD_PTR(env_info, tick_info)),
735
6563
      timer_base_(uv_now(isolate_data->event_loop())),
736
      exec_argv_(exec_args),
737
      argv_(args),
738
      exec_path_(GetExecPath(args)),
739
      should_abort_on_uncaught_toggle_(
740
6563
          isolate_,
741
          1,
742
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
743
6563
      stream_base_state_(isolate_,
744
                         StreamBase::kNumStreamBaseStateFields,
745
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
746
6563
      time_origin_(PERFORMANCE_NOW()),
747
6563
      time_origin_timestamp_(GetCurrentTimeInMicroseconds()),
748
      flags_(flags),
749
6563
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
750
6563
                     ? AllocateEnvironmentThreadId().id
751



26252
                     : thread_id.id) {
752
  // We'll be creating new objects so make sure we've entered the context.
753
13126
  HandleScope handle_scope(isolate);
754
755
  // Set some flags if only kDefaultFlags was passed. This can make API version
756
  // transitions easier for embedders.
757
6563
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
758
10616
    flags_ = flags_ |
759
5308
        EnvironmentFlags::kOwnsProcessState |
760
        EnvironmentFlags::kOwnsInspector;
761
  }
762
763
6563
  set_env_vars(per_process::system_environment);
764
6563
  enabled_debug_list_.Parse(env_vars(), isolate);
765
766
  // We create new copies of the per-Environment option sets, so that it is
767
  // easier to modify them after Environment creation. The defaults are
768
  // part of the per-Isolate option set, for which in turn the defaults are
769
  // part of the per-process option set.
770
13126
  options_ = std::make_shared<EnvironmentOptions>(
771
19689
      *isolate_data->options()->per_env);
772
6563
  inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
773
6563
      options_->debug_options().host_port);
774
775
6563
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
776
1255
    set_abort_on_uncaught_exception(false);
777
  }
778
779
#if HAVE_INSPECTOR
780
  // We can only create the inspector agent after having cloned the options.
781
6563
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
782
#endif
783
784
6563
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
785
6563
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
786
6563
    if (TracingController* tracing_controller = writer->GetTracingController())
787
6515
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
788
  }
789
790
6563
  destroy_async_id_list_.reserve(512);
791
792
6563
  performance_state_ = std::make_unique<performance::PerformanceState>(
793
6563
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
794
795
6563
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
796
6563
          TRACING_CATEGORY_NODE1(environment)) != 0) {
797
16
    auto traced_value = tracing::TracedValue::Create();
798
8
    traced_value->BeginArray("args");
799
18
    for (const std::string& arg : args) traced_value->AppendString(arg);
800
8
    traced_value->EndArray();
801
8
    traced_value->BeginArray("exec_args");
802
33
    for (const std::string& arg : exec_args) traced_value->AppendString(arg);
803
8
    traced_value->EndArray();
804

15
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(environment),
805
                                      "Environment",
806
                                      this,
807
                                      "args",
808
                                      std::move(traced_value));
809
  }
810
6563
}
811
812
1308
Environment::Environment(IsolateData* isolate_data,
813
                         Local<Context> context,
814
                         const std::vector<std::string>& args,
815
                         const std::vector<std::string>& exec_args,
816
                         const EnvSerializeInfo* env_info,
817
                         EnvironmentFlags::Flags flags,
818
1308
                         ThreadId thread_id)
819
    : Environment(isolate_data,
820
                  context->GetIsolate(),
821
                  args,
822
                  exec_args,
823
                  env_info,
824
                  flags,
825
1308
                  thread_id) {
826
1308
  InitializeMainContext(context, env_info);
827
1308
}
828
829
6563
void Environment::InitializeMainContext(Local<Context> context,
830
                                        const EnvSerializeInfo* env_info) {
831
6563
  context_.Reset(context->GetIsolate(), context);
832
6563
  AssignToContext(context, ContextInfo(""));
833
6563
  if (env_info != nullptr) {
834
5255
    DeserializeProperties(env_info);
835
  } else {
836
1308
    CreateProperties();
837
  }
838
839
6563
  if (!options_->force_async_hooks_checks) {
840
1
    async_hooks_.no_force_checks();
841
  }
842
843
  // By default, always abort when --abort-on-uncaught-exception was passed.
844
6563
  should_abort_on_uncaught_toggle_[0] = 1;
845
846
6563
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
847
                           time_origin_);
848
6563
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
849
                           per_process::node_start_time);
850
851
6563
  if (per_process::v8_initialized) {
852
6515
    performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
853
                            performance::performance_v8_start);
854
  }
855
6563
}
856
857
1232568
Environment::~Environment() {
858
  if (Environment** interrupt_data = interrupt_data_.load()) {
859
    // There are pending RequestInterrupt() callbacks. Tell them not to run,
860
    // then force V8 to run interrupts by compiling and running an empty script
861
    // so as not to leak memory.
862
10
    *interrupt_data = nullptr;
863
864
20
    Isolate::AllowJavascriptExecutionScope allow_js_here(isolate());
865
20
    HandleScope handle_scope(isolate());
866
20
    TryCatch try_catch(isolate());
867
20
    Context::Scope context_scope(context());
868
869
#ifdef DEBUG
870
    bool consistency_check = false;
871
    isolate()->RequestInterrupt([](Isolate*, void* data) {
872
      *static_cast<bool*>(data) = true;
873
    }, &consistency_check);
874
#endif
875
876
    Local<Script> script;
877
30
    if (Script::Compile(context(), String::Empty(isolate())).ToLocal(&script))
878
10
      USE(script->Run(context()));
879
880
    DCHECK(consistency_check);
881
  }
882
883
  // FreeEnvironment() should have set this.
884
6042
  CHECK(is_stopping());
885
886
6042
  if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
887
    isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
888
                                          0);
889
  }
890
891
6042
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
892
      BuildEmbedderGraph, this);
893
894
12084
  HandleScope handle_scope(isolate());
895
896
#if HAVE_INSPECTOR
897
  // Destroy inspector agent before erasing the context. The inspector
898
  // destructor depends on the context still being accessible.
899
6042
  inspector_agent_.reset();
900
#endif
901
902
12084
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
903
                                             nullptr);
904
905
6042
  if (trace_state_observer_) {
906
6042
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
907
6042
    CHECK_NOT_NULL(writer);
908
6042
    if (TracingController* tracing_controller = writer->GetTracingController())
909
5996
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
910
  }
911
912

10800
  TRACE_EVENT_NESTABLE_ASYNC_END0(
913
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
914
915
  // Do not unload addons on the main thread. Some addons need to retain memory
916
  // beyond the Environment's lifetime, and unloading them early would break
917
  // them; with Worker threads, we have the opportunity to be stricter.
918
  // Also, since the main thread usually stops just before the process exits,
919
  // this is far less relevant here.
920
6042
  if (!is_main_thread()) {
921
    // Dereference all addons that were loaded into this environment.
922
1266
    for (binding::DLib& addon : loaded_addons_) {
923
14
      addon.Close();
924
    }
925
  }
926
927
6042
  CHECK_EQ(base_object_count_, 0);
928
6042
}
929
930
6527
void Environment::InitializeLibuv() {
931
13054
  HandleScope handle_scope(isolate());
932
6527
  Context::Scope context_scope(context());
933
934
6527
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
935
6527
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
936
937
6527
  CHECK_EQ(0, uv_check_init(event_loop(), immediate_check_handle()));
938
6527
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
939
940
6527
  CHECK_EQ(0, uv_idle_init(event_loop(), immediate_idle_handle()));
941
942
6527
  CHECK_EQ(0, uv_check_start(immediate_check_handle(), CheckImmediate));
943
944
  // Inform V8's CPU profiler when we're idle.  The profiler is sampling-based
945
  // but not all samples are created equal; mark the wall clock time spent in
946
  // epoll_wait() and friends so profiling tools can filter it out.  The samples
947
  // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
948
6527
  CHECK_EQ(0, uv_prepare_init(event_loop(), &idle_prepare_handle_));
949
6527
  CHECK_EQ(0, uv_check_init(event_loop(), &idle_check_handle_));
950
951
30290
  CHECK_EQ(0, uv_async_init(
952
      event_loop(),
953
      &task_queues_async_,
954
      [](uv_async_t* async) {
955
        Environment* env = ContainerOf(
956
            &Environment::task_queues_async_, async);
957
        HandleScope handle_scope(env->isolate());
958
        Context::Scope context_scope(env->context());
959
        env->RunAndClearNativeImmediates();
960
      }));
961
6527
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
962
6527
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
963
6527
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
964
965
  {
966
13054
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
967
6527
    task_queues_async_initialized_ = true;
968

13054
    if (native_immediates_threadsafe_.size() > 0 ||
969
6527
        native_immediates_interrupts_.size() > 0) {
970
5250
      uv_async_send(&task_queues_async_);
971
    }
972
  }
973
974
  // Register clean-up cb to be called to clean up the handles
975
  // when the environment is freed, note that they are not cleaned in
976
  // the one environment per process setup, but will be called in
977
  // FreeEnvironment.
978
6527
  RegisterHandleCleanups();
979
980
6527
  StartProfilerIdleNotifier();
981
6527
}
982
983
828
void Environment::ExitEnv() {
984
828
  set_can_call_into_js(false);
985
828
  set_stopping(true);
986
828
  isolate_->TerminateExecution();
987
1656
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
988
828
}
989
990
6527
void Environment::RegisterHandleCleanups() {
991
6527
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
992
36036
                                        void* arg) {
993
36036
    handle->data = env;
994
995
36036
    env->CloseHandle(handle, [](uv_handle_t* handle) {
996
#ifdef DEBUG
997
      memset(handle, 0xab, uv_handle_size(handle->type));
998
#endif
999
36036
    });
1000
36036
  };
1001
1002
39162
  auto register_handle = [&](uv_handle_t* handle) {
1003
39162
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
1004
45689
  };
1005
6527
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
1006
6527
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
1007
6527
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
1008
6527
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
1009
6527
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
1010
6527
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
1011
6527
}
1012
1013
12075
void Environment::CleanupHandles() {
1014
  {
1015
12075
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1016
12075
    task_queues_async_initialized_ = false;
1017
  }
1018
1019
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
1020
24150
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
1021
1022
12075
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
1023
1024
12855
  for (ReqWrapBase* request : req_wrap_queue_)
1025
780
    request->Cancel();
1026
1027
17419
  for (HandleWrap* handle : handle_wrap_queue_)
1028
10688
    handle->Close();
1029
1030
48111
  for (HandleCleanup& hc : handle_cleanup_queue_)
1031
36036
    hc.cb_(this, hc.handle_, hc.arg_);
1032
12075
  handle_cleanup_queue_.clear();
1033
1034
10831
  while (handle_cleanup_waiting_ != 0 ||
1035

34983
         request_waiting_ != 0 ||
1036
12077
         !handle_wrap_queue_.IsEmpty()) {
1037
10831
    uv_run(event_loop(), UV_RUN_ONCE);
1038
  }
1039
12075
}
1040
1041
6527
void Environment::StartProfilerIdleNotifier() {
1042
6527
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
1043
185843
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
1044
185843
    env->isolate()->SetIdle(true);
1045
185843
  });
1046
6527
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
1047
185662
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
1048
185662
    env->isolate()->SetIdle(false);
1049
185662
  });
1050
6527
}
1051
1052
726204
void Environment::PrintSyncTrace() const {
1053
726204
  if (!trace_sync_io_) return;
1054
1055
2
  HandleScope handle_scope(isolate());
1056
1057
1
  fprintf(
1058
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
1059
1
  PrintStackTrace(isolate(),
1060
                  StackTrace::CurrentStackTrace(
1061
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
1062
}
1063
1064
5208
MaybeLocal<Value> Environment::RunSnapshotSerializeCallback() const {
1065
5208
  EscapableHandleScope handle_scope(isolate());
1066
10416
  if (!snapshot_serialize_callback().IsEmpty()) {
1067
    Context::Scope context_scope(context());
1068
    return handle_scope.EscapeMaybe(snapshot_serialize_callback()->Call(
1069
        context(), v8::Undefined(isolate()), 0, nullptr));
1070
  }
1071
10416
  return handle_scope.Escape(Undefined(isolate()));
1072
}
1073
1074
MaybeLocal<Value> Environment::RunSnapshotDeserializeMain() const {
1075
  EscapableHandleScope handle_scope(isolate());
1076
  if (!snapshot_deserialize_main().IsEmpty()) {
1077
    Context::Scope context_scope(context());
1078
    return handle_scope.EscapeMaybe(snapshot_deserialize_main()->Call(
1079
        context(), v8::Undefined(isolate()), 0, nullptr));
1080
  }
1081
  return handle_scope.Escape(Undefined(isolate()));
1082
}
1083
1084
6042
void Environment::RunCleanup() {
1085
6042
  started_cleanup_ = true;
1086

16843
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunCleanup");
1087
6042
  bindings_.clear();
1088
6042
  CleanupHandles();
1089
1090
18119
  while (!cleanup_hooks_.empty() ||
1091
12086
         native_immediates_.size() > 0 ||
1092

24161
         native_immediates_threadsafe_.size() > 0 ||
1093
6042
         native_immediates_interrupts_.size() > 0) {
1094
    // Copy into a vector, since we can't sort an unordered_set in-place.
1095
    std::vector<CleanupHookCallback> callbacks(
1096
12066
        cleanup_hooks_.begin(), cleanup_hooks_.end());
1097
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
1098
    // need to be able to check whether they were un-scheduled by another hook.
1099
1100
6033
    std::sort(callbacks.begin(), callbacks.end(),
1101
1028253
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
1102
      // Sort in descending order so that the most recently inserted callbacks
1103
      // are run first.
1104
1028253
      return a.insertion_order_counter_ > b.insertion_order_counter_;
1105
    });
1106
1107
165048
    for (const CleanupHookCallback& cb : callbacks) {
1108
159015
      if (cleanup_hooks_.count(cb) == 0) {
1109
        // This hook was removed from the `cleanup_hooks_` set during another
1110
        // hook that was run earlier. Nothing to do here.
1111
1188
        continue;
1112
      }
1113
1114
157827
      cb.fn_(cb.arg_);
1115
157827
      cleanup_hooks_.erase(cb);
1116
    }
1117
6033
    CleanupHandles();
1118
  }
1119
1120
6045
  for (const int fd : unmanaged_fds_) {
1121
    uv_fs_t close_req;
1122
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
1123
3
    uv_fs_req_cleanup(&close_req);
1124
  }
1125
6042
}
1126
1127
6655
void Environment::RunAtExitCallbacks() {
1128

18569
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "AtExit");
1129
19747
  for (ExitCallback at_exit : at_exit_functions_) {
1130
13092
    at_exit.cb_(at_exit.arg_);
1131
  }
1132
6655
  at_exit_functions_.clear();
1133
6655
}
1134
1135
13116
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
1136
13116
  at_exit_functions_.push_front(ExitCallback{cb, arg});
1137
13116
}
1138
1139
228844
void Environment::RunAndClearInterrupts() {
1140
228844
  while (native_immediates_interrupts_.size() > 0) {
1141
11913
    NativeImmediateQueue queue;
1142
    {
1143
23826
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1144
11913
      queue.ConcatMove(std::move(native_immediates_interrupts_));
1145
    }
1146
11913
    DebugSealHandleScope seal_handle_scope(isolate());
1147
1148
23834
    while (auto head = queue.Shift())
1149
23842
      head->Call(this);
1150
  }
1151
216931
}
1152
1153
205660
void Environment::RunAndClearNativeImmediates(bool only_refed) {
1154

416278
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment),
1155
               "RunAndClearNativeImmediates");
1156
411314
  HandleScope handle_scope(isolate_);
1157
411314
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
1158
1159
205660
  size_t ref_count = 0;
1160
1161
  // Handle interrupts first. These functions are not allowed to throw
1162
  // exceptions, so we do not need to handle that.
1163
205660
  RunAndClearInterrupts();
1164
1165
411318
  auto drain_list = [&](NativeImmediateQueue* queue) {
1166
822630
    TryCatchScope try_catch(this);
1167
411318
    DebugSealHandleScope seal_handle_scope(isolate());
1168
472814
    while (auto head = queue->Shift()) {
1169
61503
      bool is_refed = head->flags() & CallbackFlags::kRefed;
1170
61503
      if (is_refed)
1171
37051
        ref_count++;
1172
1173

61503
      if (is_refed || !only_refed)
1174
61294
        head->Call(this);
1175
1176
61498
      head.reset();  // Destroy now so that this is also observed by try_catch.
1177
1178
61498
      if (UNLIKELY(try_catch.HasCaught())) {
1179

2
        if (!try_catch.HasTerminated() && can_call_into_js())
1180
2
          errors::TriggerUncaughtException(isolate(), try_catch);
1181
1182
1
        return true;
1183
      }
1184
61496
    }
1185
411311
    return false;
1186
205660
  };
1187
205660
  while (drain_list(&native_immediates_)) {}
1188
1189
205657
  immediate_info()->ref_count_dec(ref_count);
1190
1191
205657
  if (immediate_info()->ref_count() == 0)
1192
161233
    ToggleImmediateRef(false);
1193
1194
  // It is safe to check .size() first, because there is a causal relationship
1195
  // between pushes to the threadsafe immediate list and this function being
1196
  // called. For the common case, it's worth checking the size first before
1197
  // establishing a mutex lock.
1198
  // This is intentionally placed after the `ref_count` handling, because when
1199
  // refed threadsafe immediates are created, they are not counted towards the
1200
  // count in immediate_info() either.
1201
205654
  NativeImmediateQueue threadsafe_immediates;
1202
205657
  if (native_immediates_threadsafe_.size() > 0) {
1203
4126
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1204
2063
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
1205
  }
1206
205658
  while (drain_list(&threadsafe_immediates)) {}
1207
205654
}
1208
1209
11926
void Environment::RequestInterruptFromV8() {
1210
  // The Isolate may outlive the Environment, so some logic to handle the
1211
  // situation in which the Environment is destroyed before the handler runs
1212
  // is required.
1213
1214
  // We allocate a new pointer to a pointer to this Environment instance, and
1215
  // try to set it as interrupt_data_. If interrupt_data_ was already set, then
1216
  // callbacks are already scheduled to run and we can delete our own pointer
1217
  // and just return. If it was nullptr previously, the Environment** is stored;
1218
  // ~Environment sets the Environment* contained in it to nullptr, so that
1219
  // the callback can check whether ~Environment has already run and it is thus
1220
  // not safe to access the Environment instance itself.
1221
11926
  Environment** interrupt_data = new Environment*(this);
1222
11926
  Environment** dummy = nullptr;
1223
11926
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
1224
755
    delete interrupt_data;
1225
755
    return;  // Already scheduled.
1226
  }
1227
1228
11171
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
1229
11162
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
1230
11162
    Environment* env = *env_ptr;
1231
11162
    if (env == nullptr) {
1232
      // The Environment has already been destroyed. That should be okay; any
1233
      // callback added before the Environment shuts down would have been
1234
      // handled during cleanup.
1235
10
      return;
1236
    }
1237
11152
    env->interrupt_data_.store(nullptr);
1238
11152
    env->RunAndClearInterrupts();
1239
  }, interrupt_data);
1240
}
1241
1242
9641
void Environment::ScheduleTimer(int64_t duration_ms) {
1243
9641
  if (started_cleanup_) return;
1244
9641
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
1245
}
1246
1247
3655
void Environment::ToggleTimerRef(bool ref) {
1248
3655
  if (started_cleanup_) return;
1249
1250
3655
  if (ref) {
1251
2397
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1252
  } else {
1253
1258
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1254
  }
1255
}
1256
1257
7479
void Environment::RunTimers(uv_timer_t* handle) {
1258
7479
  Environment* env = Environment::from_timer_handle(handle);
1259

7988
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunTimers");
1260
1261
7479
  if (!env->can_call_into_js())
1262
    return;
1263
1264
7479
  HandleScope handle_scope(env->isolate());
1265
7479
  Context::Scope context_scope(env->context());
1266
1267
7479
  Local<Object> process = env->process_object();
1268
7479
  InternalCallbackScope scope(env, process, {0, 0});
1269
1270
7479
  Local<Function> cb = env->timers_callback_function();
1271
  MaybeLocal<Value> ret;
1272
7479
  Local<Value> arg = env->GetNow();
1273
  // This code will loop until all currently due timers will process. It is
1274
  // impossible for us to end up in an infinite loop due to how the JS-side
1275
  // is structured.
1276
33
  do {
1277
7512
    TryCatchScope try_catch(env);
1278
7512
    try_catch.SetVerbose(true);
1279
7512
    ret = cb->Call(env->context(), process, 1, &arg);
1280

7502
  } while (ret.IsEmpty() && env->can_call_into_js());
1281
1282
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
1283
  // is reset back to `true` after being previously set to `false` then this
1284
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
1285
  // timers corruption will occur and all timers behaviour will become
1286
  // entirely unpredictable.
1287
7469
  if (ret.IsEmpty())
1288
8
    return;
1289
1290
  // To allow for less JS-C++ boundary crossing, the value returned from JS
1291
  // serves a few purposes:
1292
  // 1. If it's 0, no more timers exist and the handle should be unrefed
1293
  // 2. If it's > 0, the value represents the next timer's expiry and there
1294
  //    is at least one timer remaining that is refed.
1295
  // 3. If it's < 0, the absolute value represents the next timer's expiry
1296
  //    and there are no timers that are refed.
1297
  int64_t expiry_ms =
1298
7461
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
1299
1300
7461
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
1301
1302
7461
  if (expiry_ms != 0) {
1303
    int64_t duration_ms =
1304
6509
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
1305
1306
6509
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
1307
1308
6509
    if (expiry_ms > 0)
1309
5827
      uv_ref(h);
1310
    else
1311
682
      uv_unref(h);
1312
  } else {
1313
952
    uv_unref(h);
1314
  }
1315
}
1316
1317
1318
185662
void Environment::CheckImmediate(uv_check_t* handle) {
1319
185662
  Environment* env = Environment::from_immediate_check_handle(handle);
1320

188641
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "CheckImmediate");
1321
1322
185662
  HandleScope scope(env->isolate());
1323
185662
  Context::Scope context_scope(env->context());
1324
1325
185662
  env->RunAndClearNativeImmediates();
1326
1327

185662
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
1328
142508
    return;
1329
1330
951
  do {
1331
44098
    MakeCallback(env->isolate(),
1332
                 env->process_object(),
1333
                 env->immediate_callback_function(),
1334
                 0,
1335
                 nullptr,
1336
44105
                 {0, 0}).ToLocalChecked();
1337

44098
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
1338
1339
43147
  if (env->immediate_info()->ref_count() == 0)
1340
5176
    env->ToggleImmediateRef(false);
1341
}
1342
1343
232820
void Environment::ToggleImmediateRef(bool ref) {
1344
232820
  if (started_cleanup_) return;
1345
1346
221194
  if (ref) {
1347
    // Idle handle is needed only to stop the event loop from blocking in poll.
1348
66387
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
1349
  } else {
1350
154807
    uv_idle_stop(immediate_idle_handle());
1351
  }
1352
}
1353
1354
1355
46777
Local<Value> Environment::GetNow() {
1356
46777
  uv_update_time(event_loop());
1357
46777
  uint64_t now = uv_now(event_loop());
1358
46777
  CHECK_GE(now, timer_base());
1359
46777
  now -= timer_base();
1360
46777
  if (now <= 0xffffffff)
1361
93554
    return Integer::NewFromUnsigned(isolate(), static_cast<uint32_t>(now));
1362
  else
1363
    return Number::New(isolate(), static_cast<double>(now));
1364
}
1365
1366
28
void CollectExceptionInfo(Environment* env,
1367
                          Local<Object> obj,
1368
                          int errorno,
1369
                          const char* err_string,
1370
                          const char* syscall,
1371
                          const char* message,
1372
                          const char* path,
1373
                          const char* dest) {
1374
28
  obj->Set(env->context(),
1375
           env->errno_string(),
1376
112
           Integer::New(env->isolate(), errorno)).Check();
1377
1378
28
  obj->Set(env->context(), env->code_string(),
1379
84
           OneByteString(env->isolate(), err_string)).Check();
1380
1381
28
  if (message != nullptr) {
1382
28
    obj->Set(env->context(), env->message_string(),
1383
112
             OneByteString(env->isolate(), message)).Check();
1384
  }
1385
1386
  Local<Value> path_buffer;
1387
28
  if (path != nullptr) {
1388
    path_buffer =
1389
      Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked();
1390
    obj->Set(env->context(), env->path_string(), path_buffer).Check();
1391
  }
1392
1393
  Local<Value> dest_buffer;
1394
28
  if (dest != nullptr) {
1395
    dest_buffer =
1396
      Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked();
1397
    obj->Set(env->context(), env->dest_string(), dest_buffer).Check();
1398
  }
1399
1400
28
  if (syscall != nullptr) {
1401
28
    obj->Set(env->context(), env->syscall_string(),
1402
112
             OneByteString(env->isolate(), syscall)).Check();
1403
  }
1404
28
}
1405
1406
28
void Environment::CollectUVExceptionInfo(Local<Value> object,
1407
                                         int errorno,
1408
                                         const char* syscall,
1409
                                         const char* message,
1410
                                         const char* path,
1411
                                         const char* dest) {
1412

28
  if (!object->IsObject() || errorno == 0)
1413
    return;
1414
1415
28
  Local<Object> obj = object.As<Object>();
1416
28
  const char* err_string = uv_err_name(errorno);
1417
1418

28
  if (message == nullptr || message[0] == '\0') {
1419
28
    message = uv_strerror(errorno);
1420
  }
1421
1422
28
  node::CollectExceptionInfo(this, obj, errorno, err_string,
1423
                             syscall, message, path, dest);
1424
}
1425
1426
6563
ImmediateInfo::ImmediateInfo(Isolate* isolate, const SerializeInfo* info)
1427
6563
    : fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)) {}
1428
1429
6
ImmediateInfo::SerializeInfo ImmediateInfo::Serialize(
1430
    Local<Context> context, SnapshotCreator* creator) {
1431
6
  return {fields_.Serialize(context, creator)};
1432
}
1433
1434
5255
void ImmediateInfo::Deserialize(Local<Context> context) {
1435
5255
  fields_.Deserialize(context);
1436
5255
}
1437
1438
6
std::ostream& operator<<(std::ostream& output,
1439
                         const ImmediateInfo::SerializeInfo& i) {
1440
6
  output << "{ " << i.fields << " }";
1441
6
  return output;
1442
}
1443
1444
24
void ImmediateInfo::MemoryInfo(MemoryTracker* tracker) const {
1445
24
  tracker->TrackField("fields", fields_);
1446
24
}
1447
1448
6
TickInfo::SerializeInfo TickInfo::Serialize(Local<Context> context,
1449
                                            SnapshotCreator* creator) {
1450
6
  return {fields_.Serialize(context, creator)};
1451
}
1452
1453
5255
void TickInfo::Deserialize(Local<Context> context) {
1454
5255
  fields_.Deserialize(context);
1455
5255
}
1456
1457
6
std::ostream& operator<<(std::ostream& output,
1458
                         const TickInfo::SerializeInfo& i) {
1459
6
  output << "{ " << i.fields << " }";
1460
6
  return output;
1461
}
1462
1463
24
void TickInfo::MemoryInfo(MemoryTracker* tracker) const {
1464
24
  tracker->TrackField("fields", fields_);
1465
24
}
1466
1467
6563
TickInfo::TickInfo(Isolate* isolate, const SerializeInfo* info)
1468
    : fields_(
1469
6563
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1470
1471
6563
AsyncHooks::AsyncHooks(Isolate* isolate, const SerializeInfo* info)
1472
    : async_ids_stack_(isolate, 16 * 2, MAYBE_FIELD_PTR(info, async_ids_stack)),
1473
      fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)),
1474
      async_id_fields_(
1475
          isolate, kUidFieldsCount, MAYBE_FIELD_PTR(info, async_id_fields)),
1476

6563
      info_(info) {
1477
13126
  HandleScope handle_scope(isolate);
1478
6563
  if (info == nullptr) {
1479
1308
    clear_async_id_stack();
1480
1481
    // Always perform async_hooks checks, not just when async_hooks is enabled.
1482
    // TODO(AndreasMadsen): Consider removing this for LTS releases.
1483
    // See discussion in https://github.com/nodejs/node/pull/15454
1484
    // When removing this, do it by reverting the commit. Otherwise the test
1485
    // and flag changes won't be included.
1486
1308
    fields_[kCheck] = 1;
1487
1488
    // kDefaultTriggerAsyncId should be -1, this indicates that there is no
1489
    // specified default value and it should fallback to the executionAsyncId.
1490
    // 0 is not used as the magic value, because that indicates a missing
1491
    // context which is different from a default context.
1492
1308
    async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
1493
1494
    // kAsyncIdCounter should start at 1 because that'll be the id the execution
1495
    // context during bootstrap (code that runs before entering uv_run()).
1496
1308
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1497
  }
1498
6563
}
1499
1500
5255
void AsyncHooks::Deserialize(Local<Context> context) {
1501
5255
  async_ids_stack_.Deserialize(context);
1502
5255
  fields_.Deserialize(context);
1503
5255
  async_id_fields_.Deserialize(context);
1504
1505
  Local<Array> js_execution_async_resources;
1506
5255
  if (info_->js_execution_async_resources != 0) {
1507
    js_execution_async_resources =
1508
5255
        context->GetDataFromSnapshotOnce<Array>(
1509
15765
            info_->js_execution_async_resources).ToLocalChecked();
1510
  } else {
1511
    js_execution_async_resources = Array::New(context->GetIsolate());
1512
  }
1513
5255
  js_execution_async_resources_.Reset(
1514
      context->GetIsolate(), js_execution_async_resources);
1515
1516
  // The native_execution_async_resources_ field requires v8::Local<> instances
1517
  // for async calls whose resources were on the stack as JS objects when they
1518
  // were entered. We cannot recreate this here; however, storing these values
1519
  // on the JS equivalent gives the same result, so we do that instead.
1520
5255
  for (size_t i = 0; i < info_->native_execution_async_resources.size(); ++i) {
1521
    if (info_->native_execution_async_resources[i] == SIZE_MAX)
1522
      continue;
1523
    Local<Object> obj = context->GetDataFromSnapshotOnce<Object>(
1524
                                   info_->native_execution_async_resources[i])
1525
                               .ToLocalChecked();
1526
    js_execution_async_resources->Set(context, i, obj).Check();
1527
  }
1528
5255
  info_ = nullptr;
1529
5255
}
1530
1531
6
std::ostream& operator<<(std::ostream& output,
1532
                         const std::vector<SnapshotIndex>& v) {
1533
6
  output << "{ ";
1534
6
  for (const SnapshotIndex i : v) {
1535
    output << i << ", ";
1536
  }
1537
6
  output << " }";
1538
6
  return output;
1539
}
1540
1541
6
std::ostream& operator<<(std::ostream& output,
1542
                         const AsyncHooks::SerializeInfo& i) {
1543
  output << "{\n"
1544
6
         << "  " << i.async_ids_stack << ",  // async_ids_stack\n"
1545
6
         << "  " << i.fields << ",  // fields\n"
1546
6
         << "  " << i.async_id_fields << ",  // async_id_fields\n"
1547
6
         << "  " << i.js_execution_async_resources
1548
         << ",  // js_execution_async_resources\n"
1549
6
         << "  " << i.native_execution_async_resources
1550
         << ",  // native_execution_async_resources\n"
1551
6
         << "}";
1552
6
  return output;
1553
}
1554
1555
6
AsyncHooks::SerializeInfo AsyncHooks::Serialize(Local<Context> context,
1556
                                                SnapshotCreator* creator) {
1557
6
  SerializeInfo info;
1558
6
  info.async_ids_stack = async_ids_stack_.Serialize(context, creator);
1559
6
  info.fields = fields_.Serialize(context, creator);
1560
6
  info.async_id_fields = async_id_fields_.Serialize(context, creator);
1561
6
  if (!js_execution_async_resources_.IsEmpty()) {
1562
6
    info.js_execution_async_resources = creator->AddData(
1563
        context, js_execution_async_resources_.Get(context->GetIsolate()));
1564
6
    CHECK_NE(info.js_execution_async_resources, 0);
1565
  } else {
1566
    info.js_execution_async_resources = 0;
1567
  }
1568
1569
6
  info.native_execution_async_resources.resize(
1570
      native_execution_async_resources_.size());
1571
6
  for (size_t i = 0; i < native_execution_async_resources_.size(); i++) {
1572
    info.native_execution_async_resources[i] =
1573
        native_execution_async_resources_[i].IsEmpty() ? SIZE_MAX :
1574
            creator->AddData(
1575
                context,
1576
                native_execution_async_resources_[i]);
1577
  }
1578
6
  CHECK_EQ(contexts_.size(), 1);
1579

12
  CHECK_EQ(contexts_[0], env()->context());
1580
6
  CHECK(js_promise_hooks_[0].IsEmpty());
1581
6
  CHECK(js_promise_hooks_[1].IsEmpty());
1582
6
  CHECK(js_promise_hooks_[2].IsEmpty());
1583
6
  CHECK(js_promise_hooks_[3].IsEmpty());
1584
1585
6
  return info;
1586
}
1587
1588
24
void AsyncHooks::MemoryInfo(MemoryTracker* tracker) const {
1589
24
  tracker->TrackField("async_ids_stack", async_ids_stack_);
1590
24
  tracker->TrackField("fields", fields_);
1591
24
  tracker->TrackField("async_id_fields", async_id_fields_);
1592
24
  tracker->TrackField("js_promise_hooks", js_promise_hooks_);
1593
24
}
1594
1595
4
void AsyncHooks::grow_async_ids_stack() {
1596
4
  async_ids_stack_.reserve(async_ids_stack_.Length() * 3);
1597
1598
4
  env()->async_hooks_binding()->Set(
1599
      env()->context(),
1600
      env()->async_ids_stack_string(),
1601
12
      async_ids_stack_.GetJSArray()).Check();
1602
4
}
1603
1604
4
void AsyncHooks::FailWithCorruptedAsyncStack(double expected_async_id) {
1605
4
  fprintf(stderr,
1606
          "Error: async hook stack has become corrupted ("
1607
          "actual: %.f, expected: %.f)\n",
1608
          async_id_fields_.GetValue(kExecutionAsyncId),
1609
          expected_async_id);
1610
4
  DumpBacktrace(stderr);
1611
4
  fflush(stderr);
1612
4
  if (!env()->abort_on_uncaught_exception())
1613
4
    exit(1);
1614
  fprintf(stderr, "\n");
1615
  fflush(stderr);
1616
  ABORT_NO_BACKTRACE();
1617
}
1618
1619
596
void Environment::Exit(int exit_code) {
1620
596
  if (options()->trace_exit) {
1621
4
    HandleScope handle_scope(isolate());
1622
    Isolate::DisallowJavascriptExecutionScope disallow_js(
1623
4
        isolate(), Isolate::DisallowJavascriptExecutionScope::CRASH_ON_FAILURE);
1624
1625
2
    if (is_main_thread()) {
1626
1
      fprintf(stderr, "(node:%d) ", uv_os_getpid());
1627
    } else {
1628
1
      fprintf(stderr, "(node:%d, thread:%" PRIu64 ") ",
1629
              uv_os_getpid(), thread_id());
1630
    }
1631
1632
2
    fprintf(
1633
        stderr, "WARNING: Exited the environment with code %d\n", exit_code);
1634
2
    PrintStackTrace(isolate(),
1635
                    StackTrace::CurrentStackTrace(
1636
                        isolate(), stack_trace_limit(), StackTrace::kDetailed));
1637
  }
1638
596
  process_exit_handler_(this, exit_code);
1639
80
}
1640
1641
6586
void Environment::stop_sub_worker_contexts() {
1642
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1643
1644
6586
  while (!sub_worker_contexts_.empty()) {
1645
28
    Worker* w = *sub_worker_contexts_.begin();
1646
28
    remove_sub_worker_context(w);
1647
28
    w->Exit(1);
1648
28
    w->JoinThread();
1649
  }
1650
6558
}
1651
1652
10
Environment* Environment::worker_parent_env() const {
1653
10
  if (worker_context() == nullptr) return nullptr;
1654
  return worker_context()->env();
1655
}
1656
1657
68116
void Environment::AddUnmanagedFd(int fd) {
1658
68116
  if (!tracks_unmanaged_fds()) return;
1659
4984
  auto result = unmanaged_fds_.insert(fd);
1660
4984
  if (!result.second) {
1661
    ProcessEmitWarning(
1662
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1663
  }
1664
}
1665
1666
67737
void Environment::RemoveUnmanagedFd(int fd) {
1667
67737
  if (!tracks_unmanaged_fds()) return;
1668
4981
  size_t removed_count = unmanaged_fds_.erase(fd);
1669
4981
  if (removed_count == 0) {
1670
    ProcessEmitWarning(
1671
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1672
  }
1673
}
1674
1675
5192
void Environment::PrintInfoForSnapshotIfDebug() {
1676
5192
  if (enabled_debug_list()->enabled(DebugCategory::MKSNAPSHOT)) {
1677
    fprintf(stderr, "BaseObjects at the exit of the Environment:\n");
1678
    PrintAllBaseObjects();
1679
    fprintf(stderr, "\nNative modules without cache:\n");
1680
    for (const auto& s : native_modules_without_cache) {
1681
      fprintf(stderr, "%s\n", s.c_str());
1682
    }
1683
    fprintf(stderr, "\nNative modules with cache:\n");
1684
    for (const auto& s : native_modules_with_cache) {
1685
      fprintf(stderr, "%s\n", s.c_str());
1686
    }
1687
    fprintf(stderr, "\nStatic bindings (need to be registered):\n");
1688
    for (const auto mod : internal_bindings) {
1689
      fprintf(stderr, "%s:%s\n", mod->nm_filename, mod->nm_modname);
1690
    }
1691
  }
1692
5192
}
1693
1694
void Environment::PrintAllBaseObjects() {
1695
  size_t i = 0;
1696
  std::cout << "BaseObjects\n";
1697
  ForEachBaseObject([&](BaseObject* obj) {
1698
    std::cout << "#" << i++ << " " << obj << ": " <<
1699
      obj->MemoryInfoName() << "\n";
1700
  });
1701
}
1702
1703
5192
void Environment::VerifyNoStrongBaseObjects() {
1704
  // When a process exits cleanly, i.e. because the event loop ends up without
1705
  // things to wait for, the Node.js objects that are left on the heap should
1706
  // be:
1707
  //
1708
  //   1. weak, i.e. ready for garbage collection once no longer referenced, or
1709
  //   2. detached, i.e. scheduled for destruction once no longer referenced, or
1710
  //   3. an unrefed libuv handle, i.e. does not keep the event loop alive, or
1711
  //   4. an inactive libuv handle (essentially the same here)
1712
  //
1713
  // There are a few exceptions to this rule, but generally, if there are
1714
  // C++-backed Node.js objects on the heap that do not fall into the above
1715
  // categories, we may be looking at a potential memory leak. Most likely,
1716
  // the cause is a missing MakeWeak() call on the corresponding object.
1717
  //
1718
  // In order to avoid this kind of problem, we check the list of BaseObjects
1719
  // for these criteria. Currently, we only do so when explicitly instructed to
1720
  // or when in debug mode (where --verify-base-objects is always-on).
1721
1722
5192
  if (!options()->verify_base_objects) return;
1723
1724
  ForEachBaseObject([](BaseObject* obj) {
1725
    if (obj->IsNotIndicativeOfMemoryLeakAtExit()) return;
1726
    fprintf(stderr, "Found bad BaseObject during clean exit: %s\n",
1727
            obj->MemoryInfoName().c_str());
1728
    fflush(stderr);
1729
    ABORT();
1730
  });
1731
}
1732
1733
6
EnvSerializeInfo Environment::Serialize(SnapshotCreator* creator) {
1734
6
  EnvSerializeInfo info;
1735
6
  Local<Context> ctx = context();
1736
1737
6
  SerializeBindingData(this, creator, &info);
1738
  // Currently all modules are compiled without cache in builtin snapshot
1739
  // builder.
1740
12
  info.native_modules = std::vector<std::string>(
1741
6
      native_modules_without_cache.begin(), native_modules_without_cache.end());
1742
1743
6
  info.async_hooks = async_hooks_.Serialize(ctx, creator);
1744
6
  info.immediate_info = immediate_info_.Serialize(ctx, creator);
1745
6
  info.tick_info = tick_info_.Serialize(ctx, creator);
1746
6
  info.performance_state = performance_state_->Serialize(ctx, creator);
1747
6
  info.stream_base_state = stream_base_state_.Serialize(ctx, creator);
1748
6
  info.should_abort_on_uncaught_toggle =
1749
6
      should_abort_on_uncaught_toggle_.Serialize(ctx, creator);
1750
1751
6
  size_t id = 0;
1752
#define V(PropertyName, TypeName)                                              \
1753
  do {                                                                         \
1754
    Local<TypeName> field = PropertyName();                                    \
1755
    if (!field.IsEmpty()) {                                                    \
1756
      size_t index = creator->AddData(field);                                  \
1757
      info.persistent_templates.push_back({#PropertyName, id, index});         \
1758
    }                                                                          \
1759
    id++;                                                                      \
1760
  } while (0);
1761


















336
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1762
#undef V
1763
1764
6
  id = 0;
1765
#define V(PropertyName, TypeName)                                              \
1766
  do {                                                                         \
1767
    Local<TypeName> field = PropertyName();                                    \
1768
    if (!field.IsEmpty()) {                                                    \
1769
      size_t index = creator->AddData(ctx, field);                             \
1770
      info.persistent_values.push_back({#PropertyName, id, index});            \
1771
    }                                                                          \
1772
    id++;                                                                      \
1773
  } while (0);
1774































588
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1775
#undef V
1776
1777
6
  info.context = creator->AddData(ctx, context());
1778
6
  return info;
1779
}
1780
1781
18
std::ostream& operator<<(std::ostream& output,
1782
                         const std::vector<PropInfo>& vec) {
1783
18
  output << "{\n";
1784
360
  for (const auto& info : vec) {
1785
684
    output << "  { \"" << info.name << "\", " << std::to_string(info.id) << ", "
1786
684
           << std::to_string(info.index) << " },\n";
1787
  }
1788
18
  output << "}";
1789
18
  return output;
1790
}
1791
1792
6
std::ostream& operator<<(std::ostream& output,
1793
                         const std::vector<std::string>& vec) {
1794
6
  output << "{\n";
1795
702
  for (const auto& info : vec) {
1796
696
    output << "  \"" << info << "\",\n";
1797
  }
1798
6
  output << "}";
1799
6
  return output;
1800
}
1801
1802
6
std::ostream& operator<<(std::ostream& output, const EnvSerializeInfo& i) {
1803
  output << "{\n"
1804
6
         << "// -- bindings begins --\n"
1805
6
         << i.bindings << ",\n"
1806
         << "// -- bindings ends --\n"
1807
6
         << "// -- native_modules begins --\n"
1808
6
         << i.native_modules << ",\n"
1809
         << "// -- native_modules ends --\n"
1810
6
         << "// -- async_hooks begins --\n"
1811
6
         << i.async_hooks << ",\n"
1812
6
         << "// -- async_hooks ends --\n"
1813
6
         << i.tick_info << ",  // tick_info\n"
1814
6
         << i.immediate_info << ",  // immediate_info\n"
1815
6
         << "// -- performance_state begins --\n"
1816
6
         << i.performance_state << ",\n"
1817
6
         << "// -- performance_state ends --\n"
1818
6
         << i.stream_base_state << ",  // stream_base_state\n"
1819
6
         << i.should_abort_on_uncaught_toggle
1820
         << ",  // should_abort_on_uncaught_toggle\n"
1821
6
         << "// -- persistent_templates begins --\n"
1822
6
         << i.persistent_templates << ",\n"
1823
         << "// persistent_templates ends --\n"
1824
6
         << "// -- persistent_values begins --\n"
1825
6
         << i.persistent_values << ",\n"
1826
6
         << "// -- persistent_values ends --\n"
1827
6
         << i.context << ",  // context\n"
1828
6
         << "}";
1829
6
  return output;
1830
}
1831
1832
21020
void Environment::EnqueueDeserializeRequest(DeserializeRequestCallback cb,
1833
                                            Local<Object> holder,
1834
                                            int index,
1835
                                            InternalFieldInfo* info) {
1836
42040
  DeserializeRequest request{cb, {isolate(), holder}, index, info};
1837
21020
  deserialize_requests_.push_back(std::move(request));
1838
21020
}
1839
1840
5255
void Environment::RunDeserializeRequests() {
1841
10510
  HandleScope scope(isolate());
1842
5255
  Local<Context> ctx = context();
1843
5255
  Isolate* is = isolate();
1844
26275
  while (!deserialize_requests_.empty()) {
1845
42040
    DeserializeRequest request(std::move(deserialize_requests_.front()));
1846
21020
    deserialize_requests_.pop_front();
1847
21020
    Local<Object> holder = request.holder.Get(is);
1848
21020
    request.cb(ctx, holder, request.index, request.info);
1849
    request.holder.Reset();
1850
21020
    request.info->Delete();
1851
  }
1852
5255
}
1853
1854
5255
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1855
5255
  Local<Context> ctx = context();
1856
1857
5255
  RunDeserializeRequests();
1858
1859
5255
  native_modules_in_snapshot = info->native_modules;
1860
5255
  async_hooks_.Deserialize(ctx);
1861
5255
  immediate_info_.Deserialize(ctx);
1862
5255
  tick_info_.Deserialize(ctx);
1863
5255
  performance_state_->Deserialize(ctx);
1864
5255
  stream_base_state_.Deserialize(ctx);
1865
5255
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1866
1867
5255
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1868
    fprintf(stderr, "deserializing...\n");
1869
    std::cerr << *info << "\n";
1870
  }
1871
1872
5255
  const std::vector<PropInfo>& templates = info->persistent_templates;
1873
5255
  size_t i = 0;  // index to the array
1874
5255
  size_t id = 0;
1875
#define SetProperty(PropertyName, TypeName, vector, type, from)                \
1876
  do {                                                                         \
1877
    if (vector.size() > i && id == vector[i].id) {                             \
1878
      const PropInfo& d = vector[i];                                           \
1879
      DCHECK_EQ(d.name, #PropertyName);                                        \
1880
      MaybeLocal<TypeName> maybe_field =                                       \
1881
          from->GetDataFromSnapshotOnce<TypeName>(d.index);                    \
1882
      Local<TypeName> field;                                                   \
1883
      if (!maybe_field.ToLocal(&field)) {                                      \
1884
        fprintf(stderr,                                                        \
1885
                "Failed to deserialize environment " #type " " #PropertyName   \
1886
                "\n");                                                         \
1887
      }                                                                        \
1888
      set_##PropertyName(field);                                               \
1889
      i++;                                                                     \
1890
    }                                                                          \
1891
  } while (0);                                                                 \
1892
  id++;
1893
#define V(PropertyName, TypeName) SetProperty(PropertyName, TypeName,          \
1894
                                              templates, template, isolate_)
1895








































































204945
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V);
1896
#undef V
1897
1898
5255
  i = 0;  // index to the array
1899
5255
  id = 0;
1900
5255
  const std::vector<PropInfo>& values = info->persistent_values;
1901
#define V(PropertyName, TypeName) SetProperty(PropertyName, TypeName,          \
1902
                                              values, value, ctx)
1903






























































































































541265
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1904
#undef V
1905
#undef SetProperty
1906
1907
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1908
10510
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1909
  Local<Context> ctx_from_snapshot;
1910
5255
  if (!maybe_ctx_from_snapshot.ToLocal(&ctx_from_snapshot)) {
1911
    fprintf(stderr,
1912
            "Failed to deserialize context back reference from the snapshot\n");
1913
  }
1914
5255
  CHECK_EQ(ctx_from_snapshot, ctx);
1915
5255
}
1916
1917
1
uint64_t GuessMemoryAvailableToTheProcess() {
1918
1
  uint64_t free_in_system = uv_get_free_memory();
1919
1
  size_t allowed = uv_get_constrained_memory();
1920
1
  if (allowed == 0) {
1921
    return free_in_system;
1922
  }
1923
  size_t rss;
1924
1
  int err = uv_resident_set_memory(&rss);
1925
1
  if (err) {
1926
    return free_in_system;
1927
  }
1928
1
  if (allowed < rss) {
1929
    // Something is probably wrong. Fallback to the free memory.
1930
    return free_in_system;
1931
  }
1932
  // There may still be room for swap, but we will just leave it here.
1933
1
  return allowed - rss;
1934
}
1935
1936
24
void Environment::BuildEmbedderGraph(Isolate* isolate,
1937
                                     EmbedderGraph* graph,
1938
                                     void* data) {
1939
24
  MemoryTracker tracker(isolate, graph);
1940
24
  Environment* env = static_cast<Environment*>(data);
1941
24
  tracker.Track(env);
1942
24
  env->ForEachBaseObject([&](BaseObject* obj) {
1943
517
    if (obj->IsDoneInitializing())
1944
516
      tracker.Track(obj);
1945
517
  });
1946
24
}
1947
1948
1
size_t Environment::NearHeapLimitCallback(void* data,
1949
                                          size_t current_heap_limit,
1950
                                          size_t initial_heap_limit) {
1951
1
  Environment* env = static_cast<Environment*>(data);
1952
1953
  Debug(env,
1954
        DebugCategory::DIAGNOSTICS,
1955
        "Invoked NearHeapLimitCallback, processing=%d, "
1956
        "current_limit=%" PRIu64 ", "
1957
        "initial_limit=%" PRIu64 "\n",
1958
1
        env->is_processing_heap_limit_callback_,
1959
2
        static_cast<uint64_t>(current_heap_limit),
1960
1
        static_cast<uint64_t>(initial_heap_limit));
1961
1962
1
  size_t max_young_gen_size = env->isolate_data()->max_young_gen_size;
1963
1
  size_t young_gen_size = 0;
1964
1
  size_t old_gen_size = 0;
1965
1966
1
  HeapSpaceStatistics stats;
1967
1
  size_t num_heap_spaces = env->isolate()->NumberOfHeapSpaces();
1968
9
  for (size_t i = 0; i < num_heap_spaces; ++i) {
1969
8
    env->isolate()->GetHeapSpaceStatistics(&stats, i);
1970

15
    if (strcmp(stats.space_name(), "new_space") == 0 ||
1971
7
        strcmp(stats.space_name(), "new_large_object_space") == 0) {
1972
2
      young_gen_size += stats.space_used_size();
1973
    } else {
1974
6
      old_gen_size += stats.space_used_size();
1975
    }
1976
  }
1977
1978
  Debug(env,
1979
        DebugCategory::DIAGNOSTICS,
1980
        "max_young_gen_size=%" PRIu64 ", "
1981
        "young_gen_size=%" PRIu64 ", "
1982
        "old_gen_size=%" PRIu64 ", "
1983
        "total_size=%" PRIu64 "\n",
1984
2
        static_cast<uint64_t>(max_young_gen_size),
1985
2
        static_cast<uint64_t>(young_gen_size),
1986
2
        static_cast<uint64_t>(old_gen_size),
1987
1
        static_cast<uint64_t>(young_gen_size + old_gen_size));
1988
1989
1
  uint64_t available = GuessMemoryAvailableToTheProcess();
1990
  // TODO(joyeecheung): get a better estimate about the native memory
1991
  // usage into the overhead, e.g. based on the count of objects.
1992
1
  uint64_t estimated_overhead = max_young_gen_size;
1993
  Debug(env,
1994
        DebugCategory::DIAGNOSTICS,
1995
        "Estimated available memory=%" PRIu64 ", "
1996
        "estimated overhead=%" PRIu64 "\n",
1997
2
        static_cast<uint64_t>(available),
1998
1
        static_cast<uint64_t>(estimated_overhead));
1999
2000
  // This might be hit when the snapshot is being taken in another
2001
  // NearHeapLimitCallback invocation.
2002
  // When taking the snapshot, objects in the young generation may be
2003
  // promoted to the old generation, result in increased heap usage,
2004
  // but it should be no more than the young generation size.
2005
  // Ideally, this should be as small as possible - the heap limit
2006
  // can only be restored when the heap usage falls down below the
2007
  // new limit, so in a heap with unbounded growth the isolate
2008
  // may eventually crash with this new limit - effectively raising
2009
  // the heap limit to the new one.
2010
1
  if (env->is_processing_heap_limit_callback_) {
2011
    size_t new_limit = current_heap_limit + max_young_gen_size;
2012
    Debug(env,
2013
          DebugCategory::DIAGNOSTICS,
2014
          "Not generating snapshots in nested callback. "
2015
          "new_limit=%" PRIu64 "\n",
2016
          static_cast<uint64_t>(new_limit));
2017
    return new_limit;
2018
  }
2019
2020
  // Estimate whether the snapshot is going to use up all the memory
2021
  // available to the process. If so, just give up to prevent the system
2022
  // from killing the process for a system OOM.
2023
1
  if (estimated_overhead > available) {
2024
    Debug(env,
2025
          DebugCategory::DIAGNOSTICS,
2026
          "Not generating snapshots because it's too risky.\n");
2027
    env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
2028
                                                initial_heap_limit);
2029
    // The new limit must be higher than current_heap_limit or V8 might
2030
    // crash.
2031
    return current_heap_limit + 1;
2032
  }
2033
2034
  // Take the snapshot synchronously.
2035
1
  env->is_processing_heap_limit_callback_ = true;
2036
2037
2
  std::string dir = env->options()->diagnostic_dir;
2038
1
  if (dir.empty()) {
2039
1
    dir = env->GetCwd();
2040
  }
2041
2
  DiagnosticFilename name(env, "Heap", "heapsnapshot");
2042
1
  std::string filename = dir + kPathSeparator + (*name);
2043
2044
1
  Debug(env, DebugCategory::DIAGNOSTICS, "Start generating %s...\n", *name);
2045
2046
  // Remove the callback first in case it's triggered when generating
2047
  // the snapshot.
2048
1
  env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
2049
                                              initial_heap_limit);
2050
2051
1
  heap::WriteSnapshot(env, filename.c_str());
2052
1
  env->heap_limit_snapshot_taken_ += 1;
2053
2054
  // Don't take more snapshots than the number specified by
2055
  // --heapsnapshot-near-heap-limit.
2056
2
  if (env->heap_limit_snapshot_taken_ <
2057
1
      env->options_->heap_snapshot_near_heap_limit) {
2058
    env->isolate()->AddNearHeapLimitCallback(NearHeapLimitCallback, env);
2059
  }
2060
2061
1
  FPrintF(stderr, "Wrote snapshot to %s\n", filename.c_str());
2062
  // Tell V8 to reset the heap limit once the heap usage falls down to
2063
  // 95% of the initial limit.
2064
1
  env->isolate()->AutomaticallyRestoreInitialHeapLimit(0.95);
2065
2066
1
  env->is_processing_heap_limit_callback_ = false;
2067
2068
  // The new limit must be higher than current_heap_limit or V8 might
2069
  // crash.
2070
1
  return current_heap_limit + 1;
2071
}
2072
2073
24
inline size_t Environment::SelfSize() const {
2074
24
  size_t size = sizeof(*this);
2075
  // Remove non pointer fields that will be tracked in MemoryInfo()
2076
  // TODO(joyeecheung): refactor the MemoryTracker interface so
2077
  // this can be done for common types within the Track* calls automatically
2078
  // if a certain scope is entered.
2079
24
  size -= sizeof(async_hooks_);
2080
24
  size -= sizeof(tick_info_);
2081
24
  size -= sizeof(immediate_info_);
2082
24
  return size;
2083
}
2084
2085
24
void Environment::MemoryInfo(MemoryTracker* tracker) const {
2086
  // Iteratable STLs have their own sizes subtracted from the parent
2087
  // by default.
2088
24
  tracker->TrackField("isolate_data", isolate_data_);
2089
24
  tracker->TrackField("native_modules_with_cache", native_modules_with_cache);
2090
24
  tracker->TrackField("native_modules_without_cache",
2091
24
                      native_modules_without_cache);
2092
24
  tracker->TrackField("destroy_async_id_list", destroy_async_id_list_);
2093
24
  tracker->TrackField("exec_argv", exec_argv_);
2094
24
  tracker->TrackField("should_abort_on_uncaught_toggle",
2095
24
                      should_abort_on_uncaught_toggle_);
2096
24
  tracker->TrackField("stream_base_state", stream_base_state_);
2097
24
  tracker->TrackFieldWithSize(
2098
24
      "cleanup_hooks", cleanup_hooks_.size() * sizeof(CleanupHookCallback));
2099
24
  tracker->TrackField("async_hooks", async_hooks_);
2100
24
  tracker->TrackField("immediate_info", immediate_info_);
2101
24
  tracker->TrackField("tick_info", tick_info_);
2102
2103
#define V(PropertyName, TypeName)                                              \
2104
  tracker->TrackField(#PropertyName, PropertyName());
2105
24
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
2106
#undef V
2107
2108
  // FIXME(joyeecheung): track other fields in Environment.
2109
  // Currently MemoryTracker is unable to track these
2110
  // correctly:
2111
  // - Internal types that do not implement MemoryRetainer yet
2112
  // - STL containers with MemoryRetainer* inside
2113
  // - STL containers with numeric types inside that should not have their
2114
  //   nodes elided e.g. numeric keys in maps.
2115
  // We also need to make sure that when we add a non-pointer field as its own
2116
  // node, we shift its sizeof() size out of the Environment node.
2117
24
}
2118
2119
710179
void Environment::RunWeakRefCleanup() {
2120
710179
  isolate()->ClearKeptObjects();
2121
710179
}
2122
2123
// Not really any better place than env.cc at this moment.
2124
1531965
BaseObject::BaseObject(Environment* env, Local<Object> object)
2125
3063930
    : persistent_handle_(env->isolate(), object), env_(env) {
2126
1531965
  CHECK_EQ(false, object.IsEmpty());
2127
1531965
  CHECK_GT(object->InternalFieldCount(), 0);
2128
1531965
  object->SetAlignedPointerInInternalField(BaseObject::kSlot,
2129
                                           static_cast<void*>(this));
2130
1531965
  env->AddCleanupHook(DeleteMe, static_cast<void*>(this));
2131
1531965
  env->modify_base_object_count(1);
2132
1531965
}
2133
2134

8425110
BaseObject::~BaseObject() {
2135
3043398
  env()->modify_base_object_count(-1);
2136
3043398
  env()->RemoveCleanupHook(DeleteMe, static_cast<void*>(this));
2137
2138
3043398
  if (UNLIKELY(has_pointer_data())) {
2139
385454
    PointerData* metadata = pointer_data();
2140
385454
    CHECK_EQ(metadata->strong_ptr_count, 0);
2141
385454
    metadata->self = nullptr;
2142
385454
    if (metadata->weak_ptr_count == 0) delete metadata;
2143
  }
2144
2145
3043398
  if (persistent_handle_.IsEmpty()) {
2146
    // This most likely happened because the weak callback below cleared it.
2147
2338314
    return;
2148
  }
2149
2150
  {
2151
705084
    HandleScope handle_scope(env()->isolate());
2152
1410168
    object()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
2153
  }
2154
}
2155
2156
1319188
void BaseObject::MakeWeak() {
2157
1319188
  if (has_pointer_data()) {
2158
45601
    pointer_data()->wants_weak_jsobj = true;
2159
45601
    if (pointer_data()->strong_ptr_count > 0) return;
2160
  }
2161
2162
2638374
  persistent_handle_.SetWeak(
2163
      this,
2164
1169156
      [](const WeakCallbackInfo<BaseObject>& data) {
2165
1169156
        BaseObject* obj = data.GetParameter();
2166
        // Clear the persistent handle so that ~BaseObject() doesn't attempt
2167
        // to mess with internal fields, since the JS object may have
2168
        // transitioned into an invalid state.
2169
        // Refs: https://github.com/nodejs/node/issues/18897
2170
1169156
        obj->persistent_handle_.Reset();
2171

1169156
        CHECK_IMPLIES(obj->has_pointer_data(),
2172
                      obj->pointer_data()->strong_ptr_count == 0);
2173
1169156
        obj->OnGCCollect();
2174
1169156
      },
2175
      WeakCallbackType::kParameter);
2176
}
2177
2178
23672
void BaseObject::LazilyInitializedJSTemplateConstructor(
2179
    const FunctionCallbackInfo<Value>& args) {
2180
  DCHECK(args.IsConstructCall());
2181
  DCHECK_GT(args.This()->InternalFieldCount(), 0);
2182
23672
  args.This()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
2183
23672
}
2184
2185
23334
Local<FunctionTemplate> BaseObject::MakeLazilyInitializedJSTemplate(
2186
    Environment* env) {
2187
  Local<FunctionTemplate> t =
2188
23334
      env->NewFunctionTemplate(LazilyInitializedJSTemplateConstructor);
2189
23334
  t->Inherit(BaseObject::GetConstructorTemplate(env));
2190
46668
  t->InstanceTemplate()->SetInternalFieldCount(BaseObject::kInternalFieldCount);
2191
23334
  return t;
2192
}
2193
2194
3035185
BaseObject::PointerData* BaseObject::pointer_data() {
2195
3035185
  if (!has_pointer_data()) {
2196
194900
    PointerData* metadata = new PointerData();
2197
194900
    metadata->wants_weak_jsobj = persistent_handle_.IsWeak();
2198
194900
    metadata->self = this;
2199
194900
    pointer_data_ = metadata;
2200
  }
2201
3035185
  CHECK(has_pointer_data());
2202
3035185
  return pointer_data_;
2203
}
2204
2205
777436
void BaseObject::decrease_refcount() {
2206
777436
  CHECK(has_pointer_data());
2207
777436
  PointerData* metadata = pointer_data();
2208
777436
  CHECK_GT(metadata->strong_ptr_count, 0);
2209
777436
  unsigned int new_refcount = --metadata->strong_ptr_count;
2210
777436
  if (new_refcount == 0) {
2211
263493
    if (metadata->is_detached) {
2212
186479
      OnGCCollect();
2213

77014
    } else if (metadata->wants_weak_jsobj && !persistent_handle_.IsEmpty()) {
2214
45600
      MakeWeak();
2215
    }
2216
  }
2217
777436
}
2218
2219
779699
void BaseObject::increase_refcount() {
2220
779699
  unsigned int prev_refcount = pointer_data()->strong_ptr_count++;
2221

779699
  if (prev_refcount == 0 && !persistent_handle_.IsEmpty())
2222
265653
    persistent_handle_.ClearWeak();
2223
779699
}
2224
2225
150514
void BaseObject::DeleteMe(void* data) {
2226
150514
  BaseObject* self = static_cast<BaseObject*>(data);
2227

158485
  if (self->has_pointer_data() &&
2228
7971
      self->pointer_data()->strong_ptr_count > 0) {
2229
3417
    return self->Detach();
2230
  }
2231
147097
  delete self;
2232
}
2233
2234
460
bool BaseObject::IsDoneInitializing() const { return true; }
2235
2236
516
Local<Object> BaseObject::WrappedObject() const {
2237
516
  return object();
2238
}
2239
2240
1032
bool BaseObject::IsRootNode() const {
2241
2064
  return !persistent_handle_.IsWeak();
2242
}
2243
2244
69123
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
2245
69123
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
2246
69123
  if (tmpl.IsEmpty()) {
2247
1308
    tmpl = env->NewFunctionTemplate(nullptr);
2248
1308
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
2249
1308
    env->set_base_object_ctor_template(tmpl);
2250
  }
2251
69123
  return tmpl;
2252
}
2253
2254
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
2255
  return IsWeakOrDetached();
2256
}
2257
2258
}  // namespace node