GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.cc Lines: 979 1064 92.0 %
Date: 2022-08-31 04:20:31 Branches: 1146 2114 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_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
16221
void AsyncHooks::SetJSPromiseHooks(Local<Function> init,
70
                                   Local<Function> before,
71
                                   Local<Function> after,
72
                                   Local<Function> resolve) {
73
16221
  js_promise_hooks_[0].Reset(env()->isolate(), init);
74
16221
  js_promise_hooks_[1].Reset(env()->isolate(), before);
75
16221
  js_promise_hooks_[2].Reset(env()->isolate(), after);
76
16221
  js_promise_hooks_[3].Reset(env()->isolate(), resolve);
77
32787
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
78
16566
    if (it->IsEmpty()) {
79
      contexts_.erase(it--);
80
      continue;
81
    }
82
33132
    PersistentToLocal::Weak(env()->isolate(), *it)
83
16566
        ->SetPromiseHooks(init, before, after, resolve);
84
  }
85
16221
}
86
87
// Remember to keep this code aligned with pushAsyncContext() in JS.
88
809115
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
809115
  if (fields_[kCheck] > 0) {
94
809111
    CHECK_GE(async_id, -1);
95
809111
    CHECK_GE(trigger_async_id, -1);
96
  }
97
98
809115
  uint32_t offset = fields_[kStackLength];
99
809115
  if (offset * 2 >= async_ids_stack_.Length()) grow_async_ids_stack();
100
809115
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
101
809115
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
102
809115
  fields_[kStackLength] += 1;
103
809115
  async_id_fields_[kExecutionAsyncId] = async_id;
104
809115
  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
809115
  if (!resource.IsEmpty()) {
114
809111
    native_execution_async_resources_.resize(offset + 1);
115
    // Caveat: This is a v8::Local<> assignment, we do not keep a v8::Global<>!
116
809111
    native_execution_async_resources_[offset] = resource;
117
  }
118
809115
}
119
120
// Remember to keep this code aligned with popAsyncContext() in JS.
121
808726
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
808726
  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
1615336
  if (UNLIKELY(fields_[kCheck] > 0 &&
129

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

1615332
             !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
807666
    native_execution_async_resources_.resize(offset);
147
807666
    if (native_execution_async_resources_.size() <
148

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


















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




102885
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
341






135375
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
342










































































































































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










































































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

154
  if (!env_->owns_process_state() || !env_->can_call_into_js()) {
493
    // Ideally, we’d have a consistent story that treats all threads/Environment
494
    // instances equally here. However, tracing is essentially global, and this
495
    // callback is called from whichever thread calls `StartTracing()` or
496
    // `StopTracing()`. The only way to do this in a threadsafe fashion
497
    // seems to be only tracking this from the main thread, and only allowing
498
    // these state modifications from the main thread.
499
96
    return;
500
  }
501
502
143
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
503
143
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
504
505
143
  Isolate* isolate = env_->isolate();
506
143
  HandleScope handle_scope(isolate);
507
143
  Local<Function> cb = env_->trace_category_state_function();
508
143
  if (cb.IsEmpty())
509
85
    return;
510
58
  TryCatchScope try_catch(env_);
511
58
  try_catch.SetVerbose(true);
512
116
  Local<Value> args[] = {Boolean::New(isolate, async_hooks_enabled)};
513
116
  USE(cb->Call(env_->context(), Undefined(isolate), arraysize(args), args));
514
}
515
516
6823
void Environment::AssignToContext(Local<v8::Context> context,
517
                                  const ContextInfo& info) {
518
6823
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
519
                                           this);
520
  // Used to retrieve bindings
521
13646
  context->SetAlignedPointerInEmbedderData(
522
6823
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
523
524
  // ContextifyContexts will update this to a pointer to the native object.
525
6823
  context->SetAlignedPointerInEmbedderData(
526
      ContextEmbedderIndex::kContextifyContext, nullptr);
527
528
  // This must not be done before other context fields are initialized.
529
6823
  ContextEmbedderTag::TagNodeContext(context);
530
531
#if HAVE_INSPECTOR
532
6823
  inspector_agent()->ContextCreated(context, info);
533
#endif  // HAVE_INSPECTOR
534
535
6823
  this->async_hooks()->AddContext(context);
536
6823
}
537
538
183
void Environment::TryLoadAddon(
539
    const char* filename,
540
    int flags,
541
    const std::function<bool(binding::DLib*)>& was_loaded) {
542
183
  loaded_addons_.emplace_back(filename, flags);
543
183
  if (!was_loaded(&loaded_addons_.back())) {
544
10
    loaded_addons_.pop_back();
545
  }
546
183
}
547
548
11
std::string Environment::GetCwd() {
549
  char cwd[PATH_MAX_BYTES];
550
11
  size_t size = PATH_MAX_BYTES;
551
11
  const int err = uv_cwd(cwd, &size);
552
553
11
  if (err == 0) {
554
11
    CHECK_GT(size, 0);
555
11
    return cwd;
556
  }
557
558
  // This can fail if the cwd is deleted. In that case, fall back to
559
  // exec_path.
560
  const std::string& exec_path = exec_path_;
561
  return exec_path.substr(0, exec_path.find_last_of(kPathSeparator));
562
}
563
564
1901
void Environment::add_refs(int64_t diff) {
565
1901
  task_queues_async_refs_ += diff;
566
1901
  CHECK_GE(task_queues_async_refs_, 0);
567
1901
  if (task_queues_async_refs_ == 0)
568
420
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
569
  else
570
1481
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
571
1901
}
572
573
65384
uv_buf_t Environment::allocate_managed_buffer(const size_t suggested_size) {
574
130768
  NoArrayBufferZeroFillScope no_zero_fill_scope(isolate_data());
575
  std::unique_ptr<v8::BackingStore> bs =
576
65384
      v8::ArrayBuffer::NewBackingStore(isolate(), suggested_size);
577
65384
  uv_buf_t buf = uv_buf_init(static_cast<char*>(bs->Data()), bs->ByteLength());
578
65384
  released_allocated_buffers_.emplace(buf.base, std::move(bs));
579
65384
  return buf;
580
}
581
582
80345
std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer(
583
    const uv_buf_t& buf) {
584
80345
  std::unique_ptr<v8::BackingStore> bs;
585
80345
  if (buf.base != nullptr) {
586
65384
    auto it = released_allocated_buffers_.find(buf.base);
587
65384
    CHECK_NE(it, released_allocated_buffers_.end());
588
65384
    bs = std::move(it->second);
589
65384
    released_allocated_buffers_.erase(it);
590
  }
591
80345
  return bs;
592
}
593
594
779
void Environment::CreateProperties() {
595
1558
  HandleScope handle_scope(isolate_);
596
779
  Local<Context> ctx = context();
597
598
  {
599
779
    Context::Scope context_scope(ctx);
600
779
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
601
1558
    templ->InstanceTemplate()->SetInternalFieldCount(
602
        BaseObject::kInternalFieldCount);
603
779
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
604
605
779
    set_binding_data_ctor_template(templ);
606
  }
607
608
  // Store primordials setup by the per-context script in the environment.
609
  Local<Object> per_context_bindings =
610
1558
      GetPerContextExports(ctx).ToLocalChecked();
611
  Local<Value> primordials =
612
2337
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
613
779
  CHECK(primordials->IsObject());
614
779
  set_primordials(primordials.As<Object>());
615
616
  Local<String> prototype_string =
617
779
      FIXED_ONE_BYTE_STRING(isolate(), "prototype");
618
619
#define V(EnvPropertyName, PrimordialsPropertyName)                            \
620
  {                                                                            \
621
    Local<Value> ctor =                                                        \
622
        primordials.As<Object>()                                               \
623
            ->Get(ctx,                                                         \
624
                  FIXED_ONE_BYTE_STRING(isolate(), PrimordialsPropertyName))   \
625
            .ToLocalChecked();                                                 \
626
    CHECK(ctor->IsObject());                                                   \
627
    Local<Value> prototype =                                                   \
628
        ctor.As<Object>()->Get(ctx, prototype_string).ToLocalChecked();        \
629
    CHECK(prototype->IsObject());                                              \
630
    set_##EnvPropertyName(prototype.As<Object>());                             \
631
  }
632
633

4674
  V(primordials_safe_map_prototype_object, "SafeMap");
634

4674
  V(primordials_safe_set_prototype_object, "SafeSet");
635

4674
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
636

4674
  V(primordials_safe_weak_set_prototype_object, "SafeWeakSet");
637
#undef V
638
639
  Local<Object> process_object =
640
779
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
641
779
  set_process_object(process_object);
642
779
}
643
644
6194
std::string GetExecPath(const std::vector<std::string>& argv) {
645
  char exec_path_buf[2 * PATH_MAX];
646
6194
  size_t exec_path_len = sizeof(exec_path_buf);
647
6194
  std::string exec_path;
648
6194
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
649
6194
    exec_path = std::string(exec_path_buf, exec_path_len);
650
  } else {
651
    exec_path = argv[0];
652
  }
653
654
  // On OpenBSD process.execPath will be relative unless we
655
  // get the full path before process.execPath is used.
656
#if defined(__OpenBSD__)
657
  uv_fs_t req;
658
  req.ptr = nullptr;
659
  if (0 ==
660
      uv_fs_realpath(nullptr, &req, exec_path.c_str(), nullptr)) {
661
    CHECK_NOT_NULL(req.ptr);
662
    exec_path = std::string(static_cast<char*>(req.ptr));
663
  }
664
  uv_fs_req_cleanup(&req);
665
#endif
666
667
6194
  return exec_path;
668
}
669
670
6194
Environment::Environment(IsolateData* isolate_data,
671
                         Isolate* isolate,
672
                         const std::vector<std::string>& args,
673
                         const std::vector<std::string>& exec_args,
674
                         const EnvSerializeInfo* env_info,
675
                         EnvironmentFlags::Flags flags,
676
6194
                         ThreadId thread_id)
677
    : isolate_(isolate),
678
      isolate_data_(isolate_data),
679
      async_hooks_(isolate, MAYBE_FIELD_PTR(env_info, async_hooks)),
680
      immediate_info_(isolate, MAYBE_FIELD_PTR(env_info, immediate_info)),
681
      tick_info_(isolate, MAYBE_FIELD_PTR(env_info, tick_info)),
682
6194
      timer_base_(uv_now(isolate_data->event_loop())),
683
      exec_argv_(exec_args),
684
      argv_(args),
685
      exec_path_(GetExecPath(args)),
686
6194
      exiting_(isolate_, 1, MAYBE_FIELD_PTR(env_info, exiting)),
687
      should_abort_on_uncaught_toggle_(
688
6194
          isolate_,
689
          1,
690
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
691
6194
      stream_base_state_(isolate_,
692
                         StreamBase::kNumStreamBaseStateFields,
693
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
694
6194
      time_origin_(PERFORMANCE_NOW()),
695
6194
      time_origin_timestamp_(GetCurrentTimeInMicroseconds()),
696
      flags_(flags),
697
6194
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
698
6194
                     ? AllocateEnvironmentThreadId().id
699



24776
                     : thread_id.id) {
700
  // We'll be creating new objects so make sure we've entered the context.
701
12388
  HandleScope handle_scope(isolate);
702
703
  // Set some flags if only kDefaultFlags was passed. This can make API version
704
  // transitions easier for embedders.
705
6194
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
706
10942
    flags_ = flags_ |
707
5471
        EnvironmentFlags::kOwnsProcessState |
708
        EnvironmentFlags::kOwnsInspector;
709
  }
710
711
6194
  set_env_vars(per_process::system_environment);
712
6194
  enabled_debug_list_.Parse(env_vars(), isolate);
713
714
  // We create new copies of the per-Environment option sets, so that it is
715
  // easier to modify them after Environment creation. The defaults are
716
  // part of the per-Isolate option set, for which in turn the defaults are
717
  // part of the per-process option set.
718
12388
  options_ = std::make_shared<EnvironmentOptions>(
719
18582
      *isolate_data->options()->per_env);
720
6194
  inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
721
6194
      options_->debug_options().host_port);
722
723
6194
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
724
723
    set_abort_on_uncaught_exception(false);
725
  }
