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

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

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

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




99788
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
340






131300
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
341









































































































































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








































































204828
  PER_ISOLATE_TEMPLATE_PROPERTIES(V);
380
#undef V
381
5252
}
382
383
773
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
773
  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
7730
  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
10049
  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
213348
  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
45607
  NODE_ASYNC_PROVIDER_TYPES(V)
444
#undef V
445
446
  // TODO(legendecas): eagerly create per isolate templates.
447
773
}
448
449
6025
IsolateData::IsolateData(Isolate* isolate,
450
                         uv_loop_t* event_loop,
451
                         MultiIsolatePlatform* platform,
452
                         ArrayBufferAllocator* node_allocator,
453
6025
                         const IsolateDataSerializeInfo* isolate_data_info)
454
    : isolate_(isolate),
455
      event_loop_(event_loop),
456
48
      node_allocator_(node_allocator == nullptr ? nullptr
457
5977
                                                : node_allocator->GetImpl()),
458
12050
      platform_(platform) {
459
6025
  options_.reset(
460
6025
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
461
462
6025
  if (isolate_data_info == nullptr) {
463
773
    CreateProperties();
464
  } else {
465
5252
    DeserializeProperties(isolate_data_info);
466
  }
467
6025
}
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
6631
void Environment::AssignToContext(Local<v8::Context> context,
514
                                  const ContextInfo& info) {
515
6631
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
516
                                           this);
517
  // Used by Environment::GetCurrent to know that we are on a node context.
518
6631
  context->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kContextTag,
519
                                           Environment::kNodeContextTagPtr);
520
  // Used to retrieve bindings
521
13262
  context->SetAlignedPointerInEmbedderData(
522
6631
      ContextEmbedderIndex::kBindingListIndex, &(this->bindings_));
523
524
#if HAVE_INSPECTOR
525
6631
  inspector_agent()->ContextCreated(context, info);
526
#endif  // HAVE_INSPECTOR
527
528
6631
  this->async_hooks()->AddContext(context);
