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: 421 444 94.8 %
Date: 2019-03-02 22:23:06 Branches: 361 492 73.4 %

Line Branch Exec Source
1
#include "async_wrap.h"
2
#include "node_buffer.h"
3
#include "node_context_data.h"
4
#include "node_errors.h"
5
#include "node_file.h"
6
#include "node_internals.h"
7
#include "node_native_module.h"
8
#include "node_options-inl.h"
9
#include "node_platform.h"
10
#include "node_process.h"
11
#include "node_v8_platform-inl.h"
12
#include "node_worker.h"
13
#include "tracing/agent.h"
14
#include "tracing/traced_value.h"
15
#include "v8-profiler.h"
16
17
#include <cstdio>
18
#include <algorithm>
19
#include <atomic>
20
21
namespace node {
22
23
using errors::TryCatchScope;
24
using v8::ArrayBuffer;
25
using v8::Boolean;
26
using v8::Context;
27
using v8::EmbedderGraph;
28
using v8::External;
29
using v8::Function;
30
using v8::HandleScope;
31
using v8::Integer;
32
using v8::Isolate;
33
using v8::Local;
34
using v8::Message;
35
using v8::NewStringType;
36
using v8::Number;
37
using v8::Object;
38
using v8::Private;
39
using v8::Promise;
40
using v8::PromiseHookType;
41
using v8::StackFrame;
42
using v8::StackTrace;
43
using v8::String;
44
using v8::Symbol;
45
using v8::TracingController;
46
using v8::Undefined;
47
using v8::Value;
48
using worker::Worker;
49
50
#define kTraceCategoryCount 1
51
52
// TODO(@jasnell): Likely useful to move this to util or node_internal to
53
// allow reuse. But since we're not reusing it yet...
54
class TraceEventScope {
55
 public:
56
649254
  TraceEventScope(const char* category,
57
                  const char* name,
58
649254
                  void* id) : category_(category), name_(name), id_(id) {
59

1298512
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(category_, name_, id_);
60
649256
  }
61
649225
  ~TraceEventScope() {
62

1298442
    TRACE_EVENT_NESTABLE_ASYNC_END0(category_, name_, id_);
63
649221
  }
64
65
 private:
66
  const char* category_;
67
  const char* name_;
68
  void* id_;
69
};
70
71
int const Environment::kNodeContextTag = 0x6e6f64;
72
void* const Environment::kNodeContextTagPtr = const_cast<void*>(
73
    static_cast<const void*>(&Environment::kNodeContextTag));
74
75
4420
IsolateData::IsolateData(Isolate* isolate,
76
                         uv_loop_t* event_loop,
77
                         MultiIsolatePlatform* platform,
78
                         ArrayBufferAllocator* node_allocator)
79
    : isolate_(isolate),
80
      event_loop_(event_loop),
81
4420
      allocator_(isolate->GetArrayBufferAllocator()),
82
      node_allocator_(node_allocator),
83
4420
      uses_node_allocator_(allocator_ == node_allocator_),
84
928200
      platform_(platform) {
85
4420
  CHECK_NOT_NULL(allocator_);
86
4420
  if (platform_ != nullptr)
87
4420
    platform_->RegisterIsolate(isolate_, event_loop);
88
89
  options_.reset(
90
4420
      new PerIsolateOptions(*(per_process::cli_options->per_isolate)));
91
92
  // Create string and private symbol properties as internalized one byte
93
  // strings after the platform is properly initialized.
94
  //
95
  // Internalized because it makes property lookups a little faster and
96
  // because the string is created in the old space straight away.  It's going
97
  // to end up in the old space sooner or later anyway but now it doesn't go
98
  // through v8::Eternal's new space handling first.
99
  //
100
  // One byte because our strings are ASCII and we can safely skip V8's UTF-8
101
  // decoding step.
102
103
#define V(PropertyName, StringValue)                                        \
104
    PropertyName ## _.Set(                                                  \
105
        isolate,                                                            \
106
        Private::New(                                                       \
107
            isolate,                                                        \
108
            String::NewFromOneByte(                                         \
109
                isolate,                                                    \
110
                reinterpret_cast<const uint8_t*>(StringValue),              \
111
                NewStringType::kInternalized,                               \
112
                sizeof(StringValue) - 1).ToLocalChecked()));
113
75140
  PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V)
114
#undef V
115
#define V(PropertyName, StringValue)                                        \
116
    PropertyName ## _.Set(                                                  \
117
        isolate,                                                            \
118
        Symbol::New(                                                        \
119
            isolate,                                                        \
120
            String::NewFromOneByte(                                         \
121
                isolate,                                                    \
122
                reinterpret_cast<const uint8_t*>(StringValue),              \
123
                NewStringType::kInternalized,                               \
124
                sizeof(StringValue) - 1).ToLocalChecked()));
125
30940
  PER_ISOLATE_SYMBOL_PROPERTIES(V)
126
#undef V
127
#define V(PropertyName, StringValue)                                        \
128
    PropertyName ## _.Set(                                                  \
