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

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

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

1103722
            native_execution_async_resources_.capacity() / 2 &&
149
261629
        native_execution_async_resources_.size() > 16) {
150
      native_execution_async_resources_.shrink_to_fit();
151
    }
152
  }
153
154
1684186
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
155
43838
    HandleScope handle_scope(env()->isolate());
156
87676
    USE(js_execution_async_resources()->Set(
157
        env()->context(),
158
        env()->length_string(),
159
175352
        Integer::NewFromUnsigned(env()->isolate(), offset)));
160
  }
161
162
842093
  return fields_[kStackLength] > 0;
163
}
164
165
2336
void AsyncHooks::clear_async_id_stack() {
166
2336
  if (env()->can_call_into_js()) {
167
1353
    Isolate* isolate = env()->isolate();
168
2706
    HandleScope handle_scope(isolate);
169
1353
    if (!js_execution_async_resources_.IsEmpty()) {
170
2580
      USE(PersistentToLocal::Strong(js_execution_async_resources_)
171
2580
              ->Set(env()->context(),
172
                    env()->length_string(),
173
5160
                    Integer::NewFromUnsigned(isolate, 0)));
174
    }
175
  }
176
177
2336
  native_execution_async_resources_.clear();
178
2336
  native_execution_async_resources_.shrink_to_fit();
179
180
2336
  async_id_fields_[kExecutionAsyncId] = 0;
181
2336
  async_id_fields_[kTriggerAsyncId] = 0;
182
2336
  fields_[kStackLength] = 0;
183
2336
}
184
185
6933
void AsyncHooks::AddContext(Local<Context> ctx) {
186
20799
  ctx->SetPromiseHooks(js_promise_hooks_[0].IsEmpty()
187
6933
                           ? Local<Function>()
188
205
                           : PersistentToLocal::Strong(js_promise_hooks_[0]),
189
6933
                       js_promise_hooks_[1].IsEmpty()
190
6933
                           ? Local<Function>()
191
205
                           : PersistentToLocal::Strong(js_promise_hooks_[1]),
192
6933
                       js_promise_hooks_[2].IsEmpty()
193
6933
                           ? Local<Function>()
194
205
                           : PersistentToLocal::Strong(js_promise_hooks_[2]),
195
6933
                       js_promise_hooks_[3].IsEmpty()
196
6933
                           ? Local<Function>()
197
                           : PersistentToLocal::Strong(js_promise_hooks_[3]));
198
199
6933
  size_t id = contexts_.size();
200
6933
  contexts_.resize(id + 1);
201
6933
  contexts_[id].Reset(env()->isolate(), ctx);
202
6933
  contexts_[id].SetWeak();
203
6933
}
204
205
513
void AsyncHooks::RemoveContext(Local<Context> ctx) {
206
513
  Isolate* isolate = env()->isolate();
207
1026
  HandleScope handle_scope(isolate);
208
513
  contexts_.erase(std::remove_if(contexts_.begin(),
209
                                 contexts_.end(),
210
3895
                                 [&](auto&& el) { return el.IsEmpty(); }),
211
1026
                  contexts_.end());
212
3833
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
213
3320
    Local<Context> saved_context = PersistentToLocal::Weak(isolate, *it);
214
3320
    if (saved_context == ctx) {
215
      it->Reset();
216
      contexts_.erase(it);
217
      break;
218
    }
219
  }
220
513
}
221
222
238801
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
223
238801
    Environment* env, double default_trigger_async_id)
224
238801
    : async_hooks_(env->async_hooks()) {
225
238801
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
226
238801
    CHECK_GE(default_trigger_async_id, 0);
227
  }
228
229
238801
  old_default_trigger_async_id_ =
230
238801
      async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
231
238801
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
232
238801
      default_trigger_async_id;
233
238801
}
234
235
477600
AsyncHooks::DefaultTriggerAsyncIdScope::~DefaultTriggerAsyncIdScope() {
236
238800
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
237
238800
      old_default_trigger_async_id_;
238
238800
}
239
240
238801
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
241
238801
    AsyncWrap* async_wrap)
242
    : DefaultTriggerAsyncIdScope(async_wrap->env(),
243
238801
                                 async_wrap->get_async_id()) {}
