GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/env.cc Lines: 865 928 93.2 %
Date: 2021-04-25 04:11:48 Branches: 979 1845 53.1 %

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.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::Boolean;
35
using v8::Context;
36
using v8::EmbedderGraph;
37
using v8::Function;
38
using v8::FunctionTemplate;
39
using v8::HandleScope;
40
using v8::Integer;
41
using v8::Isolate;
42
using v8::Local;
43
using v8::MaybeLocal;
44
using v8::NewStringType;
45
using v8::Number;
46
using v8::Object;
47
using v8::Private;
48
using v8::Script;
49
using v8::SnapshotCreator;
50
using v8::StackTrace;
51
using v8::String;
52
using v8::Symbol;
53
using v8::TracingController;
54
using v8::TryCatch;
55
using v8::Undefined;
56
using v8::Value;
57
using worker::Worker;
58
59
int const Environment::kNodeContextTag = 0x6e6f64;
60
void* const Environment::kNodeContextTagPtr = const_cast<void*>(
61
    static_cast<const void*>(&Environment::kNodeContextTag));
62
63
8
std::vector<size_t> IsolateData::Serialize(SnapshotCreator* creator) {
64
8
  Isolate* isolate = creator->GetIsolate();
65
8
  std::vector<size_t> indexes;
66
16
  HandleScope handle_scope(isolate);
67
  // XXX(joyeecheung): technically speaking, the indexes here should be
68
  // consecutive and we could just return a range instead of an array,
69
  // but that's not part of the V8 API contract so we use an array
70
  // just to be safe.
71
72
#define VP(PropertyName, StringValue) V(Private, PropertyName)
73
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
74
#define VS(PropertyName, StringValue) V(String, PropertyName)
75
#define V(TypeName, PropertyName)                                              \
76
  indexes.push_back(creator->AddData(PropertyName##_.Get(isolate)));
77
32
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
78
56
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
79
1800
  PER_ISOLATE_STRING_PROPERTIES(VS)
80
104
#undef V
81
96
#undef VY
82
80
#undef VS
83
48
#undef VP
84
520
  for (size_t i = 0; i < AsyncWrap::PROVIDERS_LENGTH; i++)
85
960
    indexes.push_back(creator->AddData(async_wrap_provider(i)));
86
40
87
40
  return indexes;
88
24
}
89
32
90
4737
void IsolateData::DeserializeProperties(const std::vector<size_t>* indexes) {
91
4737
  size_t i = 0;
92
9418
  HandleScope handle_scope(isolate_);
93
24
94
24
#define VP(PropertyName, StringValue) V(Private, PropertyName)
95
32
#define VY(PropertyName, StringValue) V(Symbol, PropertyName)
96
40
#define VS(PropertyName, StringValue) V(String, PropertyName)
97
40
#define V(TypeName, PropertyName)                                              \
98
24
  do {                                                                         \
99
24
    MaybeLocal<TypeName> maybe_field =                                         \
100
24
        isolate_->GetDataFromSnapshotOnce<TypeName>((*indexes)[i++]);          \
101
24
    Local<TypeName> field;                                                     \
102
24
    if (!maybe_field.ToLocal(&field)) {                                        \
103
32
      fprintf(stderr, "Failed to deserialize " #PropertyName "\n");            \
104
40
    }                                                                          \
105
40
    PropertyName##_.Set(isolate_, field);                                      \
106
40
  } while (0);
107




112752
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
108






169116
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
109







































































































































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

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

4149
  V(primordials_safe_weak_set_prototype_object, "SafeWeakSet");
297

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


505484
                     : thread_id.id) {
358
  // We'll be creating new objects so make sure we've entered the context.
359
10316
  HandleScope handle_scope(isolate);
360
361
  // Set some flags if only kDefaultFlags was passed. This can make API version
362
  // transitions easier for embedders.
363
5158
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
364
9496
    flags_ = flags_ |
365
4748
        EnvironmentFlags::kOwnsProcessState |
366
        EnvironmentFlags::kOwnsInspector;
367
  }
368
369
5158
  set_env_vars(per_process::system_environment);
370
  // TODO(joyeecheung): pass Isolate* and env_vars to it instead of the entire
371
  // env, when the recursive dependency inclusion in "debug-utils.h" is
372
  // resolved.
373
5158
  enabled_debug_list_.Parse(this);
374
375
  // We create new copies of the per-Environment option sets, so that it is
376
  // easier to modify them after Environment creation. The defaults are
377
  // part of the per-Isolate option set, for which in turn the defaults are
378
  // part of the per-process option set.
379
10316
  options_ = std::make_shared<EnvironmentOptions>(
380
15474
      *isolate_data->options()->per_env);
381
10316
  inspector_host_port_ = std::make_shared<ExclusiveAccess<HostPort>>(
382
10316
      options_->debug_options().host_port);
383
384
5158
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
385
410
    set_abort_on_uncaught_exception(false);
386
  }
387
388
#if HAVE_INSPECTOR
389
  // We can only create the inspector agent after having cloned the options.
390
5158
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
391
#endif
392
393
5158
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
394
5158
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
395
5158
    if (TracingController* tracing_controller = writer->GetTracingController())
396
5113
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
397
  }
398
399
5158
  destroy_async_id_list_.reserve(512);
400
401
10316
  performance_state_ = std::make_unique<performance::PerformanceState>(
402
15474
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
403
404
5158
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
405
          TRACING_CATEGORY_NODE1(environment)) != 0) {
406
16
    auto traced_value = tracing::TracedValue::Create();
407
8
    traced_value->BeginArray("args");
408
8
    for (const std::string& arg : args) traced_value->AppendString(arg);
409
8
    traced_value->EndArray();
410
8
    traced_value->BeginArray("exec_args");
411
8
    for (const std::string& arg : exec_args) traced_value->AppendString(arg);
412
8
    traced_value->EndArray();
413
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(environment),
414
8
                                      "Environment",
415
                                      this,
416
7
                                      "args",
417
8
                                      std::move(traced_value));