129
        isolate,                                                            \
130
        String::NewFromOneByte(                                             \
131
            isolate,                                                        \
132
            reinterpret_cast<const uint8_t*>(StringValue),                  \
133
            NewStringType::kInternalized,                                   \
134
            sizeof(StringValue) - 1).ToLocalChecked());
135
1737060
  PER_ISOLATE_STRING_PROPERTIES(V)
136
#undef V
137
4420
}
138
139
8104
IsolateData::~IsolateData() {
140
4052
  if (platform_ != nullptr)
141
4052
    platform_->UnregisterIsolate(isolate_);
142
4052
}
143
144
145
4244
void InitThreadLocalOnce() {
146
4244
  CHECK_EQ(0, uv_key_create(&Environment::thread_local_env));
147
4244
}
148
149
134
void Environment::TrackingTraceStateObserver::UpdateTraceCategoryState() {
150
134
  if (!env_->owns_process_state()) {
151
    // Ideally, we’d have a consistent story that treats all threads/Environment
152
    // instances equally here. However, tracing is essentially global, and this
153
    // callback is called from whichever thread calls `StartTracing()` or
154
    // `StopTracing()`. The only way to do this in a threadsafe fashion
155
    // seems to be only tracking this from the main thread, and only allowing
156
    // these state modifications from the main thread.
157
71
    return;
158
  }
159
160
132
  bool async_hooks_enabled = (*(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
161
132
                                 TRACING_CATEGORY_NODE1(async_hooks)))) != 0;
162
163
132
  Isolate* isolate = env_->isolate();
164
132
  HandleScope handle_scope(isolate);
165
132
  Local<Function> cb = env_->trace_category_state_function();
166
132
  if (cb.IsEmpty())
167
67
    return;
168
130
  TryCatchScope try_catch(env_);
169
65
  try_catch.SetVerbose(true);
170
130
  Local<Value> args[] = {Boolean::New(isolate, async_hooks_enabled)};
171
260
  cb->Call(env_->context(), Undefined(isolate), arraysize(args), args)
172
195
      .ToLocalChecked();
173
}
174
175
static std::atomic<uint64_t> next_thread_id{0};
176
177
4421
uint64_t Environment::AllocateThreadId() {
178
4421
  return next_thread_id++;
179
}
180
181
4417
Environment::Environment(IsolateData* isolate_data,
182
                         Local<Context> context,
183
                         Flags flags,
184
                         uint64_t thread_id)
185
4417
    : isolate_(context->GetIsolate()),
186
      isolate_data_(isolate_data),
187
      immediate_info_(context->GetIsolate()),
188
      tick_info_(context->GetIsolate()),
189
4417
      timer_base_(uv_now(isolate_data->event_loop())),
190
      should_abort_on_uncaught_toggle_(isolate_, 1),
191
      stream_base_state_(isolate_, StreamBase::kNumStreamBaseStateFields),
192
      flags_(flags),
193
      thread_id_(thread_id == kNoThreadId ? AllocateThreadId() : thread_id),
194
      fs_stats_field_array_(isolate_, kFsStatsBufferLength),
195
      fs_stats_field_bigint_array_(isolate_, kFsStatsBufferLength),