244
245
12
std::ostream& operator<<(std::ostream& output,
246
                         const std::vector<SnapshotIndex>& v) {
247
12
  output << "{ ";
248
2142
  for (const SnapshotIndex i : v) {
249
2130
    output << i << ", ";
250
  }
251
12
  output << " }";
252
12
  return output;
253
}
254
255
6
std::ostream& operator<<(std::ostream& output,
256
                         const IsolateDataSerializeInfo& i) {
257
  output << "{\n"
258
6
         << "// -- primitive begins --\n"
259
6
         << i.primitive_values << ",\n"
260
         << "// -- primitive ends --\n"
261
6
         << "// -- template_values begins --\n"
262
6
         << i.template_values << ",\n"
263
         << "// -- template_values ends --\n"
264
6
         << "}";
265
6
  return output;
266
}
267
268
6
std::ostream& operator<<(std::ostream& output, const SnapshotMetadata& i) {
269
  output << "{\n"
270
         << "  "
271
6
         << (i.type == SnapshotMetadata::Type::kDefault
272
                 ? "SnapshotMetadata::Type::kDefault"
273
                 : "SnapshotMetadata::Type::kFullyCustomized")
274
         << ", // type\n"
275
6
         << "  \"" << i.node_version << "\", // node_version\n"
276
6
         << "  \"" << i.node_arch << "\", // node_arch\n"
277
6
         << "  \"" << i.node_platform << "\", // node_platform\n"
278
6
         << "  " << i.v8_cache_version_tag << ", // v8_cache_version_tag\n"
279
6
         << "}";
280
6
  return output;
281
}
282
283
6
IsolateDataSerializeInfo IsolateData::Serialize(SnapshotCreator* creator) {
284
6
  Isolate* isolate = creator->GetIsolate();
285
6
  IsolateDataSerializeInfo info;
286
12
  HandleScope handle_scope(isolate);
287
  // XXX(joyeecheung): technically speaking, the indexes here should be
288
  // consecutive and we could just return a range instead of an array,
289
  // but that's not part of the V8 API contract so we use an array
290
  // just to be safe.
291
292
#define VP(PropertyName, StringValue) V(Private, PropertyName)
293
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
294
#define VS(PropertyName, StringValue) V(String, PropertyName)
295
#define V(TypeName, PropertyName)                                              \
296
  info.primitive_values.push_back(                                             \
297
      creator->AddData(PropertyName##_.Get(isolate)));
298
60
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
299
78
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
300
1662
  PER_ISOLATE_STRING_PROPERTIES(VS)
301
#undef V
302
#undef VY
303
#undef VS
304
#undef VP
305
306
354
  for (size_t i = 0; i < AsyncWrap::PROVIDERS_LENGTH; i++)
307
696
    info.primitive_values.push_back(creator->AddData(async_wrap_provider(i)));
308
309
6
  uint32_t id = 0;
310
#define V(PropertyName, TypeName)                                              \
311
  do {                                                                         \
312
    Local<TypeName> field = PropertyName();                                    \
313
    if (!field.IsEmpty()) {                                                    \
314
      size_t index = creator->AddData(field);                                  \
315
      info.template_values.push_back({#PropertyName, id, index});              \
316
    }                                                                          \
317
    id++;                                                                      \
318
  } while (0);
319


















348
  PER_ISOLATE_TEMPLATE_PROPERTIES(V)
320
#undef V
321
322
6
  return info;
323
}
324
325
5520
void IsolateData::DeserializeProperties(const IsolateDataSerializeInfo* info) {
326
5520
  size_t i = 0;
327
5520
  HandleScope handle_scope(isolate_);
328
329
#define VP(PropertyName, StringValue) V(Private, PropertyName)
330
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
331
#define VS(PropertyName, StringValue) V(String, PropertyName)
332
#define V(TypeName, PropertyName)                                              \
333
  do {                                                                         \
334
    MaybeLocal<TypeName> maybe_field =                                         \
335
        isolate_->GetDataFromSnapshotOnce<TypeName>(                           \
336
            info->primitive_values[i++]);                                      \
337
    Local<TypeName> field;                                                     \
338
    if (!maybe_field.ToLocal(&field)) {                                        \
339
      fprintf(stderr, "Failed to deserialize " #PropertyName "\n");            \
340
    }                                                                          \
341
    PropertyName##_.Set(isolate_, field);                                      \
342
  } while (0);
343




104880
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
344






138000
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
345










































































































































3052560
  PER_ISOLATE_STRING_PROPERTIES(VS)
346
#undef V
347
#undef VY
348
#undef VS
349
#undef VP
350
351
325680
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
352
    MaybeLocal<String> maybe_field =
353
640320
        isolate_->GetDataFromSnapshotOnce<String>(info->primitive_values[i++]);
354
    Local<String> field;
355
320160
    if (!maybe_field.ToLocal(&field)) {
356
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
357
    }
358
320160
    async_wrap_providers_[j].Set(isolate_, field);
359
  }
360
361
5520
  const std::vector<PropInfo>& values = info->template_values;
362
5520
  i = 0;  // index to the array
363
5520
  uint32_t id = 0;
364
#define V(PropertyName, TypeName)                                              \
365
  do {                                                                         \
366
    if (values.size() > i && id == values[i].id) {                             \
367
      const PropInfo& d = values[i];                                           \
368
      DCHECK_EQ(d.name, #PropertyName);                                        \
369
      MaybeLocal<TypeName> maybe_field =                                       \
370
          isolate_->GetDataFromSnapshotOnce<TypeName>(d.index);                \
371
      Local<TypeName> field;                                                   \
372
      if (!maybe_field.ToLocal(&field)) {                                      \
373
        fprintf(stderr,                                                        \
374
                "Failed to deserialize isolate data template " #PropertyName   \
375
                "\n");                                                         \
376
      }                                                                        \
377
      set_##PropertyName(field);                                               \
378
      i++;                                                                     \
379
    }                                                                          \
380
    id++;                                                                      \
381
  } while (0);
382
383










































































226320
  PER_ISOLATE_TEMPLATE_PROPERTIES(V);
384
#undef V
385
5520
}
386
387
794
void IsolateData::CreateProperties() {
388
  // Create string and private symbol properties as internalized one byte
389
  // strings after the platform is properly initialized.
390
  //
391
  // Internalized because it makes property lookups a little faster and
392
  // because the string is created in the old space straight away.  It's going
393
  // to end up in the old space sooner or later anyway but now it doesn't go
394
  // through v8::Eternal's new space handling first.
395
  //
396
  // One byte because our strings are ASCII and we can safely skip V8's UTF-8
397
  // decoding step.
398
399
1588
  HandleScope handle_scope(isolate_);
400
401
#define V(PropertyName, StringValue)                                           \
402
  PropertyName##_.Set(                                                         \
403
      isolate_,                                                                \
404
      Private::New(isolate_,                                                   \
405
                   String::NewFromOneByte(                                     \
406
                       isolate_,                                               \
407
                       reinterpret_cast<const uint8_t*>(StringValue),          \
408
                       NewStringType::kInternalized,                           \
409
                       sizeof(StringValue) - 1)                                \
410
                       .ToLocalChecked()));
411
7940
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)
412
#undef V
413
#define V(PropertyName, StringValue)                                           \
414
  PropertyName##_.Set(                                                         \
415
      isolate_,                                                                \
416
      Symbol::New(isolate_,                                                    \
417
                  String::NewFromOneByte(                                      \
418
                      isolate_,                                                \
419
                      reinterpret_cast<const uint8_t*>(StringValue),           \
420
                      NewStringType::kInternalized,                            \
421
                      sizeof(StringValue) - 1)                                 \
422
                      .ToLocalChecked()));
423
10322
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
424
#undef V
425
#define V(PropertyName, StringValue)                                           \
426
  PropertyName##_.Set(                                                         \
427
      isolate_,                                                                \
428
      String::NewFromOneByte(isolate_,                                         \
429
                             reinterpret_cast<const uint8_t*>(StringValue),    \
430
                             NewStringType::kInternalized,                     \
431
                             sizeof(StringValue) - 1)                          \
432
          .ToLocalChecked());
433
219938
  PER_ISOLATE_STRING_PROPERTIES(V)
434
#undef V
435
436
  // Create all the provider strings that will be passed to JS. Place them in
437
  // an array so the array index matches the PROVIDER id offset. This way the
438
  // strings can be retrieved quickly.
439
#define V(Provider)                                                           \
440
  async_wrap_providers_[AsyncWrap::PROVIDER_ ## Provider].Set(                \
441
      isolate_,                                                               \
442
      String::NewFromOneByte(                                                 \
443
        isolate_,                                                             \
444
        reinterpret_cast<const uint8_t*>(#Provider),                          \
445
        NewStringType::kInternalized,                                         \
446
        sizeof(#Provider) - 1).ToLocalChecked());
447
46846
  NODE_ASYNC_PROVIDER_TYPES(V)
448
#undef V
449
450
  // TODO(legendecas): eagerly create per isolate templates.
451
794
  Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
452
1588
  templ->InstanceTemplate()->SetInternalFieldCount(
453
      BaseObject::kInternalFieldCount);
454
794
  templ->Inherit(BaseObject::GetConstructorTemplate(this));
455
794
  set_binding_data_ctor_template(templ);
456
457
794
  set_contextify_global_template(
458
794
      contextify::ContextifyContext::CreateGlobalTemplate(isolate_));
459
794
}
460
461
6314
IsolateData::IsolateData(Isolate* isolate,
462
                         uv_loop_t* event_loop,
463
                         MultiIsolatePlatform* platform,
464
                         ArrayBufferAllocator* node_allocator,
465
6314
                         const IsolateDataSerializeInfo* isolate_data_info)
466
    : isolate_(isolate),
467
      event_loop_(event_loop),
468
51
      node_allocator_(node_allocator == nullptr ? nullptr
469
6263
                                                : node_allocator->GetImpl()),
470
12628
      platform_(platform) {
471
6314
  options_.reset(
472
6314
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
473
474
6314
  if (isolate_data_info == nullptr) {
475
794
    CreateProperties();
476
  } else {
477
5520
    DeserializeProperties(isolate_data_info);
478
  }
479
6314
}
480
481
25
void IsolateData::MemoryInfo(MemoryTracker* tracker) const {
482
#define V(PropertyName, StringValue)                                           \
483
  tracker->TrackField(#PropertyName, PropertyName());
484
25
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
485
486
25
  PER_ISOLATE_STRING_PROPERTIES(V)
487
#undef V
488
489
25
  tracker->TrackField("async_wrap_providers", async_wrap_providers_);
490
491
25
  if (node_allocator_ != nullptr) {
492
25
    tracker->TrackFieldWithSize(
493
        "node_allocator", sizeof(*node_allocator_), "NodeArrayBufferAllocator");
494
  }
495
25
  tracker->TrackFieldWithSize(
496
      "platform", sizeof(*platform_), "MultiIsolatePlatform");
497
  // TODO(joyeecheung): implement MemoryRetainer in the option classes.
498
25
}
499
500
154
void TrackingTraceStateObserver::UpdateTraceCategoryState() {
501

154
  if (!env_->owns_process_state() || !env_->can_call_into_js()) {
502
    // Ideally, we’d have a consistent story that treats all threads/Environment
503
    // instances equally here. However, tracing is essentially global, and this
504
    // callback is called from whichever thread calls `StartTracing()` or
505
    // `StopTracing()`. The only way to do this in a threadsafe fashion
506
    // seems to be only tracking this from the main thread, and only allowing
507
    // these state modifications from the main thread.
508
96
    return;
509
  }
510
511
143
  if (env_->principal_realm() == nullptr) {
512
85
    return;
513
  }
514
515
58
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
516
58
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
517
518
58
  Isolate* isolate = env_->isolate();
519
58
  HandleScope handle_scope(isolate);
520
58
  Local<Function> cb = env_->trace_category_state_function();
521
58
  if (cb.IsEmpty())
522
    return;
523
58
  TryCatchScope try_catch(env_);
524
58
  try_catch.SetVerbose(true);
525
116
  Local<Value> args[] = {Boolean::New(isolate, async_hooks_enabled)};
526
116
  USE(cb->Call(env_->context(), Undefined(isolate), arraysize(args), args));
527
}
528
529
6933
void Environment::AssignToContext(Local<v8::Context> context,
530
                                  Realm* realm,
531
                                  const ContextInfo& info) {
532
6933
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
533
                                           this);
534
6933
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kRealm, realm);
535
  // Used to retrieve bindings
536
13866
  context->SetAlignedPointerInEmbedderData(
537
6933
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
538
539
  // ContextifyContexts will update this to a pointer to the native object.
540
6933
  context->SetAlignedPointerInEmbedderData(
541
      ContextEmbedderIndex::kContextifyContext, nullptr);
542
543
  // This must not be done before other context fields are initialized.
544
6933
  ContextEmbedderTag::TagNodeContext(context);
545
546
#if HAVE_INSPECTOR
547
6933
  inspector_agent()->ContextCreated(context, info);
548
#endif  // HAVE_INSPECTOR
549
550
6933
  this->async_hooks()->AddContext(context);
551
6933
}
552
553
185
void Environment::TryLoadAddon(
554
    const char* filename,
555
    int flags,
556
    const std::function<bool(binding::DLib*)>& was_loaded) {
557
185
  loaded_addons_.emplace_back(filename, flags);
558
185
  if (!was_loaded(&loaded_addons_.back())) {
559
10
    loaded_addons_.pop_back();
560
  }
561
185
}
562
563
12
std::string Environment::GetCwd() {
564
  char cwd[PATH_MAX_BYTES];
565
12
  size_t size = PATH_MAX_BYTES;
566
12
  const int err = uv_cwd(cwd, &size);
567
568
12
  if (err == 0) {
569
12
    CHECK_GT(size, 0);
570
12
    return cwd;
571
  }
572
573
  // This can fail if the cwd is deleted. In that case, fall back to
574
  // exec_path.
575
  const std::string& exec_path = exec_path_;
576
  return exec_path.substr(0, exec_path.find_last_of(kPathSeparator));
577
}
578
579
1903
void Environment::add_refs(int64_t diff) {
580
1903
  task_queues_async_refs_ += diff;
581
1903
  CHECK_GE(task_queues_async_refs_, 0);
582
1903
  if (task_queues_async_refs_ == 0)
583
421
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
584
  else
585
1482
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
586
1903
}
587
588
66425
uv_buf_t Environment::allocate_managed_buffer(const size_t suggested_size) {
589
132850
  NoArrayBufferZeroFillScope no_zero_fill_scope(isolate_data());
590
  std::unique_ptr<v8::BackingStore> bs =
591
66425
      v8::ArrayBuffer::NewBackingStore(isolate(), suggested_size);
592
66425
  uv_buf_t buf = uv_buf_init(static_cast<char*>(bs->Data()), bs->ByteLength());
593
66425
  released_allocated_buffers_.emplace(buf.base, std::move(bs));
594
66425
  return buf;
595
}
596
597
81391
std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer(
598
    const uv_buf_t& buf) {
599
81391
  std::unique_ptr<v8::BackingStore> bs;
600
81391
  if (buf.base != nullptr) {
601
66425
    auto it = released_allocated_buffers_.find(buf.base);
602
66425
    CHECK_NE(it, released_allocated_buffers_.end());
603
66425
    bs = std::move(it->second);
604
66425
    released_allocated_buffers_.erase(it);
605
  }
606
81391
  return bs;
607
}
608
609
6307
std::string GetExecPath(const std::vector<std::string>& argv) {
610
  char exec_path_buf[2 * PATH_MAX];
611
6307
  size_t exec_path_len = sizeof(exec_path_buf);
612
6307
  std::string exec_path;
613
6307
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
614
6307
    exec_path = std::string(exec_path_buf, exec_path_len);
615
  } else {
616
    exec_path = argv[0];
617
  }
618
619
  // On OpenBSD process.execPath will be relative unless we
620
  // get the full path before process.execPath is used.
621
#if defined(__OpenBSD__)
622
  uv_fs_t req;
623
  req.ptr = nullptr;
624
  if (0 ==
625
      uv_fs_realpath(nullptr, &req, exec_path.c_str(), nullptr)) {
626
    CHECK_NOT_NULL(req.ptr);
627
    exec_path = std::string(static_cast<char*>(req.ptr));
628
  }
629
  uv_fs_req_cleanup(&req);
630
#endif
631
632
6307
  return exec_path;
633
}
634
635
6307
Environment::Environment(IsolateData* isolate_data,
636
                         Isolate* isolate,
637
                         const std::vector<std::string>& args,
638
                         const std::vector<std::string>& exec_args,
639
                         const EnvSerializeInfo* env_info,
640
                         EnvironmentFlags::Flags flags,
641
6307
                         ThreadId thread_id)
642
    : isolate_(isolate),
643
      isolate_data_(isolate_data),
644
      async_hooks_(isolate, MAYBE_FIELD_PTR(env_info, async_hooks)),
645
      immediate_info_(isolate, MAYBE_FIELD_PTR(env_info, immediate_info)),
646
      tick_info_(isolate, MAYBE_FIELD_PTR(env_info, tick_info)),
647
6307
      timer_base_(uv_now(isolate_data->event_loop())),
648
      exec_argv_(exec_args),
649
      argv_(args),
650
      exec_path_(GetExecPath(args)),
651
6307
      exiting_(isolate_, 1, MAYBE_FIELD_PTR(env_info, exiting)),
652
      should_abort_on_uncaught_toggle_(
653
6307
          isolate_,
654
          1,
655
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
656
6307
      stream_base_state_(isolate_,
657
                         StreamBase::kNumStreamBaseStateFields,
658
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
659
6307
      time_origin_(PERFORMANCE_NOW()),
660
6307
      time_origin_timestamp_(GetCurrentTimeInMicroseconds()),
661
      flags_(flags),
662
6307
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
663
6307
                     ? AllocateEnvironmentThreadId().id
664



25228
                     : thread_id.id) {
665
  // We'll be creating new objects so make sure we've entered the context.
666
12614
  HandleScope handle_scope(isolate);
667
668
  // Set some flags if only kDefaultFlags was passed. This can make API version
669
  // transitions easier for embedders.
670
6307
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
671
11154
    flags_ = flags_ |
672
5577
        EnvironmentFlags::kOwnsProcessState |
673
        EnvironmentFlags::kOwnsInspector;
674
  }
675
676
6307
  set_env_vars(per_process::system_environment);
677
6307
  enabled_debug_list_.Parse(env_vars(), isolate);
678
679
  // We create new copies of the per-Environment option sets, so that it is
680
  // easier to modify them after Environment creation. The defaults are
681
  // part of the per-Isolate option set, for which in turn the defaults are
682
  // part of the per-process option set.
683
12614
  options_ = std::make_shared<EnvironmentOptions>(
684
18921
      *isolate_data->options()->per_env);
685
6307
  inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
686
6307
      options_->debug_options().host_port);
687
688
6307
  heap_snapshot_near_heap_limit_ =
689
6307
      static_cast<uint32_t>(options_->heap_snapshot_near_heap_limit);
690
691
6307
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
692
730
    set_abort_on_uncaught_exception(false);
693
  }
694
695
#if HAVE_INSPECTOR
696
  // We can only create the inspector agent after having cloned the options.
697
6307
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
698
#endif
699
700
6307
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
701
6307
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
702
6307
    if (TracingController* tracing_controller = writer->GetTracingController())
703
6256
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
704
  }
705
706
6307
  destroy_async_id_list_.reserve(512);
707
708
6307
  performance_state_ = std::make_unique<performance::PerformanceState>(
709
6307
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
710
711
6307
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
712
6307
          TRACING_CATEGORY_NODE1(environment)) != 0) {
713
16
    auto traced_value = tracing::TracedValue::Create();
714
8
    traced_value->BeginArray("args");
715
18
    for (const std::string& arg : args) traced_value->AppendString(arg);
716
8
    traced_value->EndArray();
717
8
    traced_value->BeginArray("exec_args");
718
33
    for (const std::string& arg : exec_args) traced_value->AppendString(arg);
719
8
    traced_value->EndArray();
720

15
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(environment),
721
                                      "Environment",
722
                                      this,
723
                                      "args",
724
                                      std::move(traced_value));
725
  }
726
6307
}
727
728
787
Environment::Environment(IsolateData* isolate_data,
729
                         Local<Context> context,
730
                         const std::vector<std::string>& args,
731
                         const std::vector<std::string>& exec_args,
732
                         const EnvSerializeInfo* env_info,
733
                         EnvironmentFlags::Flags flags,
734
787
                         ThreadId thread_id)
