GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.cc Lines: 1016 1102 92.2 %
Date: 2022-07-14 04:20:11 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
15378
void AsyncHooks::SetJSPromiseHooks(Local<Function> init,
69
                                   Local<Function> before,
70
                                   Local<Function> after,
71
                                   Local<Function> resolve) {
72
15378
  js_promise_hooks_[0].Reset(env()->isolate(), init);
73
15378
  js_promise_hooks_[1].Reset(env()->isolate(), before);
74
15378
  js_promise_hooks_[2].Reset(env()->isolate(), after);
75
15378
  js_promise_hooks_[3].Reset(env()->isolate(), resolve);
76
31098
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
77
15720
    if (it->IsEmpty()) {
78
      contexts_.erase(it--);
79
      continue;
80
    }
81
31440
    PersistentToLocal::Weak(env()->isolate(), *it)
82
15720
        ->SetPromiseHooks(init, before, after, resolve);
83
  }
84
15378
}
85
86
// Remember to keep this code aligned with pushAsyncContext() in JS.
87
792672
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
792672
  if (fields_[kCheck] > 0) {
93
792668
    CHECK_GE(async_id, -1);
94
792668
    CHECK_GE(trigger_async_id, -1);
95
  }
96
97
792672
  uint32_t offset = fields_[kStackLength];
98
792672
  if (offset * 2 >= async_ids_stack_.Length()) grow_async_ids_stack();
99
792672
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
100
792672
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
101
792672
  fields_[kStackLength] += 1;
102
792672
  async_id_fields_[kExecutionAsyncId] = async_id;
103
792672
  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
792672
  if (!resource.IsEmpty()) {
113
792668
    native_execution_async_resources_.resize(offset + 1);
114
    // Caveat: This is a v8::Local<> assignment, we do not keep a v8::Global<>!
115
792668
    native_execution_async_resources_[offset] = resource;
116
  }
117
792672
}
118
119
// Remember to keep this code aligned with popAsyncContext() in JS.
120
792269
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
792269
  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
1582424
  if (UNLIKELY(fields_[kCheck] > 0 &&
128

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

1582420
             !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
791210
    native_execution_async_resources_.resize(offset);
146
791210
    if (native_execution_async_resources_.size() <
147

1022604
            native_execution_async_resources_.capacity() / 2 &&
148
231394
        native_execution_async_resources_.size() > 16) {
149
      native_execution_async_resources_.shrink_to_fit();
150
    }
151
  }
152
153
1582420
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
154
30793
    HandleScope handle_scope(env()->isolate());
155
61586
    USE(js_execution_async_resources()->Set(
156
        env()->context(),
157
        env()->length_string(),
158
123172
        Integer::NewFromUnsigned(env()->isolate(), offset)));
159
  }
160
161
791210
  return fields_[kStackLength] > 0;
