GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.cc Lines: 743 802 92.6 %
Date: 2021-09-16 04:12:46 Branches: 985 1868 52.7 %

Line Branch Exec Source
1
#include "env.h"
2
#include "allocated_buffer-inl.h"
3
#include "async_wrap.h"
4
#include "base_object-inl.h"
5
#include "debug_utils-inl.h"
6
#include "diagnosticfilename-inl.h"
7
#include "memory_tracker-inl.h"
8
#include "node_buffer.h"
9
#include "node_context_data.h"
10
#include "node_errors.h"
11
#include "node_internals.h"
12
#include "node_options-inl.h"
13
#include "node_process-inl.h"
14
#include "node_v8_platform-inl.h"
15
#include "node_worker.h"
16
#include "req_wrap-inl.h"
17
#include "stream_base.h"
18
#include "tracing/agent.h"
19
#include "tracing/traced_value.h"
20
#include "util-inl.h"
21
#include "v8-profiler.h"
22
23
#include <algorithm>
24
#include <atomic>
25
#include <cinttypes>
26
#include <cstdio>
27
#include <iostream>
28
#include <limits>
29
#include <memory>
30
31
namespace node {
32
33
using errors::TryCatchScope;
34
using v8::Array;
35
using v8::Boolean;
36
using v8::Context;
37
using v8::EmbedderGraph;
38
using v8::Function;
39
using v8::FunctionTemplate;
40
using v8::HandleScope;
41
using v8::HeapSpaceStatistics;
42
using v8::Integer;
43
using v8::Isolate;
44
using v8::Local;
45
using v8::MaybeLocal;
46
using v8::NewStringType;
47
using v8::Number;
48
using v8::Object;
49
using v8::Private;
50
using v8::Script;
51
using v8::SnapshotCreator;
52
using v8::StackTrace;
53
using v8::String;
54
using v8::Symbol;
55
using v8::TracingController;
56
using v8::TryCatch;
57
using v8::Undefined;
58
using v8::Value;
59
using worker::Worker;
60
61
int const Environment::kNodeContextTag = 0x6e6f64;
62
void* const Environment::kNodeContextTagPtr = const_cast<void*>(
63
    static_cast<const void*>(&Environment::kNodeContextTag));
64
65
6
std::vector<size_t> IsolateData::Serialize(SnapshotCreator* creator) {
66
6
  Isolate* isolate = creator->GetIsolate();
67
6
  std::vector<size_t> indexes;
68
12
  HandleScope handle_scope(isolate);
69
  // XXX(joyeecheung): technically speaking, the indexes here should be
70
  // consecutive and we could just return a range instead of an array,
71
  // but that's not part of the V8 API contract so we use an array
72
  // just to be safe.
73
74
#define VP(PropertyName, StringValue) V(Private, PropertyName)
75
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
76
#define VS(PropertyName, StringValue) V(String, PropertyName)
77
#define V(TypeName, PropertyName)                                              \
78
  indexes.push_back(creator->AddData(PropertyName##_.Get(isolate)));
79
54
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
80
72
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
81
1650
  PER_ISOLATE_STRING_PROPERTIES(VS)
82
#undef V
83
#undef VY
84
#undef VS
85
#undef VP
86
354
  for (size_t i = 0; i < AsyncWrap::PROVIDERS_LENGTH; i++)
87
696
    indexes.push_back(creator->AddData(async_wrap_provider(i)));
88
89
6
  return indexes;
90
}
91
92
4843
void IsolateData::DeserializeProperties(const std::vector<size_t>* indexes) {
93
4843
  size_t i = 0;
94
9686
  HandleScope handle_scope(isolate_);
95
96
#define VP(PropertyName, StringValue) V(Private, PropertyName)
97
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
98
#define VS(PropertyName, StringValue) V(String, PropertyName)
99
#define V(TypeName, PropertyName)                                              \
100
  do {                                                                         \
101
    MaybeLocal<TypeName> maybe_field =                                         \
102
        isolate_->GetDataFromSnapshotOnce<TypeName>((*indexes)[i++]);          \
103
    Local<TypeName> field;                                                     \
104
    if (!maybe_field.ToLocal(&field)) {                                        \
105
      fprintf(stderr, "Failed to deserialize " #PropertyName "\n");            \
106
    }                                                                          \
107
    PropertyName##_.Set(isolate_, field);                                      \
108
  } while (0);
109




116232
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
110





159819
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
111









































































































































3980946
  PER_ISOLATE_STRING_PROPERTIES(VS)
112
#undef V
113
#undef VY
114
#undef VS
115
#undef VP
116
117
285737
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
118
    MaybeLocal<String> maybe_field =
119
561788
        isolate_->GetDataFromSnapshotOnce<String>((*indexes)[i++]);
120
    Local<String> field;
121
280894
    if (!maybe_field.ToLocal(&field)) {
122
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
123
    }
124
561788
    async_wrap_providers_[j].Set(isolate_, field);
125
  }
126
4843
}
127
128
634
void IsolateData::CreateProperties() {
129
  // Create string and private symbol properties as internalized one byte
130
  // strings after the platform is properly initialized.
131
  //
132
  // Internalized because it makes property lookups a little faster and
133
  // because the string is created in the old space straight away.  It's going
134
  // to end up in the old space sooner or later anyway but now it doesn't go
135
  // through v8::Eternal's new space handling first.
136
  //
137
  // One byte because our strings are ASCII and we can safely skip V8's UTF-8
138
  // decoding step.
139
140
634
  HandleScope handle_scope(isolate_);
141
142
#define V(PropertyName, StringValue)                                           \
143
  PropertyName##_.Set(                                                         \
144
      isolate_,                                                                \
145
      Private::New(isolate_,                                                   \
146
                   String::NewFromOneByte(                                     \
147
                       isolate_,                                               \
148
                       reinterpret_cast<const uint8_t*>(StringValue),          \
149
                       NewStringType::kInternalized,                           \
150
                       sizeof(StringValue) - 1)                                \
151
                       .ToLocalChecked()));
152
10144
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)
153
#undef V
154
#define V(PropertyName, StringValue)                                           \
155
  PropertyName##_.Set(                                                         \
156
      isolate_,                                                                \
157
      Symbol::New(isolate_,                                                    \
158
                  String::NewFromOneByte(                                      \
159
                      isolate_,                                                \
160
                      reinterpret_cast<const uint8_t*>(StringValue),           \
161
                      NewStringType::kInternalized,                            \
162
                      sizeof(StringValue) - 1)                                 \
163
                      .ToLocalChecked()));
164
13948
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
165
#undef V
166
#define V(PropertyName, StringValue)                                           \
167
  PropertyName##_.Set(                                                         \
168
      isolate_,                                                                \
169
      String::NewFromOneByte(isolate_,                                         \
170
                             reinterpret_cast<const uint8_t*>(StringValue),    \
171
                             NewStringType::kInternalized,                     \
172
                             sizeof(StringValue) - 1)                          \
173
          .ToLocalChecked());
174
347432
  PER_ISOLATE_STRING_PROPERTIES(V)
175
#undef V
176
177
  // Create all the provider strings that will be passed to JS. Place them in
178
  // an array so the array index matches the PROVIDER id offset. This way the
179
  // strings can be retrieved quickly.