196
318024
      context_(context->GetIsolate(), context) {
197
  // We'll be creating new objects so make sure we've entered the context.
198
4417
  HandleScope handle_scope(isolate());
199
  Context::Scope context_scope(context);
200
4417
  set_as_external(External::New(isolate(), this));
201
202
  // We create new copies of the per-Environment option sets, so that it is
203
  // easier to modify them after Environment creation. The defaults are
204
  // part of the per-Isolate option set, for which in turn the defaults are
205
  // part of the per-process option set.
206
4417
  options_.reset(new EnvironmentOptions(*isolate_data->options()->per_env));
207
4417
  inspector_host_port_.reset(new HostPort(options_->debug_options().host_port));
208
209
#if HAVE_INSPECTOR
210
  // We can only create the inspector agent after having cloned the options.
211
13251
  inspector_agent_ =
212
8834
      std::unique_ptr<inspector::Agent>(new inspector::Agent(this));
213
#endif
214
215
4417
  AssignToContext(context, ContextInfo(""));
216
217
4417
  if (tracing::AgentWriterHandle* writer = GetTracingAgentWriter()) {
218
4417
    trace_state_observer_ = std::make_unique<TrackingTraceStateObserver>(this);
219
4417
    TracingController* tracing_controller = writer->GetTracingController();
220
4417
    tracing_controller->AddTraceStateObserver(trace_state_observer_.get());
221
  }
222
223
4417
  destroy_async_id_list_.reserve(512);
224
  BeforeExit(
225
12179
      [](void* arg) {
226
3881
        Environment* env = static_cast<Environment*>(arg);
227
3881
        if (!env->destroy_async_id_list()->empty())
228
140
          AsyncWrap::DestroyAsyncIdsCallback(env, nullptr);
229
12179
      },
230
4417
      this);
231
232
4417
  performance_state_.reset(new performance::performance_state(isolate()));
233
  performance_state_->Mark(
234
4417
      performance::NODE_PERFORMANCE_MILESTONE_ENVIRONMENT);
235
  performance_state_->Mark(performance::NODE_PERFORMANCE_MILESTONE_NODE_START,
236
4417
                           per_process::node_start_time);
237
  performance_state_->Mark(
238
      performance::NODE_PERFORMANCE_MILESTONE_V8_START,
239
4417
      performance::performance_v8_start);
240
241
  // By default, always abort when --abort-on-uncaught-exception was passed.
242
4417
  should_abort_on_uncaught_toggle_[0] = 1;
243
244
8834
  std::string debug_cats;
245
4417
  credentials::SafeGetenv("NODE_DEBUG_NATIVE", &debug_cats);
246
4417
  set_debug_categories(debug_cats, true);
247
248
  isolate()->GetHeapProfiler()->AddBuildEmbedderGraphCallback(
249
4417
      BuildEmbedderGraph, this);
250
4417
  if (options_->no_force_async_hooks_checks) {
251
1
    async_hooks_.no_force_checks();
252
  }
253
254
  // TODO(addaleax): the per-isolate state should not be controlled by
255
  // a single Environment.
256
8834
  isolate()->SetPromiseRejectCallback(task_queue::PromiseRejectCallback);
257
4417
}
258
259
41620
CompileFnEntry::CompileFnEntry(Environment* env, uint32_t id)
260
41620
    : env(env), id(id) {
261
41620
  env->compile_fn_entries.insert(this);
262
41620
}
263
264
283430
Environment::~Environment() {
265
  isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback(
266
4049
      BuildEmbedderGraph, this);
267
268
  // Make sure there are no re-used libuv wrapper objects.
269
  // CleanupHandles() should have removed all of them.
270
4049
  CHECK(file_handle_read_wrap_freelist_.empty());
271
272
  // dispose the Persistent references to the compileFunction
273
  // wrappers used in the dynamic import callback
274
22998
  for (auto& entry : compile_fn_entries) {
275
18949
    delete entry;
276
  }
277
278
4049
  HandleScope handle_scope(isolate());
279
280
#if HAVE_INSPECTOR
281
  // Destroy inspector agent before erasing the context. The inspector
282
  // destructor depends on the context still being accessible.
283
4049
  inspector_agent_.reset();
284
#endif
285
286
  context()->SetAlignedPointerInEmbedderData(
287
8098
      ContextEmbedderIndex::kEnvironment, nullptr);
288
289
4049
  if (trace_state_observer_) {
290
4048
    tracing::AgentWriterHandle* writer = GetTracingAgentWriter();
291
4048
    CHECK_NOT_NULL(writer);
292
4048
    TracingController* tracing_controller = writer->GetTracingController();
293
4049
    tracing_controller->RemoveTraceStateObserver(trace_state_observer_.get());
294
  }
295
296
4049
  delete[] heap_statistics_buffer_;
297
4049
  delete[] heap_space_statistics_buffer_;
298
4049
  delete[] http_parser_buffer_;
299
300

8098
  TRACE_EVENT_NESTABLE_ASYNC_END0(
301
    TRACING_CATEGORY_NODE1(environment), "Environment", this);
302
303
  // Do not unload addons on the main thread. Some addons need to retain memory
304
  // beyond the Environment's lifetime, and unloading them early would break
305
  // them; with Worker threads, we have the opportunity to be stricter.
306
  // Also, since the main thread usually stops just before the process exits,
307
  // this is far less relevant here.
308
4049
  if (!is_main_thread()) {
309
    // Dereference all addons that were loaded into this environment.
310
180
    for (binding::DLib& addon : loaded_addons_) {
311
7
      addon.Close();
312
    }
313
4049
  }
314
4049
}
315
316
4417
void Environment::Start(bool start_profiler_idle_notifier) {
317
4417
  HandleScope handle_scope(isolate());
318
4417
  Context::Scope context_scope(context());
319
320
4417
  CHECK_EQ(0, uv_timer_init(event_loop(), timer_handle()));
321
4417
  uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
322
323
4417
  uv_check_init(event_loop(), immediate_check_handle());
324
4417
  uv_unref(reinterpret_cast<uv_handle_t*>(immediate_check_handle()));
325
326
4417
  uv_idle_init(event_loop(), immediate_idle_handle());
327
328
4417
  uv_check_start(immediate_check_handle(), CheckImmediate);
329
330
  // Inform V8's CPU profiler when we're idle.  The profiler is sampling-based
331
  // but not all samples are created equal; mark the wall clock time spent in
332
  // epoll_wait() and friends so profiling tools can filter it out.  The samples
333
  // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
334
  // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
335
  // probably fortify in the API contract, namely that the last started prepare
336
  // or check watcher runs first.  It's not 100% foolproof; if an add-on starts
337
  // a prepare or check watcher after us, any samples attributed to its callback
338
  // will be recorded with state=IDLE.
339
4417
  uv_prepare_init(event_loop(), &idle_prepare_handle_);
340
4417
  uv_check_init(event_loop(), &idle_check_handle_);
341
4417
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_));
342
4417
  uv_unref(reinterpret_cast<uv_handle_t*>(&idle_check_handle_));