726
727
#if HAVE_INSPECTOR
728
  // We can only create the inspector agent after having cloned the options.
729
6194
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
730
#endif
731
732
6194
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
733
6194
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
734
6194
    if (TracingController* tracing_controller = writer->GetTracingController())
735
6144
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
736
  }
737
738
6194
  destroy_async_id_list_.reserve(512);
739
740
6194
  performance_state_ = std::make_unique<performance::PerformanceState>(
741
6194
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
742
743
6194
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
744
6194
          TRACING_CATEGORY_NODE1(environment)) != 0) {
745
16
    auto traced_value = tracing::TracedValue::Create();
746
8
    traced_value->BeginArray("args");
747
18
    for (const std::string& arg : args) traced_value->AppendString(arg);
748
8
    traced_value->EndArray();
749
8
    traced_value->BeginArray("exec_args");
750
33
    for (const std::string& arg : exec_args) traced_value->AppendString(arg);
751
8
    traced_value->EndArray();
752

15
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(environment),
753
                                      "Environment",
754
                                      this,
755
                                      "args",
756
                                      std::move(traced_value));
757
  }
758
6194
}
759
760
779
Environment::Environment(IsolateData* isolate_data,
761
                         Local<Context> context,
762
                         const std::vector<std::string>& args,
763
                         const std::vector<std::string>& exec_args,
764
                         const EnvSerializeInfo* env_info,
765
                         EnvironmentFlags::Flags flags,
766
779
                         ThreadId thread_id)
767
    : Environment(isolate_data,
768
                  context->GetIsolate(),
769
                  args,
770
                  exec_args,
771
                  env_info,
772
                  flags,
773
779
                  thread_id) {
774
779
  InitializeMainContext(context, env_info);
775
779
}
776
777
6194
void Environment::InitializeMainContext(Local<Context> context,
778
                                        const EnvSerializeInfo* env_info) {
779
6194
  context_.Reset(context->GetIsolate(), context);
780
6194
  AssignToContext(context, ContextInfo(""));
781
6194
  if (env_info != nullptr) {
782
5415
    DeserializeProperties(env_info);
783
  } else {
784
779
    CreateProperties();
785
  }
786
787
6194
  if (!options_->force_async_hooks_checks) {
788
1
    async_hooks_.no_force_checks();
789
  }
790
791
  // By default, always abort when --abort-on-uncaught-exception was passed.
792
6194
  should_abort_on_uncaught_toggle_[0] = 1;
793
794
  // The process is not exiting by default.
795
6194
  set_exiting(false);
796
797
6194
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
798
                           time_origin_);
799
6194
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
800
                           per_process::node_start_time);
801
802
6194
  if (per_process::v8_initialized) {
803
6151
    performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
804
                            performance::performance_v8_start);
805
  }
806
6194
}
807
808
744480
Environment::~Environment() {
809
  if (Environment** interrupt_data = interrupt_data_.load()) {
810
    // There are pending RequestInterrupt() callbacks. Tell them not to run,
811
    // then force V8 to run interrupts by compiling and running an empty script
812
    // so as not to leak memory.
813
10
    *interrupt_data = nullptr;
814
815
20
    Isolate::AllowJavascriptExecutionScope allow_js_here(isolate());
816
20
    HandleScope handle_scope(isolate());
817
20
    TryCatch try_catch(isolate());
818
20
    Context::Scope context_scope(context());
819
820
#ifdef DEBUG
821
    bool consistency_check = false;
822
    isolate()->RequestInterrupt([](Isolate*, void* data) {
823
      *static_cast<bool*>(data) = true;
824
    }, &consistency_check);
825
#endif
826
827
    Local<Script> script;
828
30
    if (Script::Compile(context(), String::Empty(isolate())).ToLocal(&script))
829
10
      USE(script->Run(context()));
830
831
    DCHECK(consistency_check);
832
  }
833
834
  // FreeEnvironment() should have set this.
835
5640
  CHECK(is_stopping());
836
837
5640
  if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
838
    isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
839
                                          0);
840
  }
841
842
5640
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
843
      BuildEmbedderGraph, this);
844
845
11280
  HandleScope handle_scope(isolate());
846
847
#if HAVE_INSPECTOR
848
  // Destroy inspector agent before erasing the context. The inspector
849
  // destructor depends on the context still being accessible.
850
5640
  inspector_agent_.reset();
851
#endif
852
853
11280
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
854
                                             nullptr);
855
856
5640
  if (trace_state_observer_) {
857
5640
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
858
5640
    CHECK_NOT_NULL(writer);
859
5640
    if (TracingController* tracing_controller = writer->GetTracingController())
860
5592
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
861
  }
862
863

10526
  TRACE_EVENT_NESTABLE_ASYNC_END0(
864
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
865
866
  // Do not unload addons on the main thread. Some addons need to retain memory
867
  // beyond the Environment's lifetime, and unloading them early would break
868
  // them; with Worker threads, we have the opportunity to be stricter.
869
  // Also, since the main thread usually stops just before the process exits,
870
  // this is far less relevant here.
871
5640
  if (!is_main_thread()) {
872
    // Dereference all addons that were loaded into this environment.
873
734
    for (binding::DLib& addon : loaded_addons_) {
874
14
      addon.Close();
875
    }
876
  }
877
878
5640
  CHECK_EQ(base_object_count_, 0);
879
5640
}
880
881
6161
void Environment::InitializeLibuv() {
882
12322
  HandleScope handle_scope(isolate());
883
6161
  Context::Scope context_scope(context());
884
885
6161
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
886
6161
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
887
888
6161
  CHECK_EQ(0, uv_check_init(event_loop(), immediate_check_handle()));
889
6161
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
890
891
6161
  CHECK_EQ(0, uv_idle_init(event_loop(), immediate_idle_handle()));
892
893
6161
  CHECK_EQ(0, uv_check_start(immediate_check_handle(), CheckImmediate));
894
895
  // Inform V8's CPU profiler when we're idle.  The profiler is sampling-based
896
  // but not all samples are created equal; mark the wall clock time spent in
897
  // epoll_wait() and friends so profiling tools can filter it out.  The samples
898
  // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
899
6161
  CHECK_EQ(0, uv_prepare_init(event_loop(), &idle_prepare_handle_));
900
6161
  CHECK_EQ(0, uv_check_init(event_loop(), &idle_check_handle_));
901
902
24827
  CHECK_EQ(0, uv_async_init(
903
      event_loop(),
904
      &task_queues_async_,
905
      [](uv_async_t* async) {
906
        Environment* env = ContainerOf(
907
            &Environment::task_queues_async_, async);
908
        HandleScope handle_scope(env->isolate());
909
        Context::Scope context_scope(env->context());
910
        env->RunAndClearNativeImmediates();
911
      }));
912
6161
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
913
6161
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
914
6161
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
915
916
  {
917
12322
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
918
6161
    task_queues_async_initialized_ = true;
919

12322
    if (native_immediates_threadsafe_.size() > 0 ||
920
6161
        native_immediates_interrupts_.size() > 0) {
921
5411
      uv_async_send(&task_queues_async_);
922
    }
923
  }
924
925
  // Register clean-up cb to be called to clean up the handles
926
  // when the environment is freed, note that they are not cleaned in
927
  // the one environment per process setup, but will be called in
928
  // FreeEnvironment.
929
6161
  RegisterHandleCleanups();
930
931
6161
  StartProfilerIdleNotifier();
932
6161
}
933
934
374
void Environment::ExitEnv() {
935
374
  set_can_call_into_js(false);
936
374
  set_stopping(true);
937
374
  isolate_->TerminateExecution();
938
748
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
939
374
}
940
941
6161
void Environment::RegisterHandleCleanups() {
942
6161
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
943
33642
                                        void* arg) {
944
33642
    handle->data = env;
945
946
33642
    env->CloseHandle(handle, [](uv_handle_t* handle) {
947
#ifdef DEBUG
948
      memset(handle, 0xab, uv_handle_size(handle->type));
949
#endif
950
33642
    });
951
33642
  };