180
#define V(Provider)                                                           \
181
  async_wrap_providers_[AsyncWrap::PROVIDER_ ## Provider].Set(                \
182
      isolate_,                                                               \
183
      String::NewFromOneByte(                                                 \
184
        isolate_,                                                             \
185
        reinterpret_cast<const uint8_t*>(#Provider),                          \
186
        NewStringType::kInternalized,                                         \
187
        sizeof(#Provider) - 1).ToLocalChecked());
188
74178
  NODE_ASYNC_PROVIDER_TYPES(V)
189
#undef V
190
634
}
191
192
5477
IsolateData::IsolateData(Isolate* isolate,
193
                         uv_loop_t* event_loop,
194
                         MultiIsolatePlatform* platform,
195
                         ArrayBufferAllocator* node_allocator,
196
5477
                         const std::vector<size_t>* indexes)
197
    : isolate_(isolate),
198
      event_loop_(event_loop),
199
47
      node_allocator_(node_allocator == nullptr ? nullptr
200
5430
                                                : node_allocator->GetImpl()),
201
10954
      platform_(platform) {
202
5477
  options_.reset(
203
5477
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
204
205
5477
  if (indexes == nullptr) {
206
634
    CreateProperties();
207
  } else {
208
4843
    DeserializeProperties(indexes);
209
  }
210
5477
}
211
212
22
void IsolateData::MemoryInfo(MemoryTracker* tracker) const {
213
#define V(PropertyName, StringValue)                                           \
214
  tracker->TrackField(#PropertyName, PropertyName());
215
22
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
216
217
22
  PER_ISOLATE_STRING_PROPERTIES(V)
218
#undef V
219
220
22
  tracker->TrackField("async_wrap_providers", async_wrap_providers_);
221
222
22
  if (node_allocator_ != nullptr) {
223
22
    tracker->TrackFieldWithSize(
224
        "node_allocator", sizeof(*node_allocator_), "NodeArrayBufferAllocator");
225
  }
226
22
  tracker->TrackFieldWithSize(
227
      "platform", sizeof(*platform_), "MultiIsolatePlatform");
228
  // TODO(joyeecheung): implement MemoryRetainer in the option classes.
229
22
}
230
231
121
void TrackingTraceStateObserver::UpdateTraceCategoryState() {
232

121
  if (!env_->owns_process_state() || !env_->can_call_into_js()) {
233
    // Ideally, we’d have a consistent story that treats all threads/Environment
234
    // instances equally here. However, tracing is essentially global, and this
235
    // callback is called from whichever thread calls `StartTracing()` or
236
    // `StopTracing()`. The only way to do this in a threadsafe fashion
237
    // seems to be only tracking this from the main thread, and only allowing
238
    // these state modifications from the main thread.
239
63
    return;
240
  }
241
242
110
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
243
110
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
244
245
110
  Isolate* isolate = env_->isolate();
246
110
  HandleScope handle_scope(isolate);
247
110
  Local<Function> cb = env_->trace_category_state_function();
248
110
  if (cb.IsEmpty())
249
52
    return;
250
58
  TryCatchScope try_catch(env_);
251
58
  try_catch.SetVerbose(true);
252
116
  Local<Value> args[] = {Boolean::New(isolate, async_hooks_enabled)};
253
116
  USE(cb->Call(env_->context(), Undefined(isolate), arraysize(args), args));
254
}
255
256
619
void Environment::CreateProperties() {
257
1238
  HandleScope handle_scope(isolate_);
258
619
  Local<Context> ctx = context();
259
260
  {
261
619
    Context::Scope context_scope(ctx);
262
619
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
263
1238
    templ->InstanceTemplate()->SetInternalFieldCount(
264
        BaseObject::kInternalFieldCount);
265
619
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
266
267
619
    set_binding_data_ctor_template(templ);
268
  }
269
270
  // Store primordials setup by the per-context script in the environment.
271
  Local<Object> per_context_bindings =
272
1238
      GetPerContextExports(ctx).ToLocalChecked();
273
  Local<Value> primordials =
274
1857
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
275
619
  CHECK(primordials->IsObject());
276
619
  set_primordials(primordials.As<Object>());
277
278
  Local<String> prototype_string =
279
619
      FIXED_ONE_BYTE_STRING(isolate(), "prototype");
280
281
#define V(EnvPropertyName, PrimordialsPropertyName)                            \
282
  {                                                                            \
283
    Local<Value> ctor =                                                        \
284
        primordials.As<Object>()                                               \
285
            ->Get(ctx,                                                         \
286
                  FIXED_ONE_BYTE_STRING(isolate(), PrimordialsPropertyName))   \
287
            .ToLocalChecked();                                                 \
288
    CHECK(ctor->IsObject());                                                   \
289
    Local<Value> prototype =                                                   \
290
        ctor.As<Object>()->Get(ctx, prototype_string).ToLocalChecked();        \
291
    CHECK(prototype->IsObject());                                              \
292
    set_##EnvPropertyName(prototype.As<Object>());                             \
293
  }
294
295

3714
  V(primordials_safe_map_prototype_object, "SafeMap");
296

3714
  V(primordials_safe_set_prototype_object, "SafeSet");
297

3714
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
298

3714
  V(primordials_safe_weak_set_prototype_object, "SafeWeakSet");
299
#undef V
300
301
  Local<Object> process_object =
302
619
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
303
619
  set_process_object(process_object);
304
619
}
305
306
5462
std::string GetExecPath(const std::vector<std::string>& argv) {
307
  char exec_path_buf[2 * PATH_MAX];
308
5462
  size_t exec_path_len = sizeof(exec_path_buf);
309
5462
  std::string exec_path;
310
5462
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
311
5462
    exec_path = std::string(exec_path_buf, exec_path_len);
312
  } else {
313
    exec_path = argv[0];
314
  }
315
316
  // On OpenBSD process.execPath will be relative unless we
317
  // get the full path before process.execPath is used.
318
#if defined(__OpenBSD__)
319
  uv_fs_t req;
320
  req.ptr = nullptr;
321
  if (0 ==
322
      uv_fs_realpath(nullptr, &req, exec_path.c_str(), nullptr)) {
323
    CHECK_NOT_NULL(req.ptr);
324
    exec_path = std::string(static_cast<char*>(req.ptr));
325
  }
326
  uv_fs_req_cleanup(&req);
327
#endif
328
329
5462
  return exec_path;
330
}
331
332
5462
Environment::Environment(IsolateData* isolate_data,
333
                         Isolate* isolate,
334
                         const std::vector<std::string>& args,
335
                         const std::vector<std::string>& exec_args,
336
                         const EnvSerializeInfo* env_info,
337
                         EnvironmentFlags::Flags flags,
338
5462
                         ThreadId thread_id)
339
    : isolate_(isolate),
340
      isolate_data_(isolate_data),
341
      async_hooks_(isolate, MAYBE_FIELD_PTR(env_info, async_hooks)),
342
      immediate_info_(isolate, MAYBE_FIELD_PTR(env_info, immediate_info)),
343
      tick_info_(isolate, MAYBE_FIELD_PTR(env_info, tick_info)),
344
5462
      timer_base_(uv_now(isolate_data->event_loop())),
345
      exec_argv_(exec_args),
346
      argv_(args),
347
      exec_path_(GetExecPath(args)),
348
      should_abort_on_uncaught_toggle_(
349
5462
          isolate_,
350
          1,
351
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
352
5462
      stream_base_state_(isolate_,
353
                         StreamBase::kNumStreamBaseStateFields,
354
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
355
5462
      environment_start_time_(PERFORMANCE_NOW()),
356
      flags_(flags),
357
5462
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
358
5462
                     ? AllocateEnvironmentThreadId().id
359



21848
                     : thread_id.id) {
360
  // We'll be creating new objects so make sure we've entered the context.
361
10924
  HandleScope handle_scope(isolate);
362
363
  // Set some flags if only kDefaultFlags was passed. This can make API version
364
  // transitions easier for embedders.
365
5462
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
366
9790
    flags_ = flags_ |
367
4895
        EnvironmentFlags::kOwnsProcessState |
368
        EnvironmentFlags::kOwnsInspector;
369
  }
370
371
5462
  set_env_vars(per_process::system_environment);
372
  // TODO(joyeecheung): pass Isolate* and env_vars to it instead of the entire
373
  // env, when the recursive dependency inclusion in "debug-utils.h" is
374
  // resolved.
375
5462
  enabled_debug_list_.Parse(this);
376
377
  // We create new copies of the per-Environment option sets, so that it is
378
  // easier to modify them after Environment creation. The defaults are
379
  // part of the per-Isolate option set, for which in turn the defaults are
380
  // part of the per-process option set.
381
10924
  options_ = std::make_shared<EnvironmentOptions>(
382
16386
      *isolate_data->options()->per_env);
383
5462
  inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
384
5462
      options_->debug_options().host_port);
385
386
5462
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
387
567
    set_abort_on_uncaught_exception(false);
388
  }
389
390
#if HAVE_INSPECTOR
391
  // We can only create the inspector agent after having cloned the options.
392
5462
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
393
#endif
394
395
5462
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
396
5462
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
397
5462
    if (TracingController* tracing_controller = writer->GetTracingController())
398
5414
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
399
  }
400
401
5462
  destroy_async_id_list_.reserve(512);
402
403
5462
  performance_state_ = std::make_unique<performance::PerformanceState>(
404
5462
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
405
406
5462
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
407
5462
          TRACING_CATEGORY_NODE1(environment)) != 0) {
408
16
    auto traced_value = tracing::TracedValue::Create();
409
8
    traced_value->BeginArray("args");
410
18
    for (const std::string& arg : args) traced_value->AppendString(arg);
411
8
    traced_value->EndArray();
412
8
    traced_value->BeginArray("exec_args");
413
33
    for (const std::string& arg : exec_args) traced_value->AppendString(arg);
414
8
    traced_value->EndArray();
415

15
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(environment),
416
                                      "Environment",
417
                                      this,
418
                                      "args",
419
                                      std::move(traced_value));
420
  }
421
5462
}
422
423
619
Environment::Environment(IsolateData* isolate_data,
424
                         Local<Context> context,
425
                         const std::vector<std::string>& args,
426
                         const std::vector<std::string>& exec_args,
427
                         const EnvSerializeInfo* env_info,
428
                         EnvironmentFlags::Flags flags,
429
619
                         ThreadId thread_id)
