[C++] ThreadSanitizer
ThreadSanitizer is a data race detector for C/C++. Data races are one of the most common and hardest to debug types of bugs in concurrent systems.
Here is an example of a data race that can lead to crashes and memory corruptions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <pthread.h> #include <stdio.h> int Global; void *Thread1(void *x) { Global++; return NULL; } void *Thread2(void *x) { Global--; return NULL; } int main() { pthread_t t[2]; pthread_create(&t[0], NULL, Thread1, NULL); pthread_create(&t[1], NULL, Thread2, NULL); pthread_join(t[0], NULL); pthread_join(t[1], NULL); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
$ clang++ simple_race.cpp -fsanitize=thread -fPIE -pie -g $ ./a.out ================== WARNING: ThreadSanitizer: data race (pid=36804) Write of size 4 at 0x0001062b7068 by thread T2: * #0 Thread2(void*) simple_race.cpp:12 (a.out:x86_64+0x100000d8a) Previous write of size 4 at 0x0001062b7068 by thread T1: * #0 Thread1(void*) simple_race.cpp:7 (a.out:x86_64+0x100000d2a) Issue is caused by frames marked with "*". Location is global 'Global' at 0x0001062b7068 (a.out+0x000100001068) Thread T2 (tid=817154, running) created by main thread at: #0 pthread_create <null>:1600736 (libclang_rt.tsan_osx_dynamic.dylib:x86_64h+0x2a34d) #1 main simple_race.cpp:19 (a.out:x86_64+0x100000e07) Thread T1 (tid=817153, finished) created by main thread at: #0 pthread_create <null>:1600736 (libclang_rt.tsan_osx_dynamic.dylib:x86_64h+0x2a34d) #1 main simple_race.cpp:18 (a.out:x86_64+0x100000de8) SUMMARY: ThreadSanitizer: data race simple_race.cpp:12 in Thread2(void*) ================== ThreadSanitizer: reported 1 warnings Abort trap: 6 |