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: 655 690 94.9 %
Date: 2020-08-07 22:13:19 Branches: 857 1631 52.5 %

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




139840
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
105






209760
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
106




















































































































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

119
  if (!env_->owns_process_state() || !env_->can_call_into_js()) {
234
    // Ideally, we’d have a consistent story that treats all threads/Environment
235
    // instances equally here. However, tracing is essentially global, and this
236
    // callback is called from whichever thread calls `StartTracing()` or
237
    // `StopTracing()`. The only way to do this in a threadsafe fashion
238
    // seems to be only tracking this from the main thread, and only allowing
239
    // these state modifications from the main thread.
240
68
    return;
241
  }
242
243
111
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
244
111
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
245
246
111
  Isolate* isolate = env_->isolate();
247
170
  HandleScope handle_scope(isolate);
248
111
  Local<Function> cb = env_->trace_category_state_function();
249
111
  if (cb.IsEmpty())
250
52
    return;
251
118
  TryCatchScope try_catch(env_);
252
59
  try_catch.SetVerbose(true);
253
118
  Local<Value> args[] = {Boolean::New(isolate, async_hooks_enabled)};
254
177
  USE(cb->Call(env_->context(), Undefined(isolate), arraysize(args), args));
255
}
256
257
390
void Environment::CreateProperties() {
258
780
  HandleScope handle_scope(isolate_);
259
390
  Local<Context> ctx = context();
260
261
  {
262
    Context::Scope context_scope(ctx);
263
390
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
264
1170
    templ->InstanceTemplate()->SetInternalFieldCount(
265
390
        BaseObject::kInternalFieldCount);
266
780
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
267
268
390
    set_binding_data_ctor_template(templ);
269
  }
270
271
  // Store primordials setup by the per-context script in the environment.
272
  Local<Object> per_context_bindings =
273
780
      GetPerContextExports(ctx).ToLocalChecked();
274
  Local<Value> primordials =
275
1170
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
276
390
  CHECK(primordials->IsObject());
277
390
  set_primordials(primordials.As<Object>());
278
279
  Local<Object> process_object =
280
780
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
281
390
  set_process_object(process_object);
282
390
}
283
284
4759
std::string GetExecPath(const std::vector<std::string>& argv) {
285
  char exec_path_buf[2 * PATH_MAX];
286
4759
  size_t exec_path_len = sizeof(exec_path_buf);
287
4759
  std::string exec_path;
288
4759
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
289
4759
    exec_path = std::string(exec_path_buf, exec_path_len);
290
  } else {
291
    exec_path = argv[0];
292
  }
293
294
  // On OpenBSD process.execPath will be relative unless we
295
  // get the full path before process.execPath is used.
296
#if defined(__OpenBSD__)
297
  uv_fs_t req;
298
  req.ptr = nullptr;
299
  if (0 ==
300
      uv_fs_realpath(nullptr, &req, exec_path.c_str(), nullptr)) {
301
    CHECK_NOT_NULL(req.ptr);
302
    exec_path = std::string(static_cast<char*>(req.ptr));
303
  }
304
  uv_fs_req_cleanup(&req);
305
#endif
306
307
4759
  return exec_path;
308
}
309
310
4759
Environment::Environment(IsolateData* isolate_data,
311
                         Isolate* isolate,
312
                         const std::vector<std::string>& args,
313
                         const std::vector<std::string>& exec_args,
314
                         const EnvSerializeInfo* env_info,
315
                         EnvironmentFlags::Flags flags,
316
4759
                         ThreadId thread_id)
317
    : isolate_(isolate),
318
      isolate_data_(isolate_data),
319
      async_hooks_(isolate, MAYBE_FIELD_PTR(env_info, async_hooks)),
320
      immediate_info_(isolate, MAYBE_FIELD_PTR(env_info, immediate_info)),
321
      tick_info_(isolate, MAYBE_FIELD_PTR(env_info, tick_info)),
322
4759
      timer_base_(uv_now(isolate_data->event_loop())),
323
      exec_argv_(exec_args),
324
      argv_(args),
325
      exec_path_(GetExecPath(args)),
326
      should_abort_on_uncaught_toggle_(
327
4759
          isolate_,
328
          1,
329
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
330
4759
      stream_base_state_(isolate_,
331
                         StreamBase::kNumStreamBaseStateFields,
332
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
333
4759
      environment_start_time_(PERFORMANCE_NOW()),
334
      flags_(flags),
335
4759
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
336
4759
                     ? AllocateEnvironmentThreadId().id
337


423551
                     : thread_id.id) {
338
  // We'll be creating new objects so make sure we've entered the context.
339
9518
  HandleScope handle_scope(isolate);
340
341
  // Set some flags if only kDefaultFlags was passed. This can make API version
342
  // transitions easier for embedders.
343
4759
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
344
8822
    flags_ = flags_ |
345
4411
        EnvironmentFlags::kOwnsProcessState |
346
        EnvironmentFlags::kOwnsInspector;
347
  }
348
349
4759
  set_env_vars(per_process::system_environment);
350
  // TODO(joyeecheung): pass Isolate* and env_vars to it instead of the entire
351
  // env
352
4759
  enabled_debug_list_.Parse(this);
353
354
  // We create new copies of the per-Environment option sets, so that it is
355
  // easier to modify them after Environment creation. The defaults are
356
  // part of the per-Isolate option set, for which in turn the defaults are
357
  // part of the per-process option set.
358
4759
  options_.reset(new EnvironmentOptions(*isolate_data->options()->per_env));
359
9518
  inspector_host_port_.reset(
360
14277
      new ExclusiveAccess<HostPort>(options_->debug_options().host_port));
361
362
4759
  if (flags & EnvironmentFlags::kOwnsProcessState) {
363
    set_abort_on_uncaught_exception(false);
364
  }
365
366
#if HAVE_INSPECTOR
367
  // We can only create the inspector agent after having cloned the options.
368
4759
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
369
#endif
370
371
  static uv_once_t init_once = UV_ONCE_INIT;
372
4759
  uv_once(&init_once, InitThreadLocalOnce);
373
4759
  uv_key_set(&thread_local_env, this);
374
375
4759
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
376
4759
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
377
4759
    if (TracingController* tracing_controller = writer->GetTracingController())
378
4717
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
379
  }
380
381
4759
  destroy_async_id_list_.reserve(512);