430
    : Environment(isolate_data,
431
                  context->GetIsolate(),
432
                  args,
433
                  exec_args,
434
                  env_info,
435
                  flags,
436
619
                  thread_id) {
437
619
  InitializeMainContext(context, env_info);
438
619
}
439
440
5462
void Environment::InitializeMainContext(Local<Context> context,
441
                                        const EnvSerializeInfo* env_info) {
442
5462
  context_.Reset(context->GetIsolate(), context);
443
5462
  AssignToContext(context, ContextInfo(""));
444
5462
  if (env_info != nullptr) {
445
4843
    DeserializeProperties(env_info);
446
  } else {
447
619
    CreateProperties();
448
  }
449
450
5462
  if (!options_->force_async_hooks_checks) {
451
1
    async_hooks_.no_force_checks();
452
  }
453
454
  // By default, always abort when --abort-on-uncaught-exception was passed.
455
5462
  should_abort_on_uncaught_toggle_[0] = 1;
456
457
5462
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
458
                           environment_start_time_);
459
5462
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
460
                           per_process::node_start_time);
461
5462
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
462
                           performance::performance_v8_start);
463
5462
}
464
465
955584
Environment::~Environment() {
466
  if (Environment** interrupt_data = interrupt_data_.load()) {
467
    // There are pending RequestInterrupt() callbacks. Tell them not to run,
468
    // then force V8 to run interrupts by compiling and running an empty script
469
    // so as not to leak memory.
470
10
    *interrupt_data = nullptr;
471
472
20
    Isolate::AllowJavascriptExecutionScope allow_js_here(isolate());
473
20
    HandleScope handle_scope(isolate());
474
20
    TryCatch try_catch(isolate());
475
20
    Context::Scope context_scope(context());
476
477
#ifdef DEBUG
478
    bool consistency_check = false;
479
    isolate()->RequestInterrupt([](Isolate*, void* data) {
480
      *static_cast<bool*>(data) = true;
481
    }, &consistency_check);
482
#endif
483
484
    Local<Script> script;
485
30
    if (Script::Compile(context(), String::Empty(isolate())).ToLocal(&script))
486
10
      USE(script->Run(context()));
487
488
    DCHECK(consistency_check);
489
  }
490
491
  // FreeEnvironment() should have set this.
492
4977
  CHECK(is_stopping());
493
494
4977
  if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
495
    isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
496
                                          0);
497
  }
498
499
4977
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
500
      BuildEmbedderGraph, this);
501
502
9954
  HandleScope handle_scope(isolate());
503
504
#if HAVE_INSPECTOR
505
  // Destroy inspector agent before erasing the context. The inspector
506
  // destructor depends on the context still being accessible.
507
4977
  inspector_agent_.reset();
508
#endif
509
510
9954
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
511
                                             nullptr);
512
513
4977
  if (trace_state_observer_) {
514
4977
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
515
4977
    CHECK_NOT_NULL(writer);
516
4977
    if (TracingController* tracing_controller = writer->GetTracingController())
517
4931
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
518
  }
519
520

9357
  TRACE_EVENT_NESTABLE_ASYNC_END0(
521
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
522
523
  // Do not unload addons on the main thread. Some addons need to retain memory
524
  // beyond the Environment's lifetime, and unloading them early would break
525
  // them; with Worker threads, we have the opportunity to be stricter.
526
  // Also, since the main thread usually stops just before the process exits,
527
  // this is far less relevant here.
528
4977
  if (!is_main_thread()) {
529
    // Dereference all addons that were loaded into this environment.
530
578
    for (binding::DLib& addon : loaded_addons_) {
531
14
      addon.Close();
532
    }
533
  }
534
535
4977
  CHECK_EQ(base_object_count_, 0);
536
4977
}
537
538
5429
void Environment::InitializeLibuv() {
539
10858
  HandleScope handle_scope(isolate());
540
5429
  Context::Scope context_scope(context());
541
542
5429
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
543
5429
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
544
545
5429
  uv_check_init(event_loop(), immediate_check_handle());
546
5429
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
547
548
5429
  uv_idle_init(event_loop(), immediate_idle_handle());
549
550
5429
  uv_check_start(immediate_check_handle(), CheckImmediate);
551
552
  // Inform V8's CPU profiler when we're idle.  The profiler is sampling-based
553
  // but not all samples are created equal; mark the wall clock time spent in
554
  // epoll_wait() and friends so profiling tools can filter it out.  The samples
555
  // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
556
5429
  uv_prepare_init(event_loop(), &idle_prepare_handle_);
557
5429
  uv_check_init(event_loop(), &idle_check_handle_);
558
559
5429
  uv_async_init(
560
      event_loop(),
561
      &task_queues_async_,
562
5053
      [](uv_async_t* async) {
563
5053
        Environment* env = ContainerOf(
564
5053
            &Environment::task_queues_async_, async);
565
10100
        HandleScope handle_scope(env->isolate());
566
5053
        Context::Scope context_scope(env->context());
567
5053
        env->RunAndClearNativeImmediates();
568
5047
      });
569
5429
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
570
5429
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
571
5429
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
572
573
  {
574
10858
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
575
5429
    task_queues_async_initialized_ = true;
576

10858
    if (native_immediates_threadsafe_.size() > 0 ||
577
5429
        native_immediates_interrupts_.size() > 0) {
578
4838
      uv_async_send(&task_queues_async_);
579
    }
580
  }
581
582
  // Register clean-up cb to be called to clean up the handles
583
  // when the environment is freed, note that they are not cleaned in
584
  // the one environment per process setup, but will be called in
585
  // FreeEnvironment.
586
5429
  RegisterHandleCleanups();
587
588
5429
  StartProfilerIdleNotifier();
589
5429
}
590
591
175
void Environment::ExitEnv() {
592
175
  set_can_call_into_js(false);
593
175
  set_stopping(true);
594
175
  isolate_->TerminateExecution();
595
350
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
596
175
}
597
598
5429
void Environment::RegisterHandleCleanups() {
599
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
600
29664
                                        void* arg) {
601
29664
    handle->data = env;
602
603
29664
    env->CloseHandle(handle, [](uv_handle_t* handle) {
604
#ifdef DEBUG
605
      memset(handle, 0xab, uv_handle_size(handle->type));
606
#endif
607
29664
    });
608
5429
  };
609
610
32574
  auto register_handle = [&](uv_handle_t* handle) {
611
32574
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
612
38003
  };
613
5429
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
614
5429
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
615
5429
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
616
5429
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
617
5429
  register_handle(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
618
5429
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
619
5429
}
620
621
9948
void Environment::CleanupHandles() {
622
  {
623
9948
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
624
9948
    task_queues_async_initialized_ = false;
625
  }
626
627
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
628
19896
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
629
630
9948
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
631
632
9964
  for (ReqWrapBase* request : req_wrap_queue_)
633
16
    request->Cancel();
634
635
12752
  for (HandleWrap* handle : handle_wrap_queue_)
636
5608
    handle->Close();
637
638
39612
  for (HandleCleanup& hc : handle_cleanup_queue_)
639
29664
    hc.cb_(this, hc.handle_, hc.arg_);
640
9948
  handle_cleanup_queue_.clear();
641
642
9393
  while (handle_cleanup_waiting_ != 0 ||
643

29291
         request_waiting_ != 0 ||
644
9950
         !handle_wrap_queue_.IsEmpty()) {
645
9393
    uv_run(event_loop(), UV_RUN_ONCE);
646
  }
647
9948
}
648
649
5429
void Environment::StartProfilerIdleNotifier() {
650
5429
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
651
172037
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
652
172037
    env->isolate()->SetIdle(true);
653
172037
  });
654
5429
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
655
171878
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
656
171878
    env->isolate()->SetIdle(false);
657
171878
  });
658
5429
}
659
660
489932
void Environment::PrintSyncTrace() const {
661
489932
  if (!trace_sync_io_) return;
662
663
2
  HandleScope handle_scope(isolate());
664
665
1
  fprintf(
666
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
667
1
  PrintStackTrace(isolate(),
668
                  StackTrace::CurrentStackTrace(
669
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
670
}
671
672
4977
void Environment::RunCleanup() {
673
4977
  started_cleanup_ = true;
674
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
675
9954
                              "RunCleanup", this);
676
4977
  bindings_.clear();
677
4977
  CleanupHandles();
678
679
14927
  while (!cleanup_hooks_.empty() ||
680
9956
         native_immediates_.size() > 0 ||
681

19904
         native_immediates_threadsafe_.size() > 0 ||
682
4977
         native_immediates_interrupts_.size() > 0) {
683
    // Copy into a vector, since we can't sort an unordered_set in-place.
684
    std::vector<CleanupHookCallback> callbacks(
685
9942
        cleanup_hooks_.begin(), cleanup_hooks_.end());
686
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
687
    // need to be able to check whether they were un-scheduled by another hook.
688
689
4971
    std::sort(callbacks.begin(), callbacks.end(),
690
700920
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
691
      // Sort in descending order so that the most recently inserted callbacks
692
      // are run first.
693
700920
      return a.insertion_order_counter_ > b.insertion_order_counter_;
694
    });
695
696
117758
    for (const CleanupHookCallback& cb : callbacks) {
697
112787
      if (cleanup_hooks_.count(cb) == 0) {
698
        // This hook was removed from the `cleanup_hooks_` set during another
699
        // hook that was run earlier. Nothing to do here.
700
758
        continue;
701
      }
702
703
112029
      cb.fn_(cb.arg_);
704
112029
      cleanup_hooks_.erase(cb);
705
    }
706
4971
    CleanupHandles();
707
  }
708
709
4980
  for (const int fd : unmanaged_fds_) {
710
    uv_fs_t close_req;
711
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
712
3
    uv_fs_req_cleanup(&close_req);
713
  }
714
4977
}
715
716
5547
void Environment::RunAtExitCallbacks() {
717
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
718
11094
                              "AtExit", this);
719
16437
  for (ExitCallback at_exit : at_exit_functions_) {
720
10890
    at_exit.cb_(at_exit.arg_);
721
  }
722
5547
  at_exit_functions_.clear();
723
5547
}
724
725
10914
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
726
10914
  at_exit_functions_.push_front(ExitCallback{cb, arg});