343
344
  // Register clean-up cb to be called to clean up the handles
345
  // when the environment is freed, note that they are not cleaned in
346
  // the one environment per process setup, but will be called in
347
  // FreeEnvironment.
348
4417
  RegisterHandleCleanups();
349
350
4417
  if (start_profiler_idle_notifier) {
351
3
    StartProfilerIdleNotifier();
352
  }
353
354
  static uv_once_t init_once = UV_ONCE_INIT;
355
4417
  uv_once(&init_once, InitThreadLocalOnce);
356
8834
  uv_key_set(&thread_local_env, this);
357
4417
}
358
359
4417
MaybeLocal<Object> Environment::ProcessCliArgs(
360
    const std::vector<std::string>& args,
361
    const std::vector<std::string>& exec_args) {
362
4417
  if (args.size() > 1) {
363
3942
    std::string first_arg = args[1];
364
3942
    if (first_arg == "inspect") {
365
2
      execution_mode_ = ExecutionMode::kInspect;
366
3940
    } else if (first_arg == "debug") {
367
2
      execution_mode_ = ExecutionMode::kDebug;
368
3938
    } else if (first_arg != "-") {
369
3936
      execution_mode_ = ExecutionMode::kRunMainModule;
370
3942
    }
371
  }
372
373
8834
  if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
374
4417
          TRACING_CATEGORY_NODE1(environment)) != 0) {
375
8
    auto traced_value = tracing::TracedValue::Create();
376
8
    traced_value->BeginArray("args");
377
8
    for (const std::string& arg : args) traced_value->AppendString(arg);
378
8
    traced_value->EndArray();
379
8
    traced_value->BeginArray("exec_args");
380
8
    for (const std::string& arg : exec_args) traced_value->AppendString(arg);
381
8
    traced_value->EndArray();
382

16
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(environment),
383
                                      "Environment",
384
                                      this,
385
                                      "args",
386
8
                                      std::move(traced_value));
387
  }
388
389
4417
  exec_argv_ = exec_args;
390
  Local<Object> process_object =
391
      node::CreateProcessObject(this, args, exec_args)
392
8834
          .FromMaybe(Local<Object>());
393
4417
  set_process_object(process_object);
394
4417
  return process_object;
