GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.cc Lines: 979 1064 92.0 %
Date: 2022-08-28 04:20:35 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
814189
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
814189
  if (fields_[kCheck] > 0) {
94
814185
    CHECK_GE(async_id, -1);
95
814185
    CHECK_GE(trigger_async_id, -1);
96
  }
97
98
814189
  uint32_t offset = fields_[kStackLength];
99
814189
  if (offset * 2 >= async_ids_stack_.Length()) grow_async_ids_stack();
100
814189
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
101
814189
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
102
814189
  fields_[kStackLength] += 1;
103
814189
  async_id_fields_[kExecutionAsyncId] = async_id;
104
814189
  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
814189
  if (!resource.IsEmpty()) {
114
814185
    native_execution_async_resources_.resize(offset + 1);
115
    // Caveat: This is a v8::Local<> assignment, we do not keep a v8::Global<>!
116
814185
    native_execution_async_resources_[offset] = resource;
117
  }
118
814189
}
119
120
// Remember to keep this code aligned with popAsyncContext() in JS.
121
813798
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
813798
  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
1625484
  if (UNLIKELY(fields_[kCheck] > 0 &&
129

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

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

1074472
            native_execution_async_resources_.capacity() / 2 &&
149
261732
        native_execution_async_resources_.size() > 16) {
150
      native_execution_async_resources_.shrink_to_fit();
151
    }
152
  }
153
154
1625480
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
155
28957
    HandleScope handle_scope(env()->isolate());
156
57914
    USE(js_execution_async_resources()->Set(
157
        env()->context(),
158
        env()->length_string(),
159
115828
        Integer::NewFromUnsigned(env()->isolate(), offset)));
160
  }
161
162
812740
  return fields_[kStackLength] > 0;
163
}
164
165
2317
void AsyncHooks::clear_async_id_stack() {
166
2317
  Isolate* isolate = env()->isolate();
167
2317
  HandleScope handle_scope(isolate);
168
2317
  if (!js_execution_async_resources_.IsEmpty()) {
169
3084
    USE(PersistentToLocal::Strong(js_execution_async_resources_)
170
3084
            ->Set(env()->context(),
171
                  env()->length_string(),
172
6168
                  Integer::NewFromUnsigned(isolate, 0)));
173
  }
174
2317
  native_execution_async_resources_.clear();
175
2317
  native_execution_async_resources_.shrink_to_fit();
176
177
2317
  async_id_fields_[kExecutionAsyncId] = 0;
178
2317
  async_id_fields_[kTriggerAsyncId] = 0;
179
2317
  fields_[kStackLength] = 0;
180
2317
}
181
182
6756
void AsyncHooks::AddContext(Local<Context> ctx) {
183
20268
  ctx->SetPromiseHooks(js_promise_hooks_[0].IsEmpty()
184
6756
                           ? Local<Function>()
185
205
                           : PersistentToLocal::Strong(js_promise_hooks_[0]),
186
6756
                       js_promise_hooks_[1].IsEmpty()
187
6756
                           ? Local<Function>()
188
205
                           : PersistentToLocal::Strong(js_promise_hooks_[1]),
189
6756
                       js_promise_hooks_[2].IsEmpty()
190
6756
                           ? Local<Function>()
191
205
                           : PersistentToLocal::Strong(js_promise_hooks_[2]),
192
6756
                       js_promise_hooks_[3].IsEmpty()
193
6756
                           ? Local<Function>()
194
                           : PersistentToLocal::Strong(js_promise_hooks_[3]));
195
196
6756
  size_t id = contexts_.size();
197
6756
  contexts_.resize(id + 1);
198
6756
  contexts_[id].Reset(env()->isolate(), ctx);
199
6756
  contexts_[id].SetWeak();
200
6756
}
201
202
497
void AsyncHooks::RemoveContext(Local<Context> ctx) {
203
497
  Isolate* isolate = env()->isolate();
204
994
  HandleScope handle_scope(isolate);
205
497
  contexts_.erase(std::remove_if(contexts_.begin(),
206
                                 contexts_.end(),
207
3607
                                 [&](auto&& el) { return el.IsEmpty(); }),
208
994
                  contexts_.end());
209
3545
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
210
3048
    Local<Context> saved_context = PersistentToLocal::Weak(isolate, *it);
211
3048
    if (saved_context == ctx) {
212
      it->Reset();
213
      contexts_.erase(it);
214
      break;
215
    }
216
  }
217
497
}
218
219
239271
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
220
239271
    Environment* env, double default_trigger_async_id)