529
6631
}
530
531
164
void Environment::TryLoadAddon(
532
    const char* filename,
533
    int flags,
534
    const std::function<bool(binding::DLib*)>& was_loaded) {
535
164
  loaded_addons_.emplace_back(filename, flags);
536
164
  if (!was_loaded(&loaded_addons_.back())) {
537
8
    loaded_addons_.pop_back();
538
  }
539
164
}
540
541
10
std::string Environment::GetCwd() {
542
  char cwd[PATH_MAX_BYTES];
543
10
  size_t size = PATH_MAX_BYTES;
544
10
  const int err = uv_cwd(cwd, &size);
545
546
10
  if (err == 0) {
547
10
    CHECK_GT(size, 0);
548
10
    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
1858
void Environment::add_refs(int64_t diff) {
558
1858
  task_queues_async_refs_ += diff;
559
1858
  CHECK_GE(task_queues_async_refs_, 0);
560
1858
  if (task_queues_async_refs_ == 0)
561
398
    uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
562
  else
563
1460
    uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
564
1858
}
565
566
67318
uv_buf_t Environment::allocate_managed_buffer(const size_t suggested_size) {
567
134636
  NoArrayBufferZeroFillScope no_zero_fill_scope(isolate_data());
568
  std::unique_ptr<v8::BackingStore> bs =
569
67318
      v8::ArrayBuffer::NewBackingStore(isolate(), suggested_size);
570
67318
  uv_buf_t buf = uv_buf_init(static_cast<char*>(bs->Data()), bs->ByteLength());
571
67318
  released_allocated_buffers_.emplace(buf.base, std::move(bs));
572
67318
  return buf;
573
}
574
575
82274
std::unique_ptr<v8::BackingStore> Environment::release_managed_buffer(
576
    const uv_buf_t& buf) {
577
82274
  std::unique_ptr<v8::BackingStore> bs;
578
82274
  if (buf.base != nullptr) {
579
67318
    auto it = released_allocated_buffers_.find(buf.base);
580
67318
    CHECK_NE(it, released_allocated_buffers_.end());
581
67318
    bs = std::move(it->second);
582
67318
    released_allocated_buffers_.erase(it);
583
  }
584
82274
  return bs;
585
}
586
587
762
void Environment::CreateProperties() {
588
1524
  HandleScope handle_scope(isolate_);
589
762
  Local<Context> ctx = context();
590
591
  {
592
762
    Context::Scope context_scope(ctx);
593
762
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
594
1524
    templ->InstanceTemplate()->SetInternalFieldCount(
595
        BaseObject::kInternalFieldCount);
596
762
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
597
598
762
    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
1524
      GetPerContextExports(ctx).ToLocalChecked();
604
  Local<Value> primordials =
605
2286
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
606
762
  CHECK(primordials->IsObject());
607
762
  set_primordials(primordials.As<Object>());
608
609
  Local<String> prototype_string =
610
762
      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

4572
  V(primordials_safe_map_prototype_object, "SafeMap");
627

4572
  V(primordials_safe_set_prototype_object, "SafeSet");
628

4572
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
629

4572
  V(primordials_safe_weak_set_prototype_object, "SafeWeakSet");
630
#undef V
631
632
  Local<Object> process_object =
633
762
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
634
762
  set_process_object(process_object);
635
762
}
636
637
6014
std::string GetExecPath(const std::vector<std::string>& argv) {
638
  char exec_path_buf[2 * PATH_MAX];
639
6014
  size_t exec_path_len = sizeof(exec_path_buf);
640
6014
  std::string exec_path;
641
6014
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
642
6014
    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
6014
  return exec_path;
661
}
662
663
6014
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
6014
                         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
6014
      timer_base_(uv_now(isolate_data->event_loop())),
676
      exec_argv_(exec_args),
677
      argv_(args),
678
      exec_path_(GetExecPath(args)),
679
6014
      exiting_(isolate_, 1, MAYBE_FIELD_PTR(env_info, exiting)),
680
      should_abort_on_uncaught_toggle_(
681
6014
          isolate_,
682
          1,
683
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
684
6014
      stream_base_state_(isolate_,
685
                         StreamBase::kNumStreamBaseStateFields,
686
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
687
6014
      time_origin_(PERFORMANCE_NOW()),
688
6014
      time_origin_timestamp_(GetCurrentTimeInMicroseconds()),
689
      flags_(flags),
690
6014
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
691
6014
                     ? AllocateEnvironmentThreadId().id
692



24056
                     : thread_id.id) {
693
  // We'll be creating new objects so make sure we've entered the context.
694
12028
  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
6014
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
699
10612
    flags_ = flags_ |
700
5306
        EnvironmentFlags::kOwnsProcessState |
701
        EnvironmentFlags::kOwnsInspector;
702
  }
703
704
6014
  set_env_vars(per_process::system_environment);
705
6014
  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
12028
  options_ = std::make_shared<EnvironmentOptions>(
712
18042
      *isolate_data->options()->per_env);
713
6014
  inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
714
6014
      options_->debug_options().host_port);
715
716
6014
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
717
708
    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
6014
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
723
#endif
724
725
6014
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
726
6014
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
727
6014
    if (TracingController* tracing_controller = writer->GetTracingController())
728
5966
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
729
  }
730
731
6014
  destroy_async_id_list_.reserve(512);
732
733
6014
  performance_state_ = std::make_unique<performance::PerformanceState>(
734
6014
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
735
736
6014
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
737
6014
          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
6014
}
752
753
762
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
762
                         ThreadId thread_id)
760
    : Environment(isolate_data,
761
                  context->GetIsolate(),
762
                  args,
763
                  exec_args,
764
                  env_info,
765
                  flags,
766
762
                  thread_id) {
767
762
  InitializeMainContext(context, env_info);
768
762
}
769
770
6014
void Environment::InitializeMainContext(Local<Context> context,
771
                                        const EnvSerializeInfo* env_info) {
772
6014
  context_.Reset(context->GetIsolate(), context);
773
6014
  AssignToContext(context, ContextInfo(""));
774
6014
  if (env_info != nullptr) {
775
5252
    DeserializeProperties(env_info);
776
  } else {
777
762
    CreateProperties();
778
  }
779
780
6014
  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
6014
  should_abort_on_uncaught_toggle_[0] = 1;
786
787
  // The process is not exiting by default.
788
6014
  set_exiting(false);
789
790
6014
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
791
                           time_origin_);
792
6014
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
793
                           per_process::node_start_time);
794
795
6014
  if (per_process::v8_initialized) {
796
5973
    performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
797
                            performance::performance_v8_start);
798
  }
799
6014
}
800
801
719044
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
5366
  CHECK(is_stopping());
829
830
5366
  if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
831
    isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
832
                                          0);
833
  }