395
}
396
397
4417
void Environment::RegisterHandleCleanups() {
398
  HandleCleanupCb close_and_finish = [](Environment* env, uv_handle_t* handle,
399
44897
                                        void* arg) {
400
20240
    handle->data = env;
401
402
20240
    env->CloseHandle(handle, [](uv_handle_t* handle) {
403
#ifdef DEBUG
404
      memset(handle, 0xab, uv_handle_size(handle->type));
405
#endif
406
40480
    });
407
49314
  };
408
409
  RegisterHandleCleanup(
410
4417
      reinterpret_cast<uv_handle_t*>(timer_handle()),
411
      close_and_finish,
412
4417
      nullptr);
413
  RegisterHandleCleanup(
414
4417
      reinterpret_cast<uv_handle_t*>(immediate_check_handle()),
415
      close_and_finish,
416
4417
      nullptr);
417
  RegisterHandleCleanup(
418
4417
      reinterpret_cast<uv_handle_t*>(immediate_idle_handle()),
419
      close_and_finish,
420
4417
      nullptr);
421
  RegisterHandleCleanup(
422
      reinterpret_cast<uv_handle_t*>(&idle_prepare_handle_),
423
      close_and_finish,
424
4417
      nullptr);
425
  RegisterHandleCleanup(
426
      reinterpret_cast<uv_handle_t*>(&idle_check_handle_),
427
      close_and_finish,
428
4417
      nullptr);
429
4417
}
430
431
8266
void Environment::CleanupHandles() {
432
8300
  for (ReqWrapBase* request : req_wrap_queue_)
433
34
    request->Cancel();
434
435
10483
  for (HandleWrap* handle : handle_wrap_queue_)
436
4434
    handle->Close();
437
438
28506
  for (HandleCleanup& hc : handle_cleanup_queue_)
439
20240
    hc.cb_(this, hc.handle_, hc.arg_);
440
8266
  handle_cleanup_queue_.clear();
441
442

41177
  while (handle_cleanup_waiting_ != 0 ||
443

20588
         request_waiting_ != 0 ||
444
8266
         !handle_wrap_queue_.IsEmpty()) {
445
4056
    uv_run(event_loop(), UV_RUN_ONCE);
446
  }
447
448
8266
  file_handle_read_wrap_freelist_.clear();
449
8266
}
450
451
3
void Environment::StartProfilerIdleNotifier() {
452
3
  if (profiler_idle_notifier_started_)
453
3
    return;
454
455
3
  profiler_idle_notifier_started_ = true;
456
457
13
  uv_prepare_start(&idle_prepare_handle_, [](uv_prepare_t* handle) {
458
5
    Environment* env = ContainerOf(&Environment::idle_prepare_handle_, handle);
459
5
    env->isolate()->SetIdle(true);
460
16
  });
461
462
13
  uv_check_start(&idle_check_handle_, [](uv_check_t* handle) {
463
5
    Environment* env = ContainerOf(&Environment::idle_check_handle_, handle);
464
5
    env->isolate()->SetIdle(false);
465
16
  });
466
}
467
468
void Environment::StopProfilerIdleNotifier() {
469
  profiler_idle_notifier_started_ = false;
470
  uv_prepare_stop(&idle_prepare_handle_);
471
  uv_check_stop(&idle_check_handle_);
472
}
473
474
512734
void Environment::PrintSyncTrace() const {
475
512734
  if (!options_->trace_sync_io)
476
1025430
    return;
477
478
40
  HandleScope handle_scope(isolate());
479
  Local<StackTrace> stack =
480
40
      StackTrace::CurrentStackTrace(isolate(), 10, StackTrace::kDetailed);
481
482
  fprintf(stderr, "(node:%d) WARNING: Detected use of sync API\n",
483
40
          uv_os_getpid());
484
485
640
  for (int i = 0; i < stack->GetFrameCount() - 1; i++) {
486
560
    Local<StackFrame> stack_frame = stack->GetFrame(isolate(), i);
487
560
    node::Utf8Value fn_name_s(isolate(), stack_frame->GetFunctionName());
488
840
    node::Utf8Value script_name(isolate(), stack_frame->GetScriptName());
489
280
    const int line_number = stack_frame->GetLineNumber();
490
280
    const int column = stack_frame->GetColumn();
491
492
280
    if (stack_frame->IsEval()) {
493
      if (stack_frame->GetScriptId() == Message::kNoScriptIdInfo) {
494
        fprintf(stderr, "    at [eval]:%i:%i\n", line_number, column);
495
      } else {
496
        fprintf(stderr,
497
                "    at [eval] (%s:%i:%i)\n",
498
                *script_name,
499
                line_number,
500
                column);
501
      }
502
      break;
503
    }
504
505
280
    if (fn_name_s.length() == 0) {
506
21
      fprintf(stderr, "    at %s:%i:%i\n", *script_name, line_number, column);
507
    } else {
508
      fprintf(stderr,
509
              "    at %s (%s:%i:%i)\n",
510
              *fn_name_s,
511
              *script_name,
512
              line_number,
513
259
              column);
514
    }
515
280
  }
516
40
  fflush(stderr);
517
}
518
519
4221
void Environment::RunCleanup() {
520
4221
  started_cleanup_ = true;
521
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
522
4221
                              "RunCleanup", this);
523
4221
  CleanupHandles();
524
525
12487
  while (!cleanup_hooks_.empty()) {
526
    // Copy into a vector, since we can't sort an unordered_set in-place.
527
    std::vector<CleanupHookCallback> callbacks(
528
4045
        cleanup_hooks_.begin(), cleanup_hooks_.end());
529
    // We can't erase the copied elements from `cleanup_hooks_` yet, because we
530
    // need to be able to check whether they were un-scheduled by another hook.
531
532
    std::sort(callbacks.begin(), callbacks.end(),
533
484512
              [](const CleanupHookCallback& a, const CleanupHookCallback& b) {
534
      // Sort in descending order so that the most recently inserted callbacks
535
      // are run first.
536
484512
      return a.insertion_order_counter_ > b.insertion_order_counter_;
537
488557
    });
538
539
44676
    for (const CleanupHookCallback& cb : callbacks) {
540
40631
      if (cleanup_hooks_.count(cb) == 0) {
541
        // This hook was removed from the `cleanup_hooks_` set during another
542
        // hook that was run earlier. Nothing to do here.
543
        continue;
544
      }
545
546
40631
      cb.fn_(cb.arg_);
547
40631
      cleanup_hooks_.erase(cb);
548
    }
549
4045
    CleanupHandles();
550
8266
  }
551
4221
}
552
553
3894
void Environment::RunBeforeExitCallbacks() {
554
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
555
3894
                              "BeforeExit", this);
556
7775
  for (ExitCallback before_exit : before_exit_functions_) {
557
3881
    before_exit.cb_(before_exit.arg_);
558
  }
559
3894
  before_exit_functions_.clear();
560
3894
}
561
562
4417
void Environment::BeforeExit(void (*cb)(void* arg), void* arg) {
563
4417
  before_exit_functions_.push_back(ExitCallback{cb, arg});
564
4417
}
565
566
4048
void Environment::RunAtExitCallbacks() {
567
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
568
4048
                              "AtExit", this);
569
4055
  for (ExitCallback at_exit : at_exit_functions_) {
570
7
    at_exit.cb_(at_exit.arg_);
571
  }
572
4048
  at_exit_functions_.clear();
