1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/threading/thread.h"
6
7 #include <stddef.h>
8 #include <stdint.h>
9
10 #include <utility>
11 #include <vector>
12
13 #include "base/bind.h"
14 #include "base/debug/leak_annotations.h"
15 #include "base/macros.h"
16 #include "base/memory/ptr_util.h"
17 #include "base/message_loop/message_loop.h"
18 #include "base/message_loop/message_loop_current.h"
19 #include "base/run_loop.h"
20 #include "base/single_thread_task_runner.h"
21 #include "base/synchronization/waitable_event.h"
22 #include "base/test/gtest_util.h"
23 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
24 #include "base/threading/platform_thread.h"
25 #include "base/time/time.h"
26 #include "build/build_config.h"
27 #include "testing/gtest/include/gtest/gtest.h"
28 #include "testing/platform_test.h"
29
30 using base::Thread;
31
32 typedef PlatformTest ThreadTest;
33
34 namespace {
35
ToggleValue(bool * value)36 void ToggleValue(bool* value) {
37 ANNOTATE_BENIGN_RACE(value, "Test-only data race on boolean "
38 "in base/thread_unittest");
39 *value = !*value;
40 }
41
42 class SleepInsideInitThread : public Thread {
43 public:
SleepInsideInitThread()44 SleepInsideInitThread() : Thread("none") {
45 init_called_ = false;
46 ANNOTATE_BENIGN_RACE(
47 this, "Benign test-only data race on vptr - http://crbug.com/98219");
48 }
~SleepInsideInitThread()49 ~SleepInsideInitThread() override { Stop(); }
50
Init()51 void Init() override {
52 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(500));
53 init_called_ = true;
54 }
InitCalled()55 bool InitCalled() { return init_called_; }
56
57 private:
58 bool init_called_;
59
60 DISALLOW_COPY_AND_ASSIGN(SleepInsideInitThread);
61 };
62
63 enum ThreadEvent {
64 // Thread::Init() was called.
65 THREAD_EVENT_INIT = 0,
66
67 // The MessageLoop for the thread was deleted.
68 THREAD_EVENT_MESSAGE_LOOP_DESTROYED,
69
70 // Thread::CleanUp() was called.
71 THREAD_EVENT_CLEANUP,
72
73 // Keep at end of list.
74 THREAD_NUM_EVENTS
75 };
76
77 typedef std::vector<ThreadEvent> EventList;
78
79 class CaptureToEventList : public Thread {
80 public:
81 // This Thread pushes events into the vector |event_list| to show
82 // the order they occured in. |event_list| must remain valid for the
83 // lifetime of this thread.
CaptureToEventList(EventList * event_list)84 explicit CaptureToEventList(EventList* event_list)
85 : Thread("none"),
86 event_list_(event_list) {
87 }
88
~CaptureToEventList()89 ~CaptureToEventList() override { Stop(); }
90
Init()91 void Init() override { event_list_->push_back(THREAD_EVENT_INIT); }
92
CleanUp()93 void CleanUp() override { event_list_->push_back(THREAD_EVENT_CLEANUP); }
94
95 private:
96 EventList* event_list_;
97
98 DISALLOW_COPY_AND_ASSIGN(CaptureToEventList);
99 };
100
101 // Observer that writes a value into |event_list| when a message loop has been
102 // destroyed.
103 class CapturingDestructionObserver
104 : public base::MessageLoopCurrent::DestructionObserver {
105 public:
106 // |event_list| must remain valid throughout the observer's lifetime.
CapturingDestructionObserver(EventList * event_list)107 explicit CapturingDestructionObserver(EventList* event_list)
108 : event_list_(event_list) {
109 }
110
111 // DestructionObserver implementation:
WillDestroyCurrentMessageLoop()112 void WillDestroyCurrentMessageLoop() override {
113 event_list_->push_back(THREAD_EVENT_MESSAGE_LOOP_DESTROYED);
114 event_list_ = nullptr;
115 }
116
117 private:
118 EventList* event_list_;
119
120 DISALLOW_COPY_AND_ASSIGN(CapturingDestructionObserver);
121 };
122
123 // Task that adds a destruction observer to the current message loop.
RegisterDestructionObserver(base::MessageLoopCurrent::DestructionObserver * observer)124 void RegisterDestructionObserver(
125 base::MessageLoopCurrent::DestructionObserver* observer) {
126 base::MessageLoopCurrent::Get()->AddDestructionObserver(observer);
127 }
128
129 // Task that calls GetThreadId() of |thread|, stores the result into |id|, then
130 // signal |event|.
ReturnThreadId(base::Thread * thread,base::PlatformThreadId * id,base::WaitableEvent * event)131 void ReturnThreadId(base::Thread* thread,
132 base::PlatformThreadId* id,
133 base::WaitableEvent* event) {
134 *id = thread->GetThreadId();
135 event->Signal();
136 }
137
138 } // namespace
139
TEST_F(ThreadTest,StartWithOptions_StackSize)140 TEST_F(ThreadTest, StartWithOptions_StackSize) {
141 Thread a("StartWithStackSize");
142 // Ensure that the thread can work with only 12 kb and still process a
143 // message. At the same time, we should scale with the bitness of the system
144 // where 12 kb is definitely not enough.
145 // 12 kb = 3072 Slots on a 32-bit system, so we'll scale based off of that.
146 Thread::Options options;
147 #if defined(ADDRESS_SANITIZER) || !defined(NDEBUG)
148 // ASan bloats the stack variables and overflows the 3072 slot stack. Some
149 // debug builds also grow the stack too much.
150 options.stack_size = 2 * 3072 * sizeof(uintptr_t);
151 #else
152 options.stack_size = 3072 * sizeof(uintptr_t);
153 #endif
154 EXPECT_TRUE(a.StartWithOptions(options));
155 EXPECT_TRUE(a.message_loop());
156 EXPECT_TRUE(a.IsRunning());
157
158 base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC,
159 base::WaitableEvent::InitialState::NOT_SIGNALED);
160 a.task_runner()->PostTask(
161 FROM_HERE,
162 base::BindOnce(&base::WaitableEvent::Signal, base::Unretained(&event)));
163 event.Wait();
164 }
165
166 // Intentional test-only race for otherwise untestable code, won't fix.
167 // https://crbug.com/634383
168 #if !defined(THREAD_SANITIZER)
TEST_F(ThreadTest,StartWithOptions_NonJoinable)169 TEST_F(ThreadTest, StartWithOptions_NonJoinable) {
170 Thread* a = new Thread("StartNonJoinable");
171 // Non-joinable threads have to be leaked for now (see
172 // Thread::Options::joinable for details).
173 ANNOTATE_LEAKING_OBJECT_PTR(a);
174
175 Thread::Options options;
176 options.joinable = false;
177 EXPECT_TRUE(a->StartWithOptions(options));
178 EXPECT_TRUE(a->message_loop());
179 EXPECT_TRUE(a->IsRunning());
180
181 // Without this call this test is racy. The above IsRunning() succeeds because
182 // of an early-return condition while between Start() and StopSoon(), after
183 // invoking StopSoon() below this early-return condition is no longer
184 // satisfied and the real |is_running_| bit has to be checked. It could still
185 // be false if the message loop hasn't started for real in practice. This is
186 // only a requirement for this test because the non-joinable property forces
187 // it to use StopSoon() and not wait for a complete Stop().
188 EXPECT_TRUE(a->WaitUntilThreadStarted());
189
190 // Make the thread block until |block_event| is signaled.
191 base::WaitableEvent block_event(
192 base::WaitableEvent::ResetPolicy::AUTOMATIC,
193 base::WaitableEvent::InitialState::NOT_SIGNALED);
194 a->task_runner()->PostTask(FROM_HERE,
195 base::BindOnce(&base::WaitableEvent::Wait,
196 base::Unretained(&block_event)));
197
198 a->StopSoon();
199 EXPECT_TRUE(a->IsRunning());
200
201 // Unblock the task and give a bit of extra time to unwind QuitWhenIdle().
202 block_event.Signal();
203 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(20));
204
205 // The thread should now have stopped on its own.
206 EXPECT_FALSE(a->IsRunning());
207 }
208 #endif
209
TEST_F(ThreadTest,TwoTasksOnJoinableThread)210 TEST_F(ThreadTest, TwoTasksOnJoinableThread) {
211 bool was_invoked = false;
212 {
213 Thread a("TwoTasksOnJoinableThread");
214 EXPECT_TRUE(a.Start());
215 EXPECT_TRUE(a.message_loop());
216
217 // Test that all events are dispatched before the Thread object is
218 // destroyed. We do this by dispatching a sleep event before the
219 // event that will toggle our sentinel value.
220 a.task_runner()->PostTask(
221 FROM_HERE, base::BindOnce(static_cast<void (*)(base::TimeDelta)>(
222 &base::PlatformThread::Sleep),
223 base::TimeDelta::FromMilliseconds(20)));
224 a.task_runner()->PostTask(FROM_HERE,
225 base::BindOnce(&ToggleValue, &was_invoked));
226 }
227 EXPECT_TRUE(was_invoked);
228 }
229
TEST_F(ThreadTest,DestroyWhileRunningIsSafe)230 TEST_F(ThreadTest, DestroyWhileRunningIsSafe) {
231 Thread a("DestroyWhileRunningIsSafe");
232 EXPECT_TRUE(a.Start());
233 EXPECT_TRUE(a.WaitUntilThreadStarted());
234 }
235
236 // TODO(gab): Enable this test when destroying a non-joinable Thread instance
237 // is supported (proposal @ https://crbug.com/629139#c14).
TEST_F(ThreadTest,DISABLED_DestroyWhileRunningNonJoinableIsSafe)238 TEST_F(ThreadTest, DISABLED_DestroyWhileRunningNonJoinableIsSafe) {
239 {
240 Thread a("DestroyWhileRunningNonJoinableIsSafe");
241 Thread::Options options;
242 options.joinable = false;
243 EXPECT_TRUE(a.StartWithOptions(options));
244 EXPECT_TRUE(a.WaitUntilThreadStarted());
245 }
246
247 // Attempt to catch use-after-frees from the non-joinable thread in the
248 // scope of this test if any.
249 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(20));
250 }
251
TEST_F(ThreadTest,StopSoon)252 TEST_F(ThreadTest, StopSoon) {
253 Thread a("StopSoon");
254 EXPECT_TRUE(a.Start());
255 EXPECT_TRUE(a.message_loop());
256 EXPECT_TRUE(a.IsRunning());
257 a.StopSoon();
258 a.Stop();
259 EXPECT_FALSE(a.message_loop());
260 EXPECT_FALSE(a.IsRunning());
261 }
262
TEST_F(ThreadTest,StopTwiceNop)263 TEST_F(ThreadTest, StopTwiceNop) {
264 Thread a("StopTwiceNop");
265 EXPECT_TRUE(a.Start());
266 EXPECT_TRUE(a.message_loop());
267 EXPECT_TRUE(a.IsRunning());
268 a.StopSoon();
269 // Calling StopSoon() a second time should be a nop.
270 a.StopSoon();
271 a.Stop();
272 // Same with Stop().
273 a.Stop();
274 EXPECT_FALSE(a.message_loop());
275 EXPECT_FALSE(a.IsRunning());
276 // Calling them when not running should also nop.
277 a.StopSoon();
278 a.Stop();
279 }
280
281 // TODO(gab): Enable this test in conjunction with re-enabling the sequence
282 // check in Thread::Stop() as part of http://crbug.com/629139.
TEST_F(ThreadTest,DISABLED_StopOnNonOwningThreadIsDeath)283 TEST_F(ThreadTest, DISABLED_StopOnNonOwningThreadIsDeath) {
284 Thread a("StopOnNonOwningThreadDeath");
285 EXPECT_TRUE(a.StartAndWaitForTesting());
286
287 Thread b("NonOwningThread");
288 b.Start();
289 EXPECT_DCHECK_DEATH({
290 // Stopping |a| on |b| isn't allowed.
291 b.task_runner()->PostTask(
292 FROM_HERE, base::BindOnce(&Thread::Stop, base::Unretained(&a)));
293 // Block here so the DCHECK on |b| always happens in this scope.
294 base::PlatformThread::Sleep(base::TimeDelta::Max());
295 });
296 }
297
TEST_F(ThreadTest,TransferOwnershipAndStop)298 TEST_F(ThreadTest, TransferOwnershipAndStop) {
299 std::unique_ptr<Thread> a =
300 std::make_unique<Thread>("TransferOwnershipAndStop");
301 EXPECT_TRUE(a->StartAndWaitForTesting());
302 EXPECT_TRUE(a->IsRunning());
303
304 Thread b("TakingOwnershipThread");
305 b.Start();
306
307 base::WaitableEvent event(base::WaitableEvent::ResetPolicy::MANUAL,
308 base::WaitableEvent::InitialState::NOT_SIGNALED);
309
310 // a->DetachFromSequence() should allow |b| to use |a|'s Thread API.
311 a->DetachFromSequence();
312 b.task_runner()->PostTask(
313 FROM_HERE, base::BindOnce(
314 [](std::unique_ptr<Thread> thread_to_stop,
315 base::WaitableEvent* event_to_signal) -> void {
316 thread_to_stop->Stop();
317 event_to_signal->Signal();
318 },
319 std::move(a), base::Unretained(&event)));
320
321 event.Wait();
322 }
323
TEST_F(ThreadTest,StartTwice)324 TEST_F(ThreadTest, StartTwice) {
325 Thread a("StartTwice");
326
327 EXPECT_FALSE(a.message_loop());
328 EXPECT_FALSE(a.IsRunning());
329
330 EXPECT_TRUE(a.Start());
331 EXPECT_TRUE(a.message_loop());
332 EXPECT_TRUE(a.IsRunning());
333
334 a.Stop();
335 EXPECT_FALSE(a.message_loop());
336 EXPECT_FALSE(a.IsRunning());
337
338 EXPECT_TRUE(a.Start());
339 EXPECT_TRUE(a.message_loop());
340 EXPECT_TRUE(a.IsRunning());
341
342 a.Stop();
343 EXPECT_FALSE(a.message_loop());
344 EXPECT_FALSE(a.IsRunning());
345 }
346
347 // Intentional test-only race for otherwise untestable code, won't fix.
348 // https://crbug.com/634383
349 #if !defined(THREAD_SANITIZER)
TEST_F(ThreadTest,StartTwiceNonJoinableNotAllowed)350 TEST_F(ThreadTest, StartTwiceNonJoinableNotAllowed) {
351 LOG(ERROR) << __FUNCTION__;
352 Thread* a = new Thread("StartTwiceNonJoinable");
353 // Non-joinable threads have to be leaked for now (see
354 // Thread::Options::joinable for details).
355 ANNOTATE_LEAKING_OBJECT_PTR(a);
356
357 Thread::Options options;
358 options.joinable = false;
359 EXPECT_TRUE(a->StartWithOptions(options));
360 EXPECT_TRUE(a->message_loop());
361 EXPECT_TRUE(a->IsRunning());
362
363 // Signaled when last task on |a| is processed.
364 base::WaitableEvent last_task_event(
365 base::WaitableEvent::ResetPolicy::AUTOMATIC,
366 base::WaitableEvent::InitialState::NOT_SIGNALED);
367 a->task_runner()->PostTask(
368 FROM_HERE, base::BindOnce(&base::WaitableEvent::Signal,
369 base::Unretained(&last_task_event)));
370
371 // StopSoon() is non-blocking, Yield() to |a|, wait for last task to be
372 // processed and a little more for QuitWhenIdle() to unwind before considering
373 // the thread "stopped".
374 a->StopSoon();
375 base::PlatformThread::YieldCurrentThread();
376 last_task_event.Wait();
377 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(20));
378
379 // This test assumes that the above was sufficient to let the thread fully
380 // stop.
381 ASSERT_FALSE(a->IsRunning());
382
383 // Restarting it should not be allowed.
384 EXPECT_DCHECK_DEATH(a->Start());
385 }
386 #endif
387
TEST_F(ThreadTest,ThreadName)388 TEST_F(ThreadTest, ThreadName) {
389 Thread a("ThreadName");
390 EXPECT_TRUE(a.Start());
391 EXPECT_EQ("ThreadName", a.thread_name());
392 }
393
TEST_F(ThreadTest,ThreadId)394 TEST_F(ThreadTest, ThreadId) {
395 Thread a("ThreadId0");
396 Thread b("ThreadId1");
397 a.Start();
398 b.Start();
399
400 // Post a task that calls GetThreadId() on the created thread.
401 base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC,
402 base::WaitableEvent::InitialState::NOT_SIGNALED);
403 base::PlatformThreadId id_from_new_thread;
404 a.task_runner()->PostTask(
405 FROM_HERE,
406 base::BindOnce(ReturnThreadId, &a, &id_from_new_thread, &event));
407
408 // Call GetThreadId() on the current thread before calling event.Wait() so
409 // that this test can find a race issue with TSAN.
410 base::PlatformThreadId id_from_current_thread = a.GetThreadId();
411
412 // Check if GetThreadId() returns consistent value in both threads.
413 event.Wait();
414 EXPECT_EQ(id_from_current_thread, id_from_new_thread);
415
416 // A started thread should have a valid ID.
417 EXPECT_NE(base::kInvalidThreadId, a.GetThreadId());
418 EXPECT_NE(base::kInvalidThreadId, b.GetThreadId());
419
420 // Each thread should have a different thread ID.
421 EXPECT_NE(a.GetThreadId(), b.GetThreadId());
422 }
423
TEST_F(ThreadTest,ThreadIdWithRestart)424 TEST_F(ThreadTest, ThreadIdWithRestart) {
425 Thread a("ThreadIdWithRestart");
426 base::PlatformThreadId previous_id = base::kInvalidThreadId;
427
428 for (size_t i = 0; i < 16; ++i) {
429 EXPECT_TRUE(a.Start());
430 base::PlatformThreadId current_id = a.GetThreadId();
431 EXPECT_NE(previous_id, current_id);
432 previous_id = current_id;
433 a.Stop();
434 }
435 }
436
437 // Make sure Init() is called after Start() and before
438 // WaitUntilThreadInitialized() returns.
TEST_F(ThreadTest,SleepInsideInit)439 TEST_F(ThreadTest, SleepInsideInit) {
440 SleepInsideInitThread t;
441 EXPECT_FALSE(t.InitCalled());
442 t.StartAndWaitForTesting();
443 EXPECT_TRUE(t.InitCalled());
444 }
445
446 // Make sure that the destruction sequence is:
447 //
448 // (1) Thread::CleanUp()
449 // (2) MessageLoop::~MessageLoop()
450 // MessageLoopCurrent::DestructionObservers called.
TEST_F(ThreadTest,CleanUp)451 TEST_F(ThreadTest, CleanUp) {
452 EventList captured_events;
453 CapturingDestructionObserver loop_destruction_observer(&captured_events);
454
455 {
456 // Start a thread which writes its event into |captured_events|.
457 CaptureToEventList t(&captured_events);
458 EXPECT_TRUE(t.Start());
459 EXPECT_TRUE(t.message_loop());
460 EXPECT_TRUE(t.IsRunning());
461
462 // Register an observer that writes into |captured_events| once the
463 // thread's message loop is destroyed.
464 t.task_runner()->PostTask(
465 FROM_HERE,
466 base::BindOnce(&RegisterDestructionObserver,
467 base::Unretained(&loop_destruction_observer)));
468
469 // Upon leaving this scope, the thread is deleted.
470 }
471
472 // Check the order of events during shutdown.
473 ASSERT_EQ(static_cast<size_t>(THREAD_NUM_EVENTS), captured_events.size());
474 EXPECT_EQ(THREAD_EVENT_INIT, captured_events[0]);
475 EXPECT_EQ(THREAD_EVENT_CLEANUP, captured_events[1]);
476 EXPECT_EQ(THREAD_EVENT_MESSAGE_LOOP_DESTROYED, captured_events[2]);
477 }
478
TEST_F(ThreadTest,ThreadNotStarted)479 TEST_F(ThreadTest, ThreadNotStarted) {
480 Thread a("Inert");
481 EXPECT_FALSE(a.task_runner());
482 }
483
TEST_F(ThreadTest,MultipleWaitUntilThreadStarted)484 TEST_F(ThreadTest, MultipleWaitUntilThreadStarted) {
485 Thread a("MultipleWaitUntilThreadStarted");
486 EXPECT_TRUE(a.Start());
487 // It's OK to call WaitUntilThreadStarted() multiple times.
488 EXPECT_TRUE(a.WaitUntilThreadStarted());
489 EXPECT_TRUE(a.WaitUntilThreadStarted());
490 }
491
TEST_F(ThreadTest,FlushForTesting)492 TEST_F(ThreadTest, FlushForTesting) {
493 Thread a("FlushForTesting");
494
495 // Flushing a non-running thread should be a no-op.
496 a.FlushForTesting();
497
498 ASSERT_TRUE(a.Start());
499
500 // Flushing a thread with no tasks shouldn't block.
501 a.FlushForTesting();
502
503 constexpr base::TimeDelta kSleepPerTestTask =
504 base::TimeDelta::FromMilliseconds(50);
505 constexpr size_t kNumSleepTasks = 5;
506
507 const base::TimeTicks ticks_before_post = base::TimeTicks::Now();
508
509 for (size_t i = 0; i < kNumSleepTasks; ++i) {
510 a.task_runner()->PostTask(
511 FROM_HERE,
512 base::BindOnce(&base::PlatformThread::Sleep, kSleepPerTestTask));
513 }
514
515 // All tasks should have executed, as reflected by the elapsed time.
516 a.FlushForTesting();
517 EXPECT_GE(base::TimeTicks::Now() - ticks_before_post,
518 kNumSleepTasks * kSleepPerTestTask);
519
520 a.Stop();
521
522 // Flushing a stopped thread should be a no-op.
523 a.FlushForTesting();
524 }
525
526 namespace {
527
528 // A Thread which uses a MessageLoop on the stack. It won't start a real
529 // underlying thread (instead its messages can be processed by a RunLoop on the
530 // stack).
531 class ExternalMessageLoopThread : public Thread {
532 public:
ExternalMessageLoopThread()533 ExternalMessageLoopThread() : Thread("ExternalMessageLoopThread") {}
534
~ExternalMessageLoopThread()535 ~ExternalMessageLoopThread() override { Stop(); }
536
InstallMessageLoop()537 void InstallMessageLoop() { SetMessageLoop(&external_message_loop_); }
538
VerifyUsingExternalMessageLoop(bool expected_using_external_message_loop)539 void VerifyUsingExternalMessageLoop(
540 bool expected_using_external_message_loop) {
541 EXPECT_EQ(expected_using_external_message_loop,
542 using_external_message_loop());
543 }
544
545 private:
546 base::MessageLoop external_message_loop_;
547
548 DISALLOW_COPY_AND_ASSIGN(ExternalMessageLoopThread);
549 };
550
551 } // namespace
552
TEST_F(ThreadTest,ExternalMessageLoop)553 TEST_F(ThreadTest, ExternalMessageLoop) {
554 ExternalMessageLoopThread a;
555 EXPECT_FALSE(a.message_loop());
556 EXPECT_FALSE(a.IsRunning());
557 a.VerifyUsingExternalMessageLoop(false);
558
559 a.InstallMessageLoop();
560 EXPECT_TRUE(a.message_loop());
561 EXPECT_TRUE(a.IsRunning());
562 a.VerifyUsingExternalMessageLoop(true);
563
564 bool ran = false;
565 a.task_runner()->PostTask(
566 FROM_HERE, base::BindOnce([](bool* toggled) { *toggled = true; }, &ran));
567 base::RunLoop().RunUntilIdle();
568 EXPECT_TRUE(ran);
569
570 a.Stop();
571 EXPECT_FALSE(a.message_loop());
572 EXPECT_FALSE(a.IsRunning());
573 a.VerifyUsingExternalMessageLoop(true);
574
575 // Confirm that running any remaining tasks posted from Stop() goes smoothly
576 // (e.g. https://codereview.chromium.org/2135413003/#ps300001 crashed if
577 // StopSoon() posted Thread::ThreadQuitHelper() while |run_loop_| was null).
578 base::RunLoop().RunUntilIdle();
579 }
580