221
239271
    : async_hooks_(env->async_hooks()) {
222
239271
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
223
239271
    CHECK_GE(default_trigger_async_id, 0);
224
  }
225
226
239271
  old_default_trigger_async_id_ =
227
239271
      async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
228
239271
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
229
239271
      default_trigger_async_id;
230
239271
}
231
232
478540
AsyncHooks::DefaultTriggerAsyncIdScope::~DefaultTriggerAsyncIdScope() {
233
239270
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
234
239270
      old_default_trigger_async_id_;
235
239270
}
236
237
239271
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
238
239271
    AsyncWrap* async_wrap)
239
    : DefaultTriggerAsyncIdScope(async_wrap->env(),
240
239271
                                 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
5371
void IsolateData::DeserializeProperties(const IsolateDataSerializeInfo* info) {
323
5371
  size_t i = 0;
324
5371
  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




102049
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
341






134275
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
342










































































































































2970163
  PER_ISOLATE_STRING_PROPERTIES(VS)
343
#undef V
344
#undef VY
345
#undef VS
346
#undef VP
347
348
316889
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
349
    MaybeLocal<String> maybe_field =
350
623036
        isolate_->GetDataFromSnapshotOnce<String>(info->primitive_values[i++]);
351
    Local<String> field;
352
311518
    if (!maybe_field.ToLocal(&field)) {
353
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
354
    }
355
311518
    async_wrap_providers_[j].Set(isolate_, field);
356
  }
357
358
5371
  const std::vector<PropInfo>& values = info->template_values;
359
5371
  i = 0;  // index to the array
360
5371
  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










































































220211
  PER_ISOLATE_TEMPLATE_PROPERTIES(V);
381
#undef V
382
5371
}
383
384
786
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
1572
  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
7860
  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
10218
  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
217722
  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
46374
  NODE_ASYNC_PROVIDER_TYPES(V)
445
#undef V
446
447
  // TODO(legendecas): eagerly create per isolate templates.
448
786
  set_contextify_global_template(
449
786
      contextify::ContextifyContext::CreateGlobalTemplate(isolate_));
450
786
}
451
452
6157
IsolateData::IsolateData(Isolate* isolate,
453
                         uv_loop_t* event_loop,
454
                         MultiIsolatePlatform* platform,
455
                         ArrayBufferAllocator* node_allocator,
456
6157
                         const IsolateDataSerializeInfo* isolate_data_info)
457
    : isolate_(isolate),
458
      event_loop_(event_loop),
459
50
      node_allocator_(node_allocator == nullptr ? nullptr
460
6107
                                                : node_allocator->GetImpl()),
