GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.cc Lines: 976 1061 92.0 %
Date: 2022-08-21 04:19:51 Branches: 1145 2112 54.2 %

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

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

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

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


















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




101650
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
340






133750
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
341









































































































































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








































































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

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

4650
  V(primordials_safe_map_prototype_object, "SafeMap");
625

4650
  V(primordials_safe_set_prototype_object, "SafeSet");
626

4650
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
627

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



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

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

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

12178
    if (native_immediates_threadsafe_.size() > 0 ||
911
6089
        native_immediates_interrupts_.size() > 0) {
912
5346
      uv_async_send(&task_queues_async_);
913
    }
914
  }
915
916
  // Register clean-up cb to be called to clean up the handles
917
  // when the environment is freed, note that they are not cleaned in
918
  // the one environment per process setup, but will be called in
919
  // FreeEnvironment.
920
6089
  RegisterHandleCleanups();
921
922
6089
  StartProfilerIdleNotifier();
923
6089
}
924
925
377
void Environment::ExitEnv() {
926
377
  set_can_call_into_js(false);
927
377
  set_stopping(true);
928
377
  isolate_->TerminateExecution();
929
754
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
930
377
}
931
932
6089
void Environment::RegisterHandleCleanups() {
933
6089
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
934
33246
                                        void* arg) {
935
33246
    handle->data = env;
936
937
33246
    env->CloseHandle(handle, [](uv_handle_t* handle) {
938
#ifdef DEBUG
939
      memset(handle, 0xab, uv_handle_size(handle->type));
940
#endif
941
33246
    });
942
33246
  };
943
944
36534
  auto register_handle = [&](uv_handle_t* handle) {
945
36534
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
946
42623
  };
947
6089
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
948
6089
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
949
6089
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
950
6089
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
951
6089
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
952
6089
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
953
6089
}
954
955
11145
void Environment::CleanupHandles() {
956
  {
957
11145
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
958
11145
    task_queues_async_initialized_ = false;
959
  }
960
961
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
962
22290
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
963
964
11145
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
965
966
11308
  for (ReqWrapBase* request : req_wrap_queue_)
967
163
    request->Cancel();
968
969
15437
  for (HandleWrap* handle : handle_wrap_queue_)
970
8584
    handle->Close();
971
972
44391
  for (HandleCleanup& hc : handle_cleanup_queue_)
973
33246
    hc.cb_(this, hc.handle_, hc.arg_);
974
11145
  handle_cleanup_queue_.clear();
975
976
10462
  while (handle_cleanup_waiting_ != 0 ||
977

32754
         request_waiting_ != 0 ||
978
11147
         !handle_wrap_queue_.IsEmpty()) {
979
10462
    uv_run(event_loop(), UV_RUN_ONCE);
980
  }
981
11145
}
982
983
6089
void Environment::StartProfilerIdleNotifier() {
984
6089
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
985
202298
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
986
202298
    env->isolate()->SetIdle(true);
987
202298
  });
988
6089
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
989
202105
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
990
202105
    env->isolate()->SetIdle(false);
991
202105
  });