952
953
36966
  auto register_handle = [&](uv_handle_t* handle) {
954
36966
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
955
43127
  };
956
6161
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
957
6161
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
958
6161
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
959
6161
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
960
6161
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
961
6161
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
962
6161
}
963
964
11274
void Environment::CleanupHandles() {
965
  {
966
11274
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
967
11274
    task_queues_async_initialized_ = false;
968
  }
969
970
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
971
22548
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
972
973
11274
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
974
975
11435
  for (ReqWrapBase* request : req_wrap_queue_)
976
161
    request->Cancel();
977
978
15593
  for (HandleWrap* handle : handle_wrap_queue_)
979
8638
    handle->Close();
980
981
44916
  for (HandleCleanup& hc : handle_cleanup_queue_)
982
33642
    hc.cb_(this, hc.handle_, hc.arg_);
983
11274
  handle_cleanup_queue_.clear();
984
985
10584
  while (handle_cleanup_waiting_ != 0 ||
986

33134
         request_waiting_ != 0 ||
987
11276
         !handle_wrap_queue_.IsEmpty()) {
988
10584
    uv_run(event_loop(), UV_RUN_ONCE);
989
  }
990
11274
}
991
992
6161
void Environment::StartProfilerIdleNotifier() {
993
6161
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
994
196919
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
995
196919
    env->isolate()->SetIdle(true);
996
196919
  });
997
6161
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
998
196725
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
999
196725
    env->isolate()->SetIdle(false);
1000
196725
  });
1001
6161
}
1002
1003
722010
void Environment::PrintSyncTrace() const {
1004
722010
  if (!trace_sync_io_) return;
1005
1006
2
  HandleScope handle_scope(isolate());
1007
1008
1
  fprintf(
1009
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
1010
1
  PrintStackTrace(isolate(),
1011
                  StackTrace::CurrentStackTrace(
1012
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
1013
}
1014
1015
5284
MaybeLocal<Value> Environment::RunSnapshotSerializeCallback() const {
1016
5284
  EscapableHandleScope handle_scope(isolate());
1017
10568
  if (!snapshot_serialize_callback().IsEmpty()) {
1018
    Context::Scope context_scope(context());
1019
    return handle_scope.EscapeMaybe(snapshot_serialize_callback()->Call(
1020
        context(), v8::Undefined(isolate()), 0, nullptr));
1021
  }
1022
10568
  return handle_scope.Escape(Undefined(isolate()));
1023
}
1024
1025
MaybeLocal<Value> Environment::RunSnapshotDeserializeMain() const {
1026
  EscapableHandleScope handle_scope(isolate());
1027
  if (!snapshot_deserialize_main().IsEmpty()) {
1028
    Context::Scope context_scope(context());
1029
    return handle_scope.EscapeMaybe(snapshot_deserialize_main()->Call(
1030
        context(), v8::Undefined(isolate()), 0, nullptr));
1031
  }
1032
  return handle_scope.Escape(Undefined(isolate()));
1033
}
1034
1035
5640
void Environment::RunCleanup() {
1036
5640
  started_cleanup_ = true;
1037

16166
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunCleanup");
1038
5640
  bindings_.clear();
1039
5640
  CleanupHandles();
1040
1041
16916
  while (!cleanup_hooks_.empty() ||
1042
11282
         native_immediates_.size() > 0 ||
1043

22556
         native_immediates_threadsafe_.size() > 0 ||
1044
5640
         native_immediates_interrupts_.size() > 0) {
1045
    // Copy into a vector, since we can't sort an unordered_set in-place.
1046
    std::vector<CleanupHookCallback> callbacks(
1047
11268
        cleanup_hooks_.begin(), cleanup_hooks_.end());
1048
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
1049
    // need to be able to check whether they were un-scheduled by another hook.
1050
1051
5634
    std::sort(callbacks.begin(), callbacks.end(),
1052
1296046
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
1053
      // Sort in descending order so that the most recently inserted callbacks
1054
      // are run first.
1055
1296046
      return a.insertion_order_counter_ > b.insertion_order_counter_;
1056
    });
1057
1058
194025
    for (const CleanupHookCallback& cb : callbacks) {
1059
188391
      if (cleanup_hooks_.count(cb) == 0) {
1060
        // This hook was removed from the `cleanup_hooks_` set during another
1061
        // hook that was run earlier. Nothing to do here.
1062
1023
        continue;
1063
      }
1064
1065
187368
      cb.fn_(cb.arg_);
1066
187368
      cleanup_hooks_.erase(cb);
1067
    }
1068
5634
    CleanupHandles();
1069
  }
1070
1071
5643
  for (const int fd : unmanaged_fds_) {
1072
    uv_fs_t close_req;
1073
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
1074
3
    uv_fs_req_cleanup(&close_req);
1075
  }
1076
5640
}
1077
1078
6269
void Environment::RunAtExitCallbacks() {
1079

17958
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "AtExit");
1080
18623
  for (ExitCallback at_exit : at_exit_functions_) {
1081
12354
    at_exit.cb_(at_exit.arg_);
1082
  }
1083
6269
  at_exit_functions_.clear();
1084
6269
}
1085
1086
12378
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
1087
12378
  at_exit_functions_.push_front(ExitCallback{cb, arg});
1088
12378
}
1089
1090
234892
void Environment::RunAndClearInterrupts() {
1091
234892
  while (native_immediates_interrupts_.size() > 0) {
1092
10477
    NativeImmediateQueue queue;
1093
    {
1094
20954
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1095
10477
      queue.ConcatMove(std::move(native_immediates_interrupts_));
1096
    }
1097
10477
    DebugSealHandleScope seal_handle_scope(isolate());
1098
1099
20967
    while (auto head = queue.Shift())
1100
20980
      head->Call(this);
1101
  }
1102
224415
}
1103
1104
214223
void Environment::RunAndClearNativeImmediates(bool only_refed) {
1105

433545
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment),
1106
               "RunAndClearNativeImmediates");
1107
428440
  HandleScope handle_scope(isolate_);
1108
428440
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
1109
1110
214223
  size_t ref_count = 0;
1111
1112
  // Handle interrupts first. These functions are not allowed to throw
1113
  // exceptions, so we do not need to handle that.
1114
214223
  RunAndClearInterrupts();
1115
1116
428444
  auto drain_list = [&](NativeImmediateQueue* queue) {
1117
856882
    TryCatchScope try_catch(this);
1118
428444
    DebugSealHandleScope seal_handle_scope(isolate());
1119
488493
    while (auto head = queue->Shift()) {
1120
60056
      bool is_refed = head->flags() & CallbackFlags::kRefed;
1121
60056
      if (is_refed)
1122
35142
        ref_count++;
1123
1124

60056
      if (is_refed || !only_refed)
1125
59806
        head->Call(this);
1126
1127
60051
      head.reset();  // Destroy now so that this is also observed by try_catch.
1128
1129
60051
      if (UNLIKELY(try_catch.HasCaught())) {
1130

2
        if (!try_catch.HasTerminated() && can_call_into_js())
1131
2
          errors::TriggerUncaughtException(isolate(), try_catch);
1132
1133
1
        return true;
1134
      }
1135
60049
    }
1136
428437
    return false;
1137
214223
  };
1138
214223
  while (drain_list(&native_immediates_)) {}
1139
1140
214220
  immediate_info()->ref_count_dec(ref_count);
1141
1142
214220
  if (immediate_info()->ref_count() == 0)
1143
171950
    ToggleImmediateRef(false);
1144
1145
  // It is safe to check .size() first, because there is a causal relationship
1146
  // between pushes to the threadsafe immediate list and this function being
1147
  // called. For the common case, it's worth checking the size first before
1148
  // establishing a mutex lock.
1149
  // This is intentionally placed after the `ref_count` handling, because when
1150
  // refed threadsafe immediates are created, they are not counted towards the
1151
  // count in immediate_info() either.
1152
214217
  NativeImmediateQueue threadsafe_immediates;
1153
214220
  if (native_immediates_threadsafe_.size() > 0) {
1154
2172
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1155
1086
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
1156
  }