461
12314
      platform_(platform) {
462
6157
  options_.reset(
463
6157
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
464
465
6157
  if (isolate_data_info == nullptr) {
466
786
    CreateProperties();
467
  } else {
468
5371
    DeserializeProperties(isolate_data_info);
469
  }
470
6157
}
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
123
void TrackingTraceStateObserver::UpdateTraceCategoryState() {
492

123
  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
65
    return;
500
  }
501
502
112
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
503
112
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
504
505
112
  Isolate* isolate = env_->isolate();
506
112
  HandleScope handle_scope(isolate);
507
112
  Local<Function> cb = env_->trace_category_state_function();
508
112
  if (cb.IsEmpty())
509
54
    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
6756
void Environment::AssignToContext(Local<v8::Context> context,
517
                                  const ContextInfo& info) {
518
6756
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
519
                                           this);
520
  // Used to retrieve bindings
521
13512
  context->SetAlignedPointerInEmbedderData(
522
6756
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
523
524
  // ContextifyContexts will update this to a pointer to the native object.
525
6756
  context->SetAlignedPointerInEmbedderData(
526
      ContextEmbedderIndex::kContextifyContext, nullptr);
527
528
  // This must not be done before other context fields are initialized.
529
6756
  ContextEmbedderTag::TagNodeContext(context);
530
531
#if HAVE_INSPECTOR
532
6756
  inspector_agent()->ContextCreated(context, info);
533
#endif  // HAVE_INSPECTOR
534
535
6756
  this->async_hooks()->AddContext(context);
536
6756
}
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
1899
void Environment::add_refs(int64_t diff) {
565
1899
  task_queues_async_refs_ += diff;
566
1899
  CHECK_GE(task_queues_async_refs_, 0);
567
1899
  if (task_queues_async_refs_ == 0)
568
419
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
569
  else
570
1480
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
571
1899
}
572
573
66196
uv_buf_t Environment::allocate_managed_buffer(const size_t suggested_size) {
574
132392
  NoArrayBufferZeroFillScope no_zero_fill_scope(isolate_data());
575
  std::unique_ptr<v8::BackingStore> bs =
576
66196
      v8::ArrayBuffer::NewBackingStore(isolate(), suggested_size);
577
66196
  uv_buf_t buf = uv_buf_init(static_cast<char*>(bs->Data()), bs->ByteLength());
578
66196
  released_allocated_buffers_.emplace(buf.base, std::move(bs));
579
66196
  return buf;
580
}
581
582
81161
std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer(
583
    const uv_buf_t& buf) {
584
81161
  std::unique_ptr<v8::BackingStore> bs;
585
81161
  if (buf.base != nullptr) {
586
66196
    auto it = released_allocated_buffers_.find(buf.base);
587
66196
    CHECK_NE(it, released_allocated_buffers_.end());
588
66196
    bs = std::move(it->second);
589
66196
    released_allocated_buffers_.erase(it);
590
  }
591
81161
  return bs;
592
}
593
594
775
void Environment::CreateProperties() {
595
1550
  HandleScope handle_scope(isolate_);
596
775
  Local<Context> ctx = context();
597
598
  {
599
775
    Context::Scope context_scope(ctx);
600
775
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
601
1550
    templ->InstanceTemplate()->SetInternalFieldCount(
602
        BaseObject::kInternalFieldCount);
603
775
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
604
605
775
    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
1550
      GetPerContextExports(ctx).ToLocalChecked();
611
  Local<Value> primordials =
612
2325
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
613
775
  CHECK(primordials->IsObject());
614
775
  set_primordials(primordials.As<Object>());
615
616
  Local<String> prototype_string =
617
775
      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

4650
  V(primordials_safe_map_prototype_object, "SafeMap");
634

4650
  V(primordials_safe_set_prototype_object, "SafeSet");
635

4650
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
636

4650
  V(primordials_safe_weak_set_prototype_object, "SafeWeakSet");
637
#undef V
638
639
  Local<Object> process_object =
640
775
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
641
775
  set_process_object(process_object);
642
775
}
643
644
6146
std::string GetExecPath(const std::vector<std::string>& argv) {
645
  char exec_path_buf[2 * PATH_MAX];
646
6146
  size_t exec_path_len = sizeof(exec_path_buf);
647
6146
  std::string exec_path;
648
6146
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
649
6146
    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
6146
  return exec_path;
668
}
669
670
6146
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
6146
                         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
6146
      timer_base_(uv_now(isolate_data->event_loop())),
683
      exec_argv_(exec_args),
684
      argv_(args),
685
      exec_path_(GetExecPath(args)),
686
6146
      exiting_(isolate_, 1, MAYBE_FIELD_PTR(env_info, exiting)),
687
      should_abort_on_uncaught_toggle_(
688
6146
          isolate_,
689
          1,
690
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
691
6146
      stream_base_state_(isolate_,
692
                         StreamBase::kNumStreamBaseStateFields,
693
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
694
6146
      time_origin_(PERFORMANCE_NOW()),
695
6146
      time_origin_timestamp_(GetCurrentTimeInMicroseconds()),
696
      flags_(flags),
697
6146
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
698
6146
                     ? AllocateEnvironmentThreadId().id
699



24584
                     : thread_id.id) {
700
  // We'll be creating new objects so make sure we've entered the context.
701
12292
  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
6146
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
706
10854
    flags_ = flags_ |
707
5427
        EnvironmentFlags::kOwnsProcessState |
708
        EnvironmentFlags::kOwnsInspector;
709
  }
710
711
6146
  set_env_vars(per_process::system_environment);
712
6146
  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
12292
  options_ = std::make_shared<EnvironmentOptions>(
719
18438
      *isolate_data->options()->per_env);
720
6146
  inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
721
6146
      options_->debug_options().host_port);
722
723
6146
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
724
719
    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
6146
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
730
#endif
731
732
6146
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
733
6146
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
734
6146
    if (TracingController* tracing_controller = writer->GetTracingController())
735
6096
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
736
  }
737
738
6146
  destroy_async_id_list_.reserve(512);
739
740
6146
  performance_state_ = std::make_unique<performance::PerformanceState>(
741
6146
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
742
743
6146
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
744
6146
          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
6146
}
759
760
775
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
775
                         ThreadId thread_id)
