GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_platform.cc Lines: 350 366 95.6 %
Date: 2022-09-25 04:23:55 Branches: 79 104 76.0 %

Line Branch Exec Source
1
#include "node_platform.h"
2
#include "node_internals.h"
3
4
#include "env-inl.h"
5
#include "debug_utils-inl.h"
6
#include <algorithm>  // find_if(), find(), move()
7
#include <cmath>  // llround()
8
#include <memory>  // unique_ptr(), shared_ptr(), make_shared()
9
10
namespace node {
11
12
using v8::Isolate;
13
using v8::Object;
14
using v8::Platform;
15
using v8::Task;
16
17
namespace {
18
19
struct PlatformWorkerData {
20
  TaskQueue<Task>* task_queue;
21
  Mutex* platform_workers_mutex;
22
  ConditionVariable* platform_workers_ready;
23
  int* pending_platform_workers;
24
  int id;
25
};
26
27
22170
static void PlatformWorkerThread(void* data) {
28
  std::unique_ptr<PlatformWorkerData>
29
44304
      worker_data(static_cast<PlatformWorkerData*>(data));
30
31
22170
  TaskQueue<Task>* pending_worker_tasks = worker_data->task_queue;
32

28082
  TRACE_EVENT_METADATA1("__metadata", "thread_name", "name",
33
                        "PlatformWorkerThread");
34
35
  // Notify the main thread that the platform worker is ready.
36
  {
37
44340
    Mutex::ScopedLock lock(*worker_data->platform_workers_mutex);
38
22170
    (*worker_data->pending_platform_workers)--;
39
22170
    worker_data->platform_workers_ready->Signal(lock);
40
  }
41
42
125459
  while (std::unique_ptr<Task> task = pending_worker_tasks->BlockingPop()) {
43
103289
    task->Run();
44
103289
    pending_worker_tasks->NotifyOfCompletion();
45
103289
  }
46
22134
}
47
48
}  // namespace
49
50
class WorkerThreadsTaskRunner::DelayedTaskScheduler {
51
 public:
52
5541
  explicit DelayedTaskScheduler(TaskQueue<Task>* tasks)
53
5541
    : pending_worker_tasks_(tasks) {}
54
55
5541
  std::unique_ptr<uv_thread_t> Start() {
56
5541
    auto start_thread = [](void* data) {
57
5541
      static_cast<DelayedTaskScheduler*>(data)->Run();
58
5532
    };
59
5541
    std::unique_ptr<uv_thread_t> t { new uv_thread_t() };
60
5541
    uv_sem_init(&ready_, 0);
61
5541
    CHECK_EQ(0, uv_thread_create(t.get(), start_thread, this));
62
5541
    uv_sem_wait(&ready_);
63
5541
    uv_sem_destroy(&ready_);
64
5541
    return t;
65
  }
66
67
526
  void PostDelayedTask(std::unique_ptr<Task> task, double delay_in_seconds) {
68
526
    tasks_.Push(std::make_unique<ScheduleTask>(this, std::move(task),
69
                                               delay_in_seconds));
70
526
    uv_async_send(&flush_tasks_);
71
526
  }
72
73
5532
  void Stop() {
74
5532
    tasks_.Push(std::make_unique<StopTask>(this));
75
5532
    uv_async_send(&flush_tasks_);
76
5532
  }
77
78
 private:
79
5541
  void Run() {
80

11167
    TRACE_EVENT_METADATA1("__metadata", "thread_name", "name",
81
                          "WorkerThreadsTaskRunner::DelayedTaskScheduler");
82
5541
    loop_.data = this;
83
5541
    CHECK_EQ(0, uv_loop_init(&loop_));
84
5541
    flush_tasks_.data = this;
85
5541
    CHECK_EQ(0, uv_async_init(&loop_, &flush_tasks_, FlushTasks));
86
5541
    uv_sem_post(&ready_);
87
88
5541
    uv_run(&loop_, UV_RUN_DEFAULT);
89
5532
    CheckedUvLoopClose(&loop_);
90
5532
  }
91
92
6058
  static void FlushTasks(uv_async_t* flush_tasks) {
93
    DelayedTaskScheduler* scheduler =
94
6058
        ContainerOf(&DelayedTaskScheduler::loop_, flush_tasks->loop);
95
12116
    while (std::unique_ptr<Task> task = scheduler->tasks_.Pop())
96
12116
      task->Run();
97
6058
  }
98
99
  class StopTask : public Task {
100
   public:
101
5532
    explicit StopTask(DelayedTaskScheduler* scheduler): scheduler_(scheduler) {}
102
103
5532
    void Run() override {
104
5532
      std::vector<uv_timer_t*> timers;
105
5844
      for (uv_timer_t* timer : scheduler_->timers_)
106
312
        timers.push_back(timer);
107
5844
      for (uv_timer_t* timer : timers)
108
312
        scheduler_->TakeTimerTask(timer);
109
5532
      uv_close(reinterpret_cast<uv_handle_t*>(&scheduler_->flush_tasks_),
110
5532
               [](uv_handle_t* handle) {});
111
5532
    }
112
113
   private:
114
     DelayedTaskScheduler* scheduler_;
115
  };
116
117
  class ScheduleTask : public Task {
118
   public:
119
526
    ScheduleTask(DelayedTaskScheduler* scheduler,
120
                 std::unique_ptr<Task> task,
121
                 double delay_in_seconds)
122
526
      : scheduler_(scheduler),
123
526
        task_(std::move(task)),
124
526
        delay_in_seconds_(delay_in_seconds) {}
125
126
526
    void Run() override {
127
526
      uint64_t delay_millis = llround(delay_in_seconds_ * 1000);
128
526
      std::unique_ptr<uv_timer_t> timer(new uv_timer_t());
129
526
      CHECK_EQ(0, uv_timer_init(&scheduler_->loop_, timer.get()));
130
526
      timer->data = task_.release();
131
526
      CHECK_EQ(0, uv_timer_start(timer.get(), RunTask, delay_millis, 0));
132
526
      scheduler_->timers_.insert(timer.release());
133
526
    }
134
135
   private:
136
    DelayedTaskScheduler* scheduler_;
137
    std::unique_ptr<Task> task_;
138
    double delay_in_seconds_;
139
  };
140
141
214
  static void RunTask(uv_timer_t* timer) {
142
    DelayedTaskScheduler* scheduler =
143
214
        ContainerOf(&DelayedTaskScheduler::loop_, timer->loop);
144
214
    scheduler->pending_worker_tasks_->Push(scheduler->TakeTimerTask(timer));
145
214
  }
146
147
526
  std::unique_ptr<Task> TakeTimerTask(uv_timer_t* timer) {
148
526
    std::unique_ptr<Task> task(static_cast<Task*>(timer->data));
149
526
    uv_timer_stop(timer);
150
526
    uv_close(reinterpret_cast<uv_handle_t*>(timer), [](uv_handle_t* handle) {
151
526
      delete reinterpret_cast<uv_timer_t*>(handle);
152
526
    });
153
526
    timers_.erase(timer);
154
526
    return task;
155
  }
156
157
  uv_sem_t ready_;
158
  TaskQueue<Task>* pending_worker_tasks_;
159
160
  TaskQueue<Task> tasks_;
161
  uv_loop_t loop_;
162
  uv_async_t flush_tasks_;
163
  std::unordered_set<uv_timer_t*> timers_;
164
};
165
166
5541
WorkerThreadsTaskRunner::WorkerThreadsTaskRunner(int thread_pool_size) {
167
11082
  Mutex platform_workers_mutex;
168
11082
  ConditionVariable platform_workers_ready;
169
170
11082
  Mutex::ScopedLock lock(platform_workers_mutex);
171
5541
  int pending_platform_workers = thread_pool_size;
172
173
5541
  delayed_task_scheduler_ = std::make_unique<DelayedTaskScheduler>(
174
5541
      &pending_worker_tasks_);
175
5541
  threads_.push_back(delayed_task_scheduler_->Start());
176
177
27711
  for (int i = 0; i < thread_pool_size; i++) {
178
    PlatformWorkerData* worker_data = new PlatformWorkerData{
179
22170
      &pending_worker_tasks_, &platform_workers_mutex,
180
      &platform_workers_ready, &pending_platform_workers, i
181
22170
    };
182
22170
    std::unique_ptr<uv_thread_t> t { new uv_thread_t() };
183
22170
    if (uv_thread_create(t.get(), PlatformWorkerThread,
184
22170
                         worker_data) != 0) {
185
      break;
186
    }
187
22170
    threads_.push_back(std::move(t));
188
  }
189
190
  // Wait for platform workers to initialize before continuing with the
191
  // bootstrap.
192
25299
  while (pending_platform_workers > 0) {
193
19758
    platform_workers_ready.Wait(lock);
194
  }
195
5541
}
196
197
103078
void WorkerThreadsTaskRunner::PostTask(std::unique_ptr<Task> task) {
198
103078
  pending_worker_tasks_.Push(std::move(task));
199
103078
}
200
201
526
void WorkerThreadsTaskRunner::PostDelayedTask(std::unique_ptr<Task> task,
202
                                              double delay_in_seconds) {
203
526
  delayed_task_scheduler_->PostDelayedTask(std::move(task), delay_in_seconds);
204
526
}
205
206
14548
void WorkerThreadsTaskRunner::BlockingDrain() {
207
14548
  pending_worker_tasks_.BlockingDrain();
208
14548
}
209
210
5532
void WorkerThreadsTaskRunner::Shutdown() {
211
5532
  pending_worker_tasks_.Stop();
212
5532
  delayed_task_scheduler_->Stop();
213
33198
  for (size_t i = 0; i < threads_.size(); i++) {
214
27666
    CHECK_EQ(0, uv_thread_join(threads_[i].get()));
215
  }
216
5532
}
217
218
62401
int WorkerThreadsTaskRunner::NumberOfWorkerThreads() const {
219
62401
  return threads_.size();
220
}
221
222
6333
PerIsolatePlatformData::PerIsolatePlatformData(
223
6333
    Isolate* isolate, uv_loop_t* loop)
224
6333
  : isolate_(isolate), loop_(loop) {
225
6333
  flush_tasks_ = new uv_async_t();
226
6333
  CHECK_EQ(0, uv_async_init(loop, flush_tasks_, FlushTasks));
227
6333
  flush_tasks_->data = static_cast<void*>(this);
228
6333
  uv_unref(reinterpret_cast<uv_handle_t*>(flush_tasks_));
229
6333
}
230
231
std::shared_ptr<v8::TaskRunner>
232
28780
PerIsolatePlatformData::GetForegroundTaskRunner() {
233
28780
  return shared_from_this();
234
}
235
236
7976
void PerIsolatePlatformData::FlushTasks(uv_async_t* handle) {
237
7976
  auto platform_data = static_cast<PerIsolatePlatformData*>(handle->data);
238
7976
  platform_data->FlushForegroundTasksInternal();
239
7976
}
240
241
void PerIsolatePlatformData::PostIdleTask(std::unique_ptr<v8::IdleTask> task) {
242
  UNREACHABLE();
243
}
244
245
9714
void PerIsolatePlatformData::PostTask(std::unique_ptr<Task> task) {
246
9714
  if (flush_tasks_ == nullptr) {
247
    // V8 may post tasks during Isolate disposal. In that case, the only
248
    // sensible path forward is to discard the task.
249
    return;
250
  }
251
9714
  foreground_tasks_.Push(std::move(task));
252
9714
  uv_async_send(flush_tasks_);
253
}
254
255
5800
void PerIsolatePlatformData::PostDelayedTask(
256
    std::unique_ptr<Task> task, double delay_in_seconds) {
257
5800
  if (flush_tasks_ == nullptr) {
258
    // V8 may post tasks during Isolate disposal. In that case, the only
259
    // sensible path forward is to discard the task.
260
    return;
261
  }
262
11600
  std::unique_ptr<DelayedTask> delayed(new DelayedTask());
263
5800
  delayed->task = std::move(task);
264
5800
  delayed->platform_data = shared_from_this();
265
5800
  delayed->timeout = delay_in_seconds;
266
5800
  foreground_delayed_tasks_.Push(std::move(delayed));
267
5800
  uv_async_send(flush_tasks_);
268
}
269
270
8240
void PerIsolatePlatformData::PostNonNestableTask(std::unique_ptr<Task> task) {
271
8240
  PostTask(std::move(task));
272
8240
}
273
274
void PerIsolatePlatformData::PostNonNestableDelayedTask(
275
    std::unique_ptr<Task> task,
276
    double delay_in_seconds) {
277
  PostDelayedTask(std::move(task), delay_in_seconds);
278
}
279
280
1604
PerIsolatePlatformData::~PerIsolatePlatformData() {
281
1604
  CHECK(!flush_tasks_);
282
}
283
284
739
void PerIsolatePlatformData::AddShutdownCallback(void (*callback)(void*),
285
                                                 void* data) {
286
739
  shutdown_callbacks_.emplace_back(ShutdownCallback { callback, data });
287
739
}
288
289
5672
void PerIsolatePlatformData::Shutdown() {
290
5672
  if (flush_tasks_ == nullptr)
291
    return;
292
293
  // While there should be no V8 tasks in the queues at this point, it is
294
  // possible that Node.js-internal tasks from e.g. the inspector are still
295
  // lying around. We clear these queues and ignore the return value,
296
  // effectively deleting the tasks instead of running them.
297
5672
  foreground_delayed_tasks_.PopAll();
298
5672
  foreground_tasks_.PopAll();
299
5672
  scheduled_delayed_tasks_.clear();
300
301
  // Both destroying the scheduled_delayed_tasks_ lists and closing
302
  // flush_tasks_ handle add tasks to the event loop. We keep a count of all
303
  // non-closed handles, and when that reaches zero, we inform any shutdown
304
  // callbacks that the platform is done as far as this Isolate is concerned.
305
5672
  self_reference_ = shared_from_this();
306
5672
  uv_close(reinterpret_cast<uv_handle_t*>(flush_tasks_),
307
802
           [](uv_handle_t* handle) {
308
    std::unique_ptr<uv_async_t> flush_tasks {
309
1604
        reinterpret_cast<uv_async_t*>(handle) };
310
    PerIsolatePlatformData* platform_data =
311
802
        static_cast<PerIsolatePlatformData*>(flush_tasks->data);
312
802
    platform_data->DecreaseHandleCount();
313
802
    platform_data->self_reference_.reset();
314
802
  });
315
5672
  flush_tasks_ = nullptr;
316
}
317
318
1598
void PerIsolatePlatformData::DecreaseHandleCount() {
319
1598
  CHECK_GE(uv_handle_count_, 1);
320
1598
  if (--uv_handle_count_ == 0) {
321
1541
    for (const auto& callback : shutdown_callbacks_)
322
739
      callback.cb(callback.data);
323
  }
324
1598
}
325
326
5541
NodePlatform::NodePlatform(int thread_pool_size,
327
                           v8::TracingController* tracing_controller,
328
5541
                           v8::PageAllocator* page_allocator) {
329
5541
  if (tracing_controller != nullptr) {
330
5534
    tracing_controller_ = tracing_controller;
331
  } else {
332
7
    tracing_controller_ = new v8::TracingController();
333
  }
334
335
  // V8 will default to its built in allocator if none is provided.
336
5541
  page_allocator_ = page_allocator;
337
338
  // TODO(addaleax): It's a bit icky that we use global state here, but we can't
339
  // really do anything about it unless V8 starts exposing a way to access the
340
  // current v8::Platform instance.
341
5541
  SetTracingController(tracing_controller_);
342
  DCHECK_EQ(GetTracingController(), tracing_controller_);
343
  worker_thread_task_runner_ =
344
5541
      std::make_shared<WorkerThreadsTaskRunner>(thread_pool_size);
345
5541
}
346
347
22128
NodePlatform::~NodePlatform() {
348
11064
  Shutdown();
349
22128
}
350
351
6332
void NodePlatform::RegisterIsolate(Isolate* isolate, uv_loop_t* loop) {
352
12664
  Mutex::ScopedLock lock(per_isolate_mutex_);
353
12664
  auto delegate = std::make_shared<PerIsolatePlatformData>(isolate, loop);
354
6332
  IsolatePlatformDelegate* ptr = delegate.get();
355
  auto insertion = per_isolate_.emplace(
356
    isolate,
357
6332
    std::make_pair(ptr, std::move(delegate)));
358
6332
  CHECK(insertion.second);
359
6332
}
360
361
1
void NodePlatform::RegisterIsolate(Isolate* isolate,
362
                                   IsolatePlatformDelegate* delegate) {
363
2
  Mutex::ScopedLock lock(per_isolate_mutex_);
364
  auto insertion = per_isolate_.emplace(
365
    isolate,
366
1
    std::make_pair(delegate, std::shared_ptr<PerIsolatePlatformData>{}));
367
1
  CHECK(insertion.second);
368
1
}
369
370
5672
void NodePlatform::UnregisterIsolate(Isolate* isolate) {
371
11344
  Mutex::ScopedLock lock(per_isolate_mutex_);
372
5672
  auto existing_it = per_isolate_.find(isolate);
373
5672
  CHECK_NE(existing_it, per_isolate_.end());
374
5672
  auto& existing = existing_it->second;
375
5672
  if (existing.second) {
376
5671
    existing.second->Shutdown();
377
  }
378
5672
  per_isolate_.erase(existing_it);
379
5672
}
380
381
739
void NodePlatform::AddIsolateFinishedCallback(Isolate* isolate,
382
                                              void (*cb)(void*), void* data) {
383
739
  Mutex::ScopedLock lock(per_isolate_mutex_);
384
739
  auto it = per_isolate_.find(isolate);
385
739
  if (it == per_isolate_.end()) {
386
    cb(data);
387
    return;
388
  }
389
739
  CHECK(it->second.second);
390
739
  it->second.second->AddShutdownCallback(cb, data);
391
}
392
393
11059
void NodePlatform::Shutdown() {
394
11059
  if (has_shut_down_) return;
395
5532
  has_shut_down_ = true;
396
5532
  worker_thread_task_runner_->Shutdown();
397
398
  {
399
11064
    Mutex::ScopedLock lock(per_isolate_mutex_);
400
5532
    per_isolate_.clear();
401
  }
402
}
403
404
62401
int NodePlatform::NumberOfWorkerThreads() {
405
62401
  return worker_thread_task_runner_->NumberOfWorkerThreads();
406
}
407
408
9328
void PerIsolatePlatformData::RunForegroundTask(std::unique_ptr<Task> task) {
409
9328
  if (isolate_->IsExecutionTerminating()) return task->Run();
410
9328
  DebugSealHandleScope scope(isolate_);
411
9328
  Environment* env = Environment::GetCurrent(isolate_);
412
9328
  if (env != nullptr) {
413
15916
    v8::HandleScope scope(isolate_);
414
7962
    InternalCallbackScope cb_scope(env, Object::New(isolate_), { 0, 0 },
415
15924
                                   InternalCallbackScope::kNoFlags);
416
7962
    task->Run();
417
  } else {
418
    // The task is moved out of InternalCallbackScope if env is not available.
419
    // This is a required else block, and should not be removed.
420
    // See comment: https://github.com/nodejs/node/pull/34688#pullrequestreview-463867489
421
1366
    task->Run();
422
  }
423
}
424
425
26
void PerIsolatePlatformData::DeleteFromScheduledTasks(DelayedTask* task) {
426
  auto it = std::find_if(scheduled_delayed_tasks_.begin(),
427
                         scheduled_delayed_tasks_.end(),
428
52
                         [task](const DelayedTaskPointer& delayed) -> bool {
429
26
          return delayed.get() == task;
430
26
      });
431
26
  CHECK_NE(it, scheduled_delayed_tasks_.end());
432
26
  scheduled_delayed_tasks_.erase(it);
433
26
}
434
435
26
void PerIsolatePlatformData::RunForegroundTask(uv_timer_t* handle) {
436
26
  DelayedTask* delayed = ContainerOf(&DelayedTask::timer, handle);
437
26
  delayed->platform_data->RunForegroundTask(std::move(delayed->task));
438
26
  delayed->platform_data->DeleteFromScheduledTasks(delayed);
439
26
}
440
441
11046
void NodePlatform::DrainTasks(Isolate* isolate) {
442
11046
  std::shared_ptr<PerIsolatePlatformData> per_isolate = ForNodeIsolate(isolate);
443
11046
  if (!per_isolate) return;
444
445
3503
  do {
446
    // Worker tasks aren't associated with an Isolate.
447
14548
    worker_thread_task_runner_->BlockingDrain();
448
14548
  } while (per_isolate->FlushForegroundTasksInternal());
449
}
450
451
22528
bool PerIsolatePlatformData::FlushForegroundTasksInternal() {
452
22528
  bool did_work = false;
453
454
  while (std::unique_ptr<DelayedTask> delayed =
455
28072
      foreground_delayed_tasks_.Pop()) {
456
5544
    did_work = true;
457
5544
    uint64_t delay_millis = llround(delayed->timeout * 1000);
458
459
5544
    delayed->timer.data = static_cast<void*>(delayed.get());
460
5544
    uv_timer_init(loop_, &delayed->timer);
461
    // Timers may not guarantee queue ordering of events with the same delay if
462
    // the delay is non-zero. This should not be a problem in practice.
463
5544
    uv_timer_start(&delayed->timer, RunForegroundTask, delay_millis, 0);
464
5544
    uv_unref(reinterpret_cast<uv_handle_t*>(&delayed->timer));
465
5544
    uv_handle_count_++;
466
467
16632
    scheduled_delayed_tasks_.emplace_back(delayed.release(),
468
5248
                                          [](DelayedTask* delayed) {
469
5248
      uv_close(reinterpret_cast<uv_handle_t*>(&delayed->timer),
470
796
               [](uv_handle_t* handle) {
471
        std::unique_ptr<DelayedTask> task {
472
1592
            static_cast<DelayedTask*>(handle->data) };
473
796
        task->platform_data->DecreaseHandleCount();
474
796
      });
475
5544
    });
476
5544
  }
477
  // Move all foreground tasks into a separate queue and flush that queue.
478
  // This way tasks that are posted while flushing the queue will be run on the
479
  // next call of FlushForegroundTasksInternal.
480
22528
  std::queue<std::unique_ptr<Task>> tasks = foreground_tasks_.PopAll();
481
31822
  while (!tasks.empty()) {
482
9302
    std::unique_ptr<Task> task = std::move(tasks.front());
483
9302
    tasks.pop();
484
9302
    did_work = true;
485
9302
    RunForegroundTask(std::move(task));
486
  }
487
22520
  return did_work;
488
}
489
490
103078
void NodePlatform::CallOnWorkerThread(std::unique_ptr<Task> task) {
491
103078
  worker_thread_task_runner_->PostTask(std::move(task));
492
103078
}
493
494
526
void NodePlatform::CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
495
                                             double delay_in_seconds) {
496
526
  worker_thread_task_runner_->PostDelayedTask(std::move(task),
497
                                              delay_in_seconds);
498
526
}
499
500
501
28780
IsolatePlatformDelegate* NodePlatform::ForIsolate(Isolate* isolate) {
502
57560
  Mutex::ScopedLock lock(per_isolate_mutex_);
503
28780
  auto data = per_isolate_[isolate];
504
28780
  CHECK_NOT_NULL(data.first);
505
28780
  return data.first;
506
}
507
508
std::shared_ptr<PerIsolatePlatformData>
509
11050
NodePlatform::ForNodeIsolate(Isolate* isolate) {
510
22100
  Mutex::ScopedLock lock(per_isolate_mutex_);
511
22100
  auto data = per_isolate_[isolate];
512
11050
  CHECK_NOT_NULL(data.first);
513
11050
  return data.second;
514
}
515
516
4
bool NodePlatform::FlushForegroundTasks(Isolate* isolate) {
517
8
  std::shared_ptr<PerIsolatePlatformData> per_isolate = ForNodeIsolate(isolate);
518
4
  if (!per_isolate) return false;
519
4
  return per_isolate->FlushForegroundTasksInternal();
520
}
521
522
28536
std::unique_ptr<v8::JobHandle> NodePlatform::PostJob(v8::TaskPriority priority,
523
                                       std::unique_ptr<v8::JobTask> job_task) {
524
  return v8::platform::NewDefaultJobHandle(
525
28536
      this, priority, std::move(job_task), NumberOfWorkerThreads());
526
}
527
528
bool NodePlatform::IdleTasksEnabled(Isolate* isolate) {
529
  return ForIsolate(isolate)->IdleTasksEnabled();
530
}
531
532
std::shared_ptr<v8::TaskRunner>
533
28780
NodePlatform::GetForegroundTaskRunner(Isolate* isolate) {
534
28780
  return ForIsolate(isolate)->GetForegroundTaskRunner();
535
}
536
537
223629
double NodePlatform::MonotonicallyIncreasingTime() {
538
  // Convert nanos to seconds.
539
223629
  return uv_hrtime() / 1e9;
540
}
541
542
16468788
double NodePlatform::CurrentClockTimeMillis() {
543
16468788
  return SystemClockTimeMillis();
544
}
545
546
362336
v8::TracingController* NodePlatform::GetTracingController() {
547
362336
  CHECK_NOT_NULL(tracing_controller_);
548
362336
  return tracing_controller_;
549
}
550
551
5541
Platform::StackTracePrinter NodePlatform::GetStackTracePrinter() {
552
  return []() {
553
    fprintf(stderr, "\n");
554
    DumpBacktrace(stderr);
555
    fflush(stderr);
556
5541
  };
557
}
558
559
5542
v8::PageAllocator* NodePlatform::GetPageAllocator() {
560
5542
  return page_allocator_;
561
}
562
563
template <class T>
564
47496
TaskQueue<T>::TaskQueue()
565
    : lock_(), tasks_available_(), tasks_drained_(),