727
10914
}
728
729
205149
void Environment::RunAndClearInterrupts() {
730
205149
  while (native_immediates_interrupts_.size() > 0) {
731
9239
    NativeImmediateQueue queue;
732
    {
733
18478
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
734
9239
      queue.ConcatMove(std::move(native_immediates_interrupts_));
735
    }
736
9239
    DebugSealHandleScope seal_handle_scope(isolate());
737
738
18481
    while (auto head = queue.Shift())
739
18484
      head->Call(this);
740
  }
741
195910
}
742
743
186879
void Environment::RunAndClearNativeImmediates(bool only_refed) {
744
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
745
373752
                              "RunAndClearNativeImmediates", this);
746
373752
  HandleScope handle_scope(isolate_);
747
373752
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
748
749
186879
  size_t ref_count = 0;
750
751
  // Handle interrupts first. These functions are not allowed to throw
752
  // exceptions, so we do not need to handle that.
753
186879
  RunAndClearInterrupts();
754
755
373756
  auto drain_list = [&](NativeImmediateQueue* queue) {
756
747506
    TryCatchScope try_catch(this);
757
373756
    DebugSealHandleScope seal_handle_scope(isolate());
758
432806
    while (auto head = queue->Shift()) {
759
59057
      bool is_refed = head->flags() & CallbackFlags::kRefed;
760
59057
      if (is_refed)
761
35409
        ref_count++;
762
763

59057
      if (is_refed || !only_refed)
764
58882
        head->Call(this);
765
766
59053
      head.reset();  // Destroy now so that this is also observed by try_catch.
767
768
59053
      if (UNLIKELY(try_catch.HasCaught())) {
769

3
        if (!try_catch.HasTerminated() && can_call_into_js())
770
3
          errors::TriggerUncaughtException(isolate(), try_catch);
771
772
1
        return true;
773
      }
774
59050
    }
775
373749
    return false;
776
186879
  };
777
186879
  while (drain_list(&native_immediates_)) {}
778
779
186876
  immediate_info()->ref_count_dec(ref_count);
780
781
186876
  if (immediate_info()->ref_count() == 0)
782
147181
    ToggleImmediateRef(false);
783
784
  // It is safe to check .size() first, because there is a causal relationship
785
  // between pushes to the threadsafe immediate list and this function being
786
  // called. For the common case, it's worth checking the size first before
787
  // establishing a mutex lock.
788
  // This is intentionally placed after the `ref_count` handling, because when
789
  // refed threadsafe immediates are created, they are not counted towards the
790
  // count in immediate_info() either.
791
186873
  NativeImmediateQueue threadsafe_immediates;
792
186876
  if (native_immediates_threadsafe_.size() > 0) {
793
1678
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
794
839
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
795
  }
796
186877
  while (drain_list(&threadsafe_immediates)) {}
797
186873
}
798
799
9246
void Environment::RequestInterruptFromV8() {
800
  // The Isolate may outlive the Environment, so some logic to handle the
801
  // situation in which the Environment is destroyed before the handler runs
802
  // is required.
803
804
  // We allocate a new pointer to a pointer to this Environment instance, and
805
  // try to set it as interrupt_data_. If interrupt_data_ was already set, then
806
  // callbacks are already scheduled to run and we can delete our own pointer
807
  // and just return. If it was nullptr previously, the Environment** is stored;
808
  // ~Environment sets the Environment* contained in it to nullptr, so that
809
  // the callback can check whether ~Environment has already run and it is thus
810
  // not safe to access the Environment instance itself.
811
9246
  Environment** interrupt_data = new Environment*(this);
812
9246
  Environment** dummy = nullptr;
813
9246
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
814
329
    delete interrupt_data;
815
329
    return;  // Already scheduled.
816
  }
817
818
8917
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
819
8909
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
820
8909
    Environment* env = *env_ptr;
821
8909
    if (env == nullptr) {
822
      // The Environment has already been destroyed. That should be okay; any
823
      // callback added before the Environment shuts down would have been
824
      // handled during cleanup.
825
10
      return;
826
    }
827
8899
    env->interrupt_data_.store(nullptr);
828
8899
    env->RunAndClearInterrupts();
829
  }, interrupt_data);
830
}
831
832
8251
void Environment::ScheduleTimer(int64_t duration_ms) {
833
8251
  if (started_cleanup_) return;
834
8251
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
835
}
836
837
2285
void Environment::ToggleTimerRef(bool ref) {
838
2285
  if (started_cleanup_) return;
839
840
2285
  if (ref) {
841
1678
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
842
  } else {
843
607
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
844
  }
845
}
846
847
7016
void Environment::RunTimers(uv_timer_t* handle) {
848
7016
  Environment* env = Environment::from_timer_handle(handle);
849
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
850
7016
                              "RunTimers", env);
851
852
7016
  if (!env->can_call_into_js())
853
    return;
854
855
7016
  HandleScope handle_scope(env->isolate());
856
7016
  Context::Scope context_scope(env->context());
857
858
7016
  Local<Object> process = env->process_object();
859
7016
  InternalCallbackScope scope(env, process, {0, 0});
860
861
7016
  Local<Function> cb = env->timers_callback_function();
862
  MaybeLocal<Value> ret;
863
7016
  Local<Value> arg = env->GetNow();
864
  // This code will loop until all currently due timers will process. It is
865
  // impossible for us to end up in an infinite loop due to how the JS-side
866
  // is structured.
867
31
  do {
868
7047
    TryCatchScope try_catch(env);
869
7047
    try_catch.SetVerbose(true);
870
7047
    ret = cb->Call(env->context(), process, 1, &arg);
871

7037
  } while (ret.IsEmpty() && env->can_call_into_js());
872
873
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
874
  // is reset back to `true` after being previously set to `false` then this
875
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
876
  // timers corruption will occur and all timers behaviour will become
877
  // entirely unpredictable.
878
7006
  if (ret.IsEmpty())
879
8
    return;
880
881
  // To allow for less JS-C++ boundary crossing, the value returned from JS
882
  // serves a few purposes:
883
  // 1. If it's 0, no more timers exist and the handle should be unrefed
884
  // 2. If it's > 0, the value represents the next timer's expiry and there
885
  //    is at least one timer remaining that is refed.
886
  // 3. If it's < 0, the absolute value represents the next timer's expiry
887
  //    and there are no timers that are refed.
888
  int64_t expiry_ms =
889
6998
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
890
891
6998
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
892
893
6998
  if (expiry_ms != 0) {
894
    int64_t duration_ms =
895
6051
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
896
897
6051
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
898
899
6051
    if (expiry_ms > 0)
900
5752
      uv_ref(h);
901
    else
902
299
      uv_unref(h);
903
  } else {
904
947
    uv_unref(h);
905
  }
906
}
907
908
909
171878
void Environment::CheckImmediate(uv_check_t* handle) {
910
171878
  Environment* env = Environment::from_immediate_check_handle(handle);
911
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
912
171878
                              "CheckImmediate", env);
913
914
171878
  HandleScope scope(env->isolate());
915
171878
  Context::Scope context_scope(env->context());
916
917
171878
  env->RunAndClearNativeImmediates();
918
919

171878
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
920
132589
    return;
