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: 650 685 94.9 %
Date: 2020-07-19 22:14:24 Branches: 850 1621 52.4 %

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



137732
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP)
105






236112
  PER_ISOLATE_SYMBOL_PROPERTIES(VY)
106




















































































































4564832
  PER_ISOLATE_STRING_PROPERTIES(VS)
107
#undef V
108
#undef VY
109
#undef VS
110
#undef VP
111
112
270545
  for (size_t j = 0; j < AsyncWrap::PROVIDERS_LENGTH; j++) {
113
    MaybeLocal<String> field =
114
531252
        isolate_->GetDataFromSnapshotOnce<String>((*indexes)[i++]);
115
265626
    if (field.IsEmpty()) {
116
      fprintf(stderr, "Failed to deserialize AsyncWrap provider %zu\n", j);
117
    }
118
265626
    async_wrap_providers_[j].Set(isolate_, field.ToLocalChecked());
119
  }
120
4919
}
121
122
399
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
798
  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
5984
  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
9973
  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
185436
  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
43466
  NODE_ASYNC_PROVIDER_TYPES(V)
183
#undef V
184
399
}
185
186
5318
IsolateData::IsolateData(Isolate* isolate,
187
                         uv_loop_t* event_loop,
188
                         MultiIsolatePlatform* platform,
189
                         ArrayBufferAllocator* node_allocator,
190
5318
                         const std::vector<size_t>* indexes)
191
    : isolate_(isolate),
192
      event_loop_(event_loop),
193
10601
      node_allocator_(node_allocator == nullptr ? nullptr
194
5283
                                                : node_allocator->GetImpl()),
