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: 656 690 95.1 %
Date: 2020-08-22 22:13:06 Branches: 860 1643 52.3 %

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
234
  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
4394
void IsolateData::DeserializeProperties(const std::vector<size_t>* indexes) {
89
4394
  size_t i = 0;
90
8788
  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




140608
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
105






210912
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
106




















































































































4095208
  PER_ISOLATE_STRING_PROPERTIES(VS)
107
#undef V
108
#undef VY
109
#undef VS
110
#undef VP
111
112
241670
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
113
    MaybeLocal<String> field =
114
474552
        isolate_->GetDataFromSnapshotOnce<String>((*indexes)[i++]);
115
237276
    if (field.IsEmpty()) {
116
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
117
    }
118
237276
    async_wrap_providers_[j].Set(isolate_, field.ToLocalChecked());
119
  }
120
4394
}
121
122
466
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
932
  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
7922
  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
11650
  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
217622
  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
50794
  NODE_ASYNC_PROVIDER_TYPES(V)
183
#undef V
184
466
}
185
186
4860
IsolateData::IsolateData(Isolate* isolate,
187
                         uv_loop_t* event_loop,
188
                         MultiIsolatePlatform* platform,
189
                         ArrayBufferAllocator* node_allocator,
190
4860
                         const std::vector<size_t>* indexes)
191
    : isolate_(isolate),
192
      event_loop_(event_loop),
193
9684
      node_allocator_(node_allocator == nullptr ? nullptr
194
4824
                                                : node_allocator->GetImpl()),
195
1239300
      platform_(platform) {
196
9720
  options_.reset(
197
14580
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
198
199
4860
  if (indexes == nullptr) {
200
466
    CreateProperties();
201
  } else {
202
4394
    DeserializeProperties(indexes);
203
  }
204
4860
}
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
4404
void InitThreadLocalOnce() {
229
4404
  CHECK_EQ(0, uv_key_create(&Environment::thread_local_env));
230
4404
}
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
455
void Environment::CreateProperties() {
258
910
  HandleScope handle_scope(isolate_);
259
455
  Local<Context> ctx = context();
260
261
  {
262
    Context::Scope context_scope(ctx);
263
455
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
264
1365
    templ->InstanceTemplate()->SetInternalFieldCount(
265
455
        BaseObject::kInternalFieldCount);
266
910
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
267
268
455
    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
910
      GetPerContextExports(ctx).ToLocalChecked();
274
  Local<Value> primordials =
275
1365
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
276
455
  CHECK(primordials->IsObject());
277
455
  set_primordials(primordials.As<Object>());
278
279
  Local<Object> process_object =
280
910
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
281
455
  set_process_object(process_object);
282
455
}
283
284
4848
std::string GetExecPath(const std::vector<std::string>& argv) {
285
  char exec_path_buf[2 * PATH_MAX];
286
4848
  size_t exec_path_len = sizeof(exec_path_buf);
287
4848
  std::string exec_path;
288
4848
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
289
4848
    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
4848
  return exec_path;
308
}
309
310
4848
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
4848
                         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
4848
      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
4848
          isolate_,
328
          1,
329
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
330
4848
      stream_base_state_(isolate_,
331
                         StreamBase::kNumStreamBaseStateFields,
332
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
333
4848
      environment_start_time_(PERFORMANCE_NOW()),
334
      flags_(flags),
335
4848
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
336
4848
                     ? AllocateEnvironmentThreadId().id
337


436320
                     : thread_id.id) {
338
  // We'll be creating new objects so make sure we've entered the context.
339
9696
  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
4848
  if (flags_ & EnvironmentFlags::kDefaultFlags) {
344
8870
    flags_ = flags_ |
345
4435
        EnvironmentFlags::kOwnsProcessState |
346
        EnvironmentFlags::kOwnsInspector;
347
  }
348
349
4848
  set_env_vars(per_process::system_environment);
350
  // TODO(joyeecheung): pass Isolate* and env_vars to it instead of the entire
351
  // env
352
4848
  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
4848
  options_.reset(new EnvironmentOptions(*isolate_data->options()->per_env));
359
9696
  inspector_host_port_.reset(
360
14544
      new ExclusiveAccess<HostPort>(options_->debug_options().host_port));
361
362
4848
  if (!(flags_ & EnvironmentFlags::kOwnsProcessState)) {
363
413
    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
4848
  inspector_agent_ = std::make_unique<inspector::Agent>(this);
369
#endif
370
371
  static uv_once_t init_once = UV_ONCE_INIT;
372
4848
  uv_once(&init_once, InitThreadLocalOnce);
373
4848
  uv_key_set(&thread_local_env, this);
374
375
4848
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
376
4848
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
377
4848
    if (TracingController* tracing_controller = writer->GetTracingController())
378
4806
      tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
379
  }
380
381
4848
  destroy_async_id_list_.reserve(512);
382
383
9696
  performance_state_ = std::make_unique<performance::PerformanceState>(
384
14544
      isolate, MAYBE_FIELD_PTR(env_info, performance_state));
385
386
4848
  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
4848
  initial_base_object_count_ = base_object_count();
405
4848
}
406
407
454
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
454
                         ThreadId thread_id)
414
    : Environment(isolate_data,
415
                  context->GetIsolate(),
416
                  args,
417
                  exec_args,
418
                  env_info,
419
                  flags,
420
454
                  thread_id) {
421
454
  InitializeMainContext(context, env_info);
422
454
}
423
424
4849
void Environment::InitializeMainContext(Local<Context> context,
425
                                        const EnvSerializeInfo* env_info) {
426
4849
  context_.Reset(context->GetIsolate(), context);
427
4849
  AssignToContext(context, ContextInfo(""));
428
4849
  if (env_info != nullptr) {
429
4394
    DeserializeProperties(env_info);
430
  } else {
431
455
    CreateProperties();
432
  }
433
434
4849
  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
4849
  should_abort_on_uncaught_toggle_[0] = 1;
440
441
4849
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT,
442
4849
                           environment_start_time_);
443
4849
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
444
9698
                           per_process::node_start_time);