1157
214221
  while (drain_list(&threadsafe_immediates)) {}
1158
214217
}
1159
1160
10494
void Environment::RequestInterruptFromV8() {
1161
  // The Isolate may outlive the Environment, so some logic to handle the
1162
  // situation in which the Environment is destroyed before the handler runs
1163
  // is required.
1164
1165
  // We allocate a new pointer to a pointer to this Environment instance, and
1166
  // try to set it as interrupt_data_. If interrupt_data_ was already set, then
1167
  // callbacks are already scheduled to run and we can delete our own pointer
1168
  // and just return. If it was nullptr previously, the Environment** is stored;
1169
  // ~Environment sets the Environment* contained in it to nullptr, so that
1170
  // the callback can check whether ~Environment has already run and it is thus
1171
  // not safe to access the Environment instance itself.
1172
10494
  Environment** interrupt_data = new Environment*(this);
1173
10494
  Environment** dummy = nullptr;
1174
10494
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
1175
399
    delete interrupt_data;
1176
399
    return;  // Already scheduled.
1177
  }
1178
1179
10095
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
1180
10087
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
1181
10087
    Environment* env = *env_ptr;
1182
10087
    if (env == nullptr) {
1183
      // The Environment has already been destroyed. That should be okay; any
1184
      // callback added before the Environment shuts down would have been
1185
      // handled during cleanup.
1186
10
      return;
1187
    }
1188
10077
    env->interrupt_data_.store(nullptr);
1189
10077
    env->RunAndClearInterrupts();
1190
  }, interrupt_data);
1191
}
1192
1193
9419
void Environment::ScheduleTimer(int64_t duration_ms) {
1194
9419
  if (started_cleanup_) return;
1195
9419
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
1196
}
1197
1198
3744
void Environment::ToggleTimerRef(bool ref) {
1199
3744
  if (started_cleanup_) return;
1200
1201
3744
  if (ref) {
1202
2475
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1203
  } else {
1204
1269
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1205
  }
1206
}
1207
1208
7410
void Environment::RunTimers(uv_timer_t* handle) {
1209
7410
  Environment* env = Environment::from_timer_handle(handle);
1210

7924
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunTimers");
1211
1212
7410
  if (!env->can_call_into_js())
1213
    return;
1214
1215
7410
  HandleScope handle_scope(env->isolate());
1216
7410
  Context::Scope context_scope(env->context());
1217
1218
7410
  Local<Object> process = env->process_object();
1219
7410
  InternalCallbackScope scope(env, process, {0, 0});
1220
1221
7410
  Local<Function> cb = env->timers_callback_function();
1222
  MaybeLocal<Value> ret;
1223
7410
  Local<Value> arg = env->GetNow();
1224
  // This code will loop until all currently due timers will process. It is
1225
  // impossible for us to end up in an infinite loop due to how the JS-side
1226
  // is structured.
1227
33
  do {
1228
7443
    TryCatchScope try_catch(env);
1229
7443
    try_catch.SetVerbose(true);
1230
7443
    ret = cb->Call(env->context(), process, 1, &arg);
1231

7433
  } while (ret.IsEmpty() && env->can_call_into_js());
1232
1233
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
1234
  // is reset back to `true` after being previously set to `false` then this
1235
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
1236
  // timers corruption will occur and all timers behaviour will become
1237
  // entirely unpredictable.
1238
7400
  if (ret.IsEmpty())
1239
6
    return;
1240
1241
  // To allow for less JS-C++ boundary crossing, the value returned from JS
1242
  // serves a few purposes:
1243
  // 1. If it's 0, no more timers exist and the handle should be unrefed
1244
  // 2. If it's > 0, the value represents the next timer's expiry and there
1245
  //    is at least one timer remaining that is refed.
1246
  // 3. If it's < 0, the absolute value represents the next timer's expiry
1247
  //    and there are no timers that are refed.
1248
  int64_t expiry_ms =
1249
7394
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
1250
1251
7394
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
1252
1253
7394
  if (expiry_ms != 0) {
1254
    int64_t duration_ms =
1255
6375
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
1256
1257
6375
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
1258
1259
6375
    if (expiry_ms > 0)
1260
5692
      uv_ref(h);
1261
    else
1262
683
      uv_unref(h);
1263
  } else {
1264
1019
    uv_unref(h);
1265
  }
1266
}
1267
1268
1269
196725
void Environment::CheckImmediate(uv_check_t* handle) {
1270
196725
  Environment* env = Environment::from_immediate_check_handle(handle);
1271

199809
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "CheckImmediate");
1272
1273
196725
  HandleScope scope(env->isolate());
1274
196725
  Context::Scope context_scope(env->context());
1275
1276
196725
  env->RunAndClearNativeImmediates();
1277
1278

196725
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
1279
155025
    return;
1280
1281
952
  do {
1282
42644
    MakeCallback(env->isolate(),
1283
                 env->process_object(),
1284
                 env->immediate_callback_function(),
1285
                 0,
1286
                 nullptr,
1287
42652
                 {0, 0}).ToLocalChecked();
1288

42644
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
1289
1290
41692
  if (env->immediate_info()->ref_count() == 0)
1291
4701
    env->ToggleImmediateRef(false);
1292
}
1293
1294
241776
void Environment::ToggleImmediateRef(bool ref) {
1295
241776
  if (started_cleanup_) return;
1296
1297
230579
  if (ref) {
1298
    // Idle handle is needed only to stop the event loop from blocking in poll.
1299
65101
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
1300
  } else {
1301
165478
    uv_idle_stop(immediate_idle_handle());
1302
  }
1303
}
1304
1305
1306
47107
Local<Value> Environment::GetNow() {
1307
47107
  uv_update_time(event_loop());
1308
47107
  uint64_t now = uv_now(event_loop());
1309
47107
  CHECK_GE(now, timer_base());
1310
47107
  now -= timer_base();
1311
47107
  if (now <= 0xffffffff)
1312
94214
    return Integer::NewFromUnsigned(isolate(), static_cast<uint32_t>(now));
1313
  else
1314
    return Number::New(isolate(), static_cast<double>(now));
1315
}
1316
1317
28
void CollectExceptionInfo(Environment* env,
1318
                          Local<Object> obj,
1319
                          int errorno,
1320
                          const char* err_string,
1321
                          const char* syscall,
1322
                          const char* message,
1323
                          const char* path,
1324
                          const char* dest) {
1325
28
  obj->Set(env->context(),
1326
           env->errno_string(),
1327
112
           Integer::New(env->isolate(), errorno)).Check();
1328
1329
28
  obj->Set(env->context(), env->code_string(),
1330
84
           OneByteString(env->isolate(), err_string)).Check();
1331
1332
28
  if (message != nullptr) {
1333
28
    obj->Set(env->context(), env->message_string(),
1334
112
             OneByteString(env->isolate(), message)).Check();
1335
  }
1336
1337
  Local<Value> path_buffer;
1338
28
  if (path != nullptr) {
1339
    path_buffer =
1340
      Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked();
1341
    obj->Set(env->context(), env->path_string(), path_buffer).Check();
1342
  }
1343
1344
  Local<Value> dest_buffer;
1345
28
  if (dest != nullptr) {
1346
    dest_buffer =
1347
      Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked();
1348
    obj->Set(env->context(), env->dest_string(), dest_buffer).Check();
1349
  }
1350
1351
28
  if (syscall != nullptr) {
1352
28
    obj->Set(env->context(), env->syscall_string(),
1353
112
             OneByteString(env->isolate(), syscall)).Check();
1354
  }
1355
28
}
1356
1357
28
void Environment::CollectUVExceptionInfo(Local<Value> object,
1358
                                         int errorno,
1359
                                         const char* syscall,
1360
                                         const char* message,
1361
                                         const char* path,
1362
                                         const char* dest) {
1363

28
  if (!object->IsObject() || errorno == 0)
1364
    return;
1365
1366
28
  Local<Object> obj = object.As<Object>();
1367
28
  const char* err_string = uv_err_name(errorno);
1368
1369

28
  if (message == nullptr || message[0] == '\0') {
1370
28
    message = uv_strerror(errorno);
1371
  }
1372
1373
28
  node::CollectExceptionInfo(this, obj, errorno, err_string,
1374
                             syscall, message, path, dest);
1375
}
1376
1377
6194
ImmediateInfo::ImmediateInfo(Isolate* isolate, const SerializeInfo* info)
1378
6194
    : fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)) {}
1379
1380
6
ImmediateInfo::SerializeInfo ImmediateInfo::Serialize(
1381
    Local<Context> context, SnapshotCreator* creator) {
1382
6
  return {fields_.Serialize(context, creator)};
1383
}
1384
1385
5415
void ImmediateInfo::Deserialize(Local<Context> context) {
1386
5415
  fields_.Deserialize(context);
1387
5415
}
1388
1389
6
std::ostream& operator<<(std::ostream& output,
1390
                         const ImmediateInfo::SerializeInfo& i) {
1391
6
  output << "{ " << i.fields << " }";
1392
6
  return output;
1393
}
1394
1395
24
void ImmediateInfo::MemoryInfo(MemoryTracker* tracker) const {
1396
24
  tracker->TrackField("fields", fields_);
1397
24
}
1398
1399
6
TickInfo::SerializeInfo TickInfo::Serialize(Local<Context> context,
1400
                                            SnapshotCreator* creator) {
1401
6
  return {fields_.Serialize(context, creator)};
1402
}
1403
1404
5415
void TickInfo::Deserialize(Local<Context> context) {
1405
5415
  fields_.Deserialize(context);
1406
5415
}
1407
1408
6
std::ostream& operator<<(std::ostream& output,
1409
                         const TickInfo::SerializeInfo& i) {
1410
6
  output << "{ " << i.fields << " }";
1411
6
  return output;
1412
}
1413
1414
24
void TickInfo::MemoryInfo(MemoryTracker* tracker) const {
1415
24
  tracker->TrackField("fields", fields_);
1416
24
}
1417
1418
6194
TickInfo::TickInfo(Isolate* isolate, const SerializeInfo* info)
1419
    : fields_(
1420
6194
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1421
1422
6194
AsyncHooks::AsyncHooks(Isolate* isolate, const SerializeInfo* info)
1423
    : async_ids_stack_(isolate, 16 * 2, MAYBE_FIELD_PTR(info, async_ids_stack)),
1424
      fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)),