992
6089
}
993
994
737208
void Environment::PrintSyncTrace() const {
995
737208
  if (!trace_sync_io_) return;
996
997
2
  HandleScope handle_scope(isolate());
998
999
1
  fprintf(
1000
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
1001
1
  PrintStackTrace(isolate(),
1002
                  StackTrace::CurrentStackTrace(
1003
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
1004
}
1005
1006
5221
MaybeLocal<Value> Environment::RunSnapshotSerializeCallback() const {
1007
5221
  EscapableHandleScope handle_scope(isolate());
1008
10442
  if (!snapshot_serialize_callback().IsEmpty()) {
1009
    Context::Scope context_scope(context());
1010
    return handle_scope.EscapeMaybe(snapshot_serialize_callback()->Call(
1011
        context(), v8::Undefined(isolate()), 0, nullptr));
1012
  }
1013
10442
  return handle_scope.Escape(Undefined(isolate()));
1014
}
1015
1016
MaybeLocal<Value> Environment::RunSnapshotDeserializeMain() const {
1017
  EscapableHandleScope handle_scope(isolate());
1018
  if (!snapshot_deserialize_main().IsEmpty()) {
1019
    Context::Scope context_scope(context());
1020
    return handle_scope.EscapeMaybe(snapshot_deserialize_main()->Call(
1021
        context(), v8::Undefined(isolate()), 0, nullptr));
1022
  }
1023
  return handle_scope.Escape(Undefined(isolate()));
1024
}
1025
1026
5577
void Environment::RunCleanup() {
1027
5577
  started_cleanup_ = true;
1028

15981
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunCleanup");
1029
5577
  bindings_.clear();
1030
5577
  CleanupHandles();
1031
1032
16724
  while (!cleanup_hooks_.empty() ||
1033
11156
         native_immediates_.size() > 0 ||
1034

22301
         native_immediates_threadsafe_.size() > 0 ||
1035
5577
         native_immediates_interrupts_.size() > 0) {
1036
    // Copy into a vector, since we can't sort an unordered_set in-place.
1037
    std::vector<CleanupHookCallback> callbacks(
1038
11136
        cleanup_hooks_.begin(), cleanup_hooks_.end());
1039
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
1040
    // need to be able to check whether they were un-scheduled by another hook.
1041
1042
5568
    std::sort(callbacks.begin(), callbacks.end(),
1043
1270345
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
1044
      // Sort in descending order so that the most recently inserted callbacks
1045
      // are run first.
1046
1270345
      return a.insertion_order_counter_ > b.insertion_order_counter_;
1047
    });
1048
1049
186635
    for (const CleanupHookCallback& cb : callbacks) {
1050
181067
      if (cleanup_hooks_.count(cb) == 0) {
1051
        // This hook was removed from the `cleanup_hooks_` set during another
1052
        // hook that was run earlier. Nothing to do here.
1053
1018
        continue;
1054
      }
1055
1056
180049
      cb.fn_(cb.arg_);
1057
180049
      cleanup_hooks_.erase(cb);
1058
    }
1059
5568
    CleanupHandles();
1060
  }
1061
1062
5580
  for (const int fd : unmanaged_fds_) {
1063
    uv_fs_t close_req;
1064
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
1065
3
    uv_fs_req_cleanup(&close_req);
1066
  }
1067
5577
}
1068
1069
6200
void Environment::RunAtExitCallbacks() {
1070

17755
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "AtExit");
1071
18416
  for (ExitCallback at_exit : at_exit_functions_) {
1072
12216
    at_exit.cb_(at_exit.arg_);
1073
  }
1074
6200
  at_exit_functions_.clear();
1075
6200
}
1076
1077
12240
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
1078
12240
  at_exit_functions_.push_front(ExitCallback{cb, arg});
1079
12240
}
1080
1081
240274
void Environment::RunAndClearInterrupts() {
1082
240274
  while (native_immediates_interrupts_.size() > 0) {
1083
10505
    NativeImmediateQueue queue;
1084
    {
1085
21010
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1086
10505
      queue.ConcatMove(std::move(native_immediates_interrupts_));
1087
    }
1088
10505
    DebugSealHandleScope seal_handle_scope(isolate());
1089
1090
21019
    while (auto head = queue.Shift())
1091
21028
      head->Call(this);
1092
  }
1093
229769
}
1094
1095
219565
void Environment::RunAndClearNativeImmediates(bool only_refed) {
1096

444170
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment),
1097
               "RunAndClearNativeImmediates");
1098
439124
  HandleScope handle_scope(isolate_);
1099
439124
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
1100
1101
219565
  size_t ref_count = 0;
1102
1103
  // Handle interrupts first. These functions are not allowed to throw
1104
  // exceptions, so we do not need to handle that.
1105
219565
  RunAndClearInterrupts();