767
    : Environment(isolate_data,
768
                  context->GetIsolate(),
769
                  args,
770
                  exec_args,
771
                  env_info,
772
                  flags,
773
775
                  thread_id) {
774
775
  InitializeMainContext(context, env_info);
775
775
}
776
777
6146
void Environment::InitializeMainContext(Local<Context> context,
778
                                        const EnvSerializeInfo* env_info) {
779
6146
  context_.Reset(context->GetIsolate(), context);
780
6146
  AssignToContext(context, ContextInfo(""));
781
6146
  if (env_info != nullptr) {
782
5371
    DeserializeProperties(env_info);
783
  } else {
784
775
    CreateProperties();
785
  }
786
787
6146
  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
6146
  should_abort_on_uncaught_toggle_[0] = 1;
793
794
  // The process is not exiting by default.
795
6146
  set_exiting(false);
796
797
6146
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
798
                           time_origin_);
799
6146
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
800
                           per_process::node_start_time);
801
802
6146
  if (per_process::v8_initialized) {
803
6103
    performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
804
                            performance::performance_v8_start);
805
  }
806
6146
}
807
808
738408
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
5594
  CHECK(is_stopping());
836
837
5594
  if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
838
    isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
839
                                          0);
840
  }
841
842
5594
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
843
      BuildEmbedderGraph, this);
844
845
11188
  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
5594
  inspector_agent_.reset();
851
#endif
852
853
11188
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
854
                                             nullptr);
855
856
5594
  if (trace_state_observer_) {
857
5594
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
858
5594
    CHECK_NOT_NULL(writer);
859
5594
    if (TracingController* tracing_controller = writer->GetTracingController())
860
5546
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
861
  }
862
863

10439
  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
5594
  if (!is_main_thread()) {
872
    // Dereference all addons that were loaded into this environment.
873
730
    for (binding::DLib& addon : loaded_addons_) {
874
14
      addon.Close();
875
    }
876
  }
877
878
5594
  CHECK_EQ(base_object_count_, 0);
879
5594
}
880
881
6112
void Environment::InitializeLibuv() {
882
12224
  HandleScope handle_scope(isolate());
883
6112
  Context::Scope context_scope(context());
884
885
6112
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
886
6112
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
887
888
6112
  CHECK_EQ(0, uv_check_init(event_loop(), immediate_check_handle()));
889
6112
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
890
891
6112
  CHECK_EQ(0, uv_idle_init(event_loop(), immediate_idle_handle()));
892
893
6112
  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
6112
  CHECK_EQ(0, uv_prepare_init(event_loop(), &idle_prepare_handle_));
900
6112
  CHECK_EQ(0, uv_check_init(event_loop(), &idle_check_handle_));
901
902
25033
  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
6112
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
913
6112
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
914
6112
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
915
916
  {
917
12224
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
918
6112
    task_queues_async_initialized_ = true;
919

12224
    if (native_immediates_threadsafe_.size() > 0 ||
920
6112
        native_immediates_interrupts_.size() > 0) {
921
5367
      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
6112
  RegisterHandleCleanups();
930
931
6112
  StartProfilerIdleNotifier();
932
6112
}
933
934
364
void Environment::ExitEnv() {
935
364
  set_can_call_into_js(false);
936
364
  set_stopping(true);
937
364
  isolate_->TerminateExecution();
938
728
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
939
364
}
940
941
6112
void Environment::RegisterHandleCleanups() {
942
6112
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
943
33360
                                        void* arg) {
944
33360
    handle->data = env;
945
946
33360
    env->CloseHandle(handle, [](uv_handle_t* handle) {
947
#ifdef DEBUG
948
      memset(handle, 0xab, uv_handle_size(handle->type));
949
#endif
950
33360
    });
951
33360
  };
952
953
36672
  auto register_handle = [&](uv_handle_t* handle) {
954
36672
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
955
42784
  };
956
6112
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
957
6112
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
958
6112
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
959
6112
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
960
6112
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
961
6112
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
962
6112
}
963
964
11181
void Environment::CleanupHandles() {
965
  {
966
11181
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
967
11181
    task_queues_async_initialized_ = false;
968
  }
969
970
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
971
22362
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
972
973
11181
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
974
975
11340
  for (ReqWrapBase* request : req_wrap_queue_)
976
159
    request->Cancel();
977
978
15487
  for (HandleWrap* handle : handle_wrap_queue_)
979
8612
    handle->Close();
980
981
44541
  for (HandleCleanup& hc : handle_cleanup_queue_)
982
33360
    hc.cb_(this, hc.handle_, hc.arg_);
983
11181
  handle_cleanup_queue_.clear();
984
985
10487
  while (handle_cleanup_waiting_ != 0 ||
986

32851
         request_waiting_ != 0 ||
987
11183
         !handle_wrap_queue_.IsEmpty()) {
988
10487
    uv_run(event_loop(), UV_RUN_ONCE);
989
  }
990
11181
}
991
992
6112
void Environment::StartProfilerIdleNotifier() {
993
6112
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
994
200829
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
995
200829
    env->isolate()->SetIdle(true);
996
200829
  });
