GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.cc Lines: 976 1061 92.0 %
Date: 2022-08-17 04:19:55 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 Environment::kNodeContextTag = 0x6e6f64;
65
void* const Environment::kNodeContextTagPtr = const_cast<void*>(
66
    static_cast<const void*>(&Environment::kNodeContextTag));
67
68
16158
void AsyncHooks::SetJSPromiseHooks(Local<Function> init,
69
                                   Local<Function> before,
70
                                   Local<Function> after,
71
                                   Local<Function> resolve) {
72
16158
  js_promise_hooks_[0].Reset(env()->isolate(), init);
73
16158
  js_promise_hooks_[1].Reset(env()->isolate(), before);
74
16158
  js_promise_hooks_[2].Reset(env()->isolate(), after);
75
16158
  js_promise_hooks_[3].Reset(env()->isolate(), resolve);
76
32661
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
77
16503
    if (it->IsEmpty()) {
78
      contexts_.erase(it--);
79
      continue;
80
    }
81
33006
    PersistentToLocal::Weak(env()->isolate(), *it)
82
16503
        ->SetPromiseHooks(init, before, after, resolve);
83
  }
84
16158
}
85
86
// Remember to keep this code aligned with pushAsyncContext() in JS.
87
813540
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
813540
  if (fields_[kCheck] > 0) {
93
813536
    CHECK_GE(async_id, -1);
94
813536
    CHECK_GE(trigger_async_id, -1);
95
  }
96
97
813540
  uint32_t offset = fields_[kStackLength];
98
813540
  if (offset * 2 >= async_ids_stack_.Length()) grow_async_ids_stack();
99
813540
  async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
100
813540
  async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
101
813540
  fields_[kStackLength] += 1;
102
813540
  async_id_fields_[kExecutionAsyncId] = async_id;
103
813540
  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
813540
  if (!resource.IsEmpty()) {
113
813536
    native_execution_async_resources_.resize(offset + 1);
114
    // Caveat: This is a v8::Local<> assignment, we do not keep a v8::Global<>!
115
813536
    native_execution_async_resources_[offset] = resource;
116
  }
117
813540
}
118
119
// Remember to keep this code aligned with popAsyncContext() in JS.
120
813149
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
813149
  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
1624186
  if (UNLIKELY(fields_[kCheck] > 0 &&
128

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

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

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




101422
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
340






133450
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
341









































































































































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








































































208182
  PER_ISOLATE_TEMPLATE_PROPERTIES(V);
380
#undef V
381
5338
}
382
383
782
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
782
  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
7820
  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
10166
  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
215832
  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
46138
  NODE_ASYNC_PROVIDER_TYPES(V)
444
#undef V
445
446
  // TODO(legendecas): eagerly create per isolate templates.
447
782
}
448
449
6120
IsolateData::IsolateData(Isolate* isolate,
450
                         uv_loop_t* event_loop,
451
                         MultiIsolatePlatform* platform,
452
                         ArrayBufferAllocator* node_allocator,
453
6120
                         const IsolateDataSerializeInfo* isolate_data_info)
454
    : isolate_(isolate),
455
      event_loop_(event_loop),
456
48
      node_allocator_(node_allocator == nullptr ? nullptr
457
6072
                                                : node_allocator->GetImpl()),
458
12240
      platform_(platform) {
459
6120
  options_.reset(
460
6120
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
461
462
6120
  if (isolate_data_info == nullptr) {
463
782
    CreateProperties();
464
  } else {
465
5338
    DeserializeProperties(isolate_data_info);
466
  }
467
6120
}
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
6729
void Environment::AssignToContext(Local<v8::Context> context,
514
                                  const ContextInfo& info) {
515
6729
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
516
                                           this);
517
  // Used by Environment::GetCurrent to know that we are on a node context.
518
6729
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kContextTag,
519
                                           Environment::kNodeContextTagPtr);
520
  // Used to retrieve bindings