445
4849
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_V8_START,
446
9698
                           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
4849
  initial_base_object_count_ = base_object_count();
451
4849
}
452
453
381205
Environment::~Environment() {
454
4383
  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
4383
  CHECK(is_stopping());
481
482
4384
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
483
4385
      BuildEmbedderGraph, this);
484
485
8770
  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
4385
  inspector_agent_.reset();
491
#endif
492
493
13150
  context()->SetAlignedPointerInEmbedderData(ContextEmbedderIndex::kEnvironment,
494
4382
                                             nullptr);
495
496
4385
  if (trace_state_observer_) {
497
4384
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
498
4384
    CHECK_NOT_NULL(writer);
499
4384
    if (TracingController* tracing_controller = writer->GetTracingController())
500
4343
      tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
501
  }
502
503

8770
  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
4385
  if (!is_main_thread()) {
512
    // Dereference all addons that were loaded into this environment.
513
424
    for (binding::DLib& addon : loaded_addons_) {
514
14
      addon.Close();
515
    }
516
  }
517
518
4385
  CHECK_EQ(base_object_count_, 0);
519
8770
}
520
521
4819
void Environment::InitializeLibuv() {
522
9638
  HandleScope handle_scope(isolate());
523
4819
  Context::Scope context_scope(context());
524
525
4819
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
526
4819
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
527
528
4819
  uv_check_init(event_loop(), immediate_check_handle());
529
4819
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
530
531
4819
  uv_idle_init(event_loop(), immediate_idle_handle());
532
533
4819
  uv_check_start(immediate_check_handle(), CheckImmediate);
534
535
9638
  uv_async_init(
536
      event_loop(),
537
      &task_queues_async_,
538
12483
      [](uv_async_t* async) {
539
7664
        Environment* env = ContainerOf(
540
3832
            &Environment::task_queues_async_, async);
541
3832
        env->RunAndClearNativeImmediates();
542
17299
      });
543
4819
  uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
544
545
  {
546
9638
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
547
4819
    task_queues_async_initialized_ = true;
548

9638
    if (native_immediates_threadsafe_.size() > 0 ||
549
4819
        native_immediates_interrupts_.size() > 0) {
550
4388
      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
4819
  RegisterHandleCleanups();
559
4819
}
560
561
95
void Environment::ExitEnv() {
562
95
  set_can_call_into_js(false);
563
95
  set_stopping(true);
564
95
  isolate_->TerminateExecution();
565
190
  SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); });