834
835
5366
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
836
      BuildEmbedderGraph, this);
837
838
10732
  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
5366
  inspector_agent_.reset();
844
#endif
845
846
10732
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
847
                                             nullptr);
848
849
5366
  if (trace_state_observer_) {
850
5366
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
851
5366
    CHECK_NOT_NULL(writer);
852
5366
    if (TracingController* tracing_controller = writer->GetTracingController())
853
5320
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
854
  }
855
856

9996
  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
5366
  if (!is_main_thread()) {
865
    // Dereference all addons that were loaded into this environment.
866
716
    for (binding::DLib& addon : loaded_addons_) {
867
11
      addon.Close();
868
    }
869
  }
870
871
5366
  CHECK_EQ(base_object_count_, 0);
872
5366
}
873
874
5981
void Environment::InitializeLibuv() {
875
11962
  HandleScope handle_scope(isolate());
876
5981
  Context::Scope context_scope(context());
877
878
5981
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
879
5981
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
880
881
5981
  CHECK_EQ(0, uv_check_init(event_loop(), immediate_check_handle()));
882
5981
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
883
884
5981
  CHECK_EQ(0, uv_idle_init(event_loop(), immediate_idle_handle()));
885
886
5981
  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
5981
  CHECK_EQ(0, uv_prepare_init(event_loop(), &idle_prepare_handle_));
893
5981
  CHECK_EQ(0, uv_check_init(event_loop(), &idle_check_handle_));
894
895
24275
  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
5981
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
906
5981
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
907
5981
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
908
909
  {
910
11962
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
911
5981
    task_queues_async_initialized_ = true;
912

11962
    if (native_immediates_threadsafe_.size() > 0 ||
913
5981
        native_immediates_interrupts_.size() > 0) {
914
5249
      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
5981
  RegisterHandleCleanups();
923
924
5981
  StartProfilerIdleNotifier();
925
5981
}
926
927
369
void Environment::ExitEnv() {
928
369
  set_can_call_into_js(false);
929
369
  set_stopping(true);
930
369
  isolate_->TerminateExecution();
931
738
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
932
369
}
933
934
5981
void Environment::RegisterHandleCleanups() {
935
5981
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
936
31998
                                        void* arg) {
937
31998
    handle->data = env;
938
939
31998
    env->CloseHandle(handle, [](uv_handle_t* handle) {
940
#ifdef DEBUG
941
      memset(handle, 0xab, uv_handle_size(handle->type));
942
#endif
943
31998
    });
944
31998
  };
945
946
35886
  auto register_handle = [&](uv_handle_t* handle) {
947
35886
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
948
41867
  };
949
5981
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
950
5981
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
951
5981
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
952
5981
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
953
5981
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
954
5981
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
955
5981
}
956
957
10726
void Environment::CleanupHandles() {
958
  {
959
10726
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
960
10726
    task_queues_async_initialized_ = false;
961
  }
962
963
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
964
21452
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
965
966
10726
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
967
968
10889
  for (ReqWrapBase* request : req_wrap_queue_)
969
163
    request->Cancel();
970
971
14901
  for (HandleWrap* handle : handle_wrap_queue_)
972
8350
    handle->Close();
973
974
42724
  for (HandleCleanup& hc : handle_cleanup_queue_)
975
31998
    hc.cb_(this, hc.handle_, hc.arg_);
976
10726
  handle_cleanup_queue_.clear();
977
978
10043
  while (handle_cleanup_waiting_ != 0 ||
979

31497
         request_waiting_ != 0 ||
980
10728
         !handle_wrap_queue_.IsEmpty()) {
981
10043
    uv_run(event_loop(), UV_RUN_ONCE);
982
  }
983
10726
}
984
985
5981
void Environment::StartProfilerIdleNotifier() {
986
5981
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
987
202897
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
988
202897
    env->isolate()->SetIdle(true);
989
202897
  });
990
5981
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
991
202606
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
992
202606
    env->isolate()->SetIdle(false);
993
202606
  });