573
4048
}
574
575
7
void Environment::AtExit(void (*cb)(void* arg), void* arg) {
576
7
  at_exit_functions_.push_back(ExitCallback{cb, arg});
577
7
}
578
579
249
void Environment::AddPromiseHook(promise_hook_func fn, void* arg) {
580
  auto it = std::find_if(
581
      promise_hooks_.begin(), promise_hooks_.end(),
582
3
      [&](const PromiseHookCallback& hook) {
583

3
        return hook.cb_ == fn && hook.arg_ == arg;
584
252
      });
585
249
  if (it != promise_hooks_.end()) {
586
3
    it->enable_count_++;
587
252
    return;
588
  }
589
246
  promise_hooks_.push_back(PromiseHookCallback{fn, arg, 1});
590
591
246
  if (promise_hooks_.size() == 1) {
592
246
    isolate_->SetPromiseHook(EnvPromiseHook);
593
  }
594
}
595
596
211
bool Environment::RemovePromiseHook(promise_hook_func fn, void* arg) {
597
  auto it = std::find_if(
598
      promise_hooks_.begin(), promise_hooks_.end(),
599
211
      [&](const PromiseHookCallback& hook) {
600

211
        return hook.cb_ == fn && hook.arg_ == arg;
601
422
      });
602
603
211
  if (it == promise_hooks_.end()) return false;
604
605
211
  if (--it->enable_count_ > 0) return true;
606
607
208
  promise_hooks_.erase(it);
608
208
  if (promise_hooks_.empty()) {
609
208
    isolate_->SetPromiseHook(nullptr);
610
  }
611
612
208
  return true;
613
}
614
615
3958
void Environment::EnvPromiseHook(PromiseHookType type,
616
                                 Local<Promise> promise,
617
                                 Local<Value> parent) {
618
3958
  Local<Context> context = promise->CreationContext();
619
620
3958
  Environment* env = Environment::GetCurrent(context);
621
7916
  if (env == nullptr) return;
622
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
623
3958
                              "EnvPromiseHook", env);
624
7916
  for (const PromiseHookCallback& hook : env->promise_hooks_) {
625
3958
    hook.cb_(type, promise, parent, hook.arg_);
626
3958
  }
627
}
628
629
52564
void Environment::RunAndClearNativeImmediates() {
630
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
631
52564
                              "RunAndClearNativeImmediates", this);
632
52564
  size_t count = native_immediate_callbacks_.size();
633
52564
  if (count > 0) {
634
46371
    size_t ref_count = 0;
635
46371
    std::vector<NativeImmediateCallback> list;
636
46371
    native_immediate_callbacks_.swap(list);
637
46372
    auto drain_list = [&]() {
638
46372
      TryCatchScope try_catch(this);
639
95963
      for (auto it = list.begin(); it != list.end(); ++it) {
640
#ifdef DEBUG
641
        v8::SealHandleScope seal_handle_scope(isolate());
642
#endif
643
49593
        it->cb_(this, it->data_);
644
49592
        if (it->refed_)
645
27567
          ref_count++;
646
49592
        if (UNLIKELY(try_catch.HasCaught())) {
647
1
          if (!try_catch.HasTerminated())
648
            FatalException(isolate(), try_catch);
649
650
          // Bail out, remove the already executed callbacks from list
651
          // and set up a new TryCatch for the other pending callbacks.
652
1
          std::move_backward(it, list.end(), list.begin() + (list.end() - it));
653
1
          list.resize(list.end() - it);
654
1
          return true;
655
        }
656
      }
657
46370
      return false;
658
92742
    };
659
46371
    while (drain_list()) {}
660
661
    DCHECK_GE(immediate_info()->count(), count);
662
46370
    immediate_info()->count_dec(count);
663
46370
    immediate_info()->ref_count_dec(ref_count);
664
52563
  }
665
52563
}
666
667
668
7329
void Environment::ScheduleTimer(int64_t duration_ms) {
669
14658
  if (started_cleanup_) return;
670
7329
  uv_timer_start(timer_handle(), RunTimers, duration_ms, 0);
671
}
672
673
1259
void Environment::ToggleTimerRef(bool ref) {
674
2518
  if (started_cleanup_) return;
675
676
1259
  if (ref) {
677
951
    uv_ref(reinterpret_cast<uv_handle_t*>(timer_handle()));
678
  } else {
679
308
    uv_unref(reinterpret_cast<uv_handle_t*>(timer_handle()));
680
  }
681
}
682
683
5837
void Environment::RunTimers(uv_timer_t* handle) {
684
5837
  Environment* env = Environment::from_timer_handle(handle);
685
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
686
5837
                              "RunTimers", env);
687
688
5837
  if (!env->can_call_into_js())
689
1
    return;
690
691
11644
  HandleScope handle_scope(env->isolate());
692
11644
  Context::Scope context_scope(env->context());
693
694
5836
  Local<Object> process = env->process_object();
695
11644
  InternalCallbackScope scope(env, process, {0, 0});
696
697
5836
  Local<Function> cb = env->timers_callback_function();
698
  MaybeLocal<Value> ret;
699
5836
  Local<Value> arg = env->GetNow();
700
  // This code will loop until all currently due timers will process. It is
