GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_platform.cc Lines: 317 328 96.6 %
Date: 2019-02-26 22:23:30 Branches: 76 102 74.5 %

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

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

8474
    TRACE_EVENT_METADATA1("__metadata", "thread_name", "name",
83
                          "WorkerThreadsTaskRunner::DelayedTaskScheduler");
84
4237
    loop_.data = this;
85
4237
    CHECK_EQ(0, uv_loop_init(&loop_));
86
4237
    flush_tasks_.data = this;
87
4237
    CHECK_EQ(0, uv_async_init(&loop_, &flush_tasks_, FlushTasks));
88
4237
    uv_sem_post(&ready_);
89
90
4237
    uv_run(&loop_, UV_RUN_DEFAULT);
91
4232
    CheckedUvLoopClose(&loop_);
92
4232
  }
93
94
4233
  static void FlushTasks(uv_async_t* flush_tasks) {
95
    DelayedTaskScheduler* scheduler =
96
4233
        ContainerOf(&DelayedTaskScheduler::loop_, flush_tasks->loop);
97
8466
    while (std::unique_ptr<Task> task = scheduler->tasks_.Pop())
98
4233
      task->Run();
99
4233
  }
100
101
8464
  class StopTask : public Task {
102
   public:
103
4232
    explicit StopTask(DelayedTaskScheduler* scheduler): scheduler_(scheduler) {}
104
105
4232
    void Run() override {
106
4232
      std::vector<uv_timer_t*> timers;
107
4232
      for (uv_timer_t* timer : scheduler_->timers_)
108
        timers.push_back(timer);
109
4232
      for (uv_timer_t* timer : timers)
110
        scheduler_->TakeTimerTask(timer);
111
      uv_close(reinterpret_cast<uv_handle_t*>(&scheduler_->flush_tasks_),
112
16928
               [](uv_handle_t* handle) {});
113
4232
    }
114
115
   private:
116
     DelayedTaskScheduler* scheduler_;
117
  };
118
119
2
  class ScheduleTask : public Task {
120
   public:
121
1
    ScheduleTask(DelayedTaskScheduler* scheduler,
122
                 std::unique_ptr<Task> task,
123
                 double delay_in_seconds)
124
      : scheduler_(scheduler),
125
1
        task_(std::move(task)),
126
2
        delay_in_seconds_(delay_in_seconds) {}
127
128
1
    void Run() override {
129
      uint64_t delay_millis =
130
1
          static_cast<uint64_t>(delay_in_seconds_ + 0.5) * 1000;
131
1
      std::unique_ptr<uv_timer_t> timer(new uv_timer_t());
132
1
      CHECK_EQ(0, uv_timer_init(&scheduler_->loop_, timer.get()));
133
1
      timer->data = task_.release();
134
1
      CHECK_EQ(0, uv_timer_start(timer.get(), RunTask, delay_millis, 0));
135
1
      scheduler_->timers_.insert(timer.release());
136
1
    }
137
138
   private:
139
    DelayedTaskScheduler* scheduler_;
140
    std::unique_ptr<Task> task_;
141
    double delay_in_seconds_;
142
  };
143
144
1
  static void RunTask(uv_timer_t* timer) {
145
    DelayedTaskScheduler* scheduler =
146
1
        ContainerOf(&DelayedTaskScheduler::loop_, timer->loop);
147
1
    scheduler->pending_worker_tasks_->Push(scheduler->TakeTimerTask(timer));
148
1
  }
149
150
1
  std::unique_ptr<Task> TakeTimerTask(uv_timer_t* timer) {
151
1
    std::unique_ptr<Task> task(static_cast<Task*>(timer->data));
152
1
    uv_timer_stop(timer);
153
3
    uv_close(reinterpret_cast<uv_handle_t*>(timer), [](uv_handle_t* handle) {
154
1
      delete reinterpret_cast<uv_timer_t*>(handle);
155
4
    });
156
1
    timers_.erase(timer);
157
1
    return task;
158
  }
159
160
  uv_sem_t ready_;
161
  TaskQueue<v8::Task>* pending_worker_tasks_;
162
163
  TaskQueue<v8::Task> tasks_;
164
  uv_loop_t loop_;
165
  uv_async_t flush_tasks_;
166
  std::unordered_set<uv_timer_t*> timers_;
