Upload Kmake

This commit is contained in:
Gorochu
2026-05-26 23:36:42 -07:00
parent ba051b2f74
commit 555ec72358
41615 changed files with 13344630 additions and 1 deletions

View File

@ -0,0 +1,6 @@
specific_include_rules = {
"tracing-unittest\.cc": [
"+perfetto/tracing.h",
"+protos/perfetto"
],
}

View File

@ -0,0 +1,299 @@
// Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/libplatform/default-job.h"
#include "src/base/platform/condition-variable.h"
#include "src/base/platform/platform.h"
#include "src/libplatform/default-platform.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace v8 {
namespace platform {
namespace default_job_unittest {
// Verify that Cancel() on a job stops running the worker task and causes
// current workers to yield.
TEST(DefaultJobTest, CancelJob) {
static constexpr size_t kTooManyTasks = 1000;
static constexpr size_t kMaxTask = 4;
DefaultPlatform platform(kMaxTask);
// This Job notifies |threads_running| once started and loops until
// ShouldYield() returns true, and then returns.
class JobTest : public JobTask {
public:
~JobTest() override = default;
void Run(JobDelegate* delegate) override {
{
base::MutexGuard guard(&mutex);
worker_count++;
}
threads_running.NotifyOne();
while (!delegate->ShouldYield()) {
}
}
size_t GetMaxConcurrency(size_t /* worker_count */) const override {
return max_concurrency.load(std::memory_order_relaxed);
}
base::Mutex mutex;
base::ConditionVariable threads_running;
size_t worker_count = 0;
std::atomic_size_t max_concurrency{kTooManyTasks};
};
auto job = std::make_unique<JobTest>();
JobTest* job_raw = job.get();
auto state = std::make_shared<DefaultJobState>(
&platform, std::move(job), TaskPriority::kUserVisible, kMaxTask);
state->NotifyConcurrencyIncrease();
{
base::MutexGuard guard(&job_raw->mutex);
while (job_raw->worker_count < kMaxTask) {
job_raw->threads_running.Wait(&job_raw->mutex);
}
EXPECT_EQ(kMaxTask, job_raw->worker_count);
}
state->CancelAndWait();
// Workers should return and this test should not hang.
}
// Verify that Join() on a job contributes to max concurrency and waits for all
// workers to return.
TEST(DefaultJobTest, JoinJobContributes) {
static constexpr size_t kMaxTask = 4;
DefaultPlatform platform(kMaxTask);
// This Job notifies |threads_running| once started and blocks on a barrier
// until kMaxTask + 1 threads reach that point, and then returns.
class JobTest : public JobTask {
public:
~JobTest() override = default;
void Run(JobDelegate* delegate) override {
base::MutexGuard guard(&mutex);
worker_count++;
threads_running.NotifyAll();
while (worker_count < kMaxTask + 1) threads_running.Wait(&mutex);
--max_concurrency;
}
size_t GetMaxConcurrency(size_t /* worker_count */) const override {
return max_concurrency.load(std::memory_order_relaxed);
}
base::Mutex mutex;
base::ConditionVariable threads_running;
size_t worker_count = 0;
std::atomic_size_t max_concurrency{kMaxTask + 1};
};
auto job = std::make_unique<JobTest>();
JobTest* job_raw = job.get();
auto state = std::make_shared<DefaultJobState>(
&platform, std::move(job), TaskPriority::kUserVisible, kMaxTask);
state->NotifyConcurrencyIncrease();
// The main thread contributing is necessary for |worker_count| to reach
// kMaxTask + 1 thus, Join() should not hang.
state->Join();
EXPECT_EQ(0U, job_raw->max_concurrency);
}
// Verify that Join() on a job that uses |worker_count| eventually converges
// and doesn't hang.
TEST(DefaultJobTest, WorkerCount) {
static constexpr size_t kMaxTask = 4;
DefaultPlatform platform(kMaxTask);
// This Job spawns a workers until the first worker task completes.
class JobTest : public JobTask {
public:
~JobTest() override = default;
void Run(JobDelegate* delegate) override {
base::MutexGuard guard(&mutex);
if (max_concurrency > 0) --max_concurrency;
}
size_t GetMaxConcurrency(size_t worker_count) const override {
return worker_count + max_concurrency.load(std::memory_order_relaxed);
}
base::Mutex mutex;
std::atomic_size_t max_concurrency{kMaxTask};
};
auto job = std::make_unique<JobTest>();
JobTest* job_raw = job.get();
auto state = std::make_shared<DefaultJobState>(
&platform, std::move(job), TaskPriority::kUserVisible, kMaxTask);
state->NotifyConcurrencyIncrease();
// GetMaxConcurrency() eventually returns 0 thus, Join() should not hang.
state->Join();
EXPECT_EQ(0U, job_raw->max_concurrency);
}
// Verify that calling NotifyConcurrencyIncrease() (re-)schedules tasks with the
// intended concurrency.
TEST(DefaultJobTest, JobNotifyConcurrencyIncrease) {
static constexpr size_t kMaxTask = 4;
DefaultPlatform platform(kMaxTask);
// This Job notifies |threads_running| once started and blocks on a barrier
// until kMaxTask threads reach that point, and then returns.
class JobTest : public JobTask {
public:
~JobTest() override = default;
void Run(JobDelegate* delegate) override {
base::MutexGuard guard(&mutex);
worker_count++;
threads_running.NotifyAll();
// Wait synchronously until |kMaxTask| workers reach this point.
while (worker_count < kMaxTask) threads_running.Wait(&mutex);
--max_concurrency;
}
size_t GetMaxConcurrency(size_t /* worker_count */) const override {
return max_concurrency.load(std::memory_order_relaxed);
}
base::Mutex mutex;
base::ConditionVariable threads_running;
bool continue_flag = false;
size_t worker_count = 0;
std::atomic_size_t max_concurrency{kMaxTask / 2};
};
auto job = std::make_unique<JobTest>();
JobTest* job_raw = job.get();
auto state = std::make_shared<DefaultJobState>(
&platform, std::move(job), TaskPriority::kUserVisible, kMaxTask);
state->NotifyConcurrencyIncrease();
{
base::MutexGuard guard(&job_raw->mutex);
while (job_raw->worker_count < kMaxTask / 2)
job_raw->threads_running.Wait(&job_raw->mutex);
EXPECT_EQ(kMaxTask / 2, job_raw->worker_count);
job_raw->max_concurrency = kMaxTask;
}
state->NotifyConcurrencyIncrease();
// Workers should reach |continue_flag| and eventually return thus, Join()
// should not hang.
state->Join();
EXPECT_EQ(0U, job_raw->max_concurrency);
}
// Verify that Join() doesn't contribute if the Job is already finished.
TEST(DefaultJobTest, FinishBeforeJoin) {
static constexpr size_t kMaxTask = 4;
DefaultPlatform platform(kMaxTask);
// This Job notifies |threads_running| once started and returns.
class JobTest : public JobTask {
public:
~JobTest() override = default;
void Run(JobDelegate* delegate) override {
base::MutexGuard guard(&mutex);
worker_count++;
// Assert that main thread doesn't contribute in this test.
EXPECT_NE(main_thread_id, base::OS::GetCurrentThreadId());
worker_ran.NotifyAll();
--max_concurrency;
}
size_t GetMaxConcurrency(size_t /* worker_count */) const override {
return max_concurrency.load(std::memory_order_relaxed);
}
const int main_thread_id = base::OS::GetCurrentThreadId();
base::Mutex mutex;
base::ConditionVariable worker_ran;
size_t worker_count = 0;
std::atomic_size_t max_concurrency{kMaxTask * 5};
};
auto job = std::make_unique<JobTest>();
JobTest* job_raw = job.get();
auto state = std::make_shared<DefaultJobState>(
&platform, std::move(job), TaskPriority::kUserVisible, kMaxTask);
state->NotifyConcurrencyIncrease();
{
base::MutexGuard guard(&job_raw->mutex);
while (job_raw->worker_count < kMaxTask * 5)
job_raw->worker_ran.Wait(&job_raw->mutex);
EXPECT_EQ(kMaxTask * 5, job_raw->worker_count);
}
state->Join();
EXPECT_EQ(0U, job_raw->max_concurrency);
}
// Verify that destroying a DefaultJobHandle triggers a DCHECK if neither Join()
// or Cancel() was called.
TEST(DefaultJobTest, LeakHandle) {
class JobTest : public JobTask {
public:
~JobTest() override = default;
void Run(JobDelegate* delegate) override {}
size_t GetMaxConcurrency(size_t /* worker_count */) const override {
return 0;
}
};
DefaultPlatform platform(0);
auto job = std::make_unique<JobTest>();
auto state = std::make_shared<DefaultJobState>(&platform, std::move(job),
TaskPriority::kUserVisible, 1);
auto handle = std::make_unique<DefaultJobHandle>(std::move(state));
#ifdef DEBUG
EXPECT_DEATH_IF_SUPPORTED({ handle.reset(); }, "");
#endif // DEBUG
handle->Join();
}
TEST(DefaultJobTest, AcquireTaskId) {
class JobTest : public JobTask {
public:
~JobTest() override = default;
void Run(JobDelegate* delegate) override {}
size_t GetMaxConcurrency(size_t /* worker_count */) const override {
return 0;
}
};
DefaultPlatform platform(0);
auto job = std::make_unique<JobTest>();
auto state = std::make_shared<DefaultJobState>(&platform, std::move(job),
TaskPriority::kUserVisible, 1);
EXPECT_EQ(0U, state->AcquireTaskId());
EXPECT_EQ(1U, state->AcquireTaskId());
EXPECT_EQ(2U, state->AcquireTaskId());
EXPECT_EQ(3U, state->AcquireTaskId());
EXPECT_EQ(4U, state->AcquireTaskId());
state->ReleaseTaskId(1);
state->ReleaseTaskId(3);
EXPECT_EQ(1U, state->AcquireTaskId());
EXPECT_EQ(3U, state->AcquireTaskId());
EXPECT_EQ(5U, state->AcquireTaskId());
}
} // namespace default_job_unittest
} // namespace platform
} // namespace v8

