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

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

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

1064048
            native_execution_async_resources_.capacity() / 2 &&
148
257352
        native_execution_async_resources_.size() > 16) {
149
      native_execution_async_resources_.shrink_to_fit();
150
    }
151
  }
152
153
1613392
  if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
154
29230
    HandleScope handle_scope(env()->isolate());
155
58460
    USE(js_execution_async_resources()->Set(
156
        env()->context(),
157
        env()->length_string(),
158
116920
        Integer::NewFromUnsigned(env()->isolate(), offset)));
159
  }
160
161
806696
  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
3098
    USE(PersistentToLocal::Strong(js_execution_async_resources_)
169
3098
            ->Set(env()->context(),
170
                  env()->length_string(),
171
6196
                  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
6726
void AsyncHooks::AddContext(Local<Context> ctx) {
182
20178
  ctx->SetPromiseHooks(js_promise_hooks_[0].IsEmpty()
183
6726
                           ? Local<Function>()
184
205
                           : PersistentToLocal::Strong(js_promise_hooks_[0]),
185
6726
                       js_promise_hooks_[1].IsEmpty()
186
6726
                           ? Local<Function>()
187
205
                           : PersistentToLocal::Strong(js_promise_hooks_[1]),
188
6726
                       js_promise_hooks_[2].IsEmpty()
189
6726
                           ? Local<Function>()
190
205
                           : PersistentToLocal::Strong(js_promise_hooks_[2]),
191
6726
                       js_promise_hooks_[3].IsEmpty()
192
6726
                           ? Local<Function>()
193
                           : PersistentToLocal::Strong(js_promise_hooks_[3]));
194
195
6726
  size_t id = contexts_.size();
196
6726
  contexts_.resize(id + 1);
197
6726
  contexts_[id].Reset(env()->isolate(), ctx);
198
6726
  contexts_[id].SetWeak();
199
6726
}
200
201
513
void AsyncHooks::RemoveContext(Local<Context> ctx) {
202
513
  Isolate* isolate = env()->isolate();
203
1026
  HandleScope handle_scope(isolate);
204
513
  contexts_.erase(std::remove_if(contexts_.begin(),
205
                                 contexts_.end(),
206
3865
                                 [&](auto&& el) { return el.IsEmpty(); }),
207
1026
                  contexts_.end());
208
3802
  for (auto it = contexts_.begin(); it != contexts_.end(); it++) {
209
3289
    Local<Context> saved_context = PersistentToLocal::Weak(isolate, *it);
210
3289
    if (saved_context == ctx) {
211
      it->Reset();
212
      contexts_.erase(it);
213
      break;
214
    }
215
  }
216
513
}
217
218
238611
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
219
238611
    Environment* env, double default_trigger_async_id)
220
238611
    : async_hooks_(env->async_hooks()) {
221
238611
  if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) {
222
238611
    CHECK_GE(default_trigger_async_id, 0);
223
  }
224
225
238611
  old_default_trigger_async_id_ =
226
238611
      async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId];
227
238611
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
228
238611
      default_trigger_async_id;
229
238611
}
230
231
477220
AsyncHooks::DefaultTriggerAsyncIdScope::~DefaultTriggerAsyncIdScope() {
232
238610
  async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] =
233
238610
      old_default_trigger_async_id_;
234
238610
}
235
236
238611
AsyncHooks::DefaultTriggerAsyncIdScope::DefaultTriggerAsyncIdScope(
237
238611
    AsyncWrap* async_wrap)
238
    : DefaultTriggerAsyncIdScope(async_wrap->env(),
239
238611
                                 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
5330
void IsolateData::DeserializeProperties(const IsolateDataSerializeInfo* info) {
322
5330
  size_t i = 0;
323
5330
  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




101270
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
340






133250
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
341









































































































































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








































































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

4626
  V(primordials_safe_map_prototype_object, "SafeMap");
627

4626
  V(primordials_safe_set_prototype_object, "SafeSet");
628

4626
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
629

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



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

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

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

32667
         request_waiting_ != 0 ||
980
11119
         !handle_wrap_queue_.IsEmpty()) {
981
10431
    uv_run(event_loop(), UV_RUN_ONCE);
982
  }
983
11117
}
984
985
6065
void Environment::StartProfilerIdleNotifier() {
986
6065
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
987
198550
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
988
198550
    env->isolate()->SetIdle(true);
989
198550
  });
990
6065
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
991
198361
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
992
198361
    env->isolate()->SetIdle(false);
993
198361
  });
