GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: env.cc Lines: 741 808 91.7 %
Date: 2022-04-24 04:15:40 Branches: 1003 1908 52.6 %

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
78
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
81
1644
  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
5008
void IsolateData::DeserializeProperties(const std::vector<size_t>* indexes) {
93
5008
  size_t i = 0;
94
10016
  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




85136
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
110






125200
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
111








































































































































2739376
  PER_ISOLATE_STRING_PROPERTIES(VS)
112
#undef V
113
#undef VY
114
#undef VS
115
#undef VP
116
117
295472
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
118
    MaybeLocal<String> maybe_field =
119
580928
        isolate_->GetDataFromSnapshotOnce<String>((*indexes)[i++]);
120
    Local<String> field;
121
290464
    if (!maybe_field.ToLocal(&field)) {
122
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
123
    }
124
290464
    async_wrap_providers_[j].Set(isolate_, field);
125
  }
126
5008
}
127
128
642
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
642
  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
5778
  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
8346
  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
175908
  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
37878
  NODE_ASYNC_PROVIDER_TYPES(V)
189
#undef V
190
642
}
191
192
5650
IsolateData::IsolateData(Isolate* isolate,
193
                         uv_loop_t* event_loop,
194
                         MultiIsolatePlatform* platform,
195
                         ArrayBufferAllocator* node_allocator,
196
5650
                         const std::vector<size_t>* indexes)
197
    : isolate_(isolate),
198
      event_loop_(event_loop),
199
47
      node_allocator_(node_allocator == nullptr ? nullptr
200
5603
                                                : node_allocator->GetImpl()),
201
11300
      platform_(platform) {
202
5650
  options_.reset(
203
5650
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
204
205
5650
  if (indexes == nullptr) {
206
642
    CreateProperties();
207
  } else {
208
5008
    DeserializeProperties(indexes);
209
  }
210
5650
}
211
212
23
void IsolateData::MemoryInfo(MemoryTracker* tracker) const {
213
#define V(PropertyName, StringValue)                                           \
214
  tracker->TrackField(#PropertyName, PropertyName());
215
23
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
216
217
23
  PER_ISOLATE_STRING_PROPERTIES(V)
218
#undef V
219
220
23
  tracker->TrackField("async_wrap_providers", async_wrap_providers_);
221
222
23
  if (node_allocator_ != nullptr) {
223
23
    tracker->TrackFieldWithSize(
224
        "node_allocator", sizeof(*node_allocator_), "NodeArrayBufferAllocator");
225
  }
226
23
  tracker->TrackFieldWithSize(
227
      "platform", sizeof(*platform_), "MultiIsolatePlatform");
228
  // TODO(joyeecheung): implement MemoryRetainer in the option classes.
229
23
}
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
630
void Environment::CreateProperties() {
257
1260
  HandleScope handle_scope(isolate_);
258
630
  Local<Context> ctx = context();
259
260
  {
261
630
    Context::Scope context_scope(ctx);
262
630
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
263
1260
    templ->InstanceTemplate()->SetInternalFieldCount(
264
        BaseObject::kInternalFieldCount);
265
630
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
266
267
630
    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
1260
      GetPerContextExports(ctx).ToLocalChecked();
273
  Local<Value> primordials =
274
1890
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
275
630
  CHECK(primordials->IsObject());
276
630
  set_primordials(primordials.As<Object>());
277
278
  Local<String> prototype_string =
279
630
      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

3780
  V(primordials_safe_map_prototype_object, "SafeMap");
296

3780
  V(primordials_safe_set_prototype_object, "SafeSet");
297

3780
  V(primordials_safe_weak_map_prototype_object, "SafeWeakMap");
298

3780
  V(primordials_safe_weak_set_prototype_object, "SafeWeakSet");
299
#undef V
300
301
  Local<Object> process_object =
302
630
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
303
630
  set_process_object(process_object);
304
630
}
305
306
5638
std::string GetExecPath(const std::vector<std::string>& argv) {
307
  char exec_path_buf[2 * PATH_MAX];
308
5638
  size_t exec_path_len = sizeof(exec_path_buf);
309
5638
  std::string exec_path;
310
5638
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
311
5638
    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
5638
  return exec_path;
330
}
331
332
5638
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
5638
                         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
5638
      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
5638
          isolate_,
350
          1,
351
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
352
5638
      stream_base_state_(isolate_,
353
                         StreamBase::kNumStreamBaseStateFields,
354
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
355
5638
      environment_start_time_(PERFORMANCE_NOW()),
356
      flags_(flags),
357
5638
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
358
5638
                     ? AllocateEnvironmentThreadId().id
359



22552
                     : thread_id.id) {
360
  // We'll be creating new objects so make sure we've entered the context.
361
11276
  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
5638
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
366
10120
    flags_ = flags_ |
367
5060
        EnvironmentFlags::kOwnsProcessState |
368
        EnvironmentFlags::kOwnsInspector;
369
  }
370
371
5638
  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
5638
  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
11276
  options_ = std::make_shared<EnvironmentOptions>(
382
16914
      *isolate_data->options()->per_env);
383
5638
  inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
384
5638
      options_->debug_options().host_port);
385
386
5638
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
387
578
    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
5638
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
393
#endif
394
395
5638
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
396
5638
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
397
5638
    if (TracingController* tracing_controller = writer->GetTracingController())
398
5590
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
399
  }
400
401
5638
  destroy_async_id_list_.reserve(512);
402
403
5638
  performance_state_ = std::make_unique<performance::PerformanceState>(
404
5638
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
405
406
5638
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
407
5638
          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
5638
}
422
423
630
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
630
                         ThreadId thread_id)