162
}
163
164
3314
void AsyncHooks::clear_async_id_stack() {
165
3314
  Isolate* isolate = env()->isolate();
166
3314
  HandleScope handle_scope(isolate);
167
3314
  if (!js_execution_async_resources_.IsEmpty()) {
168
4030
    USE(PersistentToLocal::Strong(js_execution_async_resources_)
169
4030
            ->Set(env()->context(),
170
                  env()->length_string(),
171
8060
                  Integer::NewFromUnsigned(isolate, 0)));
172
  }
173
3314
  native_execution_async_resources_.clear();
174
3314
  native_execution_async_resources_.shrink_to_fit();
175
176
3314
  async_id_fields_[kExecutionAsyncId] = 0;
177
3314
  async_id_fields_[kTriggerAsyncId] = 0;
178
3314
  fields_[kStackLength] = 0;
179
3314
}
180
181
7166
void AsyncHooks::AddContext(Local<Context> ctx) {
182
21498
  ctx->SetPromiseHooks(js_promise_hooks_[0].IsEmpty()
183
7166
                           ? Local<Function>()
184
205
                           : PersistentToLocal::Strong(js_promise_hooks_[0]),
185
7166
                       js_promise_hooks_[1].IsEmpty()
186
7166
                           ? Local<Function>()
187
205
                           : PersistentToLocal::Strong(js_promise_hooks_[1]),
188
7166
                       js_promise_hooks_[2].IsEmpty()
189
7166
                           ? Local<Function>()
190
205
                           : PersistentToLocal::Strong(js_promise_hooks_[2]),
191
7166
                       js_promise_hooks_[3].IsEmpty()
192
7166
                           ? Local<Function>()
193
                           : PersistentToLocal::Strong(js_promise_hooks_[3]));
194
195
7166
  size_t id = contexts_.size();
196
7166
  contexts_.resize(id + 1);
197
7166
  contexts_[id].Reset(env()->isolate(), ctx);
198
7166
  contexts_[id].SetWeak();
199
7166
}
200
201
506
void AsyncHooks::RemoveContext(Local<Context> ctx) {
202
506
  Isolate* isolate = env()->isolate();
203
1012
  HandleScope handle_scope(isolate);
204
506
  contexts_.erase(std::remove_if(contexts_.begin(),
205
                                 contexts_.end(),
206
3942
                                 [&](auto&& el) { return el.IsEmpty(); }),
207
1012
                  contexts_.end());
208
3879
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
209
3373
    Local<Context> saved_context = PersistentToLocal::Weak(isolate, *it);
210
3373
    if (saved_context == ctx) {
211
      it->Reset();
212
      contexts_.erase(it);
213
      break;
214
    }
215
  }
216
506
}
217
218
244644
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
219
244644
    Environment* env, double default_trigger_async_id)
220
244644
    : async_hooks_(env->async_hooks()) {
221
244644
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
222
244644
    CHECK_GE(default_trigger_async_id, 0);
223
  }
224
225
244644
  old_default_trigger_async_id_ =
226
244644
      async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
227
244644
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
228
244644
      default_trigger_async_id;
229
244644
}
230
231
489286
AsyncHooks::DefaultTriggerAsyncIdScope::~DefaultTriggerAsyncIdScope() {
232
244643
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
233
244643
      old_default_trigger_async_id_;
234
244643
}
235
236
244644
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
237
244644
    AsyncWrap* async_wrap)
238
    : DefaultTriggerAsyncIdScope(async_wrap->env(),
239
244644
                                 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
5249
void IsolateData::DeserializeProperties(const std::vector<size_t>* indexes) {
269
5249
  size_t i = 0;
270
10498
  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




89233
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
286






131225
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
287









































































































































2892199
  PER_ISOLATE_STRING_PROPERTIES(VS)
288
#undef V
289
#undef VY
290
#undef VS
291
#undef VP
292
293
309691
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
294
    MaybeLocal<String> maybe_field =
295
608884
        isolate_->GetDataFromSnapshotOnce<String>((*indexes)[i++]);
296
    Local<String> field;
297
304442
    if (!maybe_field.ToLocal(&field)) {
298
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
299
    }
300
304442
    async_wrap_providers_[j].Set(isolate_, field);
301
  }
302
5249
}
303
304
1308
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
1308
  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
11772
  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
17004
  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
361008
  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
77172
  NODE_ASYNC_PROVIDER_TYPES(V)
365
#undef V
366
1308
}
367
368
6557
IsolateData::IsolateData(Isolate* isolate,
369
                         uv_loop_t* event_loop,
370
                         MultiIsolatePlatform* platform,
371
                         ArrayBufferAllocator* node_allocator,
372
6557
                         const std::vector<size_t>* indexes)
373
    : isolate_(isolate),
374
      event_loop_(event_loop),
375
47
      node_allocator_(node_allocator == nullptr ? nullptr
376
6510
                                                : node_allocator->GetImpl()),
377
13114
      platform_(platform) {
378
6557
  options_.reset(
379
6557
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
380
381
6557
  if (indexes == nullptr) {
382
1308
    CreateProperties();
383
  } else {
384
5249
    DeserializeProperties(indexes);
385
  }
386
6557
}
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
7166
void Environment::AssignToContext(Local<v8::Context> context,
433
                                  const ContextInfo& info) {
434
7166
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
435
                                           this);
436
  // Used by Environment::GetCurrent to know that we are on a node context.
437
7166
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kContextTag,
438
                                           Environment::kNodeContextTagPtr);
