]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/safestack/safestack.cc
Merge ^/head r338731 through r338987.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / safestack / safestack.cc
1 //===-- 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 <stdint.h>
21 #include <unistd.h>
22 #include <sys/resource.h>
23 #include <sys/types.h>
24 #if !defined(__NetBSD__)
25 #include <sys/user.h>
26 #endif
27
28 #include "interception/interception.h"
29 #include "sanitizer_common/sanitizer_common.h"
30
31 // TODO: The runtime library does not currently protect the safe stack beyond
32 // relying on the system-enforced ASLR. The protection of the (safe) stack can
33 // be provided by three alternative features:
34 //
35 // 1) Protection via hardware segmentation on x86-32 and some x86-64
36 // architectures: the (safe) stack segment (implicitly accessed via the %ss
37 // segment register) can be separated from the data segment (implicitly
38 // accessed via the %ds segment register). Dereferencing a pointer to the safe
39 // segment would result in a segmentation fault.
40 //
41 // 2) Protection via software fault isolation: memory writes that are not meant
42 // to access the safe stack can be prevented from doing so through runtime
43 // instrumentation. One way to do it is to allocate the safe stack(s) in the
44 // upper half of the userspace and bitmask the corresponding upper bit of the
45 // memory addresses of memory writes that are not meant to access the safe
46 // stack.
47 //
48 // 3) Protection via information hiding on 64 bit architectures: the location
49 // of the safe stack(s) can be randomized through secure mechanisms, and the
50 // leakage of the stack pointer can be prevented. Currently, libc can leak the
51 // stack pointer in several ways (e.g. in longjmp, signal handling, user-level
52 // context switching related functions, etc.). These can be fixed in libc and
53 // in other low-level libraries, by either eliminating the escaping/dumping of
54 // the stack pointer (i.e., %rsp) when that's possible, or by using
55 // encryption/PTR_MANGLE (XOR-ing the dumped stack pointer with another secret
56 // we control and protect better, as is already done for setjmp in glibc.)
57 // Furthermore, a static machine code level verifier can be ran after code
58 // generation to make sure that the stack pointer is never written to memory,
59 // or if it is, its written on the safe stack.
60 //
61 // Finally, while the Unsafe Stack pointer is currently stored in a thread
62 // local variable, with libc support it could be stored in the TCB (thread
63 // control block) as well, eliminating another level of indirection and making
64 // such accesses faster. Alternatively, dedicating a separate register for
65 // storing it would also be possible.
66
67 /// Minimum stack alignment for the unsafe stack.
68 const unsigned kStackAlign = 16;
69
70 /// Default size of the unsafe stack. This value is only used if the stack
71 /// size rlimit is set to infinity.
72 const unsigned kDefaultUnsafeStackSize = 0x2800000;
73
74 /// Runtime page size obtained through sysconf
75 static unsigned pageSize;
76
77 // TODO: To make accessing the unsafe stack pointer faster, we plan to
78 // eventually store it directly in the thread control block data structure on
79 // platforms where this structure is pointed to by %fs or %gs. This is exactly
80 // the same mechanism as currently being used by the traditional stack
81 // protector pass to store the stack guard (see getStackCookieLocation()
82 // function above). Doing so requires changing the tcbhead_t struct in glibc
83 // on Linux and tcb struct in libc on FreeBSD.
84 //
85 // For now, store it in a thread-local variable.
86 extern "C" {
87 __attribute__((visibility(
88     "default"))) __thread void *__safestack_unsafe_stack_ptr = nullptr;
89 }
90
91 // Per-thread unsafe stack information. It's not frequently accessed, so there
92 // it can be kept out of the tcb in normal thread-local variables.
93 static __thread void *unsafe_stack_start = nullptr;
94 static __thread size_t unsafe_stack_size = 0;
95 static __thread size_t unsafe_stack_guard = 0;
96
97 using namespace __sanitizer;
98
99 static inline void *unsafe_stack_alloc(size_t size, size_t guard) {
100   CHECK_GE(size + guard, size);
101   void *addr = MmapOrDie(size + guard, "unsafe_stack_alloc");
102   MprotectNoAccess((uptr)addr, (uptr)guard);
103   return (char *)addr + guard;
104 }
105
106 static inline void unsafe_stack_setup(void *start, size_t size, size_t guard) {
107   CHECK_GE((char *)start + size, (char *)start);
108   CHECK_GE((char *)start + guard, (char *)start);
109   void *stack_ptr = (char *)start + size;
110   CHECK_EQ((((size_t)stack_ptr) & (kStackAlign - 1)), 0);
111
112   __safestack_unsafe_stack_ptr = stack_ptr;
113   unsafe_stack_start = start;
114   unsafe_stack_size = size;
115   unsafe_stack_guard = guard;
116 }
117
118 static void unsafe_stack_free() {
119   if (unsafe_stack_start) {
120     UnmapOrDie((char *)unsafe_stack_start - unsafe_stack_guard,
121                unsafe_stack_size + unsafe_stack_guard);
122   }
123   unsafe_stack_start = nullptr;
124 }
125
126 /// Thread data for the cleanup handler
127 static pthread_key_t thread_cleanup_key;
128
129 /// Safe stack per-thread information passed to the thread_start function
130 struct tinfo {
131   void *(*start_routine)(void *);
132   void *start_routine_arg;
133
134   void *unsafe_stack_start;
135   size_t unsafe_stack_size;
136   size_t unsafe_stack_guard;
137 };
138
139 /// Wrap the thread function in order to deallocate the unsafe stack when the
140 /// thread terminates by returning from its main function.
141 static void *thread_start(void *arg) {
142   struct tinfo *tinfo = (struct tinfo *)arg;
143
144   void *(*start_routine)(void *) = tinfo->start_routine;
145   void *start_routine_arg = tinfo->start_routine_arg;
146
147   // Setup the unsafe stack; this will destroy tinfo content
148   unsafe_stack_setup(tinfo->unsafe_stack_start, tinfo->unsafe_stack_size,
149                      tinfo->unsafe_stack_guard);
150
151   // Make sure out thread-specific destructor will be called
152   // FIXME: we can do this only any other specific key is set by
153   // intercepting the pthread_setspecific function itself
154   pthread_setspecific(thread_cleanup_key, (void *)1);
155
156   return start_routine(start_routine_arg);
157 }
158
159 /// Thread-specific data destructor
160 static void thread_cleanup_handler(void *_iter) {
161   // We want to free the unsafe stack only after all other destructors
162   // have already run. We force this function to be called multiple times.
163   // User destructors that might run more then PTHREAD_DESTRUCTOR_ITERATIONS-1
164   // times might still end up executing after the unsafe stack is deallocated.
165   size_t iter = (size_t)_iter;
166   if (iter < PTHREAD_DESTRUCTOR_ITERATIONS) {
167     pthread_setspecific(thread_cleanup_key, (void *)(iter + 1));
168   } else {
169     // This is the last iteration
170     unsafe_stack_free();
171   }
172 }
173
174 static void EnsureInterceptorsInitialized();
175
176 /// Intercept thread creation operation to allocate and setup the unsafe stack
177 INTERCEPTOR(int, pthread_create, pthread_t *thread,
178             const pthread_attr_t *attr,
179             void *(*start_routine)(void*), void *arg) {
180   EnsureInterceptorsInitialized();
181   size_t size = 0;
182   size_t guard = 0;
183
184   if (attr) {
185     pthread_attr_getstacksize(attr, &size);
186     pthread_attr_getguardsize(attr, &guard);
187   } else {
188     // get pthread default stack size
189     pthread_attr_t tmpattr;
190     pthread_attr_init(&tmpattr);
191     pthread_attr_getstacksize(&tmpattr, &size);
192     pthread_attr_getguardsize(&tmpattr, &guard);
193     pthread_attr_destroy(&tmpattr);
194   }
195
196   CHECK_NE(size, 0);
197   CHECK_EQ((size & (kStackAlign - 1)), 0);
198   CHECK_EQ((guard & (pageSize - 1)), 0);
199
200   void *addr = unsafe_stack_alloc(size, guard);
201   struct tinfo *tinfo =
202       (struct tinfo *)(((char *)addr) + size - sizeof(struct tinfo));
203   tinfo->start_routine = start_routine;
204   tinfo->start_routine_arg = arg;
205   tinfo->unsafe_stack_start = addr;
206   tinfo->unsafe_stack_size = size;
207   tinfo->unsafe_stack_guard = guard;
208
209   return REAL(pthread_create)(thread, attr, thread_start, tinfo);
210 }
211
212 static BlockingMutex interceptor_init_lock(LINKER_INITIALIZED);
213 static bool interceptors_inited = false;
214
215 static void EnsureInterceptorsInitialized() {
216   BlockingMutexLock lock(&interceptor_init_lock);
217   if (interceptors_inited) return;
218
219   // Initialize pthread interceptors for thread allocation
220   INTERCEPT_FUNCTION(pthread_create);
221
222   interceptors_inited = true;
223 }
224
225 extern "C" __attribute__((visibility("default")))
226 #if !SANITIZER_CAN_USE_PREINIT_ARRAY
227 // On ELF platforms, the constructor is invoked using .preinit_array (see below)
228 __attribute__((constructor(0)))
229 #endif
230 void __safestack_init() {
231   // Determine the stack size for the main thread.
232   size_t size = kDefaultUnsafeStackSize;
233   size_t guard = 4096;
234
235   struct rlimit limit;
236   if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY)
237     size = limit.rlim_cur;
238
239   // Allocate unsafe stack for main thread
240   void *addr = unsafe_stack_alloc(size, guard);
241
242   unsafe_stack_setup(addr, size, guard);
243   pageSize = sysconf(_SC_PAGESIZE);
244
245   // Setup the cleanup handler
246   pthread_key_create(&thread_cleanup_key, thread_cleanup_handler);
247 }
248
249 #if SANITIZER_CAN_USE_PREINIT_ARRAY
250 // On ELF platforms, run safestack initialization before any other constructors.
251 // On other platforms we use the constructor attribute to arrange to run our
252 // initialization early.
253 extern "C" {
254 __attribute__((section(".preinit_array"),
255                used)) void (*__safestack_preinit)(void) = __safestack_init;
256 }
257 #endif
258
259 extern "C"
260     __attribute__((visibility("default"))) void *__get_unsafe_stack_bottom() {
261   return unsafe_stack_start;
262 }
263
264 extern "C"
265     __attribute__((visibility("default"))) void *__get_unsafe_stack_top() {
266   return (char*)unsafe_stack_start + unsafe_stack_size;
267 }
268
269 extern "C"
270     __attribute__((visibility("default"))) void *__get_unsafe_stack_start() {
271   return unsafe_stack_start;
272 }
273
274 extern "C"
275     __attribute__((visibility("default"))) void *__get_unsafe_stack_ptr() {
276   return __safestack_unsafe_stack_ptr;
277 }