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
12enum { kBufferSize = (1 << 15) };
13
14void *start(void *ptr)
15{
16 char buffer[kBufferSize];
17 return buffer;
18}
19
20extern unsigned sleep(unsigned seconds);
21
22int main(int argc, char **argv)
23{
24 int arg = atoi(nptr: argv[1]);
25
26 pthread_t t1, t2;
27 char *t1_buffer = NULL;
28
29 if (pthread_create(newthread: &t1, NULL, start_routine: start, NULL))
30 abort();
31 if (pthread_join(th: t1, thread_return: &t1_buffer))
32 abort();
33
34 // Stack has not yet been deallocated
35 memset(s: t1_buffer, c: 0, n: kBufferSize);
36
37 if (arg == 0)
38 return 0;
39
40 for (int i = 0; i < 3; i++) {
41 if (pthread_create(newthread: &t2, NULL, start_routine: start, NULL))
42 abort();
43 // Second thread destructor cleans up the first thread's stack.
44 if (pthread_join(th: t2, NULL))
45 abort();
46
47 // Should segfault here
48 memset(s: t1_buffer, c: 0, n: 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(seconds: 1);
54 }
55 return 0;
56}
57

source code of compiler-rt/test/safestack/pthread-cleanup.c