997
6112
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
998
200636
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
999
200636
    env->isolate()->SetIdle(false);
1000
200636
  });
1001
6112
}
1002
1003
736175
void Environment::PrintSyncTrace() const {
1004
736175
  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
5242
MaybeLocal<Value> Environment::RunSnapshotSerializeCallback() const {
1016
5242
  EscapableHandleScope handle_scope(isolate());
1017
10484
  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
10484
  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
5594
void Environment::RunCleanup() {
1036
5594
  started_cleanup_ = true;
1037

16032
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunCleanup");
1038
5594
  bindings_.clear();
1039
5594
  CleanupHandles();
1040
1041
16777
  while (!cleanup_hooks_.empty() ||
1042
11190
         native_immediates_.size() > 0 ||
1043

22371
         native_immediates_threadsafe_.size() > 0 ||
1044
5594
         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
11174
        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
5587
    std::sort(callbacks.begin(), callbacks.end(),
1052
1221386
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
1053
      // Sort in descending order so that the most recently inserted callbacks
1054
      // are run first.
1055
1221386
      return a.insertion_order_counter_ > b.insertion_order_counter_;
1056
    });
1057
1058
183136
    for (const CleanupHookCallback& cb : callbacks) {
1059
177549
      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
1019
        continue;
1063
      }
1064
1065
176530
      cb.fn_(cb.arg_);
1066
176530
      cleanup_hooks_.erase(cb);
1067
    }
1068
5587
    CleanupHandles();
1069
  }
1070
1071
5597
  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
5594
}
1077
1078
6221
void Environment::RunAtExitCallbacks() {
1079

17818
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "AtExit");
1080
18479
  for (ExitCallback at_exit : at_exit_functions_) {
1081
12258
    at_exit.cb_(at_exit.arg_);
1082
  }
1083
6221
  at_exit_functions_.clear();
1084
6221
}
1085
1086
12282
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
1087
12282
  at_exit_functions_.push_front(ExitCallback{cb, arg});
1088
12282
}
1089
1090
238890
void Environment::RunAndClearInterrupts() {
1091
238890
  while (native_immediates_interrupts_.size() > 0) {
1092
10524
    NativeImmediateQueue queue;
1093
    {
1094
21048
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1095
10524
      queue.ConcatMove(std::move(native_immediates_interrupts_));
1096
    }
1097
10524
    DebugSealHandleScope seal_handle_scope(isolate());
1098
1099
21056
    while (auto head = queue.Shift())
1100
21064
      head->Call(this);
1101
  }
1102
228366
}
1103
1104
218126
void Environment::RunAndClearNativeImmediates(bool only_refed) {
1105

441308
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment),
1106
               "RunAndClearNativeImmediates");
1107
436246
  HandleScope handle_scope(isolate_);
1108
436246
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
1109
1110
218126
  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
218126
  RunAndClearInterrupts();
1115
1116
436250
  auto drain_list = [&](NativeImmediateQueue* queue) {
1117
872494
    TryCatchScope try_catch(this);
1118
436250
    DebugSealHandleScope seal_handle_scope(isolate());
1119
496329
    while (auto head = queue->Shift()) {
1120
60086
      bool is_refed = head->flags() & CallbackFlags::kRefed;
1121
60086
      if (is_refed)
1122
35166
        ref_count++;
1123
1124

60086
      if (is_refed || !only_refed)
1125
59837
        head->Call(this);
1126
1127
60081
      head.reset();  // Destroy now so that this is also observed by try_catch.
1128
1129
60081
      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
60079
    }
1136
436243
    return false;
1137
218126
  };
1138
218126
  while (drain_list(&native_immediates_)) {}
1139
1140
218123
  immediate_info()->ref_count_dec(ref_count);
1141
1142
218123
  if (immediate_info()->ref_count() == 0)
1143
175244
    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
218120
  NativeImmediateQueue threadsafe_immediates;
1153
218123
  if (native_immediates_threadsafe_.size() > 0) {
1154
2152
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1155
1076
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
1156
  }
1157
218124
  while (drain_list(&threadsafe_immediates)) {}
1158
218120
}
1159
1160
10537
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
10537
  Environment** interrupt_data = new Environment*(this);
1173
10537
  Environment** dummy = nullptr;