439
  // Used to retrieve bindings
440
14332
  context->SetAlignedPointerInEmbedderData(
441
7166
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
442
443
#if HAVE_INSPECTOR
444
7166
  inspector_agent()->ContextCreated(context, info);
445
#endif  // HAVE_INSPECTOR
446
447
7166
  this->async_hooks()->AddContext(context);
448
7166
}
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
2923
void Environment::add_refs(int64_t diff) {
477
2923
  task_queues_async_refs_ += diff;
478
2923
  CHECK_GE(task_queues_async_refs_, 0);
479
2923
  if (task_queues_async_refs_ == 0)
480
194
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
481
  else
482
2729
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
483
2923
}
484
485
68256
uv_buf_t Environment::allocate_managed_buffer(const size_t suggested_size) {
486
136512
  NoArrayBufferZeroFillScope no_zero_fill_scope(isolate_data());
487
  std::unique_ptr<v8::BackingStore> bs =
488
68256
      v8::ArrayBuffer::NewBackingStore(isolate(), suggested_size);
489
68256
  uv_buf_t buf = uv_buf_init(static_cast<char*>(bs->Data()), bs->ByteLength());
490
68256
  released_allocated_buffers_.emplace(buf.base, std::move(bs));
491
68256
  return buf;
492
}
493
494
83101
std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer(
495
    const uv_buf_t& buf) {
496
83101
  std::unique_ptr<v8::BackingStore> bs;
497
83101
  if (buf.base != nullptr) {
498
68256
    auto it = released_allocated_buffers_.find(buf.base);
499
68256
    CHECK_NE(it, released_allocated_buffers_.end());
500
68256
    bs = std::move(it->second);
501
68256
    released_allocated_buffers_.erase(it);
502
  }
503
83101
  return bs;
504
}
505
506
1465943
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
1465943
                                   c_function);
