xref: /freebsd/libexec/rtld-elf/amd64/reloc.c (revision 0957b409)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright 1996, 1997, 1998, 1999 John D. Polstra.
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 ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  *
27  * $FreeBSD$
28  */
29 
30 /*
31  * Dynamic linker for ELF.
32  *
33  * John Polstra <jdp@polstra.com>.
34  */
35 
36 #include <sys/param.h>
37 #include <sys/mman.h>
38 #include <machine/cpufunc.h>
39 #include <machine/specialreg.h>
40 #include <machine/sysarch.h>
41 
42 #include <dlfcn.h>
43 #include <err.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <stdarg.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51 
52 #include "debug.h"
53 #include "rtld.h"
54 #include "rtld_tls.h"
55 
56 /*
57  * Process the special R_X86_64_COPY relocations in the main program.  These
58  * copy data from a shared object into a region in the main program's BSS
59  * segment.
60  *
61  * Returns 0 on success, -1 on failure.
62  */
63 int
64 do_copy_relocations(Obj_Entry *dstobj)
65 {
66     const Elf_Rela *relalim;
67     const Elf_Rela *rela;
68 
69     assert(dstobj->mainprog);	/* COPY relocations are invalid elsewhere */
70 
71     relalim = (const Elf_Rela *)((const char *) dstobj->rela + dstobj->relasize);
72     for (rela = dstobj->rela;  rela < relalim;  rela++) {
73 	if (ELF_R_TYPE(rela->r_info) == R_X86_64_COPY) {
74 	    void *dstaddr;
75 	    const Elf_Sym *dstsym;
76 	    const char *name;
77 	    size_t size;
78 	    const void *srcaddr;
79 	    const Elf_Sym *srcsym;
80 	    const Obj_Entry *srcobj, *defobj;
81 	    SymLook req;
82 	    int res;
83 
84 	    dstaddr = (void *)(dstobj->relocbase + rela->r_offset);
85 	    dstsym = dstobj->symtab + ELF_R_SYM(rela->r_info);
86 	    name = dstobj->strtab + dstsym->st_name;
87 	    size = dstsym->st_size;
88 	    symlook_init(&req, name);
89 	    req.ventry = fetch_ventry(dstobj, ELF_R_SYM(rela->r_info));
90 	    req.flags = SYMLOOK_EARLY;
91 
92 	    for (srcobj = globallist_next(dstobj); srcobj != NULL;
93 	      srcobj = globallist_next(srcobj)) {
94 		res = symlook_obj(&req, srcobj);
95 		if (res == 0) {
96 		    srcsym = req.sym_out;
97 		    defobj = req.defobj_out;
98 		    break;
99 		}
100 	    }
101 
102 	    if (srcobj == NULL) {
103 		_rtld_error("Undefined symbol \"%s\" referenced from COPY"
104 		  " relocation in %s", name, dstobj->path);
105 		return -1;
106 	    }
107 
108 	    srcaddr = (const void *)(defobj->relocbase + srcsym->st_value);
109 	    memcpy(dstaddr, srcaddr, size);
110 	}
111     }
112 
113     return 0;
114 }
115 
116 /* Initialize the special GOT entries. */
117 void
118 init_pltgot(Obj_Entry *obj)
119 {
120     if (obj->pltgot != NULL) {
121 	obj->pltgot[1] = (Elf_Addr) obj;
122 	obj->pltgot[2] = (Elf_Addr) &_rtld_bind_start;
123     }
124 }
125 
126 /* Process the non-PLT relocations. */
127 int
128 reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, int flags,
129     RtldLockState *lockstate)
130 {
131 	const Elf_Rela *relalim;
132 	const Elf_Rela *rela;
133 	SymCache *cache;
134 	const Elf_Sym *def;
135 	const Obj_Entry *defobj;
136 	Elf_Addr *where, symval;
137 	Elf32_Addr *where32;
138 	int r;
139 
140 	r = -1;
141 	symval = 0;
142 	def = NULL;
143 
144 	/*
145 	 * The dynamic loader may be called from a thread, we have
146 	 * limited amounts of stack available so we cannot use alloca().
147 	 */
148 	if (obj != obj_rtld) {
149 		cache = calloc(obj->dynsymcount, sizeof(SymCache));
150 		/* No need to check for NULL here */
151 	} else
152 		cache = NULL;
153 
154 	relalim = (const Elf_Rela *)((const char*)obj->rela + obj->relasize);
155 	for (rela = obj->rela;  rela < relalim;  rela++) {
156 		/*
157 		 * First, resolve symbol for relocations which
158 		 * reference symbols.
159 		 */
160 		switch (ELF_R_TYPE(rela->r_info)) {
161 		case R_X86_64_64:
162 		case R_X86_64_PC32:
163 		case R_X86_64_GLOB_DAT:
164 		case R_X86_64_TPOFF64:
165 		case R_X86_64_TPOFF32:
166 		case R_X86_64_DTPMOD64:
167 		case R_X86_64_DTPOFF64:
168 		case R_X86_64_DTPOFF32:
169 			def = find_symdef(ELF_R_SYM(rela->r_info), obj,
170 			    &defobj, flags, cache, lockstate);
171 			if (def == NULL)
172 				goto done;
173 			/*
174 			 * If symbol is IFUNC, only perform relocation
175 			 * when caller allowed it by passing
176 			 * SYMLOOK_IFUNC flag.  Skip the relocations
177 			 * otherwise.
178 			 *
179 			 * Also error out in case IFUNC relocations
180 			 * are specified for TLS, which cannot be
181 			 * usefully interpreted.
182 			 */
183 			if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC) {
184 				switch (ELF_R_TYPE(rela->r_info)) {
185 				case R_X86_64_64:
186 				case R_X86_64_PC32:
187 				case R_X86_64_GLOB_DAT:
188 					if ((flags & SYMLOOK_IFUNC) == 0) {
189 						obj->non_plt_gnu_ifunc = true;
190 						continue;
191 					}
192 					symval = (Elf_Addr)rtld_resolve_ifunc(
193 					    defobj, def);
194 					break;
195 				case R_X86_64_TPOFF64:
196 				case R_X86_64_TPOFF32:
197 				case R_X86_64_DTPMOD64:
198 				case R_X86_64_DTPOFF64:
199 				case R_X86_64_DTPOFF32:
200 					_rtld_error("%s: IFUNC for TLS reloc",
201 					    obj->path);
202 					goto done;
203 				}
204 			} else {
205 				if ((flags & SYMLOOK_IFUNC) != 0)
206 					continue;
207 				symval = (Elf_Addr)defobj->relocbase +
208 				    def->st_value;
209 			}
210 			break;
211 		default:
212 			if ((flags & SYMLOOK_IFUNC) != 0)
213 				continue;
214 			break;
215 		}
216 		where = (Elf_Addr *)(obj->relocbase + rela->r_offset);
217 		where32 = (Elf32_Addr *)where;
218 
219 		switch (ELF_R_TYPE(rela->r_info)) {
220 		case R_X86_64_NONE:
221 			break;
222 		case R_X86_64_64:
223 			*where = symval + rela->r_addend;
224 			break;
225 		case R_X86_64_PC32:
226 			/*
227 			 * I don't think the dynamic linker should
228 			 * ever see this type of relocation.  But the
229 			 * binutils-2.6 tools sometimes generate it.
230 			 */
231 			*where32 = (Elf32_Addr)(unsigned long)(symval +
232 		            rela->r_addend - (Elf_Addr)where);
233 			break;
234 		/* missing: R_X86_64_GOT32 R_X86_64_PLT32 */
235 		case R_X86_64_COPY:
236 			/*
237 			 * These are deferred until all other relocations have
238 			 * been done.  All we do here is make sure that the COPY
239 			 * relocation is not in a shared library.  They are
240 			 * allowed only in executable files.
241 			 */
242 			if (!obj->mainprog) {
243 				_rtld_error("%s: Unexpected R_X86_64_COPY "
244 				    "relocation in shared library", obj->path);
245 				goto done;
246 			}
247 			break;
248 		case R_X86_64_GLOB_DAT:
249 			*where = symval;
250 			break;
251 		case R_X86_64_TPOFF64:
252 			/*
253 			 * We lazily allocate offsets for static TLS
254 			 * as we see the first relocation that
255 			 * references the TLS block. This allows us to
256 			 * support (small amounts of) static TLS in
257 			 * dynamically loaded modules. If we run out
258 			 * of space, we generate an error.
259 			 */
260 			if (!defobj->tls_done) {
261 				if (!allocate_tls_offset(
262 				    __DECONST(Obj_Entry *, defobj))) {
263 					_rtld_error("%s: No space available "
264 					    "for static Thread Local Storage",
265 					    obj->path);
266 					goto done;
267 				}
268 			}
269 			*where = (Elf_Addr)(def->st_value - defobj->tlsoffset +
270 			    rela->r_addend);
271 			break;
272 		case R_X86_64_TPOFF32:
273 			/*
274 			 * We lazily allocate offsets for static TLS
275 			 * as we see the first relocation that
276 			 * references the TLS block. This allows us to
277 			 * support (small amounts of) static TLS in
278 			 * dynamically loaded modules. If we run out
279 			 * of space, we generate an error.
280 			 */
281 			if (!defobj->tls_done) {
282 				if (!allocate_tls_offset(
283 				    __DECONST(Obj_Entry *, defobj))) {
284 					_rtld_error("%s: No space available "
285 					    "for static Thread Local Storage",
286 					    obj->path);
287 					goto done;
288 				}
289 			}
290 			*where32 = (Elf32_Addr)(def->st_value -
291 			    defobj->tlsoffset + rela->r_addend);
292 			break;
293 		case R_X86_64_DTPMOD64:
294 			*where += (Elf_Addr)defobj->tlsindex;
295 			break;
296 		case R_X86_64_DTPOFF64:
297 			*where += (Elf_Addr)(def->st_value + rela->r_addend);
298 			break;
299 		case R_X86_64_DTPOFF32:
300 			*where32 += (Elf32_Addr)(def->st_value +
301 			    rela->r_addend);
302 			break;
303 		case R_X86_64_RELATIVE:
304 			*where = (Elf_Addr)(obj->relocbase + rela->r_addend);
305 			break;
306 		/*
307 		 * missing:
308 		 * R_X86_64_GOTPCREL, R_X86_64_32, R_X86_64_32S, R_X86_64_16,
309 		 * R_X86_64_PC16, R_X86_64_8, R_X86_64_PC8
310 		 */
311 		default:
312 			_rtld_error("%s: Unsupported relocation type %u"
313 			    " in non-PLT relocations\n", obj->path,
314 			    (unsigned int)ELF_R_TYPE(rela->r_info));
315 			goto done;
316 		}
317 	}
318 	r = 0;
319 done:
320 	free(cache);
321 	return (r);
322 }
323 
324 /* Process the PLT relocations. */
325 int
326 reloc_plt(Obj_Entry *obj, int flags __unused, RtldLockState *lockstate __unused)
327 {
328     const Elf_Rela *relalim;
329     const Elf_Rela *rela;
330 
331     relalim = (const Elf_Rela *)((const char *)obj->pltrela + obj->pltrelasize);
332     for (rela = obj->pltrela;  rela < relalim;  rela++) {
333 	Elf_Addr *where;
334 
335 	switch(ELF_R_TYPE(rela->r_info)) {
336 	case R_X86_64_JMP_SLOT:
337 	  /* Relocate the GOT slot pointing into the PLT. */
338 	  where = (Elf_Addr *)(obj->relocbase + rela->r_offset);
339 	  *where += (Elf_Addr)obj->relocbase;
340 	  break;
341 
342 	case R_X86_64_IRELATIVE:
343 	  obj->irelative = true;
344 	  break;
345 
346 	default:
347 	  _rtld_error("Unknown relocation type %x in PLT",
348 	    (unsigned int)ELF_R_TYPE(rela->r_info));
349 	  return (-1);
350 	}
351     }
352     return 0;
353 }
354 
355 /* Relocate the jump slots in an object. */
356 int
357 reloc_jmpslots(Obj_Entry *obj, int flags, RtldLockState *lockstate)
358 {
359     const Elf_Rela *relalim;
360     const Elf_Rela *rela;
361 
362     if (obj->jmpslots_done)
363 	return 0;
364     relalim = (const Elf_Rela *)((const char *)obj->pltrela + obj->pltrelasize);
365     for (rela = obj->pltrela;  rela < relalim;  rela++) {
366 	Elf_Addr *where, target;
367 	const Elf_Sym *def;
368 	const Obj_Entry *defobj;
369 
370 	switch (ELF_R_TYPE(rela->r_info)) {
371 	case R_X86_64_JMP_SLOT:
372 	  where = (Elf_Addr *)(obj->relocbase + rela->r_offset);
373 	  def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
374 		SYMLOOK_IN_PLT | flags, NULL, lockstate);
375 	  if (def == NULL)
376 	      return (-1);
377 	  if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC) {
378 	      obj->gnu_ifunc = true;
379 	      continue;
380 	  }
381 	  target = (Elf_Addr)(defobj->relocbase + def->st_value + rela->r_addend);
382 	  reloc_jmpslot(where, target, defobj, obj, (const Elf_Rel *)rela);
383 	  break;
384 
385 	case R_X86_64_IRELATIVE:
386 	  break;
387 
388 	default:
389 	  _rtld_error("Unknown relocation type %x in PLT",
390 	    (unsigned int)ELF_R_TYPE(rela->r_info));
391 	  return (-1);
392 	}
393     }
394     obj->jmpslots_done = true;
395     return 0;
396 }
397 
398 /* Fixup the jump slot at "where" to transfer control to "target". */
399 Elf_Addr
400 reloc_jmpslot(Elf_Addr *where, Elf_Addr target,
401     const struct Struct_Obj_Entry *obj  __unused,
402     const struct Struct_Obj_Entry *refobj  __unused,
403     const Elf_Rel *rel  __unused)
404 {
405 #ifdef dbg
406 	dbg("reloc_jmpslot: *%p = %p", where, (void *)target);
407 #endif
408 	if (!ld_bind_not)
409 		*where = target;
410 	return (target);
411 }
412 
413 int
414 reloc_iresolve(Obj_Entry *obj, RtldLockState *lockstate)
415 {
416     const Elf_Rela *relalim;
417     const Elf_Rela *rela;
418 
419     if (!obj->irelative)
420 	return (0);
421     relalim = (const Elf_Rela *)((const char *)obj->pltrela + obj->pltrelasize);
422     for (rela = obj->pltrela;  rela < relalim;  rela++) {
423 	Elf_Addr *where, target, *ptr;
424 
425 	switch (ELF_R_TYPE(rela->r_info)) {
426 	case R_X86_64_JMP_SLOT:
427 	  break;
428 
429 	case R_X86_64_IRELATIVE:
430 	  ptr = (Elf_Addr *)(obj->relocbase + rela->r_addend);
431 	  where = (Elf_Addr *)(obj->relocbase + rela->r_offset);
432 	  lock_release(rtld_bind_lock, lockstate);
433 	  target = call_ifunc_resolver(ptr);
434 	  wlock_acquire(rtld_bind_lock, lockstate);
435 	  *where = target;
436 	  break;
437 	}
438     }
439     obj->irelative = false;
440     return (0);
441 }
442 
443 int
444 reloc_gnu_ifunc(Obj_Entry *obj, int flags, RtldLockState *lockstate)
445 {
446     const Elf_Rela *relalim;
447     const Elf_Rela *rela;
448 
449     if (!obj->gnu_ifunc)
450 	return (0);
451     relalim = (const Elf_Rela *)((const char *)obj->pltrela + obj->pltrelasize);
452     for (rela = obj->pltrela;  rela < relalim;  rela++) {
453 	Elf_Addr *where, target;
454 	const Elf_Sym *def;
455 	const Obj_Entry *defobj;
456 
457 	switch (ELF_R_TYPE(rela->r_info)) {
458 	case R_X86_64_JMP_SLOT:
459 	  where = (Elf_Addr *)(obj->relocbase + rela->r_offset);
460 	  def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
461 		SYMLOOK_IN_PLT | flags, NULL, lockstate);
462 	  if (def == NULL)
463 	      return (-1);
464 	  if (ELF_ST_TYPE(def->st_info) != STT_GNU_IFUNC)
465 	      continue;
466 	  lock_release(rtld_bind_lock, lockstate);
467 	  target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
468 	  wlock_acquire(rtld_bind_lock, lockstate);
469 	  reloc_jmpslot(where, target, defobj, obj, (const Elf_Rel *)rela);
470 	  break;
471 	}
472     }
473     obj->gnu_ifunc = false;
474     return (0);
475 }
476 
477 uint32_t cpu_feature, cpu_feature2, cpu_stdext_feature, cpu_stdext_feature2;
478 
479 void
480 ifunc_init(Elf_Auxinfo aux_info[__min_size(AT_COUNT)] __unused)
481 {
482 	u_int p[4], cpu_high;
483 
484 	do_cpuid(1, p);
485 	cpu_feature = p[3];
486 	cpu_feature2 = p[2];
487 	do_cpuid(0, p);
488 	cpu_high = p[0];
489 	if (cpu_high >= 7) {
490 		cpuid_count(7, 0, p);
491 		cpu_stdext_feature = p[1];
492 		cpu_stdext_feature2 = p[2];
493 	}
494 }
495 
496 void
497 pre_init(void)
498 {
499 
500 }
501 
502 int __getosreldate(void);
503 
504 void
505 allocate_initial_tls(Obj_Entry *objs)
506 {
507 	void *addr;
508 
509 	/*
510 	 * Fix the size of the static TLS block by using the maximum
511 	 * offset allocated so far and adding a bit for dynamic
512 	 * modules to use.
513 	 */
514 	tls_static_space = tls_last_offset + RTLD_STATIC_TLS_EXTRA;
515 
516 	addr = allocate_tls(objs, 0, 3 * sizeof(Elf_Addr), sizeof(Elf_Addr));
517 	if (__getosreldate() >= P_OSREL_WRFSBASE &&
518 	    (cpu_stdext_feature & CPUID_STDEXT_FSGSBASE) != 0)
519 		wrfsbase((uintptr_t)addr);
520 	else
521 		sysarch(AMD64_SET_FSBASE, &addr);
522 }
523 
524 void *__tls_get_addr(tls_index *ti)
525 {
526     Elf_Addr** segbase;
527 
528     __asm __volatile("movq %%fs:0, %0" : "=r" (segbase));
529 
530     return tls_get_addr_common(&segbase[1], ti->ti_module, ti->ti_offset);
531 }
532