735
    : Environment(isolate_data,
736
                  context->GetIsolate(),
737
                  args,
738
                  exec_args,
739
                  env_info,
740
                  flags,
741
787
                  thread_id) {
742
787
  InitializeMainContext(context, env_info);
743
787
}
744
745
6307
void Environment::InitializeMainContext(Local<Context> context,
746
                                        const EnvSerializeInfo* env_info) {
747
6307
  principal_realm_ = std::make_unique<Realm>(
748
6307
      this, context, MAYBE_FIELD_PTR(env_info, principal_realm));
749
6307
  AssignToContext(context, principal_realm_.get(), ContextInfo(""));
750
6307
  if (env_info != nullptr) {
751
5520
    DeserializeProperties(env_info);
752
  }
753
754
6307
  if (!options_->force_async_hooks_checks) {
755
1
    async_hooks_.no_force_checks();
756
  }
757
758
  // By default, always abort when --abort-on-uncaught-exception was passed.
759
6307
  should_abort_on_uncaught_toggle_[0] = 1;
760
761
  // The process is not exiting by default.
762
6307
  set_exiting(false);
763
764
6307
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
765
                           time_origin_);
766
6307
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
767
                           per_process::node_start_time);
768
769
6307
  if (per_process::v8_initialized) {
770
6263
    performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
771
                            performance::performance_v8_start);
772
  }
773
6307
}
774
775
22584
Environment::~Environment() {
776
  HandleScope handle_scope(isolate());
777
5646
  Local<Context> ctx = context();
778
779
5646
  if (Environment** interrupt_data = interrupt_data_.load()) {
780
    // There are pending RequestInterrupt() callbacks. Tell them not to run,
781
    // then force V8 to run interrupts by compiling and running an empty script
782
    // so as not to leak memory.
783
11
    *interrupt_data = nullptr;
784
785
22
    Isolate::AllowJavascriptExecutionScope allow_js_here(isolate());
786
22
    TryCatch try_catch(isolate());
787
11
    Context::Scope context_scope(ctx);
788
789
#ifdef DEBUG
790
    bool consistency_check = false;
791
    isolate()->RequestInterrupt([](Isolate*, void* data) {
792
      *static_cast<bool*>(data) = true;
793
    }, &consistency_check);
794
#endif
795
796
    Local<Script> script;
797
33
    if (Script::Compile(ctx, String::Empty(isolate())).ToLocal(&script))
798
11
      USE(script->Run(ctx));
799
800
    DCHECK(consistency_check);
801
  }
802
803
  // FreeEnvironment() should have set this.
804
5646
  CHECK(is_stopping());
805
806
5646
  if (heapsnapshot_near_heap_limit_callback_added_) {
807
    RemoveHeapSnapshotNearHeapLimitCallback(0);
808
  }
809
810
5646
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
811
      BuildEmbedderGraph, this);
812
813
#if HAVE_INSPECTOR
814
  // Destroy inspector agent before erasing the context. The inspector
815
  // destructor depends on the context still being accessible.
816
5646
  inspector_agent_.reset();
817
#endif
818
819
5646
  ctx->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
820
                                       nullptr);
821
5646
  ctx->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kRealm, nullptr);
822
823
5646
  if (trace_state_observer_) {
824
5646
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
825
5646
    CHECK_NOT_NULL(writer);
826
5646
    if (TracingController* tracing_controller = writer->GetTracingController())
827
5597
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
828
  }
829
830

10531
  TRACE_EVENT_NESTABLE_ASYNC_END0(
831
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
832
833
  // Do not unload addons on the main thread. Some addons need to retain memory
834
  // beyond the Environment's lifetime, and unloading them early would break
835
  // them; with Worker threads, we have the opportunity to be stricter.
836
  // Also, since the main thread usually stops just before the process exits,
837
  // this is far less relevant here.
838
5646
  if (!is_main_thread()) {
839
    // Dereference all addons that were loaded into this environment.
840
741
    for (binding::DLib& addon : loaded_addons_) {
841
14
      addon.Close();
842
    }
843
  }
844
845
5646
  CHECK_EQ(base_object_count_, 0);
846
5646
}
847
848
6269
void Environment::InitializeLibuv() {
849
12538
  HandleScope handle_scope(isolate());
850
6269
  Context::Scope context_scope(context());
851
852
6269
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
853
6269
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
854
855
6269
  CHECK_EQ(0, uv_check_init(event_loop(), immediate_check_handle()));
856
6269
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
857
858
6269
  CHECK_EQ(0, uv_idle_init(event_loop(), immediate_idle_handle()));
859
860
6269
  CHECK_EQ(0, uv_check_start(immediate_check_handle(), CheckImmediate));
861
862
  // Inform V8's CPU profiler when we're idle.  The profiler is sampling-based
863
  // but not all samples are created equal; mark the wall clock time spent in
864
  // epoll_wait() and friends so profiling tools can filter it out.  The samples
865
  // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
866
6269
  CHECK_EQ(0, uv_prepare_init(event_loop(), &idle_prepare_handle_));
867
6269
  CHECK_EQ(0, uv_check_init(event_loop(), &idle_check_handle_));
868
869
25467
  CHECK_EQ(0, uv_async_init(
870
      event_loop(),
871
      &task_queues_async_,
872
      [](uv_async_t* async) {
873
        Environment* env = ContainerOf(
874
            &Environment::task_queues_async_, async);
875
        HandleScope handle_scope(env->isolate());
876
        Context::Scope context_scope(env->context());
877
        env->RunAndClearNativeImmediates();
878
      }));
879
6269
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
880
6269
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
881
6269
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
882
883
  {
884
12538
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
885
6269
    task_queues_async_initialized_ = true;
886

12538
    if (native_immediates_threadsafe_.size() > 0 ||
887
6269
        native_immediates_interrupts_.size() > 0) {
888
5516
      uv_async_send(&task_queues_async_);
889
    }
890
  }
891
892
  // Register clean-up cb to be called to clean up the handles
893
  // when the environment is freed, note that they are not cleaned in
894
  // the one environment per process setup, but will be called in
895
  // FreeEnvironment.
896
6269
  RegisterHandleCleanups();
897
898
6269
  StartProfilerIdleNotifier();
899
6269
}
900
901
370
void Environment::ExitEnv() {
902
370
  set_can_call_into_js(false);
903
370
  set_stopping(true);
904
370
  isolate_->TerminateExecution();
905
740
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
906
370
}
907
908
6269
void Environment::RegisterHandleCleanups() {
909
6269
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
910
33648
                                        void* arg) {
911
33648
    handle->data = env;
912
913
33648
    env->CloseHandle(handle, [](uv_handle_t* handle) {
914
#ifdef DEBUG
915
      memset(handle, 0xab, uv_handle_size(handle->type));
916
#endif
917
33648
    });
918
33648
  };
