reloc.c revision 112242
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: head/libexec/rtld-elf/powerpc/reloc.c 112242 2003-03-14 21:10:13Z kan $
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 */
52int
53do_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
75		if (ELF_R_TYPE(rela->r_info) != R_PPC_COPY) {
76			continue;
77		}
78
79		dstaddr = (void *) (dstobj->relocbase + rela->r_offset);
80		dstsym = dstobj->symtab + ELF_R_SYM(rela->r_info);
81		name = dstobj->strtab + dstsym->st_name;
82		hash = elf_hash(name);
83		size = dstsym->st_size;
84
85		for (srcobj = dstobj->next;  srcobj != NULL;
86		     srcobj = srcobj->next) {
87			if ((srcsym = symlook_obj(name, hash, srcobj, false))
88			    != NULL) {
89				break;
90			}
91		}
92
93		if (srcobj == NULL) {
94			_rtld_error("Undefined symbol \"%s\" "
95				    " referenced from COPY"
96				    " relocation in %s", name, dstobj->path);
97			return (-1);
98		}
99
100		srcaddr = (const void *) (srcobj->relocbase+srcsym->st_value);
101		memcpy(dstaddr, srcaddr, size);
102		dbg("copy_reloc: src=%p,dst=%p,size=%d\n",srcaddr,dstaddr,size);
103	}
104
105	return (0);
106}
107
108
109/*
110 * Perform early relocation of the run-time linker image
111 */
112void
113reloc_non_plt_self(Elf_Dyn *dynp, Elf_Addr relocbase)
114{
115	const Elf_Rela *rela = 0, *relalim;
116	Elf_Addr relasz = 0;
117	Elf_Addr *where;
118
119	/*
120	 * Extract the rela/relasz values from the dynamic section
121	 */
122	for (; dynp->d_tag != DT_NULL; dynp++) {
123		switch (dynp->d_tag) {
124		case DT_RELA:
125			rela = (const Elf_Rela *)(relocbase+dynp->d_un.d_ptr);
126			break;
127		case DT_RELASZ:
128			relasz = dynp->d_un.d_val;
129			break;
130		}
131	}
132
133	/*
134	 * Relocate these values
135	 */
136	relalim = (const Elf_Rela *)((caddr_t)rela + relasz);
137	for (; rela < relalim; rela++) {
138		where = (Elf_Addr *)(relocbase + rela->r_offset);
139		*where = (Elf_Addr)(relocbase + rela->r_addend);
140	}
141}
142
143
144/*
145 * Relocate a non-PLT object with addend.
146 */
147static int
148reloc_nonplt_object(Obj_Entry *obj_rtld, Obj_Entry *obj, const Elf_Rela *rela,
149		    SymCache *cache)
150{
151	Elf_Addr        *where = (Elf_Addr *)(obj->relocbase + rela->r_offset);
152	const Elf_Sym   *def;
153	const Obj_Entry *defobj;
154	Elf_Addr         tmp;
155
156	switch (ELF_R_TYPE(rela->r_info)) {
157
158	case R_PPC_NONE:
159		break;
160
161        case R_PPC_ADDR32:    /* word32 S + A */
162        case R_PPC_GLOB_DAT:  /* word32 S + A */
163		def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
164				  false, cache);
165		if (def == NULL) {
166			return (-1);
167		}
168
169                tmp = (Elf_Addr)(defobj->relocbase + def->st_value +
170                    rela->r_addend);
171
172		/* Don't issue write if unnecessary; avoid COW page fault */
173                if (*where != tmp) {
174                        *where = tmp;
175		}
176                break;
177
178        case R_PPC_RELATIVE:  /* word32 B + A */
179		tmp = (Elf_Addr)(obj->relocbase + rela->r_addend);
180
181		/* As above, don't issue write unnecessarily */
182		if (*where != tmp) {
183			*where = tmp;
184		}
185		break;
186
187	case R_PPC_COPY:
188		/*
189		 * These are deferred until all other relocations
190		 * have been done.  All we do here is make sure
191		 * that the COPY relocation is not in a shared
192		 * library.  They are allowed only in executable
193		 * files.
194		 */
195		if (!obj->mainprog) {
196			_rtld_error("%s: Unexpected R_COPY "
197				    " relocation in shared library",
198				    obj->path);
199			return (-1);
200		}
201		break;
202
203	case R_PPC_JMP_SLOT:
204		/*
205		 * These will be handled by the plt/jmpslot routines
206		 */
207		break;
208
209	default:
210		_rtld_error("%s: Unsupported relocation type %d"
211			    " in non-PLT relocations\n", obj->path,
212			    ELF_R_TYPE(rela->r_info));
213		return (-1);
214        }
215	return (0);
216}
217
218
219/*
220 * Process non-PLT relocations
221 */
222int
223reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld)
224{
225	const Elf_Rela *relalim;
226	const Elf_Rela *rela;
227	SymCache *cache;
228	int bytes = obj->nchains * sizeof(SymCache);
229	int r = -1;
230
231	/*
232	 * The dynamic loader may be called from a thread, we have
233	 * limited amounts of stack available so we cannot use alloca().
234	 */
235	cache = mmap(NULL, bytes, PROT_READ|PROT_WRITE, MAP_ANON, -1, 0);
236	if (cache == MAP_FAILED)
237		cache = NULL;
238
239	/*
240	 * From the SVR4 PPC ABI:
241	 * "The PowerPC family uses only the Elf32_Rela relocation
242	 *  entries with explicit addends."
243	 */
244	relalim = (const Elf_Rela *)((caddr_t)obj->rela + obj->relasize);
245	for (rela = obj->rela; rela < relalim; rela++) {
246		if (reloc_nonplt_object(obj_rtld, obj, rela, cache) < 0)
247			goto done;
248	}
249	r = 0;
250done:
251	if (cache) {
252		munmap(cache, bytes);
253	}
254	return (r);
255}
256
257
258/*
259 * Initialise a PLT slot to the resolving trampoline
260 */
261static int
262reloc_plt_object(Obj_Entry *obj, const Elf_Rela *rela)
263{
264	Elf_Word *where = (Elf_Word *)(obj->relocbase + rela->r_offset);
265	Elf_Addr *pltresolve;
266	Elf_Addr distance;
267	int reloff;
268
269	reloff = rela - obj->pltrela;
270
271	if ((reloff < 0) || (reloff >= 0x8000)) {
272		return (-1);
273	}
274
275	pltresolve = obj->pltgot + 8;
276
277	distance = (Elf_Addr)pltresolve - (Elf_Addr)(where + 1);
278
279	dbg(" reloc_plt_object: where=%p,pltres=%p,reloff=%x,distance=%x",
280	    (void *)where, (void *)pltresolve, reloff, distance);
281
282	/* li   r11,reloff  */
283	/* b    pltresolve  */
284	where[0] = 0x39600000 | reloff;
285	where[1] = 0x48000000 | (distance & 0x03fffffc);
286
287	/*
288	 * The icache will be sync'd in init_pltgot, which is called
289	 * after all the slots have been updated
290	 */
291
292	return (0);
293}
294
295
296/*
297 * Process the PLT relocations.
298 */
299int
300reloc_plt(Obj_Entry *obj)
301{
302	const Elf_Rela *relalim;
303	const Elf_Rela *rela;
304
305	if (obj->pltrelasize != 0) {
306
307		relalim = (const Elf_Rela *)((char *)obj->pltrela +
308		    obj->pltrelasize);
309		for (rela = obj->pltrela;  rela < relalim;  rela++) {
310			assert(ELF_R_TYPE(rela->r_info) == R_PPC_JMP_SLOT);
311
312			if (reloc_plt_object(obj, rela) < 0) {
313				return (-1);
314			}
315		}
316	}
317
318	return (0);
319}
320
321
322/*
323 * LD_BIND_NOW was set - force relocation for all jump slots
324 */
325int
326reloc_jmpslots(Obj_Entry *obj)
327{
328	const Obj_Entry *defobj;
329	const Elf_Rela *relalim;
330	const Elf_Rela *rela;
331	const Elf_Sym *def;
332	Elf_Addr *where;
333	Elf_Addr target;
334
335	relalim = (const Elf_Rela *)((char *)obj->pltrela + obj->pltrelasize);
336	for (rela = obj->pltrela; rela < relalim; rela++) {
337		assert(ELF_R_TYPE(rela->r_info) == R_PPC_JMP_SLOT);
338		where = (Elf_Addr *)(obj->relocbase + rela->r_offset);
339		def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
340		   true, NULL);
341		if (def == NULL) {
342			dbg("reloc_jmpslots: sym not found");
343			return (-1);
344		}
345
346		target = (Elf_Addr)(defobj->relocbase + def->st_value);
347
348#if 0
349		/* PG XXX */
350		dbg("\"%s\" in \"%s\" --> %p in \"%s\"",
351		    defobj->strtab + def->st_name, basename(obj->path),
352		    (void *)target, basename(defobj->path));
353#endif
354
355		reloc_jmpslot(where, target, defobj, obj,
356		    (const Elf_Rel *) rela);
357	}
358
359	obj->jmpslots_done = true;
360
361	return (0);
362}
363
364
365/*
366 * Update the value of a PLT jump slot. Branch directly to the target if
367 * it is within +/- 32Mb, otherwise go indirectly via the pltcall
368 * trampoline call and jump table.
369 */
370Elf_Addr
371reloc_jmpslot(Elf_Addr *wherep, Elf_Addr target, const Obj_Entry *defobj,
372	      const Obj_Entry *obj, const Elf_Rel *rel)
373{
374	Elf_Addr offset;
375	const Elf_Rela *rela = (const Elf_Rela *) rel;
376
377	dbg(" reloc_jmpslot: where=%p, target=%p",
378	    (void *)wherep, (void *)target);
379
380	/*
381	 * At the PLT entry pointed at by `wherep', construct
382	 * a direct transfer to the now fully resolved function
383	 * address.
384	 */
385	offset = target - (Elf_Addr)wherep;
386
387	if (abs(offset) < 32*1024*1024) {     /* inside 32MB? */
388		/* b    value   # branch directly */
389		*wherep = 0x48000000 | (offset & 0x03fffffc);
390		__syncicache(wherep, 4);
391	} else {
392		Elf_Addr *pltcall, *jmptab;
393		int distance;
394		int N = obj->pltrelasize / sizeof(Elf_Rela);
395		int reloff = rela - obj->pltrela;
396
397		if ((reloff < 0) || (reloff >= 0x8000)) {
398			return (-1);
399		}
400
401		pltcall = obj->pltgot;
402
403		dbg(" reloc_jmpslot: indir, reloff=%d, N=%d\n",
404		    reloff, N);
405
406		jmptab = obj->pltgot + 18 + N * 2;
407		jmptab[reloff] = target;
408
409		distance = (Elf_Addr)pltcall - (Elf_Addr)(wherep + 1);
410
411		/* li   r11,reloff */
412		/* b    pltcall  # use indirect pltcall routine */
413		wherep[0] = 0x39600000 | reloff;
414		wherep[1] = 0x48000000 | (distance & 0x03fffffc);
415		__syncicache(wherep, 8);
416	}
417
418	return (target);
419}
420
421
422/*
423 * Setup the plt glue routines.
424 */
425#define PLTCALL_SIZE    20
426#define PLTRESOLVE_SIZE 24
427
428void
429init_pltgot(Obj_Entry *obj)
430{
431	Elf_Word *pltcall, *pltresolve;
432	Elf_Word *jmptab;
433	int N = obj->pltrelasize / sizeof(Elf_Rela);
434
435	pltcall = obj->pltgot;
436
437	if (pltcall == NULL) {
438		return;
439	}
440
441	/*
442	 * From the SVR4 PPC ABI:
443	 *
444	 * 'The first 18 words (72 bytes) of the PLT are reserved for
445	 * use by the dynamic linker.
446	 *   ...
447	 * 'If the executable or shared object requires N procedure
448	 *  linkage table entries, the link editor shall reserve 3*N
449	 *  words (12*N bytes) following the 18 reserved words. The
450	 *  first 2*N of these words are the procedure linkage table
451	 *  entries themselves. The static linker directs calls to bytes
452	 *  (72 + (i-1)*8), for i between 1 and N inclusive. The remaining
453	 *  N words (4*N bytes) are reserved for use by the dynamic linker.'
454	 */
455
456	/*
457	 * Copy the absolute-call assembler stub into the first part of
458	 * the reserved PLT area.
459	 */
460	memcpy(pltcall, _rtld_powerpc_pltcall, PLTCALL_SIZE);
461
462	/*
463	 * Determine the address of the jumptable, which is the dyn-linker
464	 * reserved area after the call cells. Write the absolute address
465	 * of the jumptable into the absolute-call assembler code so it
466	 * can determine this address.
467	 */
468	jmptab = pltcall + 18 + N * 2;
469	pltcall[1] |= _ppc_ha(jmptab);	   /* addis 11,11,jmptab@ha */
470	pltcall[2] |= _ppc_la(jmptab);     /* lwz   11,jmptab@l(11) */
471
472	/*
473	 * Skip down 32 bytes into the initial reserved area and copy
474	 * in the standard resolving assembler call. Into this assembler,
475	 * insert the absolute address of the _rtld_bind_start routine
476	 * and the address of the relocation object.
477	 */
478	pltresolve = obj->pltgot + 8;
479
480	memcpy(pltresolve, _rtld_powerpc_pltresolve, PLTRESOLVE_SIZE);
481	pltresolve[0] |= _ppc_ha(_rtld_bind_start);
482	pltresolve[1] |= _ppc_la(_rtld_bind_start);
483	pltresolve[3] |= _ppc_ha(obj);
484	pltresolve[4] |= _ppc_la(obj);
485
486	/*
487	 * Sync the icache for the byte range represented by the
488	 * trampoline routines and call slots.
489	 */
490	__syncicache(pltcall, 72 + N * 8);
491}
492