1 //===-- tsan_test_util_posix.cpp ------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is a part of ThreadSanitizer (TSan), a race detector.
10 //
11 // Test utils, Linux, FreeBSD, NetBSD and Darwin implementation.
12 //===----------------------------------------------------------------------===//
13 
14 #include "sanitizer_common/sanitizer_atomic.h"
15 #include "tsan_interface.h"
16 #include "tsan_posix_util.h"
17 #include "tsan_test_util.h"
18 #include "tsan_report.h"
19 
20 #include "gtest/gtest.h"
21 
22 #include <assert.h>
23 #include <pthread.h>
24 #include <stdio.h>
25 #include <stdint.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <errno.h>
29 
30 using namespace __tsan;  // NOLINT
31 
32 static __thread bool expect_report;
33 static __thread bool expect_report_reported;
34 static __thread ReportType expect_report_type;
35 
36 static void *BeforeInitThread(void *param) {
37   (void)param;
38   return 0;
39 }
40 
41 static void AtExit() {
42 }
43 
44 void TestMutexBeforeInit() {
45   // Mutexes must be usable before __tsan_init();
46   pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
47   __interceptor_pthread_mutex_lock(&mtx);
48   __interceptor_pthread_mutex_unlock(&mtx);
49   __interceptor_pthread_mutex_destroy(&mtx);
50   pthread_t thr;
51   __interceptor_pthread_create(&thr, 0, BeforeInitThread, 0);
52   __interceptor_pthread_join(thr, 0);
53   atexit(AtExit);
54 }
55 
56 namespace __tsan {
57 bool OnReport(const ReportDesc *rep, bool suppressed) {
58   if (expect_report) {
59     if (rep->typ != expect_report_type) {
60       printf("Expected report of type %d, got type %d\n",
61              (int)expect_report_type, (int)rep->typ);
62       EXPECT_TRUE(false) << "Wrong report type";
63       return false;
64     }
65   } else {
66     EXPECT_TRUE(false) << "Unexpected report";
67     return false;
68   }
69   expect_report_reported = true;
70   return true;
71 }
72 }  // namespace __tsan
73 
74 static void* allocate_addr(int size, int offset_from_aligned = 0) {
75   static uintptr_t foo;
76   static atomic_uintptr_t uniq = {(uintptr_t)&foo};  // Some real address.
77   const int kAlign = 16;
78   CHECK(offset_from_aligned < kAlign);
79   size = (size + 2 * kAlign) & ~(kAlign - 1);
80   uintptr_t addr = atomic_fetch_add(&uniq, size, memory_order_relaxed);
81   return (void*)(addr + offset_from_aligned);
82 }
83 
84 MemLoc::MemLoc(int offset_from_aligned)
85   : loc_(allocate_addr(16, offset_from_aligned)) {
86 }
87 
88 MemLoc::~MemLoc() {
89 }
90 
91 Mutex::Mutex(Type type)
92   : alive_()
93   , type_(type) {
94 }
95 
96 Mutex::~Mutex() {
97   CHECK(!alive_);
98 }
99 
100 void Mutex::Init() {
101   CHECK(!alive_);
102   alive_ = true;
103   if (type_ == Normal)
104     CHECK_EQ(__interceptor_pthread_mutex_init((pthread_mutex_t*)mtx_, 0), 0);
105 #ifndef __APPLE__
106   else if (type_ == Spin)
107     CHECK_EQ(pthread_spin_init((pthread_spinlock_t*)mtx_, 0), 0);
108 #endif
109   else if (type_ == RW)
110     CHECK_EQ(__interceptor_pthread_rwlock_init((pthread_rwlock_t*)mtx_, 0), 0);
111   else
112     CHECK(0);
113 }
114 
115 void Mutex::StaticInit() {
116   CHECK(!alive_);
117   CHECK(type_ == Normal);
118   alive_ = true;
119   pthread_mutex_t tmp = PTHREAD_MUTEX_INITIALIZER;
120   memcpy(mtx_, &tmp, sizeof(tmp));
121 }
122 
123 void Mutex::Destroy() {
124   CHECK(alive_);
125   alive_ = false;
126   if (type_ == Normal)
127     CHECK_EQ(__interceptor_pthread_mutex_destroy((pthread_mutex_t*)mtx_), 0);
128 #ifndef __APPLE__
129   else if (type_ == Spin)
130     CHECK_EQ(pthread_spin_destroy((pthread_spinlock_t*)mtx_), 0);
131 #endif
132   else if (type_ == RW)
133     CHECK_EQ(__interceptor_pthread_rwlock_destroy((pthread_rwlock_t*)mtx_), 0);
134 }
135 
136 void Mutex::Lock() {
137   CHECK(alive_);
138   if (type_ == Normal)
139     CHECK_EQ(__interceptor_pthread_mutex_lock((pthread_mutex_t*)mtx_), 0);
140 #ifndef __APPLE__
141   else if (type_ == Spin)
142     CHECK_EQ(pthread_spin_lock((pthread_spinlock_t*)mtx_), 0);
143 #endif
144   else if (type_ == RW)
145     CHECK_EQ(__interceptor_pthread_rwlock_wrlock((pthread_rwlock_t*)mtx_), 0);
146 }
147 
148 bool Mutex::TryLock() {
149   CHECK(alive_);
150   if (type_ == Normal)
151     return __interceptor_pthread_mutex_trylock((pthread_mutex_t*)mtx_) == 0;
152 #ifndef __APPLE__
153   else if (type_ == Spin)
154     return pthread_spin_trylock((pthread_spinlock_t*)mtx_) == 0;
155 #endif
156   else if (type_ == RW)
157     return __interceptor_pthread_rwlock_trywrlock((pthread_rwlock_t*)mtx_) == 0;
158   return false;
159 }
160 
161 void Mutex::Unlock() {
162   CHECK(alive_);
163   if (type_ == Normal)
164     CHECK_EQ(__interceptor_pthread_mutex_unlock((pthread_mutex_t*)mtx_), 0);
165 #ifndef __APPLE__
166   else if (type_ == Spin)
167     CHECK_EQ(pthread_spin_unlock((pthread_spinlock_t*)mtx_), 0);
168 #endif
169   else if (type_ == RW)
170     CHECK_EQ(__interceptor_pthread_rwlock_unlock((pthread_rwlock_t*)mtx_), 0);
171 }
172 
173 void Mutex::ReadLock() {
174   CHECK(alive_);
175   CHECK(type_ == RW);
176   CHECK_EQ(__interceptor_pthread_rwlock_rdlock((pthread_rwlock_t*)mtx_), 0);
177 }
178 
179 bool Mutex::TryReadLock() {
180   CHECK(alive_);
181   CHECK(type_ == RW);
182   return __interceptor_pthread_rwlock_tryrdlock((pthread_rwlock_t*)mtx_) ==  0;
183 }
184 
185 void Mutex::ReadUnlock() {
186   CHECK(alive_);
187   CHECK(type_ == RW);
188   CHECK_EQ(__interceptor_pthread_rwlock_unlock((pthread_rwlock_t*)mtx_), 0);
189 }
190 
191 struct Event {
192   enum Type {
193     SHUTDOWN,
194     READ,
195     WRITE,
196     VPTR_UPDATE,
197     CALL,
198     RETURN,
199     MUTEX_CREATE,
200     MUTEX_DESTROY,
201     MUTEX_LOCK,
202     MUTEX_TRYLOCK,
203     MUTEX_UNLOCK,
204     MUTEX_READLOCK,
205     MUTEX_TRYREADLOCK,
206     MUTEX_READUNLOCK,
207     MEMCPY,
208     MEMSET
209   };
210   Type type;
211   void *ptr;
212   uptr arg;
213   uptr arg2;
214   bool res;
215   bool expect_report;
216   ReportType report_type;
217 
218   Event(Type type, const void *ptr = 0, uptr arg = 0, uptr arg2 = 0)
219     : type(type)
220     , ptr(const_cast<void*>(ptr))
221     , arg(arg)
222     , arg2(arg2)
223     , res()
224     , expect_report()
225     , report_type() {
226   }
227 
228   void ExpectReport(ReportType type) {
229     expect_report = true;
230     report_type = type;
231   }
232 };
233 
234 struct ScopedThread::Impl {
235   pthread_t thread;
236   bool main;
237   bool detached;
238   atomic_uintptr_t event;  // Event*
239 
240   static void *ScopedThreadCallback(void *arg);
241   void send(Event *ev);
242   void HandleEvent(Event *ev);
243 };
244 
245 void ScopedThread::Impl::HandleEvent(Event *ev) {
246   CHECK_EQ(expect_report, false);
247   expect_report = ev->expect_report;
248   expect_report_reported = false;
249   expect_report_type = ev->report_type;
250   switch (ev->type) {
251   case Event::READ:
252   case Event::WRITE: {
253     void (*tsan_mop)(void *addr) = 0;
254     if (ev->type == Event::READ) {
255       switch (ev->arg /*size*/) {
256         case 1: tsan_mop = __tsan_read1; break;
257         case 2: tsan_mop = __tsan_read2; break;
258         case 4: tsan_mop = __tsan_read4; break;
259         case 8: tsan_mop = __tsan_read8; break;
260         case 16: tsan_mop = __tsan_read16; break;
261       }
262     } else {
263       switch (ev->arg /*size*/) {
264         case 1: tsan_mop = __tsan_write1; break;
265         case 2: tsan_mop = __tsan_write2; break;
266         case 4: tsan_mop = __tsan_write4; break;
267         case 8: tsan_mop = __tsan_write8; break;
268         case 16: tsan_mop = __tsan_write16; break;
269       }
270     }
271     CHECK_NE(tsan_mop, 0);
272 #if defined(__FreeBSD__) || defined(__APPLE__) || defined(__NetBSD__)
273     const int ErrCode = ESOCKTNOSUPPORT;
274 #else
275     const int ErrCode = ECHRNG;
276 #endif
277     errno = ErrCode;
278     tsan_mop(ev->ptr);
279     CHECK_EQ(ErrCode, errno);  // In no case must errno be changed.
280     break;
281   }
282   case Event::VPTR_UPDATE:
283     __tsan_vptr_update((void**)ev->ptr, (void*)ev->arg);
284     break;
285   case Event::CALL:
286     __tsan_func_entry((void*)((uptr)ev->ptr));
287     break;
288   case Event::RETURN:
289     __tsan_func_exit();
290     break;
291   case Event::MUTEX_CREATE:
292     static_cast<Mutex*>(ev->ptr)->Init();
293     break;
294   case Event::MUTEX_DESTROY:
295     static_cast<Mutex*>(ev->ptr)->Destroy();
296     break;
297   case Event::MUTEX_LOCK:
298     static_cast<Mutex*>(ev->ptr)->Lock();
299     break;
300   case Event::MUTEX_TRYLOCK:
301     ev->res = static_cast<Mutex*>(ev->ptr)->TryLock();
302     break;
303   case Event::MUTEX_UNLOCK:
304     static_cast<Mutex*>(ev->ptr)->Unlock();
305     break;
306   case Event::MUTEX_READLOCK:
307     static_cast<Mutex*>(ev->ptr)->ReadLock();
308     break;
309   case Event::MUTEX_TRYREADLOCK:
310     ev->res = static_cast<Mutex*>(ev->ptr)->TryReadLock();
311     break;
312   case Event::MUTEX_READUNLOCK:
313     static_cast<Mutex*>(ev->ptr)->ReadUnlock();
314     break;
315   case Event::MEMCPY:
316     __interceptor_memcpy(ev->ptr, (void*)ev->arg, ev->arg2);
317     break;
318   case Event::MEMSET:
319     __interceptor_memset(ev->ptr, ev->arg, ev->arg2);
320     break;
321   default: CHECK(0);
322   }
323   if (expect_report && !expect_report_reported) {
324     printf("Missed expected report of type %d\n", (int)ev->report_type);
325     EXPECT_TRUE(false) << "Missed expected race";
326   }
327   expect_report = false;
328 }
329 
330 void *ScopedThread::Impl::ScopedThreadCallback(void *arg) {
331   __tsan_func_entry(__builtin_return_address(0));
332   Impl *impl = (Impl*)arg;
333   for (;;) {
334     Event* ev = (Event*)atomic_load(&impl->event, memory_order_acquire);
335     if (ev == 0) {
336       sched_yield();
337       continue;
338     }
339     if (ev->type == Event::SHUTDOWN) {
340       atomic_store(&impl->event, 0, memory_order_release);
341       break;
342     }
343     impl->HandleEvent(ev);
344     atomic_store(&impl->event, 0, memory_order_release);
345   }
346   __tsan_func_exit();
347   return 0;
348 }
349 
350 void ScopedThread::Impl::send(Event *e) {
351   if (main) {
352     HandleEvent(e);
353   } else {
354     CHECK_EQ(atomic_load(&event, memory_order_relaxed), 0);
355     atomic_store(&event, (uintptr_t)e, memory_order_release);
356     while (atomic_load(&event, memory_order_acquire) != 0)
357       sched_yield();
358   }
359 }
360 
361 ScopedThread::ScopedThread(bool detached, bool main) {
362   impl_ = new Impl;
363   impl_->main = main;
364   impl_->detached = detached;
365   atomic_store(&impl_->event, 0, memory_order_relaxed);
366   if (!main) {
367     pthread_attr_t attr;
368     pthread_attr_init(&attr);
369     pthread_attr_setdetachstate(
370         &attr, detached ? PTHREAD_CREATE_DETACHED : PTHREAD_CREATE_JOINABLE);
371     pthread_attr_setstacksize(&attr, 64*1024);
372     __interceptor_pthread_create(&impl_->thread, &attr,
373         ScopedThread::Impl::ScopedThreadCallback, impl_);
374   }
375 }
376 
377 ScopedThread::~ScopedThread() {
378   if (!impl_->main) {
379     Event event(Event::SHUTDOWN);
380     impl_->send(&event);
381     if (!impl_->detached)
382       __interceptor_pthread_join(impl_->thread, 0);
383   }
384   delete impl_;
385 }
386 
387 void ScopedThread::Detach() {
388   CHECK(!impl_->main);
389   CHECK(!impl_->detached);
390   impl_->detached = true;
391   __interceptor_pthread_detach(impl_->thread);
392 }
393 
394 void ScopedThread::Access(void *addr, bool is_write,
395                           int size, bool expect_race) {
396   Event event(is_write ? Event::WRITE : Event::READ, addr, size);
397   if (expect_race)
398     event.ExpectReport(ReportTypeRace);
399   impl_->send(&event);
400 }
401 
402 void ScopedThread::VptrUpdate(const MemLoc &vptr,
403                               const MemLoc &new_val,
404                               bool expect_race) {
405   Event event(Event::VPTR_UPDATE, vptr.loc(), (uptr)new_val.loc());
406   if (expect_race)
407     event.ExpectReport(ReportTypeRace);
408   impl_->send(&event);
409 }
410 
411 void ScopedThread::Call(void(*pc)()) {
412   Event event(Event::CALL, (void*)((uintptr_t)pc));
413   impl_->send(&event);
414 }
415 
416 void ScopedThread::Return() {
417   Event event(Event::RETURN);
418   impl_->send(&event);
419 }
420 
421 void ScopedThread::Create(const Mutex &m) {
422   Event event(Event::MUTEX_CREATE, &m);
423   impl_->send(&event);
424 }
425 
426 void ScopedThread::Destroy(const Mutex &m) {
427   Event event(Event::MUTEX_DESTROY, &m);
428   impl_->send(&event);
429 }
430 
431 void ScopedThread::Lock(const Mutex &m) {
432   Event event(Event::MUTEX_LOCK, &m);
433   impl_->send(&event);
434 }
435 
436 bool ScopedThread::TryLock(const Mutex &m) {
437   Event event(Event::MUTEX_TRYLOCK, &m);
438   impl_->send(&event);
439   return event.res;
440 }
441 
442 void ScopedThread::Unlock(const Mutex &m) {
443   Event event(Event::MUTEX_UNLOCK, &m);
444   impl_->send(&event);
445 }
446 
447 void ScopedThread::ReadLock(const Mutex &m) {
448   Event event(Event::MUTEX_READLOCK, &m);
449   impl_->send(&event);
450 }
451 
452 bool ScopedThread::TryReadLock(const Mutex &m) {
453   Event event(Event::MUTEX_TRYREADLOCK, &m);
454   impl_->send(&event);
455   return event.res;
456 }
457 
458 void ScopedThread::ReadUnlock(const Mutex &m) {
459   Event event(Event::MUTEX_READUNLOCK, &m);
460   impl_->send(&event);
461 }
462 
463 void ScopedThread::Memcpy(void *dst, const void *src, int size,
464                           bool expect_race) {
465   Event event(Event::MEMCPY, dst, (uptr)src, size);
466   if (expect_race)
467     event.ExpectReport(ReportTypeRace);
468   impl_->send(&event);
469 }
470 
471 void ScopedThread::Memset(void *dst, int val, int size,
472                           bool expect_race) {
473   Event event(Event::MEMSET, dst, val, size);
474   if (expect_race)
475     event.ExpectReport(ReportTypeRace);
476   impl_->send(&event);
477 }
478