994
5981
}
995
996
702137
void Environment::PrintSyncTrace() const {
997
702137
  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
5011
MaybeLocal<Value> Environment::RunSnapshotSerializeCallback() const {
1009
5011
  EscapableHandleScope handle_scope(isolate());
1010
10022
  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
10022
  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
5366
void Environment::RunCleanup() {
1029
5366
  started_cleanup_ = true;
1030

15362
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunCleanup");
1031
5366
  bindings_.clear();
1032
5366
  CleanupHandles();
1033
1034
16094
  while (!cleanup_hooks_.empty() ||
1035
10734
         native_immediates_.size() > 0 ||
1036

21460
         native_immediates_threadsafe_.size() > 0 ||
1037
5366
         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
10720
        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
5360
    std::sort(callbacks.begin(), callbacks.end(),
1045
1117282
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
1046
      // Sort in descending order so that the most recently inserted callbacks
1047
      // are run first.
1048
1117282
      return a.insertion_order_counter_ > b.insertion_order_counter_;
1049
    });
1050
1051
167293
    for (const CleanupHookCallback& cb : callbacks) {
1052
161933
      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
1009
        continue;
1056
      }
1057
1058
160924
      cb.fn_(cb.arg_);
1059
160924
      cleanup_hooks_.erase(cb);
1060
    }
1061
5360
    CleanupHandles();
1062
  }
1063
1064
5369
  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
5366
}
1070
1071
6090
void Environment::RunAtExitCallbacks() {
1072

17437
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "AtExit");
1073
18084
  for (ExitCallback at_exit : at_exit_functions_) {
1074
11994
    at_exit.cb_(at_exit.arg_);
1075
  }
1076
6090
  at_exit_functions_.clear();
1077
6090
}
1078
1079
12018
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
1080
12018
  at_exit_functions_.push_front(ExitCallback{cb, arg});
1081
12018
}
1082
1083
239659
void Environment::RunAndClearInterrupts() {
1084
239659
  while (native_immediates_interrupts_.size() > 0) {
1085
10261
    NativeImmediateQueue queue;
1086
    {
1087
20522
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1088
10261
      queue.ConcatMove(std::move(native_immediates_interrupts_));
1089
    }
1090
10261
    DebugSealHandleScope seal_handle_scope(isolate());
1091
1092
20530
    while (auto head = queue.Shift())
1093
20538
      head->Call(this);
1094
  }
1095
229398
}
1096
1097
219432
void Environment::RunAndClearNativeImmediates(bool only_refed) {
1098

443802
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment),
1099
               "RunAndClearNativeImmediates");
1100
438858
  HandleScope handle_scope(isolate_);
1101
438858
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
1102
1103
219432
  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
219432
  RunAndClearInterrupts();
1108
1109
438862
  auto drain_list = [&](NativeImmediateQueue* queue) {
1110
877718
    TryCatchScope try_catch(this);
1111
438862
    DebugSealHandleScope seal_handle_scope(isolate());
1112
498725
    while (auto head = queue->Shift()) {
1113
59870
      bool is_refed = head->flags() & CallbackFlags::kRefed;
1114
59870
      if (is_refed)
1115
35127
        ref_count++;
1116
1117

59870
      if (is_refed || !only_refed)
1118
59638
        head->Call(this);
1119
1120
59865
      head.reset();  // Destroy now so that this is also observed by try_catch.
1121
1122
59865
      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
59863
    }
1129
438855
    return false;
1130
219432
  };
1131
219432
  while (drain_list(&native_immediates_)) {}
1132
1133
219429
  immediate_info()->ref_count_dec(ref_count);
1134
1135
219429
  if (immediate_info()->ref_count() == 0)
1136
176942
    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
219426
  NativeImmediateQueue threadsafe_immediates;
1146
219429
  if (native_immediates_threadsafe_.size() > 0) {
1147
2118
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1148
1059
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
1149
  }
1150
219430
  while (drain_list(&threadsafe_immediates)) {}
1151
219426
}
1152
1153
10274
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
10274
  Environment** interrupt_data = new Environment*(this);
1166
10274
  Environment** dummy = nullptr;
1167
10274
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
1168
405
    delete interrupt_data;
1169
405
    return;  // Already scheduled.
1170
  }
1171
1172
9869
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
1173
9860
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
1174
9860
    Environment* env = *env_ptr;
1175
9860
    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
9850
    env->interrupt_data_.store(nullptr);
1182
9850
    env->RunAndClearInterrupts();
1183
  }, interrupt_data);