167
};
168
169
4237
WorkerThreadsTaskRunner::WorkerThreadsTaskRunner(int thread_pool_size) {
170
4237
  Mutex platform_workers_mutex;
171
8474
  ConditionVariable platform_workers_ready;
172
173
8474
  Mutex::ScopedLock lock(platform_workers_mutex);
174
4237
  int pending_platform_workers = thread_pool_size;
175
176
  delayed_task_scheduler_.reset(
177
4237
      new DelayedTaskScheduler(&pending_worker_tasks_));
178
4237
  threads_.push_back(delayed_task_scheduler_->Start());
179
180
21191
  for (int i = 0; i < thread_pool_size; i++) {
181
    PlatformWorkerData* worker_data = new PlatformWorkerData{
182
      &pending_worker_tasks_, &platform_workers_mutex,
183
      &platform_workers_ready, &pending_platform_workers, i
184
16954
    };
185
16954
    std::unique_ptr<uv_thread_t> t { new uv_thread_t() };
186
16954
    if (uv_thread_create(t.get(), PlatformWorkerThread,
187
16954
                         worker_data) != 0) {
188
      break;
189
    }
190
16954
    threads_.push_back(std::move(t));
191
16954
  }
192
193
  // Wait for platform workers to initialize before continuing with the
194
  // bootstrap.
195
22337
  while (pending_platform_workers > 0) {
196
13863
    platform_workers_ready.Wait(lock);
197
4237
  }
198
4237
}
199
200
135344
void WorkerThreadsTaskRunner::PostTask(std::unique_ptr<Task> task) {
201
135344
  pending_worker_tasks_.Push(std::move(task));
202
135344
}
203
204
1
void WorkerThreadsTaskRunner::PostDelayedTask(std::unique_ptr<v8::Task> task,
205
                                              double delay_in_seconds) {
206
1
  delayed_task_scheduler_->PostDelayedTask(std::move(task), delay_in_seconds);
207
1
}
208
209
13985
void WorkerThreadsTaskRunner::BlockingDrain() {
210
13985
  pending_worker_tasks_.BlockingDrain();
211
13985
}
212
213
4232
void WorkerThreadsTaskRunner::Shutdown() {
214
4232
  pending_worker_tasks_.Stop();
215
4232
  delayed_task_scheduler_->Stop();
216
25398
  for (size_t i = 0; i < threads_.size(); i++) {
217
21166
    CHECK_EQ(0, uv_thread_join(threads_[i].get()));
218
  }
219
4232
}
220
221
4634
int WorkerThreadsTaskRunner::NumberOfWorkerThreads() const {
222
4634
  return threads_.size();
223
}
224
225
4407
PerIsolatePlatformData::PerIsolatePlatformData(
226
    v8::Isolate* isolate, uv_loop_t* loop)
