xref: /netbsd-src/lib/csu/common/crt0-common.c (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 /* $NetBSD: crt0-common.c,v 1.24 2021/04/20 21:42:31 christos Exp $ */
2 
3 /*
4  * Copyright (c) 1998 Christos Zoulas
5  * Copyright (c) 1995 Christopher G. Demetriou
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *          This product includes software developed for the
19  *          NetBSD Project.  See http://www.NetBSD.org/ for
20  *          information about NetBSD.
21  * 4. The name of the author may not be used to endorse or promote products
22  *    derived from this software without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  *
35  * <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
36  */
37 
38 #include <sys/cdefs.h>
39 __RCSID("$NetBSD: crt0-common.c,v 1.24 2021/04/20 21:42:31 christos Exp $");
40 
41 #include <sys/types.h>
42 #include <sys/exec.h>
43 #include <sys/exec_elf.h>
44 #include <sys/syscall.h>
45 #include <machine/profile.h>
46 #include <stdlib.h>
47 #include <unistd.h>
48 
49 #include "csu-common.h"
50 
51 extern int main(int, char **, char **);
52 
53 typedef void (*fptr_t)(void);
54 #ifndef HAVE_INITFINI_ARRAY
55 extern void	_init(void);
56 extern void	_fini(void);
57 #endif
58 extern void	_libc_init(void);
59 
60 /*
61  * Arrange for _DYNAMIC to be weak and undefined (and therefore to show up
62  * as being at address zero, unless something else defines it).  That way,
63  * if we happen to be compiling without -static but with without any
64  * shared libs present, things will still work.
65  */
66 
67 __weakref_visible int rtld_DYNAMIC __weak_reference(_DYNAMIC);
68 
69 #ifdef MCRT0
70 extern void	monstartup(u_long, u_long);
71 extern void	_mcleanup(void);
72 extern unsigned char __etext, __eprol;
73 #endif /* MCRT0 */
74 
75 static char	 empty_string[] = "";
76 
77 char		**environ __common;
78 struct ps_strings *__ps_strings __common = 0;
79 char		*__progname __common = empty_string;
80 
81 __dead __dso_hidden void ___start(void (*)(void), struct ps_strings *);
82 
83 #define	write(fd, s, n)	__syscall(SYS_write, (fd), (s), (n))
84 
85 #define	_FATAL(str)				\
86 do {						\
87 	write(2, str, sizeof(str)-1);		\
88 	_exit(1);				\
89 } while (0)
90 
91 /*
92  * If we are using INIT_ARRAY/FINI_ARRAY and we are linked statically,
93  * we have to process these instead of relying on RTLD to do it for us.
94  *
95  * Since we don't need .init or .fini sections, just code them in C
96  * to make life easier.
97  */
98 extern const fptr_t __preinit_array_start[] __dso_hidden;
99 extern const fptr_t __preinit_array_end[] __dso_hidden __weak;
100 extern const fptr_t __init_array_start[] __dso_hidden;
101 extern const fptr_t __init_array_end[] __dso_hidden __weak;
102 extern const fptr_t __fini_array_start[] __dso_hidden;
103 extern const fptr_t __fini_array_end[] __dso_hidden __weak;
104 
105 static inline void
106 _preinit(void)
107 {
108 	for (const fptr_t *f = __preinit_array_start; f < __preinit_array_end; f++) {
109 		(*f)();
110 	}
111 }
112 
113 static inline void
114 _initarray(void)
115 {
116 	for (const fptr_t *f = __init_array_start; f < __init_array_end; f++) {
117 		(*f)();
118 	}
119 }
120 
121 static void
122 _finiarray(void)
123 {
124 	for (const fptr_t *f = __fini_array_start; f < __fini_array_end; f++) {
125 		(*f)();
126 	}
127 }
128 
129 #if defined(__x86_64__) || defined(__powerpc__) || defined(__sparc__)
130 #define HAS_IPLTA
131 static void fix_iplta(void) __noinline;
132 #elif defined(__i386__) || defined(__arm__)
133 #define HAS_IPLT
134 static void fix_iplt(void) __noinline;
135 #endif
136 
137 
138 #ifdef HAS_IPLTA
139 #include <stdio.h>
140 extern const Elf_Rela __rela_iplt_start[] __dso_hidden __weak;
141 extern const Elf_Rela __rela_iplt_end[] __dso_hidden __weak;
142 #ifdef __sparc__
143 #define IFUNC_RELOCATION R_TYPE(JMP_IREL)
144 #include <machine/elf_support.h>
145 #define write_plt(where, value) sparc_write_branch((void *)where, (void *)value)
146 #else
147 #define IFUNC_RELOCATION R_TYPE(IRELATIVE)
148 #define write_plt(where, value) *where = value
149 #endif
150 
151 static void
152 fix_iplta(void)
153 {
154 	const Elf_Rela *rela, *relalim;
155 	uintptr_t relocbase = 0;
156 	Elf_Addr *where, target;
157 
158 	rela = __rela_iplt_start;
159 	relalim = __rela_iplt_end;
160 	for (; rela < relalim; ++rela) {
161 		if (ELF_R_TYPE(rela->r_info) != IFUNC_RELOCATION)
162 			abort();
163 		where = (Elf_Addr *)(relocbase + rela->r_offset);
164 		target = (Elf_Addr)(relocbase + rela->r_addend);
165 		target = ((Elf_Addr(*)(void))target)();
166 		write_plt(where, target);
167 	}
168 }
169 #endif
170 #ifdef HAS_IPLT
171 extern const Elf_Rel __rel_iplt_start[] __dso_hidden __weak;
172 extern const Elf_Rel __rel_iplt_end[] __dso_hidden __weak;
173 #define IFUNC_RELOCATION R_TYPE(IRELATIVE)
174 
175 static void
176 fix_iplt(void)
177 {
178 	const Elf_Rel *rel, *rellim;
179 	uintptr_t relocbase = 0;
180 	Elf_Addr *where, target;
181 
182 	rel = __rel_iplt_start;
183 	rellim = __rel_iplt_end;
184 	for (; rel < rellim; ++rel) {
185 		if (ELF_R_TYPE(rel->r_info) != IFUNC_RELOCATION)
186 			abort();
187 		where = (Elf_Addr *)(relocbase + rel->r_offset);
188 		target = ((Elf_Addr(*)(void))*where)();
189 		*where = target;
190 	}
191 }
192 #endif
193 
194 #if defined(__x86_64__) || defined(__i386__)
195 #  define HAS_RELOCATE_SELF
196 #  if defined(__x86_64__)
197 #  define RELA
198 #  define REL_TAG DT_RELA
199 #  define RELSZ_TAG DT_RELASZ
200 #  define REL_TYPE Elf_Rela
201 #  else
202 #  define REL_TAG DT_REL
203 #  define RELSZ_TAG DT_RELSZ
204 #  define REL_TYPE Elf_Rel
205 #  endif
206 
207 #include <elf.h>
208 
209 static void relocate_self(struct ps_strings *) __noinline;
210 
211 static void
212 relocate_self(struct ps_strings *ps_strings)
213 {
214 	AuxInfo *aux = (AuxInfo *)(ps_strings->ps_argvstr + ps_strings->ps_nargvstr +
215 	    ps_strings->ps_nenvstr + 2);
216 	uintptr_t relocbase = (uintptr_t)~0U;
217 	const Elf_Phdr *phdr = NULL;
218 	Elf_Half phnum = (Elf_Half)~0;
219 
220 	for (; aux->a_type != AT_NULL; ++aux) {
221 		switch (aux->a_type) {
222 		case AT_BASE:
223 			if (aux->a_v)
224 				return;
225 			break;
226 		case AT_PHDR:
227 			phdr = (void *)aux->a_v;
228 			break;
229 		case AT_PHNUM:
230 			phnum = (Elf_Half)aux->a_v;
231 			break;
232 		}
233 	}
234 
235 	if (phdr == NULL || phnum == (Elf_Half)~0)
236 		return;
237 
238 	const Elf_Phdr *phlimit = phdr + phnum, *dynphdr = NULL;
239 
240 	for (; phdr < phlimit; ++phdr) {
241 		if (phdr->p_type == PT_DYNAMIC)
242 			dynphdr = phdr;
243 		if (phdr->p_type == PT_PHDR)
244 			relocbase = (uintptr_t)phdr - phdr->p_vaddr;
245 	}
246 	if (dynphdr == NULL || relocbase == (uintptr_t)~0U)
247 		return;
248 
249 	Elf_Dyn *dynp = (Elf_Dyn *)((uint8_t *)dynphdr->p_vaddr + relocbase);
250 
251 	const REL_TYPE *relocs = 0, *relocslim;
252 	Elf_Addr relocssz = 0;
253 
254 	for (; dynp->d_tag != DT_NULL; dynp++) {
255 		switch (dynp->d_tag) {
256 		case REL_TAG:
257 			relocs =
258 			    (const REL_TYPE *)(relocbase + dynp->d_un.d_ptr);
259 			break;
260 		case RELSZ_TAG:
261 			relocssz = dynp->d_un.d_val;
262 			break;
263 		}
264 	}
265 	relocslim = (const REL_TYPE *)((const uint8_t *)relocs + relocssz);
266 	for (; relocs < relocslim; ++relocs) {
267 		Elf_Addr *where;
268 
269 		where = (Elf_Addr *)(relocbase + relocs->r_offset);
270 
271 		switch (ELF_R_TYPE(relocs->r_info)) {
272 		case R_TYPE(RELATIVE):  /* word64 B + A */
273 #ifdef RELA
274 			*where = (Elf_Addr)(relocbase + relocs->r_addend);
275 #else
276 			*where += (Elf_Addr)relocbase;
277 #endif
278 			break;
279 #ifdef IFUNC_RELOCATION
280 		case IFUNC_RELOCATION:
281 			break;
282 #endif
283 		default:
284 			abort();
285 		}
286 	}
287 }
288 #endif
289 
290 void
291 ___start(void (*cleanup)(void),			/* from shared loader */
292     struct ps_strings *ps_strings)
293 {
294 #if defined(HAS_RELOCATE_SELF)
295 	relocate_self(ps_strings);
296 #endif
297 
298 	if (ps_strings == NULL)
299 		_FATAL("ps_strings missing\n");
300 	__ps_strings = ps_strings;
301 
302 	environ = ps_strings->ps_envstr;
303 
304 	if (ps_strings->ps_argvstr[0] != NULL) {
305 		char *c;
306 		__progname = ps_strings->ps_argvstr[0];
307 		for (c = ps_strings->ps_argvstr[0]; *c; ++c) {
308 			if (*c == '/')
309 				__progname = c + 1;
310 		}
311 	} else {
312 		__progname = empty_string;
313 	}
314 
315 	if (cleanup != NULL)
316 		atexit(cleanup);
317 
318 	_libc_init();
319 
320 	if (&rtld_DYNAMIC == NULL) {
321 #ifdef HAS_IPLTA
322 		fix_iplta();
323 #endif
324 #ifdef HAS_IPLT
325 		fix_iplt();
326 #endif
327 	}
328 
329 	_preinit();
330 
331 #ifdef MCRT0
332 	atexit(_mcleanup);
333 	monstartup((u_long)&__eprol, (u_long)&__etext);
334 #endif
335 
336 	atexit(_finiarray);
337 	_initarray();
338 
339 #ifndef HAVE_INITFINI_ARRAY
340 	atexit(_fini);
341 	_init();
342 #endif
343 
344 	exit(main(ps_strings->ps_nargvstr, ps_strings->ps_argvstr, environ));
345 }
346