994
6065
}
995
996
731752
void Environment::PrintSyncTrace() const {
997
731752
  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
5208
MaybeLocal<Value> Environment::RunSnapshotSerializeCallback() const {
1009
5208
  EscapableHandleScope handle_scope(isolate());
1010
10416
  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
10416
  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
5563
void Environment::RunCleanup() {
1029
5563
  started_cleanup_ = true;
1030

15944
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "RunCleanup");
1031
5563
  bindings_.clear();
1032
5563
  CleanupHandles();
1033
1034
16682
  while (!cleanup_hooks_.empty() ||
1035
11128
         native_immediates_.size() > 0 ||
1036

22245
         native_immediates_threadsafe_.size() > 0 ||
1037
5563
         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
11108
        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
5554
    std::sort(callbacks.begin(), callbacks.end(),
1045
1167149
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
1046
      // Sort in descending order so that the most recently inserted callbacks
1047
      // are run first.
1048
1167149
      return a.insertion_order_counter_ > b.insertion_order_counter_;
1049
    });
1050
1051
173203
    for (const CleanupHookCallback& cb : callbacks) {
1052
167649
      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
1010
        continue;
1056
      }
1057
1058
166639
      cb.fn_(cb.arg_);
1059
166639
      cleanup_hooks_.erase(cb);
1060
    }
1061
5554
    CleanupHandles();
1062
  }
1063
1064
5566
  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
5563
}
1070
1071
6176
void Environment::RunAtExitCallbacks() {
1072

17687
  TRACE_EVENT0(TRACING_CATEGORY_NODE1(environment), "AtExit");
1073
18344
  for (ExitCallback at_exit : at_exit_functions_) {
1074
12168
    at_exit.cb_(at_exit.arg_);
1075
  }
1076
6176
  at_exit_functions_.clear();
1077
6176
}
1078
1079
12192
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
1080
12192
  at_exit_functions_.push_front(ExitCallback{cb, arg});
1081
12192
}
1082
1083
236499
void Environment::RunAndClearInterrupts() {
1084
236499
  while (native_immediates_interrupts_.size() > 0) {
1085
10496
    NativeImmediateQueue queue;
1086
    {
1087
20992
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1088
10496
      queue.ConcatMove(std::move(native_immediates_interrupts_));
1089
    }
1090
10496
    DebugSealHandleScope seal_handle_scope(isolate());
1091
1092
21001
    while (auto head = queue.Shift())
1093
21010
      head->Call(this);
1094
  }
1095
226003
}
1096
1097
215776
void Environment::RunAndClearNativeImmediates(bool only_refed) {
1098

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

59823
      if (is_refed || !only_refed)
1118
59581
        head->Call(this);
1119
1120
59818
      head.reset();  // Destroy now so that this is also observed by try_catch.
1121
1122
59818
      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
59816
    }
1129
431543
    return false;
1130
215776
  };
1131
215776
  while (drain_list(&native_immediates_)) {}
1132
1133
215773
  immediate_info()->ref_count_dec(ref_count);
1134
1135
215773
  if (immediate_info()->ref_count() == 0)
1136
172904
    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
215770
  NativeImmediateQueue threadsafe_immediates;
1146
215773
  if (native_immediates_threadsafe_.size() > 0) {
1147
2144
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
1148
1072
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
1149
  }
1150
215774
  while (drain_list(&threadsafe_immediates)) {}
1151
215770
}
1152
1153
10510
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
10510
  Environment** interrupt_data = new Environment*(this);
1166
10510
  Environment** dummy = nullptr;
1167
10510
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
1168
380
    delete interrupt_data;
1169
380
    return;  // Already scheduled.
1170
  }
1171
1172
10130
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
1173
10121
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
1174
10121
    Environment* env = *env_ptr;
1175
10121
    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
10111
    env->interrupt_data_.store(nullptr);
1182
10111
    env->RunAndClearInterrupts();
1183
  }, interrupt_data);