418
  }
419
5166
}
420
8
421
477
Environment::Environment(IsolateData* isolate_data,
422
                         Local<Context> context,
423
                         const std::vector<std::string>& args,
424
                         const std::vector<std::string>& exec_args,
425
                         const EnvSerializeInfo* env_info,
426
                         EnvironmentFlags::Flags flags,
427
461
                         ThreadId thread_id)
428
    : Environment(isolate_data,
429
                  context->GetIsolate(),
430
                  args,
431
                  exec_args,
432
                  env_info,
433
                  flags,
434
461
                  thread_id) {
435
461
  InitializeMainContext(context, env_info);
436
461
}
437
438
5158
void Environment::InitializeMainContext(Local<Context> context,
439
                                        const EnvSerializeInfo* env_info) {
440
5158
  context_.Reset(context->GetIsolate(), context);
441
5158
  AssignToContext(context, ContextInfo(""));
442
5158
  if (env_info != nullptr) {
443
4697
    DeserializeProperties(env_info);
444
  } else {
445
461
    CreateProperties();
446
  }
447
448
5158
  if (options_->no_force_async_hooks_checks) {
449
1
    async_hooks_.no_force_checks();
450
  }
451
452
  // By default, always abort when --abort-on-uncaught-exception was passed.
453
5158
  should_abort_on_uncaught_toggle_[0] = 1;
454
455
5158
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
456
5158
                           environment_start_time_);
457
5158
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
458
10316
                           per_process::node_start_time);
459
5158
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
460
10316
                           performance::performance_v8_start);
