xref: /freebsd/libexec/rtld-elf/powerpc/reloc.c (revision 9a14aa017b21c292740c00ee098195cd46642730)
1 /*      $NetBSD: ppc_reloc.c,v 1.10 2001/09/10 06:09:41 mycroft Exp $   */
2 
3 /*-
4  * Copyright (C) 1998   Tsubai Masanari
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  * 3. The name of the author may not be used to endorse or promote products
16  *    derived from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31 
32 #include <sys/param.h>
33 #include <sys/mman.h>
34 
35 #include <errno.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <unistd.h>
40 #include <machine/cpu.h>
41 #include <machine/cpufunc.h>
42 #include <machine/md_var.h>
43 
44 #include "debug.h"
45 #include "rtld.h"
46 
47 #define _ppc_ha(x) ((((u_int32_t)(x) & 0x8000) ? \
48                         ((u_int32_t)(x) + 0x10000) : (u_int32_t)(x)) >> 16)
49 #define _ppc_la(x) ((u_int32_t)(x) & 0xffff)
50 
51 #define min(a,b) (((a) < (b)) ? (a) : (b))
52 #define max(a,b) (((a) > (b)) ? (a) : (b))
53 
54 #define PLT_EXTENDED_BEGIN	(1 << 13)
55 #define JMPTAB_BASE(N)		(18 + N*2 + ((N > PLT_EXTENDED_BEGIN) ? \
56 				    (N - PLT_EXTENDED_BEGIN)*2 : 0))
57 
58 /*
59  * Process the R_PPC_COPY relocations
60  */
61 int
62 do_copy_relocations(Obj_Entry *dstobj)
63 {
64 	const Elf_Rela *relalim;
65 	const Elf_Rela *rela;
66 
67 	/*
68 	 * COPY relocs are invalid outside of the main program
69 	 */
70 	assert(dstobj->mainprog);
71 
72 	relalim = (const Elf_Rela *) ((caddr_t) dstobj->rela +
73 	    dstobj->relasize);
74 	for (rela = dstobj->rela;  rela < relalim;  rela++) {
75 		void *dstaddr;
76 		const Elf_Sym *dstsym;
77 		const char *name;
78 		size_t size;
79 		const void *srcaddr;
80 		const Elf_Sym *srcsym = NULL;
81 		const Obj_Entry *srcobj, *defobj;
82 		SymLook req;
83 		int res;
84 
85 		if (ELF_R_TYPE(rela->r_info) != R_PPC_COPY) {
86 			continue;
87 		}
88 
89 		dstaddr = (void *) (dstobj->relocbase + rela->r_offset);
90 		dstsym = dstobj->symtab + ELF_R_SYM(rela->r_info);
91 		name = dstobj->strtab + dstsym->st_name;
92 		size = dstsym->st_size;
93 		symlook_init(&req, name);
94 		req.ventry = fetch_ventry(dstobj, ELF_R_SYM(rela->r_info));
95 
96 		for (srcobj = dstobj->next;  srcobj != NULL;
97 		     srcobj = srcobj->next) {
98 			res = symlook_obj(&req, srcobj);
99 			if (res == 0) {
100 				srcsym = req.sym_out;
101 				defobj = req.defobj_out;
102 				break;
103 			}
104 		}
105 
106 		if (srcobj == NULL) {
107 			_rtld_error("Undefined symbol \"%s\" "
108 				    " referenced from COPY"
109 				    " relocation in %s", name, dstobj->path);
110 			return (-1);
111 		}
112 
113 		srcaddr = (const void *) (defobj->relocbase+srcsym->st_value);
114 		memcpy(dstaddr, srcaddr, size);
115 		dbg("copy_reloc: src=%p,dst=%p,size=%d\n",srcaddr,dstaddr,size);
116 	}
117 
118 	return (0);
119 }
120 
121 
122 /*
123  * Perform early relocation of the run-time linker image
124  */
125 void
126 reloc_non_plt_self(Elf_Dyn *dynp, Elf_Addr relocbase)
127 {
128 	const Elf_Rela *rela = 0, *relalim;
129 	Elf_Addr relasz = 0;
130 	Elf_Addr *where;
131 
132 	/*
133 	 * Extract the rela/relasz values from the dynamic section
134 	 */
135 	for (; dynp->d_tag != DT_NULL; dynp++) {
136 		switch (dynp->d_tag) {
137 		case DT_RELA:
138 			rela = (const Elf_Rela *)(relocbase+dynp->d_un.d_ptr);
139 			break;
140 		case DT_RELASZ:
141 			relasz = dynp->d_un.d_val;
142 			break;
143 		}
144 	}
145 
146 	/*
147 	 * Relocate these values
148 	 */
149 	relalim = (const Elf_Rela *)((caddr_t)rela + relasz);
150 	for (; rela < relalim; rela++) {
151 		where = (Elf_Addr *)(relocbase + rela->r_offset);
152 		*where = (Elf_Addr)(relocbase + rela->r_addend);
153 	}
154 }
155 
156 
157 /*
158  * Relocate a non-PLT object with addend.
159  */
160 static int
161 reloc_nonplt_object(Obj_Entry *obj_rtld, Obj_Entry *obj, const Elf_Rela *rela,
162     SymCache *cache, RtldLockState *lockstate)
163 {
164 	Elf_Addr        *where = (Elf_Addr *)(obj->relocbase + rela->r_offset);
165 	const Elf_Sym   *def;
166 	const Obj_Entry *defobj;
167 	Elf_Addr         tmp;
168 
169 	switch (ELF_R_TYPE(rela->r_info)) {
170 
171 	case R_PPC_NONE:
172 		break;
173 
174         case R_PPC_ADDR32:    /* word32 S + A */
175         case R_PPC_GLOB_DAT:  /* word32 S + A */
176 		def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
177 		    false, cache, lockstate);
178 		if (def == NULL) {
179 			return (-1);
180 		}
181 
182                 tmp = (Elf_Addr)(defobj->relocbase + def->st_value +
183                     rela->r_addend);
184 
185 		/* Don't issue write if unnecessary; avoid COW page fault */
186                 if (*where != tmp) {
187                         *where = tmp;
188 		}
189                 break;
190 
191         case R_PPC_RELATIVE:  /* word32 B + A */
192 		tmp = (Elf_Addr)(obj->relocbase + rela->r_addend);
193 
194 		/* As above, don't issue write unnecessarily */
195 		if (*where != tmp) {
196 			*where = tmp;
197 		}
198 		break;
199 
200 	case R_PPC_COPY:
201 		/*
202 		 * These are deferred until all other relocations
203 		 * have been done.  All we do here is make sure
204 		 * that the COPY relocation is not in a shared
205 		 * library.  They are allowed only in executable
206 		 * files.
207 		 */
208 		if (!obj->mainprog) {
209 			_rtld_error("%s: Unexpected R_COPY "
210 				    " relocation in shared library",
211 				    obj->path);
212 			return (-1);
213 		}
214 		break;
215 
216 	case R_PPC_JMP_SLOT:
217 		/*
218 		 * These will be handled by the plt/jmpslot routines
219 		 */
220 		break;
221 
222 	case R_PPC_DTPMOD32:
223 		def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
224 		    false, cache, lockstate);
225 
226 		if (def == NULL)
227 			return (-1);
228 
229 		*where = (Elf_Addr) defobj->tlsindex;
230 
231 		break;
232 
233 	case R_PPC_TPREL32:
234 		def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
235 		    false, cache, lockstate);
236 
237 		if (def == NULL)
238 			return (-1);
239 
240 		/*
241 		 * We lazily allocate offsets for static TLS as we
242 		 * see the first relocation that references the
243 		 * TLS block. This allows us to support (small
244 		 * amounts of) static TLS in dynamically loaded
245 		 * modules. If we run out of space, we generate an
246 		 * error.
247 		 */
248 		if (!defobj->tls_done) {
249 			if (!allocate_tls_offset((Obj_Entry*) defobj)) {
250 				_rtld_error("%s: No space available for static "
251 				    "Thread Local Storage", obj->path);
252 				return (-1);
253 			}
254 		}
255 
256 		*(Elf_Addr **)where = *where * sizeof(Elf_Addr)
257 		    + (Elf_Addr *)(def->st_value + rela->r_addend
258 		    + defobj->tlsoffset - TLS_TP_OFFSET);
259 
260 		break;
261 
262 	case R_PPC_DTPREL32:
263 		def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
264 		    false, cache, lockstate);
265 
266 		if (def == NULL)
267 			return (-1);
268 
269 		*where += (Elf_Addr)(def->st_value + rela->r_addend
270 		    - TLS_DTV_OFFSET);
271 
272 		break;
273 
274 	default:
275 		_rtld_error("%s: Unsupported relocation type %d"
276 			    " in non-PLT relocations\n", obj->path,
277 			    ELF_R_TYPE(rela->r_info));
278 		return (-1);
279         }
280 	return (0);
281 }
282 
283 
284 /*
285  * Process non-PLT relocations
286  */
287 int
288 reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, RtldLockState *lockstate)
289 {
290 	const Elf_Rela *relalim;
291 	const Elf_Rela *rela;
292 	SymCache *cache;
293 	int r = -1;
294 
295 	/*
296 	 * The dynamic loader may be called from a thread, we have
297 	 * limited amounts of stack available so we cannot use alloca().
298 	 */
299 	if (obj != obj_rtld) {
300 		cache = calloc(obj->nchains, sizeof(SymCache));
301 		/* No need to check for NULL here */
302 	} else
303 		cache = NULL;
304 
305 	/*
306 	 * From the SVR4 PPC ABI:
307 	 * "The PowerPC family uses only the Elf32_Rela relocation
308 	 *  entries with explicit addends."
309 	 */
310 	relalim = (const Elf_Rela *)((caddr_t)obj->rela + obj->relasize);
311 	for (rela = obj->rela; rela < relalim; rela++) {
312 		if (reloc_nonplt_object(obj_rtld, obj, rela, cache, lockstate)
313 		    < 0)
314 			goto done;
315 	}
316 	r = 0;
317 done:
318 	if (cache != NULL)
319 		free(cache);
320 
321 	/* Synchronize icache for text seg in case we made any changes */
322 	__syncicache(obj->mapbase, obj->textsize);
323 
324 	return (r);
325 }
326 
327 /*
328  * Initialise a PLT slot to the resolving trampoline
329  */
330 static int
331 reloc_plt_object(Obj_Entry *obj, const Elf_Rela *rela)
332 {
333 	Elf_Word *where = (Elf_Word *)(obj->relocbase + rela->r_offset);
334 	Elf_Addr *pltresolve, *pltlongresolve, *jmptab;
335 	Elf_Addr distance;
336 	int N = obj->pltrelasize / sizeof(Elf_Rela);
337 	int reloff;
338 
339 	reloff = rela - obj->pltrela;
340 
341 	if (reloff < 0)
342 		return (-1);
343 
344 	pltlongresolve = obj->pltgot + 5;
345 	pltresolve = pltlongresolve + 5;
346 
347 	distance = (Elf_Addr)pltresolve - (Elf_Addr)(where + 1);
348 
349 	dbg(" reloc_plt_object: where=%p,pltres=%p,reloff=%x,distance=%x",
350 	    (void *)where, (void *)pltresolve, reloff, distance);
351 
352 	if (reloff < PLT_EXTENDED_BEGIN) {
353 		/* li   r11,reloff  */
354 		/* b    pltresolve  */
355 		where[0] = 0x39600000 | reloff;
356 		where[1] = 0x48000000 | (distance & 0x03fffffc);
357 	} else {
358 		jmptab = obj->pltgot + JMPTAB_BASE(N);
359 		jmptab[reloff] = (u_int)pltlongresolve;
360 
361 		/* lis	r11,jmptab[reloff]@ha */
362 		/* lwzu	r12,jmptab[reloff]@l(r11) */
363 		/* mtctr r12 */
364 		/* bctr */
365 		where[0] = 0x3d600000 | _ppc_ha(&jmptab[reloff]);
366 		where[1] = 0x858b0000 | _ppc_la(&jmptab[reloff]);
367 		where[2] = 0x7d8903a6;
368 		where[3] = 0x4e800420;
369 	}
370 
371 
372 	/*
373 	 * The icache will be sync'd in reloc_plt, which is called
374 	 * after all the slots have been updated
375 	 */
376 
377 	return (0);
378 }
379 
380 
381 /*
382  * Process the PLT relocations.
383  */
384 int
385 reloc_plt(Obj_Entry *obj)
386 {
387 	const Elf_Rela *relalim;
388 	const Elf_Rela *rela;
389 	int N = obj->pltrelasize / sizeof(Elf_Rela);
390 
391 	if (obj->pltrelasize != 0) {
392 
393 		relalim = (const Elf_Rela *)((char *)obj->pltrela +
394 		    obj->pltrelasize);
395 		for (rela = obj->pltrela;  rela < relalim;  rela++) {
396 			assert(ELF_R_TYPE(rela->r_info) == R_PPC_JMP_SLOT);
397 
398 			if (reloc_plt_object(obj, rela) < 0) {
399 				return (-1);
400 			}
401 		}
402 	}
403 
404 	/*
405 	 * Sync the icache for the byte range represented by the
406 	 * trampoline routines and call slots.
407 	 */
408 	if (obj->pltgot != NULL)
409 		__syncicache(obj->pltgot, JMPTAB_BASE(N)*4);
410 
411 	return (0);
412 }
413 
414 
415 /*
416  * LD_BIND_NOW was set - force relocation for all jump slots
417  */
418 int
419 reloc_jmpslots(Obj_Entry *obj, RtldLockState *lockstate)
420 {
421 	const Obj_Entry *defobj;
422 	const Elf_Rela *relalim;
423 	const Elf_Rela *rela;
424 	const Elf_Sym *def;
425 	Elf_Addr *where;
426 	Elf_Addr target;
427 
428 	relalim = (const Elf_Rela *)((char *)obj->pltrela + obj->pltrelasize);
429 	for (rela = obj->pltrela; rela < relalim; rela++) {
430 		assert(ELF_R_TYPE(rela->r_info) == R_PPC_JMP_SLOT);
431 		where = (Elf_Addr *)(obj->relocbase + rela->r_offset);
432 		def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
433 		    true, NULL, lockstate);
434 		if (def == NULL) {
435 			dbg("reloc_jmpslots: sym not found");
436 			return (-1);
437 		}
438 
439 		target = (Elf_Addr)(defobj->relocbase + def->st_value);
440 
441 #if 0
442 		/* PG XXX */
443 		dbg("\"%s\" in \"%s\" --> %p in \"%s\"",
444 		    defobj->strtab + def->st_name, basename(obj->path),
445 		    (void *)target, basename(defobj->path));
446 #endif
447 
448 		reloc_jmpslot(where, target, defobj, obj,
449 		    (const Elf_Rel *) rela);
450 	}
451 
452 	obj->jmpslots_done = true;
453 
454 	return (0);
455 }
456 
457 
458 /*
459  * Update the value of a PLT jump slot. Branch directly to the target if
460  * it is within +/- 32Mb, otherwise go indirectly via the pltcall
461  * trampoline call and jump table.
462  */
463 Elf_Addr
464 reloc_jmpslot(Elf_Addr *wherep, Elf_Addr target, const Obj_Entry *defobj,
465 	      const Obj_Entry *obj, const Elf_Rel *rel)
466 {
467 	Elf_Addr offset;
468 	const Elf_Rela *rela = (const Elf_Rela *) rel;
469 
470 	dbg(" reloc_jmpslot: where=%p, target=%p",
471 	    (void *)wherep, (void *)target);
472 
473 	/*
474 	 * At the PLT entry pointed at by `wherep', construct
475 	 * a direct transfer to the now fully resolved function
476 	 * address.
477 	 */
478 	offset = target - (Elf_Addr)wherep;
479 
480 	if (abs(offset) < 32*1024*1024) {     /* inside 32MB? */
481 		/* b    value   # branch directly */
482 		*wherep = 0x48000000 | (offset & 0x03fffffc);
483 		__syncicache(wherep, 4);
484 	} else {
485 		Elf_Addr *pltcall, *jmptab;
486 		int distance;
487 		int N = obj->pltrelasize / sizeof(Elf_Rela);
488 		int reloff = rela - obj->pltrela;
489 
490 		if (reloff < 0)
491 			return (-1);
492 
493 		pltcall = obj->pltgot;
494 
495 		dbg(" reloc_jmpslot: indir, reloff=%x, N=%x\n",
496 		    reloff, N);
497 
498 		jmptab = obj->pltgot + JMPTAB_BASE(N);
499 		jmptab[reloff] = target;
500 		powerpc_mb(); /* Order jmptab update before next changes */
501 
502 		if (reloff < PLT_EXTENDED_BEGIN) {
503 			/* for extended PLT entries, we keep the old code */
504 
505 			distance = (Elf_Addr)pltcall - (Elf_Addr)(wherep + 1);
506 
507 			/* li   r11,reloff */
508 			/* b    pltcall  # use indirect pltcall routine */
509 
510 			/* first instruction same as before */
511 			wherep[1] = 0x48000000 | (distance & 0x03fffffc);
512 			__syncicache(wherep, 8);
513 		}
514 	}
515 
516 	return (target);
517 }
518 
519 int
520 reloc_iresolve(Obj_Entry *obj, struct Struct_RtldLockState *lockstate)
521 {
522 
523 	/* XXX not implemented */
524 	return (0);
525 }
526 
527 int
528 reloc_gnu_ifunc(Obj_Entry *obj, struct Struct_RtldLockState *lockstate)
529 {
530 
531 	/* XXX not implemented */
532 	return (0);
533 }
534 
535 /*
536  * Setup the plt glue routines.
537  */
538 #define PLTCALL_SIZE	   	20
539 #define PLTLONGRESOLVE_SIZE	20
540 #define PLTRESOLVE_SIZE		24
541 
542 void
543 init_pltgot(Obj_Entry *obj)
544 {
545 	Elf_Word *pltcall, *pltresolve, *pltlongresolve;
546 	Elf_Word *jmptab;
547 	int N = obj->pltrelasize / sizeof(Elf_Rela);
548 
549 	pltcall = obj->pltgot;
550 
551 	if (pltcall == NULL) {
552 		return;
553 	}
554 
555 	/*
556 	 * From the SVR4 PPC ABI:
557 	 *
558 	 * 'The first 18 words (72 bytes) of the PLT are reserved for
559 	 * use by the dynamic linker.
560 	 *   ...
561 	 * 'If the executable or shared object requires N procedure
562 	 *  linkage table entries, the link editor shall reserve 3*N
563 	 *  words (12*N bytes) following the 18 reserved words. The
564 	 *  first 2*N of these words are the procedure linkage table
565 	 *  entries themselves. The static linker directs calls to bytes
566 	 *  (72 + (i-1)*8), for i between 1 and N inclusive. The remaining
567 	 *  N words (4*N bytes) are reserved for use by the dynamic linker.'
568 	 */
569 
570 	/*
571 	 * Copy the absolute-call assembler stub into the first part of
572 	 * the reserved PLT area.
573 	 */
574 	memcpy(pltcall, _rtld_powerpc_pltcall, PLTCALL_SIZE);
575 
576 	/*
577 	 * Determine the address of the jumptable, which is the dyn-linker
578 	 * reserved area after the call cells. Write the absolute address
579 	 * of the jumptable into the absolute-call assembler code so it
580 	 * can determine this address.
581 	 */
582 	jmptab = obj->pltgot + JMPTAB_BASE(N);
583 	pltcall[1] |= _ppc_ha(jmptab);	   /* addis 11,11,jmptab@ha */
584 	pltcall[2] |= _ppc_la(jmptab);     /* lwz   11,jmptab@l(11) */
585 
586 	/*
587 	 * Skip down 20 bytes into the initial reserved area and copy
588 	 * in the standard resolving assembler call. Into this assembler,
589 	 * insert the absolute address of the _rtld_bind_start routine
590 	 * and the address of the relocation object.
591 	 *
592 	 * We place pltlongresolve first, so it can fix up its arguments
593 	 * and then fall through to the regular PLT resolver.
594 	 */
595 	pltlongresolve = obj->pltgot + 5;
596 
597 	memcpy(pltlongresolve, _rtld_powerpc_pltlongresolve,
598 	    PLTLONGRESOLVE_SIZE);
599 	pltlongresolve[0] |= _ppc_ha(jmptab);	/* lis	12,jmptab@ha	*/
600 	pltlongresolve[1] |= _ppc_la(jmptab);	/* addi	12,12,jmptab@l	*/
601 
602 	pltresolve = pltlongresolve + PLTLONGRESOLVE_SIZE/sizeof(uint32_t);
603 	memcpy(pltresolve, _rtld_powerpc_pltresolve, PLTRESOLVE_SIZE);
604 	pltresolve[0] |= _ppc_ha(_rtld_bind_start);
605 	pltresolve[1] |= _ppc_la(_rtld_bind_start);
606 	pltresolve[3] |= _ppc_ha(obj);
607 	pltresolve[4] |= _ppc_la(obj);
608 
609 	/*
610 	 * The icache will be sync'd in reloc_plt, which is called
611 	 * after all the slots have been updated
612 	 */
613 }
614 
615 void
616 allocate_initial_tls(Obj_Entry *list)
617 {
618 	register Elf_Addr **tp __asm__("r2");
619 	Elf_Addr **_tp;
620 
621 	/*
622 	* Fix the size of the static TLS block by using the maximum
623 	* offset allocated so far and adding a bit for dynamic modules to
624 	* use.
625 	*/
626 
627 	tls_static_space = tls_last_offset + tls_last_size + RTLD_STATIC_TLS_EXTRA;
628 
629 	_tp = (Elf_Addr **) ((char *) allocate_tls(list, NULL, TLS_TCB_SIZE, 8)
630 	    + TLS_TP_OFFSET + TLS_TCB_SIZE);
631 
632 	/*
633 	 * XXX gcc seems to ignore 'tp = _tp;'
634 	 */
635 
636 	__asm __volatile("mr %0,%1" : "=r"(tp) : "r"(_tp));
637 }
638 
639 void*
640 __tls_get_addr(tls_index* ti)
641 {
642 	register Elf_Addr **tp __asm__("r2");
643 	char *p;
644 
645 	p = tls_get_addr_common((Elf_Addr**)((Elf_Addr)tp - TLS_TP_OFFSET
646 	    - TLS_TCB_SIZE), ti->ti_module, ti->ti_offset);
647 
648 	return (p + TLS_DTV_OFFSET);
649 }
650