1174
10537
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
1175
394
    delete interrupt_data;
1176
394
    return;  // Already scheduled.
1177
  }
1178
1179
10143
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
1180
10134
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
1181
10134
    Environment* env = *env_ptr;
1182
10134
    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
10124
    env->interrupt_data_.store(nullptr);
1189
10124
    env->RunAndClearInterrupts();
1190
  }, interrupt_data);
1191
}
1192
1193
9343
void Environment::ScheduleTimer(int64_t duration_ms) {
1194
9343
  if (started_cleanup_) return;
1195
9343
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
1196
}
1197
1198
3745
void Environment::ToggleTimerRef(bool ref) {
1199
3745
  if (started_cleanup_) return;
1200
1201
3745
  if (ref) {
1202
2475
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1203
  } else {
1204
1270
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1205
  }
1206
}
1207
1208
7340
void Environment::RunTimers(uv_timer_t* handle) {
1209
7340
  Environment* env = Environment::from_timer_handle(handle);
1210

7855
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunTimers");
1211
1212
7340
  if (!env->can_call_into_js())
1213
    return;
1214
1215
7340
  HandleScope handle_scope(env->isolate());
1216
7340
  Context::Scope context_scope(env->context());
1217
1218
7340
  Local<Object> process = env->process_object();
1219
7340
  InternalCallbackScope scope(env, process, {0, 0});
1220
1221
7340
  Local<Function> cb = env->timers_callback_function();
1222
  MaybeLocal<Value> ret;
1223
7340
  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
7373
    TryCatchScope try_catch(env);
1229
7373
    try_catch.SetVerbose(true);
1230
7373
    ret = cb->Call(env->context(), process, 1, &arg);
1231

7363
  } 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
7330
  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
7324
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
1250
1251
7324
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
1252
1253
7324
  if (expiry_ms != 0) {
1254
    int64_t duration_ms =
1255
6304
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
1256
1257
6304
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
1258
1259
6304
    if (expiry_ms > 0)
1260
5607
      uv_ref(h);
1261
    else
1262
697
      uv_unref(h);
1263
  } else {
1264
1020
    uv_unref(h);
1265
  }