461
5158
}
462
463
446690
Environment::~Environment() {
464
4702
  if (Environment** interrupt_data = interrupt_data_.load()) {
465
    // There are pending RequestInterrupt() callbacks. Tell them not to run,
466
    // then force V8 to run interrupts by compiling and running an empty script
467
    // so as not to leak memory.
468
10
    *interrupt_data = nullptr;
469
470
20
    Isolate::AllowJavascriptExecutionScope allow_js_here(isolate());
471
20
    HandleScope handle_scope(isolate());
472
20
    TryCatch try_catch(isolate());
473
10
    Context::Scope context_scope(context());
474
475
#ifdef DEBUG
476
    bool consistency_check = false;
477
    isolate()->RequestInterrupt([](Isolate*, void* data) {
478
      *static_cast<bool*>(data) = true;
479
    }, &consistency_check);
480
#endif
481
482
    Local<Script> script;
483
30
    if (Script::Compile(context(), String::Empty(isolate())).ToLocal(&script))
484
20
      USE(script->Run(context()));
485
486
    DCHECK(consistency_check);
487
  }
488
489
  // FreeEnvironment() should have set this.
490
4702
  CHECK(is_stopping());
491
492
4702
  if (options_->heap_snapshot_near_heap_limit > heap_limit_snapshot_taken_) {
493
1
    isolate_->RemoveNearHeapLimitCallback(Environment::NearHeapLimitCallback,
494
1
                                          0);
495
  }
496
497
4702
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
498
4702
      BuildEmbedderGraph, this);
499
500
9404
  HandleScope handle_scope(isolate());
501
502
#if HAVE_INSPECTOR
503
  // Destroy inspector agent before erasing the context. The inspector
504
  // destructor depends on the context still being accessible.
505
4702
  inspector_agent_.reset();
506
#endif
507
508
14106
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
509
4702
                                             nullptr);
510
511
4702
  if (trace_state_observer_) {
512
4702
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
513
4702
    CHECK_NOT_NULL(writer);
514
4702
    if (TracingController* tracing_controller = writer->GetTracingController())
515
4659
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
516
  }
517
518
4702
  TRACE_EVENT_NESTABLE_ASYNC_END0(
519
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
520
521
4265
  // Do not unload addons on the main thread. Some addons need to retain memory
522
4702
  // beyond the Environment's lifetime, and unloading them early would break
523
  // them; with Worker threads, we have the opportunity to be stricter.
524
7
  // Also, since the main thread usually stops just before the process exits,
525
7
  // this is far less relevant here.
526
14
  if (!is_main_thread()) {
527
    // Dereference all addons that were loaded into this environment.
528
421
    for (binding::DLib& addon : loaded_addons_) {
529
14
      addon.Close();
530
    }
531
  }
532
533
4702
  CHECK_EQ(base_object_count_, 0);
534
9404
}
535
536
5125
void Environment::InitializeLibuv() {
537
10250
  HandleScope handle_scope(isolate());
538
5125
  Context::Scope context_scope(context());
539
540
5125
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
541
5125
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
542
543
5125
  uv_check_init(event_loop(), immediate_check_handle());
544
5125
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
545
546
5125
  uv_idle_init(event_loop(), immediate_idle_handle());
547
548
5125
  uv_check_start(immediate_check_handle(), CheckImmediate);
549
550
  // Inform V8's CPU profiler when we're idle.  The profiler is sampling-based
551
  // but not all samples are created equal; mark the wall clock time spent in
552
  // epoll_wait() and friends so profiling tools can filter it out.  The samples
553
  // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
554
5125
  uv_prepare_init(event_loop(), &idle_prepare_handle_);
555
5125
  uv_check_init(event_loop(), &idle_check_handle_);
556
557
10250
  uv_async_init(
558
      event_loop(),
559
      &task_queues_async_,
560
14003
      [](uv_async_t* async) {
561
8878
        Environment* env = ContainerOf(
562
4439
            &Environment::task_queues_async_, async);
563
8872
        HandleScope handle_scope(env->isolate());
564
4439
        Context::Scope context_scope(env->context());
565
4439
        env->RunAndClearNativeImmediates();
566
19122
      });
567
5125
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
568
5125
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
569
5125
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
570
571
  {
572
10250
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
573
5125
    task_queues_async_initialized_ = true;
574

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

55154
  while (handle_cleanup_waiting_ != 0 ||
641

27782
         request_waiting_ != 0 ||
642
9399
         !handle_wrap_queue_.IsEmpty()) {
643
8986
    uv_run(event_loop(), UV_RUN_ONCE);
644
  }
645
9397
}
646
647
5125
void Environment::StartProfilerIdleNotifier() {
648
1002107
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
649
493366
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
650
493377
    env->isolate()->SetIdle(true);
651
996992
  });