430
    : Environment(isolate_data,
431
                  context->GetIsolate(),
432
                  args,
433
                  exec_args,
434
                  env_info,
435
                  flags,
436
630
                  thread_id) {
437
630
  InitializeMainContext(context, env_info);
438
630
}
439
440
5638
void Environment::InitializeMainContext(Local<Context> context,
441
                                        const EnvSerializeInfo* env_info) {
442
5638
  context_.Reset(context->GetIsolate(), context);
443
5638
  AssignToContext(context, ContextInfo(""));
444
5638
  if (env_info != nullptr) {
445
5008
    DeserializeProperties(env_info);
446
  } else {
447
630
    CreateProperties();
448
  }
449
450
5638
  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
5638
  should_abort_on_uncaught_toggle_[0] = 1;
456
457
5638
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
458
                           environment_start_time_);
459
5638
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
460
                           per_process::node_start_time);
461
462
5638
  if (per_process::v8_initialized) {
463
5590
    performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
464
                            performance::performance_v8_start);
465
  }
466
5638
}
467
468
1007440
Environment::~Environment() {
469
  if (Environment** interrupt_data = interrupt_data_.load()) {
470
    // There are pending RequestInterrupt() callbacks. Tell them not to run,
471
    // then force V8 to run interrupts by compiling and running an empty script
472
    // so as not to leak memory.
473
10
    *interrupt_data = nullptr;
474
475
20
    Isolate::AllowJavascriptExecutionScope allow_js_here(isolate());
476
20
    HandleScope handle_scope(isolate());
477
20
    TryCatch try_catch(isolate());
478
20
    Context::Scope context_scope(context());
479
480
#ifdef DEBUG
481
    bool consistency_check = false;
482
    isolate()->RequestInterrupt([](Isolate*, void* data) {
483
      *static_cast<bool*>(data) = true;
484
    }, &consistency_check);
485
#endif
486
487
    Local<Script> script;
488
30
    if (Script::Compile(context(), String::Empty(isolate())).ToLocal(&script))
489
10
      USE(script->Run(context()));
490
491
    DCHECK(consistency_check);
492
  }
493
494
  // FreeEnvironment() should have set this.
495
5140
  CHECK(is_stopping());
496
497
5140
  if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
498
    isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
499
                                          0);
500
  }
501
502
5140
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
503
      BuildEmbedderGraph, this);
504
505
10280
  HandleScope handle_scope(isolate());
506
507
#if HAVE_INSPECTOR
508
  // Destroy inspector agent before erasing the context. The inspector
509
  // destructor depends on the context still being accessible.
510
5140
  inspector_agent_.reset();
511
#endif
512
513
10280
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
514
                                             nullptr);
515
516
5140
  if (trace_state_observer_) {
517
5140
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
518
5140
    CHECK_NOT_NULL(writer);
519
5140
    if (TracingController* tracing_controller = writer->GetTracingController())
520
5094
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
521
  }
522
523

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

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

30251
         request_waiting_ != 0 ||