521
13458
  context->SetAlignedPointerInEmbedderData(
522
6729
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
523
524
#if HAVE_INSPECTOR
525
6729
  inspector_agent()->ContextCreated(context, info);
526
#endif  // HAVE_INSPECTOR
527
528
6729
  this->async_hooks()->AddContext(context);
529
6729
}
530
531
170
void Environment::TryLoadAddon(
532
    const char* filename,
533
    int flags,
534
    const std::function<bool(binding::DLib*)>& was_loaded) {
535
170
  loaded_addons_.emplace_back(filename, flags);
536
170
  if (!was_loaded(&loaded_addons_.back())) {
537
8
    loaded_addons_.pop_back();
538
  }
539
170
}
540
541
11
std::string Environment::GetCwd() {
542
  char cwd[PATH_MAX_BYTES];
543
11
  size_t size = PATH_MAX_BYTES;
544
11
  const int err = uv_cwd(cwd, &size);
545
546
11
  if (err == 0) {
547
11
    CHECK_GT(size, 0);
548
11
    return cwd;
549
  }
550
551
  // This can fail if the cwd is deleted. In that case, fall back to
552
  // exec_path.
553
  const std::string& exec_path = exec_path_;
554
  return exec_path.substr(0, exec_path.find_last_of(kPathSeparator));
555
}
556
557
1893
void Environment::add_refs(int64_t diff) {
558
1893
  task_queues_async_refs_ += diff;
559
1893
  CHECK_GE(task_queues_async_refs_, 0);
560
1893
  if (task_queues_async_refs_ == 0)
561
416
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
562
  else
563
1477
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
564
1893
}
565
566
67054
uv_buf_t Environment::allocate_managed_buffer(const size_t suggested_size) {
567
134108
  NoArrayBufferZeroFillScope no_zero_fill_scope(isolate_data());
568
  std::unique_ptr<v8::BackingStore> bs =
569
67054
      v8::ArrayBuffer::NewBackingStore(isolate(), suggested_size);
570
67054
  uv_buf_t buf = uv_buf_init(static_cast<char*>(bs->Data()), bs->ByteLength());
571
67054
  released_allocated_buffers_.emplace(buf.base, std::move(bs));
572
67054
  return buf;
573
}
574
575
82016
std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer(
576
    const uv_buf_t& buf) {
577
82016
  std::unique_ptr<v8::BackingStore> bs;
578
82016
  if (buf.base != nullptr) {
579
67054
    auto it = released_allocated_buffers_.find(buf.base);
580
67054
    CHECK_NE(it, released_allocated_buffers_.end());
581
67054
    bs = std::move(it->second);
582
67054
    released_allocated_buffers_.erase(it);
583
  }
584
82016
  return bs;
585
}
586
587
772
void Environment::CreateProperties() {
588
1544
  HandleScope handle_scope(isolate_);
589
772
  Local<Context> ctx = context();
590
591
  {
592
772
    Context::Scope context_scope(ctx);
593
772
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
594
1544
    templ->InstanceTemplate()->SetInternalFieldCount(
595
        BaseObject::kInternalFieldCount);
596
772
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
597
598
772
    set_binding_data_ctor_template(templ);
599
  }
600
601
  // Store primordials setup by the per-context script in the environment.
602
  Local<Object> per_context_bindings =
603
1544
      GetPerContextExports(ctx).ToLocalChecked();
604
  Local<Value> primordials =
605
2316
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
606
772
  CHECK(primordials->IsObject());
607
772
  set_primordials(primordials.As<Object>());
608
609
  Local<String> prototype_string =
610
772
      FIXED_ONE_BYTE_STRING(isolate(), "prototype");
611
612
#define V(EnvPropertyName, PrimordialsPropertyName)                            \
613
  {                                                                            \
614
    Local<Value> ctor =                                                        \
615
        primordials.As<Object>()                                               \
616
            ->Get(ctx,                                                         \
617
                  FIXED_ONE_BYTE_STRING(isolate(), PrimordialsPropertyName))   \
618
            .ToLocalChecked();                                                 \
619
    CHECK(ctor->IsObject());                                                   \
620
    Local<Value> prototype =                                                   \
621
        ctor.As<Object>()->Get(ctx, prototype_string).ToLocalChecked();        \
622
    CHECK(prototype->IsObject());                                              \
623
    set_##EnvPropertyName(prototype.As<Object>());                             \
624
  }
625
626

4632
  V(primordials_safe_map_prototype_object, "SafeMap");
627

4632
  V(primordials_safe_set_prototype_object, "SafeSet");
628

4632
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
629

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



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

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

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

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

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

15957
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunCleanup");
1031
5568
  bindings_.clear();
1032
5568
  CleanupHandles();
1033
1034
16699
  while (!cleanup_hooks_.empty() ||
1035
11138
         native_immediates_.size() > 0 ||
1036

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

17713
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "AtExit");
1073
18371
  for (ExitCallback at_exit : at_exit_functions_) {
1074
12186
    at_exit.cb_(at_exit.arg_);
1075
  }
1076
6185
  at_exit_functions_.clear();
1077
6185
}
1078
1079
12210
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
1080
12210
  at_exit_functions_.push_front(ExitCallback{cb, arg});