566
95
}
567
568
4819
void Environment::RegisterHandleCleanups() {
569
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
570
39651
                                        void* arg) {
571
17416
    handle->data = env;
572
573
34832
    env->CloseHandle(handle, [](uv_handle_t* handle) {
574
#ifdef DEBUG
575
      memset(handle, 0xab, uv_handle_size(handle->type));
576
#endif
577
34834
    });
578
44468
  };
579
580
19276
  auto register_handle = [&](uv_handle_t* handle) {
581
19276
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
582
24095
  };
583
4819
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
584
4819
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
585
4819
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
586
4819
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
587
4819
}
588
589
8761
void Environment::CleanupHandles() {
590
  {
591
17525
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
592
8764
    task_queues_async_initialized_ = false;
593
  }
594
595
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
596
17525
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
597
598
8762
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
599
600
8803
  for (ReqWrapBase* request : req_wrap_queue_)
601
39
    request->Cancel();
602
603
11159
  for (HandleWrap* handle : handle_wrap_queue_)
604
4784
    handle->Close();
605
606
26181
  for (HandleCleanup& hc : handle_cleanup_queue_)
607
17415
    hc.cb_(this, hc.handle_, hc.arg_);
608
8764
  handle_cleanup_queue_.clear();
609
610

51341
  while (handle_cleanup_waiting_ != 0 ||
611

25878
         request_waiting_ != 0 ||
612
8764
         !handle_wrap_queue_.IsEmpty()) {
613
8353
    uv_run(event_loop(), UV_RUN_ONCE);
614
  }
615
8765
}
616
617
322859
void Environment::PrintSyncTrace() const {
618
322859
  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
4380
void Environment::RunCleanup() {
630
4380
  started_cleanup_ = true;
631
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
632
8765
                              "RunCleanup", this);
633
4380
  bindings_.clear();
634
4384
  initial_base_object_count_ = 0;
635
4384
  CleanupHandles();
636
637

26291
  while (!cleanup_hooks_.empty() ||
638
8772
         native_immediates_.size() > 0 ||
639

17532
         native_immediates_threadsafe_.size() > 0 ||
640
4385
         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
8757
        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
8760
    std::sort(callbacks.begin(), callbacks.end(),
648
776860
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
649
      // Sort in descending order so that the most recently inserted callbacks
650
      // are run first.
651
776860
      return a.insertion_order_counter_ > b.insertion_order_counter_;
652
781240
    });
653
654
100456
    for (const CleanupHookCallback& cb : callbacks) {
655
96081
      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
646
        continue;
659
      }
660
661
95433
      cb.fn_(cb.arg_);
662
95434
      cleanup_hooks_.erase(cb);
663
    }
664
4380
    CleanupHandles();
665
  }
666
667
4388
  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
4385
}
673
674
4914
void Environment::RunAtExitCallbacks() {
675
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
676
9830
                              "AtExit", this);
677
14592
  for (ExitCallback at_exit : at_exit_functions_) {
678
9676
    at_exit.cb_(at_exit.arg_);
679
  }
680
4916
  at_exit_functions_.clear();
681
4916
}
682
683
9697
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
684
9697
  at_exit_functions_.push_front(ExitCallback{cb, arg});
