xref: /openbsd-src/lib/libc/dlfcn/init.c (revision ff0e7be1ebbcc809ea8ad2b6dafe215824da9e46)
1 /*	$OpenBSD: init.c,v 1.18 2023/02/27 15:00:17 deraadt 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 #if defined(APIWARN)
39 __warn_references(syscall,
40     "syscall() may go away, please rewrite code to use direct calls");
41 #endif
42 
43 #define MAX(a,b)	(((a)>(b))?(a):(b))
44 
45 #ifdef TIB_EXTRA_ALIGN
46 # define TIB_ALIGN	MAX(__alignof__(struct tib), TIB_EXTRA_ALIGN)
47 #else
48 # define TIB_ALIGN	__alignof__(struct tib)
49 #endif
50 
51 /* XXX should be in an include file shared with csu */
52 char	***_csu_finish(char **_argv, char **_envp, void (*_cleanup)(void));
53 
54 /* provide definitions for these */
55 int	_pagesize = 0;
56 struct timekeep	*_timekeep;
57 
58 /*
59  * In dynamically linked binaries environ and __progname are overridden by
60  * the definitions in ld.so.
61  */
62 char	**environ __attribute__((weak)) = NULL;
63 char	*__progname __attribute__((weak)) = NULL;
64 
65 
66 #ifndef PIC
67 struct dl_phdr_info	_static_phdr_info __relro = { .dlpi_name = "a.out" };
68 
69 static inline void early_static_init(char **_argv, char **_envp);
70 static inline void setup_static_tib(Elf_Phdr *_phdr, int _phnum);
71 
72 /* provided by the linker */
73 extern Elf_Ehdr __executable_start[] __attribute__((weak));
74 #endif /* PIC */
75 
76 /* provide definitions for these */
77 const dl_cb *_dl_cb __relro = NULL;
78 
79 int	pinsyscall(int, void *, size_t);
80 PROTO_NORMAL(pinsyscall);
81 
82 int	HIDDEN(execve)(const char *, char *const *, char *const *)
83 	__attribute__((weak));
84 
85 void _libc_preinit(int, char **, char **, dl_cb_cb *) __dso_hidden;
86 void
87 _libc_preinit(int argc, char **argv, char **envp, dl_cb_cb *cb)
88 {
89 	AuxInfo	*aux;
90 #ifndef PIC
91 	Elf_Phdr *phdr = NULL;
92 	int phnum = 0;
93 
94 	/* static libc in a static link? */
95 	if (cb == NULL)
96 		early_static_init(argv, envp);
97 #endif /* !PIC */
98 
99 	if (cb != NULL)
100 		_dl_cb = cb(DL_CB_CUR);
101 
102 	/* Extract useful bits from the auxiliary vector */
103 	while (*envp++ != NULL)
104 		;
105 	for (aux = (void *)envp; aux->au_id != AUX_null; aux++) {
106 		switch (aux->au_id) {
107 		case AUX_pagesz:
108 			_pagesize = aux->au_v;
109 			break;
110 #ifndef PIC
111 		case AUX_base:
112 			_static_phdr_info.dlpi_addr = aux->au_v;
113 			break;
114 		case AUX_phdr:
115 			phdr = (void *)aux->au_v;
116 			break;
117 		case AUX_phnum:
118 			phnum = aux->au_v;
119 			break;
120 #endif /* !PIC */
121 		case AUX_openbsd_timekeep:
122 			if (_tc_get_timecount) {
123 				_timekeep = (void *)aux->au_v;
124 				if (_timekeep &&
125 				    _timekeep->tk_version != TK_VERSION)
126 					_timekeep = NULL;
127 			}
128 			if (issetugid() == 0 && getenv("LIBC_NOUSERTC"))
129 				_timekeep = NULL;
130 			break;
131 		}
132 	}
133 
134 #ifndef PIC
135 	if (cb == NULL && phdr == NULL && __executable_start != NULL) {
136 		/*
137 		 * Static non-PIE processes don't get an AUX vector,
138 		 * so find the phdrs through the ELF header
139 		 */
140 		_static_phdr_info.dlpi_addr = (Elf_Addr)__executable_start;
141 		phdr = (void *)((char *)__executable_start +
142 		    __executable_start->e_phoff);
143 		phnum = __executable_start->e_phnum;
144 	}
145 	_static_phdr_info.dlpi_phdr = phdr;
146 	_static_phdr_info.dlpi_phnum = phnum;
147 
148 	/* static libc in a static link? */
149 	if (cb == NULL) {
150 		setup_static_tib(phdr, phnum);
151 
152 #if !defined(__hppa__)
153 		if (&HIDDEN(execve)) {
154 			extern const int _execve_size;
155 
156 			pinsyscall(SYS_execve, &HIDDEN(execve), _execve_size);
157 		}
158 #endif
159 	}
160 
161 	/*
162 	 * If a static binary has text relocations (DT_TEXT), then un-writeable
163 	 * segments were not made immutable by the kernel.  Textrel and RELRO
164 	 * changes have now been completed and permissions corrected, so these
165 	 * regions can become immutable.
166 	 */
167 	if (phdr) {
168 		int i;
169 
170 		for (i = 0; i < phnum; i++) {
171 			if (phdr[i].p_type == PT_LOAD &&
172 			    (phdr[i].p_flags & PF_W) == 0)
173 				mimmutable((void *)(_static_phdr_info.dlpi_addr +
174 				    phdr[i].p_vaddr), phdr[i].p_memsz);
175 		}
176 	}
177 #endif /* !PIC */
178 }
179 
180 /* ARM just had to be different... */
181 #ifndef __arm__
182 # define TYPE	"@"
183 #else
184 # define TYPE	"%"
185 #endif
186 
187 #ifdef __LP64__
188 # define VALUE_ALIGN		".balign 8"
189 # define VALUE_DIRECTIVE	".quad"
190 #else
191 # define VALUE_ALIGN		".balign 4"
192 # ifdef __hppa__
193    /* hppa just had to be different: func pointers prefix with 'P%' */
194 #  define VALUE_DIRECTIVE	".int P%"
195 # else
196 #  define VALUE_DIRECTIVE	".int"
197 # endif
198 #endif
199 
200 #define ADD_TO_ARRAY(func, which) \
201 	__asm(	" .section ."#which",\"a\","TYPE#which"\n " \
202 	VALUE_ALIGN"\n "VALUE_DIRECTIVE" "#func"\n .previous")
203 
204 #ifdef PIC
205 ADD_TO_ARRAY(_libc_preinit, init_array);
206 #else
207 ADD_TO_ARRAY(_libc_preinit, preinit_array);
208 #endif
209 
210 /*
211  * In dynamic links, invoke ld.so's dl_clean_boot() callback, if any,
212  * and register its cleanup.
213  */
214 char ***
215 _csu_finish(char **argv, char **envp, void (*cleanup)(void))
216 {
217 	if (_dl_cb != NULL && _dl_cb->dl_clean_boot != NULL)
218 		_dl_cb->dl_clean_boot();
219 
220 	if (cleanup != NULL)
221 		atexit(cleanup);
222 
223 	return &environ;
224 }
225 
226 #ifndef PIC
227 /*
228  * static libc in a static link?  Then set up __progname and environ
229  */
230 static inline void
231 early_static_init(char **argv, char **envp)
232 {
233 	static char progname_storage[NAME_MAX+1];
234 
235 	environ = envp;
236 
237 	/* set up __progname */
238 	if (*argv != NULL) {		/* NULL ptr if argc = 0 */
239 		const char *p = strrchr(*argv, '/');
240 
241 		if (p == NULL)
242 			p = *argv;
243 		else
244 			p++;
245 		strlcpy(progname_storage, p, sizeof(progname_storage));
246 	}
247 	__progname = progname_storage;
248 }
249 
250 /*
251  * static TLS handling
252  */
253 #define ELF_ROUND(x,malign)	(((x) + (malign)-1) & ~((malign)-1))
254 
255 /* for static binaries, the location and size of the TLS image */
256 static void		*static_tls __relro;
257 static size_t		static_tls_fsize __relro;
258 
259 size_t			_static_tls_size __relro = 0;
260 int			_static_tls_align __relro;
261 int			_static_tls_align_offset __relro;
262 
263 static inline void
264 setup_static_tib(Elf_Phdr *phdr, int phnum)
265 {
266 	struct tib *tib;
267 	char *base;
268 	int i;
269 
270 	_static_tls_align = TIB_ALIGN;
271 	if (phdr != NULL) {
272 		for (i = 0; i < phnum; i++) {
273 			if (phdr[i].p_type != PT_TLS)
274 				continue;
275 			if (phdr[i].p_memsz == 0)
276 				break;
277 			if (phdr[i].p_memsz < phdr[i].p_filesz)
278 				break;		/* invalid */
279 			if (phdr[i].p_align > getpagesize())
280 				break;		/* nope */
281 			_static_tls_align = MAX(phdr[i].p_align, TIB_ALIGN);
282 #if TLS_VARIANT == 1
283 			/*
284 			 * Variant 1 places the data after the TIB.  If the
285 			 * TLS alignment is larger than the TIB alignment
286 			 * then we may need to pad in front of the TIB to
287 			 * place the TLS data on the proper alignment.
288 			 * Example: p_align=16 sizeof(TIB)=52 align(TIB)=4
289 			 * - need to offset the TIB 12 bytes from the start
290 			 * - to place ths TLS data at offset 64
291 			 */
292 			_static_tls_size = phdr[i].p_memsz;
293 			_static_tls_align_offset =
294 			    ELF_ROUND(sizeof(struct tib), _static_tls_align) -
295 			    sizeof(struct tib);
296 #elif TLS_VARIANT == 2
297 			/*
298 			 * Variant 2 places the data before the TIB
299 			 * so we need to round up the size to the
300 			 * TLS data alignment TIB's alignment.
301 			 * Example A: p_memsz=24 p_align=16 align(TIB)=8
302 			 * - need to allocate 32 bytes for TLS as compiler
303 			 * - will give the first TLS symbol an offset of -32
304 			 * Example B: p_memsz=4 p_align=4 align(TIB)=8
305 			 * - need to allocate 8 bytes so that the TIB is
306 			 * - properly aligned
307 			 */
308 			_static_tls_size = ELF_ROUND(phdr[i].p_memsz,
309 			    phdr[i].p_align);
310 			_static_tls_align_offset = ELF_ROUND(_static_tls_size,
311 			    _static_tls_align) - _static_tls_size;
312 #endif
313 			if (phdr[i].p_vaddr != 0 && phdr[i].p_filesz != 0) {
314 				static_tls = (void *)phdr[i].p_vaddr +
315 				    _static_phdr_info.dlpi_addr;
316 				static_tls_fsize = phdr[i].p_filesz;
317 			}
318 			break;
319 		}
320 	}
321 
322 	base = mmap(NULL, _static_tls_size + _static_tls_align_offset
323 	    + sizeof *tib, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
324 
325 	tib = _static_tls_init(base, NULL);
326 	tib->tib_tid = getthrid();
327 	TCB_SET(TIB_TO_TCB(tib));
328 #if ! TCB_HAVE_MD_GET
329 	_libc_single_tcb = TIB_TO_TCB(tib);
330 #endif
331 }
332 
333 struct tib *
334 _static_tls_init(char *base, void *thread)
335 {
336 	struct tib *tib;
337 
338 	base += _static_tls_align_offset;
339 # if TLS_VARIANT == 1
340 	tib = (struct tib *)base;
341 	base += sizeof(struct tib);
342 # elif TLS_VARIANT == 2
343 	tib = (struct tib *)(base + _static_tls_size);
344 # endif
345 
346 	if (_static_tls_size) {
347 		if (static_tls != NULL)
348 			memcpy(base, static_tls, static_tls_fsize);
349 		memset(base + static_tls_fsize, 0,
350 		    _static_tls_size - static_tls_fsize);
351 	}
352 
353 	TIB_INIT(tib, NULL, thread);
354 	return tib;
355 }
356 #endif /* !PIC */
357