919
920
37614
  auto register_handle = [&](uv_handle_t* handle) {
921
37614
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
922
43883
  };
923
6269
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
924
6269
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
925
6269
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
926
6269
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
927
6269
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
928
6269
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
929
6269
}
930
931
11282
void Environment::CleanupHandles() {
932
  {
933
11282
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
934
11282
    task_queues_async_initialized_ = false;
935
  }
936
937
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
938
22564
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
939
940
11282
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
941
942
11444
  for (ReqWrapBase* request : req_wrap_queue_)
943
162
    request->Cancel();
944
945
15874
  for (HandleWrap* handle : handle_wrap_queue_)
946
9184
    handle->Close();
947
948
44930
  for (HandleCleanup& hc : handle_cleanup_queue_)
949
33648
    hc.cb_(this, hc.handle_, hc.arg_);
950
11282
  handle_cleanup_queue_.clear();
951
952
10580
  while (handle_cleanup_waiting_ != 0 ||
953

33146
         request_waiting_ != 0 ||
954
11284
         !handle_wrap_queue_.IsEmpty()) {
955
10580
    uv_run(event_loop(), UV_RUN_ONCE);
956
  }
957
11282
}
958
959
6269
void Environment::StartProfilerIdleNotifier() {
960
6269
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
961
214482
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
962
214482
    env->isolate()->SetIdle(true);
963
214482
  });
964
6269
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
965
214193
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
966
214193
    env->isolate()->SetIdle(false);
967
214193
  });
968
6269
}
969
970
744655
void Environment::PrintSyncTrace() const {
971
744655
  if (!trace_sync_io_) return;
972
973
2
  HandleScope handle_scope(isolate());
974
975
1
  fprintf(
976
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
977
1
  PrintStackTrace(isolate(),
978
                  StackTrace::CurrentStackTrace(
979
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
980
}
981
982
5286
MaybeLocal<Value> Environment::RunSnapshotSerializeCallback() const {
983
5286
  EscapableHandleScope handle_scope(isolate());
984
10572
  if (!snapshot_serialize_callback().IsEmpty()) {
985
    Context::Scope context_scope(context());
986
    return handle_scope.EscapeMaybe(snapshot_serialize_callback()->Call(
987
        context(), v8::Undefined(isolate()), 0, nullptr));
988
  }
989
10572
  return handle_scope.Escape(Undefined(isolate()));
990
}
991
992
MaybeLocal<Value> Environment::RunSnapshotDeserializeMain() const {
993
  EscapableHandleScope handle_scope(isolate());
994
  if (!snapshot_deserialize_main().IsEmpty()) {
995
    Context::Scope context_scope(context());
996
    return handle_scope.EscapeMaybe(snapshot_deserialize_main()->Call(
997
        context(), v8::Undefined(isolate()), 0, nullptr));
998
  }
999
  return handle_scope.Escape(Undefined(isolate()));
1000
}
1001
1002
5646
void Environment::RunCleanup() {
1003
5646
  started_cleanup_ = true;
1004

16177
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunCleanup");
1005
5646
  bindings_.clear();
1006
5646
  CleanupHandles();
1007
1008

22576
  while (!cleanup_queue_.empty() || native_immediates_.size() > 0 ||
1009

22576
         native_immediates_threadsafe_.size() > 0 ||
1010
5646
         native_immediates_interrupts_.size() > 0) {
1011
5636
    cleanup_queue_.Drain();
1012
5636
    CleanupHandles();
1013
  }
1014
1015
5649
  for (const int fd : unmanaged_fds_) {
1016
    uv_fs_t close_req;
1017
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
1018
3
    uv_fs_req_cleanup(&close_req);
1019
  }
1020
5646
}
1021
1022
6380
void Environment::RunAtExitCallbacks() {
1023

18283
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "AtExit");
1024
18956
  for (ExitCallback at_exit : at_exit_functions_) {
1025
12576
    at_exit.cb_(at_exit.arg_);
1026
  }
1027
6380
  at_exit_functions_.clear();
1028
6380
}
1029
1030
12604
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
1031
12604
  at_exit_functions_.push_front(ExitCallback{cb, arg});
1032
12604
}
1033
1034
252959
void Environment::RunAndClearInterrupts() {
1035
252959
  while (native_immediates_interrupts_.size() > 0) {
1036
10677
    NativeImmediateQueue queue;
1037
    {
1038
21358
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1039
10679
      queue.ConcatMove(std::move(native_immediates_interrupts_));
1040
    }
1041
10679
    DebugSealHandleScope seal_handle_scope(isolate());
1042
1043
21367
    while (auto head = queue.Shift())
1044
21378
      head->Call(this);
1045
  }
1046
242280
}
1047
1048
231877
void Environment::RunAndClearNativeImmediates(bool only_refed) {
1049

468949
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment),
1050
               "RunAndClearNativeImmediates");
1051
463746
  HandleScope handle_scope(isolate_);
1052
  // In case the Isolate is no longer accessible just use an empty Local. This
1053
  // is not an issue for InternalCallbackScope as this case is already handled
1054
  // in its constructor but we avoid calls into v8 which can crash the process
1055
  // in debug builds.
1056
  Local<Object> obj =
1057
231877
      can_call_into_js() ? Object::New(isolate_) : Local<Object>();
1058
463746
  InternalCallbackScope cb_scope(this, obj, {0, 0});
1059
1060
231877
  size_t ref_count = 0;
1061
1062
  // Handle interrupts first. These functions are not allowed to throw
1063
  // exceptions, so we do not need to handle that.
1064
231877
  RunAndClearInterrupts();
1065
1066
463750
  auto drain_list = [&](NativeImmediateQueue* queue) {
1067
927493
    TryCatchScope try_catch(this);
1068
463750
    DebugSealHandleScope seal_handle_scope(isolate());
1069
524058
    while (auto head = queue->Shift()) {
1070
60316
      bool is_refed = head->flags() & CallbackFlags::kRefed;
1071
60316
      if (is_refed)
1072
35179
        ref_count++;
1073
1074

60316
      if (is_refed || !only_refed)
1075
60045
        head->Call(this);
1076
1077
60311
      head.reset();  // Destroy now so that this is also observed by try_catch.
1078
1079
60311
      if (UNLIKELY(try_catch.HasCaught())) {
1080

3
        if (!try_catch.HasTerminated() && can_call_into_js())
1081
3
          errors::TriggerUncaughtException(isolate(), try_catch);
1082
1083
1
        return true;
1084
      }
1085
60308
    }
1086
463742
    return false;
1087
231876
  };
1088
231876
  while (drain_list(&native_immediates_)) {}
1089
1090
231873
  immediate_info()->ref_count_dec(ref_count);
1091
1092
231873
  if (immediate_info()->ref_count() == 0)
1093
175598
    ToggleImmediateRef(false);
1094
1095
  // It is safe to check .size() first, because there is a causal relationship
1096
  // between pushes to the threadsafe immediate list and this function being
1097
  // called. For the common case, it's worth checking the size first before
1098
  // establishing a mutex lock.
1099
  // This is intentionally placed after the `ref_count` handling, because when
1100
  // refed threadsafe immediates are created, they are not counted towards the
1101
  // count in immediate_info() either.
1102
231869
  NativeImmediateQueue threadsafe_immediates;
1103
231873
  if (native_immediates_threadsafe_.size() > 0) {
1104
2184
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1105
1092
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
1106
  }
1107
231874
  while (drain_list(&threadsafe_immediates)) {}
1108
231869
}
1109
1110
10695
void Environment::RequestInterruptFromV8() {
1111
  // The Isolate may outlive the Environment, so some logic to handle the
1112
  // situation in which the Environment is destroyed before the handler runs
1113
  // is required.
1114
1115
  // We allocate a new pointer to a pointer to this Environment instance, and
1116
  // try to set it as interrupt_data_. If interrupt_data_ was already set, then
1117
  // callbacks are already scheduled to run and we can delete our own pointer
1118
  // and just return. If it was nullptr previously, the Environment** is stored;
1119
  // ~Environment sets the Environment* contained in it to nullptr, so that
1120
  // the callback can check whether ~Environment has already run and it is thus
1121
  // not safe to access the Environment instance itself.
1122
10695
  Environment** interrupt_data = new Environment*(this);
1123
10695
  Environment** dummy = nullptr;
1124
10695
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
1125
388
    delete interrupt_data;
1126
388
    return;  // Already scheduled.
1127
  }
1128
1129
10307
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
1130
10297
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
1131
10297
    Environment* env = *env_ptr;
1132
10297
    if (env == nullptr) {
1133
      // The Environment has already been destroyed. That should be okay; any
1134
      // callback added before the Environment shuts down would have been
1135
      // handled during cleanup.
1136
11
      return;
1137
    }
1138
10286
    env->interrupt_data_.store(nullptr);
1139
10286
    env->RunAndClearInterrupts();
1140
  }, interrupt_data);
