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