xref: /llvm-project/compiler-rt/test/safestack/pthread-cleanup.c (revision 7d644e1215b376ec5e915df9ea2eeb56e2d94626)
1 // RUN: %clang_safestack %s -pthread -o %t
2 // RUN: %run %t 0
3 // RUN: not --crash %run %t 1
4 
5 // Test unsafe stack deallocation. Unsafe stacks are not deallocated immediately
6 // at thread exit. They are deallocated by following exiting threads.
7 
8 #include <stdlib.h>
9 #include <string.h>
10 #include <pthread.h>
11 
12 enum { kBufferSize = (1 << 15) };
13 
start(void * ptr)14 void *start(void *ptr)
15 {
16   char buffer[kBufferSize];
17   return buffer;
18 }
19 
20 extern unsigned sleep(unsigned seconds);
21 
main(int argc,char ** argv)22 int main(int argc, char **argv)
23 {
24   int arg = atoi(argv[1]);
25 
26   pthread_t t1, t2;
27   char *t1_buffer = NULL;
28 
29   if (pthread_create(&t1, NULL, start, NULL))
30     abort();
31   if (pthread_join(t1, &t1_buffer))
32     abort();
33 
34   // Stack has not yet been deallocated
35   memset(t1_buffer, 0, kBufferSize);
36 
37   if (arg == 0)
38     return 0;
39 
40   for (int i = 0; i < 3; i++) {
41     if (pthread_create(&t2, NULL, start, NULL))
42       abort();
43     // Second thread destructor cleans up the first thread's stack.
44     if (pthread_join(t2, NULL))
45       abort();
46 
47     // Should segfault here
48     memset(t1_buffer, 0, kBufferSize);
49 
50     // PR39001: Re-try in the rare case that pthread_join() returns before the
51     // thread finishes exiting in the kernel--hence the tgkill() check for t1
52     // returns that it's alive despite pthread_join() returning.
53     sleep(1);
54   }
55   return 0;
56 }
57