227
4407
  : loop_(loop) {
228
4407
  flush_tasks_ = new uv_async_t();
229
4407
  CHECK_EQ(0, uv_async_init(loop, flush_tasks_, FlushTasks));
230
4407
  flush_tasks_->data = static_cast<void*>(this);
231
4407
  uv_unref(reinterpret_cast<uv_handle_t*>(flush_tasks_));
232
4407
}
233
234
5330
void PerIsolatePlatformData::FlushTasks(uv_async_t* handle) {
235
5330
  auto platform_data = static_cast<PerIsolatePlatformData*>(handle->data);
236
5330
  platform_data->FlushForegroundTasksInternal();
237
5329
}
238
239
void PerIsolatePlatformData::PostIdleTask(std::unique_ptr<v8::IdleTask> task) {
240
  UNREACHABLE();
241
}
242
243
10756
void PerIsolatePlatformData::PostTask(std::unique_ptr<Task> task) {
244
10756
  CHECK_NOT_NULL(flush_tasks_);
245
10756
  foreground_tasks_.Push(std::move(task));
246
10756
  uv_async_send(flush_tasks_);
247
10756
}
248
249
135
void PerIsolatePlatformData::PostDelayedTask(
250
    std::unique_ptr<Task> task, double delay_in_seconds) {
251
135
  CHECK_NOT_NULL(flush_tasks_);
252
135
  std::unique_ptr<DelayedTask> delayed(new DelayedTask());
253
135
  delayed->task = std::move(task);
254
135
  delayed->platform_data = shared_from_this();
255
135
  delayed->timeout = delay_in_seconds;
256
135
  foreground_delayed_tasks_.Push(std::move(delayed));
257
135
  uv_async_send(flush_tasks_);
258
135
}
259
260
7818
PerIsolatePlatformData::~PerIsolatePlatformData() {
261
3909
  Shutdown();
262
3909
}
263
264
7945
void PerIsolatePlatformData::Shutdown() {
265
7945
  if (flush_tasks_ == nullptr)
266
11854
    return;
267
268
4036
  CHECK_NULL(foreground_delayed_tasks_.Pop());
269
4036
  CHECK_NULL(foreground_tasks_.Pop());
270
4036
  CancelPendingDelayedTasks();
271
272
  uv_close(reinterpret_cast<uv_handle_t*>(flush_tasks_),
273
4376
           [](uv_handle_t* handle) {
274
170
    delete reinterpret_cast<uv_async_t*>(handle);
275
8412
  });
276
4036
  flush_tasks_ = nullptr;
277
}
278
279
4404
void PerIsolatePlatformData::ref() {
280
4404
  ref_count_++;
281
4404
}
282
283
8072
int PerIsolatePlatformData::unref() {
284
8072
  return --ref_count_;
285
}
286
287
4237
NodePlatform::NodePlatform(int thread_pool_size,
288
4237
                           TracingController* tracing_controller) {
289
4237
  if (tracing_controller) {
290
4237
    tracing_controller_ = tracing_controller;
291
  } else {
292
    tracing_controller_ = new TracingController();
293
  }
294
8474
  worker_thread_task_runner_ =
295
4237
      std::make_shared<WorkerThreadsTaskRunner>(thread_pool_size);
296
4237
}
297
298
8811
void NodePlatform::RegisterIsolate(Isolate* isolate, uv_loop_t* loop) {
299
8811
  Mutex::ScopedLock lock(per_isolate_mutex_);
300
17622
  std::shared_ptr<PerIsolatePlatformData> existing = per_isolate_[isolate];
301
8811
  if (existing) {
302
4404
    CHECK_EQ(loop, existing->event_loop());
303
4404
    existing->ref();
304
  } else {
305
8814
    per_isolate_[isolate] =
306
4407
        std::make_shared<PerIsolatePlatformData>(isolate, loop);
307
8811
  }
308
8811
}
309
310
8072
void NodePlatform::UnregisterIsolate(Isolate* isolate) {
311
8072
  Mutex::ScopedLock lock(per_isolate_mutex_);
312
16144
  std::shared_ptr<PerIsolatePlatformData> existing = per_isolate_[isolate];
313
8072
  CHECK(existing);
314
8072
  if (existing->unref() == 0) {
315
4036
    existing->Shutdown();
316
4036
    per_isolate_.erase(isolate);
317
8072
  }
318
8072
}
319
320
4232
void NodePlatform::Shutdown() {
321
4232
  worker_thread_task_runner_->Shutdown();
322
323
  {
324
4232
    Mutex::ScopedLock lock(per_isolate_mutex_);
325
4232
    per_isolate_.clear();
326
  }
327
4232
}
328
329
4634
int NodePlatform::NumberOfWorkerThreads() {
330
4634
  return worker_thread_task_runner_->NumberOfWorkerThreads();
331
}
332
333
10488
void PerIsolatePlatformData::RunForegroundTask(std::unique_ptr<Task> task) {
334
10488
  Isolate* isolate = Isolate::GetCurrent();
335
10488
  HandleScope scope(isolate);
336
10495
  Environment* env = Environment::GetCurrent(isolate);
337
  InternalCallbackScope cb_scope(env, Local<Object>(), { 0, 0 },
338
31485
                                 InternalCallbackScope::kAllowEmptyResource);
339
20987
  task->Run();
340
10492
}
341
342
2
void PerIsolatePlatformData::DeleteFromScheduledTasks(DelayedTask* task) {
343
  auto it = std::find_if(scheduled_delayed_tasks_.begin(),
344
                         scheduled_delayed_tasks_.end(),
345
2
                         [task](const DelayedTaskPointer& delayed) -> bool {
346
2
          return delayed.get() == task;
347
2
      });
348
2
  CHECK_NE(it, scheduled_delayed_tasks_.end());
349
2
  scheduled_delayed_tasks_.erase(it);
350
2
}
351
352
2
void PerIsolatePlatformData::RunForegroundTask(uv_timer_t* handle) {
353
2
  DelayedTask* delayed = static_cast<DelayedTask*>(handle->data);
354
2
  RunForegroundTask(std::move(delayed->task));
355
2
  delayed->platform_data->DeleteFromScheduledTasks(delayed);
356
2
}
357
358
8071
void PerIsolatePlatformData::CancelPendingDelayedTasks() {
359
8071
  scheduled_delayed_tasks_.clear();
360
8071
}
361
362
8056
void NodePlatform::DrainTasks(Isolate* isolate) {
363
8056
  std::shared_ptr<PerIsolatePlatformData> per_isolate = ForIsolate(isolate);
364
365
13985
  do {
366
    // Worker tasks aren't associated with an Isolate.
367
13985
    worker_thread_task_runner_->BlockingDrain();
368
22039
  } while (per_isolate->FlushForegroundTasksInternal());
369
8054
}
370
371
175377
bool PerIsolatePlatformData::FlushForegroundTasksInternal() {
372
175377
  bool did_work = false;
373
374
  while (std::unique_ptr<DelayedTask> delayed =
375
175511
      foreground_delayed_tasks_.Pop()) {
376
134
    did_work = true;
377
    uint64_t delay_millis =
378
134
        static_cast<uint64_t>(delayed->timeout + 0.5) * 1000;
379
134
    delayed->timer.data = static_cast<void*>(delayed.get());
380
134
    uv_timer_init(loop_, &delayed->timer);
381
    // Timers may not guarantee queue ordering of events with the same delay if
382
    // the delay is non-zero. This should not be a problem in practice.
383
134
    uv_timer_start(&delayed->timer, RunForegroundTask, delay_millis, 0);
384
134
    uv_unref(reinterpret_cast<uv_handle_t*>(&delayed->timer));
385
386
134
    scheduled_delayed_tasks_.emplace_back(delayed.release(),
387
130
                                          [](DelayedTask* delayed) {
388
      uv_close(reinterpret_cast<uv_handle_t*>(&delayed->timer),
389
136
               [](uv_handle_t* handle) {
390
3
        delete static_cast<DelayedTask*>(handle->data);
391
266
      });
392
264
    });
393
134
  }
394
  // Move all foreground tasks into a separate queue and flush that queue.
395
  // This way tasks that are posted while flushing the queue will be run on the
396
  // next call of FlushForegroundTasksInternal.
397
175377
  std::queue<std::unique_ptr<Task>> tasks = foreground_tasks_.PopAll();
398
361228
  while (!tasks.empty()) {
399
10486
    std::unique_ptr<Task> task = std::move(tasks.front());
400
10493
    tasks.pop();
401
10493
    did_work = true;
402
10493
    RunForegroundTask(std::move(task));
403
10490
  }
404
175507
  return did_work;
405
}
406
407
135344
void NodePlatform::CallOnWorkerThread(std::unique_ptr<v8::Task> task) {
408
135344
  worker_thread_task_runner_->PostTask(std::move(task));
409
135344
}
410
411
1
void NodePlatform::CallDelayedOnWorkerThread(std::unique_ptr<v8::Task> task,
412
                                             double delay_in_seconds) {
413
1
  worker_thread_task_runner_->PostDelayedTask(std::move(task),
414
1
                                              delay_in_seconds);
415
1
}
416
417
418
std::shared_ptr<PerIsolatePlatformData>
419
187751
NodePlatform::ForIsolate(Isolate* isolate) {
420
187751
  Mutex::ScopedLock lock(per_isolate_mutex_);
421
187751
  std::shared_ptr<PerIsolatePlatformData> data = per_isolate_[isolate];
422
187751
  CHECK(data);
423
187751
  return data;
424
}
425
426
void NodePlatform::CallOnForegroundThread(Isolate* isolate, Task* task) {
427
  ForIsolate(isolate)->PostTask(std::unique_ptr<Task>(task));
428
}
429
430
void NodePlatform::CallDelayedOnForegroundThread(Isolate* isolate,
431
                                                 Task* task,
432
                                                 double delay_in_seconds) {
433
  ForIsolate(isolate)->PostDelayedTask(
434
    std::unique_ptr<Task>(task), delay_in_seconds);
435
}
436
437
156062
bool NodePlatform::FlushForegroundTasks(v8::Isolate* isolate) {
438
156062
  return ForIsolate(isolate)->FlushForegroundTasksInternal();
439
}
440
441
4035
void NodePlatform::CancelPendingDelayedTasks(v8::Isolate* isolate) {
442
4035
  ForIsolate(isolate)->CancelPendingDelayedTasks();
443
4035
}
444
445
30878
bool NodePlatform::IdleTasksEnabled(Isolate* isolate) { return false; }
446
447
std::shared_ptr<v8::TaskRunner>
448
19598
NodePlatform::GetForegroundTaskRunner(Isolate* isolate) {
449
19598
  return ForIsolate(isolate);
450
}
451
452
1222297
double NodePlatform::MonotonicallyIncreasingTime() {
453
  // Convert nanos to seconds.
454
1222297
  return uv_hrtime() / 1e9;
455
}
456
457
108748408
double NodePlatform::CurrentClockTimeMillis() {
458
108748408
  return SystemClockTimeMillis();
459
}
460
461
214811
TracingController* NodePlatform::GetTracingController() {
462
214811
  CHECK_NOT_NULL(tracing_controller_);
463
214811
  return tracing_controller_;
464
}
465
466
template <class T>
467
17288
TaskQueue<T>::TaskQueue()
468
    : lock_(), tasks_available_(), tasks_drained_(),