View File

@ -0,0 +1,285 @@
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/libplatform/default-platform.h"
#include "src/base/platform/semaphore.h"
#include "src/base/platform/time.h"
#include "testing/gmock/include/gmock/gmock.h"
using testing::InSequence;
using testing::StrictMock;
namespace v8 {
namespace platform {
namespace default_platform_unittest {
namespace {
struct MockTask : public Task {
// See issue v8:8185
~MockTask() /* override */ { Die(); }
MOCK_METHOD(void, Run, (), (override));
MOCK_METHOD(void, Die, ());
};
struct MockIdleTask : public IdleTask {
// See issue v8:8185
~MockIdleTask() /* override */ { Die(); }
MOCK_METHOD(void, Run, (double deadline_in_seconds), (override));
MOCK_METHOD(void, Die, ());
};
class DefaultPlatformWithMockTime : public DefaultPlatform {
public:
explicit DefaultPlatformWithMockTime(int thread_pool_size = 0)
: DefaultPlatform(thread_pool_size, IdleTaskSupport::kEnabled, nullptr) {
mock_time_ = 0.0;
SetTimeFunctionForTesting([]() { return mock_time_; });
}
void IncreaseTime(double seconds) { mock_time_ += seconds; }
private:
static double mock_time_;
};
double DefaultPlatformWithMockTime::mock_time_ = 0.0;
template <typename Platform>
class PlatformTest : public ::testing::Test {
public:
Isolate* isolate() { return reinterpret_cast<Isolate*>(dummy_); }
Platform* platform() { return &platform_; }
std::shared_ptr<TaskRunner> task_runner() {
if (!task_runner_) {
task_runner_ = platform_.GetForegroundTaskRunner(
isolate(), TaskPriority::kUserBlocking);
}
DCHECK_NOT_NULL(task_runner_);
return task_runner_;
}
// These methods take ownership of the task. Tests might still reference them,
// if the tasks are expected to still exist.
void CallOnForegroundThread(Task* task) {
task_runner()->PostTask(std::unique_ptr<Task>(task));
}
void CallNonNestableOnForegroundThread(Task* task) {
task_runner()->PostNonNestableTask(std::unique_ptr<Task>(task));
}
void CallDelayedOnForegroundThread(Task* task, double delay_in_seconds) {
task_runner()->PostDelayedTask(std::unique_ptr<Task>(task),
delay_in_seconds);
}
void CallIdleOnForegroundThread(IdleTask* task) {
task_runner()->PostIdleTask(std::unique_ptr<IdleTask>(task));
}
bool PumpMessageLoop() { return platform_.PumpMessageLoop(isolate()); }
private:
Platform platform_;
InSequence in_sequence_;
std::shared_ptr<TaskRunner> task_runner_;
int dummy_ = 0;
};
class DefaultPlatformTest : public PlatformTest<DefaultPlatform> {};
class DefaultPlatformTestWithMockTime
: public PlatformTest<DefaultPlatformWithMockTime> {};
} // namespace
TEST_F(DefaultPlatformTest, PumpMessageLoop) {
EXPECT_FALSE(platform()->PumpMessageLoop(isolate()));
StrictMock<MockTask>* task = new StrictMock<MockTask>;
CallOnForegroundThread(task);
EXPECT_CALL(*task, Run());
EXPECT_CALL(*task, Die());
EXPECT_TRUE(PumpMessageLoop());
EXPECT_FALSE(PumpMessageLoop());
}
TEST_F(DefaultPlatformTest, PumpMessageLoopWithTaskRunner) {
std::shared_ptr<TaskRunner> taskrunner = platform()->GetForegroundTaskRunner(
isolate(), TaskPriority::kUserBlocking);
EXPECT_FALSE(PumpMessageLoop());
StrictMock<MockTask>* task = new StrictMock<MockTask>;
taskrunner->PostTask(std::unique_ptr<Task>(task));
EXPECT_CALL(*task, Run());
EXPECT_CALL(*task, Die());
EXPECT_TRUE(PumpMessageLoop());
EXPECT_FALSE(PumpMessageLoop());
}
TEST_F(DefaultPlatformTest, PumpMessageLoopNested) {
EXPECT_FALSE(PumpMessageLoop());
StrictMock<MockTask>* nestable_task1 = new StrictMock<MockTask>;
StrictMock<MockTask>* non_nestable_task2 = new StrictMock<MockTask>;
StrictMock<MockTask>* nestable_task3 = new StrictMock<MockTask>;
StrictMock<MockTask>* non_nestable_task4 = new StrictMock<MockTask>;
CallOnForegroundThread(nestable_task1);
CallNonNestableOnForegroundThread(non_nestable_task2);
CallOnForegroundThread(nestable_task3);
CallNonNestableOnForegroundThread(non_nestable_task4);
// Nestable tasks are FIFO; non-nestable tasks are FIFO. A task being
// non-nestable may cause it to be executed later, but not earlier.
EXPECT_CALL(*nestable_task1, Run).WillOnce([this]() {
EXPECT_TRUE(PumpMessageLoop());
});
EXPECT_CALL(*nestable_task3, Run());
EXPECT_CALL(*nestable_task3, Die());
EXPECT_CALL(*nestable_task1, Die());
EXPECT_TRUE(PumpMessageLoop());
EXPECT_CALL(*non_nestable_task2, Run());
EXPECT_CALL(*non_nestable_task2, Die());
EXPECT_TRUE(PumpMessageLoop());
EXPECT_CALL(*non_nestable_task4, Run());
EXPECT_CALL(*non_nestable_task4, Die());
EXPECT_TRUE(PumpMessageLoop());
EXPECT_FALSE(PumpMessageLoop());
}
TEST_F(DefaultPlatformTestWithMockTime, PumpMessageLoopDelayed) {
EXPECT_FALSE(PumpMessageLoop());
StrictMock<MockTask>* task1 = new StrictMock<MockTask>;
StrictMock<MockTask>* task2 = new StrictMock<MockTask>;
CallDelayedOnForegroundThread(task2, 100);
CallDelayedOnForegroundThread(task1, 10);
EXPECT_FALSE(PumpMessageLoop());
platform()->IncreaseTime(11);
EXPECT_CALL(*task1, Run());
EXPECT_CALL(*task1, Die());
EXPECT_TRUE(PumpMessageLoop());
EXPECT_FALSE(PumpMessageLoop());
platform()->IncreaseTime(90);
EXPECT_CALL(*task2, Run());
EXPECT_CALL(*task2, Die());
EXPECT_TRUE(PumpMessageLoop());
}
TEST_F(DefaultPlatformTestWithMockTime, PumpMessageLoopNoStarvation) {
EXPECT_FALSE(PumpMessageLoop());
StrictMock<MockTask>* task1 = new StrictMock<MockTask>;
StrictMock<MockTask>* task2 = new StrictMock<MockTask>;
StrictMock<MockTask>* task3 = new StrictMock<MockTask>;
CallOnForegroundThread(task1);
CallDelayedOnForegroundThread(task2, 10);
platform()->IncreaseTime(11);
EXPECT_CALL(*task1, Run());
EXPECT_CALL(*task1, Die());
EXPECT_TRUE(PumpMessageLoop());
CallOnForegroundThread(task3);
EXPECT_CALL(*task2, Run());
EXPECT_CALL(*task2, Die());
EXPECT_TRUE(PumpMessageLoop());
EXPECT_CALL(*task3, Run());
EXPECT_CALL(*task3, Die());
EXPECT_TRUE(PumpMessageLoop());
}
TEST_F(DefaultPlatformTestWithMockTime,
PendingDelayedTasksAreDestroyedOnShutdown) {
StrictMock<MockTask>* task = new StrictMock<MockTask>;
CallDelayedOnForegroundThread(task, 10);
EXPECT_CALL(*task, Die());
}
TEST_F(DefaultPlatformTestWithMockTime, RunIdleTasks) {
StrictMock<MockIdleTask>* task = new StrictMock<MockIdleTask>;
CallIdleOnForegroundThread(task);
EXPECT_CALL(*task, Run(42.0 + 23.0));
EXPECT_CALL(*task, Die());
platform()->IncreaseTime(23.0);
platform()->RunIdleTasks(isolate(), 42.0);
}
TEST_F(DefaultPlatformTestWithMockTime,
PendingIdleTasksAreDestroyedOnShutdown) {
StrictMock<MockIdleTask>* task = new StrictMock<MockIdleTask>;
CallIdleOnForegroundThread(task);
EXPECT_CALL(*task, Die());
}
namespace {
class TestBackgroundTask : public Task {
public:
explicit TestBackgroundTask(base::Semaphore* sem, bool* executed)
: sem_(sem), executed_(executed) {}
~TestBackgroundTask() override { Die(); }
MOCK_METHOD(void, Die, ());
void Run() override {
*executed_ = true;
sem_->Signal();
}
private:
base::Semaphore* sem_;
bool* executed_;
};
} // namespace
TEST(CustomDefaultPlatformTest, RunBackgroundTask) {
DefaultPlatform platform(1);
base::Semaphore sem(0);
bool task_executed = false;
StrictMock<TestBackgroundTask>* task =
new StrictMock<TestBackgroundTask>(&sem, &task_executed);
EXPECT_CALL(*task, Die());
platform.PostTaskOnWorkerThread(TaskPriority::kUserVisible,
std::unique_ptr<Task>(task));
EXPECT_TRUE(sem.WaitFor(base::TimeDelta::FromSeconds(1)));
EXPECT_TRUE(task_executed);
}
TEST(CustomDefaultPlatformTest, PostForegroundTaskAfterPlatformTermination) {
std::shared_ptr<TaskRunner> foreground_taskrunner;
{
DefaultPlatformWithMockTime platform(1);
int dummy;
Isolate* isolate = reinterpret_cast<Isolate*>(&dummy);
foreground_taskrunner =
platform.GetForegroundTaskRunner(isolate, TaskPriority::kUserBlocking);
}
// It should still be possible to post foreground tasks, even when the
// platform does not exist anymore.
StrictMock<MockTask>* task1 = new StrictMock<MockTask>;
EXPECT_CALL(*task1, Die());
foreground_taskrunner->PostTask(std::unique_ptr<Task>(task1));
StrictMock<MockTask>* task2 = new StrictMock<MockTask>;
EXPECT_CALL(*task2, Die());
foreground_taskrunner->PostDelayedTask(std::unique_ptr<Task>(task2), 10);
StrictMock<MockIdleTask>* task3 = new StrictMock<MockIdleTask>;
EXPECT_CALL(*task3, Die());
foreground_taskrunner->PostIdleTask(std::unique_ptr<IdleTask>(task3));
}
} // namespace default_platform_unittest
} // namespace platform
} // namespace v8