652
1001861
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
653
493243
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
654
493250
    env->isolate()->SetIdle(false);
655
996739
  });
656
5125
}
657
658
455707
void Environment::PrintSyncTrace() const {
659
455707
  if (!trace_sync_io_) return;
660
661
2
  HandleScope handle_scope(isolate());
662
663
1
  fprintf(
664
1
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
665
1
  PrintStackTrace(isolate(),
666
                  StackTrace::CurrentStackTrace(
667
1
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
668
}
669
670
4701
void Environment::RunCleanup() {
671
4701
  started_cleanup_ = true;
672
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
673
9403
                              "RunCleanup", this);
674
4701
  bindings_.clear();
675
4702
  CleanupHandles();
676
677

28193
  while (!cleanup_hooks_.empty() ||
678
9406
         native_immediates_.size() > 0 ||
679

18801
         native_immediates_threadsafe_.size() > 0 ||
680
4702
         native_immediates_interrupts_.size() > 0) {
681
    // Copy into a vector, since we can't sort an unordered_set in-place.
682
    std::vector<CleanupHookCallback> callbacks(
683
9390
        cleanup_hooks_.begin(), cleanup_hooks_.end());
684
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
685
    // need to be able to check whether they were un-scheduled by another hook.
686
687
9389
    std::sort(callbacks.begin(), callbacks.end(),
688
745353
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
689
      // Sort in descending order so that the most recently inserted callbacks
690
      // are run first.
691
745353
      return a.insertion_order_counter_ > b.insertion_order_counter_;
692
750048
    });
693
694
115632
    for (const CleanupHookCallback& cb : callbacks) {
695
110933
      if (cleanup_hooks_.count(cb) == 0) {
696
        // This hook was removed from the `cleanup_hooks_` set during another
697
        // hook that was run earlier. Nothing to do here.
698
751
        continue;
699
      }
700
701
110187
      cb.fn_(cb.arg_);
702
110202
      cleanup_hooks_.erase(cb);
703
    }
704
4695
    CleanupHandles();
705
  }
706
707
4705
  for (const int fd : unmanaged_fds_) {
708
    uv_fs_t close_req;
709
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
710
3
    uv_fs_req_cleanup(&close_req);
711
  }
712
4702
}
713
714
5228
void Environment::RunAtExitCallbacks() {
715
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
716
10456
                              "AtExit", this);
717
15506
  for (ExitCallback at_exit : at_exit_functions_) {
718
10278
    at_exit.cb_(at_exit.arg_);
719
  }
720
5228
  at_exit_functions_.clear();
721
5228
}
722
723
10302
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
724
10302
  at_exit_functions_.push_front(ExitCallback{cb, arg});
725
10302
}
726
727
523938
void Environment::RunAndClearInterrupts() {
728
532479
  while (native_immediates_interrupts_.size() > 0) {
729
17082
    NativeImmediateQueue queue;
730
    {
731
17082
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
732
8541
      queue.ConcatMove(std::move(native_immediates_interrupts_));
733
    }
734
8541
    DebugSealHandleScope seal_handle_scope(isolate());
735
736
25629
    while (auto head = queue.Shift())
737
17088
      head->Call(this);
738
  }
739
515399
}
740
741
507076
void Environment::RunAndClearNativeImmediates(bool only_refed) {
742
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
743
1014148
                              "RunAndClearNativeImmediates", this);
744
1014150
  HandleScope handle_scope(isolate_);
745
1014157
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
746
747
507080
  size_t ref_count = 0;
748
749
  // Handle interrupts first. These functions are not allowed to throw