1106
1107
439128
  auto drain_list = [&](NativeImmediateQueue* queue) {
1108
878250
    TryCatchScope try_catch(this);
1109
439128
    DebugSealHandleScope seal_handle_scope(isolate());
1110
499179
    while (auto head = queue->Shift()) {
1111
60058
      bool is_refed = head->flags() & CallbackFlags::kRefed;
1112
60058
      if (is_refed)
1113
35140
        ref_count++;
1114
1115

60058
      if (is_refed || !only_refed)
1116
59813
        head->Call(this);
1117
1118
60053
      head.reset();  // Destroy now so that this is also observed by try_catch.
1119
1120
60053
      if (UNLIKELY(try_catch.HasCaught())) {
1121

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

9702
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunTimers");
1202
1203
9180
  if (!env->can_call_into_js())
1204
    return;
1205
1206
9180
  HandleScope handle_scope(env->isolate());
1207
9180
  Context::Scope context_scope(env->context());
1208
1209
9180
  Local<Object> process = env->process_object();
1210
9180
  InternalCallbackScope scope(env, process, {0, 0});
1211
1212
9180
  Local<Function> cb = env->timers_callback_function();
1213
  MaybeLocal<Value> ret;
1214
9180
  Local<Value> arg = env->GetNow();
1215
  // This code will loop until all currently due timers will process. It is
1216
  // impossible for us to end up in an infinite loop due to how the JS-side
1217
  // is structured.
1218
33
  do {
1219
9213
    TryCatchScope try_catch(env);
1220
9213
    try_catch.SetVerbose(true);
1221
9213
    ret = cb->Call(env->context(), process, 1, &arg);
1222

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

205147
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "CheckImmediate");
1263
1264
202105
  HandleScope scope(env->isolate());
1265
202105
  Context::Scope context_scope(env->context());
1266
1267
202105
  env->RunAndClearNativeImmediates();
1268
1269

202105
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
1270
160256
    return;
1271
1272
952
  do {
1273
42793
    MakeCallback(env->isolate(),
1274
                 env->process_object(),
1275
                 env->immediate_callback_function(),
1276
                 0,
1277
                 nullptr,
1278
42801
                 {0, 0}).ToLocalChecked();
1279

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

28
  if (!object->IsObject() || errorno == 0)
1355
    return;
1356
1357
28
  Local<Object> obj = object.As<Object>();
1358
28
  const char* err_string = uv_err_name(errorno);
1359
1360

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

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

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
































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
































































































































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

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

7887742
BaseObject::~BaseObject() {
2056
2870352
  env()->modify_base_object_count(-1);
2057
2870352
  env()->RemoveCleanupHook(DeleteMe, static_cast<void*>(this));
2058
2059
2870352
  if (UNLIKELY(has_pointer_data())) {
2060
365330
    PointerData* metadata = pointer_data();
2061
365330
    CHECK_EQ(metadata->strong_ptr_count, 0);
2062
365330
    metadata->self = nullptr;
2063
365330
    if (metadata->weak_ptr_count == 0) delete metadata;
2064
  }
2065
2066
2870352
  if (persistent_handle_.IsEmpty()) {
2067
    // This most likely happened because the weak callback below cleared it.
2068
2147038
    return;
2069
  }
2070
2071
  {
2072
723314
    HandleScope handle_scope(env()->isolate());
2073
1446628
    object()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
2074
  }
2075
}
2076
2077
1236929
void BaseObject::MakeWeak() {
2078
1236929
  if (has_pointer_data()) {
2079
42681
    pointer_data()->wants_weak_jsobj = true;
2080
42681
    if (pointer_data()->strong_ptr_count > 0) return;
2081
  }
2082
2083
2473856
  persistent_handle_.SetWeak(
2084
      this,
2085
1073518
      [](const WeakCallbackInfo<BaseObject>& data) {
2086
1073518
        BaseObject* obj = data.GetParameter();
2087
        // Clear the persistent handle so that ~BaseObject() doesn't attempt
2088
        // to mess with internal fields, since the JS object may have
2089
        // transitioned into an invalid state.
2090
        // Refs: https://github.com/nodejs/node/issues/18897
2091
1073518
        obj->persistent_handle_.Reset();
2092

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

73165
    } else if (metadata->wants_weak_jsobj && !persistent_handle_.IsEmpty()) {
2144
42680
      MakeWeak();
2145
    }
2146
  }
2147
742935
}
2148
2149
745346
void BaseObject::increase_refcount() {
2150
745346
  unsigned int prev_refcount = pointer_data()->strong_ptr_count++;
2151

745346
  if (prev_refcount == 0 && !persistent_handle_.IsEmpty())
2152
252160
    persistent_handle_.ClearWeak();
2153
745346
}
2154
2155
163803
void BaseObject::DeleteMe(void* data) {
2156
163803
  BaseObject* self = static_cast<BaseObject*>(data);
2157

168801
  if (self->has_pointer_data() &&
2158
4998
      self->pointer_data()->strong_ptr_count > 0) {
2159
828
    return self->Detach();
2160
  }
2161
162975
  delete self;
2162
}
2163
2164
530
bool BaseObject::IsDoneInitializing() const { return true; }
2165
2166
586
Local<Object> BaseObject::WrappedObject() const {
2167
586
  return object();
2168
}
2169
2170
1172
bool BaseObject::IsRootNode() const {
2171
2344
  return !persistent_handle_.IsWeak();
2172
}
2173
2174
55165
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
2175
55165
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
2176
55165
  if (tmpl.IsEmpty()) {
2177
775
    tmpl = NewFunctionTemplate(env->isolate(), nullptr);
2178
775
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
2179
775
    env->set_base_object_ctor_template(tmpl);
2180
  }
2181
55165
  return tmpl;
2182
}
2183
2184
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
2185
  return IsWeakOrDetached();
2186
}
2187
2188
}  // namespace node