701
  // impossible for us to end up in an infinite loop due to how the JS-side
702
  // is structured.
703
5840
  do {
704
5865
    TryCatchScope try_catch(env);
705
5865
    try_catch.SetVerbose(true);
706
11730
    ret = cb->Call(env->context(), process, 1, &arg);
707

5840
  } while (ret.IsEmpty() && env->can_call_into_js());
708
709
  // NOTE(apapirovski): If it ever becomes possible that `call_into_js` above
710
  // is reset back to `true` after being previously set to `false` then this
711
  // code becomes invalid and needs to be rewritten. Otherwise catastrophic
712
  // timers corruption will occur and all timers behaviour will become
713
  // entirely unpredictable.
714
5811
  if (ret.IsEmpty())
715
3
    return;
716
717
  // To allow for less JS-C++ boundary crossing, the value returned from JS
718
  // serves a few purposes:
719
  // 1. If it's 0, no more timers exist and the handle should be unrefed
720
  // 2. If it's > 0, the value represents the next timer's expiry and there
721
  //    is at least one timer remaining that is refed.
722
  // 3. If it's < 0, the absolute value represents the next timer's expiry
723
  //    and there are no timers that are refed.
724
  int64_t expiry_ms =
725
23232
      ret.ToLocalChecked()->IntegerValue(env->context()).FromJust();
726
727
5808
  uv_handle_t* h = reinterpret_cast<uv_handle_t*>(handle);
728
729
5808
  if (expiry_ms != 0) {
730
    int64_t duration_ms =
731
5307
        llabs(expiry_ms) - (uv_now(env->event_loop()) - env->timer_base());
732
733
5307
    env->ScheduleTimer(duration_ms > 0 ? duration_ms : 1);
734
735
5307
    if (expiry_ms > 0)
736
4860
      uv_ref(h);
737
    else
738
447
      uv_unref(h);
739
  } else {
740
501
    uv_unref(h);
741
5808
  }