195
1345454
      platform_(platform) {
196
10636
  options_.reset(
197
15953
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
198
199
5318
  if (indexes == nullptr) {
200
399
    CreateProperties();
201
  } else {
202
4919
    DeserializeProperties(indexes);
203
  }
204
5317
}
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
4929
void InitThreadLocalOnce() {
229
4929
  CHECK_EQ(0, uv_key_create(&Environment::thread_local_env));
230
4929
}
231
232
120
void TrackingTraceStateObserver::UpdateTraceCategoryState() {
233

120
  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
69
    return;
241
  }
242
243
112
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
244
112
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
245
246
112
  Isolate* isolate = env_->isolate();
247
171
  HandleScope handle_scope(isolate);
248
112
  Local<Function> cb = env_->trace_category_state_function();
249
112
  if (cb.IsEmpty())
250
53
    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
385
void Environment::CreateProperties() {
258
769
  HandleScope handle_scope(isolate_);
259
385
  Local<Context> ctx = context();
260
261
  {
262
    Context::Scope context_scope(ctx);
263
385
    Local<FunctionTemplate> templ = FunctionTemplate::New(isolate());
264
1155
    templ->InstanceTemplate()->SetInternalFieldCount(
265
385
        BaseObject::kInternalFieldCount);
266
770
    templ->Inherit(BaseObject::GetConstructorTemplate(this));
267
268
385
    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
770
      GetPerContextExports(ctx).ToLocalChecked();
274
  Local<Value> primordials =
275
1155
      per_context_bindings->Get(ctx, primordials_string()).ToLocalChecked();
276
385
  CHECK(primordials->IsObject());
277
385
  set_primordials(primordials.As<Object>());
278
279
  Local<Object> process_object =
280
769
      node::CreateProcessObject(this).FromMaybe(Local<Object>());
281
384
  set_process_object(process_object);
282
385
}
283
284
5303
std::string GetExecPath(const std::vector<std::string>& argv) {
285
  char exec_path_buf[2 * PATH_MAX];
286
5303
  size_t exec_path_len = sizeof(exec_path_buf);
287
5303
  std::string exec_path;
288
5303
  if (uv_exepath(exec_path_buf, &exec_path_len) == 0) {
289
5303
    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
5303
  return exec_path;
308
}
309
310
5303
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
5303
                         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
5303
      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
5303
          isolate_,
328
          1,
329
          MAYBE_FIELD_PTR(env_info, should_abort_on_uncaught_toggle)),
330
5303
      stream_base_state_(isolate_,
331
                         StreamBase::kNumStreamBaseStateFields,
332
                         MAYBE_FIELD_PTR(env_info, stream_base_state)),
333
5303
      environment_start_time_(PERFORMANCE_NOW()),
334
      flags_(flags),
335
5303
      thread_id_(thread_id.id == static_cast<uint64_t>(-1)
336
5303
                     ? AllocateEnvironmentThreadId().id
337


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

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

10554
    if (native_immediates_threadsafe_.size() > 0 ||
549
5277
        native_immediates_interrupts_.size() > 0) {
550
4913
      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
5277
  RegisterHandleCleanups();
559
5277
}
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
5277
void Environment::RegisterHandleCleanups() {
569
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
570
43501
                                        void* arg) {
571
19112
    handle->data = env;
572
573
38218
    env->CloseHandle(handle, [](uv_handle_t* handle) {
574
#ifdef DEBUG
575
      memset(handle, 0xab, uv_handle_size(handle->type));
576
#endif
577
38221
    });
578
48775
  };
579
580
21108
  auto register_handle = [&](uv_handle_t* handle) {
581
21108
    RegisterHandleCleanup(handle, close_and_finish, nullptr);
582
26385
  };
583
5277
  register_handle(reinterpret_cast<uv_handle_t*>(timer_handle()));
584
5277
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
585
5277
  register_handle(reinterpret_cast<uv_handle_t*>(immediate_idle_handle()));
586
5277
  register_handle(reinterpret_cast<uv_handle_t*>(&task_queues_async_));
587
5277
}
588
589
9603
void Environment::CleanupHandles() {
590
  {
591
19209
    Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
592
9606
    task_queues_async_initialized_ = false;
593
  }
594
595
  Isolate::DisallowJavascriptExecutionScope disallow_js(isolate(),
596
19209
      Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
597
598
9605
  RunAndClearNativeImmediates(true /* skip unrefed SetImmediate()s */);
599
600
9644
  for (ReqWrapBase* request : req_wrap_queue_)
601
40
    request->Cancel();
602
603
12421
  for (HandleWrap* handle : handle_wrap_queue_)
604
5638
    handle->Close();
605
606
28712
  for (HandleCleanup& hc : handle_cleanup_queue_)
607
19113
    hc.cb_(this, hc.handle_, hc.arg_);
608
9606
  handle_cleanup_queue_.clear();
609
610

56591
  while (handle_cleanup_waiting_ != 0 ||
611

28470
         request_waiting_ != 0 ||
612
9605
         !handle_wrap_queue_.IsEmpty()) {
613
9262
    uv_run(event_loop(), UV_RUN_ONCE);
614
  }
615
9606
}
616
617
338375
void Environment::PrintSyncTrace() const {
618
338375
  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
4803
void Environment::RunCleanup() {
630
4803
  started_cleanup_ = true;
631
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
632
9608
                              "RunCleanup", this);
633
4804
  bindings_.clear();
634
4803
  initial_base_object_count_ = 0;
635
4803
  CleanupHandles();
636
637
14408
  while (!cleanup_hooks_.empty()) {
638
    // Copy into a vector, since we can't sort an unordered_set in-place.
639
    std::vector<CleanupHookCallback> callbacks(
640
9602
        cleanup_hooks_.begin(), cleanup_hooks_.end());
641
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
642
    // need to be able to check whether they were un-scheduled by another hook.
643
644
9604
    std::sort(callbacks.begin(), callbacks.end(),
645
777861
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
646
      // Sort in descending order so that the most recently inserted callbacks
647
      // are run first.
648
777861
      return a.insertion_order_counter_ > b.insertion_order_counter_;
649
782663
    });
650
651
103820
    for (const CleanupHookCallback& cb : callbacks) {
652
99018
      if (cleanup_hooks_.count(cb) == 0) {
653
        // This hook was removed from the `cleanup_hooks_` set during another
654
        // hook that was run earlier. Nothing to do here.
655
649
        continue;
656
      }
657
658
98371
      cb.fn_(cb.arg_);
659
98367
      cleanup_hooks_.erase(cb);
660
    }
661
4802
    CleanupHandles();
662
  }
663
664
4806
  for (const int fd : unmanaged_fds_) {
665
    uv_fs_t close_req;
666
1
    uv_fs_close(nullptr, &close_req, fd, nullptr);
667
1
    uv_fs_req_cleanup(&close_req);
668
  }
669
4804
}
670
671
5362
void Environment::RunAtExitCallbacks() {
672
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
673
10727
                              "AtExit", this);
674
15950
  for (ExitCallback at_exit : at_exit_functions_) {
675
10585
    at_exit.cb_(at_exit.arg_);
676
  }
677
5365
  at_exit_functions_.clear();
678
5364
}
679
680
10606
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
681
10606
  at_exit_functions_.push_front(ExitCallback{cb, arg});
682
10607
}
683
684
484766
void Environment::RunAndClearInterrupts() {
685
491929
  while (native_immediates_interrupts_.size() > 0) {
686
14326
    NativeImmediateQueue queue;
687
    {
688
14326
      Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_);
689
7163
      queue.ConcatMove(std::move(native_immediates_interrupts_));
690
    }
691
7163
    DebugSealHandleScope seal_handle_scope(isolate());
692
693
21493
    while (auto head = queue.Shift())
694
14330
      head->Call(this);
695
  }