382
383
9518
  performance_state_ = std::make_unique<performance::PerformanceState>(
384
14277
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
385
386
4759
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
387
          TRACING_CATEGORY_NODE1(environment)) != 0) {
388
16
    auto traced_value = tracing::TracedValue::Create();
389
8
    traced_value->BeginArray("args");
390
8
    for (const std::string& arg : args) traced_value->AppendString(arg);
391
8
    traced_value->EndArray();
392
8
    traced_value->BeginArray("exec_args");
393
8
    for (const std::string& arg : exec_args) traced_value->AppendString(arg);
394
8
    traced_value->EndArray();
395

16
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(environment),
396
                                      "Environment",
397
                                      this,
398
                                      "args",
399
                                      std::move(traced_value));
400
  }
401
402
  // This adjusts the return value of base_object_count() so that tests that
403
  // check the count do not have to account for internally created BaseObjects.
404
4759
  initial_base_object_count_ = base_object_count();
405
4759
}
406
407
389
Environment::Environment(IsolateData* isolate_data,
408
                         Local<Context> context,
409
                         const std::vector<std::string>& args,
410
                         const std::vector<std::string>& exec_args,
411
                         const EnvSerializeInfo* env_info,
412
                         EnvironmentFlags::Flags flags,
413
389
                         ThreadId thread_id)
414
    : Environment(isolate_data,
415
                  context->GetIsolate(),
416
                  args,
417
                  exec_args,
418
                  env_info,
419
                  flags,
420
389
                  thread_id) {
421
389
  InitializeMainContext(context, env_info);
422
389
}
423
424
4760
void Environment::InitializeMainContext(Local<Context> context,
425
                                        const EnvSerializeInfo* env_info) {
426
4760
  context_.Reset(context->GetIsolate(), context);
427
4760
  AssignToContext(context, ContextInfo(""));
428
4760
  if (env_info != nullptr) {
429
4370
    DeserializeProperties(env_info);
430
  } else {
431
390
    CreateProperties();
432
  }
433
434
4760
  if (options_->no_force_async_hooks_checks) {
435
1
    async_hooks_.no_force_checks();
436
  }
437
438
  // By default, always abort when --abort-on-uncaught-exception was passed.
439
4760
  should_abort_on_uncaught_toggle_[0] = 1;
440
441
4760
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
442
4760
                           environment_start_time_);
443
4760
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
444
9520
                           per_process::node_start_time);
445
4760
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
446
9520
                           performance::performance_v8_start);
447
448
  // This adjusts the return value of base_object_count() so that tests that
449
  // check the count do not have to account for internally created BaseObjects.
450
4760
  initial_base_object_count_ = base_object_count();
451
4760
}
452
453
368836
Environment::~Environment() {
454
4292
  if (Environment** interrupt_data = interrupt_data_.load()) {
455
    // There are pending RequestInterrupt() callbacks. Tell them not to run,
456
    // then force V8 to run interrupts by compiling and running an empty script
457
    // so as not to leak memory.
458
11
    *interrupt_data = nullptr;
459
460
22
    Isolate::AllowJavascriptExecutionScope allow_js_here(isolate());
461
22
    HandleScope handle_scope(isolate());
462
22
    TryCatch try_catch(isolate());
463
11
    Context::Scope context_scope(context());
464
465
#ifdef DEBUG
466
    bool consistency_check = false;
467
    isolate()->RequestInterrupt([](Isolate*, void* data) {
468
      *static_cast<bool*>(data) = true;
469
    }, &consistency_check);
470
#endif
471
472
    Local<Script> script;
473
33
    if (Script::Compile(context(), String::Empty(isolate())).ToLocal(&script))
474
22
      USE(script->Run(context()));
475
476
    DCHECK(consistency_check);
477
  }
478
479
  // FreeEnvironment() should have set this.
480
4293
  CHECK(is_stopping());
481
482
4292
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
483
4293
      BuildEmbedderGraph, this);
484
485
8586
  HandleScope handle_scope(isolate());
486
487
#if HAVE_INSPECTOR
488
  // Destroy inspector agent before erasing the context. The inspector
489
  // destructor depends on the context still being accessible.
490
4293
  inspector_agent_.reset();
491
#endif
492
493
12877
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
494
4292
                                             nullptr);
495
496
4293
  if (trace_state_observer_) {
497
4293
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
498
4293
    CHECK_NOT_NULL(writer);
499
4293
    if (TracingController* tracing_controller = writer->GetTracingController())
500
4252
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
501
  }
502
503

8586
  TRACE_EVENT_NESTABLE_ASYNC_END0(
504
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
505
506
  // Do not unload addons on the main thread. Some addons need to retain memory
507
  // beyond the Environment's lifetime, and unloading them early would break
508
  // them; with Worker threads, we have the opportunity to be stricter.
509
  // Also, since the main thread usually stops just before the process exits,
510
  // this is far less relevant here.
511
4293
  if (!is_main_thread()) {
512
    // Dereference all addons that were loaded into this environment.
513
359
    for (binding::DLib& addon : loaded_addons_) {
514
14
      addon.Close();
515
    }
516
  }
517
518
4293
  CHECK_EQ(base_object_count_, 0);
519
8585
}
520
521
4732
void Environment::InitializeLibuv() {
522
9464
  HandleScope handle_scope(isolate());
523
4732
  Context::Scope context_scope(context());
524
525
4732
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
526
4732
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
527
528
4732
  uv_check_init(event_loop(), immediate_check_handle());
529
4732
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
530
531
4732
  uv_idle_init(event_loop(), immediate_idle_handle());
532
533
4732
  uv_check_start(immediate_check_handle(), CheckImmediate);
534
535
9464
  uv_async_init(
536
      event_loop(),
537
      &task_queues_async_,
538
11878
      [](uv_async_t* async) {
539
7146
        Environment* env = ContainerOf(
540
3573
            &Environment::task_queues_async_, async);
541
3573
        env->RunAndClearNativeImmediates();
542
16607
      });
543
4732
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
544
545
  {
546
9464
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
547
4732
    task_queues_async_initialized_ = true;
548

9464
    if (native_immediates_threadsafe_.size() > 0 ||
549
4732
        native_immediates_interrupts_.size() > 0) {
550
4364
      uv_async_send(&task_queues_async_);
551
    }
552
  }
553
554
  // Register clean-up cb to be called to clean up the handles
555
  // when the environment is freed, note that they are not cleaned in
556
  // the one environment per process setup, but will be called in
557
  // FreeEnvironment.
558
4732
  RegisterHandleCleanups();
559
4732
}
560
561
91
void Environment::ExitEnv() {
562
91
  set_can_call_into_js(false);
563
91
  set_stopping(true);
564
91
  isolate_->TerminateExecution();
565
182
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
566
91
}
567
568
4732
void Environment::RegisterHandleCleanups() {
569
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
570
38856
                                        void* arg) {
571
17063
    handle->data = env;
572
573
34126
    env->CloseHandle(handle, [](uv_handle_t* handle) {
574
#ifdef DEBUG
575
      memset(handle, 0xab, uv_handle_size(handle->type));
576
#endif
577
34126
    });
578
43588
  };