469
17288
      outstanding_tasks_(0), stopped_(false), task_queue_() { }
470
471
template <class T>
472
150469
void TaskQueue<T>::Push(std::unique_ptr<T> task) {
473
150469
  Mutex::ScopedLock scoped_lock(lock_);
474
150469
  outstanding_tasks_++;
475
150469
  task_queue_.push(std::move(task));
476
150469
  tasks_available_.Signal(scoped_lock);
477
150469
}
478
479
template <class T>
480
192049
std::unique_ptr<T> TaskQueue<T>::Pop() {
481
192049
  Mutex::ScopedLock scoped_lock(lock_);
482

192049
  if (task_queue_.empty()) {
483
187682
    return std::unique_ptr<T>(nullptr);
484
  }
485
8734
  std::unique_ptr<T> result = std::move(task_queue_.front());
486
4367
  task_queue_.pop();
487
196416
  return result;
488
}
489
490
template <class T>
491
152273
std::unique_ptr<T> TaskQueue<T>::BlockingPop() {
492
152273
  Mutex::ScopedLock scoped_lock(lock_);
493

441951
  while (task_queue_.empty() && !stopped_) {
494
137373
    tasks_available_.Wait(scoped_lock);
495
  }
496
152279
  if (stopped_) {
497
16934
    return std::unique_ptr<T>(nullptr);
498
  }
499
270690
  std::unique_ptr<T> result = std::move(task_queue_.front());
500
135345
  task_queue_.pop();
501
287624
  return result;
502
}
503
504
template <class T>
505
135157
void TaskQueue<T>::NotifyOfCompletion() {
506
135157
  Mutex::ScopedLock scoped_lock(lock_);
507
135345
  if (--outstanding_tasks_ == 0) {
508
88653
    tasks_drained_.Broadcast(scoped_lock);
509
135345
  }
510
135313
}
511
512
template <class T>
513
13985
void TaskQueue<T>::BlockingDrain() {
514
13985
  Mutex::ScopedLock scoped_lock(lock_);
515
28056
  while (outstanding_tasks_ > 0) {
516
86
    tasks_drained_.Wait(scoped_lock);
517
13985
  }
518
13985
}
519
520
template <class T>
521
4232
void TaskQueue<T>::Stop() {
522
4232
  Mutex::ScopedLock scoped_lock(lock_);
523
4232
  stopped_ = true;
524
4232
  tasks_available_.Broadcast(scoped_lock);
525
4232
}
526
527
template <class T>
528
175377
std::queue<std::unique_ptr<T>> TaskQueue<T>::PopAll() {
529
175377
  Mutex::ScopedLock scoped_lock(lock_);
530
175377
  std::queue<std::unique_ptr<T>> result;
531
175371
  result.swap(task_queue_);
532
175374
  return result;
533
}
534
535
}  // namespace node