1425
      async_id_fields_(
1426
          isolate, kUidFieldsCount, MAYBE_FIELD_PTR(info, async_id_fields)),
1427

6194
      info_(info) {
1428
12388
  HandleScope handle_scope(isolate);
1429
6194
  if (info == nullptr) {
1430
779
    clear_async_id_stack();
1431
1432
    // Always perform async_hooks checks, not just when async_hooks is enabled.
1433
    // TODO(AndreasMadsen): Consider removing this for LTS releases.
1434
    // See discussion in https://github.com/nodejs/node/pull/15454
1435
    // When removing this, do it by reverting the commit. Otherwise the test
1436
    // and flag changes won't be included.
1437
779
    fields_[kCheck] = 1;
1438
1439
    // kDefaultTriggerAsyncId should be -1, this indicates that there is no
1440
    // specified default value and it should fallback to the executionAsyncId.
1441
    // 0 is not used as the magic value, because that indicates a missing
1442
    // context which is different from a default context.
1443
779
    async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
1444
1445
    // kAsyncIdCounter should start at 1 because that'll be the id the execution
1446
    // context during bootstrap (code that runs before entering uv_run()).
1447
779
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1448
  }
1449
6194
}
1450
1451
5415
void AsyncHooks::Deserialize(Local<Context> context) {
1452
5415
  async_ids_stack_.Deserialize(context);
1453
5415
  fields_.Deserialize(context);
1454
5415
  async_id_fields_.Deserialize(context);
1455
1456
  Local<Array> js_execution_async_resources;
1457
5415
  if (info_->js_execution_async_resources != 0) {
1458
    js_execution_async_resources =
1459
5415
        context->GetDataFromSnapshotOnce<Array>(
1460
16245
            info_->js_execution_async_resources).ToLocalChecked();
1461
  } else {
1462
    js_execution_async_resources = Array::New(context->GetIsolate());
1463
  }
1464
5415
  js_execution_async_resources_.Reset(
1465
      context->GetIsolate(), js_execution_async_resources);
1466
1467
  // The native_execution_async_resources_ field requires v8::Local<> instances
1468
  // for async calls whose resources were on the stack as JS objects when they
1469
  // were entered. We cannot recreate this here; however, storing these values
1470
  // on the JS equivalent gives the same result, so we do that instead.
1471
5415
  for (size_t i = 0; i < info_->native_execution_async_resources.size(); ++i) {
1472
    if (info_->native_execution_async_resources[i] == SIZE_MAX)
1473
      continue;
1474
    Local<Object> obj = context->GetDataFromSnapshotOnce<Object>(
1475
                                   info_->native_execution_async_resources[i])
1476
                               .ToLocalChecked();
1477
    js_execution_async_resources->Set(context, i, obj).Check();
1478
  }
1479
5415
  info_ = nullptr;
1480
5415
}
1481
1482
6
std::ostream& operator<<(std::ostream& output,
1483
                         const AsyncHooks::SerializeInfo& i) {
1484
  output << "{\n"
1485
6
         << "  " << i.async_ids_stack << ",  // async_ids_stack\n"
1486
6
         << "  " << i.fields << ",  // fields\n"
1487
6
         << "  " << i.async_id_fields << ",  // async_id_fields\n"
1488
6
         << "  " << i.js_execution_async_resources
1489
         << ",  // js_execution_async_resources\n"
1490
6
         << "  " << i.native_execution_async_resources
1491
         << ",  // native_execution_async_resources\n"
1492
6
         << "}";
1493
6
  return output;
1494
}
1495
1496
6
AsyncHooks::SerializeInfo AsyncHooks::Serialize(Local<Context> context,
1497
                                                SnapshotCreator* creator) {
1498
6
  SerializeInfo info;
1499
  // TODO(joyeecheung): some of these probably don't need to be serialized.
1500
6
  info.async_ids_stack = async_ids_stack_.Serialize(context, creator);
1501
6
  info.fields = fields_.Serialize(context, creator);
1502
6
  info.async_id_fields = async_id_fields_.Serialize(context, creator);
1503
6
  if (!js_execution_async_resources_.IsEmpty()) {
1504
6
    info.js_execution_async_resources = creator->AddData(
1505
        context, js_execution_async_resources_.Get(context->GetIsolate()));
1506
6
    CHECK_NE(info.js_execution_async_resources, 0);
1507
  } else {
1508
    info.js_execution_async_resources = 0;
1509
  }
1510
1511
6
  info.native_execution_async_resources.resize(
1512
      native_execution_async_resources_.size());
1513
6
  for (size_t i = 0; i < native_execution_async_resources_.size(); i++) {
1514
    info.native_execution_async_resources[i] =
1515
        native_execution_async_resources_[i].IsEmpty() ? SIZE_MAX :
1516
            creator->AddData(
1517
                context,
1518
                native_execution_async_resources_[i]);
1519
  }
1520
6
  CHECK_EQ(contexts_.size(), 1);
1521

12
  CHECK_EQ(contexts_[0], env()->context());
1522
6
  CHECK(js_promise_hooks_[0].IsEmpty());
1523
6
  CHECK(js_promise_hooks_[1].IsEmpty());
1524
6
  CHECK(js_promise_hooks_[2].IsEmpty());
1525
6
  CHECK(js_promise_hooks_[3].IsEmpty());
1526
1527
6
  return info;
1528
}
1529
1530
24
void AsyncHooks::MemoryInfo(MemoryTracker* tracker) const {
1531
24
  tracker->TrackField("async_ids_stack", async_ids_stack_);
1532
24
  tracker->TrackField("fields", fields_);
1533
24
  tracker->TrackField("async_id_fields", async_id_fields_);
1534
24
  tracker->TrackField("js_promise_hooks", js_promise_hooks_);
1535
24
}
1536
1537
4
void AsyncHooks::grow_async_ids_stack() {
1538
4
  async_ids_stack_.reserve(async_ids_stack_.Length() * 3);
1539
1540
4
  env()->async_hooks_binding()->Set(
1541
      env()->context(),
1542
      env()->async_ids_stack_string(),
1543
12
      async_ids_stack_.GetJSArray()).Check();
1544
4
}
1545
1546
4
void AsyncHooks::FailWithCorruptedAsyncStack(double expected_async_id) {
1547
4
  fprintf(stderr,
1548
          "Error: async hook stack has become corrupted ("
1549
          "actual: %.f, expected: %.f)\n",
1550
          async_id_fields_.GetValue(kExecutionAsyncId),
1551
          expected_async_id);
1552
4
  DumpBacktrace(stderr);
1553
4
  fflush(stderr);
1554
4
  if (!env()->abort_on_uncaught_exception())
1555
4
    exit(1);
1556
  fprintf(stderr, "\n");
1557
  fflush(stderr);
1558
  ABORT_NO_BACKTRACE();
1559
}
1560
1561
612
void Environment::Exit(int exit_code) {
1562
612
  if (options()->trace_exit) {
1563
4
    HandleScope handle_scope(isolate());
1564
    Isolate::DisallowJavascriptExecutionScope disallow_js(
1565
4
        isolate(), Isolate::DisallowJavascriptExecutionScope::CRASH_ON_FAILURE);
1566
1567
2
    if (is_main_thread()) {
1568
1
      fprintf(stderr, "(node:%d) ", uv_os_getpid());
1569
    } else {
1570
1
      fprintf(stderr, "(node:%d, thread:%" PRIu64 ") ",
1571
              uv_os_getpid(), thread_id());
1572
    }
1573
1574
2
    fprintf(
1575
        stderr, "WARNING: Exited the environment with code %d\n", exit_code);
1576
2
    PrintStackTrace(isolate(),
1577
                    StackTrace::CurrentStackTrace(
1578
                        isolate(), stack_trace_limit(), StackTrace::kDetailed));
1579
  }
1580
612
  process_exit_handler_(this, exit_code);
1581
63
}
1582
1583
6217
void Environment::stop_sub_worker_contexts() {
1584
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1585
1586
6217
  while (!sub_worker_contexts_.empty()) {
1587
28
    Worker* w = *sub_worker_contexts_.begin();
1588
28
    remove_sub_worker_context(w);
1589
28
    w->Exit(1);
1590
28
    w->JoinThread();
1591
  }
1592
6189
}
1593
1594
10
Environment* Environment::worker_parent_env() const {
1595
10
  if (worker_context() == nullptr) return nullptr;
1596
  return worker_context()->env();
1597
}
1598
1599
64270
void Environment::AddUnmanagedFd(int fd) {
1600
64270
  if (!tracks_unmanaged_fds()) return;
1601
2723
  auto result = unmanaged_fds_.insert(fd);
1602
2723
  if (!result.second) {
1603
    ProcessEmitWarning(
1604
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1605
  }
1606
}
1607
1608
63881
void Environment::RemoveUnmanagedFd(int fd) {
1609
63881
  if (!tracks_unmanaged_fds()) return;
1610
2720
  size_t removed_count = unmanaged_fds_.erase(fd);
1611
2720
  if (removed_count == 0) {
1612
    ProcessEmitWarning(
1613
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1614
  }
1615
}
1616
1617
5258
void Environment::PrintInfoForSnapshotIfDebug() {
1618
10516
  if (enabled_debug_list()->enabled(DebugCategory::MKSNAPSHOT)) {
1619
    fprintf(stderr, "BaseObjects at the exit of the Environment:\n");
1620
    PrintAllBaseObjects();
1621
    fprintf(stderr, "\nNative modules without cache:\n");
1622
    for (const auto& s : builtins_without_cache) {
1623
      fprintf(stderr, "%s\n", s.c_str());
1624
    }
1625
    fprintf(stderr, "\nNative modules with cache:\n");
1626
    for (const auto& s : builtins_with_cache) {
1627
      fprintf(stderr, "%s\n", s.c_str());
1628
    }
1629
    fprintf(stderr, "\nStatic bindings (need to be registered):\n");
1630
    for (const auto mod : internal_bindings) {
1631
      fprintf(stderr, "%s:%s\n", mod->nm_filename, mod->nm_modname);
1632
    }
1633
  }
1634
5258
}
1635
1636
void Environment::PrintAllBaseObjects() {
1637
  size_t i = 0;
1638
  std::cout << "BaseObjects\n";
1639
  ForEachBaseObject([&](BaseObject* obj) {
1640
    std::cout << "#" << i++ << " " << obj << ": " <<
1641
      obj->MemoryInfoName() << "\n";
1642
  });
1643
}
1644
1645
5258
void Environment::VerifyNoStrongBaseObjects() {
1646
  // When a process exits cleanly, i.e. because the event loop ends up without
1647
  // things to wait for, the Node.js objects that are left on the heap should
1648
  // be:
1649
  //
1650
  //   1. weak, i.e. ready for garbage collection once no longer referenced, or
1651
  //   2. detached, i.e. scheduled for destruction once no longer referenced, or
1652
  //   3. an unrefed libuv handle, i.e. does not keep the event loop alive, or
1653
  //   4. an inactive libuv handle (essentially the same here)
1654
  //
1655
  // There are a few exceptions to this rule, but generally, if there are
1656
  // C++-backed Node.js objects on the heap that do not fall into the above
1657
  // categories, we may be looking at a potential memory leak. Most likely,
1658
  // the cause is a missing MakeWeak() call on the corresponding object.
1659
  //
1660
  // In order to avoid this kind of problem, we check the list of BaseObjects
1661
  // for these criteria. Currently, we only do so when explicitly instructed to
1662
  // or when in debug mode (where --verify-base-objects is always-on).
1663
1664
5258
  if (!options()->verify_base_objects) return;
1665
1666
  ForEachBaseObject([](BaseObject* obj) {
1667
    if (obj->IsNotIndicativeOfMemoryLeakAtExit()) return;
1668
    fprintf(stderr, "Found bad BaseObject during clean exit: %s\n",
1669
            obj->MemoryInfoName().c_str());
1670
    fflush(stderr);
1671
    ABORT();
1672
  });
1673
}
1674
1675
6
EnvSerializeInfo Environment::Serialize(SnapshotCreator* creator) {
1676
6
  EnvSerializeInfo info;
1677
6
  Local<Context> ctx = context();
1678
1679
  // Currently all modules are compiled without cache in builtin snapshot
1680
  // builder.
1681
12
  info.builtins = std::vector<std::string>(builtins_without_cache.begin(),
1682
6
                                           builtins_without_cache.end());
1683
1684
6
  info.async_hooks = async_hooks_.Serialize(ctx, creator);
1685
6
  info.immediate_info = immediate_info_.Serialize(ctx, creator);
1686
6
  info.tick_info = tick_info_.Serialize(ctx, creator);
1687
6
  info.performance_state = performance_state_->Serialize(ctx, creator);
1688
6
  info.exiting = exiting_.Serialize(ctx, creator);
1689
6
  info.stream_base_state = stream_base_state_.Serialize(ctx, creator);
1690
6
  info.should_abort_on_uncaught_toggle =
1691
6
      should_abort_on_uncaught_toggle_.Serialize(ctx, creator);
1692
1693
6
  uint32_t id = 0;
1694
#define V(PropertyName, TypeName)                                              \
1695
  do {                                                                         \
1696
    Local<TypeName> field = PropertyName();                                    \
1697
    if (!field.IsEmpty()) {                                                    \
1698
      size_t index = creator->AddData(ctx, field);                             \
1699
      info.persistent_values.push_back({#PropertyName, id, index});            \
1700
    }                                                                          \
1701
    id++;                                                                      \
1702
  } while (0);
1703































582
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1704
#undef V
1705
1706
  // Do this after other creator->AddData() calls so that Snapshotable objects
1707
  // can use 0 to indicate that a SnapshotIndex is invalid.
1708
6
  SerializeSnapshotableObjects(this, creator, &info);
1709
1710
6
  info.context = creator->AddData(ctx, context());
1711
6
  return info;
1712
}
1713
1714
18
std::ostream& operator<<(std::ostream& output,
1715
                         const std::vector<PropInfo>& vec) {
1716
18
  output << "{\n";
1717
360
  for (const auto& info : vec) {
1718
342
    output << "  " << info << ",\n";
1719
  }
1720
18
  output << "}";
1721
18
  return output;
1722
}
1723
1724
342
std::ostream& operator<<(std::ostream& output, const PropInfo& info) {
1725
342
  output << "{ \"" << info.name << "\", " << std::to_string(info.id) << ", "
1726
684
         << std::to_string(info.index) << " }";
1727
342
  return output;
1728
}
1729
1730
6
std::ostream& operator<<(std::ostream& output,
1731
                         const std::vector<std::string>& vec) {
1732
6
  output << "{\n";
1733
702
  for (const auto& info : vec) {
1734
696
    output << "  \"" << info << "\",\n";
1735
  }
1736
6
  output << "}";
1737
6
  return output;
1738
}
1739
1740
6
std::ostream& operator<<(std::ostream& output, const EnvSerializeInfo& i) {
1741
  output << "{\n"
1742
6
         << "// -- native_objects begins --\n"
1743
6
         << i.native_objects << ",\n"
1744
         << "// -- native_objects ends --\n"
1745
6
         << "// -- builtins begins --\n"
1746
6
         << i.builtins << ",\n"
1747
         << "// -- builtins ends --\n"
1748
6
         << "// -- async_hooks begins --\n"
1749
6
         << i.async_hooks << ",\n"
1750
6
         << "// -- async_hooks ends --\n"
1751
6
         << i.tick_info << ",  // tick_info\n"
1752
6
         << i.immediate_info << ",  // immediate_info\n"
1753
6
         << "// -- performance_state begins --\n"
1754
6
         << i.performance_state << ",\n"
1755
6
         << "// -- performance_state ends --\n"
1756
6
         << i.exiting << ",  // exiting\n"
1757
6
         << i.stream_base_state << ",  // stream_base_state\n"
1758
6
         << i.should_abort_on_uncaught_toggle
1759
         << ",  // should_abort_on_uncaught_toggle\n"
1760
6
         << "// -- persistent_values begins --\n"
1761
6
         << i.persistent_values << ",\n"
1762
6
         << "// -- persistent_values ends --\n"
1763
6
         << i.context << ",  // context\n"
1764
6
         << "}";
1765
6
  return output;
1766
}
1767
1768
21660
void Environment::EnqueueDeserializeRequest(DeserializeRequestCallback cb,
1769
                                            Local<Object> holder,
1770
                                            int index,
1771
                                            InternalFieldInfoBase* info) {
1772
  DCHECK_EQ(index, BaseObject::kEmbedderType);
1773
43320
  DeserializeRequest request{cb, {isolate(), holder}, index, info};
1774
21660
  deserialize_requests_.push_back(std::move(request));
1775
21660
}
1776
1777
5415
void Environment::RunDeserializeRequests() {
1778
10830
  HandleScope scope(isolate());
1779
5415
  Local<Context> ctx = context();
1780
5415
  Isolate* is = isolate();
1781
27075
  while (!deserialize_requests_.empty()) {
1782
43320
    DeserializeRequest request(std::move(deserialize_requests_.front()));
1783
21660
    deserialize_requests_.pop_front();
1784
21660
    Local<Object> holder = request.holder.Get(is);
1785
21660
    request.cb(ctx, holder, request.index, request.info);
1786
    request.holder.Reset();
1787
21660
    request.info->Delete();
1788
  }
1789
5415
}
1790
1791
5415
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1792
5415
  Local<Context> ctx = context();
1793
1794
5415
  RunDeserializeRequests();
1795
1796
5415
  builtins_in_snapshot = info->builtins;
1797
5415
  async_hooks_.Deserialize(ctx);
1798
5415
  immediate_info_.Deserialize(ctx);
1799
5415
  tick_info_.Deserialize(ctx);
1800
5415
  performance_state_->Deserialize(ctx);
1801
5415
  exiting_.Deserialize(ctx);
1802
5415
  stream_base_state_.Deserialize(ctx);
1803
5415
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1804
1805
5415
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1806
    fprintf(stderr, "deserializing...\n");
1807
    std::cerr << *info << "\n";
1808
  }
1809
1810
5415
  const std::vector<PropInfo>& values = info->persistent_values;
1811
5415
  size_t i = 0;  // index to the array
1812
5415
  uint32_t id = 0;
1813
#define V(PropertyName, TypeName)                                              \
1814
  do {                                                                         \
1815
    if (values.size() > i && id == values[i].id) {                             \
1816
      const PropInfo& d = values[i];                                           \
1817
      DCHECK_EQ(d.name, #PropertyName);                                        \
1818
      MaybeLocal<TypeName> maybe_field =                                       \
1819
          ctx->GetDataFromSnapshotOnce<TypeName>(d.index);                     \
1820
      Local<TypeName> field;                                                   \
1821
      if (!maybe_field.ToLocal(&field)) {                                      \
1822
        fprintf(stderr,                                                        \
1823
                "Failed to deserialize environment value " #PropertyName       \
1824
                "\n");                                                         \
1825
      }                                                                        \
1826
      set_##PropertyName(field);                                               \
1827
      i++;                                                                     \
1828
    }                                                                          \
1829
    id++;                                                                      \
1830
  } while (0);
1831
1832






























































































































541500
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1833
#undef V
1834
1835
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1836
10830
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1837
  Local<Context> ctx_from_snapshot;
1838
5415
  if (!maybe_ctx_from_snapshot.ToLocal(&ctx_from_snapshot)) {
1839
    fprintf(stderr,
1840
            "Failed to deserialize context back reference from the snapshot\n");
1841
  }
1842
5415
  CHECK_EQ(ctx_from_snapshot, ctx);
1843
5415
}
1844
1845
1
uint64_t GuessMemoryAvailableToTheProcess() {
1846
1
  uint64_t free_in_system = uv_get_free_memory();
1847
1
  size_t allowed = uv_get_constrained_memory();
1848
1
  if (allowed == 0) {
1849
    return free_in_system;
1850
  }
1851
  size_t rss;
1852
1
  int err = uv_resident_set_memory(&rss);
1853
1
  if (err) {
1854
    return free_in_system;
1855
  }
1856
1
  if (allowed < rss) {
1857
    // Something is probably wrong. Fallback to the free memory.
1858
    return free_in_system;
1859
  }
1860
  // There may still be room for swap, but we will just leave it here.
1861
1
  return allowed - rss;
1862
}
1863
1864
24
void Environment::BuildEmbedderGraph(Isolate* isolate,
1865
                                     EmbedderGraph* graph,
1866
                                     void* data) {
1867
24
  MemoryTracker tracker(isolate, graph);
1868
24
  Environment* env = static_cast<Environment*>(data);
1869
24
  tracker.Track(env);
1870
24
  env->ForEachBaseObject([&](BaseObject* obj) {
1871
633
    if (obj->IsDoneInitializing())
1872
632
      tracker.Track(obj);
1873
633
  });
1874
24
}
1875
1876
1
size_t Environment::NearHeapLimitCallback(void* data,
1877
                                          size_t current_heap_limit,
1878
                                          size_t initial_heap_limit) {
1879
1
  Environment* env = static_cast<Environment*>(data);
1880
1881
  Debug(env,
1882
        DebugCategory::DIAGNOSTICS,
1883
        "Invoked NearHeapLimitCallback, processing=%d, "
1884
        "current_limit=%" PRIu64 ", "
1885
        "initial_limit=%" PRIu64 "\n",
1886
1
        env->is_processing_heap_limit_callback_,
1887
2
        static_cast<uint64_t>(current_heap_limit),
1888
1
        static_cast<uint64_t>(initial_heap_limit));
1889
1890
1
  size_t max_young_gen_size = env->isolate_data()->max_young_gen_size;
1891
1
  size_t young_gen_size = 0;
1892
1
  size_t old_gen_size = 0;
1893
1894
1
  HeapSpaceStatistics stats;
1895
1
  size_t num_heap_spaces = env->isolate()->NumberOfHeapSpaces();
1896
9
  for (size_t i = 0; i < num_heap_spaces; ++i) {
1897
8
    env->isolate()->GetHeapSpaceStatistics(&stats, i);
1898

15
    if (strcmp(stats.space_name(), "new_space") == 0 ||
1899
7
        strcmp(stats.space_name(), "new_large_object_space") == 0) {
1900
2
      young_gen_size += stats.space_used_size();
1901
    } else {
1902
6
      old_gen_size += stats.space_used_size();
1903
    }
1904
  }
1905
1906
  Debug(env,
1907
        DebugCategory::DIAGNOSTICS,
1908
        "max_young_gen_size=%" PRIu64 ", "
1909
        "young_gen_size=%" PRIu64 ", "
1910
        "old_gen_size=%" PRIu64 ", "
1911
        "total_size=%" PRIu64 "\n",
1912
2
        static_cast<uint64_t>(max_young_gen_size),
1913
2
        static_cast<uint64_t>(young_gen_size),
1914
2
        static_cast<uint64_t>(old_gen_size),
1915
1
        static_cast<uint64_t>(young_gen_size + old_gen_size));
1916
1917
1
  uint64_t available = GuessMemoryAvailableToTheProcess();
1918
  // TODO(joyeecheung): get a better estimate about the native memory
1919
  // usage into the overhead, e.g. based on the count of objects.
1920
1
  uint64_t estimated_overhead = max_young_gen_size;
1921
  Debug(env,
1922
        DebugCategory::DIAGNOSTICS,
1923
        "Estimated available memory=%" PRIu64 ", "
1924
        "estimated overhead=%" PRIu64 "\n",
1925
2
        static_cast<uint64_t>(available),
1926
1
        static_cast<uint64_t>(estimated_overhead));
1927
1928
  // This might be hit when the snapshot is being taken in another
1929
  // NearHeapLimitCallback invocation.
1930
  // When taking the snapshot, objects in the young generation may be
1931
  // promoted to the old generation, result in increased heap usage,
1932
  // but it should be no more than the young generation size.
1933
  // Ideally, this should be as small as possible - the heap limit
1934
  // can only be restored when the heap usage falls down below the
1935
  // new limit, so in a heap with unbounded growth the isolate
1936
  // may eventually crash with this new limit - effectively raising
1937
  // the heap limit to the new one.
1938
1
  if (env->is_processing_heap_limit_callback_) {
1939
    size_t new_limit = current_heap_limit + max_young_gen_size;
1940
    Debug(env,
1941
          DebugCategory::DIAGNOSTICS,
1942
          "Not generating snapshots in nested callback. "
1943
          "new_limit=%" PRIu64 "\n",
1944
          static_cast<uint64_t>(new_limit));
1945
    return new_limit;
1946
  }
1947
1948
  // Estimate whether the snapshot is going to use up all the memory
1949
  // available to the process. If so, just give up to prevent the system
1950
  // from killing the process for a system OOM.
1951
1
  if (estimated_overhead > available) {
1952
    Debug(env,
1953
          DebugCategory::DIAGNOSTICS,
1954
          "Not generating snapshots because it's too risky.\n");
1955
    env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
1956
                                                initial_heap_limit);
1957
    // The new limit must be higher than current_heap_limit or V8 might
1958
    // crash.
1959
    return current_heap_limit + 1;
1960
  }
1961
1962
  // Take the snapshot synchronously.
1963
1
  env->is_processing_heap_limit_callback_ = true;
1964
1965
2
  std::string dir = env->options()->diagnostic_dir;
1966
1
  if (dir.empty()) {
1967
1
    dir = env->GetCwd();
1968
  }
1969
2
  DiagnosticFilename name(env, "Heap", "heapsnapshot");
1970
1
  std::string filename = dir + kPathSeparator + (*name);
1971
1972
1
  Debug(env, DebugCategory::DIAGNOSTICS, "Start generating %s...\n", *name);
1973
1974
  // Remove the callback first in case it's triggered when generating
1975
  // the snapshot.
1976
1
  env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
1977
                                              initial_heap_limit);
1978
1979
1
  heap::WriteSnapshot(env, filename.c_str());
1980
1
  env->heap_limit_snapshot_taken_ += 1;
1981
1982
  // Don't take more snapshots than the number specified by
1983
  // --heapsnapshot-near-heap-limit.
1984
2
  if (env->heap_limit_snapshot_taken_ <
1985
1
      env->options_->heap_snapshot_near_heap_limit) {
1986
    env->isolate()->AddNearHeapLimitCallback(NearHeapLimitCallback, env);
1987
  }
1988
1989
1
  FPrintF(stderr, "Wrote snapshot to %s\n", filename.c_str());
1990
  // Tell V8 to reset the heap limit once the heap usage falls down to
1991
  // 95% of the initial limit.
1992
1
  env->isolate()->AutomaticallyRestoreInitialHeapLimit(0.95);
1993
1994
1
  env->is_processing_heap_limit_callback_ = false;
1995
1996
  // The new limit must be higher than current_heap_limit or V8 might
1997
  // crash.
1998
1
  return current_heap_limit + 1;
1999
}
2000
2001
24
inline size_t Environment::SelfSize() const {
2002
24
  size_t size = sizeof(*this);
2003
  // Remove non pointer fields that will be tracked in MemoryInfo()
2004
  // TODO(joyeecheung): refactor the MemoryTracker interface so
2005
  // this can be done for common types within the Track* calls automatically
2006
  // if a certain scope is entered.
2007
24
  size -= sizeof(async_hooks_);
2008
24
  size -= sizeof(tick_info_);
2009
24
  size -= sizeof(immediate_info_);
2010
24
  return size;
2011
}
2012
2013
24
void Environment::MemoryInfo(MemoryTracker* tracker) const {
2014
  // Iteratable STLs have their own sizes subtracted from the parent
2015
  // by default.
2016
24
  tracker->TrackField("isolate_data", isolate_data_);
2017
24
  tracker->TrackField("builtins_with_cache", builtins_with_cache);
2018
24
  tracker->TrackField("builtins_without_cache", builtins_without_cache);
2019
24
  tracker->TrackField("destroy_async_id_list", destroy_async_id_list_);
2020
24
  tracker->TrackField("exec_argv", exec_argv_);
2021
24
  tracker->TrackField("exiting", exiting_);
2022
24
  tracker->TrackField("should_abort_on_uncaught_toggle",
2023
24
                      should_abort_on_uncaught_toggle_);
2024
24
  tracker->TrackField("stream_base_state", stream_base_state_);
2025
24
  tracker->TrackFieldWithSize(
2026
24
      "cleanup_hooks", cleanup_hooks_.size() * sizeof(CleanupHookCallback));
2027
24
  tracker->TrackField("async_hooks", async_hooks_);
2028
24
  tracker->TrackField("immediate_info", immediate_info_);
2029
24
  tracker->TrackField("tick_info", tick_info_);
2030
2031
#define V(PropertyName, TypeName)                                              \
2032
  tracker->TrackField(#PropertyName, PropertyName());
2033
24
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
2034
#undef V
2035
2036
  // FIXME(joyeecheung): track other fields in Environment.
2037
  // Currently MemoryTracker is unable to track these
2038
  // correctly:
2039
  // - Internal types that do not implement MemoryRetainer yet
2040
  // - STL containers with MemoryRetainer* inside
2041
  // - STL containers with numeric types inside that should not have their
2042
  //   nodes elided e.g. numeric keys in maps.
2043
  // We also need to make sure that when we add a non-pointer field as its own
2044
  // node, we shift its sizeof() size out of the Environment node.
2045
24
}
2046
2047
735188
void Environment::RunWeakRefCleanup() {
2048
735188
  isolate()->ClearKeptObjects();
2049
735188
}
2050
2051
// Not really any better place than env.cc at this moment.
2052
1454544
BaseObject::BaseObject(Environment* env, Local<Object> object)
2053
2909088
    : persistent_handle_(env->isolate(), object), env_(env) {
2054
1454544
  CHECK_EQ(false, object.IsEmpty());
2055
1454544
  CHECK_GE(object->InternalFieldCount(), BaseObject::kInternalFieldCount);
2056
1454544
  object->SetAlignedPointerInInternalField(BaseObject::kEmbedderType,
2057
                                           &kNodeEmbedderId);
2058
1454544
  object->SetAlignedPointerInInternalField(BaseObject::kSlot,
2059
                                           static_cast<void*>(this));
2060
1454544
  env->AddCleanupHook(DeleteMe, static_cast<void*>(this));
2061
1454544
  env->modify_base_object_count(1);
2062
1454544
}
2063
2064

7913132
BaseObject::~BaseObject() {
2065
2883200
  env()->modify_base_object_count(-1);
2066
2883200
  env()->RemoveCleanupHook(DeleteMe, static_cast<void*>(this));
2067
2068
2883200
  if (UNLIKELY(has_pointer_data())) {
2069
366754
    PointerData* metadata = pointer_data();
2070
366754
    CHECK_EQ(metadata->strong_ptr_count, 0);
2071
366754
    metadata->self = nullptr;
2072
366754
    if (metadata->weak_ptr_count == 0) delete metadata;
2073
  }
2074
2075
2883200
  if (persistent_handle_.IsEmpty()) {
2076
    // This most likely happened because the weak callback below cleared it.
2077
2146732
    return;
2078
  }
2079
2080
  {
2081
736468
    HandleScope handle_scope(env()->isolate());
2082
1472936
    object()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
2083
  }
2084
}
2085
2086
1242399
void BaseObject::MakeWeak() {
2087
1242399
  if (has_pointer_data()) {
2088
42675
    pointer_data()->wants_weak_jsobj = true;
2089
42675
    if (pointer_data()->strong_ptr_count > 0) return;
2090
  }
2091
2092
2484796
  persistent_handle_.SetWeak(
2093
      this,
2094
1073365
      [](const WeakCallbackInfo<BaseObject>& data) {
2095
1073365
        BaseObject* obj = data.GetParameter();
2096
        // Clear the persistent handle so that ~BaseObject() doesn't attempt
2097
        // to mess with internal fields, since the JS object may have
2098
        // transitioned into an invalid state.
2099
        // Refs: https://github.com/nodejs/node/issues/18897
2100
1073365
        obj->persistent_handle_.Reset();
2101

1073365
        CHECK_IMPLIES(obj->has_pointer_data(),
2102
                      obj->pointer_data()->strong_ptr_count == 0);
2103
1073365
        obj->OnGCCollect();
2104
1073365
      },
2105
      WeakCallbackType::kParameter);
2106
}
2107
2108
// This just has to be different from the Chromium ones:
2109
// https://source.chromium.org/chromium/chromium/src/+/main:gin/public/gin_embedders.h;l=18-23;drc=5a758a97032f0b656c3c36a3497560762495501a
2110
// Otherwise, when Node is loaded in an isolate which uses cppgc, cppgc will
2111
// misinterpret the data stored in the embedder fields and try to garbage
2112
// collect them.
2113
uint16_t kNodeEmbedderId = 0x90de;
2114
2115
23696
void BaseObject::LazilyInitializedJSTemplateConstructor(
2116
    const FunctionCallbackInfo<Value>& args) {
2117
  DCHECK(args.IsConstructCall());
2118
23696
  CHECK_GE(args.This()->InternalFieldCount(), BaseObject::kInternalFieldCount);
2119
23696
  args.This()->SetAlignedPointerInInternalField(BaseObject::kEmbedderType,
2120
                                                &kNodeEmbedderId);
2121
23696
  args.This()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
2122
23696
}
2123
2124
21544
Local<FunctionTemplate> BaseObject::MakeLazilyInitializedJSTemplate(
2125
    Environment* env) {
2126
  Local<FunctionTemplate> t = NewFunctionTemplate(
2127
21544
      env->isolate(), LazilyInitializedJSTemplateConstructor);
2128
21544
  t->Inherit(BaseObject::GetConstructorTemplate(env));
2129
43088
  t->InstanceTemplate()->SetInternalFieldCount(BaseObject::kInternalFieldCount);
2130
21544
  return t;
2131
}
2132
2133
2897394
BaseObject::PointerData* BaseObject::pointer_data() {
2134
2897394
  if (!has_pointer_data()) {
2135
185707
    PointerData* metadata = new PointerData();
2136
185707
    metadata->wants_weak_jsobj = persistent_handle_.IsWeak();
2137
185707
    metadata->self = this;
2138
185707
    pointer_data_ = metadata;
2139
  }
2140
2897394
  CHECK(has_pointer_data());
2141
2897394
  return pointer_data_;
2142
}
2143
2144
744352
void BaseObject::decrease_refcount() {
2145
744352
  CHECK(has_pointer_data());
2146
744352
  PointerData* metadata = pointer_data();
2147
744352
  CHECK_GT(metadata->strong_ptr_count, 0);
2148
744352
  unsigned int new_refcount = --metadata->strong_ptr_count;
2149
744352
  if (new_refcount == 0) {
2150
250648
    if (metadata->is_detached) {
2151
177418
      OnGCCollect();
2152

73230
    } else if (metadata->wants_weak_jsobj && !persistent_handle_.IsEmpty()) {
2153
42674
      MakeWeak();
2154
    }
2155
  }
2156
744352
}
2157
2158
746788
void BaseObject::increase_refcount() {
2159
746788
  unsigned int prev_refcount = pointer_data()->strong_ptr_count++;
2160

746788
  if (prev_refcount == 0 && !persistent_handle_.IsEmpty())
2161
252962
    persistent_handle_.ClearWeak();
2162
746788
}
2163
2164
169530
void BaseObject::DeleteMe(void* data) {
2165
169530
  BaseObject* self = static_cast<BaseObject*>(data);
2166

174479
  if (self->has_pointer_data() &&
2167
4949
      self->pointer_data()->strong_ptr_count > 0) {
2168
824
    return self->Detach();
2169
  }
2170
168706
  delete self;
2171
}
2172
2173
576
bool BaseObject::IsDoneInitializing() const { return true; }
2174
2175
632
Local<Object> BaseObject::WrappedObject() const {
2176
632
  return object();
2177
}
2178
2179
1264
bool BaseObject::IsRootNode() const {
2180
2528
  return !persistent_handle_.IsWeak();
2181
}
2182
2183
55652
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
2184
55652
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
2185
55652
  if (tmpl.IsEmpty()) {
2186
779
    tmpl = NewFunctionTemplate(env->isolate(), nullptr);
2187
779
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
2188
779
    env->set_base_object_ctor_template(tmpl);
2189
  }
2190
55652
  return tmpl;
2191
}
2192
2193
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
2194
  return IsWeakOrDetached();
2195
}
2196
2197
}  // namespace node