696
477608
}
697
698
470583
void Environment::RunAndClearNativeImmediates(bool only_refed) {
699
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
700
941171
                              "RunAndClearNativeImmediates", this);
701
470584
  size_t ref_count = 0;
702
703
  // Handle interrupts first. These functions are not allowed to throw
704
  // exceptions, so we do not need to handle that.
705
470584
  RunAndClearInterrupts();
706
707
941171
  auto drain_list = [&](NativeImmediateQueue* queue) {
708
1940230
    TryCatchScope try_catch(this);
709
941185
    DebugSealHandleScope seal_handle_scope(isolate());
710
1057262
    while (auto head = queue->Shift()) {
711
58046
      bool is_refed = head->flags() & CallbackFlags::kRefed;
712
58046
      if (is_refed)
713
35719
        ref_count++;
714
715

58046
      if (is_refed || !only_refed)
716
115754
        head->Call(this);
717
718
58042
      head.reset();  // Destroy now so that this is also observed by try_catch.
719
720
58042
      if (UNLIKELY(try_catch.HasCaught())) {
721

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

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

456927
  if (env->immediate_info()->count() == 0 || !env->can_call_into_js())
872
425217
    return;
873
874
32304
  do {
875
64619
    MakeCallback(env->isolate(),
876
                 env->process_object(),
877
                 env->immediate_callback_function(),
878
                 0,
879
                 nullptr,
880
32316
                 {0, 0}).ToLocalChecked();
881

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

28
  if (!object->IsObject() || errorno == 0)
957
    return;
958
959
28
  Local<Object> obj = object.As<Object>();
960
28
  const char* err_string = uv_err_name(errorno);
961
962

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

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















40
  ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V)
1235
#undef V
1236
1237
1
  id = 0;
1238
#define V(PropertyName, TypeName)                                              \
1239
  do {                                                                         \
1240
    Local<TypeName> field = PropertyName();                                    \
1241
    if (!field.IsEmpty()) {                                                    \
1242
      size_t index = creator->AddData(ctx, field);                             \
1243
      info.persistent_values.push_back({#PropertyName, id, index});            \
1244
    }                                                                          \
1245
    id++;                                                                      \
1246
  } while (0);
1247

























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






























































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






































































































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

95584
  if (self->has_pointer_data() &&
1442
2544
      self->pointer_data()->strong_ptr_count > 0) {
1443
235
    return self->Detach();
1444
  }
1445
92808
  delete self;
1446
}
1447
1448
284
bool BaseObject::IsDoneInitializing() const { return true; }
1449
1450
344
Local<Object> BaseObject::WrappedObject() const {
1451
344
  return object();
1452
}
1453
1454
688
bool BaseObject::IsRootNode() const {
1455
1376
  return !persistent_handle_.IsWeak();
1456
}
1457
1458
40913
Local<FunctionTemplate> BaseObject::GetConstructorTemplate(Environment* env) {
1459
40913
  Local<FunctionTemplate> tmpl = env->base_object_ctor_template();
1460
40913
  if (tmpl.IsEmpty()) {
1461
384
    tmpl = env->NewFunctionTemplate(nullptr);
1462
768
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "BaseObject"));
1463
384
    env->set_base_object_ctor_template(tmpl);
1464
  }
1465
40913
  return tmpl;
1466
}
1467
1468

14970
}  // namespace node