566
47496
      outstanding_tasks_(0), stopped_(false), task_queue_() { }
567
568
template <class T>
569
249728
void TaskQueue<T>::Push(std::unique_ptr<T> task) {
570
499456
  Mutex::ScopedLock scoped_lock(lock_);
571
249728
  outstanding_tasks_++;
572
249728
  task_queue_.push(std::move(task));
573
249728
  tasks_available_.Signal(scoped_lock);
574
249728
}
575
576
template <class T>
577
80376
std::unique_ptr<T> TaskQueue<T>::Pop() {
578
160752
  Mutex::ScopedLock scoped_lock(lock_);
579
80376
  if (task_queue_.empty()) {
580
57172
    return std::unique_ptr<T>(nullptr);
581
  }
582
46408
  std::unique_ptr<T> result = std::move(task_queue_.front());
583
23204
  task_queue_.pop();
584
23204
  return result;
585
}
586
587
template <class T>
588
125459
std::unique_ptr<T> TaskQueue<T>::BlockingPop() {
589
250882
  Mutex::ScopedLock scoped_lock(lock_);
590

242635
  while (task_queue_.empty() && !stopped_) {
591
117212
    tasks_available_.Wait(scoped_lock);
592
  }
593
125423
  if (stopped_) {
594
22134
    return std::unique_ptr<T>(nullptr);
595
  }
596
206578
  std::unique_ptr<T> result = std::move(task_queue_.front());
597
103289
  task_queue_.pop();
598
103289
  return result;
599
}
600
601
template <class T>
602
103289
void TaskQueue<T>::NotifyOfCompletion() {
603
206578
  Mutex::ScopedLock scoped_lock(lock_);
604
103289
  if (--outstanding_tasks_ == 0) {
605
46522
    tasks_drained_.Broadcast(scoped_lock);
606
  }
607
103289
}
608
609
template <class T>
610
14548
void TaskQueue<T>::BlockingDrain() {
611
29096
  Mutex::ScopedLock scoped_lock(lock_);
612
15810
  while (outstanding_tasks_ > 0) {
613
1262
    tasks_drained_.Wait(scoped_lock);
614
  }
615
14548
}
616
617
template <class T>
618
5532
void TaskQueue<T>::Stop() {
619
11064
  Mutex::ScopedLock scoped_lock(lock_);
620
5532
  stopped_ = true;
621
5532
  tasks_available_.Broadcast(scoped_lock);
622
5532
}
623
624
template <class T>
625
33872
std::queue<std::unique_ptr<T>> TaskQueue<T>::PopAll() {
626
67744
  Mutex::ScopedLock scoped_lock(lock_);
627
33872
  std::queue<std::unique_ptr<T>> result;
628
33872
  result.swap(task_queue_);
629
33872
  return result;
630
}
631
632
}  // namespace node