1266
}
1267
1268
1269
200636
void Environment::CheckImmediate(uv_check_t* handle) {
1270
200636
  Environment* env = Environment::from_immediate_check_handle(handle);
1271

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

200636
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
1279
158330
    return;
1280
1281
951
  do {
1282
43249
    MakeCallback(env->isolate(),
1283
                 env->process_object(),
1284
                 env->immediate_callback_function(),
1285
                 0,
1286
                 nullptr,
1287
43257
                 {0, 0}).ToLocalChecked();
1288

43249
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
1289
1290
42298
  if (env->immediate_info()->ref_count() == 0)
1291
4700
    env->ToggleImmediateRef(false);
1292
}
1293
1294
245698
void Environment::ToggleImmediateRef(bool ref) {
1295
245698
  if (started_cleanup_) return;
1296
1297
234596
  if (ref) {
1298
    // Idle handle is needed only to stop the event loop from blocking in poll.
1299
65730
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
1300
  } else {
1301
168866
    uv_idle_stop(immediate_idle_handle());
1302
  }
1303
}
1304
1305
1306
46972
Local<Value> Environment::GetNow() {
1307
46972
  uv_update_time(event_loop());
1308
46972
  uint64_t now = uv_now(event_loop());
1309
46972
  CHECK_GE(now, timer_base());
1310
46972
  now -= timer_base();
1311
46972
  if (now <= 0xffffffff)
1312
93944
    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
6146
ImmediateInfo::ImmediateInfo(Isolate* isolate, const SerializeInfo* info)
1378
6146
    : 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
5371
void ImmediateInfo::Deserialize(Local<Context> context) {
1386
5371
  fields_.Deserialize(context);
1387
5371
}
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
5371
void TickInfo::Deserialize(Local<Context> context) {
1405
5371
  fields_.Deserialize(context);
1406
5371
}
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
6146
TickInfo::TickInfo(Isolate* isolate, const SerializeInfo* info)
1419
    : fields_(
1420
6146
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1421
1422
6146
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

6146
      info_(info) {
1428
12292
  HandleScope handle_scope(isolate);
1429
6146
  if (info == nullptr) {
1430
775
    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
775
    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
775
    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
775
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1448
  }
1449
6146
}
1450
1451
5371
void AsyncHooks::Deserialize(Local<Context> context) {
1452
5371
  async_ids_stack_.Deserialize(context);
1453
5371
  fields_.Deserialize(context);
1454
5371
  async_id_fields_.Deserialize(context);
1455
1456
  Local<Array> js_execution_async_resources;
1457
5371
  if (info_->js_execution_async_resources != 0) {
1458
    js_execution_async_resources =
1459
5371
        context->GetDataFromSnapshotOnce<Array>(
1460
16113
            info_->js_execution_async_resources).ToLocalChecked();
1461
  } else {
1462
    js_execution_async_resources = Array::New(context->GetIsolate());
1463
  }
1464
5371
  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
5371
  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
5371
  info_ = nullptr;
1480
5371
}
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
610
void Environment::Exit(int exit_code) {
1562
610
  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
610
  process_exit_handler_(this, exit_code);
1581
63
}
1582
1583
6168
void Environment::stop_sub_worker_contexts() {
1584
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1585
1586
6168
  while (!sub_worker_contexts_.empty()) {
1587
27
    Worker* w = *sub_worker_contexts_.begin();
1588
27
    remove_sub_worker_context(w);
1589
27
    w->Exit(1);
1590
27
    w->JoinThread();
1591
  }
1592
6141
}
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
67201
void Environment::AddUnmanagedFd(int fd) {
1600
67201
  if (!tracks_unmanaged_fds()) return;
1601
2721
  auto result = unmanaged_fds_.insert(fd);
1602
2721
  if (!result.second) {
1603
    ProcessEmitWarning(
1604
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1605
  }
1606
}
1607
1608
66818
void Environment::RemoveUnmanagedFd(int fd) {
1609
66818
  if (!tracks_unmanaged_fds()) return;
1610
2718
  size_t removed_count = unmanaged_fds_.erase(fd);
1611
2718
  if (removed_count == 0) {
1612
    ProcessEmitWarning(
1613
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1614
  }
1615
}
1616
1617
5220
void Environment::PrintInfoForSnapshotIfDebug() {
1618
10440
  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
5220
}
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
5220
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
5220
  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
21484
void Environment::EnqueueDeserializeRequest(DeserializeRequestCallback cb,
1769
                                            Local<Object> holder,
1770
                                            int index,
1771
                                            InternalFieldInfoBase* info) {
1772
  DCHECK_EQ(index, BaseObject::kEmbedderType);
1773
42968
  DeserializeRequest request{cb, {isolate(), holder}, index, info};
1774
21484
  deserialize_requests_.push_back(std::move(request));
1775
21484
}
1776
1777
5371
void Environment::RunDeserializeRequests() {
1778
10742
  HandleScope scope(isolate());
1779
5371
  Local<Context> ctx = context();
1780
5371
  Isolate* is = isolate();
1781
26855
  while (!deserialize_requests_.empty()) {
1782
42968
    DeserializeRequest request(std::move(deserialize_requests_.front()));
1783
21484
    deserialize_requests_.pop_front();
1784
21484
    Local<Object> holder = request.holder.Get(is);
1785
21484
    request.cb(ctx, holder, request.index, request.info);
1786
    request.holder.Reset();
1787
21484
    request.info->Delete();
1788
  }
1789
5371
}
1790
1791
5371
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1792
5371
  Local<Context> ctx = context();
1793
1794
5371
  RunDeserializeRequests();
1795
1796
5371
  builtins_in_snapshot = info->builtins;
1797
5371
  async_hooks_.Deserialize(ctx);
1798
5371
  immediate_info_.Deserialize(ctx);
1799
5371
  tick_info_.Deserialize(ctx);
1800
5371
  performance_state_->Deserialize(ctx);
1801
5371
  exiting_.Deserialize(ctx);
1802
5371
  stream_base_state_.Deserialize(ctx);
1803
5371
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1804
1805
5371
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1806
    fprintf(stderr, "deserializing...\n");
1807
    std::cerr << *info << "\n";
1808
  }
1809
1810
5371
  const std::vector<PropInfo>& values = info->persistent_values;
1811
5371
  size_t i = 0;  // index to the array
1812
5371
  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






























































































































537100
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1833
#undef V
1834
1835
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1836
10742
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1837
  Local<Context> ctx_from_snapshot;
1838
5371
  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
5371
  CHECK_EQ(ctx_from_snapshot, ctx);
1843
5371
}
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
587
    if (obj->IsDoneInitializing())
1872
586
      tracker.Track(obj);
1873
587
  });
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
740139
void Environment::RunWeakRefCleanup() {
2048
740139
  isolate()->ClearKeptObjects();
2049
740139
}
2050
2051
// Not really any better place than env.cc at this moment.
2052
1443372
BaseObject::BaseObject(Environment* env, Local<Object> object)
2053
2886744
    : persistent_handle_(env->isolate(), object), env_(env) {
2054
1443372
  CHECK_EQ(false, object.IsEmpty());
2055
1443372
  CHECK_GE(object->InternalFieldCount(), BaseObject::kInternalFieldCount);
2056
1443372
  object->SetAlignedPointerInInternalField(BaseObject::kEmbedderType,
2057
                                           &kNodeEmbedderId);
2058
1443372
  object->SetAlignedPointerInInternalField(BaseObject::kSlot,
2059
                                           static_cast<void*>(this));
2060
1443372
  env->AddCleanupHook(DeleteMe, static_cast<void*>(this));
2061
1443372
  env->modify_base_object_count(1);
2062
1443372
}
2063
2064

7871072
BaseObject::~BaseObject() {
2065
2862202
  env()->modify_base_object_count(-1);
2066
2862202
  env()->RemoveCleanupHook(DeleteMe, static_cast<void*>(this));
2067
2068
2862202
  if (UNLIKELY(has_pointer_data())) {
2069
366050
    PointerData* metadata = pointer_data();
2070
366050
    CHECK_EQ(metadata->strong_ptr_count, 0);
2071
366050
    metadata->self = nullptr;
2072
366050
    if (metadata->weak_ptr_count == 0) delete metadata;
2073
  }
2074
2075
2862202
  if (persistent_handle_.IsEmpty()) {
2076
    // This most likely happened because the weak callback below cleared it.
2077
2146668
    return;
2078
  }
2079
2080
  {
2081
715534
    HandleScope handle_scope(env()->isolate());
2082
1431068
    object()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
2083
  }
2084
}
2085
2086
1231840
void BaseObject::MakeWeak() {
2087
1231840
  if (has_pointer_data()) {
2088
42709
    pointer_data()->wants_weak_jsobj = true;
2089
42709
    if (pointer_data()->strong_ptr_count > 0) return;
2090
  }
2091
2092
2463678
  persistent_handle_.SetWeak(
2093
      this,
2094
1073333
      [](const WeakCallbackInfo<BaseObject>& data) {
2095
1073333
        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
1073333
        obj->persistent_handle_.Reset();
2101

1073333
        CHECK_IMPLIES(obj->has_pointer_data(),
2102
                      obj->pointer_data()->strong_ptr_count == 0);
2103
1073333
        obj->OnGCCollect();
2104
1073333
      },
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
23717
void BaseObject::LazilyInitializedJSTemplateConstructor(
2116
    const FunctionCallbackInfo<Value>& args) {
2117
  DCHECK(args.IsConstructCall());
2118
23717
  CHECK_GE(args.This()->InternalFieldCount(), BaseObject::kInternalFieldCount);
2119
23717
  args.This()->SetAlignedPointerInInternalField(BaseObject::kEmbedderType,
2120
                                                &kNodeEmbedderId);
2121
23717
  args.This()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
2122
23717
}
2123
2124
21425
Local<FunctionTemplate> BaseObject::MakeLazilyInitializedJSTemplate(
2125
    Environment* env) {
2126
  Local<FunctionTemplate> t = NewFunctionTemplate(
2127
21425
      env->isolate(), LazilyInitializedJSTemplateConstructor);
2128
21425
  t->Inherit(BaseObject::GetConstructorTemplate(env));
2129
42850
  t->InstanceTemplate()->SetInternalFieldCount(BaseObject::kInternalFieldCount);
2130
21425
  return t;
2131
}
2132
2133
2895259
BaseObject::PointerData* BaseObject::pointer_data() {
2134
2895259
  if (!has_pointer_data()) {
2135
185346
    PointerData* metadata = new PointerData();
2136
185346
    metadata->wants_weak_jsobj = persistent_handle_.IsWeak();
2137
185346
    metadata->self = this;
2138
185346
    pointer_data_ = metadata;
2139
  }
2140
2895259
  CHECK(has_pointer_data());
2141
2895259
  return pointer_data_;
2142
}
2143
2144
743979
void BaseObject::decrease_refcount() {
2145
743979
  CHECK(has_pointer_data());
2146
743979
  PointerData* metadata = pointer_data();
2147
743979
  CHECK_GT(metadata->strong_ptr_count, 0);
2148
743979
  unsigned int new_refcount = --metadata->strong_ptr_count;
2149
743979
  if (new_refcount == 0) {
2150
250244
    if (metadata->is_detached) {
2151
177066
      OnGCCollect();
2152

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

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

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