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
main(int argc,char ** argv)20 int main(int argc, char **argv)
21 {
22 int arg = atoi(argv[1]);
23
24 pthread_t t1, t2;
25 char *t1_buffer = NULL;
26
27 if (pthread_create(&t1, NULL, start, NULL))
28 abort();
29 if (pthread_join(t1, &t1_buffer))
30 abort();
31
32 // Stack has not yet been deallocated
33 memset(t1_buffer, 0, kBufferSize);
34
35 if (arg == 0)
36 return 0;
37
38 for (int i = 0; i < 3; i++) {
39 if (pthread_create(&t2, NULL, start, NULL))
40 abort();
41 // Second thread destructor cleans up the first thread's stack.
42 if (pthread_join(t2, NULL))
43 abort();
44
45 // Should segfault here
46 memset(t1_buffer, 0, kBufferSize);
47
48 // PR39001: Re-try in the rare case that pthread_join() returns before the
49 // thread finishes exiting in the kernel--hence the tgkill() check for t1
50 // returns that it's alive despite pthread_join() returning.
51 sleep(1);
52 }
53 return 0;
54 }
55