1141
}
1142
1143
10825
void Environment::ScheduleTimer(int64_t duration_ms) {
1144
10825
  if (started_cleanup_) return;
1145
10825
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
1146
}
1147
1148
3954
void Environment::ToggleTimerRef(bool ref) {
1149
3954
  if (started_cleanup_) return;
1150
1151
3954
  if (ref) {
1152
2648
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1153
  } else {
1154
1306
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1155
  }
1156
}
1157
1158
8809
void Environment::RunTimers(uv_timer_t* handle) {
1159
8809
  Environment* env = Environment::from_timer_handle(handle);
1160

9325
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunTimers");
1161
1162
8809
  if (!env->can_call_into_js())
1163
    return;
1164
1165
8809
  HandleScope handle_scope(env->isolate());
1166
8809
  Context::Scope context_scope(env->context());
1167
1168
8809
  Local<Object> process = env->process_object();
1169
8809
  InternalCallbackScope scope(env, process, {0, 0});
1170
1171
8809
  Local<Function> cb = env->timers_callback_function();
1172
  MaybeLocal<Value> ret;
1173
8809
  Local<Value> arg = env->GetNow();
1174
  // This code will loop until all currently due timers will process. It is
1175
  // impossible for us to end up in an infinite loop due to how the JS-side
1176
  // is structured.
1177
33
  do {
1178
8842
    TryCatchScope try_catch(env);
1179
8842
    try_catch.SetVerbose(true);
1180
8842
    ret = cb->Call(env->context(), process, 1, &arg);
1181

8832
  } while (ret.IsEmpty() && env->can_call_into_js());
1182
1183
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
1184
  // is reset back to `true` after being previously set to `false` then this
1185
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
1186
  // timers corruption will occur and all timers behaviour will become
1187
  // entirely unpredictable.
1188
8799
  if (ret.IsEmpty())
1189
6
    return;
1190
1191
  // To allow for less JS-C++ boundary crossing, the value returned from JS
1192
  // serves a few purposes:
1193
  // 1. If it's 0, no more timers exist and the handle should be unrefed
1194
  // 2. If it's > 0, the value represents the next timer's expiry and there
1195
  //    is at least one timer remaining that is refed.
1196
  // 3. If it's < 0, the absolute value represents the next timer's expiry
1197
  //    and there are no timers that are refed.
1198
  int64_t expiry_ms =
1199
8793
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
1200
1201
8793
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
1202
1203
8793
  if (expiry_ms != 0) {
1204
    int64_t duration_ms =
1205
7634
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
1206
1207
7634
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
1208
1209
7634
    if (expiry_ms > 0)
1210
6954
      uv_ref(h);
1211
    else
1212
680
      uv_unref(h);
1213
  } else {
1214
1159
    uv_unref(h);
1215
  }
1216
}
1217
1218
1219
214193
void Environment::CheckImmediate(uv_check_t* handle) {
1220
214193
  Environment* env = Environment::from_immediate_check_handle(handle);
1221

217324
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "CheckImmediate");
1222
1223
214193
  HandleScope scope(env->isolate());
1224
214193
  Context::Scope context_scope(env->context());
1225
1226
214193
  env->RunAndClearNativeImmediates();
1227
1228

214193
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
1229
158498
    return;
1230
1231
952
  do {
1232
56635
    MakeCallback(env->isolate(),
1233
                 env->process_object(),
1234
                 env->immediate_callback_function(),
1235
                 0,
1236
                 nullptr,
1237
56647
                 {0, 0}).ToLocalChecked();
1238

56635
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
1239
1240
55683
  if (env->immediate_info()->ref_count() == 0)
1241
4701
    env->ToggleImmediateRef(false);
1242
}
1243
1244
259442
void Environment::ToggleImmediateRef(bool ref) {
1245
259442
  if (started_cleanup_) return;
1246
1247
248241
  if (ref) {
1248
    // Idle handle is needed only to stop the event loop from blocking in poll.
1249
79119
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
1250
  } else {
1251
169122
    uv_idle_stop(immediate_idle_handle());
1252
  }
1253
}
1254
1255
1256
50223
Local<Value> Environment::GetNow() {
1257
50223
  uv_update_time(event_loop());
1258
50223
  uint64_t now = uv_now(event_loop());
1259
50223
  CHECK_GE(now, timer_base());
1260
50223
  now -= timer_base();
1261
50223
  if (now <= 0xffffffff)
1262
100446
    return Integer::NewFromUnsigned(isolate(), static_cast<uint32_t>(now));
1263
  else
1264
    return Number::New(isolate(), static_cast<double>(now));
1265
}
1266
1267
28
void CollectExceptionInfo(Environment* env,
1268
                          Local<Object> obj,
1269
                          int errorno,
1270
                          const char* err_string,
1271
                          const char* syscall,
1272
                          const char* message,
1273
                          const char* path,
1274
                          const char* dest) {
1275
28
  obj->Set(env->context(),
1276
           env->errno_string(),
1277
112
           Integer::New(env->isolate(), errorno)).Check();
1278
1279
28
  obj->Set(env->context(), env->code_string(),
1280
84
           OneByteString(env->isolate(), err_string)).Check();
1281
1282
28
  if (message != nullptr) {
1283
28
    obj->Set(env->context(), env->message_string(),
1284
112
             OneByteString(env->isolate(), message)).Check();
1285
  }
1286
1287
  Local<Value> path_buffer;
1288
28
  if (path != nullptr) {
1289
    path_buffer =
1290
      Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked();
1291
    obj->Set(env->context(), env->path_string(), path_buffer).Check();
1292
  }
1293
1294
  Local<Value> dest_buffer;
1295
28
  if (dest != nullptr) {
1296
    dest_buffer =
1297
      Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked();
1298
    obj->Set(env->context(), env->dest_string(), dest_buffer).Check();
1299
  }
1300
1301
28
  if (syscall != nullptr) {
1302
28
    obj->Set(env->context(), env->syscall_string(),
1303
112
             OneByteString(env->isolate(), syscall)).Check();
1304
  }
1305
28
}
1306
1307
28
void Environment::CollectUVExceptionInfo(Local<Value> object,
1308
                                         int errorno,
1309
                                         const char* syscall,
1310
                                         const char* message,
1311
                                         const char* path,
1312
                                         const char* dest) {
1313

28
  if (!object->IsObject() || errorno == 0)
1314
    return;
1315
1316
28
  Local<Object> obj = object.As<Object>();
1317
28
  const char* err_string = uv_err_name(errorno);
1318
1319

28
  if (message == nullptr || message[0] == '\0') {
1320
28
    message = uv_strerror(errorno);
1321
  }
1322
1323
28
  node::CollectExceptionInfo(this, obj, errorno, err_string,
1324
                             syscall, message, path, dest);
1325
}
1326
1327
6307
ImmediateInfo::ImmediateInfo(Isolate* isolate, const SerializeInfo* info)
1328
6307
    : fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)) {}
1329
1330
6
ImmediateInfo::SerializeInfo ImmediateInfo::Serialize(
1331
    Local<Context> context, SnapshotCreator* creator) {
1332
6
  return {fields_.Serialize(context, creator)};
1333
}
1334
1335
5520
void ImmediateInfo::Deserialize(Local<Context> context) {
1336
5520
  fields_.Deserialize(context);
1337
5520
}
1338
1339
6
std::ostream& operator<<(std::ostream& output,
1340
                         const ImmediateInfo::SerializeInfo& i) {
1341
6
  output << "{ " << i.fields << " }";
1342
6
  return output;
1343
}
1344
1345
25
void ImmediateInfo::MemoryInfo(MemoryTracker* tracker) const {
1346
25
  tracker->TrackField("fields", fields_);
1347
25
}
1348
1349
6
TickInfo::SerializeInfo TickInfo::Serialize(Local<Context> context,
1350
                                            SnapshotCreator* creator) {
1351
6
  return {fields_.Serialize(context, creator)};
1352
}
1353
1354
5520
void TickInfo::Deserialize(Local<Context> context) {
1355
5520
  fields_.Deserialize(context);
1356
5520
}
1357
1358
6
std::ostream& operator<<(std::ostream& output,
1359
                         const TickInfo::SerializeInfo& i) {
1360
6
  output << "{ " << i.fields << " }";
1361
6
  return output;
1362
}
1363
1364
25
void TickInfo::MemoryInfo(MemoryTracker* tracker) const {
1365
25
  tracker->TrackField("fields", fields_);
1366
25
}
1367
1368
6307
TickInfo::TickInfo(Isolate* isolate, const SerializeInfo* info)
1369
    : fields_(
1370
6307
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1371
1372
6307
AsyncHooks::AsyncHooks(Isolate* isolate, const SerializeInfo* info)
1373
    : async_ids_stack_(isolate, 16 * 2, MAYBE_FIELD_PTR(info, async_ids_stack)),
1374
      fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)),
1375
      async_id_fields_(
1376
          isolate, kUidFieldsCount, MAYBE_FIELD_PTR(info, async_id_fields)),
1377