647
10273
         !handle_wrap_queue_.IsEmpty()) {
648
9707
    uv_run(event_loop(), UV_RUN_ONCE);
649
  }
650
10271
}
651
652
5602
void Environment::StartProfilerIdleNotifier() {
653
5602
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
654
181120
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
655
181120
    env->isolate()->SetIdle(true);
656
181120
  });
657
5602
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
658
180959
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
659
180959
    env->isolate()->SetIdle(false);
660
180959
  });
661
5602
}
662
663
664658
void Environment::PrintSyncTrace() const {
664
664658
  if (!trace_sync_io_) return;
665
666
2
  HandleScope handle_scope(isolate());
667
668
1
  fprintf(
669
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
670
1
  PrintStackTrace(isolate(),
671
                  StackTrace::CurrentStackTrace(
672
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
673
}
674
675
5140
void Environment::RunCleanup() {
676
5140
  started_cleanup_ = true;
677
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
678
10280
                              "RunCleanup", this);
679
5140
  bindings_.clear();
680
5140
  CleanupHandles();
681
682
15413
  while (!cleanup_hooks_.empty() ||
683
10282
         native_immediates_.size() > 0 ||
684

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

61154
      if (is_refed || !only_refed)
767
60960
        head->Call(this);
768
769
61150
      head.reset();  // Destroy now so that this is also observed by try_catch.
770
771
61150
      if (UNLIKELY(try_catch.HasCaught())) {
772

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

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

180959
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
923
139741
    return;
924
925
946
  do {
926
42157
    MakeCallback(env->isolate(),
927
                 env->process_object(),
928
                 env->immediate_callback_function(),
929
                 0,
930
                 nullptr,
931
42164
                 {0, 0}).ToLocalChecked();
932

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

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

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

5638
      info_(info) {
1072
11276
  HandleScope handle_scope(isolate);
1073
5638
  if (info == nullptr) {
1074
630
    clear_async_id_stack();
1075
1076
    // Always perform async_hooks checks, not just when async_hooks is enabled.
1077
    // TODO(AndreasMadsen): Consider removing this for LTS releases.
1078
    // See discussion in https://github.com/nodejs/node/pull/15454
1079
    // When removing this, do it by reverting the commit. Otherwise the test
1080
    // and flag changes won't be included.
1081
630
    fields_[kCheck] = 1;
1082
1083
    // kDefaultTriggerAsyncId should be -1, this indicates that there is no
1084
    // specified default value and it should fallback to the executionAsyncId.
1085
    // 0 is not used as the magic value, because that indicates a missing
1086
    // context which is different from a default context.
1087
630
    async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
1088
1089
    // kAsyncIdCounter should start at 1 because that'll be the id the execution
1090
    // context during bootstrap (code that runs before entering uv_run()).
1091
630
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1092
  }
1093
5638
}
1094
1095
5008
void AsyncHooks::Deserialize(Local<Context> context) {
1096
5008
  async_ids_stack_.Deserialize(context);
1097
5008
  fields_.Deserialize(context);
1098
5008
  async_id_fields_.Deserialize(context);
1099
1100
  Local<Array> js_execution_async_resources;
1101
5008
  if (info_->js_execution_async_resources != 0) {
1102
    js_execution_async_resources =
1103
5008
        context->GetDataFromSnapshotOnce<Array>(
1104
15024
            info_->js_execution_async_resources).ToLocalChecked();
1105
  } else {
1106
    js_execution_async_resources = Array::New(context->GetIsolate());
1107
  }
1108
5008
  js_execution_async_resources_.Reset(
1109
      context->GetIsolate(), js_execution_async_resources);
1110
1111
  // The native_execution_async_resources_ field requires v8::Local<> instances
1112
  // for async calls whose resources were on the stack as JS objects when they
1113
  // were entered. We cannot recreate this here; however, storing these values
1114
  // on the JS equivalent gives the same result, so we do that instead.
1115
5008
  for (size_t i = 0; i < info_->native_execution_async_resources.size(); ++i) {
1116
    if (info_->native_execution_async_resources[i] == SIZE_MAX)
1117
      continue;
1118
    Local<Object> obj = context->GetDataFromSnapshotOnce<Object>(
1119
                                   info_->native_execution_async_resources[i])
1120
                               .ToLocalChecked();
1121
    js_execution_async_resources->Set(context, i, obj).Check();
1122
  }
1123
5008
  info_ = nullptr;
1124
5008
}
1125
1126
6
std::ostream& operator<<(std::ostream& output,
1127
                         const std::vector<SnapshotIndex>& v) {
1128
6
  output << "{ ";
1129
6
  for (const SnapshotIndex i : v) {
1130
    output << i << ", ";
1131
  }
1132
6
  output << " }";
1133
6
  return output;
1134
}
1135
1136
6
std::ostream& operator<<(std::ostream& output,
1137
                         const AsyncHooks::SerializeInfo& i) {
1138
  output << "{\n"
1139
6
         << "  " << i.async_ids_stack << ",  // async_ids_stack\n"
1140
6
         << "  " << i.fields << ",  // fields\n"
1141
6
         << "  " << i.async_id_fields << ",  // async_id_fields\n"
1142
6
         << "  " << i.js_execution_async_resources
1143
         << ",  // js_execution_async_resources\n"
1144
6
         << "  " << i.native_execution_async_resources
1145
         << ",  // native_execution_async_resources\n"
1146
6
         << "}";
1147
6
  return output;
1148
}
1149
1150
6
AsyncHooks::SerializeInfo AsyncHooks::Serialize(Local<Context> context,
1151
                                                SnapshotCreator* creator) {
1152
6
  SerializeInfo info;
1153
6
  info.async_ids_stack = async_ids_stack_.Serialize(context, creator);
1154
6
  info.fields = fields_.Serialize(context, creator);
1155
6
  info.async_id_fields = async_id_fields_.Serialize(context, creator);
1156
6
  if (!js_execution_async_resources_.IsEmpty()) {
1157
6
    info.js_execution_async_resources = creator->AddData(
1158
        context, js_execution_async_resources_.Get(context->GetIsolate()));
1159
6
    CHECK_NE(info.js_execution_async_resources, 0);
1160
  } else {
1161
    info.js_execution_async_resources = 0;
1162
  }
1163
1164
6
  info.native_execution_async_resources.resize(
1165
      native_execution_async_resources_.size());
1166
6
  for (size_t i = 0; i < native_execution_async_resources_.size(); i++) {
1167
    info.native_execution_async_resources[i] =
1168
        native_execution_async_resources_[i].IsEmpty() ? SIZE_MAX :
1169
            creator->AddData(
1170
                context,
1171
                native_execution_async_resources_[i]);
1172
  }
1173
6
  CHECK_EQ(contexts_.size(), 1);
1174

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


















336
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1357
#undef V
1358
1359
6
  id = 0;
1360
#define V(PropertyName, TypeName)                                              \
1361
  do {                                                                         \
1362
    Local<TypeName> field = PropertyName();                                    \
1363
    if (!field.IsEmpty()) {                                                    \
1364
      size_t index = creator->AddData(ctx, field);                             \
1365
      info.persistent_values.push_back({#PropertyName, id, index});            \
1366
    }                                                                          \
1367
    id++;                                                                      \
1368
  } while (0);
1369





























564
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1370
#undef V
1371
1372
6
  info.context = creator->AddData(ctx, context());
1373
6
  return info;
1374
}
1375
1376
18
std::ostream& operator<<(std::ostream& output,
1377
                         const std::vector<PropInfo>& vec) {
1378
18
  output << "{\n";
1379
360
  for (const auto& info : vec) {
1380
684
    output << "  { \"" << info.name << "\", " << std::to_string(info.id) << ", "
1381
684
           << std::to_string(info.index) << " },\n";
1382
  }
1383
18
  output << "}";
1384
18
  return output;
1385
}
1386
1387
6
std::ostream& operator<<(std::ostream& output,
1388
                         const std::vector<std::string>& vec) {
1389
6
  output << "{\n";
1390
678
  for (const auto& info : vec) {
1391
672
    output << "  \"" << info << "\",\n";
1392
  }
1393
6
  output << "}";
1394
6
  return output;
1395
}
1396
1397
6
std::ostream& operator<<(std::ostream& output, const EnvSerializeInfo& i) {
1398
  output << "{\n"
1399
6
         << "// -- bindings begins --\n"
1400
6
         << i.bindings << ",\n"
1401
         << "// -- bindings ends --\n"
1402
6
         << "// -- native_modules begins --\n"
1403
6
         << i.native_modules << ",\n"
1404
         << "// -- native_modules ends --\n"
1405
6
         << "// -- async_hooks begins --\n"
1406
6
         << i.async_hooks << ",\n"
1407
6
         << "// -- async_hooks ends --\n"
1408
6
         << i.tick_info << ",  // tick_info\n"
1409
6
         << i.immediate_info << ",  // immediate_info\n"
1410
6
         << "// -- performance_state begins --\n"
1411
6
         << i.performance_state << ",\n"
1412
6
         << "// -- performance_state ends --\n"
1413
6
         << i.stream_base_state << ",  // stream_base_state\n"
1414
6
         << i.should_abort_on_uncaught_toggle
1415
         << ",  // should_abort_on_uncaught_toggle\n"
1416
6
         << "// -- persistent_templates begins --\n"
1417
6
         << i.persistent_templates << ",\n"
1418
         << "// persistent_templates ends --\n"
1419
6
         << "// -- persistent_values begins --\n"
1420
6
         << i.persistent_values << ",\n"
1421
6
         << "// -- persistent_values ends --\n"
1422
6
         << i.context << ",  // context\n"
1423
6
         << "}";
1424
6
  return output;
1425
}
1426
1427
20032
void Environment::EnqueueDeserializeRequest(DeserializeRequestCallback cb,
1428
                                            Local<Object> holder,
1429
                                            int index,
1430
                                            InternalFieldInfo* info) {
1431
40064
  DeserializeRequest request{cb, {isolate(), holder}, index, info};
1432
20032
  deserialize_requests_.push_back(std::move(request));
1433
20032
}
1434
1435
5008
void Environment::RunDeserializeRequests() {
1436
10016
  HandleScope scope(isolate());
1437
5008
  Local<Context> ctx = context();
1438
5008
  Isolate* is = isolate();
1439
25040
  while (!deserialize_requests_.empty()) {
1440
40064
    DeserializeRequest request(std::move(deserialize_requests_.front()));
1441
20032
    deserialize_requests_.pop_front();
1442
20032
    Local<Object> holder = request.holder.Get(is);
1443
20032
    request.cb(ctx, holder, request.index, request.info);
1444
    request.holder.Reset();
1445
20032
    request.info->Delete();
1446
  }
1447
5008
}
1448
1449
5008
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1450
5008
  Local<Context> ctx = context();
1451
1452
5008
  RunDeserializeRequests();
1453
1454
5008
  native_modules_in_snapshot = info->native_modules;
1455
5008
  async_hooks_.Deserialize(ctx);
1456
5008
  immediate_info_.Deserialize(ctx);
1457
5008
  tick_info_.Deserialize(ctx);
1458
5008
  performance_state_->Deserialize(ctx);
1459
5008
  stream_base_state_.Deserialize(ctx);
1460
5008
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1461
1462
5008
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1463
    fprintf(stderr, "deserializing...\n");
1464
    std::cerr << *info << "\n";
1465
  }
1466
1467
5008
  const std::vector<PropInfo>& templates = info->persistent_templates;
1468
5008
  size_t i = 0;  // index to the array
1469
5008
  size_t id = 0;
1470
#define SetProperty(PropertyName, TypeName, vector, type, from)                \
1471
  do {                                                                         \
1472
    if (vector.size() > i && id == vector[i].id) {                             \
1473
      const PropInfo& d = vector[i];                                           \
1474
      DCHECK_EQ(d.name, #PropertyName);                                        \
1475
      MaybeLocal<TypeName> maybe_field =                                       \
1476
          from->GetDataFromSnapshotOnce<TypeName>(d.index);                    \
1477
      Local<TypeName> field;                                                   \
1478
      if (!maybe_field.ToLocal(&field)) {                                      \
1479
        fprintf(stderr,                                                        \
1480
                "Failed to deserialize environment " #type " " #PropertyName   \
1481
                "\n");                                                         \
1482
      }                                                                        \
1483
      set_##PropertyName(field);                                               \
1484
      i++;                                                                     \
1485
    }                                                                          \
1486
  } while (0);                                                                 \
1487
  id++;
1488
#define V(PropertyName, TypeName) SetProperty(PropertyName, TypeName,          \
1489
                                              templates, template, isolate_)
1490








































































195312
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V);
1491
#undef V
1492
1493
5008
  i = 0;  // index to the array
1494
5008
  id = 0;
1495
5008
  const std::vector<PropInfo>& values = info->persistent_values;
1496
#define V(PropertyName, TypeName) SetProperty(PropertyName, TypeName,          \
1497
                                              values, value, ctx)
1498






















































































































515824
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1499
#undef V
1500
#undef SetProperty
1501
1502
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1503
10016
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1504
  Local<Context> ctx_from_snapshot;
1505
5008
  if (!maybe_ctx_from_snapshot.ToLocal(&ctx_from_snapshot)) {
1506
    fprintf(stderr,
1507
            "Failed to deserialize context back reference from the snapshot\n");
1508
  }
1509
5008
  CHECK_EQ(ctx_from_snapshot, ctx);
1510
5008
}
1511
1512
1
uint64_t GuessMemoryAvailableToTheProcess() {
1513
1
  uint64_t free_in_system = uv_get_free_memory();
1514
1
  size_t allowed = uv_get_constrained_memory();
1515
1
  if (allowed == 0) {
1516
    return free_in_system;
1517
  }
1518
  size_t rss;
1519
1
  int err = uv_resident_set_memory(&rss);
1520
1
  if (err) {
1521
    return free_in_system;
1522
  }
1523
1
  if (allowed < rss) {
1524
    // Something is probably wrong. Fallback to the free memory.
1525
    return free_in_system;
1526
  }
1527
  // There may still be room for swap, but we will just leave it here.
1528
1
  return allowed - rss;
1529
}
1530
1531
23
void Environment::BuildEmbedderGraph(Isolate* isolate,
1532
                                     EmbedderGraph* graph,
1533
                                     void* data) {
1534
23
  MemoryTracker tracker(isolate, graph);
1535
23
  Environment* env = static_cast<Environment*>(data);
1536
23
  tracker.Track(env);
1537
23
  env->ForEachBaseObject([&](BaseObject* obj) {
1538
493
    if (obj->IsDoneInitializing())
1539
492
      tracker.Track(obj);
1540
493
  });
1541
23
}
1542
1543
1
size_t Environment::NearHeapLimitCallback(void* data,
1544
                                          size_t current_heap_limit,
1545
                                          size_t initial_heap_limit) {
1546
1
  Environment* env = static_cast<Environment*>(data);
1547
1548
  Debug(env,
1549
        DebugCategory::DIAGNOSTICS,
1550
        "Invoked NearHeapLimitCallback, processing=%d, "
1551
        "current_limit=%" PRIu64 ", "
1552
        "initial_limit=%" PRIu64 "\n",
1553
1
        env->is_processing_heap_limit_callback_,
1554
2
        static_cast<uint64_t>(current_heap_limit),
1555
1
        static_cast<uint64_t>(initial_heap_limit));
1556
1557
1
  size_t max_young_gen_size = env->isolate_data()->max_young_gen_size;
1558
1
  size_t young_gen_size = 0;
1559
1
  size_t old_gen_size = 0;
1560
1561
1
  HeapSpaceStatistics stats;
1562
1
  size_t num_heap_spaces = env->isolate()->NumberOfHeapSpaces();
1563
9
  for (size_t i = 0; i < num_heap_spaces; ++i) {
1564
8
    env->isolate()->GetHeapSpaceStatistics(&stats, i);
1565

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

136660
  if (self->has_pointer_data() &&
1722
4276
      self->pointer_data()->strong_ptr_count > 0) {
1723
280
    return self->Detach();
1724
  }
1725
132104
  delete self;
1726
}
1727
1728
437
bool BaseObject::IsDoneInitializing() const { return true; }
1729
1730
492
Local<Object> BaseObject::WrappedObject() const {
1731
492
  return object();
1732
}
1733
1734
984
bool BaseObject::IsRootNode() const {
1735
1968
  return !persistent_handle_.IsWeak();
1736
}
1737
1738
49282
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
1739
49282
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
1740
49282
  if (tmpl.IsEmpty()) {
1741
630
    tmpl = env->NewFunctionTemplate(nullptr);
1742
630
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
1743
630
    env->set_base_object_ctor_template(tmpl);
1744
  }
1745
49282
  return tmpl;
1746
}
1747
1748
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
1749
  return IsWeakOrDetached();
1750
}
1751
1752
}  // namespace node