1184
}
1185
1186
8237
void Environment::ScheduleTimer(int64_t duration_ms) {
1187
8237
  if (started_cleanup_) return;
1188
8237
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
1189
}
1190
1191
3655
void Environment::ToggleTimerRef(bool ref) {
1192
3655
  if (started_cleanup_) return;
1193
1194
3655
  if (ref) {
1195
2391
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1196
  } else {
1197
1264
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
1198
  }
1199
}
1200
1201
6230
void Environment::RunTimers(uv_timer_t* handle) {
1202
6230
  Environment* env = Environment::from_timer_handle(handle);
1203

6739
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunTimers");
1204
1205
6230
  if (!env->can_call_into_js())
1206
    return;
1207
1208
6230
  HandleScope handle_scope(env->isolate());
1209
6230
  Context::Scope context_scope(env->context());
1210
1211
6230
  Local<Object> process = env->process_object();
1212
6230
  InternalCallbackScope scope(env, process, {0, 0});
1213
1214
6230
  Local<Function> cb = env->timers_callback_function();
1215
  MaybeLocal<Value> ret;
1216
6230
  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
33
  do {
1221
6263
    TryCatchScope try_catch(env);
1222
6263
    try_catch.SetVerbose(true);
1223
6263
    ret = cb->Call(env->context(), process, 1, &arg);
1224

6254
  } 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
6221
  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
6215
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
1243
1244
6215
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
1245
1246
6215
  if (expiry_ms != 0) {
1247
    int64_t duration_ms =
1248
5275
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
1249
1250
5275
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
1251
1252
5275
    if (expiry_ms > 0)
1253
4364
      uv_ref(h);
1254
    else
1255
911
      uv_unref(h);
1256
  } else {
1257
940
    uv_unref(h);
1258
  }
1259
}
1260
1261
1262
202606
void Environment::CheckImmediate(uv_check_t* handle) {
1263
202606
  Environment* env = Environment::from_immediate_check_handle(handle);
1264

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

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

42865
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
1282
1283
41914
  if (env->immediate_info()->ref_count() == 0)
1284
4709
    env->ToggleImmediateRef(false);
1285
}
1286
1287
247011
void Environment::ToggleImmediateRef(bool ref) {
1288
247011
  if (started_cleanup_) return;
1289
1290
236362
  if (ref) {
1291
    // Idle handle is needed only to stop the event loop from blocking in poll.
1292
65336
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
1293
  } else {
1294
171026
    uv_idle_stop(immediate_idle_handle());
1295
  }
1296
}
1297
1298
1299
44699
Local<Value> Environment::GetNow() {
1300
44699
  uv_update_time(event_loop());
1301
44699
  uint64_t now = uv_now(event_loop());
1302
44699
  CHECK_GE(now, timer_base());
1303
44699
  now -= timer_base();
1304
44699
  if (now <= 0xffffffff)
1305
89398
    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
6014
ImmediateInfo::ImmediateInfo(Isolate* isolate, const SerializeInfo* info)
1371
6014
    : 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
5252
void ImmediateInfo::Deserialize(Local<Context> context) {
1379
5252
  fields_.Deserialize(context);
1380
5252
}
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
5252
void TickInfo::Deserialize(Local<Context> context) {
1398
5252
  fields_.Deserialize(context);
1399
5252
}
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
6014
TickInfo::TickInfo(Isolate* isolate, const SerializeInfo* info)
1412
    : fields_(
1413
6014
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1414
1415
6014
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

6014
      info_(info) {
1421
12028
  HandleScope handle_scope(isolate);
1422
6014
  if (info == nullptr) {
1423
762
    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
762
    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
762
    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
762
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1441
  }
1442
6014
}
1443
1444
5252
void AsyncHooks::Deserialize(Local<Context> context) {
1445
5252
  async_ids_stack_.Deserialize(context);
1446
5252
  fields_.Deserialize(context);
1447
5252
  async_id_fields_.Deserialize(context);
1448
1449
  Local<Array> js_execution_async_resources;
1450
5252
  if (info_->js_execution_async_resources != 0) {
1451
    js_execution_async_resources =
1452
5252
        context->GetDataFromSnapshotOnce<Array>(
1453
15756
            info_->js_execution_async_resources).ToLocalChecked();
1454
  } else {
1455
    js_execution_async_resources = Array::New(context->GetIsolate());
1456
  }
1457
5252
  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
5252
  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
5252
  info_ = nullptr;
1473
5252
}
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
707
void Environment::Exit(int exit_code) {
1555
707
  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
707
  process_exit_handler_(this, exit_code);
1574
64
}
1575
1576
6037
void Environment::stop_sub_worker_contexts() {
1577
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1578
1579
6037
  while (!sub_worker_contexts_.empty()) {
1580
28
    Worker* w = *sub_worker_contexts_.begin();
1581
28
    remove_sub_worker_context(w);
1582
28
    w->Exit(1);
1583
28
    w->JoinThread();
1584
  }
1585
6009
}
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
61832
void Environment::AddUnmanagedFd(int fd) {
1593
61832
  if (!tracks_unmanaged_fds()) return;
1594
2676
  auto result = unmanaged_fds_.insert(fd);
1595
2676
  if (!result.second) {
1596
    ProcessEmitWarning(
1597
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1598
  }
1599
}
1600
1601
61448
void Environment::RemoveUnmanagedFd(int fd) {
1602
61448
  if (!tracks_unmanaged_fds()) return;
1603
2673
  size_t removed_count = unmanaged_fds_.erase(fd);
1604
2673
  if (removed_count == 0) {
1605
    ProcessEmitWarning(
1606
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1607
  }
1608
}
1609
1610
4986
void Environment::PrintInfoForSnapshotIfDebug() {
1611
4986
  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
4986
}
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
4986
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
4986
  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
21008
void Environment::EnqueueDeserializeRequest(DeserializeRequestCallback cb,
1762
                                            Local<Object> holder,
1763
                                            int index,
1764
                                            InternalFieldInfoBase* info) {
1765
  DCHECK_EQ(index, BaseObject::kEmbedderType);
1766
42016
  DeserializeRequest request{cb, {isolate(), holder}, index, info};
1767
21008
  deserialize_requests_.push_back(std::move(request));
1768
21008
}
1769
1770
5252
void Environment::RunDeserializeRequests() {
1771
10504
  HandleScope scope(isolate());
1772
5252
  Local<Context> ctx = context();
1773
5252
  Isolate* is = isolate();
1774
26260
  while (!deserialize_requests_.empty()) {
1775
42016
    DeserializeRequest request(std::move(deserialize_requests_.front()));
1776
21008
    deserialize_requests_.pop_front();
1777
21008
    Local<Object> holder = request.holder.Get(is);
1778
21008
    request.cb(ctx, holder, request.index, request.info);
1779
    request.holder.Reset();
1780
21008
    request.info->Delete();
1781
  }
1782
5252
}
1783
1784
5252
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1785
5252
  Local<Context> ctx = context();
1786
1787
5252
  RunDeserializeRequests();
1788
1789
5252
  builtins_in_snapshot = info->builtins;
1790
5252
  async_hooks_.Deserialize(ctx);
1791
5252
  immediate_info_.Deserialize(ctx);
1792
5252
  tick_info_.Deserialize(ctx);
1793
5252
  performance_state_->Deserialize(ctx);
1794
5252
  exiting_.Deserialize(ctx);
1795
5252
  stream_base_state_.Deserialize(ctx);
1796
5252
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1797
1798
5252
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1799
    fprintf(stderr, "deserializing...\n");
1800
    std::cerr << *info << "\n";
1801
  }
1802
1803
5252
  const std::vector<PropInfo>& values = info->persistent_values;
1804
5252
  size_t i = 0;  // index to the array
1805
5252
  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
































































































































540956
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1826
#undef V
1827
1828
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1829
10504
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1830
  Local<Context> ctx_from_snapshot;
1831
5252
  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
5252
  CHECK_EQ(ctx_from_snapshot, ctx);
1836
5252
}
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
738085
void Environment::RunWeakRefCleanup() {
2041
738085
  isolate()->ClearKeptObjects();
2042
738085
}
2043
2044
// Not really any better place than env.cc at this moment.
2045
1428252
BaseObject::BaseObject(Environment* env, Local<Object> object)
2046
2856504
    : persistent_handle_(env->isolate(), object), env_(env) {
2047
1428252
  CHECK_EQ(false, object.IsEmpty());
2048
1428252
  CHECK_GE(object->InternalFieldCount(), BaseObject::kInternalFieldCount);
2049
1428252
  object->SetAlignedPointerInInternalField(BaseObject::kEmbedderType,
2050
                                           &kNodeEmbedderId);
2051
1428252
  object->SetAlignedPointerInInternalField(BaseObject::kSlot,
2052
                                           static_cast<void*>(this));
2053
1428252
  env->AddCleanupHook(DeleteMe, static_cast<void*>(this));
2054
1428252
  env->modify_base_object_count(1);
2055
1428252
}
2056
2057

7802956
BaseObject::~BaseObject() {
2058
2829240
  env()->modify_base_object_count(-1);
2059
2829240
  env()->RemoveCleanupHook(DeleteMe, static_cast<void*>(this));
2060
2061
2829240
  if (UNLIKELY(has_pointer_data())) {
2062
362172
    PointerData* metadata = pointer_data();
2063
362172
    CHECK_EQ(metadata->strong_ptr_count, 0);
2064
362172
    metadata->self = nullptr;
2065
362172
    if (metadata->weak_ptr_count == 0) delete metadata;
2066
  }
2067
2068
2829240
  if (persistent_handle_.IsEmpty()) {
2069
    // This most likely happened because the weak callback below cleared it.
2070
2144476
    return;
2071
  }
2072
2073
  {
2074
684764
    HandleScope handle_scope(env()->isolate());
2075
1369528
    object()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
2076
  }
2077
}
2078
2079
1219380
void BaseObject::MakeWeak() {
2080
1219380
  if (has_pointer_data()) {
2081
42683
    pointer_data()->wants_weak_jsobj = true;
2082
42683
    if (pointer_data()->strong_ptr_count > 0) return;
2083
  }
2084
2085
2438758
  persistent_handle_.SetWeak(
2086
      this,
2087
1072237
      [](const WeakCallbackInfo<BaseObject>& data) {
2088
1072237
        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
1072237
        obj->persistent_handle_.Reset();
2094

1072237
        CHECK_IMPLIES(obj->has_pointer_data(),
2095
                      obj->pointer_data()->strong_ptr_count == 0);
2096
1072237
        obj->OnGCCollect();
2097
1072237
      },
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
23950
void BaseObject::LazilyInitializedJSTemplateConstructor(
2109
    const FunctionCallbackInfo<Value>& args) {
2110
  DCHECK(args.IsConstructCall());
2111
23950
  CHECK_GE(args.This()->InternalFieldCount(), BaseObject::kInternalFieldCount);
2112
23950
  args.This()->SetAlignedPointerInInternalField(BaseObject::kEmbedderType,
2113
                                                &kNodeEmbedderId);
2114
23950
  args.This()->SetAlignedPointerInInternalField(BaseObject::kSlot, nullptr);
2115
23950
}
2116
2117
21067
Local<FunctionTemplate> BaseObject::MakeLazilyInitializedJSTemplate(
2118
    Environment* env) {
2119
  Local<FunctionTemplate> t = NewFunctionTemplate(
2120
21067
      env->isolate(), LazilyInitializedJSTemplateConstructor);
2121
21067
  t->Inherit(BaseObject::GetConstructorTemplate(env));
2122
42134
  t->InstanceTemplate()->SetInternalFieldCount(BaseObject::kInternalFieldCount);
2123
21067
  return t;
2124
}
2125
2126
2881559
BaseObject::PointerData* BaseObject::pointer_data() {
2127
2881559
  if (!has_pointer_data()) {
2128
183780
    PointerData* metadata = new PointerData();
2129
183780
    metadata->wants_weak_jsobj = persistent_handle_.IsWeak();
2130
183780
    metadata->self = this;
2131
183780
    pointer_data_ = metadata;
2132
  }
2133
2881559
  CHECK(has_pointer_data());
2134
2881559
  return pointer_data_;
2135
}
2136
2137
740882
void BaseObject::decrease_refcount() {
2138
740882
  CHECK(has_pointer_data());
2139
740882
  PointerData* metadata = pointer_data();
2140
740882
  CHECK_GT(metadata->strong_ptr_count, 0);
2141
740882
  unsigned int new_refcount = --metadata->strong_ptr_count;
2142
740882
  if (new_refcount == 0) {
2143
248126
    if (metadata->is_detached) {
2144
175133
      OnGCCollect();
2145

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

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

151133
  if (self->has_pointer_data() &&
2160
5022
      self->pointer_data()->strong_ptr_count > 0) {
2161
822
    return self->Detach();
2162
  }
2163
145289
  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
54295
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
2177
54295
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
2178
54295
  if (tmpl.IsEmpty()) {
2179
762
    tmpl = NewFunctionTemplate(env->isolate(), nullptr);
2180
762
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
2181
762
    env->set_base_object_ctor_template(tmpl);
2182
  }
2183
54295
  return tmpl;
2184
}
2185
2186
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
2187
  return IsWeakOrDetached();
2188
}
2189
2190
}  // namespace node