579
580
18928
  auto register_handle = [&](uv_handle_t* handle) {
581
18928
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
582
23660
  };
583
4732
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
584
4732
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
585
4732
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
586
4732
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
587
4732
}
588
589
8581
void Environment::CleanupHandles() {
590
  {
591
17165
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
592
8584
    task_queues_async_initialized_ = false;
593
  }
594
595
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
596
17166
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
597
598
8583
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
599
600
8620
  for (ReqWrapBase* request : req_wrap_queue_)
601
39
    request->Cancel();
602
603
10853
  for (HandleWrap* handle : handle_wrap_queue_)
604
4538
    handle->Close();
605
606
25647
  for (HandleCleanup& hc : handle_cleanup_queue_)
607
17062
    hc.cb_(this, hc.handle_, hc.arg_);
608
8583
  handle_cleanup_queue_.clear();
609
610

50457
  while (handle_cleanup_waiting_ != 0 ||
611

25403
         request_waiting_ != 0 ||
612
8585
         !handle_wrap_queue_.IsEmpty()) {
613
8236
    uv_run(event_loop(), UV_RUN_ONCE);
614
  }
615
8584
}
616
617
309049
void Environment::PrintSyncTrace() const {
618
309049
  if (!trace_sync_io_) return;
619
620
2
  HandleScope handle_scope(isolate());
621
622
1
  fprintf(
623
1
      stderr, "(node:%d) WARNING: Detected use of sync API\n", uv_os_getpid());
624
1
  PrintStackTrace(isolate(),
625
                  StackTrace::CurrentStackTrace(
626
1
                      isolate(), stack_trace_limit(), StackTrace::kDetailed));
627
}
628
629
4291
void Environment::RunCleanup() {
630
4291
  started_cleanup_ = true;
631
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
632
8584
                              "RunCleanup", this);
633
4293
  bindings_.clear();
634
4292
  initial_base_object_count_ = 0;
635
4292
  CleanupHandles();
636
637

25749
  while (!cleanup_hooks_.empty() ||
638
8587
         native_immediates_.size() > 0 ||
639

17167
         native_immediates_threadsafe_.size() > 0 ||
640
4293
         native_immediates_interrupts_.size() > 0) {
641
    // Copy into a vector, since we can't sort an unordered_set in-place.
642
    std::vector<CleanupHookCallback> callbacks(
643
8580
        cleanup_hooks_.begin(), cleanup_hooks_.end());
644
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
645
    // need to be able to check whether they were un-scheduled by another hook.
646
647
8582
    std::sort(callbacks.begin(), callbacks.end(),
648
758095
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
649
      // Sort in descending order so that the most recently inserted callbacks
650
      // are run first.
651
758095
      return a.insertion_order_counter_ > b.insertion_order_counter_;
652
762386
    });
653
654
98707
    for (const CleanupHookCallback& cb : callbacks) {
655
94417
      if (cleanup_hooks_.count(cb) == 0) {
656
        // This hook was removed from the `cleanup_hooks_` set during another
657
        // hook that was run earlier. Nothing to do here.
658
635
        continue;
659
      }
660
661
93783
      cb.fn_(cb.arg_);
662
93782
      cleanup_hooks_.erase(cb);
663
    }
664
4290
    CleanupHandles();
665
  }
666
667
4296
  for (const int fd : unmanaged_fds_) {
668
    uv_fs_t close_req;
669
3
    uv_fs_close(nullptr, &close_req, fd, nullptr);
670
3
    uv_fs_req_cleanup(&close_req);
671
  }
672
4293
}
673
674
4819
void Environment::RunAtExitCallbacks() {
675
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
676
9640
                              "AtExit", this);
677
14320
  for (ExitCallback at_exit : at_exit_functions_) {
678
9498
    at_exit.cb_(at_exit.arg_);
679
  }
680
4821
  at_exit_functions_.clear();
681
4821
}
682
683
9519
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
684
9519
  at_exit_functions_.push_front(ExitCallback{cb, arg});
685
9519
}
686
687
426627
void Environment::RunAndClearInterrupts() {
688
433150
  while (native_immediates_interrupts_.size() > 0) {
689
13046
    NativeImmediateQueue queue;
690
    {
691
13046
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
692
6523
      queue.ConcatMove(std::move(native_immediates_interrupts_));
693
    }
694
6523
    DebugSealHandleScope seal_handle_scope(isolate());
695
696
19573
    while (auto head = queue.Shift())
697
13050
      head->Call(this);
698
  }
699
420109
}
700
701
413714
void Environment::RunAndClearNativeImmediates(bool only_refed) {
702
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
703
827433
                              "RunAndClearNativeImmediates", this);
704
827440
  HandleScope handle_scope(isolate_);
705
827443
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
706
707
413723
  size_t ref_count = 0;
708
709
  // Handle interrupts first. These functions are not allowed to throw
710
  // exceptions, so we do not need to handle that.
711
413723
  RunAndClearInterrupts();
712
713
827434
  auto drain_list = [&](NativeImmediateQueue* queue) {
714
1711725
    TryCatchScope try_catch(this);
715
827437
    DebugSealHandleScope seal_handle_scope(isolate());
716
941453
    while (auto head = queue->Shift()) {
717
57014
      bool is_refed = head->flags() & CallbackFlags::kRefed;
718
57014
      if (is_refed)
719
35052
        ref_count++;
720
721

57014
      if (is_refed || !only_refed)
722
113692
        head->Call(this);
723
724
57012
      head.reset();  // Destroy now so that this is also observed by try_catch.
725
726
57012
      if (UNLIKELY(try_catch.HasCaught())) {
727

6
        if (!try_catch.HasTerminated() && can_call_into_js())
728
2
          errors::TriggerUncaughtException(isolate(), try_catch);
729
730
2
        return true;
731
      }
732
57009
    }
733
827438
    return false;
734
413720
  };