921
922
941
  do {
923
40223
    MakeCallback(env->isolate(),
924
                 env->process_object(),
925
                 env->immediate_callback_function(),
926
                 0,
927
                 nullptr,
928
40230
                 {0, 0}).ToLocalChecked();
929

40223
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
930
931
39282
  if (env->immediate_info()->ref_count() == 0)
932
4621
    env->ToggleImmediateRef(false);
933
}
934
935
214303
void Environment::ToggleImmediateRef(bool ref) {
936
214303
  if (started_cleanup_) return;
937
938
204358
  if (ref) {
939
    // Idle handle is needed only to stop the event loop from blocking in poll.
940
62478
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
941
  } else {
942
141880
    uv_idle_stop(immediate_idle_handle());
943
  }
944
}
945
946
947
26836
Local<Value> Environment::GetNow() {
948
26836
  uv_update_time(event_loop());
949
26836
  uint64_t now = uv_now(event_loop());
950
26836
  CHECK_GE(now, timer_base());
951
26836
  now -= timer_base();
952
26836
  if (now <= 0xffffffff)
953
53672
    return Integer::NewFromUnsigned(isolate(), static_cast<uint32_t>(now));
954
  else
955
    return Number::New(isolate(), static_cast<double>(now));
956
}
957
958
28
void CollectExceptionInfo(Environment* env,
959
                          Local<Object> obj,
960
                          int errorno,
961
                          const char* err_string,
962
                          const char* syscall,
963
                          const char* message,
964
                          const char* path,
965
                          const char* dest) {
966
28
  obj->Set(env->context(),
967
           env->errno_string(),
968
112
           Integer::New(env->isolate(), errorno)).Check();
969
970
28
  obj->Set(env->context(), env->code_string(),
971
84
           OneByteString(env->isolate(), err_string)).Check();
972
973
28
  if (message != nullptr) {
974
28
    obj->Set(env->context(), env->message_string(),
975
112
             OneByteString(env->isolate(), message)).Check();
976
  }
977
978
  Local<Value> path_buffer;
979
28
  if (path != nullptr) {
980
    path_buffer =
981
      Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked();
982
    obj->Set(env->context(), env->path_string(), path_buffer).Check();
983
  }
984
985
  Local<Value> dest_buffer;
986
28
  if (dest != nullptr) {
987
    dest_buffer =
988
      Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked();
989
    obj->Set(env->context(), env->dest_string(), dest_buffer).Check();
990
  }
991
992
28
  if (syscall != nullptr) {
993
28
    obj->Set(env->context(), env->syscall_string(),
994
112
             OneByteString(env->isolate(), syscall)).Check();
995
  }
996
28
}
997
998
28
void Environment::CollectUVExceptionInfo(Local<Value> object,
999
                                         int errorno,
1000
                                         const char* syscall,
1001
                                         const char* message,
1002
                                         const char* path,
1003
                                         const char* dest) {
1004

28
  if (!object->IsObject() || errorno == 0)
1005
    return;
1006
1007
28
  Local<Object> obj = object.As<Object>();
1008
28
  const char* err_string = uv_err_name(errorno);
1009
1010

28
  if (message == nullptr || message[0] == '\0') {
1011
28
    message = uv_strerror(errorno);
1012
  }
1013
1014
28
  node::CollectExceptionInfo(this, obj, errorno, err_string,
1015
                             syscall, message, path, dest);
1016
}
1017
1018
5462
ImmediateInfo::ImmediateInfo(Isolate* isolate, const SerializeInfo* info)
1019
5462
    : fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)) {}
1020
1021
6
ImmediateInfo::SerializeInfo ImmediateInfo::Serialize(
1022
    Local<Context> context, SnapshotCreator* creator) {
1023
6
  return {fields_.Serialize(context, creator)};
1024
}
1025
1026
4843
void ImmediateInfo::Deserialize(Local<Context> context) {
1027
4843
  fields_.Deserialize(context);
1028
4843
}
1029
1030
6
std::ostream& operator<<(std::ostream& output,
1031
                         const ImmediateInfo::SerializeInfo& i) {
1032
6
  output << "{ " << i.fields << " }";
1033
6
  return output;
1034
}
1035
1036
22
void ImmediateInfo::MemoryInfo(MemoryTracker* tracker) const {
1037
22
  tracker->TrackField("fields", fields_);
1038
22
}
1039
1040
6
TickInfo::SerializeInfo TickInfo::Serialize(Local<Context> context,
1041
                                            SnapshotCreator* creator) {
1042
6
  return {fields_.Serialize(context, creator)};
1043
}
1044
1045
4843
void TickInfo::Deserialize(Local<Context> context) {
1046
4843
  fields_.Deserialize(context);
1047
4843
}
1048
1049
6
std::ostream& operator<<(std::ostream& output,
1050
                         const TickInfo::SerializeInfo& i) {
1051
6
  output << "{ " << i.fields << " }";
1052
6
  return output;
1053
}
1054
1055
22
void TickInfo::MemoryInfo(MemoryTracker* tracker) const {
1056
22
  tracker->TrackField("fields", fields_);
1057
22
}
1058
1059
5462
TickInfo::TickInfo(Isolate* isolate, const SerializeInfo* info)
1060
    : fields_(
1061
5462
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1062
1063
5462
AsyncHooks::AsyncHooks(Isolate* isolate, const SerializeInfo* info)
1064
    : async_ids_stack_(isolate, 16 * 2, MAYBE_FIELD_PTR(info, async_ids_stack)),
1065
      fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)),
1066
      async_id_fields_(
1067
          isolate, kUidFieldsCount, MAYBE_FIELD_PTR(info, async_id_fields)),
1068