View File

@ -0,0 +1,279 @@
// Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/libplatform/default-worker-threads-task-runner.h"
#include <algorithm>
#include <vector>
#include "include/v8-platform.h"
#include "src/base/platform/platform.h"
#include "src/base/platform/semaphore.h"
#include "src/base/platform/time.h"
#include "testing/gtest-support.h"
namespace v8 {
namespace platform {
class TestTask : public v8::Task {
public:
explicit TestTask(std::function<void()> f) : f_(std::move(f)) {}
void Run() override { f_(); }
private:
std::function<void()> f_;
};
double RealTime() {
return base::TimeTicks::Now().ToInternalValue() /
static_cast<double>(base::Time::kMicrosecondsPerSecond);
}
TEST(DefaultWorkerThreadsTaskRunnerUnittest, PostTaskOrder) {
DefaultWorkerThreadsTaskRunner runner(1, RealTime);
std::vector<int> order;
base::Semaphore semaphore(0);
std::unique_ptr<TestTask> task1 =
std::make_unique<TestTask>([&] { order.push_back(1); });
std::unique_ptr<TestTask> task2 =
std::make_unique<TestTask>([&] { order.push_back(2); });
std::unique_ptr<TestTask> task3 = std::make_unique<TestTask>([&] {
order.push_back(3);
semaphore.Signal();
});
runner.PostTask(std::move(task1));
runner.PostTask(std::move(task2));
runner.PostTask(std::move(task3));
semaphore.Wait();
runner.Terminate();
ASSERT_EQ(3UL, order.size());
ASSERT_EQ(1, order[0]);
ASSERT_EQ(2, order[1]);
ASSERT_EQ(3, order[2]);
}
TEST(DefaultWorkerThreadsTaskRunnerUnittest, PostTaskOrderMultipleWorkers) {
DefaultWorkerThreadsTaskRunner runner(4, RealTime);
base::Mutex vector_lock;
std::vector<int> order;
std::atomic_int count{0};
std::unique_ptr<TestTask> task1 = std::make_unique<TestTask>([&] {
base::MutexGuard guard(&vector_lock);
order.push_back(1);
count++;
});
std::unique_ptr<TestTask> task2 = std::make_unique<TestTask>([&] {
base::MutexGuard guard(&vector_lock);
order.push_back(2);
count++;
});
std::unique_ptr<TestTask> task3 = std::make_unique<TestTask>([&] {
base::MutexGuard guard(&vector_lock);
order.push_back(3);
count++;
});
std::unique_ptr<TestTask> task4 = std::make_unique<TestTask>([&] {
base::MutexGuard guard(&vector_lock);
order.push_back(4);
count++;
});
std::unique_ptr<TestTask> task5 = std::make_unique<TestTask>([&] {
base::MutexGuard guard(&vector_lock);
order.push_back(5);
count++;
});
runner.PostTask(std::move(task1));
runner.PostTask(std::move(task2));
runner.PostTask(std::move(task3));
runner.PostTask(std::move(task4));
runner.PostTask(std::move(task5));
// We can't observe any ordering when there are multiple worker threads. The
// tasks are guaranteed to be dispatched to workers in the input order, but
// the workers are different threads and can be scheduled arbitrarily. Just
// check that all of the tasks were run once.
while (count != 5) {
}
runner.Terminate();
ASSERT_EQ(5UL, order.size());
ASSERT_EQ(1, std::count(order.begin(), order.end(), 1));
ASSERT_EQ(1, std::count(order.begin(), order.end(), 2));
ASSERT_EQ(1, std::count(order.begin(), order.end(), 3));
ASSERT_EQ(1, std::count(order.begin(), order.end(), 4));
ASSERT_EQ(1, std::count(order.begin(), order.end(), 5));
}
class FakeClock {
public:
static double time() { return time_.load(); }
static void set_time(double time) { time_.store(time); }
static void set_time_and_wake_up_runner(
double time, DefaultWorkerThreadsTaskRunner* runner) {
time_.store(time);
// PostTask will cause the condition variable WaitFor() call to be notified
// early, rather than waiting for the real amount of time. WaitFor() listens
// to the system clock and not our FakeClock.
runner->PostTask(std::make_unique<TestTask>([] {}));
}
private:
static std::atomic<double> time_;
};
std::atomic<double> FakeClock::time_{0.0};
TEST(DefaultWorkerThreadsTaskRunnerUnittest, PostDelayedTaskOrder) {
FakeClock::set_time(0.0);
DefaultWorkerThreadsTaskRunner runner(1, FakeClock::time);
std::vector<int> order;
base::Semaphore task1_semaphore(0);
base::Semaphore task3_semaphore(0);
std::unique_ptr<TestTask> task1 = std::make_unique<TestTask>([&] {
order.push_back(1);
task1_semaphore.Signal();
});
std::unique_ptr<TestTask> task2 =
std::make_unique<TestTask>([&] { order.push_back(2); });
std::unique_ptr<TestTask> task3 = std::make_unique<TestTask>([&] {
order.push_back(3);
task3_semaphore.Signal();
});
runner.PostDelayedTask(std::move(task1), 100);
runner.PostTask(std::move(task2));
runner.PostTask(std::move(task3));
FakeClock::set_time_and_wake_up_runner(99, &runner);
task3_semaphore.Wait();
ASSERT_EQ(2UL, order.size());
ASSERT_EQ(2, order[0]);
ASSERT_EQ(3, order[1]);
FakeClock::set_time_and_wake_up_runner(101, &runner);
task1_semaphore.Wait();
runner.Terminate();
ASSERT_EQ(3UL, order.size());
ASSERT_EQ(2, order[0]);
ASSERT_EQ(3, order[1]);
ASSERT_EQ(1, order[2]);
}
TEST(DefaultWorkerThreadsTaskRunnerUnittest, PostDelayedTaskOrder2) {
FakeClock::set_time(0.0);
DefaultWorkerThreadsTaskRunner runner(1, FakeClock::time);
std::vector<int> order;
base::Semaphore task1_semaphore(0);
base::Semaphore task2_semaphore(0);
base::Semaphore task3_semaphore(0);
std::unique_ptr<TestTask> task1 = std::make_unique<TestTask>([&] {
order.push_back(1);
task1_semaphore.Signal();
});
std::unique_ptr<TestTask> task2 = std::make_unique<TestTask>([&] {
order.push_back(2);
task2_semaphore.Signal();
});
std::unique_ptr<TestTask> task3 = std::make_unique<TestTask>([&] {
order.push_back(3);
task3_semaphore.Signal();
});
runner.PostDelayedTask(std::move(task1), 500);
runner.PostDelayedTask(std::move(task2), 100);
runner.PostDelayedTask(std::move(task3), 200);
FakeClock::set_time_and_wake_up_runner(101, &runner);
task2_semaphore.Wait();
ASSERT_EQ(1UL, order.size());
ASSERT_EQ(2, order[0]);
FakeClock::set_time_and_wake_up_runner(201, &runner);
task3_semaphore.Wait();
ASSERT_EQ(2UL, order.size());
ASSERT_EQ(2, order[0]);
ASSERT_EQ(3, order[1]);
FakeClock::set_time_and_wake_up_runner(501, &runner);
task1_semaphore.Wait();
runner.Terminate();
ASSERT_EQ(3UL, order.size());
ASSERT_EQ(2, order[0]);
ASSERT_EQ(3, order[1]);
ASSERT_EQ(1, order[2]);
}
TEST(DefaultWorkerThreadsTaskRunnerUnittest, PostAfterTerminate) {
FakeClock::set_time(0.0);
DefaultWorkerThreadsTaskRunner runner(1, FakeClock::time);
std::vector<int> order;
base::Semaphore task1_semaphore(0);
base::Semaphore task2_semaphore(0);
base::Semaphore task3_semaphore(0);
std::unique_ptr<TestTask> task1 = std::make_unique<TestTask>([&] {
order.push_back(1);
task1_semaphore.Signal();
});
std::unique_ptr<TestTask> task2 = std::make_unique<TestTask>([&] {
order.push_back(2);
task2_semaphore.Signal();
});
std::unique_ptr<TestTask> task3 = std::make_unique<TestTask>([&] {
order.push_back(3);
task3_semaphore.Signal();
});
runner.PostTask(std::move(task1));
runner.PostDelayedTask(std::move(task2), 100);
task1_semaphore.Wait();
ASSERT_EQ(1UL, order.size());
ASSERT_EQ(1, order[0]);
runner.Terminate();
FakeClock::set_time_and_wake_up_runner(201, &runner);
// OK, we can't actually prove that this never executes. But wait a bit at
// least.
bool signalled =
task2_semaphore.WaitFor(base::TimeDelta::FromMilliseconds(100));
ASSERT_FALSE(signalled);
ASSERT_EQ(1UL, order.size());
ASSERT_EQ(1, order[0]);
runner.PostTask(std::move(task3));
signalled = task3_semaphore.WaitFor(base::TimeDelta::FromMilliseconds(100));
ASSERT_FALSE(signalled);
ASSERT_EQ(1UL, order.size());
ASSERT_EQ(1, order[0]);
}
TEST(DefaultWorkerThreadsTaskRunnerUnittest, NoIdleTasks) {
DefaultWorkerThreadsTaskRunner runner(1, FakeClock::time);
ASSERT_FALSE(runner.IdleTasksEnabled());
runner.Terminate();
}
} // namespace platform
} // namespace v8