735
413721
  while (drain_list(&native_immediates_)) {}
736
737
413718
  immediate_info()->ref_count_dec(ref_count);
738
739
413719
  if (immediate_info()->ref_count() == 0)
740
383511
    ToggleImmediateRef(false);
741
742
  // It is safe to check .size() first, because there is a causal relationship
743
  // between pushes to the threadsafe immediate list and this function being
744
  // called. For the common case, it's worth checking the size first before
745
  // establishing a mutex lock.
746
  // This is intentionally placed after the `ref_count` handling, because when
747
  // refed threadsafe immediates are created, they are not counted towards the
748
  // count in immediate_info() either.
749
827438
  NativeImmediateQueue threadsafe_immediates;
750
413719
  if (native_immediates_threadsafe_.size() > 0) {
751
1032
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
752
516
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
753
  }
754
413720
  while (drain_list(&threadsafe_immediates)) {}
755
413717
}
756
757
6528
void Environment::RequestInterruptFromV8() {
758
  // The Isolate may outlive the Environment, so some logic to handle the
759
  // situation in which the Environment is destroyed before the handler runs
760
  // is required.
761
762
  // We allocate a new pointer to a pointer to this Environment instance, and
763
  // try to set it as interrupt_data_. If interrupt_data_ was already set, then
764
  // callbacks are already scheduled to run and we can delete our own pointer
765
  // and just return. If it was nullptr previously, the Environment** is stored;
766
  // ~Environment sets the Environment* contained in it to nullptr, so that
767
  // the callback can check whether ~Environment has already run and it is thus
768
  // not safe to access the Environment instance itself.
769
6528
  Environment** interrupt_data = new Environment*(this);
770
6529
  Environment** dummy = nullptr;
771
6529
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
772
255
    delete interrupt_data;
773
255
    return;  // Already scheduled.
774
  }
775
776
31353
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
777
12521
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
778
6266
    Environment* env = *env_ptr;
779
6266
    if (env == nullptr) {
780
      // The Environment has already been destroyed. That should be okay; any
781
      // callback added before the Environment shuts down would have been
782
      // handled during cleanup.
783
11
      return;
784
    }
785
6255
    env->interrupt_data_.store(nullptr);
786
6255
    env->RunAndClearInterrupts();
787
18813
  }, interrupt_data);
788
}
789
790
6174
void Environment::ScheduleTimer(int64_t duration_ms) {
791
6174
  if (started_cleanup_) return;
792
6174
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
793
}
794
795
1119
void Environment::ToggleTimerRef(bool ref) {
796
1119
  if (started_cleanup_) return;
797
798
1119
  if (ref) {
799
776
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
800
  } else {
801
343
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
802
  }
803
}
804
805
5090
void Environment::RunTimers(uv_timer_t* handle) {
806
5090
  Environment* env = Environment::from_timer_handle(handle);
807
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
808
10181
                              "RunTimers", env);
809
810
5095
  if (!env->can_call_into_js())
811
    return;
812
813
10182
  HandleScope handle_scope(env->isolate());
814
10182
  Context::Scope context_scope(env->context());
815
816
5096
  Local<Object> process = env->process_object();
817
10182
  InternalCallbackScope scope(env, process, {0, 0});
818
819
5097
  Local<Function> cb = env->timers_callback_function();
820
  MaybeLocal<Value> ret;
821
5097
  Local<Value> arg = env->GetNow();
822
  // This code will loop until all currently due timers will process. It is
823
  // impossible for us to end up in an infinite loop due to how the JS-side
824
  // is structured.
825
5119
  do {
826
10248
    TryCatchScope try_catch(env);
827
5129
    try_catch.SetVerbose(true);
828
10258
    ret = cb->Call(env->context(), process, 1, &arg);
829

5119
  } while (ret.IsEmpty() && env->can_call_into_js());
830
831
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
832
  // is reset back to `true` after being previously set to `false` then this
833
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
834
  // timers corruption will occur and all timers behaviour will become
835
  // entirely unpredictable.
836
5087
  if (ret.IsEmpty())
837
3
    return;
838
839
  // To allow for less JS-C++ boundary crossing, the value returned from JS
840
  // serves a few purposes:
841
  // 1. If it's 0, no more timers exist and the handle should be unrefed
842
  // 2. If it's > 0, the value represents the next timer's expiry and there
843
  //    is at least one timer remaining that is refed.
844
  // 3. If it's < 0, the absolute value represents the next timer's expiry
845
  //    and there are no timers that are refed.
846
  int64_t expiry_ms =
847
20339
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
848
849
5085
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
850
851
5085
  if (expiry_ms != 0) {
852
    int64_t duration_ms =
853
4744
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
854
855
4744
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
856
857
4744
    if (expiry_ms > 0)
858
4283
      uv_ref(h);
859
    else
860
461
      uv_unref(h);
861
  } else {
862
341
    uv_unref(h);
863
  }
864
}
865
866
867
401558
void Environment::CheckImmediate(uv_check_t* handle) {
868
401558
  Environment* env = Environment::from_immediate_check_handle(handle);
869
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
870
431507
                              "CheckImmediate", env);
871
872
431504
  HandleScope scope(env->isolate());
873
431507
  Context::Scope context_scope(env->context());
874
875
401566
  env->RunAndClearNativeImmediates();
876
877

401563
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
878
371597
    return;