520
}
521
522
374001
void Environment::SetMethod(Local<v8::Object> that,
523
                            const char* name,
524
                            v8::FunctionCallback callback) {
525
374001
  Local<v8::Context> context = isolate()->GetCurrentContext();
526
  Local<v8::Function> function =
527
374001
      NewFunctionTemplate(callback,
528
                          Local<v8::Signature>(),
529
                          v8::ConstructorBehavior::kThrow,
530
374001
                          v8::SideEffectType::kHasSideEffect)
531
374001
          ->GetFunction(context)
532
374001
          .ToLocalChecked();
533
  // kInternalized strings are created in the old space.
534
374001
  const v8::NewStringType type = v8::NewStringType::kInternalized;
535
  Local<v8::String> name_string =
536
748002
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
537
748002
  that->Set(context, name_string, function).Check();
538
374001
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
539
374001
}
540
541
2598
void Environment::SetFastMethod(Local<v8::Object> that,
542
                                const char* name,
543
                                v8::FunctionCallback slow_callback,
544
                                const v8::CFunction* c_function) {
545
2598
  Local<v8::Context> context = isolate()->GetCurrentContext();
546
  Local<v8::Function> function =
547
2598
      NewFunctionTemplate(slow_callback,
548
                          Local<v8::Signature>(),
549
                          v8::ConstructorBehavior::kThrow,
550
                          v8::SideEffectType::kHasNoSideEffect,
551
2598
                          c_function)
552
2598
          ->GetFunction(context)
553
2598
          .ToLocalChecked();
554
2598
  const v8::NewStringType type = v8::NewStringType::kInternalized;
555
  Local<v8::String> name_string =
556
5196
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
557
2598
  that->Set(context, name_string, function).Check();
558
2598
}
559
560
113162
void Environment::SetMethodNoSideEffect(Local<v8::Object> that,
561
                                        const char* name,
562
                                        v8::FunctionCallback callback) {
563
113162
  Local<v8::Context> context = isolate()->GetCurrentContext();
564
  Local<v8::Function> function =
565
113162
      NewFunctionTemplate(callback,
566
                          Local<v8::Signature>(),
567
                          v8::ConstructorBehavior::kThrow,
568
113162
                          v8::SideEffectType::kHasNoSideEffect)
569
113162
          ->GetFunction(context)
570
113162
          .ToLocalChecked();
571
  // kInternalized strings are created in the old space.
572
113162
  const v8::NewStringType type = v8::NewStringType::kInternalized;
573
  Local<v8::String> name_string =
574
226324
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
575
226324
  that->Set(context, name_string, function).Check();
576
113162
  function->SetName(name_string);  // NODE_SET_METHOD() compatibility.
577
113162
}
578
579
670785
void Environment::SetProtoMethod(Local<v8::FunctionTemplate> that,
580
                                 const char* name,
581
                                 v8::FunctionCallback callback) {
582
670785
  Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
583
  Local<v8::FunctionTemplate> t =
584
      NewFunctionTemplate(callback,
585
                          signature,
586
                          v8::ConstructorBehavior::kThrow,
587
670785
                          v8::SideEffectType::kHasSideEffect);
588
  // kInternalized strings are created in the old space.
589
670785
  const v8::NewStringType type = v8::NewStringType::kInternalized;
590
  Local<v8::String> name_string =
591
1341570
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
592
1341570
  that->PrototypeTemplate()->Set(name_string, t);
593
670785
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
594
670785
}
595
596
98071
void Environment::SetProtoMethodNoSideEffect(Local<v8::FunctionTemplate> that,
597
                                             const char* name,
598
                                             v8::FunctionCallback callback) {
599
98071
  Local<v8::Signature> signature = v8::Signature::New(isolate(), that);
600
  Local<v8::FunctionTemplate> t =
601
      NewFunctionTemplate(callback,
602
                          signature,
603
                          v8::ConstructorBehavior::kThrow,
604
98071
                          v8::SideEffectType::kHasNoSideEffect);
605
  // kInternalized strings are created in the old space.
606
98071
  const v8::NewStringType type = v8::NewStringType::kInternalized;
607
  Local<v8::String> name_string =
608
196142
      v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked();
609
196142
  that->PrototypeTemplate()->Set(name_string, t);
610
98071
  t->SetClassName(name_string);  // NODE_SET_PROTOTYPE_METHOD() compatibility.
611
98071
}
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
133948
void Environment::SetConstructorFunction(Local<v8::Object> that,
631
                                         const char* name,
632
                                         Local<v8::FunctionTemplate> tmpl,
633
                                         SetConstructorFunctionFlag flag) {
634
133948
  SetConstructorFunction(that, OneByteString(isolate(), name), tmpl, flag);
635
133948
}
636
637
140443
void Environment::SetConstructorFunction(Local<v8::Object> that,
638
                                         Local<v8::String> name,
639
                                         Local<v8::FunctionTemplate> tmpl,
640
                                         SetConstructorFunctionFlag flag) {
641
140443
  if (LIKELY(flag == SetConstructorFunctionFlag::SET_CLASS_NAME))
642
126122
    tmpl->SetClassName(name);
643
280886
  that->Set(context(), name, tmpl->GetFunction(context()).ToLocalChecked())
644
      .Check();
645
140443
}
646
647
1299
void Environment::CreateProperties() {
648
2598
  HandleScope handle_scope(isolate_);
649
1299
  Local<Context> ctx = context();
650
651
  {
652
1299
    Context::Scope context_scope(ctx);
653
1299
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
654
2598
    templ->InstanceTemplate()->SetInternalFieldCount(
655
        BaseObject::kInternalFieldCount);
656
1299
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
657
658
1299
    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
2598
      GetPerContextExports(ctx).ToLocalChecked();
664
  Local<Value> primordials =
665
3897
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
666
1299
  CHECK(primordials->IsObject());
667
1299
  set_primordials(primordials.As<Object>());
668
669
  Local<String> prototype_string =
670
1299
      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

7794
  V(primordials_safe_map_prototype_object, "SafeMap");
687

7794
  V(primordials_safe_set_prototype_object, "SafeSet");
688

7794
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
689

7794
  V(primordials_safe_weak_set_prototype_object, "SafeWeakSet");
690
#undef V
691
692
  Local<Object> process_object =
693
1299
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
694
1299
  set_process_object(process_object);
695
1299
}
696
697
6548
std::string GetExecPath(const std::vector<std::string>& argv) {
698
  char exec_path_buf[2 * PATH_MAX];
699
6548
  size_t exec_path_len = sizeof(exec_path_buf);
700
6548
  std::string exec_path;
701
6548
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
702
6548
    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
6548
  return exec_path;
721
}
722
723
6548
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
6548
                         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
6548
      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
6548
          isolate_,
741
          1,
742
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
743
6548
      stream_base_state_(isolate_,
744
                         StreamBase::kNumStreamBaseStateFields,
745
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
746
6548
      environment_start_time_(PERFORMANCE_NOW()),
747
      flags_(flags),
748
6548
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
749
6548
                     ? AllocateEnvironmentThreadId().id
750



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

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

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

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

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

16542
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunCleanup");
1089
5939
  bindings_.clear();
1090
5939
  CleanupHandles();
1091
1092
17811
  while (!cleanup_hooks_.empty() ||
1093
11880
         native_immediates_.size() > 0 ||
1094

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

18533
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "AtExit");
1131
19702
  for (ExitCallback at_exit : at_exit_functions_) {
1132
13062
    at_exit.cb_(at_exit.arg_);
1133
  }
1134
6640
  at_exit_functions_.clear();
1135
6640
}
1136
1137
13086
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
1138
13086
  at_exit_functions_.push_front(ExitCallback{cb, arg});
1139
13086
}
1140
1141
230976
void Environment::RunAndClearInterrupts() {
1142
230976
  while (native_immediates_interrupts_.size() > 0) {
1143
11910
    NativeImmediateQueue queue;
1144
    {
1145
23820
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1146
11910
      queue.ConcatMove(std::move(native_immediates_interrupts_));
1147
    }
1148
11910
    DebugSealHandleScope seal_handle_scope(isolate());
1149
1150
23828
    while (auto head = queue.Shift())
1151
23836
      head->Call(this);
1152
  }
1153
219066
}
1154
1155
207818
void Environment::RunAndClearNativeImmediates(bool only_refed) {
1156

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

61419
      if (is_refed || !only_refed)
1176
61211
        head->Call(this);
1177
1178
61414
      head.reset();  // Destroy now so that this is also observed by try_catch.
1179
1180
61414
      if (UNLIKELY(try_catch.HasCaught())) {
1181

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

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

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

190940
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "CheckImmediate");
1323
1324
187964
  HandleScope scope(env->isolate());
1325
187964
  Context::Scope context_scope(env->context());
1326
1327
187964
  env->RunAndClearNativeImmediates();
1328
1329

187964
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
1330
144176
    return;
1331
1332
951
  do {
1333
44732
    MakeCallback(env->isolate(),
1334
                 env->process_object(),
1335
                 env->immediate_callback_function(),
1336
                 0,
1337
                 nullptr,
1338
44739
                 {0, 0}).ToLocalChecked();
1339

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

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

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

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

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


















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































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








































































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






























































































































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

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

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

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

76800
    } else if (metadata->wants_weak_jsobj && !persistent_handle_.IsEmpty()) {
2216
45493
      MakeWeak();
2217
    }
2218
  }
2219
774435
}
2220
2221
777050
void BaseObject::increase_refcount() {
2222
777050
  unsigned int prev_refcount = pointer_data()->strong_ptr_count++;
2223

777050
  if (prev_refcount == 0 && !persistent_handle_.IsEmpty())
2224
264618
    persistent_handle_.ClearWeak();
2225
777050
}
2226
2227
147600
void BaseObject::DeleteMe(void* data) {
2228
147600
  BaseObject* self = static_cast<BaseObject*>(data);
2229

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