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 #pragma once
30
31 #include <link.h>
32 #include <pthread.h>
33 #include <stdatomic.h>
34 #include <stdint.h>
35 #include <sys/cdefs.h>
36
37 #include "bionic_elf_dtv_offset.h"
38
39 __LIBC_HIDDEN__ extern _Atomic(size_t) __libc_tls_generation_copy;
40
41 struct TlsAlign {
42 size_t value = 1;
43 size_t skew = 0; // p_vaddr % p_align
44
45 template <typename T>
of_typeTlsAlign46 static constexpr TlsAlign of_type() {
47 return TlsAlign{.value = alignof(T)};
48 }
49 };
50
51 struct TlsAlignedSize {
52 size_t size = 0;
53 TlsAlign align;
54
55 template <typename T>
of_typeTlsAlignedSize56 static constexpr TlsAlignedSize of_type() {
57 return TlsAlignedSize{.size = sizeof(T), .align = TlsAlign::of_type<T>()};
58 }
59 };
60
61 struct TlsSegment {
62 TlsAlignedSize aligned_size;
63 const void* init_ptr = ""; // Field is non-null even when init_size is 0.
64 size_t init_size = 0;
65 };
66
67 __LIBC_HIDDEN__ bool __bionic_get_tls_segment(const ElfW(Phdr)* phdr_table, size_t phdr_count,
68 ElfW(Addr) load_bias, TlsSegment* out);
69
70 __LIBC_HIDDEN__ bool __bionic_check_tls_align(size_t align);
71
72 struct StaticTlsLayout {
StaticTlsLayoutStaticTlsLayout73 constexpr StaticTlsLayout() {}
74
75 public:
offset_bionic_tcbStaticTlsLayout76 size_t offset_bionic_tcb() const { return offset_bionic_tcb_; }
offset_bionic_tlsStaticTlsLayout77 size_t offset_bionic_tls() const { return offset_bionic_tls_; }
78 size_t offset_thread_pointer() const;
offset_exeStaticTlsLayout79 size_t offset_exe() const { return offset_exe_; }
80
sizeStaticTlsLayout81 size_t size() const { return cursor_; }
82
83 size_t reserve_exe_segment_and_tcb(const TlsSegment* exe_segment, const char* progname);
84 size_t reserve_bionic_tls();
reserve_solib_segmentStaticTlsLayout85 size_t reserve_solib_segment(const TlsSegment& segment) { return reserve(segment.aligned_size); }
86 void finish_layout();
87
88 #if !defined(STATIC_TLS_LAYOUT_TEST)
89 private:
90 #endif
91 size_t cursor_ = 0;
92 size_t align_ = 1;
93
94 // Offsets to various Bionic TLS structs from the beginning of static TLS.
95 size_t offset_bionic_tcb_ = SIZE_MAX;
96 size_t offset_bionic_tls_ = SIZE_MAX;
97
98 size_t offset_exe_ = SIZE_MAX;
99
100 struct TpAllocations {
101 size_t before;
102 size_t tp;
103 size_t after;
104 };
105
106 size_t align_cursor(TlsAlign align);
107 size_t align_cursor_unskewed(size_t align);
108 size_t reserve(TlsAlignedSize aligned_size);
109 TpAllocations reserve_tp_pair(TlsAlignedSize before, TlsAlignedSize after);
110
reserve_typeStaticTlsLayout111 template <typename T> size_t reserve_type() {
112 return reserve(TlsAlignedSize::of_type<T>());
113 }
114 };
115
116 static constexpr size_t kTlsGenerationNone = 0;
117 static constexpr size_t kTlsGenerationFirst = 1;
118
119 // The first ELF TLS module has ID 1. Zero is reserved for the first word of
120 // the DTV, a generation count. Unresolved weak symbols also use module ID 0.
121 static constexpr size_t kTlsUninitializedModuleId = 0;
122
__tls_module_id_to_idx(size_t id)123 static inline size_t __tls_module_id_to_idx(size_t id) { return id - 1; }
__tls_module_idx_to_id(size_t idx)124 static inline size_t __tls_module_idx_to_id(size_t idx) { return idx + 1; }
125
126 // A descriptor for a single ELF TLS module.
127 struct TlsModule {
128 TlsSegment segment;
129
130 // Offset into the static TLS block or SIZE_MAX for a dynamic module.
131 size_t static_offset = SIZE_MAX;
132
133 // The generation in which this module was loaded. Dynamic TLS lookups use
134 // this field to detect when a module has been unloaded.
135 size_t first_generation = kTlsGenerationNone;
136
137 // Used by the dynamic linker to track the associated soinfo* object.
138 void* soinfo_ptr = nullptr;
139 };
140
141 // Signature of the callbacks that will be called after DTLS creation and
142 // before DTLS destruction.
143 typedef void (*dtls_listener_t)(void* dynamic_tls_begin, void* dynamic_tls_end);
144
145 // Signature of the thread-exit callbacks.
146 typedef void (*thread_exit_cb_t)(void);
147
148 struct CallbackHolder {
149 thread_exit_cb_t cb;
150 CallbackHolder* prev;
151 };
152
153 // Table of the ELF TLS modules. Either the dynamic linker or the static
154 // initialization code prepares this table, and it's then used during thread
155 // creation and for dynamic TLS lookups.
156 struct TlsModules {
TlsModulesTlsModules157 constexpr TlsModules() {}
158
159 // A pointer to the TLS generation counter in libc.so. The counter is
160 // incremented each time an solib is loaded or unloaded.
161 _Atomic(size_t) generation = kTlsGenerationFirst;
162 _Atomic(size_t) *generation_libc_so = nullptr;
163
164 // Access to the TlsModule[] table requires taking this lock.
165 pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
166
167 // Pointer to a block of TlsModule objects. The first module has ID 1 and
168 // is stored at index 0 in this table.
169 size_t module_count = 0;
170 size_t static_module_count = 0;
171 TlsModule* module_table = nullptr;
172
173 // Callback to be invoked after a dynamic TLS allocation.
174 dtls_listener_t on_creation_cb = nullptr;
175
176 // Callback to be invoked before a dynamic TLS deallocation.
177 dtls_listener_t on_destruction_cb = nullptr;
178
179 // The first thread-exit callback; inlined to avoid allocation.
180 thread_exit_cb_t first_thread_exit_callback = nullptr;
181
182 // The additional callbacks, if any.
183 CallbackHolder* thread_exit_callback_tail_node = nullptr;
184 };
185
186 void __init_static_tls(void* static_tls);
187
188 // Dynamic Thread Vector. Each thread has a different DTV. For each module
189 // (executable or solib), the DTV has a pointer to that module's TLS memory. The
190 // DTV is initially empty and is allocated on-demand. It grows as more modules
191 // are dlopen'ed. See https://www.akkadia.org/drepper/tls.pdf.
192 //
193 // The layout of the DTV is specified in various documents, but it is not part
194 // of Bionic's public ABI. A compiler can't generate code to access it directly,
195 // because it can't access libc's global generation counter.
196 struct TlsDtv {
197 // Number of elements in this object's modules field.
198 size_t count;
199
200 // A pointer to an older TlsDtv object that should be freed when the thread
201 // exits. The objects aren't immediately freed because a DTV could be
202 // reallocated by a signal handler that interrupted __tls_get_addr's fast
203 // path.
204 TlsDtv* next;
205
206 // The DTV slot points at this field, which allows omitting an add instruction
207 // on the fast path for a TLS lookup. The arm64 tlsdesc_resolver.S depends on
208 // the layout of fields past this point.
209 size_t generation;
210 void* modules[];
211 };
212
213 struct TlsIndex {
214 size_t module_id;
215 size_t offset;
216 };
217
218 #if defined(__i386__)
219 #define TLS_GET_ADDR_CALLING_CONVENTION __attribute__((regparm(1)))
220 #define TLS_GET_ADDR ___tls_get_addr
221 #else
222 #define TLS_GET_ADDR_CALLING_CONVENTION
223 #define TLS_GET_ADDR __tls_get_addr
224 #endif
225
226 extern "C" void* TLS_GET_ADDR(const TlsIndex* ti) TLS_GET_ADDR_CALLING_CONVENTION;
227
228 struct bionic_tcb;
229 void __free_dynamic_tls(bionic_tcb* tcb);
230 void __notify_thread_exit_callbacks();
231
232