blob: 43366fdf70cbf06ea27df1ccb725ef4542e5054b [file] [log] [blame]
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -07001//===-- safestack.cc ------------------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the runtime support for the safe stack protection
11// mechanism. The runtime manages allocation/deallocation of the unsafe stack
12// for the main thread, as well as all pthreads that are created/destroyed
13// during program execution.
14//
15//===----------------------------------------------------------------------===//
16
17#include <limits.h>
18#include <pthread.h>
19#include <stddef.h>
20#include <sys/resource.h>
21#include <sys/user.h>
22
23#include "interception/interception.h"
24#include "sanitizer_common/sanitizer_common.h"
25
26// TODO: The runtime library does not currently protect the safe stack. The
27// protection of the (safe) stack can be provided by two alternative features
28// that requires C library support:
29//
30// 1) Protection via hardware segmentation on x32 architectures: the (safe)
31// stack segment (implicitly accessed via the %ss segment register) can be
32// separated from the data segment (implicitly accessed via the %ds segment
33// register). Dereferencing a pointer to the safe segment would result in a
34// segmentation fault.
35//
36// 2) Protection via information hiding on 64 bit architectures: the location of
37// the safe stack can be randomized through secure mechanisms, and the leakage
38// of the stack pointer can be prevented. Currently, libc can leak the stack
39// pointer in several ways (e.g. in longjmp, signal handling, user-level context
40// switching related functions, etc.). These can be fixed in libc and in other
41// low-level libraries, by either eliminating the escaping/dumping of the stack
42// pointer (i.e., %rsp) when that's possible, or by using encryption/PTR_MANGLE
43// (XOR-ing the dumped stack pointer with another secret we control and protect
44// better). (This is already done for setjmp in glibc.) Furthermore, a static
45// machine code level verifier can be ran after code generation to make sure
46// that the stack pointer is never written to memory, or if it is, its written
47// on the safe stack.
48//
49// Finally, while the Unsafe Stack pointer is currently stored in a thread local
50// variable, with libc support it could be stored in the TCB (thread control
51// block) as well, eliminating another level of indirection. Alternatively,
52// dedicating a separate register for storing it would also be possible.
53
54/// Minimum stack alignment for the unsafe stack.
55const unsigned kStackAlign = 16;
56
57/// Default size of the unsafe stack. This value is only used if the stack
58/// size rlimit is set to infinity.
59const unsigned kDefaultUnsafeStackSize = 0x2800000;
60
61// TODO: To make accessing the unsafe stack pointer faster, we plan to
62// eventually store it directly in the thread control block data structure on
63// platforms where this structure is pointed to by %fs or %gs. This is exactly
64// the same mechanism as currently being used by the traditional stack
65// protector pass to store the stack guard (see getStackCookieLocation()
66// function above). Doing so requires changing the tcbhead_t struct in glibc
67// on Linux and tcb struct in libc on FreeBSD.
68//
69// For now, store it in a thread-local variable.
70extern "C" {
71__attribute__((visibility(
72 "default"))) __thread void *__safestack_unsafe_stack_ptr = nullptr;
73}
74
75// Per-thread unsafe stack information. It's not frequently accessed, so there
76// it can be kept out of the tcb in normal thread-local variables.
77static __thread void *unsafe_stack_start = nullptr;
78static __thread size_t unsafe_stack_size = 0;
79static __thread size_t unsafe_stack_guard = 0;
80
81static inline void *unsafe_stack_alloc(size_t size, size_t guard) {
82 CHECK_GE(size + guard, size);
83 void *addr = MmapOrDie(size + guard, "unsafe_stack_alloc");
84 MprotectNoAccess((uptr)addr, (uptr)guard);
85 return (char *)addr + guard;
86}
87
88static inline void unsafe_stack_setup(void *start, size_t size, size_t guard) {
89 CHECK_GE((char *)start + size, (char *)start);
90 CHECK_GE((char *)start + guard, (char *)start);
91 void *stack_ptr = (char *)start + size;
92 CHECK_EQ((((size_t)stack_ptr) & (kStackAlign - 1)), 0);
93
94 __safestack_unsafe_stack_ptr = stack_ptr;
95 unsafe_stack_start = start;
96 unsafe_stack_size = size;
97 unsafe_stack_guard = guard;
98}
99
100static void unsafe_stack_free() {
101 if (unsafe_stack_start) {
102 UnmapOrDie((char *)unsafe_stack_start - unsafe_stack_guard,
103 unsafe_stack_size + unsafe_stack_guard);
104 }
105 unsafe_stack_start = nullptr;
106}
107
108/// Thread data for the cleanup handler
109static pthread_key_t thread_cleanup_key;
110
111/// Safe stack per-thread information passed to the thread_start function
112struct tinfo {
113 void *(*start_routine)(void *);
114 void *start_routine_arg;
115
116 void *unsafe_stack_start;
117 size_t unsafe_stack_size;
118 size_t unsafe_stack_guard;
119};
120
121/// Wrap the thread function in order to deallocate the unsafe stack when the
122/// thread terminates by returning from its main function.
123static void *thread_start(void *arg) {
124 struct tinfo *tinfo = (struct tinfo *)arg;
125
126 void *(*start_routine)(void *) = tinfo->start_routine;
127 void *start_routine_arg = tinfo->start_routine_arg;
128
129 // Setup the unsafe stack; this will destroy tinfo content
130 unsafe_stack_setup(tinfo->unsafe_stack_start, tinfo->unsafe_stack_size,
131 tinfo->unsafe_stack_guard);
132
133 // Make sure out thread-specific destructor will be called
134 // FIXME: we can do this only any other specific key is set by
135 // intercepting the pthread_setspecific function itself
136 pthread_setspecific(thread_cleanup_key, (void *)1);
137
138 return start_routine(start_routine_arg);
139}
140
141/// Thread-specific data destructor
142static void thread_cleanup_handler(void *_iter) {
143 // We want to free the unsafe stack only after all other destructors
144 // have already run. We force this function to be called multiple times.
145 // User destructors that might run more then PTHREAD_DESTRUCTOR_ITERATIONS-1
146 // times might still end up executing after the unsafe stack is deallocated.
147 size_t iter = (size_t)_iter;
148 if (iter < PTHREAD_DESTRUCTOR_ITERATIONS) {
149 pthread_setspecific(thread_cleanup_key, (void *)(iter + 1));
150 } else {
151 // This is the last iteration
152 unsafe_stack_free();
153 }
154}
155
156/// Intercept thread creation operation to allocate and setup the unsafe stack
157INTERCEPTOR(int, pthread_create, pthread_t *thread,
158 const pthread_attr_t *attr,
159 void *(*start_routine)(void*), void *arg) {
160
161 size_t size = 0;
162 size_t guard = 0;
163
164 if (attr != NULL) {
165 pthread_attr_getstacksize(attr, &size);
166 pthread_attr_getguardsize(attr, &guard);
167 } else {
168 // get pthread default stack size
169 pthread_attr_t tmpattr;
170 pthread_attr_init(&tmpattr);
171 pthread_attr_getstacksize(&tmpattr, &size);
172 pthread_attr_getguardsize(&tmpattr, &guard);
173 pthread_attr_destroy(&tmpattr);
174 }
175
176 CHECK_NE(size, 0);
177 CHECK_EQ((size & (kStackAlign - 1)), 0);
178 CHECK_EQ((guard & (PAGE_SIZE - 1)), 0);
179
180 void *addr = unsafe_stack_alloc(size, guard);
181 struct tinfo *tinfo =
182 (struct tinfo *)(((char *)addr) + size - sizeof(struct tinfo));
183 tinfo->start_routine = start_routine;
184 tinfo->start_routine_arg = arg;
185 tinfo->unsafe_stack_start = addr;
186 tinfo->unsafe_stack_size = size;
187 tinfo->unsafe_stack_guard = guard;
188
189 return REAL(pthread_create)(thread, attr, thread_start, tinfo);
190}
191
192extern "C" __attribute__((visibility("default")))
193#if !SANITIZER_CAN_USE_PREINIT_ARRAY
194// On ELF platforms, the constructor is invoked using .preinit_array (see below)
195__attribute__((constructor(0)))
196#endif
197void __safestack_init() {
198 // Determine the stack size for the main thread.
199 size_t size = kDefaultUnsafeStackSize;
200 size_t guard = 4096;
201
202 struct rlimit limit;
203 if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY)
204 size = limit.rlim_cur;
205
206 // Allocate unsafe stack for main thread
207 void *addr = unsafe_stack_alloc(size, guard);
208
209 unsafe_stack_setup(addr, size, guard);
210
211 // Initialize pthread interceptors for thread allocation
212 INTERCEPT_FUNCTION(pthread_create);
213
214 // Setup the cleanup handler
215 pthread_key_create(&thread_cleanup_key, thread_cleanup_handler);
216}
217
218#if SANITIZER_CAN_USE_PREINIT_ARRAY
219// On ELF platforms, run safestack initialization before any other constructors.
220// On other platforms we use the constructor attribute to arrange to run our
221// initialization early.
222extern "C" {
223__attribute__((section(".preinit_array"),
224 used)) void (*__safestack_preinit)(void) = __safestack_init;
225}
226#endif
227
228extern "C"
229 __attribute__((visibility("default"))) void *__get_unsafe_stack_start() {
230 return unsafe_stack_start;
231}
232
233extern "C"
234 __attribute__((visibility("default"))) void *__get_unsafe_stack_ptr() {
235 return __safestack_unsafe_stack_ptr;
236}