879
880
30886
  do {
881
61783
    MakeCallback(env->isolate(),
882
                 env->process_object(),
883
                 env->immediate_callback_function(),
884
                 0,
885
                 nullptr,
886
30906
                 {0, 0}).ToLocalChecked();
887

30886
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
888
889
29947
  if (env->immediate_info()->ref_count() == 0)
890
5088
    env->ToggleImmediateRef(false);
891
}
892
893
441408
void Environment::ToggleImmediateRef(bool ref) {
894
441408
  if (started_cleanup_) return;
895
896
432826
  if (ref) {
897
    // Idle handle is needed only to stop the event loop from blocking in poll.
898
157298
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
899
  } else {
900
380030
    uv_idle_stop(immediate_idle_handle());
901
  }
902
}
903
904
905
21933
Local<Value> Environment::GetNow() {
906
21933
  uv_update_time(event_loop());
907
21933
  uint64_t now = uv_now(event_loop());
908
21934
  CHECK_GE(now, timer_base());
909
21934
  now -= timer_base();
910
21934
  if (now <= 0xffffffff)
911
43868
    return Integer::NewFromUnsigned(isolate(), static_cast<uint32_t>(now));
912
  else
913
    return Number::New(isolate(), static_cast<double>(now));
914
}
915
916
28
void CollectExceptionInfo(Environment* env,
917
                          Local<Object> obj,
918
                          int errorno,
919
                          const char* err_string,
920
                          const char* syscall,
921
                          const char* message,
922
                          const char* path,
923
                          const char* dest) {
924
56
  obj->Set(env->context(),
925
           env->errno_string(),
926
140
           Integer::New(env->isolate(), errorno)).Check();
927
928
56
  obj->Set(env->context(), env->code_string(),
929
140
           OneByteString(env->isolate(), err_string)).Check();
930
931
28
  if (message != nullptr) {
932
56
    obj->Set(env->context(), env->message_string(),
933
140
             OneByteString(env->isolate(), message)).Check();
934
  }
935
936
  Local<Value> path_buffer;
937
28
  if (path != nullptr) {
938
    path_buffer =
939
      Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked();
940
    obj->Set(env->context(), env->path_string(), path_buffer).Check();
941
  }
942
943
  Local<Value> dest_buffer;
944
28
  if (dest != nullptr) {
945
    dest_buffer =
946
      Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked();
947
    obj->Set(env->context(), env->dest_string(), dest_buffer).Check();
948
  }
949
950
28
  if (syscall != nullptr) {
951
56
    obj->Set(env->context(), env->syscall_string(),
952
140
             OneByteString(env->isolate(), syscall)).Check();
953
  }
954
28
}
955
956
28
void Environment::CollectUVExceptionInfo(Local<Value> object,
957
                                         int errorno,
958
                                         const char* syscall,
959
                                         const char* message,
960
                                         const char* path,
961
                                         const char* dest) {
962

28
  if (!object->IsObject() || errorno == 0)
963
    return;
964
965
28
  Local<Object> obj = object.As<Object>();
966
28
  const char* err_string = uv_err_name(errorno);
967
968

28
  if (message == nullptr || message[0] == '\0') {
969
28
    message = uv_strerror(errorno);
970
  }
971
972
  node::CollectExceptionInfo(this, obj, errorno, err_string,
973
28
                             syscall, message, path, dest);
974
}
975
976
4759
ImmediateInfo::ImmediateInfo(v8::Isolate* isolate, const SerializeInfo* info)
977
4759
    : fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)) {}
