• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *  * Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *  * Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in
12  *    the documentation and/or other materials provided with the
13  *    distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include "private/bionic_elf_tls.h"
30 
31 #include <async_safe/CHECK.h>
32 #include <async_safe/log.h>
33 #include <string.h>
34 #include <sys/param.h>
35 #include <unistd.h>
36 
37 #include "private/ScopedRWLock.h"
38 #include "private/ScopedSignalBlocker.h"
39 #include "private/bionic_globals.h"
40 #include "platform/bionic/macros.h"
41 #include "private/bionic_tls.h"
42 #include "pthread_internal.h"
43 
44 // Every call to __tls_get_addr needs to check the generation counter, so
45 // accesses to the counter need to be as fast as possible. Keep a copy of it in
46 // a hidden variable, which can be accessed without using the GOT. The linker
47 // will update this variable when it updates its counter.
48 //
49 // To allow the linker to update this variable, libc.so's constructor passes its
50 // address to the linker. To accommodate a possible __tls_get_addr call before
51 // libc.so's constructor, this local copy is initialized to SIZE_MAX, forcing
52 // __tls_get_addr to initially use the slow path.
53 __LIBC_HIDDEN__ _Atomic(size_t) __libc_tls_generation_copy = SIZE_MAX;
54 
55 // Search for a TLS segment in the given phdr table. Returns true if it has a
56 // TLS segment and false otherwise.
__bionic_get_tls_segment(const ElfW (Phdr)* phdr_table,size_t phdr_count,ElfW (Addr)load_bias,TlsSegment * out)57 bool __bionic_get_tls_segment(const ElfW(Phdr)* phdr_table, size_t phdr_count,
58                               ElfW(Addr) load_bias, TlsSegment* out) {
59   for (size_t i = 0; i < phdr_count; ++i) {
60     const ElfW(Phdr)& phdr = phdr_table[i];
61     if (phdr.p_type == PT_TLS) {
62       *out = TlsSegment {
63         phdr.p_memsz,
64         phdr.p_align,
65         reinterpret_cast<void*>(load_bias + phdr.p_vaddr),
66         phdr.p_filesz,
67       };
68       return true;
69     }
70   }
71   return false;
72 }
73 
74 // Return true if the alignment of a TLS segment is a valid power-of-two. Also
75 // cap the alignment if it's too high.
__bionic_check_tls_alignment(size_t * alignment)76 bool __bionic_check_tls_alignment(size_t* alignment) {
77   // N.B. The size does not need to be a multiple of the alignment. With
78   // ld.bfd (or after using binutils' strip), the TLS segment's size isn't
79   // rounded up.
80   if (*alignment == 0 || !powerof2(*alignment)) {
81     return false;
82   }
83   // Bionic only respects TLS alignment up to one page.
84   *alignment = MIN(*alignment, PAGE_SIZE);
85   return true;
86 }
87 
offset_thread_pointer() const88 size_t StaticTlsLayout::offset_thread_pointer() const {
89   return offset_bionic_tcb_ + (-MIN_TLS_SLOT * sizeof(void*));
90 }
91 
92 // Reserves space for the Bionic TCB and the executable's TLS segment. Returns
93 // the offset of the executable's TLS segment.
reserve_exe_segment_and_tcb(const TlsSegment * exe_segment,const char * progname)94 size_t StaticTlsLayout::reserve_exe_segment_and_tcb(const TlsSegment* exe_segment,
95                                                     const char* progname __attribute__((unused))) {
96   // Special case: if the executable has no TLS segment, then just allocate a
97   // TCB and skip the minimum alignment check on ARM.
98   if (exe_segment == nullptr) {
99     offset_bionic_tcb_ = reserve_type<bionic_tcb>();
100     return 0;
101   }
102 
103 #if defined(__arm__) || defined(__aarch64__)
104 
105   // First reserve enough space for the TCB before the executable segment.
106   reserve(sizeof(bionic_tcb), 1);
107 
108   // Then reserve the segment itself.
109   const size_t result = reserve(exe_segment->size, exe_segment->alignment);
110 
111   // The variant 1 ABI that ARM linkers follow specifies a 2-word TCB between
112   // the thread pointer and the start of the executable's TLS segment, but both
113   // the thread pointer and the TLS segment are aligned appropriately for the
114   // TLS segment. Calculate the distance between the thread pointer and the
115   // EXE's segment.
116   const size_t exe_tpoff = __BIONIC_ALIGN(sizeof(void*) * 2, exe_segment->alignment);
117 
118   const size_t min_bionic_alignment = BIONIC_ROUND_UP_POWER_OF_2(MAX_TLS_SLOT) * sizeof(void*);
119   if (exe_tpoff < min_bionic_alignment) {
120     async_safe_fatal("error: \"%s\": executable's TLS segment is underaligned: "
121                      "alignment is %zu, needs to be at least %zu for %s Bionic",
122                      progname, exe_segment->alignment, min_bionic_alignment,
123                      (sizeof(void*) == 4 ? "ARM" : "ARM64"));
124   }
125 
126   offset_bionic_tcb_ = result - exe_tpoff - (-MIN_TLS_SLOT * sizeof(void*));
127   return result;
128 
129 #elif defined(__i386__) || defined(__x86_64__)
130 
131   // x86 uses variant 2 TLS layout. The executable's segment is located just
132   // before the TCB.
133   static_assert(MIN_TLS_SLOT == 0, "First slot of bionic_tcb must be slot #0 on x86");
134   const size_t exe_size = round_up_with_overflow_check(exe_segment->size, exe_segment->alignment);
135   reserve(exe_size, 1);
136   const size_t max_align = MAX(alignof(bionic_tcb), exe_segment->alignment);
137   offset_bionic_tcb_ = reserve(sizeof(bionic_tcb), max_align);
138   return offset_bionic_tcb_ - exe_size;
139 
140 #elif defined(__riscv)
141 
142   // First reserve enough space for the TCB before the executable segment.
143   offset_bionic_tcb_ = reserve(sizeof(bionic_tcb), 1);
144 
145   // Then reserve the segment itself.
146   const size_t exe_size = round_up_with_overflow_check(exe_segment->size, exe_segment->alignment);
147   return reserve(exe_size, 1);
148 
149 #else
150 #error "Unrecognized architecture"
151 #endif
152 }
153 
reserve_bionic_tls()154 void StaticTlsLayout::reserve_bionic_tls() {
155   offset_bionic_tls_ = reserve_type<bionic_tls>();
156 }
157 
finish_layout()158 void StaticTlsLayout::finish_layout() {
159   // Round the offset up to the alignment.
160   offset_ = round_up_with_overflow_check(offset_, alignment_);
161 
162   if (overflowed_) {
163     async_safe_fatal("error: TLS segments in static TLS overflowed");
164   }
165 }
166 
167 // The size is not required to be a multiple of the alignment. The alignment
168 // must be a positive power-of-two.
reserve(size_t size,size_t alignment)169 size_t StaticTlsLayout::reserve(size_t size, size_t alignment) {
170   offset_ = round_up_with_overflow_check(offset_, alignment);
171   const size_t result = offset_;
172   if (__builtin_add_overflow(offset_, size, &offset_)) overflowed_ = true;
173   alignment_ = MAX(alignment_, alignment);
174   return result;
175 }
176 
round_up_with_overflow_check(size_t value,size_t alignment)177 size_t StaticTlsLayout::round_up_with_overflow_check(size_t value, size_t alignment) {
178   const size_t old_value = value;
179   value = __BIONIC_ALIGN(value, alignment);
180   if (value < old_value) overflowed_ = true;
181   return value;
182 }
183 
184 // Copy each TLS module's initialization image into a newly-allocated block of
185 // static TLS memory. To reduce dirty pages, this function only writes to pages
186 // within the static TLS that need initialization. The memory should already be
187 // zero-initialized on entry.
__init_static_tls(void * static_tls)188 void __init_static_tls(void* static_tls) {
189   // The part of the table we care about (i.e. static TLS modules) never changes
190   // after startup, but we still need the mutex because the table could grow,
191   // moving the initial part. If this locking is too slow, we can duplicate the
192   // static part of the table.
193   TlsModules& modules = __libc_shared_globals()->tls_modules;
194   ScopedSignalBlocker ssb;
195   ScopedReadLock locker(&modules.rwlock);
196 
197   for (size_t i = 0; i < modules.module_count; ++i) {
198     TlsModule& module = modules.module_table[i];
199     if (module.static_offset == SIZE_MAX) {
200       // All of the static modules come before all of the dynamic modules, so
201       // once we see the first dynamic module, we're done.
202       break;
203     }
204     if (module.segment.init_size == 0) {
205       // Skip the memcpy call for TLS segments with no initializer, which is
206       // common.
207       continue;
208     }
209     memcpy(static_cast<char*>(static_tls) + module.static_offset,
210            module.segment.init_ptr,
211            module.segment.init_size);
212   }
213 }
214 
dtv_size_in_bytes(size_t module_count)215 static inline size_t dtv_size_in_bytes(size_t module_count) {
216   return sizeof(TlsDtv) + module_count * sizeof(void*);
217 }
218 
219 // Calculates the number of module slots to allocate in a new DTV. For small
220 // objects (up to 1KiB), the TLS allocator allocates memory in power-of-2 sizes,
221 // so for better space usage, ensure that the DTV size (header + slots) is a
222 // power of 2.
223 //
224 // The lock on TlsModules must be held.
calculate_new_dtv_count()225 static size_t calculate_new_dtv_count() {
226   size_t loaded_cnt = __libc_shared_globals()->tls_modules.module_count;
227   size_t bytes = dtv_size_in_bytes(MAX(1, loaded_cnt));
228   if (!powerof2(bytes)) {
229     bytes = BIONIC_ROUND_UP_POWER_OF_2(bytes);
230   }
231   return (bytes - sizeof(TlsDtv)) / sizeof(void*);
232 }
233 
234 // This function must be called with signals blocked and a write lock on
235 // TlsModules held.
update_tls_dtv(bionic_tcb * tcb)236 static void update_tls_dtv(bionic_tcb* tcb) {
237   const TlsModules& modules = __libc_shared_globals()->tls_modules;
238   BionicAllocator& allocator = __libc_shared_globals()->tls_allocator;
239 
240   // Use the generation counter from the shared globals instead of the local
241   // copy, which won't be initialized yet if __tls_get_addr is called before
242   // libc.so's constructor.
243   if (__get_tcb_dtv(tcb)->generation == atomic_load(&modules.generation)) {
244     return;
245   }
246 
247   const size_t old_cnt = __get_tcb_dtv(tcb)->count;
248 
249   // If the DTV isn't large enough, allocate a larger one. Because a signal
250   // handler could interrupt the fast path of __tls_get_addr, we don't free the
251   // old DTV. Instead, we add the old DTV to a list, then free all of a thread's
252   // DTVs at thread-exit. Each time the DTV is reallocated, its size at least
253   // doubles.
254   if (modules.module_count > old_cnt) {
255     size_t new_cnt = calculate_new_dtv_count();
256     TlsDtv* const old_dtv = __get_tcb_dtv(tcb);
257     TlsDtv* const new_dtv = static_cast<TlsDtv*>(allocator.alloc(dtv_size_in_bytes(new_cnt)));
258     memcpy(new_dtv, old_dtv, dtv_size_in_bytes(old_cnt));
259     new_dtv->count = new_cnt;
260     new_dtv->next = old_dtv;
261     __set_tcb_dtv(tcb, new_dtv);
262   }
263 
264   TlsDtv* const dtv = __get_tcb_dtv(tcb);
265 
266   const StaticTlsLayout& layout = __libc_shared_globals()->static_tls_layout;
267   char* static_tls = reinterpret_cast<char*>(tcb) - layout.offset_bionic_tcb();
268 
269   // Initialize static TLS modules and free unloaded modules.
270   for (size_t i = 0; i < dtv->count; ++i) {
271     if (i < modules.module_count) {
272       const TlsModule& mod = modules.module_table[i];
273       if (mod.static_offset != SIZE_MAX) {
274         dtv->modules[i] = static_tls + mod.static_offset;
275         continue;
276       }
277       if (mod.first_generation != kTlsGenerationNone &&
278           mod.first_generation <= dtv->generation) {
279         continue;
280       }
281     }
282     if (modules.on_destruction_cb != nullptr) {
283       void* dtls_begin = dtv->modules[i];
284       void* dtls_end =
285           static_cast<void*>(static_cast<char*>(dtls_begin) + allocator.get_chunk_size(dtls_begin));
286       modules.on_destruction_cb(dtls_begin, dtls_end);
287     }
288     allocator.free(dtv->modules[i]);
289     dtv->modules[i] = nullptr;
290   }
291 
292   dtv->generation = atomic_load(&modules.generation);
293 }
294 
tls_get_addr_slow_path(const TlsIndex * ti)295 __attribute__((noinline)) static void* tls_get_addr_slow_path(const TlsIndex* ti) {
296   TlsModules& modules = __libc_shared_globals()->tls_modules;
297   bionic_tcb* tcb = __get_bionic_tcb();
298 
299   // Block signals and lock TlsModules. We may need the allocator, so take
300   // a write lock.
301   ScopedSignalBlocker ssb;
302   ScopedWriteLock locker(&modules.rwlock);
303 
304   update_tls_dtv(tcb);
305 
306   TlsDtv* dtv = __get_tcb_dtv(tcb);
307   const size_t module_idx = __tls_module_id_to_idx(ti->module_id);
308   void* mod_ptr = dtv->modules[module_idx];
309   if (mod_ptr == nullptr) {
310     const TlsSegment& segment = modules.module_table[module_idx].segment;
311     mod_ptr = __libc_shared_globals()->tls_allocator.memalign(segment.alignment, segment.size);
312     if (segment.init_size > 0) {
313       memcpy(mod_ptr, segment.init_ptr, segment.init_size);
314     }
315     dtv->modules[module_idx] = mod_ptr;
316 
317     // Reports the allocation to the listener, if any.
318     if (modules.on_creation_cb != nullptr) {
319       modules.on_creation_cb(mod_ptr,
320                              static_cast<void*>(static_cast<char*>(mod_ptr) + segment.size));
321     }
322   }
323 
324   return static_cast<char*>(mod_ptr) + ti->offset + TLS_DTV_OFFSET;
325 }
326 
327 // Returns the address of a thread's TLS memory given a module ID and an offset
328 // into that module's TLS segment. This function is called on every access to a
329 // dynamic TLS variable on targets that don't use TLSDESC. arm64 uses TLSDESC,
330 // so it only calls this function on a thread's first access to a module's TLS
331 // segment.
332 //
333 // On most targets, this accessor function is __tls_get_addr and
334 // TLS_GET_ADDR_CCONV is unset. 32-bit x86 uses ___tls_get_addr instead and a
335 // regparm() calling convention.
TLS_GET_ADDR(const TlsIndex * ti)336 extern "C" void* TLS_GET_ADDR(const TlsIndex* ti) TLS_GET_ADDR_CCONV {
337   TlsDtv* dtv = __get_tcb_dtv(__get_bionic_tcb());
338 
339   // TODO: See if we can use a relaxed memory ordering here instead.
340   size_t generation = atomic_load(&__libc_tls_generation_copy);
341   if (__predict_true(generation == dtv->generation)) {
342     void* mod_ptr = dtv->modules[__tls_module_id_to_idx(ti->module_id)];
343     if (__predict_true(mod_ptr != nullptr)) {
344       return static_cast<char*>(mod_ptr) + ti->offset + TLS_DTV_OFFSET;
345     }
346   }
347 
348   return tls_get_addr_slow_path(ti);
349 }
350 
351 // This function frees:
352 //  - TLS modules referenced by the current DTV.
353 //  - The list of DTV objects associated with the current thread.
354 //
355 // The caller must have already blocked signals.
__free_dynamic_tls(bionic_tcb * tcb)356 void __free_dynamic_tls(bionic_tcb* tcb) {
357   TlsModules& modules = __libc_shared_globals()->tls_modules;
358   BionicAllocator& allocator = __libc_shared_globals()->tls_allocator;
359 
360   // If we didn't allocate any dynamic memory, skip out early without taking
361   // the lock.
362   TlsDtv* dtv = __get_tcb_dtv(tcb);
363   if (dtv->generation == kTlsGenerationNone) {
364     return;
365   }
366 
367   // We need the write lock to use the allocator.
368   ScopedWriteLock locker(&modules.rwlock);
369 
370   // First free everything in the current DTV.
371   for (size_t i = 0; i < dtv->count; ++i) {
372     if (i < modules.module_count && modules.module_table[i].static_offset != SIZE_MAX) {
373       // This module's TLS memory is allocated statically, so don't free it here.
374       continue;
375     }
376 
377     if (modules.on_destruction_cb != nullptr) {
378       void* dtls_begin = dtv->modules[i];
379       void* dtls_end =
380           static_cast<void*>(static_cast<char*>(dtls_begin) + allocator.get_chunk_size(dtls_begin));
381       modules.on_destruction_cb(dtls_begin, dtls_end);
382     }
383 
384     allocator.free(dtv->modules[i]);
385   }
386 
387   // Now free the thread's list of DTVs.
388   while (dtv->generation != kTlsGenerationNone) {
389     TlsDtv* next = dtv->next;
390     allocator.free(dtv);
391     dtv = next;
392   }
393 
394   // Clear the DTV slot. The DTV must not be used again with this thread.
395   tcb->tls_slot(TLS_SLOT_DTV) = nullptr;
396 }
397 
398 // Invokes all the registered thread_exit callbacks, if any.
__notify_thread_exit_callbacks()399 void __notify_thread_exit_callbacks() {
400   TlsModules& modules = __libc_shared_globals()->tls_modules;
401   if (modules.first_thread_exit_callback == nullptr) {
402     // If there is no first_thread_exit_callback, there shouldn't be a tail.
403     CHECK(modules.thread_exit_callback_tail_node == nullptr);
404     return;
405   }
406 
407   // Callbacks are supposed to be invoked in the reverse order
408   // in which they were registered.
409   CallbackHolder* node = modules.thread_exit_callback_tail_node;
410   while (node != nullptr) {
411     node->cb();
412     node = node->prev;
413   }
414   modules.first_thread_exit_callback();
415 }
416