1184
}
1185
1186
9631
void Environment::ScheduleTimer(int64_t duration_ms) {
1187
9631
  if (started_cleanup_) return;
1188
9631
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
1189
}
1190
1191
3668
void Environment::ToggleTimerRef(bool ref) {
1192
3668
  if (started_cleanup_) return;
1193
1194
3668
  if (ref) {
1195
2404
    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
7628
void Environment::RunTimers(uv_timer_t* handle) {
1202
7628
  Environment* env = Environment::from_timer_handle(handle);
1203

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

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

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

198361
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
1272
156065
    return;
1273
1274
952
  do {
1275
43240
    MakeCallback(env->isolate(),
1276
                 env->process_object(),
1277
                 env->immediate_callback_function(),
1278
                 0,
1279
                 nullptr,
1280
43248
                 {0, 0}).ToLocalChecked();
1281

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

6101
      info_(info) {
1421
12202
  HandleScope handle_scope(isolate);
1422
6101
  if (info == nullptr) {
1423
771
    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
771
    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
771
    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
771
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1441
  }
1442
6101
}
1443
1444
5330
void AsyncHooks::Deserialize(Local<Context> context) {
1445
5330
  async_ids_stack_.Deserialize(context);
1446
5330
  fields_.Deserialize(context);
1447
5330
  async_id_fields_.Deserialize(context);
1448
1449
  Local<Array> js_execution_async_resources;
1450
5330
  if (info_->js_execution_async_resources != 0) {
1451
    js_execution_async_resources =
1452
5330
        context->GetDataFromSnapshotOnce<Array>(
1453
15990
            info_->js_execution_async_resources).ToLocalChecked();
1454
  } else {
1455
    js_execution_async_resources = Array::New(context->GetIsolate());
1456
  }
1457
5330
  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
5330
  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
5330
  info_ = nullptr;
1473
5330
}
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
596
void Environment::Exit(int exit_code) {
1555
596
  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
596
  process_exit_handler_(this, exit_code);
1574
63
}
1575
1576
6123
void Environment::stop_sub_worker_contexts() {
1577
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1578
1579
6123
  while (!sub_worker_contexts_.empty()) {
1580
27
    Worker* w = *sub_worker_contexts_.begin();
1581
27
    remove_sub_worker_context(w);
1582
27
    w->Exit(1);
1583
27
    w->JoinThread();
1584
  }
1585
6096
}
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
64803
void Environment::AddUnmanagedFd(int fd) {
1593
64803
  if (!tracks_unmanaged_fds()) return;
1594
2678
  auto result = unmanaged_fds_.insert(fd);
1595
2678
  if (!result.second) {
1596
    ProcessEmitWarning(
1597
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1598
  }
1599
}
1600
1601
64420
void Environment::RemoveUnmanagedFd(int fd) {
1602
64420
  if (!tracks_unmanaged_fds()) return;
1603
2675
  size_t removed_count = unmanaged_fds_.erase(fd);
1604
2675
  if (removed_count == 0) {
1605
    ProcessEmitWarning(
1606
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1607
  }
1608
}
1609
1610
5185
void Environment::PrintInfoForSnapshotIfDebug() {
1611
5185
  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
5185
}
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
5185
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
5185
  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
6
  SerializeBindingData(this, creator, &info);
1673
  // Currently all modules are compiled without cache in builtin snapshot
1674
  // builder.
1675
12
  info.builtins = std::vector<std::string>(builtins_without_cache.begin(),
1676
6
                                           builtins_without_cache.end());
1677
1678
6
  info.async_hooks = async_hooks_.Serialize(ctx, creator);
1679
6
  info.immediate_info = immediate_info_.Serialize(ctx, creator);
1680
6
  info.tick_info = tick_info_.Serialize(ctx, creator);
1681
6
  info.performance_state = performance_state_->Serialize(ctx, creator);
1682
6
  info.exiting = exiting_.Serialize(ctx, creator);
1683
6
  info.stream_base_state = stream_base_state_.Serialize(ctx, creator);
1684
6
  info.should_abort_on_uncaught_toggle =
1685
6
      should_abort_on_uncaught_toggle_.Serialize(ctx, creator);
1686
1687
6
  uint32_t id = 0;
1688
#define V(PropertyName, TypeName)                                              \
1689
  do {                                                                         \
1690
    Local<TypeName> field = PropertyName();                                    \
1691
    if (!field.IsEmpty()) {                                                    \
1692
      size_t index = creator->AddData(ctx, field);                             \
1693
      info.persistent_values.push_back({#PropertyName, id, index});            \
1694
    }                                                                          \
1695
    id++;                                                                      \
1696
  } while (0);
1697
































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
































































































































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

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

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

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

73050
    } else if (metadata->wants_weak_jsobj && !persistent_handle_.IsEmpty()) {
2143
42601
      MakeWeak();
2144
    }
2145
  }
2146
741771
}
2147
2148
744116
void BaseObject::increase_refcount() {
2149
744116
  unsigned int prev_refcount = pointer_data()->strong_ptr_count++;
2150

744116
  if (prev_refcount == 0 && !persistent_handle_.IsEmpty())
2151
251778
    persistent_handle_.ClearWeak();
2152
744116
}
2153
2154
149885
void BaseObject::DeleteMe(void* data) {
2155
149885
  BaseObject* self = static_cast<BaseObject*>(data);
2156

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