6307
      info_(info) {
1378
12614
  HandleScope handle_scope(isolate);
1379
6307
  if (info == nullptr) {
1380
787
    clear_async_id_stack();
1381
1382
    // Always perform async_hooks checks, not just when async_hooks is enabled.
1383
    // TODO(AndreasMadsen): Consider removing this for LTS releases.
1384
    // See discussion in https://github.com/nodejs/node/pull/15454
1385
    // When removing this, do it by reverting the commit. Otherwise the test
1386
    // and flag changes won't be included.
1387
787
    fields_[kCheck] = 1;
1388
1389
    // kDefaultTriggerAsyncId should be -1, this indicates that there is no
1390
    // specified default value and it should fallback to the executionAsyncId.
1391
    // 0 is not used as the magic value, because that indicates a missing
1392
    // context which is different from a default context.
1393
787
    async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
1394
1395
    // kAsyncIdCounter should start at 1 because that'll be the id the execution
1396
    // context during bootstrap (code that runs before entering uv_run()).
1397
787
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1398
  }
1399
6307
}
1400
1401
5520
void AsyncHooks::Deserialize(Local<Context> context) {
1402
5520
  async_ids_stack_.Deserialize(context);
1403
5520
  fields_.Deserialize(context);
1404
5520
  async_id_fields_.Deserialize(context);
1405
1406
  Local<Array> js_execution_async_resources;
1407
5520
  if (info_->js_execution_async_resources != 0) {
1408
    js_execution_async_resources =
1409
5520
        context->GetDataFromSnapshotOnce<Array>(
1410
16560
            info_->js_execution_async_resources).ToLocalChecked();
1411
  } else {
1412
    js_execution_async_resources = Array::New(context->GetIsolate());
1413
  }
1414
5520
  js_execution_async_resources_.Reset(
1415
      context->GetIsolate(), js_execution_async_resources);
1416
1417
  // The native_execution_async_resources_ field requires v8::Local<> instances
1418
  // for async calls whose resources were on the stack as JS objects when they
1419
  // were entered. We cannot recreate this here; however, storing these values
1420
  // on the JS equivalent gives the same result, so we do that instead.
1421
5520
  for (size_t i = 0; i < info_->native_execution_async_resources.size(); ++i) {
1422
    if (info_->native_execution_async_resources[i] == SIZE_MAX)
1423
      continue;
1424
    Local<Object> obj = context->GetDataFromSnapshotOnce<Object>(
1425
                                   info_->native_execution_async_resources[i])
1426
                               .ToLocalChecked();
1427
    js_execution_async_resources->Set(context, i, obj).Check();
1428
  }
1429
5520
  info_ = nullptr;
1430
5520
}
1431
1432
6
std::ostream& operator<<(std::ostream& output,
1433
                         const AsyncHooks::SerializeInfo& i) {
1434
  output << "{\n"
1435
6
         << "  " << i.async_ids_stack << ",  // async_ids_stack\n"
1436
6
         << "  " << i.fields << ",  // fields\n"
1437
6
         << "  " << i.async_id_fields << ",  // async_id_fields\n"
1438
6
         << "  " << i.js_execution_async_resources
1439
         << ",  // js_execution_async_resources\n"
1440
6
         << "  " << i.native_execution_async_resources
1441
         << ",  // native_execution_async_resources\n"
1442
6
         << "}";
1443
6
  return output;
1444
}
1445
1446
6
AsyncHooks::SerializeInfo AsyncHooks::Serialize(Local<Context> context,
1447
                                                SnapshotCreator* creator) {
1448
6
  SerializeInfo info;
1449
  // TODO(joyeecheung): some of these probably don't need to be serialized.
1450
6
  info.async_ids_stack = async_ids_stack_.Serialize(context, creator);
1451
6
  info.fields = fields_.Serialize(context, creator);
1452
6
  info.async_id_fields = async_id_fields_.Serialize(context, creator);
1453
6
  if (!js_execution_async_resources_.IsEmpty()) {
1454
6
    info.js_execution_async_resources = creator->AddData(
1455
        context, js_execution_async_resources_.Get(context->GetIsolate()));
1456
6
    CHECK_NE(info.js_execution_async_resources, 0);
1457
  } else {
1458
    info.js_execution_async_resources = 0;
1459
  }
1460
1461
6
  info.native_execution_async_resources.resize(
1462
      native_execution_async_resources_.size());
1463
6
  for (size_t i = 0; i < native_execution_async_resources_.size(); i++) {
1464
    info.native_execution_async_resources[i] =
1465
        native_execution_async_resources_[i].IsEmpty() ? SIZE_MAX :
1466
            creator->AddData(
1467
                context,
1468
                native_execution_async_resources_[i]);
1469
  }
1470
6
  CHECK_EQ(contexts_.size(), 1);
1471

12
  CHECK_EQ(contexts_[0], env()->context());
1472
6
  CHECK(js_promise_hooks_[0].IsEmpty());
1473
6
  CHECK(js_promise_hooks_[1].IsEmpty());
1474
6
  CHECK(js_promise_hooks_[2].IsEmpty());
1475
6
  CHECK(js_promise_hooks_[3].IsEmpty());
1476
1477
6
  return info;
1478
}
1479
1480
25
void AsyncHooks::MemoryInfo(MemoryTracker* tracker) const {
1481
25
  tracker->TrackField("async_ids_stack", async_ids_stack_);
1482
25
  tracker->TrackField("fields", fields_);
1483
25
  tracker->TrackField("async_id_fields", async_id_fields_);
1484
25
  tracker->TrackField("js_promise_hooks", js_promise_hooks_);
1485
25
}
1486
1487
4
void AsyncHooks::grow_async_ids_stack() {
1488
4
  async_ids_stack_.reserve(async_ids_stack_.Length() * 3);
1489
1490
4
  env()->async_hooks_binding()->Set(
1491
      env()->context(),
1492
      env()->async_ids_stack_string(),
1493
12
      async_ids_stack_.GetJSArray()).Check();
1494
4
}
1495
1496
4
void AsyncHooks::FailWithCorruptedAsyncStack(double expected_async_id) {
1497
4
  fprintf(stderr,
1498
          "Error: async hook stack has become corrupted ("
1499
          "actual: %.f, expected: %.f)\n",
1500
          async_id_fields_.GetValue(kExecutionAsyncId),
1501
          expected_async_id);
1502
4
  DumpBacktrace(stderr);
1503
4
  fflush(stderr);
1504
4
  if (!env()->abort_on_uncaught_exception())
1505
4
    exit(1);
1506
  fprintf(stderr, "\n");
1507
  fflush(stderr);
1508
  ABORT_NO_BACKTRACE();
1509
}
1510
1511
717
void Environment::Exit(int exit_code) {
1512
717
  if (options()->trace_exit) {
1513
4
    HandleScope handle_scope(isolate());
1514
    Isolate::DisallowJavascriptExecutionScope disallow_js(
1515
4
        isolate(), Isolate::DisallowJavascriptExecutionScope::CRASH_ON_FAILURE);
1516
1517
2
    if (is_main_thread()) {
1518
1
      fprintf(stderr, "(node:%d) ", uv_os_getpid());
1519
    } else {
1520
1
      fprintf(stderr, "(node:%d, thread:%" PRIu64 ") ",
1521
              uv_os_getpid(), thread_id());
1522
    }
1523
1524
2
    fprintf(
1525
        stderr, "WARNING: Exited the environment with code %d\n", exit_code);
1526
2
    PrintStackTrace(isolate(),
1527
                    StackTrace::CurrentStackTrace(
1528
                        isolate(), stack_trace_limit(), StackTrace::kDetailed));
1529
  }
1530
717
  process_exit_handler_(this, exit_code);
1531
63
}
1532
1533
6327
void Environment::stop_sub_worker_contexts() {
1534
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1535
1536
6327
  while (!sub_worker_contexts_.empty()) {
1537
27
    Worker* w = *sub_worker_contexts_.begin();
1538
27
    remove_sub_worker_context(w);
1539
27
    w->Exit(1);
1540
27
    w->JoinThread();
1541
  }
1542
6300
}
1543
1544
10
Environment* Environment::worker_parent_env() const {
1545
10
  if (worker_context() == nullptr) return nullptr;
1546
  return worker_context()->env();
1547
}
1548
1549
68134
void Environment::AddUnmanagedFd(int fd) {
1550
68134
  if (!tracks_unmanaged_fds()) return;
1551
2725
  auto result = unmanaged_fds_.insert(fd);
1552
2725
  if (!result.second) {
1553
    ProcessEmitWarning(
1554
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1555
  }
1556
}
1557
1558
67745
void Environment::RemoveUnmanagedFd(int fd) {
1559
67745
  if (!tracks_unmanaged_fds()) return;
1560
2722
  size_t removed_count = unmanaged_fds_.erase(fd);
1561
2722
  if (removed_count == 0) {
1562
    ProcessEmitWarning(
1563
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1564
  }
1565
}
1566
1567
5262
void Environment::PrintInfoForSnapshotIfDebug() {
1568
10524
  if (enabled_debug_list()->enabled(DebugCategory::MKSNAPSHOT)) {
1569
    fprintf(stderr, "BaseObjects at the exit of the Environment:\n");
1570
    PrintAllBaseObjects();
1571
    fprintf(stderr, "\nNative modules without cache:\n");
1572
    for (const auto& s : builtins_without_cache) {
1573
      fprintf(stderr, "%s\n", s.c_str());
1574
    }
1575
    fprintf(stderr, "\nNative modules with cache:\n");
1576
    for (const auto& s : builtins_with_cache) {
1577
      fprintf(stderr, "%s\n", s.c_str());
1578
    }
1579
    fprintf(stderr, "\nStatic bindings (need to be registered):\n");
1580
    for (const auto mod : internal_bindings) {
1581
      fprintf(stderr, "%s:%s\n", mod->nm_filename, mod->nm_modname);
1582
    }
1583
  }
1584
5262
}
1585
1586
void Environment::PrintAllBaseObjects() {
1587
  size_t i = 0;
1588
  std::cout << "BaseObjects\n";
1589
  ForEachBaseObject([&](BaseObject* obj) {
1590
    std::cout << "#" << i++ << " " << obj << ": " <<
1591
      obj->MemoryInfoName() << "\n";
1592
  });
1593
}
1594
1595
5262
void Environment::VerifyNoStrongBaseObjects() {
1596
  // When a process exits cleanly, i.e. because the event loop ends up without
1597
  // things to wait for, the Node.js objects that are left on the heap should
1598
  // be:
1599
  //
1600
  //   1. weak, i.e. ready for garbage collection once no longer referenced, or
1601
  //   2. detached, i.e. scheduled for destruction once no longer referenced, or
1602
  //   3. an unrefed libuv handle, i.e. does not keep the event loop alive, or
1603
  //   4. an inactive libuv handle (essentially the same here)
1604
  //
1605
  // There are a few exceptions to this rule, but generally, if there are
1606
  // C++-backed Node.js objects on the heap that do not fall into the above
1607
  // categories, we may be looking at a potential memory leak. Most likely,
1608
  // the cause is a missing MakeWeak() call on the corresponding object.
1609
  //
1610
  // In order to avoid this kind of problem, we check the list of BaseObjects
1611
  // for these criteria. Currently, we only do so when explicitly instructed to
1612
  // or when in debug mode (where --verify-base-objects is always-on).
1613
1614
5262
  if (!options()->verify_base_objects) return;
1615
1616
  ForEachBaseObject([](BaseObject* obj) {
1617
    if (obj->IsNotIndicativeOfMemoryLeakAtExit()) return;
1618
    fprintf(stderr, "Found bad BaseObject during clean exit: %s\n",
1619
            obj->MemoryInfoName().c_str());
1620
    fflush(stderr);
1621
    ABORT();
1622
  });
1623
}
1624
1625
6
EnvSerializeInfo Environment::Serialize(SnapshotCreator* creator) {
1626
6
  EnvSerializeInfo info;
1627
6
  Local<Context> ctx = context();
1628
1629
  // Currently all modules are compiled without cache in builtin snapshot
1630
  // builder.
1631
12
  info.builtins = std::vector<std::string>(builtins_without_cache.begin(),
1632
6
                                           builtins_without_cache.end());
1633
1634
6
  info.async_hooks = async_hooks_.Serialize(ctx, creator);
1635
6
  info.immediate_info = immediate_info_.Serialize(ctx, creator);
1636
6
  info.tick_info = tick_info_.Serialize(ctx, creator);
1637
6
  info.performance_state = performance_state_->Serialize(ctx, creator);
1638
6
  info.exiting = exiting_.Serialize(ctx, creator);
1639
6
  info.stream_base_state = stream_base_state_.Serialize(ctx, creator);
1640
6
  info.should_abort_on_uncaught_toggle =
1641
6
      should_abort_on_uncaught_toggle_.Serialize(ctx, creator);
1642
1643
  // Do this after other creator->AddData() calls so that Snapshotable objects
1644
  // can use 0 to indicate that a SnapshotIndex is invalid.
1645
6
  SerializeSnapshotableObjects(this, creator, &info);
1646
1647
6
  info.principal_realm = principal_realm_->Serialize(creator);
1648
6
  return info;
1649
}
1650
1651
22080
void Environment::EnqueueDeserializeRequest(DeserializeRequestCallback cb,
1652
                                            Local<Object> holder,
1653
                                            int index,
1654
                                            InternalFieldInfoBase* info) {
1655
  DCHECK_EQ(index, BaseObject::kEmbedderType);
1656
44160
  DeserializeRequest request{cb, {isolate(), holder}, index, info};
1657
22080
  deserialize_requests_.push_back(std::move(request));
1658
22080
}
1659
1660
5520
void Environment::RunDeserializeRequests() {
1661
11040
  HandleScope scope(isolate());
1662
5520
  Local<Context> ctx = context();
1663
5520
  Isolate* is = isolate();
1664
27600
  while (!deserialize_requests_.empty()) {
1665
44160
    DeserializeRequest request(std::move(deserialize_requests_.front()));
1666
22080
    deserialize_requests_.pop_front();
1667
22080
    Local<Object> holder = request.holder.Get(is);
1668
22080
    request.cb(ctx, holder, request.index, request.info);
1669
    request.holder.Reset();
1670
22080
    request.info->Delete();
1671
  }
1672
5520
}
1673
1674
5520
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1675
5520
  Local<Context> ctx = context();
1676
1677
5520
  RunDeserializeRequests();
1678
1679
5520
  builtins_in_snapshot = info->builtins;
1680
5520
  async_hooks_.Deserialize(ctx);
1681
5520
  immediate_info_.Deserialize(ctx);
1682
5520
  tick_info_.Deserialize(ctx);
1683
5520
  performance_state_->Deserialize(ctx);
1684
5520
  exiting_.Deserialize(ctx);
1685
5520
  stream_base_state_.Deserialize(ctx);
1686
5520
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1687
1688
5520
  principal_realm_->DeserializeProperties(&info->principal_realm);
1689
1690
5520
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1691
    fprintf(stderr, "deserializing...\n");
1692
    std::cerr << *info << "\n";
1693
  }
1694
5520
}
1695
1696
4
uint64_t GuessMemoryAvailableToTheProcess() {
1697
4
  uint64_t free_in_system = uv_get_free_memory();
1698
4
  size_t allowed = uv_get_constrained_memory();
1699
4
  if (allowed == 0) {
1700
    return free_in_system;
1701
  }
1702
  size_t rss;
1703
4
  int err = uv_resident_set_memory(&rss);
1704
4
  if (err) {
1705
    return free_in_system;
1706
  }
1707
4
  if (allowed < rss) {
1708
    // Something is probably wrong. Fallback to the free memory.
1709
    return free_in_system;
1710
  }
1711
  // There may still be room for swap, but we will just leave it here.
1712
4
  return allowed - rss;
1713
}
1714
1715
25
void Environment::BuildEmbedderGraph(Isolate* isolate,
1716
                                     EmbedderGraph* graph,
1717
                                     void* data) {
1718
50
  MemoryTracker tracker(isolate, graph);
1719
25
  Environment* env = static_cast<Environment*>(data);
1720
25
  tracker.Track(env);
1721
25
}
1722
1723
4
size_t Environment::NearHeapLimitCallback(void* data,
1724
                                          size_t current_heap_limit,
1725
                                          size_t initial_heap_limit) {
1726
4
  Environment* env = static_cast<Environment*>(data);
1727
1728
  Debug(env,
1729
        DebugCategory::DIAGNOSTICS,
1730
        "Invoked NearHeapLimitCallback, processing=%d, "
1731
        "current_limit=%" PRIu64 ", "
1732
        "initial_limit=%" PRIu64 "\n",
1733
4
        env->is_in_heapsnapshot_heap_limit_callback_,
1734
8
        static_cast<uint64_t>(current_heap_limit),
1735
4
        static_cast<uint64_t>(initial_heap_limit));
1736
1737
4
  size_t max_young_gen_size = env->isolate_data()->max_young_gen_size;
1738
4
  size_t young_gen_size = 0;
1739
4
  size_t old_gen_size = 0;
1740
1741
4
  HeapSpaceStatistics stats;
1742
4
  size_t num_heap_spaces = env->isolate()->NumberOfHeapSpaces();
1743
36
  for (size_t i = 0; i < num_heap_spaces; ++i) {
1744
32
    env->isolate()->GetHeapSpaceStatistics(&stats, i);
1745

60
    if (strcmp(stats.space_name(), "new_space") == 0 ||
1746
28
        strcmp(stats.space_name(), "new_large_object_space") == 0) {
1747
8
      young_gen_size += stats.space_used_size();
1748
    } else {
1749
24
      old_gen_size += stats.space_used_size();
1750
    }
1751
  }
1752
1753
  Debug(env,
1754
        DebugCategory::DIAGNOSTICS,
1755
        "max_young_gen_size=%" PRIu64 ", "
1756
        "young_gen_size=%" PRIu64 ", "
1757
        "old_gen_size=%" PRIu64 ", "
1758
        "total_size=%" PRIu64 "\n",
1759
8
        static_cast<uint64_t>(max_young_gen_size),
1760
8
        static_cast<uint64_t>(young_gen_size),
1761
8
        static_cast<uint64_t>(old_gen_size),
1762
4
        static_cast<uint64_t>(young_gen_size + old_gen_size));
1763
1764
4
  uint64_t available = GuessMemoryAvailableToTheProcess();
1765
  // TODO(joyeecheung): get a better estimate about the native memory
1766
  // usage into the overhead, e.g. based on the count of objects.
1767
4
  uint64_t estimated_overhead = max_young_gen_size;
1768
  Debug(env,
1769
        DebugCategory::DIAGNOSTICS,
1770
        "Estimated available memory=%" PRIu64 ", "
1771
        "estimated overhead=%" PRIu64 "\n",
1772
8
        static_cast<uint64_t>(available),
1773
4
        static_cast<uint64_t>(estimated_overhead));
1774
1775
  // This might be hit when the snapshot is being taken in another
1776
  // NearHeapLimitCallback invocation.
1777
  // When taking the snapshot, objects in the young generation may be
1778
  // promoted to the old generation, result in increased heap usage,
1779
  // but it should be no more than the young generation size.
1780
  // Ideally, this should be as small as possible - the heap limit
1781
  // can only be restored when the heap usage falls down below the
1782
  // new limit, so in a heap with unbounded growth the isolate
1783
  // may eventually crash with this new limit - effectively raising
1784
  // the heap limit to the new one.
1785
4
  size_t new_limit = current_heap_limit + max_young_gen_size;
1786
4
  if (env->is_in_heapsnapshot_heap_limit_callback_) {
1787
    Debug(env,
1788
          DebugCategory::DIAGNOSTICS,
1789
          "Not generating snapshots in nested callback. "
1790
          "new_limit=%" PRIu64 "\n",
1791
2
          static_cast<uint64_t>(new_limit));
1792
2
    return new_limit;
1793
  }
1794
1795
  // Estimate whether the snapshot is going to use up all the memory
1796
  // available to the process. If so, just give up to prevent the system
1797
  // from killing the process for a system OOM.
1798
2
  if (estimated_overhead > available) {
1799
    Debug(env,
1800
          DebugCategory::DIAGNOSTICS,
1801
          "Not generating snapshots because it's too risky.\n");
1802
    env->RemoveHeapSnapshotNearHeapLimitCallback(0);
1803
    // The new limit must be higher than current_heap_limit or V8 might
1804
    // crash.
1805
    return new_limit;
1806
  }
1807
1808
  // Take the snapshot synchronously.
1809
2
  env->is_in_heapsnapshot_heap_limit_callback_ = true;
1810
1811
4
  std::string dir = env->options()->diagnostic_dir;
1812
2
  if (dir.empty()) {
1813
2
    dir = env->GetCwd();
1814
  }
1815
4
  DiagnosticFilename name(env, "Heap", "heapsnapshot");
1816
2
  std::string filename = dir + kPathSeparator + (*name);
1817
1818
2
  Debug(env, DebugCategory::DIAGNOSTICS, "Start generating %s...\n", *name);
1819
1820
2
  heap::WriteSnapshot(env, filename.c_str());
1821
2
  env->heap_limit_snapshot_taken_ += 1;
1822
1823
  Debug(env,
1824
        DebugCategory::DIAGNOSTICS,
1825
        "%" PRIu32 "/%" PRIu32 " snapshots taken.\n",
1826
2
        env->heap_limit_snapshot_taken_,
1827
2
        env->heap_snapshot_near_heap_limit_);
1828
1829
  // Don't take more snapshots than the limit specified.
1830
2
  if (env->heap_limit_snapshot_taken_ == env->heap_snapshot_near_heap_limit_) {
1831
    Debug(env,
1832
          DebugCategory::DIAGNOSTICS,
1833
          "Removing the near heap limit callback");
1834
2
    env->RemoveHeapSnapshotNearHeapLimitCallback(0);
1835
  }
1836
1837
2
  FPrintF(stderr, "Wrote snapshot to %s\n", filename.c_str());
1838
  // Tell V8 to reset the heap limit once the heap usage falls down to
1839
  // 95% of the initial limit.
1840
2
  env->isolate()->AutomaticallyRestoreInitialHeapLimit(0.95);
1841
1842
2
  env->is_in_heapsnapshot_heap_limit_callback_ = false;
1843
1844
  // The new limit must be higher than current_heap_limit or V8 might
1845
  // crash.
1846
2
  return new_limit;
1847
}
1848
1849
25
inline size_t Environment::SelfSize() const {
1850
25
  size_t size = sizeof(*this);
1851
  // Remove non pointer fields that will be tracked in MemoryInfo()
1852
  // TODO(joyeecheung): refactor the MemoryTracker interface so
1853
  // this can be done for common types within the Track* calls automatically
1854
  // if a certain scope is entered.
1855
25
  size -= sizeof(async_hooks_);
1856
25
  size -= sizeof(cleanup_queue_);
1857
25
  size -= sizeof(tick_info_);
1858
25
  size -= sizeof(immediate_info_);
1859
25
  return size;
1860
}
1861
1862
25
void Environment::MemoryInfo(MemoryTracker* tracker) const {
1863
  // Iteratable STLs have their own sizes subtracted from the parent
1864
  // by default.
1865
25
  tracker->TrackField("isolate_data", isolate_data_);
1866
25
  tracker->TrackField("builtins_with_cache", builtins_with_cache);
1867
25
  tracker->TrackField("builtins_without_cache", builtins_without_cache);
1868
25
  tracker->TrackField("destroy_async_id_list", destroy_async_id_list_);
1869
25
  tracker->TrackField("exec_argv", exec_argv_);
1870
25
  tracker->TrackField("exiting", exiting_);
1871
25
  tracker->TrackField("should_abort_on_uncaught_toggle",
1872
25
                      should_abort_on_uncaught_toggle_);
1873
25
  tracker->TrackField("stream_base_state", stream_base_state_);
1874
25
  tracker->TrackField("cleanup_queue", cleanup_queue_);
1875
25
  tracker->TrackField("async_hooks", async_hooks_);
1876
25
  tracker->TrackField("immediate_info", immediate_info_);
1877
25
  tracker->TrackField("tick_info", tick_info_);
1878
25
  tracker->TrackField("principal_realm", principal_realm_);
1879
1880
  // FIXME(joyeecheung): track other fields in Environment.
1881
  // Currently MemoryTracker is unable to track these
1882
  // correctly:
1883
  // - Internal types that do not implement MemoryRetainer yet
1884
  // - STL containers with MemoryRetainer* inside
1885
  // - STL containers with numeric types inside that should not have their
1886
  //   nodes elided e.g. numeric keys in maps.
1887
  // We also need to make sure that when we add a non-pointer field as its own
1888
  // node, we shift its sizeof() size out of the Environment node.
1889
25
}
1890
1891
769373
void Environment::RunWeakRefCleanup() {
1892
769373
  isolate()->ClearKeptObjects();
1893
769373
}
1894
1895
// Not really any better place than env.cc at this moment.
1896
1462161
BaseObject::BaseObject(Environment* env, Local<Object> object)
1897
2924322
    : persistent_handle_(env->isolate(), object), env_(env) {
1898
1462161
  CHECK_EQ(false, object.IsEmpty());
1899
1462161
  CHECK_GE(object->InternalFieldCount(), BaseObject::kInternalFieldCount);
1900
1462161
  object->SetAlignedPointerInInternalField(BaseObject::kEmbedderType,
1901
                                           &kNodeEmbedderId);
1902
1462161
  object->SetAlignedPointerInInternalField(BaseObject::kSlot,
1903
                                           static_cast<void*>(this));
1904
1462161
  env->AddCleanupHook(DeleteMe, static_cast<void*>(this));
1905
1462161
  env->modify_base_object_count(1);
1906
1462161
}
1907
1908