1081
12210
}
1082
1083
238827
void Environment::RunAndClearInterrupts() {
1084
238827
  while (native_immediates_interrupts_.size() > 0) {
1085
10508
    NativeImmediateQueue queue;
1086
    {
1087
21016
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1088
10508
      queue.ConcatMove(std::move(native_immediates_interrupts_));
1089
    }
1090
10508
    DebugSealHandleScope seal_handle_scope(isolate());
1091
1092
21026
    while (auto head = queue.Shift())
1093
21036
      head->Call(this);
1094
  }
1095
228319
}
1096
1097
218097
void Environment::RunAndClearNativeImmediates(bool only_refed) {
1098

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

59895
      if (is_refed || !only_refed)
1118
59651
        head->Call(this);
1119
1120
59890
      head.reset();  // Destroy now so that this is also observed by try_catch.
1121
1122
59890
      if (UNLIKELY(try_catch.HasCaught())) {
1123

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

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

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

203728
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "CheckImmediate");
1265
1266
200693
  HandleScope scope(env->isolate());
1267
200693
  Context::Scope context_scope(env->context());
1268
1269
200693
  env->RunAndClearNativeImmediates();
1270
1271

200693
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
1272
159289
    return;
1273
1274
951
  do {
1275
42347
    MakeCallback(env->isolate(),
1276
                 env->process_object(),
1277
                 env->immediate_callback_function(),
1278
                 0,
1279
                 nullptr,
1280
42355
                 {0, 0}).ToLocalChecked();
1281

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

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

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

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

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
































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
































































































































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

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

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

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

73144
    } else if (metadata->wants_weak_jsobj && !persistent_handle_.IsEmpty()) {
2146
42635
      MakeWeak();
2147
    }
2148
  }
2149
742928
}
2150
2151
745289
void BaseObject::increase_refcount() {
2152
745289
  unsigned int prev_refcount = pointer_data()->strong_ptr_count++;
2153

745289
  if (prev_refcount == 0 && !persistent_handle_.IsEmpty())
2154
252240
    persistent_handle_.ClearWeak();
2155
745289
}
2156
2157
149932
void BaseObject::DeleteMe(void* data) {
2158
149932
  BaseObject* self = static_cast<BaseObject*>(data);
2159

154951
  if (self->has_pointer_data() &&
2160
5019
      self->pointer_data()->strong_ptr_count > 0) {
2161
819
    return self->Detach();
2162
  }
2163
149113
  delete self;
2164
}
2165
2166
486
bool BaseObject::IsDoneInitializing() const { return true; }
2167
2168
542
Local<Object> BaseObject::WrappedObject() const {
2169
542
  return object();
2170
}
2171
2172
1084
bool BaseObject::IsRootNode() const {
2173
2168
  return !persistent_handle_.IsWeak();
2174
}
2175
2176
55004
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
2177
55004
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
2178
55004
  if (tmpl.IsEmpty()) {
2179
772
    tmpl = NewFunctionTemplate(env->isolate(), nullptr);
2180
772
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
2181
772
    env->set_base_object_ctor_template(tmpl);
2182
  }
2183
55004
  return tmpl;
2184
}
2185
2186
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
2187
  return IsWeakOrDetached();
2188
}
2189
2190
}  // namespace node