685
9697
}
686
687
428777
void Environment::RunAndClearInterrupts() {
688
435617
  while (native_immediates_interrupts_.size() > 0) {
689
13680
    NativeImmediateQueue queue;
690
    {
691
13680
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
692
6840
      queue.ConcatMove(std::move(native_immediates_interrupts_));
693
    }
694
6840
    DebugSealHandleScope seal_handle_scope(isolate());
695
696
20522
    while (auto head = queue.Shift())
697
13682
      head->Call(this);
698
  }
699
421940
}
700
701
415263
void Environment::RunAndClearNativeImmediates(bool only_refed) {
702
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
703
830525
                              "RunAndClearNativeImmediates", this);
704
830528
  HandleScope handle_scope(isolate_);
705
830529
  InternalCallbackScope cb_scope(this, Object::New(isolate_), { 0, 0 });
706
707
415263
  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
415263
  RunAndClearInterrupts();
712
713
830520
  auto drain_list = [&](NativeImmediateQueue* queue) {
714
1716665
    TryCatchScope try_catch(this);
715
830524
    DebugSealHandleScope seal_handle_scope(isolate());
716
942082
    while (auto head = queue->Shift()) {
717
55783
      bool is_refed = head->flags() & CallbackFlags::kRefed;
718
55783
      if (is_refed)
719
33809
        ref_count++;
720
721

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

4
        if (!try_catch.HasTerminated() && can_call_into_js())
728
2
          errors::TriggerUncaughtException(isolate(), try_catch);
729
730
1
        return true;
731
      }
732
55779
    }
733
830526
    return false;
734
415262
  };
735
415262
  while (drain_list(&native_immediates_)) {}
736
737
415262
  immediate_info()->ref_count_dec(ref_count);
738
739
415263
  if (immediate_info()->ref_count() == 0)
740
384974
    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
830528
  NativeImmediateQueue threadsafe_immediates;
750
415268
  if (native_immediates_threadsafe_.size() > 0) {
751
1114
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
752
557
    threadsafe_immediates.ConcatMove(std::move(native_immediates_threadsafe_));
753
  }
754
415261
  while (drain_list(&threadsafe_immediates)) {}
755
415262
}
756
757
6845
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
6845
  Environment** interrupt_data = new Environment*(this);
770
6845
  Environment** dummy = nullptr;
771
6845
  if (!interrupt_data_.compare_exchange_strong(dummy, interrupt_data)) {
772
280
    delete interrupt_data;
773
280
    return;  // Already scheduled.
774
  }
775
776
32809
  isolate()->RequestInterrupt([](Isolate* isolate, void* data) {
777
13103
    std::unique_ptr<Environment*> env_ptr { static_cast<Environment**>(data) };
778
6557
    Environment* env = *env_ptr;
779
6557
    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
6546
    env->interrupt_data_.store(nullptr);
786
6546
    env->RunAndClearInterrupts();
787
19687
  }, interrupt_data);
788
}
789
790
6100
void Environment::ScheduleTimer(int64_t duration_ms) {
791
6100
  if (started_cleanup_) return;
792
6100
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
793
}
794
795
1113
void Environment::ToggleTimerRef(bool ref) {
796
1113
  if (started_cleanup_) return;
797
798
1113
  if (ref) {
799
772
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
800
  } else {
801
341
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
802
  }
803
}
804
805
5038
void Environment::RunTimers(uv_timer_t* handle) {
806
5038
  Environment* env = Environment::from_timer_handle(handle);
807
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
808
10064
                              "RunTimers", env);
809
810
5038
  if (!env->can_call_into_js())
811
    return;
812
813
10064
  HandleScope handle_scope(env->isolate());
814
10064
  Context::Scope context_scope(env->context());
815
816
5038
  Local<Object> process = env->process_object();
817
10064
  InternalCallbackScope scope(env, process, {0, 0});
818
819
5038
  Local<Function> cb = env->timers_callback_function();
820
  MaybeLocal<Value> ret;
