xref: /freebsd/lib/libc/gen/tls.c (revision 48cce2a2982ff3d13327c6cfbdf9441539ce42b3)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2004 Doug Rabson
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 /*
30  * Define stubs for TLS internals so that programs and libraries can
31  * link. These functions will be replaced by functional versions at
32  * runtime from ld-elf.so.1.
33  */
34 
35 #include <sys/param.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <elf.h>
39 #include <unistd.h>
40 
41 #include "rtld.h"
42 #include "libc_private.h"
43 
44 #define	tls_assert(cond)	((cond) ? (void) 0 :			\
45     (tls_msg(#cond ": assert failed: " __FILE__ ":"			\
46       __XSTRING(__LINE__) "\n"), abort()))
47 #define	tls_msg(s)		write(STDOUT_FILENO, s, strlen(s))
48 
49 /* Provided by jemalloc to avoid bootstrapping issues. */
50 void	*__je_bootstrap_malloc(size_t size);
51 void	*__je_bootstrap_calloc(size_t num, size_t size);
52 void	__je_bootstrap_free(void *ptr);
53 
54 __weak_reference(__libc_allocate_tls, _rtld_allocate_tls);
55 __weak_reference(__libc_free_tls, _rtld_free_tls);
56 
57 #ifdef __i386__
58 
59 __weak_reference(___libc_tls_get_addr, ___tls_get_addr);
60 __attribute__((__regparm__(1))) void * ___libc_tls_get_addr(void *);
61 
62 #endif
63 
64 void * __libc_tls_get_addr(void *);
65 __weak_reference(__libc_tls_get_addr, __tls_get_addr);
66 
67 void *_rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign);
68 void _rtld_free_tls(void *tls, size_t tcbsize, size_t tcbalign);
69 void *__libc_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign);
70 void __libc_free_tls(void *tls, size_t tcbsize, size_t tcbalign);
71 
72 #ifndef PIC
73 
74 static size_t libc_tls_static_space;
75 static size_t libc_tls_init_size;
76 static size_t libc_tls_init_align;
77 static void *libc_tls_init;
78 #endif
79 
80 void *
__libc_tls_get_addr(void * vti)81 __libc_tls_get_addr(void *vti)
82 {
83 	struct dtv *dtv;
84 	tls_index *ti;
85 
86 	dtv = _tcb_get()->tcb_dtv;
87 	ti = vti;
88 	return (dtv->dtv_slots[ti->ti_module - 1].dtvs_tls +
89 	    (ti->ti_offset + TLS_DTV_OFFSET));
90 }
91 
92 #ifdef __i386__
93 
94 /* GNU ABI */
95 
96 __attribute__((__regparm__(1)))
97 void *
___libc_tls_get_addr(void * vti)98 ___libc_tls_get_addr(void *vti)
99 {
100 	return (__libc_tls_get_addr(vti));
101 }
102 
103 #endif
104 
105 #ifndef PIC
106 
107 static void *
libc_malloc_aligned(size_t size,size_t align)108 libc_malloc_aligned(size_t size, size_t align)
109 {
110 	void *mem, *res;
111 
112 	if (align < sizeof(void *))
113 		align = sizeof(void *);
114 
115 	mem = __je_bootstrap_malloc(size + sizeof(void *) + align - 1);
116 	if (mem == NULL)
117 		return (NULL);
118 	res = (void *)roundup2((uintptr_t)mem + sizeof(void *), align);
119 	*(void **)((uintptr_t)res - sizeof(void *)) = mem;
120 	return (res);
121 }
122 
123 static void
libc_free_aligned(void * ptr)124 libc_free_aligned(void *ptr)
125 {
126 	void *mem;
127 	uintptr_t x;
128 
129 	if (ptr == NULL)
130 		return;
131 
132 	x = (uintptr_t)ptr;
133 	x -= sizeof(void *);
134 	mem = *(void **)x;
135 	__je_bootstrap_free(mem);
136 }
137 
138 #ifdef TLS_VARIANT_I
139 
140 /*
141  * There are two versions of variant I of TLS
142  *
143  * - ARM and aarch64 uses original variant I as is described in [1] and [2],
144  *   where TP points to start of TCB followed by aligned TLS segment.
145  *   Both TCB and TLS must be aligned to alignment of TLS section. The TCB[0]
146  *   points to DTV vector and DTV values are real addresses (without bias).
147  *   Note: for Local Exec TLS Model, the offsets from TP (TCB in this case) to
148  *   TLS variables are computed by linker, so we cannot overalign TLS section.
149  *
150  * - PowerPC and RISC-V use modified version of variant I, described in [3]
151  *   where TP points (with bias) to TLS and TCB immediately precedes TLS without
152  *   any alignment gap[4]. Only TLS should be aligned.  The TCB[0] points to DTV
153  *   vector and DTV values are biased by constant value (TLS_DTV_OFFSET) from
154  *   real addresses. However, like RTLD, we don't actually bias the DTV values,
155  *   instead we compensate in __tls_get_addr for ti_offset's bias.
156  *
157  * [1] Ulrich Drepper: ELF Handling for Thread-Local Storage
158  *     www.akkadia.org/drepper/tls.pdf
159  *
160  * [2] ARM IHI 0045E: Addenda to, and Errata in, the ABI for the ARM(r)
161  *     Architecture
162  *   infocenter.arm.com/help/topic/com.arm.doc.ihi0045e/IHI0045E_ABI_addenda.pdf
163  *
164  * [3] OpenPOWER: Power Architecture 64-Bit ELF V2 ABI Specification
165  *     https://members.openpowerfoundation.org/document/dl/576
166  *
167  * [4] Its unclear if "without any alignment gap" is hard ABI requirement,
168  *     but we must follow this rule due to suboptimal _tcb_set()
169  *     (aka <ARCH>_SET_TP) implementation. This function doesn't expect TP but
170  *     TCB as argument.
171  */
172 
173 /*
174  * Return pointer to allocated TLS block
175  */
176 static void *
get_tls_block_ptr(void * tcb,size_t tcbsize)177 get_tls_block_ptr(void *tcb, size_t tcbsize)
178 {
179 	size_t extra_size, post_size, pre_size, tls_block_size;
180 
181 	/* Compute fragments sizes. */
182 	extra_size = tcbsize - TLS_TCB_SIZE;
183 #if defined(__aarch64__) || defined(__arm__)
184 	post_size =  roundup2(TLS_TCB_SIZE, libc_tls_init_align) - TLS_TCB_SIZE;
185 #else
186 	post_size = 0;
187 #endif
188 	tls_block_size = tcbsize + post_size;
189 	pre_size = roundup2(tls_block_size, libc_tls_init_align) -
190 	    tls_block_size;
191 
192 	return ((char *)tcb - pre_size - extra_size);
193 }
194 
195 /*
196  * Free Static TLS using the Variant I method. The tcbsize
197  * and tcbalign parameters must be the same as those used to allocate
198  * the block.
199  */
200 void
__libc_free_tls(void * tcb,size_t tcbsize,size_t tcbalign __unused)201 __libc_free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused)
202 {
203 	struct dtv *dtv;
204 
205 	dtv = ((struct tcb *)tcb)->tcb_dtv;
206 	__je_bootstrap_free(dtv);
207 	libc_free_aligned(get_tls_block_ptr(tcb, tcbsize));
208 }
209 
210 /*
211  * Allocate Static TLS using the Variant I method.
212  *
213  * To handle all above requirements, we setup the following layout for
214  * TLS block:
215  * (whole memory block is aligned with MAX(TLS_TCB_ALIGN, tls_init_align))
216  *
217  * +----------+--------------+--------------+-----------+------------------+
218  * | pre gap  | extended TCB |     TCB      | post gap  |    TLS segment   |
219  * | pre_size |  extra_size  | TLS_TCB_SIZE | post_size | tls_static_space |
220  * +----------+--------------+--------------+-----------+------------------+
221  *
222  * where:
223  *  extra_size is tcbsize - TLS_TCB_SIZE
224  *  post_size is used to adjust TCB to TLS alignment for first version of TLS
225  *            layout and is always 0 for second version.
226  *  pre_size  is used to adjust TCB alignment for first version and to adjust
227  *            TLS alignment for second version.
228  *
229  */
230 void *
__libc_allocate_tls(void * oldtcb,size_t tcbsize,size_t tcbalign)231 __libc_allocate_tls(void *oldtcb, size_t tcbsize, size_t tcbalign)
232 {
233 	struct dtv *dtv;
234 	struct tcb *tcb;
235 	char *tls_block, *tls;
236 	size_t extra_size, maxalign, post_size, pre_size, tls_block_size;
237 
238 	if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE)
239 		return (oldtcb);
240 
241 	tls_assert(tcbalign >= TLS_TCB_ALIGN);
242 	maxalign = MAX(tcbalign, libc_tls_init_align);
243 
244 	/* Compute fragmets sizes. */
245 	extra_size = tcbsize - TLS_TCB_SIZE;
246 #if defined(__aarch64__) || defined(__arm__)
247 	post_size = roundup2(TLS_TCB_SIZE, libc_tls_init_align) - TLS_TCB_SIZE;
248 #else
249 	post_size = 0;
250 #endif
251 	tls_block_size = tcbsize + post_size;
252 	pre_size = roundup2(tls_block_size, libc_tls_init_align) -
253 	    tls_block_size;
254 	tls_block_size += pre_size + libc_tls_static_space;
255 
256 	/* Allocate whole TLS block */
257 	tls_block = libc_malloc_aligned(tls_block_size, maxalign);
258 	if (tls_block == NULL) {
259 		tls_msg("__libc_allocate_tls: Out of memory.\n");
260 		abort();
261 	}
262 	memset(tls_block, 0, tls_block_size);
263 	tcb = (struct tcb *)(tls_block + pre_size + extra_size);
264 	tls = (char *)tcb + TLS_TCB_SIZE + post_size;
265 
266 	if (oldtcb != NULL) {
267 		memcpy(tls_block, get_tls_block_ptr(oldtcb, tcbsize),
268 		    tls_block_size);
269 		libc_free_aligned(oldtcb);
270 
271 		/* Adjust the DTV. */
272 		dtv = tcb->tcb_dtv;
273 		dtv->dtv_slots[0].dtvs_tls = tls;
274 	} else {
275 		dtv = __je_bootstrap_malloc(sizeof(struct dtv) +
276 		    sizeof(struct dtv_slot));
277 		if (dtv == NULL) {
278 			tls_msg("__libc_allocate_tls: Out of memory.\n");
279 			abort();
280 		}
281 		/* Build the DTV. */
282 		tcb->tcb_dtv = dtv;
283 		dtv->dtv_gen = 1;		/* Generation. */
284 		dtv->dtv_size = 1;		/* Segments count. */
285 		dtv->dtv_slots[0].dtvs_tls = tls;
286 
287 		if (libc_tls_init_size > 0)
288 			memcpy(tls, libc_tls_init, libc_tls_init_size);
289 	}
290 
291 	return (tcb);
292 }
293 
294 #endif
295 
296 #ifdef TLS_VARIANT_II
297 
298 /*
299  * Free Static TLS using the Variant II method.
300  */
301 void
__libc_free_tls(void * tcb,size_t tcbsize __unused,size_t tcbalign)302 __libc_free_tls(void *tcb, size_t tcbsize __unused, size_t tcbalign)
303 {
304 	size_t size;
305 	struct dtv *dtv;
306 	uintptr_t tlsstart, tlsend;
307 
308 	/*
309 	 * Figure out the size of the initial TLS block so that we can
310 	 * find stuff which ___tls_get_addr() allocated dynamically.
311 	 */
312 	tcbalign = MAX(tcbalign, libc_tls_init_align);
313 	size = roundup2(libc_tls_static_space, tcbalign);
314 
315 	dtv = ((struct tcb *)tcb)->tcb_dtv;
316 	tlsend = (uintptr_t)tcb;
317 	tlsstart = tlsend - size;
318 	libc_free_aligned((void*)tlsstart);
319 	__je_bootstrap_free(dtv);
320 }
321 
322 /*
323  * Allocate Static TLS using the Variant II method.
324  */
325 void *
__libc_allocate_tls(void * oldtcb,size_t tcbsize,size_t tcbalign)326 __libc_allocate_tls(void *oldtcb, size_t tcbsize, size_t tcbalign)
327 {
328 	size_t size;
329 	char *tls_block, *tls;
330 	struct dtv *dtv;
331 	struct tcb *tcb;
332 
333 	tcbalign = MAX(tcbalign, libc_tls_init_align);
334 	size = roundup2(libc_tls_static_space, tcbalign);
335 
336 	if (tcbsize < 2 * sizeof(uintptr_t))
337 		tcbsize = 2 * sizeof(uintptr_t);
338 	tls_block = libc_malloc_aligned(size + tcbsize, tcbalign);
339 	if (tls_block == NULL) {
340 		tls_msg("__libc_allocate_tls: Out of memory.\n");
341 		abort();
342 	}
343 	memset(tls_block, 0, size + tcbsize);
344 	dtv = __je_bootstrap_malloc(sizeof(struct dtv) +
345 	    sizeof(struct dtv_slot));
346 	if (dtv == NULL) {
347 		tls_msg("__libc_allocate_tls: Out of memory.\n");
348 		abort();
349 	}
350 
351 	tcb = (struct tcb *)(tls_block + size);
352 	tls = (char *)tcb - libc_tls_static_space;
353 	tcb->tcb_self = tcb;
354 	tcb->tcb_dtv = dtv;
355 
356 	dtv->dtv_gen = 1;
357 	dtv->dtv_size = 1;
358 	dtv->dtv_slots[0].dtvs_tls = tls;
359 
360 	if (oldtcb != NULL) {
361 		/*
362 		 * Copy the static TLS block over whole.
363 		 */
364 		memcpy(tls, (const char *)oldtcb - libc_tls_static_space,
365 		    libc_tls_static_space);
366 
367 		/*
368 		 * We assume that this block was the one we created with
369 		 * allocate_initial_tls().
370 		 */
371 		_rtld_free_tls(oldtcb, 2 * sizeof(uintptr_t),
372 		    sizeof(uintptr_t));
373 	} else {
374 		memcpy(tls, libc_tls_init, libc_tls_init_size);
375 		memset(tls + libc_tls_init_size, 0,
376 		    libc_tls_static_space - libc_tls_init_size);
377 	}
378 
379 	return (tcb);
380 }
381 
382 #endif /* TLS_VARIANT_II */
383 
384 #else
385 
386 void *
__libc_allocate_tls(void * oldtcb __unused,size_t tcbsize __unused,size_t tcbalign __unused)387 __libc_allocate_tls(void *oldtcb __unused, size_t tcbsize __unused,
388 	size_t tcbalign __unused)
389 {
390 	return (0);
391 }
392 
393 void
__libc_free_tls(void * tcb __unused,size_t tcbsize __unused,size_t tcbalign __unused)394 __libc_free_tls(void *tcb __unused, size_t tcbsize __unused,
395 	size_t tcbalign __unused)
396 {
397 }
398 
399 #endif /* PIC */
400 
401 void
_init_tls(void)402 _init_tls(void)
403 {
404 #ifndef PIC
405 	Elf_Addr *sp;
406 	Elf_Auxinfo *aux, *auxp;
407 	Elf_Phdr *phdr;
408 	size_t phent, phnum;
409 	int i;
410 	void *tls;
411 
412 	sp = (Elf_Addr *) environ;
413 	while (*sp++ != 0)
414 		;
415 	aux = (Elf_Auxinfo *) sp;
416 	phdr = NULL;
417 	phent = phnum = 0;
418 	for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
419 		switch (auxp->a_type) {
420 		case AT_PHDR:
421 			phdr = auxp->a_un.a_ptr;
422 			break;
423 
424 		case AT_PHENT:
425 			phent = auxp->a_un.a_val;
426 			break;
427 
428 		case AT_PHNUM:
429 			phnum = auxp->a_un.a_val;
430 			break;
431 		}
432 	}
433 	if (phdr == NULL || phent != sizeof(Elf_Phdr) || phnum == 0)
434 		return;
435 
436 	for (i = 0; (unsigned) i < phnum; i++) {
437 		if (phdr[i].p_type == PT_TLS) {
438 			libc_tls_static_space = roundup2(phdr[i].p_memsz,
439 			    phdr[i].p_align);
440 			libc_tls_init_size = phdr[i].p_filesz;
441 			libc_tls_init_align = phdr[i].p_align;
442 			libc_tls_init = (void *)phdr[i].p_vaddr;
443 			break;
444 		}
445 	}
446 	tls = _rtld_allocate_tls(NULL, TLS_TCB_SIZE, TLS_TCB_ALIGN);
447 
448 	_tcb_set(tls);
449 #endif
450 }
451