xref: /freebsd/usr.sbin/kldxref/ef_riscv.c (revision 1d386b48)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2018 John Baldwin <jhb@FreeBSD.org>
5  *
6  * This software was developed by SRI International and the University of
7  * Cambridge Computer Laboratory (Department of Computer Science and
8  * Technology) under DARPA contract HR0011-18-C-0016 ("ECATS"), as part of the
9  * DARPA SSITH research programme.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/cdefs.h>
34 #include <sys/types.h>
35 #include <machine/elf.h>
36 
37 #include <err.h>
38 #include <errno.h>
39 
40 #include "ef.h"
41 
42 int
43 ef_reloc(struct elf_file *ef, const void *reldata, int reltype, Elf_Off relbase,
44     Elf_Off dataoff, size_t len, void *dest)
45 {
46 	Elf_Addr *where;
47 	const Elf_Rela *rela;
48 	Elf_Addr addend, addr;
49 	Elf_Size rtype, symidx;
50 
51 	switch (reltype) {
52 	case EF_RELOC_RELA:
53 		rela = (const Elf_Rela *)reldata;
54 		where = (Elf_Addr *)((char *)dest + relbase + rela->r_offset -
55 		    dataoff);
56 		addend = rela->r_addend;
57 		rtype = ELF_R_TYPE(rela->r_info);
58 		symidx = ELF_R_SYM(rela->r_info);
59 		break;
60 	default:
61 		return (EINVAL);
62 	}
63 
64 	if ((char *)where < (char *)dest || (char *)where >= (char *)dest + len)
65 		return (0);
66 
67 	switch (rtype) {
68 	case R_RISCV_64:	/* S + A */
69 		addr = EF_SYMADDR(ef, symidx) + addend;
70 		*where = addr;
71 		break;
72 	case R_RISCV_RELATIVE:	/* B + A */
73 		addr = addend + relbase;
74 		*where = addr;
75 		break;
76 	default:
77 		warnx("unhandled relocation type %d", (int)rtype);
78 	}
79 	return (0);
80 }
81