5462
      info_(info) {
1069
10924
  HandleScope handle_scope(isolate);
1070
5462
  if (info == nullptr) {
1071
619
    clear_async_id_stack();
1072
1073
    // Always perform async_hooks checks, not just when async_hooks is enabled.
1074
    // TODO(AndreasMadsen): Consider removing this for LTS releases.
1075
    // See discussion in https://github.com/nodejs/node/pull/15454
1076
    // When removing this, do it by reverting the commit. Otherwise the test
1077
    // and flag changes won't be included.
1078
619
    fields_[kCheck] = 1;
1079
1080
    // kDefaultTriggerAsyncId should be -1, this indicates that there is no
1081
    // specified default value and it should fallback to the executionAsyncId.
1082
    // 0 is not used as the magic value, because that indicates a missing
1083
    // context which is different from a default context.
1084
619
    async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
1085
1086
    // kAsyncIdCounter should start at 1 because that'll be the id the execution
1087
    // context during bootstrap (code that runs before entering uv_run()).
1088
619
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1089
  }
1090
5462
}
1091
1092
4843
void AsyncHooks::Deserialize(Local<Context> context) {
1093
4843
  async_ids_stack_.Deserialize(context);
1094
4843
  fields_.Deserialize(context);
1095
4843
  async_id_fields_.Deserialize(context);
1096
4843
  if (info_->js_execution_async_resources != 0) {
1097
4843
    Local<Array> arr = context->GetDataFromSnapshotOnce<Array>(
1098
9686
                                  info_->js_execution_async_resources)
1099
4843
                              .ToLocalChecked();
1100
4843
    js_execution_async_resources_.Reset(context->GetIsolate(), arr);
1101
  }
1102
1103
4843
  native_execution_async_resources_.resize(
1104
4843
      info_->native_execution_async_resources.size());
1105
4843
  for (size_t i = 0; i < info_->native_execution_async_resources.size(); ++i) {
1106
    Local<Object> obj = context->GetDataFromSnapshotOnce<Object>(
1107
                                   info_->native_execution_async_resources[i])
1108
                               .ToLocalChecked();
1109
    native_execution_async_resources_[i].Reset(context->GetIsolate(), obj);
1110
  }
1111
4843
  info_ = nullptr;
1112
4843
}
1113
1114
6
std::ostream& operator<<(std::ostream& output,
1115
                         const std::vector<SnapshotIndex>& v) {
1116
6
  output << "{ ";
1117
6
  for (const SnapshotIndex i : v) {
1118
    output << i << ", ";
1119
  }
1120
6
  output << " }";
1121
6
  return output;
1122
}
1123
1124
6
std::ostream& operator<<(std::ostream& output,
1125
                         const AsyncHooks::SerializeInfo& i) {
1126
  output << "{\n"
1127
6
         << "  " << i.async_ids_stack << ",  // async_ids_stack\n"
1128
6
         << "  " << i.fields << ",  // fields\n"
1129
6
         << "  " << i.async_id_fields << ",  // async_id_fields\n"
1130
6
         << "  " << i.js_execution_async_resources
1131
         << ",  // js_execution_async_resources\n"
1132
6
         << "  " << i.native_execution_async_resources
1133
         << ",  // native_execution_async_resources\n"
1134
6
         << "}";
1135
6
  return output;
1136
}
1137
1138
6
AsyncHooks::SerializeInfo AsyncHooks::Serialize(Local<Context> context,
1139
                                                SnapshotCreator* creator) {
1140
6
  SerializeInfo info;
1141
6
  info.async_ids_stack = async_ids_stack_.Serialize(context, creator);
1142
6
  info.fields = fields_.Serialize(context, creator);
1143
6
  info.async_id_fields = async_id_fields_.Serialize(context, creator);
1144
6
  if (!js_execution_async_resources_.IsEmpty()) {
1145
6
    info.js_execution_async_resources = creator->AddData(
1146
        context, js_execution_async_resources_.Get(context->GetIsolate()));
1147
6
    CHECK_NE(info.js_execution_async_resources, 0);
1148
  } else {
1149
    info.js_execution_async_resources = 0;
1150
  }
1151
1152
6
  info.native_execution_async_resources.resize(
1153
      native_execution_async_resources_.size());
1154
6
  for (size_t i = 0; i < native_execution_async_resources_.size(); i++) {
1155
    info.native_execution_async_resources[i] = creator->AddData(
1156
        context,
1157
        native_execution_async_resources_[i].Get(context->GetIsolate()));
1158
  }
1159
6
  CHECK_EQ(contexts_.size(), 1);
1160

12
  CHECK_EQ(contexts_[0], env()->context());
1161
6
  CHECK(js_promise_hooks_[0].IsEmpty());
1162
6
  CHECK(js_promise_hooks_[1].IsEmpty());
1163
6
  CHECK(js_promise_hooks_[2].IsEmpty());
1164
6
  CHECK(js_promise_hooks_[3].IsEmpty());
1165
1166
6
  return info;
1167
}
1168
1169
22
void AsyncHooks::MemoryInfo(MemoryTracker* tracker) const {
1170
22
  tracker->TrackField("async_ids_stack", async_ids_stack_);
1171
22
  tracker->TrackField("fields", fields_);
1172
22
  tracker->TrackField("async_id_fields", async_id_fields_);
1173
22
  tracker->TrackField("js_promise_hooks", js_promise_hooks_);
1174
22
}
1175
1176
4
void AsyncHooks::grow_async_ids_stack() {
1177
4
  async_ids_stack_.reserve(async_ids_stack_.Length() * 3);
1178
1179
4
  env()->async_hooks_binding()->Set(
1180
      env()->context(),
1181
      env()->async_ids_stack_string(),
1182
12
      async_ids_stack_.GetJSArray()).Check();
1183
4
}
1184
1185
553
void Environment::Exit(int exit_code) {
1186
553
  if (options()->trace_exit) {
1187
4
    HandleScope handle_scope(isolate());
1188
    Isolate::DisallowJavascriptExecutionScope disallow_js(
1189
4
        isolate(), Isolate::DisallowJavascriptExecutionScope::CRASH_ON_FAILURE);
1190
1191
2
    if (is_main_thread()) {
1192
1
      fprintf(stderr, "(node:%d) ", uv_os_getpid());
1193
    } else {
1194
1
      fprintf(stderr, "(node:%d, thread:%" PRIu64 ") ",
1195
              uv_os_getpid(), thread_id());
1196
    }
1197
1198
2
    fprintf(
1199
        stderr, "WARNING: Exited the environment with code %d\n", exit_code);
1200
2
    PrintStackTrace(isolate(),
1201
                    StackTrace::CurrentStackTrace(
1202
                        isolate(), stack_trace_limit(), StackTrace::kDetailed));
1203
  }
1204
553
  process_exit_handler_(this, exit_code);
1205
73
}
1206
1207
5484
void Environment::stop_sub_worker_contexts() {
1208
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1209
1210
5484
  while (!sub_worker_contexts_.empty()) {
1211
27
    Worker* w = *sub_worker_contexts_.begin();
1212
27
    remove_sub_worker_context(w);
1213
27
    w->Exit(1);
1214
27
    w->JoinThread();
1215
  }
1216
5457
}
1217
1218
10
Environment* Environment::worker_parent_env() const {
1219
10
  if (worker_context() == nullptr) return nullptr;
1220
  return worker_context()->env();
1221
}
1222
1223
54907
void Environment::AddUnmanagedFd(int fd) {
1224
54907
  if (!tracks_unmanaged_fds()) return;
1225
2013
  auto result = unmanaged_fds_.insert(fd);
1226
2013
  if (!result.second) {
1227
    ProcessEmitWarning(
1228
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1229
  }
1230
}
1231
1232
54538
void Environment::RemoveUnmanagedFd(int fd) {
1233
54538
  if (!tracks_unmanaged_fds()) return;
1234
2010
  size_t removed_count = unmanaged_fds_.erase(fd);
1235
2010
  if (removed_count == 0) {
1236
    ProcessEmitWarning(
1237
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1238
  }
1239
}
1240
1241
4779
void Environment::PrintInfoForSnapshotIfDebug() {
1242
4779
  if (enabled_debug_list()->enabled(DebugCategory::MKSNAPSHOT)) {
1243
    fprintf(stderr, "BaseObjects at the exit of the Environment:\n");
1244
    PrintAllBaseObjects();
1245
    fprintf(stderr, "\nNative modules without cache:\n");
1246
    for (const auto& s : native_modules_without_cache) {
1247
      fprintf(stderr, "%s\n", s.c_str());
1248
    }
1249
    fprintf(stderr, "\nNative modules with cache:\n");
1250
    for (const auto& s : native_modules_with_cache) {
1251
      fprintf(stderr, "%s\n", s.c_str());
1252
    }
1253
    fprintf(stderr, "\nStatic bindings (need to be registered):\n");
1254
    for (const auto mod : internal_bindings) {
1255
      fprintf(stderr, "%s:%s\n", mod->nm_filename, mod->nm_modname);
1256
    }
1257
  }
1258
4779
}
1259
1260
void Environment::PrintAllBaseObjects() {
1261
  size_t i = 0;
1262
  std::cout << "BaseObjects\n";
1263
  ForEachBaseObject([&](BaseObject* obj) {
1264
    std::cout << "#" << i++ << " " << obj << ": " <<
1265
      obj->MemoryInfoName() << "\n";
1266
  });
1267
}
1268
1269
4779
void Environment::VerifyNoStrongBaseObjects() {
1270
  // When a process exits cleanly, i.e. because the event loop ends up without
1271
  // things to wait for, the Node.js objects that are left on the heap should
1272
  // be:
1273
  //
1274
  //   1. weak, i.e. ready for garbage collection once no longer referenced, or
1275
  //   2. detached, i.e. scheduled for destruction once no longer referenced, or
1276
  //   3. an unrefed libuv handle, i.e. does not keep the event loop alive, or
1277
  //   4. an inactive libuv handle (essentially the same here)
1278
  //
1279
  // There are a few exceptions to this rule, but generally, if there are
1280
  // C++-backed Node.js objects on the heap that do not fall into the above
1281
  // categories, we may be looking at a potential memory leak. Most likely,
1282
  // the cause is a missing MakeWeak() call on the corresponding object.
1283
  //
1284
  // In order to avoid this kind of problem, we check the list of BaseObjects
1285
  // for these criteria. Currently, we only do so when explicitly instructed to
1286
  // or when in debug mode (where --verify-base-objects is always-on).
1287
1288
4779
  if (!options()->verify_base_objects) return;
1289
1290
  ForEachBaseObject([](BaseObject* obj) {
1291
    if (obj->IsNotIndicativeOfMemoryLeakAtExit()) return;
1292
    fprintf(stderr, "Found bad BaseObject during clean exit: %s\n",
1293
            obj->MemoryInfoName().c_str());
1294
    fflush(stderr);
1295
    ABORT();
1296
  });
1297
}
1298
1299
6
EnvSerializeInfo Environment::Serialize(SnapshotCreator* creator) {
1300
6
  EnvSerializeInfo info;
1301
6
  Local<Context> ctx = context();
1302
1303
6
  SerializeBindingData(this, creator, &info);
1304
  // Currently all modules are compiled without cache in builtin snapshot
1305
  // builder.
1306
12
  info.native_modules = std::vector<std::string>(
1307
6
      native_modules_without_cache.begin(), native_modules_without_cache.end());
1308
1309
6
  info.async_hooks = async_hooks_.Serialize(ctx, creator);
1310
6
  info.immediate_info = immediate_info_.Serialize(ctx, creator);
1311
6
  info.tick_info = tick_info_.Serialize(ctx, creator);
1312
6
  info.performance_state = performance_state_->Serialize(ctx, creator);
1313
6
  info.stream_base_state = stream_base_state_.Serialize(ctx, creator);
1314
6
  info.should_abort_on_uncaught_toggle =
1315
6
      should_abort_on_uncaught_toggle_.Serialize(ctx, creator);
1316
1317
6
  size_t id = 0;
1318
#define V(PropertyName, TypeName)                                              \
1319
  do {                                                                         \
1320
    Local<TypeName> field = PropertyName();                                    \
1321
    if (!field.IsEmpty()) {                                                    \
1322
      size_t index = creator->AddData(field);                                  \
1323
      info.persistent_templates.push_back({#PropertyName, id, index});         \
1324
    }                                                                          \
1325
    id++;                                                                      \
1326
  } while (0);
1327


















336
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1328
#undef V
1329
1330
6
  id = 0;
1331
#define V(PropertyName, TypeName)                                              \
1332
  do {                                                                         \
1333
    Local<TypeName> field = PropertyName();                                    \
1334
    if (!field.IsEmpty()) {                                                    \
1335
      size_t index = creator->AddData(ctx, field);                             \
1336
      info.persistent_values.push_back({#PropertyName, id, index});            \
1337
    }                                                                          \
1338
    id++;                                                                      \
1339
  } while (0);
1340




























534
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1341
#undef V
1342
1343
6
  info.context = creator->AddData(ctx, context());
1344
6
  return info;
1345
}
1346
1347
18
std::ostream& operator<<(std::ostream& output,
1348
                         const std::vector<PropInfo>& vec) {
1349
18
  output << "{\n";
1350
336
  for (const auto& info : vec) {
1351
636
    output << "  { \"" << info.name << "\", " << std::to_string(info.id) << ", "
1352
636
           << std::to_string(info.index) << " },\n";
1353
  }
1354
18
  output << "}";
1355
18
  return output;
1356
}
1357
1358
6
std::ostream& operator<<(std::ostream& output,
1359
                         const std::vector<std::string>& vec) {
1360
6
  output << "{\n";
1361
504
  for (const auto& info : vec) {
1362
498
    output << "  \"" << info << "\",\n";
1363
  }
1364
6
  output << "}";
1365
6
  return output;
1366
}
1367
1368
6
std::ostream& operator<<(std::ostream& output, const EnvSerializeInfo& i) {
1369
  output << "{\n"
1370
6
         << "// -- bindings begins --\n"
1371
6
         << i.bindings << ",\n"
1372
         << "// -- bindings ends --\n"
1373
6
         << "// -- native_modules begins --\n"
1374
6
         << i.native_modules << ",\n"
1375
         << "// -- native_modules ends --\n"
1376
6
         << "// -- async_hooks begins --\n"
1377
6
         << i.async_hooks << ",\n"
1378
6
         << "// -- async_hooks ends --\n"
1379
6
         << i.tick_info << ",  // tick_info\n"
1380
6
         << i.immediate_info << ",  // immediate_info\n"
1381
6
         << "// -- performance_state begins --\n"
1382
6
         << i.performance_state << ",\n"
1383
6
         << "// -- performance_state ends --\n"
1384
6
         << i.stream_base_state << ",  // stream_base_state\n"
1385
6
         << i.should_abort_on_uncaught_toggle
1386
         << ",  // should_abort_on_uncaught_toggle\n"
1387
6
         << "// -- persistent_templates begins --\n"
1388
6
         << i.persistent_templates << ",\n"
1389
         << "// persistent_templates ends --\n"
1390
6
         << "// -- persistent_values begins --\n"
1391
6
         << i.persistent_values << ",\n"
1392
6
         << "// -- persistent_values ends --\n"
1393
6
         << i.context << ",  // context\n"
1394
6
         << "}";
1395
6
  return output;
1396
}
1397
1398
14529
void Environment::EnqueueDeserializeRequest(DeserializeRequestCallback cb,
1399
                                            Local<Object> holder,
1400
                                            int index,
1401
                                            InternalFieldInfo* info) {
1402
29058
  DeserializeRequest request{cb, {isolate(), holder}, index, info};
1403
14529
  deserialize_requests_.push_back(std::move(request));
1404
14529
}
1405
1406
4843
void Environment::RunDeserializeRequests() {
1407
9686
  HandleScope scope(isolate());
1408
4843
  Local<Context> ctx = context();
1409
4843
  Isolate* is = isolate();
1410
19372
  while (!deserialize_requests_.empty()) {
1411
29058
    DeserializeRequest request(std::move(deserialize_requests_.front()));
1412
14529
    deserialize_requests_.pop_front();
1413
14529
    Local<Object> holder = request.holder.Get(is);
1414
14529
    request.cb(ctx, holder, request.index, request.info);
1415
    request.holder.Reset();
1416
14529
    request.info->Delete();
1417
  }
1418
4843
}
1419
1420
4843
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1421
4843
  Local<Context> ctx = context();
1422
1423
4843
  RunDeserializeRequests();
1424
1425
4843
  native_modules_in_snapshot = info->native_modules;
1426
4843
  async_hooks_.Deserialize(ctx);
1427
4843
  immediate_info_.Deserialize(ctx);
1428
4843
  tick_info_.Deserialize(ctx);
1429
4843
  performance_state_->Deserialize(ctx);
1430
4843
  stream_base_state_.Deserialize(ctx);
1431
4843
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1432
1433
4843
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1434
    fprintf(stderr, "deserializing...\n");
1435
    std::cerr << *info << "\n";
1436
  }
1437
1438
4843
  const std::vector<PropInfo>& templates = info->persistent_templates;
1439
4843
  size_t i = 0;  // index to the array
1440
4843
  size_t id = 0;
1441
#define SetProperty(PropertyName, TypeName, vector, type, from)                \
1442
  do {                                                                         \
1443
    if (vector.size() > i && id == vector[i].id) {                             \
1444
      const PropInfo& d = vector[i];                                           \
1445
      DCHECK_EQ(d.name, #PropertyName);                                        \
1446
      MaybeLocal<TypeName> maybe_field =                                       \
1447
          from->GetDataFromSnapshotOnce<TypeName>(d.index);                    \
1448
      Local<TypeName> field;                                                   \
1449
      if (!maybe_field.ToLocal(&field)) {                                      \
1450
        fprintf(stderr,                                                        \
1451
                "Failed to deserialize environment " #type " " #PropertyName   \
1452
                "\n");                                                         \
1453
      }                                                                        \
1454
      set_##PropertyName(field);                                               \
1455
      i++;                                                                     \
1456
    }                                                                          \
1457
  } while (0);                                                                 \
1458
  id++;
1459
#define V(PropertyName, TypeName) SetProperty(PropertyName, TypeName,          \
1460
                                              templates, template, isolate_)
1461








































































188877
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V);
1462
#undef V
1463
1464
4843
  i = 0;  // index to the array
1465
4843
  id = 0;
1466
4843
  const std::vector<PropInfo>& values = info->persistent_values;
1467
#define V(PropertyName, TypeName) SetProperty(PropertyName, TypeName,          \
1468
                                              values, value, ctx)
1469


















































































































455242
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1470
#undef V
1471
#undef SetProperty
1472
1473
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1474
9686
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1475
  Local<Context> ctx_from_snapshot;
1476
4843
  if (!maybe_ctx_from_snapshot.ToLocal(&ctx_from_snapshot)) {
1477
    fprintf(stderr,
1478
            "Failed to deserialize context back reference from the snapshot\n");
1479
  }
1480
4843
  CHECK_EQ(ctx_from_snapshot, ctx);
1481
4843
}
1482
1483
1
uint64_t GuessMemoryAvailableToTheProcess() {
1484
1
  uint64_t free_in_system = uv_get_free_memory();
1485
1
  size_t allowed = uv_get_constrained_memory();
1486
1
  if (allowed == 0) {
1487
    return free_in_system;
1488
  }
1489
  size_t rss;
1490
1
  int err = uv_resident_set_memory(&rss);
1491
1
  if (err) {
1492
    return free_in_system;
1493
  }
1494
1
  if (allowed < rss) {
1495
    // Something is probably wrong. Fallback to the free memory.
1496
    return free_in_system;
1497
  }
1498
  // There may still be room for swap, but we will just leave it here.
1499
1
  return allowed - rss;
1500
}
1501
1502
22
void Environment::BuildEmbedderGraph(Isolate* isolate,
1503
                                     EmbedderGraph* graph,
1504
                                     void* data) {
1505
22
  MemoryTracker tracker(isolate, graph);
1506
22
  Environment* env = static_cast<Environment*>(data);
1507
22
  tracker.Track(env);
1508
22
  env->ForEachBaseObject([&](BaseObject* obj) {
1509
440
    if (obj->IsDoneInitializing())
1510
439
      tracker.Track(obj);
1511
440
  });
1512
22
}
1513
1514
1
size_t Environment::NearHeapLimitCallback(void* data,
1515
                                          size_t current_heap_limit,
1516
                                          size_t initial_heap_limit) {
1517
1
  Environment* env = static_cast<Environment*>(data);
1518
1519
  Debug(env,
1520
        DebugCategory::DIAGNOSTICS,
1521
        "Invoked NearHeapLimitCallback, processing=%d, "
1522
        "current_limit=%" PRIu64 ", "
1523
        "initial_limit=%" PRIu64 "\n",
1524
1
        env->is_processing_heap_limit_callback_,
1525
2
        static_cast<uint64_t>(current_heap_limit),
1526
1
        static_cast<uint64_t>(initial_heap_limit));
1527
1528
1
  size_t max_young_gen_size = env->isolate_data()->max_young_gen_size;
1529
1
  size_t young_gen_size = 0;
1530
1
  size_t old_gen_size = 0;
1531
1532
1
  HeapSpaceStatistics stats;
1533
1
  size_t num_heap_spaces = env->isolate()->NumberOfHeapSpaces();
1534
9
  for (size_t i = 0; i < num_heap_spaces; ++i) {
1535
8
    env->isolate()->GetHeapSpaceStatistics(&stats, i);
1536

15
    if (strcmp(stats.space_name(), "new_space") == 0 ||
1537
7
        strcmp(stats.space_name(), "new_large_object_space") == 0) {
1538
2
      young_gen_size += stats.space_used_size();
1539
    } else {
1540
6
      old_gen_size += stats.space_used_size();
1541
    }
1542
  }
1543
1544
  Debug(env,
1545
        DebugCategory::DIAGNOSTICS,
1546
        "max_young_gen_size=%" PRIu64 ", "
1547
        "young_gen_size=%" PRIu64 ", "
1548
        "old_gen_size=%" PRIu64 ", "
1549
        "total_size=%" PRIu64 "\n",
1550
2
        static_cast<uint64_t>(max_young_gen_size),
1551
2
        static_cast<uint64_t>(young_gen_size),
1552
2
        static_cast<uint64_t>(old_gen_size),
1553
1
        static_cast<uint64_t>(young_gen_size + old_gen_size));
1554
1555
1
  uint64_t available = GuessMemoryAvailableToTheProcess();
1556
  // TODO(joyeecheung): get a better estimate about the native memory
1557
  // usage into the overhead, e.g. based on the count of objects.
1558
1
  uint64_t estimated_overhead = max_young_gen_size;
1559
  Debug(env,
1560
        DebugCategory::DIAGNOSTICS,
1561
        "Estimated available memory=%" PRIu64 ", "
1562
        "estimated overhead=%" PRIu64 "\n",
1563
2
        static_cast<uint64_t>(available),
1564
1
        static_cast<uint64_t>(estimated_overhead));
1565
1566
  // This might be hit when the snapshot is being taken in another
1567
  // NearHeapLimitCallback invocation.
1568
  // When taking the snapshot, objects in the young generation may be
1569
  // promoted to the old generation, result in increased heap usage,
1570
  // but it should be no more than the young generation size.
1571
  // Ideally, this should be as small as possible - the heap limit
1572
  // can only be restored when the heap usage falls down below the
1573
  // new limit, so in a heap with unbounded growth the isolate
1574
  // may eventually crash with this new limit - effectively raising
1575
  // the heap limit to the new one.
1576
1
  if (env->is_processing_heap_limit_callback_) {
1577
    size_t new_limit = initial_heap_limit + max_young_gen_size;
1578
    Debug(env,
1579
          DebugCategory::DIAGNOSTICS,
1580
          "Not generating snapshots in nested callback. "
1581
          "new_limit=%" PRIu64 "\n",
1582
          static_cast<uint64_t>(new_limit));
1583
    return new_limit;
1584
  }
1585
1586
  // Estimate whether the snapshot is going to use up all the memory
1587
  // available to the process. If so, just give up to prevent the system
1588
  // from killing the process for a system OOM.
1589
1
  if (estimated_overhead > available) {
1590
    Debug(env,
1591
          DebugCategory::DIAGNOSTICS,
1592
          "Not generating snapshots because it's too risky.\n");
1593
    env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
1594
                                                initial_heap_limit);
1595
    return current_heap_limit;
1596
  }
1597
1598
  // Take the snapshot synchronously.
1599
1
  env->is_processing_heap_limit_callback_ = true;
1600
1601
2
  std::string dir = env->options()->diagnostic_dir;
1602
1
  if (dir.empty()) {
1603
1
    dir = env->GetCwd();
1604
  }
1605
2
  DiagnosticFilename name(env, "Heap", "heapsnapshot");
1606
1
  std::string filename = dir + kPathSeparator + (*name);
1607
1608
1
  Debug(env, DebugCategory::DIAGNOSTICS, "Start generating %s...\n", *name);
1609
1610
  // Remove the callback first in case it's triggered when generating
1611
  // the snapshot.
1612
1
  env->isolate()->RemoveNearHeapLimitCallback(NearHeapLimitCallback,
1613
                                              initial_heap_limit);
1614
1615
1
  heap::WriteSnapshot(env->isolate(), filename.c_str());
1616
1
  env->heap_limit_snapshot_taken_ += 1;
1617
1618
  // Don't take more snapshots than the number specified by
1619
  // --heapsnapshot-near-heap-limit.
1620
2
  if (env->heap_limit_snapshot_taken_ <
1621
1
      env->options_->heap_snapshot_near_heap_limit) {
1622
    env->isolate()->AddNearHeapLimitCallback(NearHeapLimitCallback, env);
1623
  }
1624
1625
1
  FPrintF(stderr, "Wrote snapshot to %s\n", filename.c_str());
1626
  // Tell V8 to reset the heap limit once the heap usage falls down to
1627
  // 95% of the initial limit.
1628
1
  env->isolate()->AutomaticallyRestoreInitialHeapLimit(0.95);
1629
1630
1
  env->is_processing_heap_limit_callback_ = false;
1631
1
  return initial_heap_limit;
1632
}
1633
1634
22
inline size_t Environment::SelfSize() const {
1635
22
  size_t size = sizeof(*this);
1636
  // Remove non pointer fields that will be tracked in MemoryInfo()
1637
  // TODO(joyeecheung): refactor the MemoryTracker interface so
1638
  // this can be done for common types within the Track* calls automatically
1639
  // if a certain scope is entered.
1640
22
  size -= sizeof(async_hooks_);
1641
22
  size -= sizeof(tick_info_);
1642
22
  size -= sizeof(immediate_info_);
1643
22
  return size;
1644
}
1645
1646
22
void Environment::MemoryInfo(MemoryTracker* tracker) const {
1647
  // Iteratable STLs have their own sizes subtracted from the parent
1648
  // by default.
1649
22
  tracker->TrackField("isolate_data", isolate_data_);
1650
22
  tracker->TrackField("native_modules_with_cache", native_modules_with_cache);
1651
22
  tracker->TrackField("native_modules_without_cache",
1652
22
                      native_modules_without_cache);
1653
22
  tracker->TrackField("destroy_async_id_list", destroy_async_id_list_);
1654
22
  tracker->TrackField("exec_argv", exec_argv_);
1655
22
  tracker->TrackField("should_abort_on_uncaught_toggle",
1656
22
                      should_abort_on_uncaught_toggle_);
1657
22
  tracker->TrackField("stream_base_state", stream_base_state_);
1658
22
  tracker->TrackFieldWithSize(
1659
22
      "cleanup_hooks", cleanup_hooks_.size() * sizeof(CleanupHookCallback));
1660
22
  tracker->TrackField("async_hooks", async_hooks_);
1661
22
  tracker->TrackField("immediate_info", immediate_info_);
1662
22
  tracker->TrackField("tick_info", tick_info_);
1663
1664
#define V(PropertyName, TypeName)                                              \
1665
  tracker->TrackField(#PropertyName, PropertyName());
1666
22
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1667
#undef V
1668
1669
  // FIXME(joyeecheung): track other fields in Environment.
1670
  // Currently MemoryTracker is unable to track these
1671
  // correctly:
1672
  // - Internal types that do not implement MemoryRetainer yet
1673
  // - STL containers with MemoryRetainer* inside
1674
  // - STL containers with numeric types inside that should not have their
1675
  //   nodes elided e.g. numeric keys in maps.
1676
  // We also need to make sure that when we add a non-pointer field as its own
1677
  // node, we shift its sizeof() size out of the Environment node.
1678
22
}
1679
1680
685284
void Environment::RunWeakRefCleanup() {
1681
685284
  isolate()->ClearKeptObjects();
1682
685284
}
1683
1684
// Not really any better place than env.cc at this moment.
1685
105955
void BaseObject::DeleteMe(void* data) {
1686
105955
  BaseObject* self = static_cast<BaseObject*>(data);
1687

110005
  if (self->has_pointer_data() &&
1688
4050
      self->pointer_data()->strong_ptr_count > 0) {
1689
272
    return self->Detach();
1690
  }
1691
105683
  delete self;
1692
}
1693
1694
386
bool BaseObject::IsDoneInitializing() const { return true; }
1695
1696
439
Local<Object> BaseObject::WrappedObject() const {
1697
439
  return object();
1698
}
1699
1700
878
bool BaseObject::IsRootNode() const {
1701
1756
  return !persistent_handle_.IsWeak();
1702
}
1703
1704
82457
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
1705
82457
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
1706
82457
  if (tmpl.IsEmpty()) {
1707
619
    tmpl = env->NewFunctionTemplate(nullptr);
1708
619
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
1709
619
    env->set_base_object_ctor_template(tmpl);
1710
  }
1711
82457
  return tmpl;
1712
}
1713
1714
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
1715
  return IsWeakOrDetached();
1716
}
1717
1718
}  // namespace node