742
}
743
744
745
574733
void Environment::CheckImmediate(uv_check_t* handle) {
746
574733
  Environment* env = Environment::from_immediate_check_handle(handle);
747
  TraceEventScope trace_scope(TRACING_CATEGORY_NODE1(environment),
748
574733
                              "CheckImmediate", env);
749
750
574733
  if (env->immediate_info()->count() == 0)
751
522171
    return;
752
753
105119
  HandleScope scope(env->isolate());
754
105119
  Context::Scope context_scope(env->context());
755
756
52564
  env->RunAndClearNativeImmediates();
757
758
52563
  if (!env->can_call_into_js())
759
3
    return;
760
761
53076
  do {
762
    MakeCallback(env->isolate(),
763
                 env->process_object(),
764
                 env->immediate_callback_function(),
765
                 0,
766
                 nullptr,
767
106157
                 {0, 0}).ToLocalChecked();
768

53076
  } while (env->immediate_info()->has_outstanding() && env->can_call_into_js());
769
770
52555
  if (env->immediate_info()->ref_count() == 0)
771
78672
    env->ToggleImmediateRef(false);
772
}
773
774
74575
void Environment::ToggleImmediateRef(bool ref) {
775
149150
  if (started_cleanup_) return;
776
777
74574
  if (ref) {
778
    // Idle handle is needed only to stop the event loop from blocking in poll.
779
151584
    uv_idle_start(immediate_idle_handle(), [](uv_idle_t*){ });
780
  } else {
781
26131
    uv_idle_stop(immediate_idle_handle());
782
  }
783
}
784
785
786
339628
Local<Value> Environment::GetNow() {
787
339628
  uv_update_time(event_loop());
788
339628
  uint64_t now = uv_now(event_loop());
789
339628
  CHECK_GE(now, timer_base());
790
339628
  now -= timer_base();
791
339628
  if (now <= 0xffffffff)
792
679256
    return Integer::NewFromUnsigned(isolate(), static_cast<uint32_t>(now));
793
  else
794
    return Number::New(isolate(), static_cast<double>(now));
795
}
796
797
798
4417
void Environment::set_debug_categories(const std::string& cats, bool enabled) {
799
4417
  std::string debug_categories = cats;
800
4417
  while (!debug_categories.empty()) {
801
4
    std::string::size_type comma_pos = debug_categories.find(',');
802
4
    std::string wanted = ToLower(debug_categories.substr(0, comma_pos));
803
804
#define V(name)                                                          \
805
    {                                                                    \
806
      static const std::string available_category = ToLower(#name);      \
807
      if (available_category.find(wanted) != std::string::npos)          \
808
        set_debug_enabled(DebugCategory::name, enabled);                 \
809
    }
810
811
































































4
    DEBUG_CATEGORY_NAMES(V)
812
813
4
    if (comma_pos == std::string::npos)
814
4
      break;
815
    // Use everything after the `,` as the list for the next iteration.
816
    debug_categories = debug_categories.substr(comma_pos + 1);
817
4417
  }
818
4417
}
819
820
28
void CollectExceptionInfo(Environment* env,
821
                          Local<Object> obj,
822
                          int errorno,
823
                          const char* err_string,
824
                          const char* syscall,
825
                          const char* message,
826
                          const char* path,
827
                          const char* dest) {
828
  obj->Set(env->context(),
829
           env->errno_string(),
830
140
           Integer::New(env->isolate(), errorno)).FromJust();
831
832
  obj->Set(env->context(), env->code_string(),
833
140
           OneByteString(env->isolate(), err_string)).FromJust();
834
835
28
  if (message != nullptr) {
836
    obj->Set(env->context(), env->message_string(),
837
140
             OneByteString(env->isolate(), message)).FromJust();
838
  }
839
840
  Local<Value> path_buffer;
841
28
  if (path != nullptr) {
842
    path_buffer =
843
      Buffer::Copy(env->isolate(), path, strlen(path)).ToLocalChecked();
844
    obj->Set(env->context(), env->path_string(), path_buffer).FromJust();
845
  }
846
847
  Local<Value> dest_buffer;
848
28
  if (dest != nullptr) {
849
    dest_buffer =
850
      Buffer::Copy(env->isolate(), dest, strlen(dest)).ToLocalChecked();
851
    obj->Set(env->context(), env->dest_string(), dest_buffer).FromJust();
852
  }
853
854
28
  if (syscall != nullptr) {
855
    obj->Set(env->context(), env->syscall_string(),
856
140
             OneByteString(env->isolate(), syscall)).FromJust();
857
  }
858
28
}
859
860
28
void Environment::CollectUVExceptionInfo(Local<Value> object,
861
                                         int errorno,
862
                                         const char* syscall,
863
                                         const char* message,
864
                                         const char* path,
865
                                         const char* dest) {
866

28
  if (!object->IsObject() || errorno == 0)
867
28
    return;
868
869
28
  Local<Object> obj = object.As<Object>();
870
28
  const char* err_string = uv_err_name(errorno);
871
872

28
  if (message == nullptr || message[0] == '\0') {
873
28
    message = uv_strerror(errorno);
874
  }
875
876
  node::CollectExceptionInfo(this, obj, errorno, err_string,
877
28
                             syscall, message, path, dest);
878
}
879
880
881
8
void Environment::AsyncHooks::grow_async_ids_stack() {
882
8
  async_ids_stack_.reserve(async_ids_stack_.Length() * 3);
883
884
8
  env()->async_hooks_binding()->Set(
885
      env()->context(),
886
      env()->async_ids_stack_string(),
887
48
      async_ids_stack_.GetJSArray()).FromJust();
888
8
}
889
890
uv_key_t Environment::thread_local_env = {};
891
892
387
void Environment::Exit(int exit_code) {
893
387
  if (is_main_thread()) {
894
365
    stop_sub_worker_contexts();
895
364
    DisposePlatform();
896
364
    exit(exit_code);
897
  } else {
898
22
    worker_context_->Exit(exit_code);
899
  }
900
22
}
901
902
4413
void Environment::stop_sub_worker_contexts() {
903
8848
  while (!sub_worker_contexts_.empty()) {
904
23
    Worker* w = *sub_worker_contexts_.begin();
905
23
    remove_sub_worker_context(w);
906
23
    w->Exit(1);
907
23
    w->JoinThread();
908
  }
909
4412
}
910
911
32
void Environment::BuildEmbedderGraph(Isolate* isolate,
912
                                     EmbedderGraph* graph,
913
                                     void* data) {
914
32
  MemoryTracker tracker(isolate, graph);
915
93
  static_cast<Environment*>(data)->ForEachBaseObject([&](BaseObject* obj) {
916
93
    tracker.Track(obj);
917
125
  });
918
32
}
919
920
409268
char* Environment::Reallocate(char* data, size_t old_size, size_t size) {
921
  // If we know that the allocator is our ArrayBufferAllocator, we can let
922
  // if reallocate directly.
923
409268
  if (isolate_data()->uses_node_allocator()) {
924
    return static_cast<char*>(
925
409268
        isolate_data()->node_allocator()->Reallocate(data, old_size, size));
926
  }
927
  // Generic allocators do not provide a reallocation method; we need to
928
  // allocate a new chunk of memory and copy the data over.
929
  char* new_data = AllocateUnchecked(size);
930
  if (new_data == nullptr) return nullptr;
931
  memcpy(new_data, data, std::min(size, old_size));
932
  if (size > old_size)
933
    memset(new_data + old_size, 0, size - old_size);
934
  Free(data, old_size);
935
  return new_data;
936
}
937
938
// Not really any better place than env.cc at this moment.
939
40555
void BaseObject::DeleteMe(void* data) {
940
40555
  BaseObject* self = static_cast<BaseObject*>(data);
941
40555
  delete self;
942
40555
}
943
944
93
Local<Object> BaseObject::WrappedObject() const {
945
93
  return object();
946
}
947
948
93
bool BaseObject::IsRootNode() const {
949
186
  return !persistent_handle_.IsWeak();
950
}
951
952
}  // namespace node