View File

@ -0,0 +1,71 @@
// Copyright 2022 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "include/v8-platform.h"
#include "src/init/v8.h"
#include "test/unittests/heap/heap-utils.h"
#include "test/unittests/test-utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace v8 {
template <typename TMixin>
class WithSingleThreadedDefaultPlatformMixin : public TMixin {
public:
WithSingleThreadedDefaultPlatformMixin() {
platform_ = v8::platform::NewSingleThreadedDefaultPlatform();
CHECK_NOT_NULL(platform_.get());
i::V8::InitializePlatformForTesting(platform_.get());
v8::V8::Initialize();
}
~WithSingleThreadedDefaultPlatformMixin() override {
CHECK_NOT_NULL(platform_.get());
v8::V8::Dispose();
v8::V8::DisposePlatform();
}
v8::Platform* platform() const { return platform_.get(); }
private:
std::unique_ptr<v8::Platform> platform_;
};
class SingleThreadedDefaultPlatformTest
: public WithIsolateScopeMixin< //
WithIsolateMixin< //
WithSingleThreadedDefaultPlatformMixin< //
::testing::Test>>> {
public:
static void SetUpTestSuite() {
i::v8_flags.single_threaded = true;
i::FlagList::EnforceFlagImplications();
WithIsolateScopeMixin::SetUpTestSuite();
}
static void TearDownTestSuite() {
WithIsolateScopeMixin::TearDownTestSuite();
}
};
TEST_F(SingleThreadedDefaultPlatformTest, SingleThreadedDefaultPlatform) {
{
i::HandleScope scope(i_isolate());
v8::Local<Context> env = Context::New(isolate());
v8::Context::Scope context_scope(env);
RunJS(
"function f() {"
" for (let i = 0; i < 10; i++)"
" (new Array(10)).fill(0);"
" return 0;"
"}"
"f();");
}
InvokeMinorGC(i_isolate());
InvokeMemoryReducingMajorGCs(i_isolate());
}
} // namespace v8

View File

@ -0,0 +1,63 @@
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "include/v8-platform.h"
#include "src/base/platform/platform.h"
#include "src/libplatform/task-queue.h"
#include "testing/gmock/include/gmock/gmock.h"
using testing::InSequence;
using testing::IsNull;
using testing::StrictMock;
namespace v8 {
namespace platform {
namespace task_queue_unittest {
namespace {
struct MockTask : public Task {
MOCK_METHOD(void, Run, (), (override));
};
class TaskQueueThread final : public base::Thread {
public:
explicit TaskQueueThread(TaskQueue* queue)
: Thread(Options("libplatform TaskQueueThread")), queue_(queue) {}
void Run() override { EXPECT_THAT(queue_->GetNext(), IsNull()); }
private:
TaskQueue* queue_;
};
} // namespace
TEST(TaskQueueTest, Basic) {
TaskQueue queue;
std::unique_ptr<Task> task(new MockTask());
Task* ptr = task.get();
queue.Append(std::move(task));
EXPECT_EQ(ptr, queue.GetNext().get());
queue.Terminate();
EXPECT_THAT(queue.GetNext(), IsNull());
}
TEST(TaskQueueTest, TerminateMultipleReaders) {
TaskQueue queue;
TaskQueueThread thread1(&queue);
TaskQueueThread thread2(&queue);
CHECK(thread1.Start());
CHECK(thread2.Start());
queue.Terminate();
thread1.Join();
thread2.Join();
}
} // namespace task_queue_unittest
} // namespace platform
} // namespace v8

View File