978
979
1
ImmediateInfo::SerializeInfo ImmediateInfo::Serialize(
980
    v8::Local<v8::Context> context, v8::SnapshotCreator* creator) {
981
1
  return {fields_.Serialize(context, creator)};
982
}
983
984
4370
void ImmediateInfo::Deserialize(Local<Context> context) {
985
4370
  fields_.Deserialize(context);
986
4370
}
987
988
1
std::ostream& operator<<(std::ostream& output,
989
                         const ImmediateInfo::SerializeInfo& i) {
990
1
  output << "{ " << i.fields << " }";
991
1
  return output;
992
}
993
994
19
void ImmediateInfo::MemoryInfo(MemoryTracker* tracker) const {
995
19
  tracker->TrackField("fields", fields_);
996
19
}
997
998
1
TickInfo::SerializeInfo TickInfo::Serialize(v8::Local<v8::Context> context,
999
                                            v8::SnapshotCreator* creator) {
1000
1
  return {fields_.Serialize(context, creator)};
1001
}
1002
1003
4370
void TickInfo::Deserialize(Local<Context> context) {
1004
4370
  fields_.Deserialize(context);
1005
4370
}
1006
1007
1
std::ostream& operator<<(std::ostream& output,
1008
                         const TickInfo::SerializeInfo& i) {
1009
1
  output << "{ " << i.fields << " }";
1010
1
  return output;
1011
}
1012
1013
19
void TickInfo::MemoryInfo(MemoryTracker* tracker) const {
1014
19
  tracker->TrackField("fields", fields_);
1015
19
}
1016
1017
4759
TickInfo::TickInfo(v8::Isolate* isolate, const SerializeInfo* info)
1018
    : fields_(
1019
4759
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1020
1021
4759
AsyncHooks::AsyncHooks(v8::Isolate* isolate, const SerializeInfo* info)
1022
    : async_ids_stack_(isolate, 16 * 2, MAYBE_FIELD_PTR(info, async_ids_stack)),
1023
      fields_(isolate, kFieldsCount, MAYBE_FIELD_PTR(info, fields)),
1024
      async_id_fields_(
1025
          isolate, kUidFieldsCount, MAYBE_FIELD_PTR(info, async_id_fields)),
1026

9518
      info_(info) {
1027
9518
  v8::HandleScope handle_scope(isolate);
1028
4759
  if (info == nullptr) {
1029
389
    clear_async_id_stack();
1030
1031
    // Always perform async_hooks checks, not just when async_hooks is enabled.
1032
    // TODO(AndreasMadsen): Consider removing this for LTS releases.
1033
    // See discussion in https://github.com/nodejs/node/pull/15454
1034
    // When removing this, do it by reverting the commit. Otherwise the test
1035
    // and flag changes won't be included.
1036
389
    fields_[kCheck] = 1;
1037
1038
    // kDefaultTriggerAsyncId should be -1, this indicates that there is no
1039
    // specified default value and it should fallback to the executionAsyncId.
1040
    // 0 is not used as the magic value, because that indicates a missing
1041
    // context which is different from a default context.
1042
389
    async_id_fields_[AsyncHooks::kDefaultTriggerAsyncId] = -1;
1043
1044
    // kAsyncIdCounter should start at 1 because that'll be the id the execution
1045
    // context during bootstrap (code that runs before entering uv_run()).
1046
389
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1047
  }
1048
4759
}
1049
1050
4370
void AsyncHooks::Deserialize(Local<Context> context) {
1051
4370
  async_ids_stack_.Deserialize(context);
1052
4370
  fields_.Deserialize(context);
1053
4370
  async_id_fields_.Deserialize(context);
1054
4370
  if (info_->js_execution_async_resources != 0) {
1055
    v8::Local<v8::Array> arr = context
1056
8740
                                   ->GetDataFromSnapshotOnce<v8::Array>(
1057
8740
                                       info_->js_execution_async_resources)
1058
4370
                                   .ToLocalChecked();
1059
4370
    js_execution_async_resources_.Reset(context->GetIsolate(), arr);
1060
  }
1061
1062
4370
  native_execution_async_resources_.resize(
1063
8740
      info_->native_execution_async_resources.size());
1064
4370
  for (size_t i = 0; i < info_->native_execution_async_resources.size(); ++i) {
1065
    v8::Local<v8::Object> obj =
1066
        context
1067
            ->GetDataFromSnapshotOnce<v8::Object>(
1068
                info_->native_execution_async_resources[i])
1069
            .ToLocalChecked();
1070
    native_execution_async_resources_[i].Reset(context->GetIsolate(), obj);
1071
  }
1072
4370
  info_ = nullptr;
1073
4370
}
1074
1075
1
std::ostream& operator<<(std::ostream& output,
1076
                         const std::vector<SnapshotIndex>& v) {
1077
1
  output << "{ ";
1078
1
  for (const SnapshotIndex i : v) {
1079
    output << i << ", ";
1080
  }
1081
1
  output << " }";
1082
1
  return output;
1083
}
1084
1085
1
std::ostream& operator<<(std::ostream& output,
1086
                         const AsyncHooks::SerializeInfo& i) {
1087
  output << "{\n"
1088
1
         << "  " << i.async_ids_stack << ",  // async_ids_stack\n"
1089
2
         << "  " << i.fields << ",  // fields\n"
1090
2
         << "  " << i.async_id_fields << ",  // async_id_fields\n"
1091
2
         << "  " << i.js_execution_async_resources
1092
         << ",  // js_execution_async_resources\n"
1093
2
         << "  " << i.native_execution_async_resources
1094
         << ",  // native_execution_async_resources\n"
1095
1
         << "}";
1096
1
  return output;
1097
}
1098
1099
1
AsyncHooks::SerializeInfo AsyncHooks::Serialize(Local<Context> context,
1100
                                                SnapshotCreator* creator) {
1101
1
  SerializeInfo info;
1102
1
  info.async_ids_stack = async_ids_stack_.Serialize(context, creator);
1103
1
  info.fields = fields_.Serialize(context, creator);
1104
1
  info.async_id_fields = async_id_fields_.Serialize(context, creator);
1105
2
  if (!js_execution_async_resources_.IsEmpty()) {
1106
2
    info.js_execution_async_resources = creator->AddData(
1107
        context, js_execution_async_resources_.Get(context->GetIsolate()));
1108
1
    CHECK_NE(info.js_execution_async_resources, 0);
1109
  } else {
1110
    info.js_execution_async_resources = 0;
1111
  }
1112
1113
1
  info.native_execution_async_resources.resize(
1114
1
      native_execution_async_resources_.size());
1115
1
  for (size_t i = 0; i < native_execution_async_resources_.size(); i++) {
1116
    info.native_execution_async_resources[i] = creator->AddData(
1117
        context,
1118
        native_execution_async_resources_[i].Get(context->GetIsolate()));
1119
  }
1120
1121
1
  return info;
1122
}
1123
1124
19
void AsyncHooks::MemoryInfo(MemoryTracker* tracker) const {
1125
19
  tracker->TrackField("async_ids_stack", async_ids_stack_);
1126
19
  tracker->TrackField("fields", fields_);
1127
19
  tracker->TrackField("async_id_fields", async_id_fields_);
1128
19
}
1129
1130
8
void AsyncHooks::grow_async_ids_stack() {
1131
8
  async_ids_stack_.reserve(async_ids_stack_.Length() * 3);
1132
1133
24
  env()->async_hooks_binding()->Set(
1134
      env()->context(),
1135
      env()->async_ids_stack_string(),
1136
40
      async_ids_stack_.GetJSArray()).Check();
1137
8
}
1138
1139
uv_key_t Environment::thread_local_env = {};
1140
1141
508
void Environment::Exit(int exit_code) {
1142
508
  if (options()->trace_exit) {
1143
4
    HandleScope handle_scope(isolate());
1144
1145
2
    if (is_main_thread()) {
1146
1
      fprintf(stderr, "(node:%d) ", uv_os_getpid());
1147
    } else {
1148
1
      fprintf(stderr, "(node:%d, thread:%" PRIu64 ") ",
1149
1
              uv_os_getpid(), thread_id());
1150
    }
1151
1152
    fprintf(
1153
2
        stderr, "WARNING: Exited the environment with code %d\n", exit_code);
1154
2
    PrintStackTrace(isolate(),
1155
                    StackTrace::CurrentStackTrace(
1156
2
                        isolate(), stack_trace_limit(), StackTrace::kDetailed));
1157
  }
1158
508
  process_exit_handler_(this, exit_code);
1159
47
}
1160
1161
4779
void Environment::stop_sub_worker_contexts() {
1162
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1163
1164
4805
  while (!sub_worker_contexts_.empty()) {
1165
26
    Worker* w = *sub_worker_contexts_.begin();
1166
26
    remove_sub_worker_context(w);
1167
26
    w->Exit(1);
1168
26
    w->JoinThread();
1169
  }
1170
4754
}
1171
1172
2
Environment* Environment::worker_parent_env() const {
1173
2
  if (worker_context() == nullptr) return nullptr;
1174
  return worker_context()->env();
1175
}
1176
1177
42748
void Environment::AddUnmanagedFd(int fd) {
1178
42748
  if (!tracks_unmanaged_fds()) return;
1179
327
  auto result = unmanaged_fds_.insert(fd);
1180
327
  if (!result.second) {
1181
    ProcessEmitWarning(
1182
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1183
  }
1184
}
1185
1186
42382
void Environment::RemoveUnmanagedFd(int fd) {
1187
42382
  if (!tracks_unmanaged_fds()) return;
1188
324
  size_t removed_count = unmanaged_fds_.erase(fd);
1189
324
  if (removed_count == 0) {
1190
    ProcessEmitWarning(
1191
1
        this, "File descriptor %d closed but not opened in unmanaged mode", fd);
1192
  }
1193
}
1194
1195
void Environment::ForEachBaseObject(BaseObjectIterator iterator) {
1196
  size_t i = 0;
1197
  for (const auto& hook : cleanup_hooks_) {
1198
    BaseObject* obj = hook.GetBaseObject();
1199
    if (obj != nullptr) iterator(i, obj);
1200
    i++;
1201
  }
1202
}
1203
1204
void PrintBaseObject(size_t i, BaseObject* obj) {
1205
  std::cout << "#" << i << " " << obj << ": " << obj->MemoryInfoName() << "\n";
1206
}
1207
1208
void Environment::PrintAllBaseObjects() {
1209
  std::cout << "BaseObjects\n";
1210
  ForEachBaseObject(PrintBaseObject);
1211
}
1212
1213
1
EnvSerializeInfo Environment::Serialize(SnapshotCreator* creator) {
1214
1
  EnvSerializeInfo info;
1215
1
  Local<Context> ctx = context();
1216
1217
  // Currently all modules are compiled without cache in builtin snapshot
1218
  // builder.
1219
2
  info.native_modules = std::vector<std::string>(
1220
1
      native_modules_without_cache.begin(), native_modules_without_cache.end());
1221
1222
1
  info.async_hooks = async_hooks_.Serialize(ctx, creator);
1223
1
  info.immediate_info = immediate_info_.Serialize(ctx, creator);
1224
1
  info.tick_info = tick_info_.Serialize(ctx, creator);
1225
1
  info.performance_state = performance_state_->Serialize(ctx, creator);
1226
1
  info.stream_base_state = stream_base_state_.Serialize(ctx, creator);
1227
1
  info.should_abort_on_uncaught_toggle =
1228
1
      should_abort_on_uncaught_toggle_.Serialize(ctx, creator);
1229
1230
1
  size_t id = 0;
1231
#define V(PropertyName, TypeName)                                              \
1232
  do {                                                                         \
1233
    Local<TypeName> field = PropertyName();                                    \
1234
    if (!field.IsEmpty()) {                                                    \
1235
      size_t index = creator->AddData(field);                                  \
1236
      info.persistent_templates.push_back({#PropertyName, id, index});         \
1237
    }                                                                          \
1238
    id++;                                                                      \
1239
  } while (0);
1240















40
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1241
#undef V
1242
1243
1
  id = 0;
1244
#define V(PropertyName, TypeName)                                              \
1245
  do {                                                                         \
1246
    Local<TypeName> field = PropertyName();                                    \
1247
    if (!field.IsEmpty()) {                                                    \
1248
      size_t index = creator->AddData(ctx, field);                             \
1249
      info.persistent_values.push_back({#PropertyName, id, index});            \
1250
    }                                                                          \
1251
    id++;                                                                      \
1252
  } while (0);
1253

























75
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1254
#undef V
1255
1256
2
  info.context = creator->AddData(ctx, context());
1257
1
  return info;
1258
}
1259
1260
2
std::ostream& operator<<(std::ostream& output,
1261
                         const std::vector<PropInfo>& vec) {
1262
2
  output << "{\n";
1263
33
  for (const auto& info : vec) {
1264
62
    output << "  { \"" << info.name << "\", " << std::to_string(info.id) << ", "
1265
93
           << std::to_string(info.index) << " },\n";
1266
  }
1267
2
  output << "}";
1268
2
  return output;
1269
}
1270
1271
1
std::ostream& operator<<(std::ostream& output,
1272
                         const std::vector<std::string>& vec) {
1273
1
  output << "{\n";
1274
39
  for (const auto& info : vec) {
1275
38
    output << "  \"" << info << "\",\n";
1276
  }
1277
1
  output << "}";
1278
1
  return output;
1279
}
1280
1281
1
std::ostream& operator<<(std::ostream& output, const EnvSerializeInfo& i) {
1282
  output << "{\n"
1283
1
         << "// -- native_modules begins --\n"
1284
2
         << i.native_modules << ",\n"
1285
         << "// -- native_modules ends --\n"
1286
1
         << "// -- async_hooks begins --\n"
1287
2
         << i.async_hooks << ",\n"
1288
1
         << "// -- async_hooks ends --\n"
1289
2
         << i.tick_info << ",  // tick_info\n"
1290
2
         << i.immediate_info << ",  // immediate_info\n"
1291
1
         << "// -- performance_state begins --\n"
1292
2
         << i.performance_state << ",\n"
1293
1
         << "// -- performance_state ends --\n"
1294
2
         << i.stream_base_state << ",  // stream_base_state\n"
1295
2
         << i.should_abort_on_uncaught_toggle
1296
         << ",  // should_abort_on_uncaught_toggle\n"
1297
1
         << "// -- persistent_templates begins --\n"
1298
2
         << i.persistent_templates << ",\n"
1299
         << "// persistent_templates ends --\n"
1300
1
         << "// -- persistent_values begins --\n"
1301
2
         << i.persistent_values << ",\n"
1302
1
         << "// -- persistent_values ends --\n"
1303
2
         << i.context << ",  // context\n"
1304
1
         << "}";
1305
1
  return output;
1306
}
1307
1308
4370
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1309
4370
  Local<Context> ctx = context();
1310
1311
4370
  native_modules_in_snapshot = info->native_modules;
1312
4370
  async_hooks_.Deserialize(ctx);
1313
4370
  immediate_info_.Deserialize(ctx);
1314
4370
  tick_info_.Deserialize(ctx);
1315
4370
  performance_state_->Deserialize(ctx);
1316
4370
  stream_base_state_.Deserialize(ctx);
1317
4370
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1318
1319
4370
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1320
    fprintf(stderr, "deserializing...\n");
1321
    std::cerr << *info << "\n";
1322
  }
1323
1324
4370
  const std::vector<PropInfo>& templates = info->persistent_templates;
1325
4370
  size_t i = 0;  // index to the array
1326
4370
  size_t id = 0;
1327
#define V(PropertyName, TypeName)                                              \
1328
  do {                                                                         \
1329
    if (templates.size() > i && id == templates[i].id) {                       \
1330
      const PropInfo& d = templates[i];                                        \
1331
      DCHECK_EQ(d.name, #PropertyName);                                        \
1332
      MaybeLocal<TypeName> maybe_field =                                       \
1333
          isolate_->GetDataFromSnapshotOnce<TypeName>(d.index);                \
1334
      Local<TypeName> field;                                                   \
1335
      if (!maybe_field.ToLocal(&field)) {                                      \
1336
        fprintf(stderr,                                                        \
1337
                "Failed to deserialize environment template " #PropertyName    \
1338
                "\n");                                                         \
1339
      }                                                                        \
1340
      set_##PropertyName(field);                                               \
1341
      i++;                                                                     \
1342
    }                                                                          \
1343
  } while (0);                                                                 \
1344
  id++;
1345






























































74290
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V);
1346
#undef V
1347
1348
4370
  i = 0;  // index to the array
1349
4370
  id = 0;
1350
4370
  const std::vector<PropInfo>& values = info->persistent_values;
1351
#define V(PropertyName, TypeName)                                              \
1352
  do {                                                                         \
1353
    if (values.size() > i && id == values[i].id) {                             \
1354
      const PropInfo& d = values[i];                                           \
1355
      DCHECK_EQ(d.name, #PropertyName);                                        \
1356
      MaybeLocal<TypeName> maybe_field =                                       \
1357
          ctx->GetDataFromSnapshotOnce<TypeName>(d.index);                     \
1358
      Local<TypeName> field;                                                   \
1359
      if (!maybe_field.ToLocal(&field)) {                                      \
1360
        fprintf(stderr,                                                        \
1361
                "Failed to deserialize environment value " #PropertyName       \
1362
                "\n");                                                         \
1363
      }                                                                        \
1364
      set_##PropertyName(field);                                               \
1365
      i++;                                                                     \
1366
    }                                                                          \
1367
  } while (0);                                                                 \
1368
  id++;
1369






































































































305900
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1370
#undef V
1371
1372
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1373
13110
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1374
  Local<Context> ctx_from_snapshot;
1375
4370
  if (!maybe_ctx_from_snapshot.ToLocal(&ctx_from_snapshot)) {
1376
    fprintf(stderr,
1377
            "Failed to deserialize context back reference from the snapshot\n");
1378
  }
1379
4370
  CHECK_EQ(ctx_from_snapshot, ctx);
1380
4370
}
1381
1382
19
void Environment::BuildEmbedderGraph(Isolate* isolate,
1383
                                     EmbedderGraph* graph,
1384
                                     void* data) {
1385
38
  MemoryTracker tracker(isolate, graph);
1386
19
  Environment* env = static_cast<Environment*>(data);
1387
19
  tracker.Track(env);
1388
385
  env->ForEachBaseObject([&](BaseObject* obj) {
1389
347
    if (obj->IsDoneInitializing())
1390
344
      tracker.Track(obj);
1391
366
  });
1392
19
}
1393
1394
19
inline size_t Environment::SelfSize() const {
1395
19
  size_t size = sizeof(*this);
1396
  // Remove non pointer fields that will be tracked in MemoryInfo()
1397
  // TODO(joyeecheung): refactor the MemoryTracker interface so
1398
  // this can be done for common types within the Track* calls automatically
1399
  // if a certain scope is entered.
1400
19
  size -= sizeof(async_hooks_);
1401
19
  size -= sizeof(tick_info_);
1402
19
  size -= sizeof(immediate_info_);
1403
19
  return size;
1404
}
1405
1406
19
void Environment::MemoryInfo(MemoryTracker* tracker) const {
1407
  // Iteratable STLs have their own sizes subtracted from the parent
1408
  // by default.
1409
19
  tracker->TrackField("isolate_data", isolate_data_);
1410
19
  tracker->TrackField("native_modules_with_cache", native_modules_with_cache);
1411
19
  tracker->TrackField("native_modules_without_cache",
1412
19
                      native_modules_without_cache);
1413
19
  tracker->TrackField("destroy_async_id_list", destroy_async_id_list_);
1414
19
  tracker->TrackField("exec_argv", exec_argv_);
1415
19
  tracker->TrackField("should_abort_on_uncaught_toggle",
1416
19
                      should_abort_on_uncaught_toggle_);
1417
19
  tracker->TrackField("stream_base_state", stream_base_state_);
1418
19
  tracker->TrackFieldWithSize(
1419
38
      "cleanup_hooks", cleanup_hooks_.size() * sizeof(CleanupHookCallback));
1420
19
  tracker->TrackField("async_hooks", async_hooks_);
1421
19
  tracker->TrackField("immediate_info", immediate_info_);
1422
19
  tracker->TrackField("tick_info", tick_info_);
1423
1424
#define V(PropertyName, TypeName)                                              \
1425
  tracker->TrackField(#PropertyName, PropertyName());
1426
19
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V)
1427
#undef V
1428
1429
  // FIXME(joyeecheung): track other fields in Environment.
1430
  // Currently MemoryTracker is unable to track these
1431
  // correctly:
1432
  // - Internal types that do not implement MemoryRetainer yet
1433
  // - STL containers with MemoryRetainer* inside
1434
  // - STL containers with numeric types inside that should not have their
1435
  //   nodes elided e.g. numeric keys in maps.
1436
  // We also need to make sure that when we add a non-pointer field as its own
1437
  // node, we shift its sizeof() size out of the Environment node.
1438
19
}
1439
1440
1002254
void Environment::RunWeakRefCleanup() {
1441
1002254
  isolate()->ClearKeptObjects();
1442
1002279
}
1443
1444
// Not really any better place than env.cc at this moment.
1445
88982
void BaseObject::DeleteMe(void* data) {
1446
88982
  BaseObject* self = static_cast<BaseObject*>(data);
1447

91405
  if (self->has_pointer_data() &&
1448
2423
      self->pointer_data()->strong_ptr_count > 0) {
1449
234
    return self->Detach();
1450
  }
1451
88749
  delete self;
1452
}
1453
1454
284
bool BaseObject::IsDoneInitializing() const { return true; }
1455
1456
344
Local<Object> BaseObject::WrappedObject() const {
1457
344
  return object();
1458
}
1459
1460
688
bool BaseObject::IsRootNode() const {
1461
1376
  return !persistent_handle_.IsWeak();
1462
}
1463
1464
36548
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
1465
36548
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
1466
36548
  if (tmpl.IsEmpty()) {
1467
389
    tmpl = env->NewFunctionTemplate(nullptr);
1468
778
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
1469
389
    env->set_base_object_ctor_template(tmpl);
1470
  }
1471
36548
  return tmpl;
1472
}
1473
1474

13323
}  // namespace node