xref: /freebsd/libexec/rtld-elf/powerpc/reloc.c (revision f0a75d274af375d15b97b830966b99a02b7db911)
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 
42 #include "debug.h"
43 #include "rtld.h"
44 
45 #define _ppc_ha(x) ((((u_int32_t)(x) & 0x8000) ? \
46                         ((u_int32_t)(x) + 0x10000) : (u_int32_t)(x)) >> 16)
47 #define _ppc_la(x) ((u_int32_t)(x) & 0xffff)
48 
49 /*
50  * Process the R_PPC_COPY relocations
51  */
52 int
53 do_copy_relocations(Obj_Entry *dstobj)
54 {
55 	const Elf_Rela *relalim;
56 	const Elf_Rela *rela;
57 
58 	/*
59 	 * COPY relocs are invalid outside of the main program
60 	 */
61 	assert(dstobj->mainprog);
62 
63 	relalim = (const Elf_Rela *) ((caddr_t) dstobj->rela +
64 	    dstobj->relasize);
65 	for (rela = dstobj->rela;  rela < relalim;  rela++) {
66 		void *dstaddr;
67 		const Elf_Sym *dstsym;
68 		const char *name;
69 		unsigned long hash;
70 		size_t size;
71 		const void *srcaddr;
72 		const Elf_Sym *srcsym = NULL;
73 		Obj_Entry *srcobj;
74 		const Ver_Entry *ve;
75 
76 		if (ELF_R_TYPE(rela->r_info) != R_PPC_COPY) {
77 			continue;
78 		}
79 
80 		dstaddr = (void *) (dstobj->relocbase + rela->r_offset);
81 		dstsym = dstobj->symtab + ELF_R_SYM(rela->r_info);
82 		name = dstobj->strtab + dstsym->st_name;
83 		hash = elf_hash(name);
84 		size = dstsym->st_size;
85 		ve = fetch_ventry(dstobj, ELF_R_SYM(rela->r_info));
86 
87 		for (srcobj = dstobj->next;  srcobj != NULL;
88 		     srcobj = srcobj->next) {
89 			if ((srcsym = symlook_obj(name, hash, srcobj, ve, 0))
90 			    != NULL) {
91 				break;
92 			}
93 		}
94 
95 		if (srcobj == NULL) {
96 			_rtld_error("Undefined symbol \"%s\" "
97 				    " referenced from COPY"
98 				    " relocation in %s", name, dstobj->path);
99 			return (-1);
100 		}
101 
102 		srcaddr = (const void *) (srcobj->relocbase+srcsym->st_value);
103 		memcpy(dstaddr, srcaddr, size);
104 		dbg("copy_reloc: src=%p,dst=%p,size=%d\n",srcaddr,dstaddr,size);
105 	}
106 
107 	return (0);
108 }
109 
110 
111 /*
112  * Perform early relocation of the run-time linker image
113  */
114 void
115 reloc_non_plt_self(Elf_Dyn *dynp, Elf_Addr relocbase)
116 {
117 	const Elf_Rela *rela = 0, *relalim;
118 	Elf_Addr relasz = 0;
119 	Elf_Addr *where;
120 
121 	/*
122 	 * Extract the rela/relasz values from the dynamic section
123 	 */
124 	for (; dynp->d_tag != DT_NULL; dynp++) {
125 		switch (dynp->d_tag) {
126 		case DT_RELA:
127 			rela = (const Elf_Rela *)(relocbase+dynp->d_un.d_ptr);
128 			break;
129 		case DT_RELASZ:
130 			relasz = dynp->d_un.d_val;
131 			break;
132 		}
133 	}
134 
135 	/*
136 	 * Relocate these values
137 	 */
138 	relalim = (const Elf_Rela *)((caddr_t)rela + relasz);
139 	for (; rela < relalim; rela++) {
140 		where = (Elf_Addr *)(relocbase + rela->r_offset);
141 		*where = (Elf_Addr)(relocbase + rela->r_addend);
142 	}
143 }
144 
145 
146 /*
147  * Relocate a non-PLT object with addend.
148  */
149 static int
150 reloc_nonplt_object(Obj_Entry *obj_rtld, Obj_Entry *obj, const Elf_Rela *rela,
151 		    SymCache *cache)
152 {
153 	Elf_Addr        *where = (Elf_Addr *)(obj->relocbase + rela->r_offset);
154 	const Elf_Sym   *def;
155 	const Obj_Entry *defobj;
156 	Elf_Addr         tmp;
157 
158 	switch (ELF_R_TYPE(rela->r_info)) {
159 
160 	case R_PPC_NONE:
161 		break;
162 
163         case R_PPC_ADDR32:    /* word32 S + A */
164         case R_PPC_GLOB_DAT:  /* word32 S + A */
165 		def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
166 				  false, cache);
167 		if (def == NULL) {
168 			return (-1);
169 		}
170 
171                 tmp = (Elf_Addr)(defobj->relocbase + def->st_value +
172                     rela->r_addend);
173 
174 		/* Don't issue write if unnecessary; avoid COW page fault */
175                 if (*where != tmp) {
176                         *where = tmp;
177 		}
178                 break;
179 
180         case R_PPC_RELATIVE:  /* word32 B + A */
181 		tmp = (Elf_Addr)(obj->relocbase + rela->r_addend);
182 
183 		/* As above, don't issue write unnecessarily */
184 		if (*where != tmp) {
185 			*where = tmp;
186 		}
187 		break;
188 
189 	case R_PPC_COPY:
190 		/*
191 		 * These are deferred until all other relocations
192 		 * have been done.  All we do here is make sure
193 		 * that the COPY relocation is not in a shared
194 		 * library.  They are allowed only in executable
195 		 * files.
196 		 */
197 		if (!obj->mainprog) {
198 			_rtld_error("%s: Unexpected R_COPY "
199 				    " relocation in shared library",
200 				    obj->path);
201 			return (-1);
202 		}
203 		break;
204 
205 	case R_PPC_JMP_SLOT:
206 		/*
207 		 * These will be handled by the plt/jmpslot routines
208 		 */
209 		break;
210 
211 	case R_PPC_DTPMOD32:
212 		def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
213 		    false, cache);
214 
215 		if (def == NULL)
216 			return (-1);
217 
218 		*where = (Elf_Addr) defobj->tlsindex;
219 
220 		break;
221 
222 	case R_PPC_TPREL32:
223 		def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
224 		    false, cache);
225 
226 		if (def == NULL)
227 			return (-1);
228 
229 		/*
230 		 * We lazily allocate offsets for static TLS as we
231 		 * see the first relocation that references the
232 		 * TLS block. This allows us to support (small
233 		 * amounts of) static TLS in dynamically loaded
234 		 * modules. If we run out of space, we generate an
235 		 * error.
236 		 */
237 		if (!defobj->tls_done) {
238 			if (!allocate_tls_offset((Obj_Entry*) defobj)) {
239 				_rtld_error("%s: No space available for static "
240 				    "Thread Local Storage", obj->path);
241 				return (-1);
242 			}
243 		}
244 
245 		*(Elf_Addr **)where = *where * sizeof(Elf_Addr)
246 		    + (Elf_Addr *)(def->st_value + rela->r_addend
247 		    + defobj->tlsoffset - TLS_TP_OFFSET);
248 
249 		break;
250 
251 	case R_PPC_DTPREL32:
252 		def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
253 		    false, cache);
254 
255 		if (def == NULL)
256 			return (-1);
257 
258 		*where += (Elf_Addr)(def->st_value + rela->r_addend
259 		    - TLS_DTV_OFFSET);
260 
261 		break;
262 
263 	default:
264 		_rtld_error("%s: Unsupported relocation type %d"
265 			    " in non-PLT relocations\n", obj->path,
266 			    ELF_R_TYPE(rela->r_info));
267 		return (-1);
268         }
269 	return (0);
270 }
271 
272 
273 /*
274  * Process non-PLT relocations
275  */
276 int
277 reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld)
278 {
279 	const Elf_Rela *relalim;
280 	const Elf_Rela *rela;
281 	SymCache *cache;
282 	int bytes = obj->nchains * sizeof(SymCache);
283 	int r = -1;
284 
285 	/*
286 	 * The dynamic loader may be called from a thread, we have
287 	 * limited amounts of stack available so we cannot use alloca().
288 	 */
289 	cache = mmap(NULL, bytes, PROT_READ|PROT_WRITE, MAP_ANON, -1, 0);
290 	if (cache == MAP_FAILED)
291 		cache = NULL;
292 
293 	/*
294 	 * From the SVR4 PPC ABI:
295 	 * "The PowerPC family uses only the Elf32_Rela relocation
296 	 *  entries with explicit addends."
297 	 */
298 	relalim = (const Elf_Rela *)((caddr_t)obj->rela + obj->relasize);
299 	for (rela = obj->rela; rela < relalim; rela++) {
300 		if (reloc_nonplt_object(obj_rtld, obj, rela, cache) < 0)
301 			goto done;
302 	}
303 	r = 0;
304 done:
305 	if (cache) {
306 		munmap(cache, bytes);
307 	}
308 	return (r);
309 }
310 
311 
312 /*
313  * Initialise a PLT slot to the resolving trampoline
314  */
315 static int
316 reloc_plt_object(Obj_Entry *obj, const Elf_Rela *rela)
317 {
318 	Elf_Word *where = (Elf_Word *)(obj->relocbase + rela->r_offset);
319 	Elf_Addr *pltresolve;
320 	Elf_Addr distance;
321 	int reloff;
322 
323 	reloff = rela - obj->pltrela;
324 
325 	if ((reloff < 0) || (reloff >= 0x8000)) {
326 		return (-1);
327 	}
328 
329 	pltresolve = obj->pltgot + 8;
330 
331 	distance = (Elf_Addr)pltresolve - (Elf_Addr)(where + 1);
332 
333 	dbg(" reloc_plt_object: where=%p,pltres=%p,reloff=%x,distance=%x",
334 	    (void *)where, (void *)pltresolve, reloff, distance);
335 
336 	/* li   r11,reloff  */
337 	/* b    pltresolve  */
338 	where[0] = 0x39600000 | reloff;
339 	where[1] = 0x48000000 | (distance & 0x03fffffc);
340 
341 	/*
342 	 * The icache will be sync'd in init_pltgot, which is called
343 	 * after all the slots have been updated
344 	 */
345 
346 	return (0);
347 }
348 
349 
350 /*
351  * Process the PLT relocations.
352  */
353 int
354 reloc_plt(Obj_Entry *obj)
355 {
356 	const Elf_Rela *relalim;
357 	const Elf_Rela *rela;
358 
359 	if (obj->pltrelasize != 0) {
360 
361 		relalim = (const Elf_Rela *)((char *)obj->pltrela +
362 		    obj->pltrelasize);
363 		for (rela = obj->pltrela;  rela < relalim;  rela++) {
364 			assert(ELF_R_TYPE(rela->r_info) == R_PPC_JMP_SLOT);
365 
366 			if (reloc_plt_object(obj, rela) < 0) {
367 				return (-1);
368 			}
369 		}
370 	}
371 
372 	return (0);
373 }
374 
375 
376 /*
377  * LD_BIND_NOW was set - force relocation for all jump slots
378  */
379 int
380 reloc_jmpslots(Obj_Entry *obj)
381 {
382 	const Obj_Entry *defobj;
383 	const Elf_Rela *relalim;
384 	const Elf_Rela *rela;
385 	const Elf_Sym *def;
386 	Elf_Addr *where;
387 	Elf_Addr target;
388 
389 	relalim = (const Elf_Rela *)((char *)obj->pltrela + obj->pltrelasize);
390 	for (rela = obj->pltrela; rela < relalim; rela++) {
391 		assert(ELF_R_TYPE(rela->r_info) == R_PPC_JMP_SLOT);
392 		where = (Elf_Addr *)(obj->relocbase + rela->r_offset);
393 		def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
394 		   true, NULL);
395 		if (def == NULL) {
396 			dbg("reloc_jmpslots: sym not found");
397 			return (-1);
398 		}
399 
400 		target = (Elf_Addr)(defobj->relocbase + def->st_value);
401 
402 #if 0
403 		/* PG XXX */
404 		dbg("\"%s\" in \"%s\" --> %p in \"%s\"",
405 		    defobj->strtab + def->st_name, basename(obj->path),
406 		    (void *)target, basename(defobj->path));
407 #endif
408 
409 		reloc_jmpslot(where, target, defobj, obj,
410 		    (const Elf_Rel *) rela);
411 	}
412 
413 	obj->jmpslots_done = true;
414 
415 	return (0);
416 }
417 
418 
419 /*
420  * Update the value of a PLT jump slot. Branch directly to the target if
421  * it is within +/- 32Mb, otherwise go indirectly via the pltcall
422  * trampoline call and jump table.
423  */
424 Elf_Addr
425 reloc_jmpslot(Elf_Addr *wherep, Elf_Addr target, const Obj_Entry *defobj,
426 	      const Obj_Entry *obj, const Elf_Rel *rel)
427 {
428 	Elf_Addr offset;
429 	const Elf_Rela *rela = (const Elf_Rela *) rel;
430 
431 	dbg(" reloc_jmpslot: where=%p, target=%p",
432 	    (void *)wherep, (void *)target);
433 
434 	/*
435 	 * At the PLT entry pointed at by `wherep', construct
436 	 * a direct transfer to the now fully resolved function
437 	 * address.
438 	 */
439 	offset = target - (Elf_Addr)wherep;
440 
441 	if (abs(offset) < 32*1024*1024) {     /* inside 32MB? */
442 		/* b    value   # branch directly */
443 		*wherep = 0x48000000 | (offset & 0x03fffffc);
444 		__syncicache(wherep, 4);
445 	} else {
446 		Elf_Addr *pltcall, *jmptab;
447 		int distance;
448 		int N = obj->pltrelasize / sizeof(Elf_Rela);
449 		int reloff = rela - obj->pltrela;
450 
451 		if ((reloff < 0) || (reloff >= 0x8000)) {
452 			return (-1);
453 		}
454 
455 		pltcall = obj->pltgot;
456 
457 		dbg(" reloc_jmpslot: indir, reloff=%d, N=%d\n",
458 		    reloff, N);
459 
460 		jmptab = obj->pltgot + 18 + N * 2;
461 		jmptab[reloff] = target;
462 
463 		distance = (Elf_Addr)pltcall - (Elf_Addr)(wherep + 1);
464 
465 		/* li   r11,reloff */
466 		/* b    pltcall  # use indirect pltcall routine */
467 		wherep[0] = 0x39600000 | reloff;
468 		wherep[1] = 0x48000000 | (distance & 0x03fffffc);
469 		__syncicache(wherep, 8);
470 	}
471 
472 	return (target);
473 }
474 
475 
476 /*
477  * Setup the plt glue routines.
478  */
479 #define PLTCALL_SIZE    20
480 #define PLTRESOLVE_SIZE 24
481 
482 void
483 init_pltgot(Obj_Entry *obj)
484 {
485 	Elf_Word *pltcall, *pltresolve;
486 	Elf_Word *jmptab;
487 	int N = obj->pltrelasize / sizeof(Elf_Rela);
488 
489 	pltcall = obj->pltgot;
490 
491 	if (pltcall == NULL) {
492 		return;
493 	}
494 
495 	/*
496 	 * From the SVR4 PPC ABI:
497 	 *
498 	 * 'The first 18 words (72 bytes) of the PLT are reserved for
499 	 * use by the dynamic linker.
500 	 *   ...
501 	 * 'If the executable or shared object requires N procedure
502 	 *  linkage table entries, the link editor shall reserve 3*N
503 	 *  words (12*N bytes) following the 18 reserved words. The
504 	 *  first 2*N of these words are the procedure linkage table
505 	 *  entries themselves. The static linker directs calls to bytes
506 	 *  (72 + (i-1)*8), for i between 1 and N inclusive. The remaining
507 	 *  N words (4*N bytes) are reserved for use by the dynamic linker.'
508 	 */
509 
510 	/*
511 	 * Copy the absolute-call assembler stub into the first part of
512 	 * the reserved PLT area.
513 	 */
514 	memcpy(pltcall, _rtld_powerpc_pltcall, PLTCALL_SIZE);
515 
516 	/*
517 	 * Determine the address of the jumptable, which is the dyn-linker
518 	 * reserved area after the call cells. Write the absolute address
519 	 * of the jumptable into the absolute-call assembler code so it
520 	 * can determine this address.
521 	 */
522 	jmptab = pltcall + 18 + N * 2;
523 	pltcall[1] |= _ppc_ha(jmptab);	   /* addis 11,11,jmptab@ha */
524 	pltcall[2] |= _ppc_la(jmptab);     /* lwz   11,jmptab@l(11) */
525 
526 	/*
527 	 * Skip down 32 bytes into the initial reserved area and copy
528 	 * in the standard resolving assembler call. Into this assembler,
529 	 * insert the absolute address of the _rtld_bind_start routine
530 	 * and the address of the relocation object.
531 	 */
532 	pltresolve = obj->pltgot + 8;
533 
534 	memcpy(pltresolve, _rtld_powerpc_pltresolve, PLTRESOLVE_SIZE);
535 	pltresolve[0] |= _ppc_ha(_rtld_bind_start);
536 	pltresolve[1] |= _ppc_la(_rtld_bind_start);
537 	pltresolve[3] |= _ppc_ha(obj);
538 	pltresolve[4] |= _ppc_la(obj);
539 
540 	/*
541 	 * Sync the icache for the byte range represented by the
542 	 * trampoline routines and call slots.
543 	 */
544 	__syncicache(pltcall, 72 + N * 8);
545 }
546 
547 void
548 allocate_initial_tls(Obj_Entry *list)
549 {
550 	register Elf_Addr **tp __asm__("r2");
551 	Elf_Addr **_tp;
552 
553 	/*
554 	* Fix the size of the static TLS block by using the maximum
555 	* offset allocated so far and adding a bit for dynamic modules to
556 	* use.
557 	*/
558 
559 	tls_static_space = tls_last_offset + tls_last_size + RTLD_STATIC_TLS_EXTRA;
560 
561 	_tp = (Elf_Addr **) ((char *) allocate_tls(list, NULL, TLS_TCB_SIZE, 8)
562 	    + TLS_TP_OFFSET + TLS_TCB_SIZE);
563 
564 	/*
565 	 * XXX gcc seems to ignore 'tp = _tp;'
566 	 */
567 
568 	__asm __volatile("mr %0,%1" : "=r"(tp) : "r"(_tp));
569 }
570 
571 void*
572 __tls_get_addr(tls_index* ti)
573 {
574 	register Elf_Addr **tp __asm__("r2");
575 	char *p;
576 
577 	p = tls_get_addr_common((Elf_Addr**)((Elf_Addr)tp - TLS_TP_OFFSET
578 	    - TLS_TCB_SIZE), ti->ti_module, ti->ti_offset);
579 
580 	return (p + TLS_DTV_OFFSET);
581 }
582