@ -0,0 +1,895 @@
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <limits>
#include "include/libplatform/v8-tracing.h"
#include "src/base/platform/platform.h"
#include "src/libplatform/default-platform.h"
#include "src/tracing/trace-event.h"
#include "test/unittests/test-utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#ifdef V8_USE_PERFETTO
#include "perfetto/tracing/track_event.h" // nogncheck
#include "perfetto/tracing/track_event_legacy.h" // nogncheck
#include "protos/perfetto/trace/trace.pb.h" // nogncheck
#include "src/libplatform/tracing/trace-event-listener.h"
#include "src/tracing/traced-value.h"
#endif // V8_USE_PERFETTO
namespace v8 {
namespace platform {
namespace tracing {
class PlatformTracingTest : public TestWithPlatform {};
TEST_F(PlatformTracingTest, TestTraceConfig) {
TraceConfig* trace_config = new TraceConfig();
trace_config->AddIncludedCategory("v8");
trace_config->AddIncludedCategory(TRACE_DISABLED_BY_DEFAULT("v8.runtime"));
CHECK_EQ(trace_config->IsSystraceEnabled(), false);
CHECK_EQ(trace_config->IsArgumentFilterEnabled(), false);
CHECK_EQ(trace_config->IsCategoryGroupEnabled("v8"), true);
CHECK_EQ(trace_config->IsCategoryGroupEnabled("v8.cpu_profile"), false);
CHECK_EQ(trace_config->IsCategoryGroupEnabled(
TRACE_DISABLED_BY_DEFAULT("v8.runtime")),
true);
CHECK_EQ(trace_config->IsCategoryGroupEnabled("v8,v8.cpu_profile"), true);
CHECK_EQ(
trace_config->IsCategoryGroupEnabled("v8,disabled-by-default-v8.runtime"),
true);
CHECK_EQ(trace_config->IsCategoryGroupEnabled("v8_cpu_profile"), false);
delete trace_config;
}
// Perfetto doesn't use TraceObject.
#if !defined(V8_USE_PERFETTO)
TEST_F(PlatformTracingTest, TestTraceObject) {
TraceObject trace_object;
uint8_t category_enabled_flag = 41;
trace_object.Initialize('X', &category_enabled_flag, "Test.Trace",
"Test.Scope", 42, 123, 0, nullptr, nullptr, nullptr,
nullptr, 0, 1729, 4104);
CHECK_EQ('X', trace_object.phase());
CHECK_EQ(category_enabled_flag, *trace_object.category_enabled_flag());
CHECK_EQ(std::string("Test.Trace"), std::string(trace_object.name()));
CHECK_EQ(std::string("Test.Scope"), std::string(trace_object.scope()));
CHECK_EQ(0u, trace_object.duration());
CHECK_EQ(0u, trace_object.cpu_duration());
}
class ConvertableToTraceFormatMock : public v8::ConvertableToTraceFormat {
public:
ConvertableToTraceFormatMock(const ConvertableToTraceFormatMock&) = delete;
ConvertableToTraceFormatMock& operator=(const ConvertableToTraceFormatMock&) =
delete;
explicit ConvertableToTraceFormatMock(int value) : value_(value) {}
void AppendAsTraceFormat(std::string* out) const override {
*out += "[" + std::to_string(value_) + "," + std::to_string(value_) + "]";
}
private:
int value_;
};
class MockTraceWriter : public TraceWriter {
public:
void AppendTraceEvent(TraceObject* trace_event) override {
// TraceObject might not have been initialized.
const char* name = trace_event->name() ? trace_event->name() : "";
events_.push_back(name);
}
void Flush() override {}
std::vector<std::string> events() { return events_; }
private:
std::vector<std::string> events_;
};
#endif // !defined(V8_USE_PERFETTO)
// Perfetto doesn't use the ring buffer.
#if !defined(V8_USE_PERFETTO)
TEST_F(PlatformTracingTest, TestTraceBufferRingBuffer) {
// We should be able to add kChunkSize * 2 + 1 trace events.
const int HANDLES_COUNT = TraceBufferChunk::kChunkSize * 2 + 1;
MockTraceWriter* writer = new MockTraceWriter();
TraceBuffer* ring_buffer =
TraceBuffer::CreateTraceBufferRingBuffer(2, writer);
std::string names[HANDLES_COUNT];
for (int i = 0; i < HANDLES_COUNT; ++i) {
names[i] = "Test.EventNo" + std::to_string(i);
}
std::vector<uint64_t> handles(HANDLES_COUNT);
uint8_t category_enabled_flag = 41;
for (size_t i = 0; i < handles.size(); ++i) {
TraceObject* trace_object = ring_buffer->AddTraceEvent(&handles[i]);
CHECK_NOT_NULL(trace_object);
trace_object->Initialize('X', &category_enabled_flag, names[i].c_str(),
"Test.Scope", 42, 123, 0, nullptr, nullptr,
nullptr, nullptr, 0, 1729, 4104);
trace_object = ring_buffer->GetEventByHandle(handles[i]);
CHECK_NOT_NULL(trace_object);
CHECK_EQ('X', trace_object->phase());
CHECK_EQ(names[i], std::string(trace_object->name()));
CHECK_EQ(category_enabled_flag, *trace_object->category_enabled_flag());
}
// We should only be able to retrieve the last kChunkSize + 1.
for (size_t i = 0; i < TraceBufferChunk::kChunkSize; ++i) {
CHECK_NULL(ring_buffer->GetEventByHandle(handles[i]));
}
for (size_t i = TraceBufferChunk::kChunkSize; i < handles.size(); ++i) {
TraceObject* trace_object = ring_buffer->GetEventByHandle(handles[i]);
CHECK_NOT_NULL(trace_object);
// The object properties should be correct.
CHECK_EQ('X', trace_object->phase());
CHECK_EQ(names[i], std::string(trace_object->name()));
CHECK_EQ(category_enabled_flag, *trace_object->category_enabled_flag());
}
// Check Flush(), that the writer wrote the last kChunkSize 1 event names.
ring_buffer->Flush();
auto events = writer->events();
CHECK_EQ(TraceBufferChunk::kChunkSize + 1, events.size());
for (size_t i = TraceBufferChunk::kChunkSize; i < handles.size(); ++i) {
CHECK_EQ(names[i], events[i - TraceBufferChunk::kChunkSize]);
}
delete ring_buffer;
}
#endif // !defined(V8_USE_PERFETTO)
// Perfetto has an internal JSON exporter.
#if !defined(V8_USE_PERFETTO)
void PopulateJSONWriter(TraceWriter* writer) {
v8::Platform* old_platform = i::V8::GetCurrentPlatform();
std::unique_ptr<v8::Platform> default_platform(
v8::platform::NewDefaultPlatform());
i::V8::SetPlatformForTesting(default_platform.get());
auto tracing = std::make_unique<v8::platform::tracing::TracingController>();
v8::platform::tracing::TracingController* tracing_controller = tracing.get();
static_cast<v8::platform::DefaultPlatform*>(default_platform.get())
->SetTracingController(std::move(tracing));
TraceBuffer* ring_buffer =
TraceBuffer::CreateTraceBufferRingBuffer(1, writer);
tracing_controller->Initialize(ring_buffer);
TraceConfig* trace_config = new TraceConfig();
trace_config->AddIncludedCategory("v8-cat");
tracing_controller->StartTracing(trace_config);
TraceObject trace_object;
trace_object.InitializeForTesting(
'X', tracing_controller->GetCategoryGroupEnabled("v8-cat"), "Test0",
v8::internal::tracing::kGlobalScope, 42, 0x1234, 0, nullptr, nullptr,
nullptr, nullptr, TRACE_EVENT_FLAG_HAS_ID, 11, 22, 100, 50, 33, 44);
writer->AppendTraceEvent(&trace_object);
trace_object.InitializeForTesting(
'Y', tracing_controller->GetCategoryGroupEnabled("v8-cat"), "Test1",
v8::internal::tracing::kGlobalScope, 43, 0x5678, 0, nullptr, nullptr,
nullptr, nullptr, TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT,
55, 66, 110, 55, 77, 88);
writer->AppendTraceEvent(&trace_object);
tracing_controller->StopTracing();
i::V8::SetPlatformForTesting(old_platform);
}
TEST_F(PlatformTracingTest, TestJSONTraceWriter) {
std::ostringstream stream;
TraceWriter* writer = TraceWriter::CreateJSONTraceWriter(stream);
PopulateJSONWriter(writer);
std::string trace_str = stream.str();
std::string expected_trace_str =
"{\"traceEvents\":[{\"pid\":11,\"tid\":22,\"ts\":100,\"tts\":50,"
"\"ph\":\"X\",\"cat\":\"v8-cat\",\"name\":\"Test0\",\"dur\":33,"
"\"tdur\":44,\"id\":\"0x2a\",\"args\":{}},{\"pid\":55,\"tid\":66,"
"\"ts\":110,\"tts\":55,\"ph\":\"Y\",\"cat\":\"v8-cat\",\"name\":"
"\"Test1\",\"dur\":77,\"tdur\":88,\"bind_id\":\"0x5678\","
"\"flow_in\":true,\"flow_out\":true,\"args\":{}}]}";
CHECK_EQ(expected_trace_str, trace_str);
}
TEST_F(PlatformTracingTest, TestJSONTraceWriterWithCustomtag) {
std::ostringstream stream;
TraceWriter* writer = TraceWriter::CreateJSONTraceWriter(stream, "customTag");
PopulateJSONWriter(writer);
std::string trace_str = stream.str();
std::string expected_trace_str =
"{\"customTag\":[{\"pid\":11,\"tid\":22,\"ts\":100,\"tts\":50,"
"\"ph\":\"X\",\"cat\":\"v8-cat\",\"name\":\"Test0\",\"dur\":33,"
"\"tdur\":44,\"id\":\"0x2a\",\"args\":{}},{\"pid\":55,\"tid\":66,"
"\"ts\":110,\"tts\":55,\"ph\":\"Y\",\"cat\":\"v8-cat\",\"name\":"
"\"Test1\",\"dur\":77,\"tdur\":88,\"bind_id\":\"0x5678\","
"\"flow_in\":true,\"flow_out\":true,\"args\":{}}]}";
CHECK_EQ(expected_trace_str, trace_str);
}
#endif // !defined(V8_USE_PERFETTO)
void GetJSONStrings(std::vector<std::string>* ret, const std::string& str,
const std::string& param, const std::string& start_delim,
const std::string& end_delim) {
size_t pos = str.find(param);
while (pos != std::string::npos) {
size_t start_pos = str.find(start_delim, pos + param.length());
size_t end_pos = str.find(end_delim, start_pos + 1);
CHECK_NE(start_pos, std::string::npos);
CHECK_NE(end_pos, std::string::npos);
ret->push_back(str.substr(start_pos + 1, end_pos - start_pos - 1));
pos = str.find(param, pos + 1);
}
}
// With Perfetto the tracing controller doesn't observe events.
#if !defined(V8_USE_PERFETTO)
TEST_F(PlatformTracingTest, TestTracingController) {
v8::Platform* old_platform = i::V8::GetCurrentPlatform();
std::unique_ptr<v8::Platform> default_platform(
v8::platform::NewDefaultPlatform());
i::V8::SetPlatformForTesting(default_platform.get());
auto tracing = std::make_unique<v8::platform::tracing::TracingController>();
v8::platform::tracing::TracingController* tracing_controller = tracing.get();
static_cast<v8::platform::DefaultPlatform*>(default_platform.get())
->SetTracingController(std::move(tracing));
MockTraceWriter* writer = new MockTraceWriter();
TraceBuffer* ring_buffer =
TraceBuffer::CreateTraceBufferRingBuffer(1, writer);
tracing_controller->Initialize(ring_buffer);
TraceConfig* trace_config = new TraceConfig();
trace_config->AddIncludedCategory("v8");
tracing_controller->StartTracing(trace_config);
TRACE_EVENT0("v8", "v8.Test");
// cat category is not included in default config
TRACE_EVENT0("cat", "v8.Test2");
TRACE_EVENT0("v8", "v8.Test3");
tracing_controller->StopTracing();
CHECK_EQ(2u, writer->events().size());
CHECK_EQ(std::string("v8.Test"), writer->events()[0]);
CHECK_EQ(std::string("v8.Test3"), writer->events()[1]);
i::V8::SetPlatformForTesting(old_platform);
}
TEST_F(PlatformTracingTest, TestTracingControllerMultipleArgsAndCopy) {
std::ostringstream stream, perfetto_stream;
uint64_t aa = 11;
unsigned int bb = 22;
uint16_t cc = 33;
unsigned char dd = 44;
int64_t ee = -55;
int ff = -66;
int16_t gg = -77;
signed char hh = -88;
bool ii1 = true;
bool ii2 = false;
double jj1 = 99.0;
double jj2 = 1e100;
double jj3 = std::numeric_limits<double>::quiet_NaN();
double jj4 = std::numeric_limits<double>::infinity();
double jj5 = -std::numeric_limits<double>::infinity();
void* kk = &aa;
const char* ll = "100";
std::string mm = "INIT";
std::string mmm = "\"INIT\"";
// Create a scope for the tracing controller to terminate the trace writer.
{
v8::Platform* old_platform = i::V8::GetCurrentPlatform();
std::unique_ptr<v8::Platform> default_platform(
v8::platform::NewDefaultPlatform());
i::V8::SetPlatformForTesting(default_platform.get());
auto tracing = std::make_unique<v8::platform::tracing::TracingController>();
v8::platform::tracing::TracingController* tracing_controller =
tracing.get();
static_cast<v8::platform::DefaultPlatform*>(default_platform.get())
->SetTracingController(std::move(tracing));
TraceWriter* writer = TraceWriter::CreateJSONTraceWriter(stream);
TraceBuffer* ring_buffer =
TraceBuffer::CreateTraceBufferRingBuffer(1, writer);
tracing_controller->Initialize(ring_buffer);
TraceConfig* trace_config = new TraceConfig();
trace_config->AddIncludedCategory("v8");
tracing_controller->StartTracing(trace_config);
{
TRACE_EVENT1("v8", "v8.Test.aa", "aa", aa);
TRACE_EVENT1("v8", "v8.Test.bb", "bb", bb);
TRACE_EVENT1("v8", "v8.Test.cc", "cc", cc);
TRACE_EVENT1("v8", "v8.Test.dd", "dd", dd);
TRACE_EVENT1("v8", "v8.Test.ee", "ee", ee);
TRACE_EVENT1("v8", "v8.Test.ff", "ff", ff);
TRACE_EVENT1("v8", "v8.Test.gg", "gg", gg);
TRACE_EVENT1("v8", "v8.Test.hh", "hh", hh);
TRACE_EVENT1("v8", "v8.Test.ii", "ii1", ii1);
TRACE_EVENT1("v8", "v8.Test.ii", "ii2", ii2);
TRACE_EVENT1("v8", "v8.Test.jj1", "jj1", jj1);
TRACE_EVENT1("v8", "v8.Test.jj2", "jj2", jj2);
TRACE_EVENT1("v8", "v8.Test.jj3", "jj3", jj3);
TRACE_EVENT1("v8", "v8.Test.jj4", "jj4", jj4);
TRACE_EVENT1("v8", "v8.Test.jj5", "jj5", jj5);
TRACE_EVENT1("v8", "v8.Test.kk", "kk", kk);
TRACE_EVENT1("v8", "v8.Test.ll", "ll", ll);
TRACE_EVENT1("v8", "v8.Test.mm", "mm", TRACE_STR_COPY(mmm.c_str()));
TRACE_EVENT2("v8", "v8.Test2.1", "aa", aa, "ll", ll);
TRACE_EVENT2("v8", "v8.Test2.2", "mm1", TRACE_STR_COPY(mm.c_str()), "mm2",
TRACE_STR_COPY(mmm.c_str()));
// Check copies are correct.
TRACE_EVENT_COPY_INSTANT0("v8", mm.c_str(), TRACE_EVENT_SCOPE_THREAD);
TRACE_EVENT_COPY_INSTANT2("v8", mm.c_str(), TRACE_EVENT_SCOPE_THREAD,
"mm1", mm.c_str(), "mm2", mmm.c_str());
mm = "CHANGED";
mmm = "CHANGED";
TRACE_EVENT_INSTANT1("v8", "v8.Test", TRACE_EVENT_SCOPE_THREAD, "a1",
new ConvertableToTraceFormatMock(42));
std::unique_ptr<ConvertableToTraceFormatMock> trace_event_arg(
new ConvertableToTraceFormatMock(42));
TRACE_EVENT_INSTANT2("v8", "v8.Test", TRACE_EVENT_SCOPE_THREAD, "a1",
std::move(trace_event_arg), "a2",
new ConvertableToTraceFormatMock(123));
}
tracing_controller->StopTracing();
i::V8::SetPlatformForTesting(old_platform);
}
std::string trace_str = stream.str();
std::vector<std::string> all_args, all_names, all_cats;
GetJSONStrings(&all_args, trace_str, "\"args\"", "{", "}");
GetJSONStrings(&all_names, trace_str, "\"name\"", "\"", "\"");
GetJSONStrings(&all_cats, trace_str, "\"cat\"", "\"", "\"");
CHECK_EQ(all_args.size(), 24u);
CHECK_EQ(all_args[0], "\"aa\":11");
CHECK_EQ(all_args[1], "\"bb\":22");
CHECK_EQ(all_args[2], "\"cc\":33");
CHECK_EQ(all_args[3], "\"dd\":44");
CHECK_EQ(all_args[4], "\"ee\":-55");
CHECK_EQ(all_args[5], "\"ff\":-66");
CHECK_EQ(all_args[6], "\"gg\":-77");
CHECK_EQ(all_args[7], "\"hh\":-88");
CHECK_EQ(all_args[8], "\"ii1\":true");
CHECK_EQ(all_args[9], "\"ii2\":false");
CHECK_EQ(all_args[10], "\"jj1\":99.0");
CHECK_EQ(all_args[11], "\"jj2\":1e+100");
CHECK_EQ(all_args[12], "\"jj3\":\"NaN\"");
CHECK_EQ(all_args[13], "\"jj4\":\"Infinity\"");
CHECK_EQ(all_args[14], "\"jj5\":\"-Infinity\"");
std::ostringstream pointer_stream;
pointer_stream << "\"kk\":\"" << &aa << "\"";
CHECK_EQ(all_args[15], pointer_stream.str());
CHECK_EQ(all_args[16], "\"ll\":\"100\"");
CHECK_EQ(all_args[17], "\"mm\":\"\\\"INIT\\\"\"");
CHECK_EQ(all_names[18], "v8.Test2.1");
CHECK_EQ(all_args[18], "\"aa\":11,\"ll\":\"100\"");
CHECK_EQ(all_args[19], "\"mm1\":\"INIT\",\"mm2\":\"\\\"INIT\\\"\"");
CHECK_EQ(all_names[20], "INIT");
CHECK_EQ(all_names[21], "INIT");
CHECK_EQ(all_args[21], "\"mm1\":\"INIT\",\"mm2\":\"\\\"INIT\\\"\"");
CHECK_EQ(all_args[22], "\"a1\":[42,42]");
CHECK_EQ(all_args[23], "\"a1\":[42,42],\"a2\":[123,123]");
}
#endif // !defined(V8_USE_PERFETTO)
// In Perfetto build there are no TracingObservers. Instead the code relies on
// TrackEventSessionObserver to track tracing sessions, which is tested
// upstream.
#if !defined(V8_USE_PERFETTO)
namespace {
class TraceStateObserverImpl : public TracingController::TraceStateObserver {
public:
void OnTraceEnabled() override { ++enabled_count; }
void OnTraceDisabled() override { ++disabled_count; }
int enabled_count = 0;
int disabled_count = 0;
};
} // namespace
TEST_F(PlatformTracingTest, TracingObservers) {
v8::Platform* old_platform = i::V8::GetCurrentPlatform();
std::unique_ptr<v8::Platform> default_platform(
v8::platform::NewDefaultPlatform());
i::V8::SetPlatformForTesting(default_platform.get());
auto tracing = std::make_unique<v8::platform::tracing::TracingController>();
v8::platform::tracing::TracingController* tracing_controller = tracing.get();
static_cast<v8::platform::DefaultPlatform*>(default_platform.get())
->SetTracingController(std::move(tracing));
MockTraceWriter* writer = new MockTraceWriter();
v8::platform::tracing::TraceBuffer* ring_buffer =
v8::platform::tracing::TraceBuffer::CreateTraceBufferRingBuffer(1,
writer);
tracing_controller->Initialize(ring_buffer);
v8::platform::tracing::TraceConfig* trace_config =
new v8::platform::tracing::TraceConfig();
trace_config->AddIncludedCategory("v8");
TraceStateObserverImpl observer;
tracing_controller->AddTraceStateObserver(&observer);
CHECK_EQ(0, observer.enabled_count);
CHECK_EQ(0, observer.disabled_count);
tracing_controller->StartTracing(trace_config);
CHECK_EQ(1, observer.enabled_count);
CHECK_EQ(0, observer.disabled_count);
TraceStateObserverImpl observer2;
tracing_controller->AddTraceStateObserver(&observer2);
CHECK_EQ(1, observer2.enabled_count);
CHECK_EQ(0, observer2.disabled_count);
tracing_controller->RemoveTraceStateObserver(&observer2);
CHECK_EQ(1, observer2.enabled_count);
CHECK_EQ(0, observer2.disabled_count);
tracing_controller->StopTracing();
CHECK_EQ(1, observer.enabled_count);
CHECK_EQ(1, observer.disabled_count);
CHECK_EQ(1, observer2.enabled_count);
CHECK_EQ(0, observer2.disabled_count);
tracing_controller->RemoveTraceStateObserver(&observer);
CHECK_EQ(1, observer.enabled_count);
CHECK_EQ(1, observer.disabled_count);
trace_config = new v8::platform::tracing::TraceConfig();
tracing_controller->StartTracing(trace_config);
tracing_controller->StopTracing();
CHECK_EQ(1, observer.enabled_count);
CHECK_EQ(1, observer.disabled_count);
i::V8::SetPlatformForTesting(old_platform);
}
#endif // !defined(V8_USE_PERFETTO)
// With Perfetto the tracing controller doesn't observe events.
#if !defined(V8_USE_PERFETTO)
class TraceWritingThread : public base::Thread {
public:
TraceWritingThread(
v8::platform::tracing::TracingController* tracing_controller)
: base::Thread(base::Thread::Options("TraceWritingThread")),
tracing_controller_(tracing_controller) {}
void Run() override {
while (!stopped_.load()) {
TRACE_EVENT0("v8", "v8.Test");
tracing_controller_->AddTraceEvent('A', nullptr, "v8", "", 1, 1, 0,
nullptr, nullptr, nullptr, nullptr, 0);
tracing_controller_->AddTraceEventWithTimestamp('A', nullptr, "v8", "", 1,
1, 0, nullptr, nullptr,
nullptr, nullptr, 0, 0);
}
}
void Stop() { stopped_.store(true); }
private:
std::atomic_bool stopped_{false};
v8::platform::tracing::TracingController* tracing_controller_;
};
TEST_F(PlatformTracingTest, AddTraceEventMultiThreaded) {
v8::Platform* old_platform = i::V8::GetCurrentPlatform();
std::unique_ptr<v8::Platform> default_platform(
v8::platform::NewDefaultPlatform());
i::V8::SetPlatformForTesting(default_platform.get());
auto tracing = std::make_unique<v8::platform::tracing::TracingController>();
v8::platform::tracing::TracingController* tracing_controller = tracing.get();
static_cast<v8::platform::DefaultPlatform*>(default_platform.get())
->SetTracingController(std::move(tracing));
MockTraceWriter* writer = new MockTraceWriter();
TraceBuffer* ring_buffer =
TraceBuffer::CreateTraceBufferRingBuffer(1, writer);
tracing_controller->Initialize(ring_buffer);
TraceConfig* trace_config = new TraceConfig();
trace_config->AddIncludedCategory("v8");
tracing_controller->StartTracing(trace_config);
TraceWritingThread thread(tracing_controller);
thread.StartSynchronously();
TRACE_EVENT0("v8", "v8.Test2");
TRACE_EVENT0("v8", "v8.Test2");
base::OS::Sleep(base::TimeDelta::FromMilliseconds(10));
tracing_controller->StopTracing();
thread.Stop();
thread.Join();
i::V8::SetPlatformForTesting(old_platform);
}
#endif // !defined(V8_USE_PERFETTO)
#ifdef V8_USE_PERFETTO
using TrackEvent = ::perfetto::protos::TrackEvent;
class TestListener : public TraceEventListener {
public:
void ParseFromArray(const std::vector<char>& array) {
perfetto::protos::Trace trace;
CHECK(trace.ParseFromArray(array.data(), static_cast<int>(array.size())));
for (int i = 0; i < trace.packet_size(); i++) {
// TODO(petermarshall): ChromeTracePacket instead.
const perfetto::protos::TracePacket& packet = trace.packet(i);
ProcessPacket(packet);
}
}
const std::string& get_event(size_t index) { return events_.at(index); }
size_t events_size() const { return events_.size(); }
private:
void ProcessPacket(const ::perfetto::protos::TracePacket& packet) {
if (packet.incremental_state_cleared()) {
categories_.clear();
event_names_.clear();
debug_annotation_names_.clear();
}
if (!packet.has_track_event()) return;
// Update incremental state.
if (packet.has_interned_data()) {
const auto& interned_data = packet.interned_data();
for (const auto& it : interned_data.event_categories()) {
CHECK_EQ(categories_.find(it.iid()), categories_.end());
categories_[it.iid()] = it.name();
}
for (const auto& it : interned_data.event_names()) {
CHECK_EQ(event_names_.find(it.iid()), event_names_.end());
event_names_[it.iid()] = it.name();
}
for (const auto& it : interned_data.debug_annotation_names()) {
CHECK_EQ(debug_annotation_names_.find(it.iid()),
debug_annotation_names_.end());
debug_annotation_names_[it.iid()] = it.name();
}
}
const auto& track_event = packet.track_event();
std::string slice;
switch (track_event.type()) {
case perfetto::protos::TrackEvent::TYPE_SLICE_BEGIN:
slice += "B";
break;
case perfetto::protos::TrackEvent::TYPE_SLICE_END:
slice += "E";
break;
case perfetto::protos::TrackEvent::TYPE_INSTANT:
slice += "I";
break;
default:
case perfetto::protos::TrackEvent::TYPE_UNSPECIFIED:
CHECK(false);
}
slice += ":" +
(track_event.category_iids_size()
? categories_[track_event.category_iids().Get(0)]
: "") +
".";
if (track_event.name_iid()) {
slice += event_names_[track_event.name_iid()];
} else {
slice += track_event.name();
}
if (track_event.debug_annotations_size()) {
slice += "(";
bool first_annotation = true;
for (const auto& it : track_event.debug_annotations()) {
if (!first_annotation) {
slice += ",";
}
if (!it.name().empty()) {
slice += it.name();
} else {
slice += debug_annotation_names_[it.name_iid()];
}
slice += "=";
std::stringstream value;
if (it.has_bool_value()) {
value << "(bool)" << it.bool_value();
} else if (it.has_uint_value()) {
value << "(uint)" << it.uint_value();
} else if (it.has_int_value()) {
value << "(int)" << it.int_value();
} else if (it.has_double_value()) {
value << "(double)" << it.double_value();
} else if (it.has_string_value()) {
value << "(string)" << it.string_value();
} else if (it.has_pointer_value()) {
value << "(pointer)0x" << std::hex << it.pointer_value();
} else if (it.has_legacy_json_value()) {
value << "(json)" << it.legacy_json_value();
} else if (it.has_nested_value()) {
value << "(nested)" << it.nested_value().string_value();
}
slice += value.str();
first_annotation = false;
}
slice += ")";
}
events_.push_back(slice);
}
std::vector<std::string> events_;
std::map<uint64_t, std::string> categories_;
std::map<uint64_t, std::string> event_names_;
std::map<uint64_t, std::string> debug_annotation_names_;
};
class TracingTestHarness {
public:
TracingTestHarness() {
old_platform_ = i::V8::GetCurrentPlatform();
default_platform_ = v8::platform::NewDefaultPlatform();
i::V8::SetPlatformForTesting(default_platform_.get());
auto tracing = std::make_unique<v8::platform::tracing::TracingController>();
tracing_controller_ = tracing.get();
static_cast<v8::platform::DefaultPlatform*>(default_platform_.get())
->SetTracingController(std::move(tracing));
tracing_controller_->InitializeForPerfetto(&perfetto_json_stream_);
tracing_controller_->SetTraceEventListenerForTesting(&listener_);
}
~TracingTestHarness() { i::V8::SetPlatformForTesting(old_platform_); }
void StartTracing() {
TraceConfig* trace_config = new TraceConfig();
trace_config->AddIncludedCategory("v8");
tracing_controller_->StartTracing(trace_config);
}
void StopTracing() {
v8::TrackEvent::Flush();
tracing_controller_->StopTracing();
}
const std::string& get_event(size_t index) {
return listener_.get_event(index);
}
size_t events_size() const { return listener_.events_size(); }
std::string perfetto_json_stream() { return perfetto_json_stream_.str(); }
private:
std::unique_ptr<v8::Platform> default_platform_;
v8::Platform* old_platform_;
v8::platform::tracing::TracingController* tracing_controller_;
TestListener listener_;
std::ostringstream perfetto_json_stream_;
};
TEST_F(PlatformTracingTest, Perfetto) {
TracingTestHarness harness;
harness.StartTracing();
uint64_t uint64_arg = 1024;
const char* str_arg = "str_arg";
{
TRACE_EVENT0("v8", "test1");
TRACE_EVENT1("v8", "test2", "arg1", uint64_arg);
TRACE_EVENT2("v8", "test3", "arg1", uint64_arg, "arg2", str_arg);
}
harness.StopTracing();
CHECK_EQ("B:v8.test1", harness.get_event(0));
CHECK_EQ("B:v8.test2(arg1=(uint)1024)", harness.get_event(1));
CHECK_EQ("B:v8.test3(arg1=(uint)1024,arg2=(string)str_arg)",
harness.get_event(2));
CHECK_EQ("E:.", harness.get_event(3));
CHECK_EQ("E:.", harness.get_event(4));
CHECK_EQ("E:.", harness.get_event(5));
CHECK_EQ(6, harness.events_size());
}
// Replacement for 'TestTracingController'
TEST_F(PlatformTracingTest, Categories) {
TracingTestHarness harness;
harness.StartTracing();
{
TRACE_EVENT0("v8", "v8.Test");
// cat category is not included in default config
TRACE_EVENT0("cat", "v8.Test2");
TRACE_EVENT0("v8", "v8.Test3");
}
harness.StopTracing();
CHECK_EQ(4, harness.events_size());
CHECK_EQ("B:v8.v8.Test", harness.get_event(0));
CHECK_EQ("B:v8.v8.Test3", harness.get_event(1));
CHECK_EQ("E:.", harness.get_event(2));
CHECK_EQ("E:.", harness.get_event(3));
}
// Replacement for 'TestTracingControllerMultipleArgsAndCopy'
TEST_F(PlatformTracingTest, MultipleArgsAndCopy) {
uint64_t aa = 11;
unsigned int bb = 22;
uint16_t cc = 33;
unsigned char dd = 44;
int64_t ee = -55;
int ff = -66;
int16_t gg = -77;
signed char hh = -88;
bool ii1 = true;
bool ii2 = false;
double jj1 = 99.0;
double jj2 = 1e100;
double jj3 = std::numeric_limits<double>::quiet_NaN();
double jj4 = std::numeric_limits<double>::infinity();
double jj5 = -std::numeric_limits<double>::infinity();
void* kk = &aa;
const char* ll = "100";
std::string mm = "INIT";
std::string mmm = "\"INIT\"";
TracingTestHarness harness;
harness.StartTracing();
// Create a scope for the tracing controller to terminate the trace writer.
{
TRACE_EVENT1("v8", "v8.Test.aa", "aa", aa);
TRACE_EVENT1("v8", "v8.Test.bb", "bb", bb);
TRACE_EVENT1("v8", "v8.Test.cc", "cc", cc);
TRACE_EVENT1("v8", "v8.Test.dd", "dd", dd);
TRACE_EVENT1("v8", "v8.Test.ee", "ee", ee);
TRACE_EVENT1("v8", "v8.Test.ff", "ff", ff);
TRACE_EVENT1("v8", "v8.Test.gg", "gg", gg);
TRACE_EVENT1("v8", "v8.Test.hh", "hh", hh);
TRACE_EVENT1("v8", "v8.Test.ii", "ii1", ii1);
TRACE_EVENT1("v8", "v8.Test.ii", "ii2", ii2);
TRACE_EVENT1("v8", "v8.Test.jj1", "jj1", jj1);
TRACE_EVENT1("v8", "v8.Test.jj2", "jj2", jj2);
TRACE_EVENT1("v8", "v8.Test.jj3", "jj3", jj3);
TRACE_EVENT1("v8", "v8.Test.jj4", "jj4", jj4);
TRACE_EVENT1("v8", "v8.Test.jj5", "jj5", jj5);
TRACE_EVENT1("v8", "v8.Test.kk", "kk", kk);
TRACE_EVENT1("v8", "v8.Test.ll", "ll", ll);
TRACE_EVENT1("v8", "v8.Test.mm", "mm", TRACE_STR_COPY(mmm.c_str()));
TRACE_EVENT2("v8", "v8.Test2.1", "aa", aa, "ll", ll);
TRACE_EVENT2("v8", "v8.Test2.2", "mm1", TRACE_STR_COPY(mm.c_str()), "mm2",
TRACE_STR_COPY(mmm.c_str()));
// Check copies are correct.
TRACE_EVENT_COPY_INSTANT0("v8", mm.c_str(), TRACE_EVENT_SCOPE_THREAD);
TRACE_EVENT_COPY_INSTANT2("v8", mm.c_str(), TRACE_EVENT_SCOPE_THREAD, "mm1",
mm.c_str(), "mm2", mmm.c_str());
mm = "CHANGED";
mmm = "CHANGED";
auto arg = v8::tracing::TracedValue::Create();
arg->SetInteger("value", 42);
TRACE_EVENT_INSTANT1("v8", "v8.Test", TRACE_EVENT_SCOPE_THREAD, "a1",
std::move(arg));
arg = v8::tracing::TracedValue::Create();
arg->SetString("value", "string");
auto arg2 = v8::tracing::TracedValue::Create();
arg2->SetDouble("value", 1.23);
TRACE_EVENT_INSTANT2("v8", "v8.Test", TRACE_EVENT_SCOPE_THREAD, "a1",
std::move(arg), "a2", std::move(arg2));
}
harness.StopTracing();
CHECK_EQ("B:v8.v8.Test.aa(aa=(uint)11)", harness.get_event(0));
CHECK_EQ("B:v8.v8.Test.bb(bb=(uint)22)", harness.get_event(1));
CHECK_EQ("B:v8.v8.Test.cc(cc=(uint)33)", harness.get_event(2));
CHECK_EQ("B:v8.v8.Test.dd(dd=(uint)44)", harness.get_event(3));
CHECK_EQ("B:v8.v8.Test.ee(ee=(int)-55)", harness.get_event(4));
CHECK_EQ("B:v8.v8.Test.ff(ff=(int)-66)", harness.get_event(5));
CHECK_EQ("B:v8.v8.Test.gg(gg=(int)-77)", harness.get_event(6));
CHECK_EQ("B:v8.v8.Test.hh(hh=(int)-88)", harness.get_event(7));
CHECK_EQ("B:v8.v8.Test.ii(ii1=(bool)1)", harness.get_event(8));
CHECK_EQ("B:v8.v8.Test.ii(ii2=(bool)0)", harness.get_event(9));
CHECK_EQ("B:v8.v8.Test.jj1(jj1=(double)99)", harness.get_event(10));
CHECK_EQ("B:v8.v8.Test.jj2(jj2=(double)1e+100)", harness.get_event(11));
CHECK_EQ("B:v8.v8.Test.jj3(jj3=(double)nan)", harness.get_event(12));
CHECK_EQ("B:v8.v8.Test.jj4(jj4=(double)inf)", harness.get_event(13));
CHECK_EQ("B:v8.v8.Test.jj5(jj5=(double)-inf)", harness.get_event(14));
std::ostringstream pointer_stream;
pointer_stream << "B:v8.v8.Test.kk(kk=(pointer)" << &aa << ")";
CHECK_EQ(pointer_stream.str().c_str(), harness.get_event(15));
CHECK_EQ("B:v8.v8.Test.ll(ll=(string)100)", harness.get_event(16));
CHECK_EQ("B:v8.v8.Test.mm(mm=(string)\"INIT\")", harness.get_event(17));
CHECK_EQ("B:v8.v8.Test2.1(aa=(uint)11,ll=(string)100)",
harness.get_event(18));
CHECK_EQ("B:v8.v8.Test2.2(mm1=(string)INIT,mm2=(string)\"INIT\")",
harness.get_event(19));
CHECK_EQ("I:v8.INIT", harness.get_event(20));
CHECK_EQ("I:v8.INIT(mm1=(string)INIT,mm2=(string)\"INIT\")",
harness.get_event(21));
CHECK_EQ("I:v8.v8.Test(a1=(json){\"value\":42})", harness.get_event(22));
CHECK_EQ(
"I:v8.v8.Test(a1=(json){\"value\":\"string\"},a2=(json){\"value\":1.23})",
harness.get_event(23));
// Check the terminating end events.
for (size_t i = 0; i < 20; i++) CHECK_EQ("E:.", harness.get_event(24 + i));
}
TEST_F(PlatformTracingTest, JsonIntegrationTest) {
// Check that tricky values are rendered correctly in the JSON output.
double big_num = 1e100;
double nan_num = std::numeric_limits<double>::quiet_NaN();
double inf_num = std::numeric_limits<double>::infinity();
double neg_inf_num = -std::numeric_limits<double>::infinity();
TracingTestHarness harness;
harness.StartTracing();
{
TRACE_EVENT1("v8", "v8.Test.1", "1", big_num);
TRACE_EVENT1("v8", "v8.Test.2", "2", nan_num);
TRACE_EVENT1("v8", "v8.Test.3", "3", inf_num);
TRACE_EVENT1("v8", "v8.Test.4", "4", neg_inf_num);
}
harness.StopTracing();
std::string json = harness.perfetto_json_stream();
std::cout << json << "\n";
std::vector<std::string> all_args, all_cats;
GetJSONStrings(&all_args, json, "\"args\"", "{", "}");
GetJSONStrings(&all_cats, json, "\"cat\"", "\"", "\"");
// Ignore the metadata events.
int i = 0;
while (all_cats[i] == "__metadata") ++i;
CHECK_EQ("\"1\":1e+100", all_args[i++]);
CHECK_EQ("\"2\":\"NaN\"", all_args[i++]);
CHECK_EQ("\"3\":\"Infinity\"", all_args[i++]);
CHECK_EQ("\"4\":\"-Infinity\"", all_args[i++]);
}
#endif // V8_USE_PERFETTO
} // namespace tracing
} // namespace platform
} // namespace v8

