1*7c3d14c8STreehugger Robot // Test that the deadlock detector can find a deadlock that actually happened.
2*7c3d14c8STreehugger Robot // Currently we will fail to report such a deadlock because we check for
3*7c3d14c8STreehugger Robot // cycles in lock-order graph after pthread_mutex_lock.
4*7c3d14c8STreehugger Robot
5*7c3d14c8STreehugger Robot // RUN: %clangxx_tsan %s -o %t
6*7c3d14c8STreehugger Robot // RUN: not %run %t 2>&1 | FileCheck %s
7*7c3d14c8STreehugger Robot // XFAIL: *
8*7c3d14c8STreehugger Robot #include <pthread.h>
9*7c3d14c8STreehugger Robot #include <stdio.h>
10*7c3d14c8STreehugger Robot #include <unistd.h>
11*7c3d14c8STreehugger Robot
12*7c3d14c8STreehugger Robot pthread_mutex_t mu1, mu2;
13*7c3d14c8STreehugger Robot pthread_barrier_t barrier;
14*7c3d14c8STreehugger Robot
Thread(void * p)15*7c3d14c8STreehugger Robot void *Thread(void *p) {
16*7c3d14c8STreehugger Robot // mu2 => mu1
17*7c3d14c8STreehugger Robot pthread_mutex_lock(&mu2);
18*7c3d14c8STreehugger Robot pthread_barrier_wait(&barrier);
19*7c3d14c8STreehugger Robot pthread_mutex_lock(&mu1);
20*7c3d14c8STreehugger Robot // CHECK: ThreadSanitizer: lock-order-inversion (potential deadlock)
21*7c3d14c8STreehugger Robot pthread_mutex_unlock(&mu1);
22*7c3d14c8STreehugger Robot pthread_mutex_unlock(&mu2);
23*7c3d14c8STreehugger Robot return p;
24*7c3d14c8STreehugger Robot }
25*7c3d14c8STreehugger Robot
main()26*7c3d14c8STreehugger Robot int main() {
27*7c3d14c8STreehugger Robot pthread_mutex_init(&mu1, NULL);
28*7c3d14c8STreehugger Robot pthread_mutex_init(&mu2, NULL);
29*7c3d14c8STreehugger Robot pthread_barrier_init(&barrier, 0, 2);
30*7c3d14c8STreehugger Robot
31*7c3d14c8STreehugger Robot fprintf(stderr, "This test is going to deadlock and die in 3 seconds\n");
32*7c3d14c8STreehugger Robot alarm(3);
33*7c3d14c8STreehugger Robot
34*7c3d14c8STreehugger Robot pthread_t t;
35*7c3d14c8STreehugger Robot pthread_create(&t, 0, Thread, 0);
36*7c3d14c8STreehugger Robot
37*7c3d14c8STreehugger Robot // mu1 => mu2
38*7c3d14c8STreehugger Robot pthread_mutex_lock(&mu1);
39*7c3d14c8STreehugger Robot pthread_barrier_wait(&barrier);
40*7c3d14c8STreehugger Robot pthread_mutex_lock(&mu2);
41*7c3d14c8STreehugger Robot pthread_mutex_unlock(&mu2);
42*7c3d14c8STreehugger Robot pthread_mutex_unlock(&mu1);
43*7c3d14c8STreehugger Robot
44*7c3d14c8STreehugger Robot pthread_join(t, 0);
45*7c3d14c8STreehugger Robot
46*7c3d14c8STreehugger Robot pthread_mutex_destroy(&mu1);
47*7c3d14c8STreehugger Robot pthread_mutex_destroy(&mu2);
48*7c3d14c8STreehugger Robot pthread_barrier_destroy(&barrier);
49*7c3d14c8STreehugger Robot fprintf(stderr, "FAILED\n");
50*7c3d14c8STreehugger Robot }
51