xref: /openbsd-src/lib/libc/dlfcn/init.c (revision 8550894424f8a4aa4aafb6cd57229dd6ed7cd9dd)
1 /*	$OpenBSD: init.c,v 1.12 2023/01/16 07:09:12 guenther Exp $ */
2 /*
3  * Copyright (c) 2014,2015 Philip Guenther <guenther@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 
19 #define _DYN_LOADER
20 
21 #include <sys/types.h>
22 #include <sys/syscall.h>
23 #include <sys/timetc.h>		/* timekeep */
24 
25 #ifndef PIC
26 #include <sys/mman.h>
27 #endif
28 
29 #include <tib.h>
30 #include <limits.h>		/* NAME_MAX */
31 #include <link.h>
32 #include <stdlib.h>		/* atexit */
33 #include <string.h>
34 #include <unistd.h>
35 
36 #include "init.h"
37 
38 #define MAX(a,b)	(((a)>(b))?(a):(b))
39 
40 #ifdef TIB_EXTRA_ALIGN
41 # define TIB_ALIGN	MAX(__alignof__(struct tib), TIB_EXTRA_ALIGN)
42 #else
43 # define TIB_ALIGN	__alignof__(struct tib)
44 #endif
45 
46 /* XXX should be in an include file shared with csu */
47 char	***_csu_finish(char **_argv, char **_envp, void (*_cleanup)(void));
48 
49 /* provide definitions for these */
50 int	_pagesize = 0;
51 struct timekeep	*_timekeep;
52 
53 /*
54  * In dynamically linked binaries environ and __progname are overridden by
55  * the definitions in ld.so.
56  */
57 char	**environ __attribute__((weak)) = NULL;
58 char	*__progname __attribute__((weak)) = NULL;
59 
60 
61 #ifndef PIC
62 struct dl_phdr_info	_static_phdr_info __relro = { .dlpi_name = "a.out" };
63 
64 static inline void early_static_init(char **_argv, char **_envp);
65 static inline void setup_static_tib(Elf_Phdr *_phdr, int _phnum);
66 
67 /* provided by the linker */
68 extern Elf_Ehdr __executable_start[] __attribute__((weak));
69 #endif /* PIC */
70 
71 /* provide definitions for these */
72 const dl_cb *_dl_cb __relro = NULL;
73 
74 void _libc_preinit(int, char **, char **, dl_cb_cb *) __dso_hidden;
75 void
76 _libc_preinit(int argc, char **argv, char **envp, dl_cb_cb *cb)
77 {
78 	AuxInfo	*aux;
79 #ifndef PIC
80 	Elf_Phdr *phdr = NULL;
81 	int phnum = 0;
82 
83 	/* static libc in a static link? */
84 	if (cb == NULL)
85 		early_static_init(argv, envp);
86 #endif /* !PIC */
87 
88 	if (cb != NULL)
89 		_dl_cb = cb(DL_CB_CUR);
90 
91 	/* Extract useful bits from the auxiliary vector */
92 	while (*envp++ != NULL)
93 		;
94 	for (aux = (void *)envp; aux->au_id != AUX_null; aux++) {
95 		switch (aux->au_id) {
96 		case AUX_pagesz:
97 			_pagesize = aux->au_v;
98 			break;
99 #ifndef PIC
100 		case AUX_base:
101 			_static_phdr_info.dlpi_addr = aux->au_v;
102 			break;
103 		case AUX_phdr:
104 			phdr = (void *)aux->au_v;
105 			break;
106 		case AUX_phnum:
107 			phnum = aux->au_v;
108 			break;
109 #endif /* !PIC */
110 		case AUX_openbsd_timekeep:
111 			if (_tc_get_timecount) {
112 				_timekeep = (void *)aux->au_v;
113 				if (_timekeep &&
114 				    _timekeep->tk_version != TK_VERSION)
115 					_timekeep = NULL;
116 			}
117 			if (issetugid() == 0 && getenv("LIBC_NOUSERTC"))
118 				_timekeep = NULL;
119 			break;
120 		}
121 	}
122 
123 #ifndef PIC
124 	if (cb == NULL && phdr == NULL && __executable_start != NULL) {
125 		/*
126 		 * Static non-PIE processes don't get an AUX vector,
127 		 * so find the phdrs through the ELF header
128 		 */
129 		_static_phdr_info.dlpi_addr = (Elf_Addr)__executable_start;
130 		phdr = (void *)((char *)__executable_start +
131 		    __executable_start->e_phoff);
132 		phnum = __executable_start->e_phnum;
133 	}
134 	_static_phdr_info.dlpi_phdr = phdr;
135 	_static_phdr_info.dlpi_phnum = phnum;
136 
137 	/* static libc in a static link? */
138 	if (cb == NULL)
139 		setup_static_tib(phdr, phnum);
140 
141 	/*
142 	 * If a static binary has text relocations (DT_TEXT), then un-writeable
143 	 * segments were not made immutable by the kernel.  Textrel and RELRO
144 	 * changes have now been completed and permissions corrected, so these
145 	 * regions can become immutable.
146 	 */
147 	if (phdr) {
148 		int i;
149 
150 		for (i = 0; i < phnum; i++) {
151 			if (phdr[i].p_type == PT_LOAD &&
152 			    (phdr[i].p_flags & PF_W) == 0)
153 				mimmutable((void *)(_static_phdr_info.dlpi_addr +
154 				    phdr[i].p_vaddr), phdr[i].p_memsz);
155 		}
156 	}
157 #endif /* !PIC */
158 }
159 
160 /* ARM just had to be different... */
161 #ifndef __arm__
162 # define TYPE	"@"
163 #else
164 # define TYPE	"%"
165 #endif
166 
167 #ifdef __LP64__
168 # define VALUE_ALIGN		".balign 8"
169 # define VALUE_DIRECTIVE	".quad"
170 #else
171 # define VALUE_ALIGN		".balign 4"
172 # ifdef __hppa__
173    /* hppa just had to be different: func pointers prefix with 'P%' */
174 #  define VALUE_DIRECTIVE	".int P%"
175 # else
176 #  define VALUE_DIRECTIVE	".int"
177 # endif
178 #endif
179 
180 #define ADD_TO_ARRAY(func, which) \
181 	__asm(	" .section ."#which",\"a\","TYPE#which"\n " \
182 	VALUE_ALIGN"\n "VALUE_DIRECTIVE" "#func"\n .previous")
183 
184 #ifdef PIC
185 ADD_TO_ARRAY(_libc_preinit, init_array);
186 #else
187 ADD_TO_ARRAY(_libc_preinit, preinit_array);
188 #endif
189 
190 /*
191  * In dynamic links, invoke ld.so's dl_clean_boot() callback, if any,
192  * and register its cleanup.
193  */
194 char ***
195 _csu_finish(char **argv, char **envp, void (*cleanup)(void))
196 {
197 	if (_dl_cb != NULL && _dl_cb->dl_clean_boot != NULL)
198 		_dl_cb->dl_clean_boot();
199 
200 	if (cleanup != NULL)
201 		atexit(cleanup);
202 
203 	return &environ;
204 }
205 
206 #ifndef PIC
207 /*
208  * static libc in a static link?  Then set up __progname and environ
209  */
210 static inline void
211 early_static_init(char **argv, char **envp)
212 {
213 	static char progname_storage[NAME_MAX+1];
214 
215 	environ = envp;
216 
217 	/* set up __progname */
218 	if (*argv != NULL) {		/* NULL ptr if argc = 0 */
219 		const char *p = strrchr(*argv, '/');
220 
221 		if (p == NULL)
222 			p = *argv;
223 		else
224 			p++;
225 		strlcpy(progname_storage, p, sizeof(progname_storage));
226 	}
227 	__progname = progname_storage;
228 }
229 
230 /*
231  * static TLS handling
232  */
233 #define ELF_ROUND(x,malign)	(((x) + (malign)-1) & ~((malign)-1))
234 
235 /* for static binaries, the location and size of the TLS image */
236 static void		*static_tls __relro;
237 static size_t		static_tls_fsize __relro;
238 
239 size_t			_static_tls_size __relro = 0;
240 int			_static_tls_align __relro;
241 int			_static_tls_align_offset __relro;
242 
243 static inline void
244 setup_static_tib(Elf_Phdr *phdr, int phnum)
245 {
246 	struct tib *tib;
247 	char *base;
248 	int i;
249 
250 	_static_tls_align = TIB_ALIGN;
251 	if (phdr != NULL) {
252 		for (i = 0; i < phnum; i++) {
253 			if (phdr[i].p_type != PT_TLS)
254 				continue;
255 			if (phdr[i].p_memsz == 0)
256 				break;
257 			if (phdr[i].p_memsz < phdr[i].p_filesz)
258 				break;		/* invalid */
259 			if (phdr[i].p_align > getpagesize())
260 				break;		/* nope */
261 			_static_tls_align = MAX(phdr[i].p_align, TIB_ALIGN);
262 #if TLS_VARIANT == 1
263 			/*
264 			 * Variant 1 places the data after the TIB.  If the
265 			 * TLS alignment is larger than the TIB alignment
266 			 * then we may need to pad in front of the TIB to
267 			 * place the TLS data on the proper alignment.
268 			 * Example: p_align=16 sizeof(TIB)=52 align(TIB)=4
269 			 * - need to offset the TIB 12 bytes from the start
270 			 * - to place ths TLS data at offset 64
271 			 */
272 			_static_tls_size = phdr[i].p_memsz;
273 			_static_tls_align_offset =
274 			    ELF_ROUND(sizeof(struct tib), _static_tls_align) -
275 			    sizeof(struct tib);
276 #elif TLS_VARIANT == 2
277 			/*
278 			 * Variant 2 places the data before the TIB
279 			 * so we need to round up the size to the
280 			 * TLS data alignment TIB's alignment.
281 			 * Example A: p_memsz=24 p_align=16 align(TIB)=8
282 			 * - need to allocate 32 bytes for TLS as compiler
283 			 * - will give the first TLS symbol an offset of -32
284 			 * Example B: p_memsz=4 p_align=4 align(TIB)=8
285 			 * - need to allocate 8 bytes so that the TIB is
286 			 * - properly aligned
287 			 */
288 			_static_tls_size = ELF_ROUND(phdr[i].p_memsz,
289 			    phdr[i].p_align);
290 			_static_tls_align_offset = ELF_ROUND(_static_tls_size,
291 			    _static_tls_align) - _static_tls_size;
292 #endif
293 			if (phdr[i].p_vaddr != 0 && phdr[i].p_filesz != 0) {
294 				static_tls = (void *)phdr[i].p_vaddr +
295 				    _static_phdr_info.dlpi_addr;
296 				static_tls_fsize = phdr[i].p_filesz;
297 			}
298 			break;
299 		}
300 	}
301 
302 	base = mmap(NULL, _static_tls_size + _static_tls_align_offset
303 	    + sizeof *tib, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
304 
305 	tib = _static_tls_init(base, NULL);
306 	tib->tib_tid = getthrid();
307 	TCB_SET(TIB_TO_TCB(tib));
308 #if ! TCB_HAVE_MD_GET
309 	_libc_single_tcb = TIB_TO_TCB(tib);
310 #endif
311 }
312 
313 struct tib *
314 _static_tls_init(char *base, void *thread)
315 {
316 	struct tib *tib;
317 
318 	base += _static_tls_align_offset;
319 # if TLS_VARIANT == 1
320 	tib = (struct tib *)base;
321 	base += sizeof(struct tib);
322 # elif TLS_VARIANT == 2
323 	tib = (struct tib *)(base + _static_tls_size);
324 # endif
325 
326 	if (_static_tls_size) {
327 		if (static_tls != NULL)
328 			memcpy(base, static_tls, static_tls_fsize);
329 		memset(base + static_tls_fsize, 0,
330 		    _static_tls_size - static_tls_fsize);
331 	}
332 
333 	TIB_INIT(tib, NULL, thread);
334 	return tib;
335 }
336 #endif /* !PIC */
337