View File

@ -0,0 +1,69 @@
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "include/v8-platform.h"
#include "src/libplatform/task-queue.h"
#include "src/libplatform/worker-thread.h"
#include "testing/gmock/include/gmock/gmock.h"
using testing::InSequence;
using testing::IsNull;
using testing::StrictMock;
namespace v8 {
namespace platform {
namespace {
struct MockTask : public Task {
// See issue v8:8185
~MockTask() /* override */ { Die(); }
MOCK_METHOD(void, Run, (), (override));
MOCK_METHOD(void, Die, ());
};
} // namespace
// Needs to be in v8::platform due to BlockUntilQueueEmptyForTesting
// being private.
TEST(WorkerThreadTest, PostSingleTask) {
TaskQueue queue;
WorkerThread thread1(&queue);
WorkerThread thread2(&queue);
InSequence s;
std::unique_ptr<StrictMock<MockTask>> task(new StrictMock<MockTask>);
EXPECT_CALL(*task.get(), Run());
EXPECT_CALL(*task.get(), Die());
queue.Append(std::move(task));
// The next call should not time out.
queue.BlockUntilQueueEmptyForTesting();
queue.Terminate();
}
namespace worker_thread_unittest {
TEST(WorkerThreadTest, Basic) {
static const size_t kNumTasks = 10;
TaskQueue queue;
for (size_t i = 0; i < kNumTasks; ++i) {
InSequence s;
std::unique_ptr<StrictMock<MockTask>> task(new StrictMock<MockTask>);
EXPECT_CALL(*task.get(), Run());
EXPECT_CALL(*task.get(), Die());
queue.Append(std::move(task));
}
WorkerThread thread1(&queue);
WorkerThread thread2(&queue);
// TaskQueue DCHECKS that it's empty in its destructor.
queue.Terminate();
}
} // namespace worker_thread_unittest
} // namespace platform
} // namespace v8