821
5038
  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
5060
  do {
826
10129
    TryCatchScope try_catch(env);
827
5069
    try_catch.SetVerbose(true);
828
10138
    ret = cb->Call(env->context(), process, 1, &arg);
829

5060
  } 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
5029
  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
20104
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
848
849
5026
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
850
851
5026
  if (expiry_ms != 0) {
852
    int64_t duration_ms =
853
4690
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
854
855
4690
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
856
857
4690
    if (expiry_ms > 0)
858
4336
      uv_ref(h);
859
    else
860
354
      uv_unref(h);
861
  } else {
862
336
    uv_unref(h);
863
  }
864
}
865
866
867
402666
void Environment::CheckImmediate(uv_check_t* handle) {
868
402666
  Environment* env = Environment::from_immediate_check_handle(handle);
869
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
870
432698
                              "CheckImmediate", env);
871
872
432696
  HandleScope scope(env->isolate());
873
432697
  Context::Scope context_scope(env->context());
874
875
402670
  env->RunAndClearNativeImmediates();
876
877

402669
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
878
372628
    return;
879
880
30967
  do {
881
61945
    MakeCallback(env->isolate(),
882
                 env->process_object(),
883
                 env->immediate_callback_function(),
884
                 0,
885
                 nullptr,
886
30981
                 {0, 0}).ToLocalChecked();
887

30967
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
888
889
30028
  if (env->immediate_info()->ref_count() == 0)
890
5216
    env->ToggleImmediateRef(false);
891
}
892
893
443173
void Environment::ToggleImmediateRef(bool ref) {
894
443173
  if (started_cleanup_) return;
895
896
434412
  if (ref) {
897
    // Idle handle is needed only to stop the event loop from blocking in poll.
898
157544
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
899
  } else {
900
381451
    uv_idle_stop(immediate_idle_handle());
901
  }
902
}
903
904
905
21957
Local<Value> Environment::GetNow() {
906
21957
  uv_update_time(event_loop());
907
21957
  uint64_t now = uv_now(event_loop());
908
21957
  CHECK_GE(now, timer_base());
909
21957
  now -= timer_base();
910
21957
  if (now <= 0xffffffff)
911
43914
    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
4848
ImmediateInfo::ImmediateInfo(v8::Isolate* isolate, const SerializeInfo* info)
977
4848
    : 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
4394
void ImmediateInfo::Deserialize(Local<Context> context) {
985
4394
  fields_.Deserialize(context);
986
4394
}
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
4394
void TickInfo::Deserialize(Local<Context> context) {
1004
4394
  fields_.Deserialize(context);
1005
4394
}
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
4848
TickInfo::TickInfo(v8::Isolate* isolate, const SerializeInfo* info)
1018
    : fields_(
1019
4848
          isolate, kFieldsCount, info == nullptr ? nullptr : &(info->fields)) {}
1020
1021
4848
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

9696
      info_(info) {
1027
9696
  v8::HandleScope handle_scope(isolate);
1028
4848
  if (info == nullptr) {
1029
454
    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
454
    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
454
    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
454
    async_id_fields_[AsyncHooks::kAsyncIdCounter] = 1;
1047
  }
1048
4848
}
1049
1050
4394
void AsyncHooks::Deserialize(Local<Context> context) {
1051
4394
  async_ids_stack_.Deserialize(context);
1052
4394
  fields_.Deserialize(context);
1053
4394
  async_id_fields_.Deserialize(context);
1054
4394
  if (info_->js_execution_async_resources != 0) {
1055
    v8::Local<v8::Array> arr = context
1056
8788
                                   ->GetDataFromSnapshotOnce<v8::Array>(
1057
8788
                                       info_->js_execution_async_resources)
1058
4394
                                   .ToLocalChecked();
1059
4394
    js_execution_async_resources_.Reset(context->GetIsolate(), arr);
1060
  }
1061
1062
4394
  native_execution_async_resources_.resize(
1063
8788
      info_->native_execution_async_resources.size());
1064
4394
  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
4394
  info_ = nullptr;
1073
4394
}
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
511
void Environment::Exit(int exit_code) {
1142
511
  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
511
  process_exit_handler_(this, exit_code);
1159
53
}
1160
1161
4864
void Environment::stop_sub_worker_contexts() {
1162
  DCHECK_EQ(Isolate::GetCurrent(), isolate());
1163
1164
4889
  while (!sub_worker_contexts_.empty()) {
1165
25
    Worker* w = *sub_worker_contexts_.begin();
1166
25
    remove_sub_worker_context(w);
1167
25
    w->Exit(1);
1168
25
    w->JoinThread();
1169
  }
1170
4839
}
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
45578
void Environment::AddUnmanagedFd(int fd) {
1178
45578
  if (!tracks_unmanaged_fds()) return;
1179
495
  auto result = unmanaged_fds_.insert(fd);
1180
495
  if (!result.second) {
1181
    ProcessEmitWarning(
1182
1
        this, "File descriptor %d opened in unmanaged mode twice", fd);
1183
  }
1184
}
1185
1186
45212
void Environment::RemoveUnmanagedFd(int fd) {
1187
45212
  if (!tracks_unmanaged_fds()) return;
1188
492
  size_t removed_count = unmanaged_fds_.erase(fd);
1189
492
  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
















41
  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
4394
void Environment::DeserializeProperties(const EnvSerializeInfo* info) {
1309
4394
  Local<Context> ctx = context();
1310
1311
4394
  native_modules_in_snapshot = info->native_modules;
1312
4394
  async_hooks_.Deserialize(ctx);
1313
4394
  immediate_info_.Deserialize(ctx);
1314
4394
  tick_info_.Deserialize(ctx);
1315
4394
  performance_state_->Deserialize(ctx);
1316
4394
  stream_base_state_.Deserialize(ctx);
1317
4394
  should_abort_on_uncaught_toggle_.Deserialize(ctx);
1318
1319
4394
  if (enabled_debug_list_.enabled(DebugCategory::MKSNAPSHOT)) {
1320
    fprintf(stderr, "deserializing...\n");
1321
    std::cerr << *info << "\n";
1322
  }
1323
1324
4394
  const std::vector<PropInfo>& templates = info->persistent_templates;
1325
4394
  size_t i = 0;  // index to the array
1326
4394
  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
































































74698
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V);
1346
#undef V
1347
1348
4394
  i = 0;  // index to the array
1349
4394
  id = 0;
1350
4394
  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






































































































307580
  ENVIRONMENT_STRONG_PERSISTENT_VALUES(V);
1370
#undef V
1371
1372
  MaybeLocal<Context> maybe_ctx_from_snapshot =
1373
13182
      ctx->GetDataFromSnapshotOnce<Context>(info->context);
1374
  Local<Context> ctx_from_snapshot;
1375
4394
  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
4394
  CHECK_EQ(ctx_from_snapshot, ctx);
1380
4394
}
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
1013111
void Environment::RunWeakRefCleanup() {
1441
1013111
  isolate()->ClearKeptObjects();
1442
1013129
}
1443
1444
// Not really any better place than env.cc at this moment.
1445
90673
void BaseObject::DeleteMe(void* data) {
1446
90673
  BaseObject* self = static_cast<BaseObject*>(data);
1447

93174
  if (self->has_pointer_data() &&
1448
2501
      self->pointer_data()->strong_ptr_count > 0) {
1449
241
    return self->Detach();
1450
  }
1451
90435
  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
37229
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
1465
37229
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
1466
37229
  if (tmpl.IsEmpty()) {
1467
454
    tmpl = env->NewFunctionTemplate(nullptr);
1468
908
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
1469
454
    env->set_base_object_ctor_template(tmpl);
1470
  }
1471
37229
  return tmpl;
1472
}
1473
1474

13395
}  // namespace node