7941420
BaseObject::~BaseObject() {
1909
2893546
  env()->modify_base_object_count(-1);
1910
2893546
  env()->RemoveCleanupHook(DeleteMe, static_cast<void*>(this));
1911
1912
2893546
  if (UNLIKELY(has_pointer_data())) {
1913
392722
    PointerData* metadata = pointer_data();
1914
392722
    CHECK_EQ(metadata->strong_ptr_count, 0);
1915
392722
    metadata->self = nullptr;
1916
392722
    if (metadata->weak_ptr_count == 0) delete metadata;
1917
  }
1918
1919
2893546
  if (persistent_handle_.IsEmpty()) {
1920
    // This most likely happened because the weak callback below cleared it.
1921
2154328
    return;
1922
  }
1923
1924
  {
1925
739218
    HandleScope handle_scope(env()->isolate());
1926
1478436
    object()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
1927
  }
1928
}
1929
1930
1325426
void BaseObject::MakeWeak() {
1931
1325426
  if (has_pointer_data()) {
1932
42718
    pointer_data()->wants_weak_jsobj = true;
1933
42718
    if (pointer_data()->strong_ptr_count > 0) return;
1934
  }
1935
1936
2650850
  persistent_handle_.SetWeak(
1937
      this,
1938
1077163
      [](const WeakCallbackInfo<BaseObject>& data) {
1939
1077163
        BaseObject* obj = data.GetParameter();
1940
        // Clear the persistent handle so that ~BaseObject() doesn't attempt
1941
        // to mess with internal fields, since the JS object may have
1942
        // transitioned into an invalid state.
1943
        // Refs: https://github.com/nodejs/node/issues/18897
1944
1077163
        obj->persistent_handle_.Reset();
1945

1077163
        CHECK_IMPLIES(obj->has_pointer_data(),
1946
                      obj->pointer_data()->strong_ptr_count == 0);
1947
1077163
        obj->OnGCCollect();
1948
1077163
      },
1949
      WeakCallbackType::kParameter);
1950
}
1951
1952
// This just has to be different from the Chromium ones:
1953
// https://source.chromium.org/chromium/chromium/src/+/main:gin/public/gin_embedders.h;l=18-23;drc=5a758a97032f0b656c3c36a3497560762495501a
1954
// Otherwise, when Node is loaded in an isolate which uses cppgc, cppgc will
1955
// misinterpret the data stored in the embedder fields and try to garbage
1956
// collect them.
1957
uint16_t kNodeEmbedderId = 0x90de;
1958
1959
23729
void BaseObject::LazilyInitializedJSTemplateConstructor(
1960
    const FunctionCallbackInfo<Value>& args) {
1961
  DCHECK(args.IsConstructCall());
1962
23729
  CHECK_GE(args.This()->InternalFieldCount(), BaseObject::kInternalFieldCount);
1963
23729
  args.This()->SetAlignedPointerInInternalField(BaseObject::kEmbedderType,
1964
                                                &kNodeEmbedderId);
1965
23729
  args.This()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
1966
23729
}
1967
1968
21845
Local<FunctionTemplate> BaseObject::MakeLazilyInitializedJSTemplate(
1969
    Environment* env) {
1970
  Local<FunctionTemplate> t = NewFunctionTemplate(
1971
21845
      env->isolate(), LazilyInitializedJSTemplateConstructor);
1972
21845
  t->Inherit(BaseObject::GetConstructorTemplate(env));
1973
43690
  t->InstanceTemplate()->SetInternalFieldCount(BaseObject::kInternalFieldCount);
1974
21845
  return t;
1975
}
1976
1977
3354384
BaseObject::PointerData* BaseObject::pointer_data() {
1978
3354384
  if (!has_pointer_data()) {
1979
199156
    PointerData* metadata = new PointerData();
1980
199156
    metadata->wants_weak_jsobj = persistent_handle_.IsWeak();
1981
199156
    metadata->self = this;
1982
199156
    pointer_data_ = metadata;
1983
  }
1984
3354384
  CHECK(has_pointer_data());
1985
3354384
  return pointer_data_;
1986
}
1987
1988
836451
void BaseObject::decrease_refcount() {
1989
836451
  CHECK(has_pointer_data());
1990
836451
  PointerData* metadata = pointer_data();
1991
836451
  CHECK_GT(metadata->strong_ptr_count, 0);
1992
836451
  unsigned int new_refcount = --metadata->strong_ptr_count;
1993
836451
  if (new_refcount == 0) {
1994
263745
    if (metadata->is_detached) {
1995
190402
      OnGCCollect();
1996

73343
    } else if (metadata->wants_weak_jsobj && !persistent_handle_.IsEmpty()) {
1997
42717
      MakeWeak();
1998
    }
1999
  }
2000
836451
}
2001
2002
839398
void BaseObject::increase_refcount() {
2003
839398
  unsigned int prev_refcount = pointer_data()->strong_ptr_count++;
2004

839398
  if (prev_refcount == 0 && !persistent_handle_.IsEmpty())
2005
266525
    persistent_handle_.ClearWeak();
2006
839398
}
2007
2008
170156
void BaseObject::DeleteMe(void* data) {
2009
170156
  BaseObject* self = static_cast<BaseObject*>(data);
2010

175192
  if (self->has_pointer_data() &&
2011
5036
      self->pointer_data()->strong_ptr_count > 0) {
2012
905
    return self->Detach();
2013
  }
2014
169251
  delete self;
2015
}
2016
2017
589
bool BaseObject::IsDoneInitializing() const { return true; }
2018
2019
649
Local<Object> BaseObject::WrappedObject() const {
2020
649
  return object();
2021
}
2022
2023
1298
bool BaseObject::IsRootNode() const {
2024
2596
  return !persistent_handle_.IsWeak();
2025
}
2026
2027
56411
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(
2028
    IsolateData* isolate_data) {
2029
56411
  Local<FunctionTemplate> tmpl = isolate_data->base_object_ctor_template();
2030
56411
  if (tmpl.IsEmpty()) {
2031
794
    tmpl = NewFunctionTemplate(isolate_data->isolate(), nullptr);
2032
794
    tmpl->SetClassName(
2033
        FIXED_ONE_BYTE_STRING(isolate_data->isolate(), "BaseObject"));
2034
794
    isolate_data->set_base_object_ctor_template(tmpl);
2035
  }
2036
56411
  return tmpl;
2037
}
2038
2039
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
2040
  return IsWeakOrDetached();
2041
}
2042
2043
}  // namespace node