750
  // exceptions, so we do not need to handle that.
751
507080
  RunAndClearInterrupts();
752
753
1014142
  auto drain_list = [&](NativeImmediateQueue* queue) {
754
2086844
    TryCatchScope try_catch(this);
755
1014144
    DebugSealHandleScope seal_handle_scope(isolate());
756
1131603
    while (auto head = queue->Shift()) {
757
58735
      bool is_refed = head->flags() & CallbackFlags::kRefed;
758
58735
      if (is_refed)
759
36346
        ref_count++;
760
761

58735
      if (is_refed || !only_refed)
762
117106
        head->Call(this);
763
764
58731
      head.reset();  // Destroy now so that this is also observed by try_catch.
765
766
58731
      if (UNLIKELY(try_catch.HasCaught())) {
767

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

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

493237
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
918
378280
    return;
919
920
115890
  do {
921
231787
    MakeCallback(env->isolate(),
922
                 env->process_object(),
923
                 env->immediate_callback_function(),
924
                 0,
925
                 nullptr,
926
115902
                 {0, 0}).ToLocalChecked();
927

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

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

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

10316
      info_(info) {
1067
10316
  v8::HandleScope handle_scope(isolate);
1068
5158
  if (info == nullptr) {
1069
461
    clear_async_id_stack();
1070
1071
    // Always perform async_hooks checks, not just when async_hooks is enabled.
1072
    // TODO(AndreasMadsen): Consider removing this for LTS releases.
1073
    // See discussion in https://github.com/nodejs/node/pull/15454
1074
    // When removing this, do it by reverting the commit. Otherwise the test
1075
    // and flag changes won't be included.
1076
461
    fields_[kCheck] = 1;
1077
1078
    // kDefaultTriggerAsyncId should be -1, this indicates that there is no
1079
    // specified default value and it should fallback to the executionAsyncId.
1080
    // 0 is not used as the magic value, because that indicates a missing
1081
    // context which is different from a default context.
1082
461
    async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
1083
1084
    // kAsyncIdCounter should start at 1 because that'll be the id the execution
1085
    // context during bootstrap (code that runs before entering uv_run()).
1086
461
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1087
  }
1088
5158
}
1089
1090
4697
void AsyncHooks::Deserialize(Local<Context> context) {
1091
4697
  async_ids_stack_.Deserialize(context);
1092
4697
  fields_.Deserialize(context);
1093
4697
  async_id_fields_.Deserialize(context);
1094
4697
  if (info_->js_execution_async_resources != 0) {
1095
    v8::Local<v8::Array> arr = context
1096
9394
                                   ->GetDataFromSnapshotOnce<v8::Array>(
1097
9394
                                       info_->js_execution_async_resources)
1098
4697
                                   .ToLocalChecked();
1099
4697
    js_execution_async_resources_.Reset(context->GetIsolate(), arr);
1100
  }
1101
1102
4697
  native_execution_async_resources_.resize(
1103
9394
      info_->native_execution_async_resources.size());
1104
4697
  for (size_t i = 0; i < info_->native_execution_async_resources.size(); ++i) {
1105
    v8::Local<v8::Object> obj =
1106
        context
1107
            ->GetDataFromSnapshotOnce<v8::Object>(
1108
                info_->native_execution_async_resources[i])
1109
            .ToLocalChecked();
1110
    native_execution_async_resources_[i].Reset(context->GetIsolate(), obj);
1111
  }
1112
4697
  info_ = nullptr;
1113
4697
}
1114
1115
8
std::ostream& operator<<(std::ostream& output,
1116
                         const std::vector<SnapshotIndex>& v) {
1117
8
  output << "{ ";
1118
8
  for (const SnapshotIndex i : v) {
1119
    output << i << ", ";
1120
  }
1121
8
  output << " }";
1122
8
  return output;
1123
}
1124
1125
8
std::ostream& operator<<(std::ostream& output,
1126
                         const AsyncHooks::SerializeInfo& i) {
1127
  output << "{\n"
1128
8
         << "  " << i.async_ids_stack << ",  // async_ids_stack\n"
1129
16
         << "  " << i.fields << ",  // fields\n"
1130
16
         << "  " << i.async_id_fields << ",  // async_id_fields\n"
1131
16
         << "  " << i.js_execution_async_resources
1132
         << ",  // js_execution_async_resources\n"
1133
16
         << "  " << i.native_execution_async_resources
1134
         << ",  // native_execution_async_resources\n"
1135
8
         << "}";
1136
8
  return output;
1137
}
1138
1139
8
AsyncHooks::SerializeInfo AsyncHooks::Serialize(Local<Context> context,
1140
                                                SnapshotCreator* creator) {
1141
8
  SerializeInfo info;
1142
8
  info.async_ids_stack = async_ids_stack_.Serialize(context, creator);
1143
8
  info.fields = fields_.Serialize(context, creator);
1144
8
  info.async_id_fields = async_id_fields_.Serialize(context, creator);
1145
16
  if (!js_execution_async_resources_.IsEmpty()) {
1146
16
    info.js_execution_async_resources = creator->AddData(
1147
        context, js_execution_async_resources_.Get(context->GetIsolate()));
1148
8
    CHECK_NE(info.js_execution_async_resources, 0);
1149
  } else {
1150
    info.js_execution_async_resources = 0;
1151
  }
1152
1153
8
  info.native_execution_async_resources.resize(
1154
8
      native_execution_async_resources_.size());
1155
8
  for (size_t i = 0; i < native_execution_async_resources_.size(); i++) {
1156
    info.native_execution_async_resources[i] = creator->AddData(
1157
        context,
1158
        native_execution_async_resources_[i].Get(context->GetIsolate()));
1159
  }
1160
1161
8
  return info;
1162
}
1163
1164
22
void AsyncHooks::MemoryInfo(MemoryTracker* tracker) const {
1165
22
  tracker->TrackField("async_ids_stack", async_ids_stack_);
1166
22
  tracker->TrackField("fields", fields_);
1167
22
  tracker->TrackField("async_id_fields", async_id_fields_);
1168
22
}
1169
1170
10
void AsyncHooks::grow_async_ids_stack() {
1171
10
  async_ids_stack_.reserve(async_ids_stack_.Length() * 3);
1172
1173
30
  env()->async_hooks_binding()->Set(
1174
      env()->context(),
1175
      env()->async_ids_stack_string(),
1176
50
      async_ids_stack_.GetJSArray()).Check();
1177
10
}
1178
1179
509
void Environment::Exit(int exit_code) {
1180
509
  if (options()->trace_exit) {
1181
4
    HandleScope handle_scope(isolate());
1182
    Isolate::DisallowJavascriptExecutionScope disallow_js(
1183
4
        isolate(), Isolate::DisallowJavascriptExecutionScope::CRASH_ON_FAILURE);
1184
1185
2
    if (is_main_thread()) {
1186
1
      fprintf(stderr, "(node:%d) ", uv_os_getpid());
1187
    } else {
1188
1
      fprintf(stderr, "(node:%d, thread:%" PRIu64 ") ",
1189
1
              uv_os_getpid(), thread_id());
1190
    }
1191
1192
    fprintf(
1193
2
        stderr, "WARNING: Exited the environment with code %d\n", exit_code);
1194
2
    PrintStackTrace(isolate(),
1195
                    StackTrace::CurrentStackTrace(
1196
2
                        isolate(), stack_trace_limit(), StackTrace::kDetailed));
1197
  }
1198
509
  process_exit_handler_(this, exit_code);
1199
58
}
1200
1201
5179
void Environment::stop_sub_worker_contexts() {
1202
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1203
1204
5205
  while (!sub_worker_contexts_.empty()) {
1205
26
    Worker* w = *sub_worker_contexts_.begin();
1206
26
    remove_sub_worker_context(w);
1207
26
    w->Exit(1);
1208
26
    w->JoinThread();
1209
  }
1210
5152
}
1211
1212
4
Environment* Environment::worker_parent_env() const {
1213
4
  if (worker_context() == nullptr) return nullptr;
1214
  return worker_context()->env();
1215
}
1216
1217
55061
void Environment::AddUnmanagedFd(int fd) {
1218
55061
  if (!tracks_unmanaged_fds()) return;
1219
1577
  auto result = unmanaged_fds_.insert(fd);
1220
1577
  if (!result.second) {
1221
    ProcessEmitWarning(
1222
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1223
  }
1224
}
1225
1226
54691
void Environment::RemoveUnmanagedFd(int fd) {
1227
54691
  if (!tracks_unmanaged_fds()) return;
1228
1574
  size_t removed_count = unmanaged_fds_.erase(fd);
1229
1574
  if (removed_count == 0) {
1230
    ProcessEmitWarning(
1231
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1232
  }
1233
}
1234
1235
4555
void Environment::PrintInfoForSnapshotIfDebug() {
1236
4555
  if (enabled_debug_list()->enabled(DebugCategory::MKSNAPSHOT)) {
1237
    fprintf(stderr, "BaseObjects at the exit of the Environment:\n");
1238
    PrintAllBaseObjects();
1239
    fprintf(stderr, "\nNative modules without cache:\n");
1240
    for (const auto& s : native_modules_without_cache) {
1241
      fprintf(stderr, "%s\n", s.c_str());
1242
    }
1243
    fprintf(stderr, "\nNative modules with cache:\n");
1244
    for (const auto& s : native_modules_with_cache) {
1245
      fprintf(stderr, "%s\n", s.c_str());
1246
    }
1247
    fprintf(stderr, "\nStatic bindings (need to be registered):\n");
1248
    for (const auto mod : internal_bindings) {
1249
      fprintf(stderr, "%s:%s\n", mod->nm_filename, mod->nm_modname);
1250
    }
1251
  }
1252
4555
}
1253
1254
void Environment::PrintAllBaseObjects() {
1255
  size_t i = 0;
1256
  std::cout << "BaseObjects\n";
1257
  ForEachBaseObject([&](BaseObject* obj) {
1258
    std::cout << "#" << i++ << " " << obj << ": " <<
1259
      obj->MemoryInfoName() << "\n";
1260
  });
1261
}
1262
1263
4555
void Environment::VerifyNoStrongBaseObjects() {
1264
  // When a process exits cleanly, i.e. because the event loop ends up without
1265
  // things to wait for, the Node.js objects that are left on the heap should
1266
  // be:
1267
  //
1268
  //   1. weak, i.e. ready for garbage collection once no longer referenced, or
1269
  //   2. detached, i.e. scheduled for destruction once no longer referenced, or
1270
  //   3. an unrefed libuv handle, i.e. does not keep the event loop alive, or
1271
  //   4. an inactive libuv handle (essentially the same here)
1272
  //
1273
  // There are a few exceptions to this rule, but generally, if there are
1274
  // C++-backed Node.js objects on the heap that do not fall into the above
1275
  // categories, we may be looking at a potential memory leak. Most likely,
1276
  // the cause is a missing MakeWeak() call on the corresponding object.
1277
  //
1278
  // In order to avoid this kind of problem, we check the list of BaseObjects
1279
  // for these criteria. Currently, we only do so when explicitly instructed to
1280
  // or when in debug mode (where --verify-base-objects is always-on).
1281
1282
4555
  if (!options()->verify_base_objects) return;
1283
1284
  ForEachBaseObject([](BaseObject* obj) {
1285
    if (obj->IsNotIndicativeOfMemoryLeakAtExit()) return;
1286
    fprintf(stderr, "Found bad BaseObject during clean exit: %s\n",
1287
            obj->MemoryInfoName().c_str());
1288
    fflush(stderr);
1289
    ABORT();
1290
  });
1291
}
1292
1293
8
EnvSerializeInfo Environment::Serialize(SnapshotCreator* creator) {
1294
8
  EnvSerializeInfo info;
1295
8
  Local<Context> ctx = context();
1296
1297
8
  SerializeBindingData(this, creator, &info);
1298
  // Currently all modules are compiled without cache in builtin snapshot
1299
  // builder.
1300
16
  info.native_modules = std::vector<std::string>(
1301
8
      native_modules_without_cache.begin(), native_modules_without_cache.end());
1302
1303
8
  info.async_hooks = async_hooks_.Serialize(ctx, creator);
1304
8
  info.immediate_info = immediate_info_.Serialize(ctx, creator);
1305
8
  info.tick_info = tick_info_.Serialize(ctx, creator);
1306
8
  info.performance_state = performance_state_->Serialize(ctx, creator);
1307
8
  info.stream_base_state = stream_base_state_.Serialize(ctx, creator);
1308
8
  info.should_abort_on_uncaught_toggle =
1309
8
      should_abort_on_uncaught_toggle_.Serialize(ctx, creator);
1310
1311
8
  size_t id = 0;
1312
#define V(PropertyName, TypeName)                                              \
1313
  do {                                                                         \
1314
    Local<TypeName> field = PropertyName();                                    \
1315
    if (!field.IsEmpty()) {                                                    \
1316
      size_t index = creator->AddData(field);                                  \
1317
      info.persistent_templates.push_back({#PropertyName, id, index});         \
1318
    }                                                                          \
1319
    id++;                                                                      \
1320
  } while (0);
1321










224
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1322
8
#undef V
1323
16
1324
8
  id = 0;
1325
24
#define V(PropertyName, TypeName)                                              \
1326
8
  do {                                                                         \
1327
32
    Local<TypeName> field = PropertyName();                                    \
1328
24
    if (!field.IsEmpty()) {                                                    \
1329
8
      size_t index = creator->AddData(ctx, field);                             \
1330
16
      info.persistent_values.push_back({#PropertyName, id, index});            \
1331
    }                                                                          \
1332
16
    id++;                                                                      \
1333
  } while (0);
1334




















488
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1335
16
#undef V
1336

48
1337
32
  info.context = creator->AddData(ctx, context());
1338

72
  return info;
1339

48
}
1340
48
1341

72
std::ostream& operator<<(std::ostream& output,
1342
16
                         const std::vector<PropInfo>& vec) {
1343

56
  output << "{\n";
1344
400
  for (const auto& info : vec) {
1345

760
    output << "  { \"" << info.name << "\", " << std::to_string(info.id) << ", "
1346
1088
           << std::to_string(info.index) << " },\n";
1347

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








































































145607
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V);
1456
#undef V
1457
1458
4697
  i = 0;  // index to the array
1459
4697
  id = 0;
1460
4697
  const std::vector<PropInfo>& values = info->persistent_values;
1461
#define V(PropertyName, TypeName) SetProperty(PropertyName, TypeName,          \
1462
                                              values, value, ctx)
1463














































































































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

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

107775
  if (self->has_pointer_data() &&
1682
4077
      self->pointer_data()->strong_ptr_count > 0) {
1683
292
    return self->Detach();
1684
22
  }
1685
103452
  delete self;
1686
22
}
1687
22
1688
386
bool BaseObject::IsDoneInitializing() const { return true; }
1689
22
1690
448
Local<Object> BaseObject::WrappedObject() const {
1691
448
  return object();
1692
}
1693
1694
852
bool BaseObject::IsRootNode() const {
1695
1704
  return !persistent_handle_.IsWeak();
1696
}
1697
1698
81682
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
1699
81682
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
1700
81682
  if (tmpl.IsEmpty()) {
1701
461
    tmpl = env->NewFunctionTemplate(nullptr);
1702
922
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
1703
461
    env->set_base_object_ctor_template(tmpl);
1704
  }
1705
81682
  return tmpl;
1706
}
1707
1708
bool BaseObject::IsNotIndicativeOfMemoryLeakAtExit() const {
1709
  return IsWeakOrDetached();
1710
}
1711
1712

14316
}  // namespace node