1/*-
2 * Copyright 1996-1998 John D. Polstra.
3 * Copyright (c) 2015 Ruslan Bukin <br@bsdpad.com>
4 * Copyright (c) 2016 Yukishige Shibata <y-shibat@mtd.biglobe.ne.jp>
5 * All rights reserved.
6 *
7 * Portions of this software were developed by SRI International and the
8 * University of Cambridge Computer Laboratory under DARPA/AFRL contract
9 * FA8750-10-C-0237 ("CTSRD"), as part of the DARPA CRASH research programme.
10 *
11 * Portions of this software were developed by the University of Cambridge
12 * Computer Laboratory as part of the CTSRD Project, with support from the
13 * UK Higher Education Innovation Fund (HEIF).
14 *
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
17 * are met:
18 * 1. Redistributions of source code must retain the above copyright
19 *    notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 *    notice, this list of conditions and the following disclaimer in the
22 *    documentation and/or other materials provided with the distribution.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#include <sys/cdefs.h>
38__FBSDID("$FreeBSD: releng/11.0/sys/riscv/riscv/elf_machdep.c 301205 2016-06-02 15:14:40Z br $");
39
40#include <sys/param.h>
41#include <sys/kernel.h>
42#include <sys/systm.h>
43#include <sys/exec.h>
44#include <sys/imgact.h>
45#include <sys/linker.h>
46#include <sys/proc.h>
47#include <sys/sysctl.h>
48#include <sys/sysent.h>
49#include <sys/imgact_elf.h>
50#include <sys/syscall.h>
51#include <sys/signalvar.h>
52#include <sys/vnode.h>
53
54#include <vm/vm.h>
55#include <vm/pmap.h>
56#include <vm/vm_param.h>
57
58#include <machine/elf.h>
59#include <machine/md_var.h>
60
61struct sysentvec elf64_freebsd_sysvec = {
62	.sv_size	= SYS_MAXSYSCALL,
63	.sv_table	= sysent,
64	.sv_mask	= 0,
65	.sv_errsize	= 0,
66	.sv_errtbl	= NULL,
67	.sv_transtrap	= NULL,
68	.sv_fixup	= __elfN(freebsd_fixup),
69	.sv_sendsig	= sendsig,
70	.sv_sigcode	= sigcode,
71	.sv_szsigcode	= &szsigcode,
72	.sv_name	= "FreeBSD ELF64",
73	.sv_coredump	= __elfN(coredump),
74	.sv_imgact_try	= NULL,
75	.sv_minsigstksz	= MINSIGSTKSZ,
76	.sv_pagesize	= PAGE_SIZE,
77	.sv_minuser	= VM_MIN_ADDRESS,
78	.sv_maxuser	= VM_MAXUSER_ADDRESS,
79	.sv_usrstack	= USRSTACK,
80	.sv_psstrings	= PS_STRINGS,
81	.sv_stackprot	= VM_PROT_ALL,
82	.sv_copyout_strings	= exec_copyout_strings,
83	.sv_setregs	= exec_setregs,
84	.sv_fixlimit	= NULL,
85	.sv_maxssiz	= NULL,
86	.sv_flags	= SV_ABI_FREEBSD | SV_LP64,
87	.sv_set_syscall_retval = cpu_set_syscall_retval,
88	.sv_fetch_syscall_args = cpu_fetch_syscall_args,
89	.sv_syscallnames = syscallnames,
90	.sv_schedtail	= NULL,
91	.sv_thread_detach = NULL,
92	.sv_trap	= NULL,
93};
94INIT_SYSENTVEC(elf64_sysvec, &elf64_freebsd_sysvec);
95
96static Elf64_Brandinfo freebsd_brand_info = {
97	.brand		= ELFOSABI_FREEBSD,
98	.machine	= EM_RISCV,
99	.compat_3_brand	= "FreeBSD",
100	.emul_path	= NULL,
101	.interp_path	= "/libexec/ld-elf.so.1",
102	.sysvec		= &elf64_freebsd_sysvec,
103	.interp_newpath	= NULL,
104	.brand_note	= &elf64_freebsd_brandnote,
105	.flags		= BI_CAN_EXEC_DYN | BI_BRAND_NOTE
106};
107
108SYSINIT(elf64, SI_SUB_EXEC, SI_ORDER_FIRST,
109	(sysinit_cfunc_t) elf64_insert_brand_entry,
110	&freebsd_brand_info);
111
112static Elf64_Brandinfo freebsd_brand_oinfo = {
113	.brand		= ELFOSABI_FREEBSD,
114	.machine	= EM_RISCV,
115	.compat_3_brand	= "FreeBSD",
116	.emul_path	= NULL,
117	.interp_path	= "/usr/libexec/ld-elf.so.1",
118	.sysvec		= &elf64_freebsd_sysvec,
119	.interp_newpath	= NULL,
120	.brand_note	= &elf64_freebsd_brandnote,
121	.flags		= BI_CAN_EXEC_DYN | BI_BRAND_NOTE
122};
123
124SYSINIT(oelf64, SI_SUB_EXEC, SI_ORDER_ANY,
125	(sysinit_cfunc_t) elf64_insert_brand_entry,
126	&freebsd_brand_oinfo);
127
128static int debug_kld;
129SYSCTL_INT(_kern, OID_AUTO, debug_kld,
130	   CTLFLAG_RW, &debug_kld, 0,
131	   "Activate debug prints in elf_reloc_internal()");
132
133struct type2str_ent {
134	int type;
135	const char *str;
136};
137
138void
139elf64_dump_thread(struct thread *td, void *dst, size_t *off)
140{
141
142}
143
144/*
145 * Following 4 functions are used to manupilate bits on 32bit interger value.
146 * FIXME: I implemetend for ease-to-understand rather than for well-optimized.
147 */
148static uint32_t
149gen_bitmask(int msb, int lsb)
150{
151	uint32_t mask;
152
153	if (msb == sizeof(mask) * 8 - 1)
154		mask = ~0;
155	else
156		mask = (1U << (msb + 1)) - 1;
157
158	if (lsb > 0)
159		mask &= ~((1U << lsb) - 1);
160
161	return (mask);
162}
163
164static uint32_t
165extract_bits(uint32_t x, int msb, int lsb)
166{
167	uint32_t mask;
168
169	mask = gen_bitmask(msb, lsb);
170
171	x &= mask;
172	x >>= lsb;
173
174	return (x);
175}
176
177static uint32_t
178insert_bits(uint32_t d, uint32_t s, int msb, int lsb)
179{
180	uint32_t mask;
181
182	mask = gen_bitmask(msb, lsb);
183
184	d &= ~mask;
185
186	s <<= lsb;
187	s &= mask;
188
189	return (d | s);
190}
191
192static uint32_t
193insert_imm(uint32_t insn, uint32_t imm, int imm_msb, int imm_lsb,
194    int insn_lsb)
195{
196	int insn_msb;
197	uint32_t v;
198
199	v = extract_bits(imm, imm_msb, imm_lsb);
200	insn_msb = (imm_msb - imm_lsb) + insn_lsb;
201
202	return (insert_bits(insn, v, insn_msb, insn_lsb));
203}
204
205/*
206 * The RISC-V ISA is designed so that all of immediate values are
207 * sign-extended.
208 * An immediate value is sometimes generated at runtime by adding
209 * 12bit sign integer and 20bit signed integer. This requests 20bit
210 * immediate value to be ajusted if the MSB of the 12bit immediate
211 * value is asserted (sign-extended value is treated as negative value).
212 *
213 * For example, 0x123800 can be calculated by adding upper 20 bit of
214 * 0x124000 and sign-extended 12bit immediate whose bit pattern is
215 * 0x800 as follows:
216 *   0x123800
217 *     = 0x123000 + 0x800
218 *     = (0x123000 + 0x1000) + (-0x1000 + 0x800)
219 *     = (0x123000 + 0x1000) + (0xff...ff800)
220 *     = 0x124000            + sign-extention(0x800)
221 */
222static uint32_t
223calc_hi20_imm(uint32_t value)
224{
225	/*
226	 * There is the arithmetical hack that can remove conditional
227	 * statement. But I implement it in straightforward way.
228	 */
229	if ((value & 0x800) != 0)
230		value += 0x1000;
231	return (value & ~0xfff);
232}
233
234static const struct type2str_ent t2s[] = {
235	{ R_RISCV_NONE,		"R_RISCV_NONE"		},
236	{ R_RISCV_64,		"R_RISCV_64"		},
237	{ R_RISCV_JUMP_SLOT,	"R_RISCV_JUMP_SLOT"	},
238	{ R_RISCV_RELATIVE,	"R_RISCV_RELATIVE"	},
239	{ R_RISCV_JAL,		"R_RISCV_JAL"		},
240	{ R_RISCV_CALL,		"R_RISCV_CALL"		},
241	{ R_RISCV_PCREL_HI20,	"R_RISCV_PCREL_HI20"	},
242	{ R_RISCV_PCREL_LO12_I,	"R_RISCV_PCREL_LO12_I"	},
243	{ R_RISCV_PCREL_LO12_S,	"R_RISCV_PCREL_LO12_S"	},
244	{ R_RISCV_HI20,		"R_RISCV_HI20"		},
245	{ R_RISCV_LO12_I,	"R_RISCV_LO12_I"	},
246	{ R_RISCV_LO12_S,	"R_RISCV_LO12_S"	},
247};
248
249static const char *
250reloctype_to_str(int type)
251{
252	int i;
253
254	for (i = 0; i < sizeof(t2s) / sizeof(t2s[0]); ++i) {
255		if (type == t2s[i].type)
256			return t2s[i].str;
257	}
258
259	return "*unknown*";
260}
261
262/*
263 * Currently kernel loadable module for RISCV is compiled with -fPIC option.
264 * (see also additional CFLAGS definition for RISCV in sys/conf/kmod.mk)
265 * Only R_RISCV_64, R_RISCV_JUMP_SLOT and RISCV_RELATIVE are emitted in
266 * the module. Other relocations will be processed when kernel loadable
267 * modules are built in non-PIC.
268 *
269 * FIXME: only RISCV64 is supported.
270 */
271static int
272elf_reloc_internal(linker_file_t lf, Elf_Addr relocbase, const void *data,
273    int type, int local, elf_lookup_fn lookup)
274{
275	Elf_Size rtype, symidx;
276	const Elf_Rela *rela;
277	Elf_Addr val, addr;
278	Elf64_Addr *where;
279	Elf_Addr addend;
280	uint32_t before32_1;
281	uint32_t before32;
282	uint64_t before64;
283	uint32_t* insn32p;
284	uint32_t imm20;
285	int error;
286
287	switch (type) {
288	case ELF_RELOC_RELA:
289		rela = (const Elf_Rela *)data;
290		where = (Elf_Addr *)(relocbase + rela->r_offset);
291		insn32p = (uint32_t*)where;
292		addend = rela->r_addend;
293		rtype = ELF_R_TYPE(rela->r_info);
294		symidx = ELF_R_SYM(rela->r_info);
295		break;
296	default:
297		printf("%s:%d unknown reloc type %d\n",
298		       __FUNCTION__, __LINE__, type);
299		return -1;
300	}
301
302	switch (rtype) {
303	case R_RISCV_NONE:
304		break;
305
306	case R_RISCV_64:
307	case R_RISCV_JUMP_SLOT:
308		error = lookup(lf, symidx, 1, &addr);
309		if (error != 0)
310			return -1;
311
312		val = addr;
313		before64 = *where;
314		if (*where != val)
315			*where = val;
316
317		if (debug_kld)
318			printf("%p %c %-24s %016lx -> %016lx\n",
319			       where,
320			       (local? 'l': 'g'),
321			       reloctype_to_str(rtype),
322			       before64, *where);
323		break;
324
325	case R_RISCV_RELATIVE:
326		val = relocbase + addend;
327
328		before64 = *where;
329		if (*where != val)
330			*where = val;
331
332		if (debug_kld)
333			printf("%p %c %-24s %016lx -> %016lx\n",
334			       where,
335			       (local? 'l': 'g'),
336			       reloctype_to_str(rtype),
337			       before64, *where);
338		break;
339
340	case R_RISCV_JAL:
341		error = lookup(lf, symidx, 1, &addr);
342		if (error != 0)
343			return -1;
344
345		val = addr - (Elf_Addr)where;
346		if ((val <= -(1UL << 20) || (1UL << 20) <= val)) {
347			printf("kldload: huge offset against R_RISCV_JAL\n");
348			return -1;
349		}
350
351		before32 = *insn32p;
352		*insn32p = insert_imm(*insn32p, val, 20, 20, 31);
353		*insn32p = insert_imm(*insn32p, val, 10,  1, 21);
354		*insn32p = insert_imm(*insn32p, val, 11, 11, 20);
355		*insn32p = insert_imm(*insn32p, val, 19, 12, 12);
356
357		if (debug_kld)
358			printf("%p %c %-24s %08x -> %08x\n",
359			       where,
360			       (local? 'l': 'g'),
361			       reloctype_to_str(rtype),
362			       before32, *insn32p);
363		break;
364
365	case R_RISCV_CALL:
366		/*
367		 * R_RISCV_CALL relocates 8-byte region that consists
368		 * of the sequence of AUIPC and JALR.
369		 */
370		/* calculate and check the pc relative offset. */
371		error = lookup(lf, symidx, 1, &addr);
372		if (error != 0)
373			return -1;
374		val = addr - (Elf_Addr)where;
375		if ((val <= -(1UL << 32) || (1UL << 32) <= val)) {
376			printf("kldload: huge offset against R_RISCV_CALL\n");
377			return -1;
378		}
379
380		/* Relocate AUIPC. */
381		before32 = insn32p[0];
382		imm20 = calc_hi20_imm(val);
383		insn32p[0] = insert_imm(insn32p[0], imm20, 31, 12, 12);
384
385		/* Relocate JALR. */
386		before32_1 = insn32p[1];
387		insn32p[1] = insert_imm(insn32p[1], val, 11,  0, 20);
388
389		if (debug_kld)
390			printf("%p %c %-24s %08x %08x -> %08x %08x\n",
391			       where,
392			       (local? 'l': 'g'),
393			       reloctype_to_str(rtype),
394			       before32,   insn32p[0],
395			       before32_1, insn32p[1]);
396		break;
397
398	case R_RISCV_PCREL_HI20:
399		val = addr - (Elf_Addr)where;
400		insn32p = (uint32_t*)where;
401		before32 = *insn32p;
402		imm20 = calc_hi20_imm(val);
403		*insn32p = insert_imm(*insn32p, imm20, 31, 12, 12);
404
405		if (debug_kld)
406			printf("%p %c %-24s %08x -> %08x\n",
407			       where,
408			       (local? 'l': 'g'),
409			       reloctype_to_str(rtype),
410			       before32, *insn32p);
411		break;
412
413	case R_RISCV_PCREL_LO12_I:
414		val = addr - (Elf_Addr)where;
415		insn32p = (uint32_t*)where;
416		before32 = *insn32p;
417		*insn32p = insert_imm(*insn32p, addr, 11,  0, 20);
418
419		if (debug_kld)
420			printf("%p %c %-24s %08x -> %08x\n",
421			       where,
422			       (local? 'l': 'g'),
423			       reloctype_to_str(rtype),
424			       before32, *insn32p);
425		break;
426
427	case R_RISCV_PCREL_LO12_S:
428		val = addr - (Elf_Addr)where;
429		insn32p = (uint32_t*)where;
430		before32 = *insn32p;
431		*insn32p = insert_imm(*insn32p, addr, 11,  5, 25);
432		*insn32p = insert_imm(*insn32p, addr,  4,  0,  7);
433		if (debug_kld)
434			printf("%p %c %-24s %08x -> %08x\n",
435			       where,
436			       (local? 'l': 'g'),
437			       reloctype_to_str(rtype),
438			       before32, *insn32p);
439		break;
440
441	case R_RISCV_HI20:
442		error = lookup(lf, symidx, 1, &addr);
443		if (error != 0)
444			return -1;
445
446		insn32p = (uint32_t*)where;
447		before32 = *insn32p;
448		imm20 = calc_hi20_imm(val);
449		*insn32p = insert_imm(*insn32p, imm20, 31, 12, 12);
450
451		if (debug_kld)
452			printf("%p %c %-24s %08x -> %08x\n",
453			       where,
454			       (local? 'l': 'g'),
455			       reloctype_to_str(rtype),
456			       before32, *insn32p);
457		break;
458
459	case R_RISCV_LO12_I:
460		error = lookup(lf, symidx, 1, &addr);
461		if (error != 0)
462			return -1;
463
464		val = addr;
465		insn32p = (uint32_t*)where;
466		before32 = *insn32p;
467		*insn32p = insert_imm(*insn32p, addr, 11,  0, 20);
468
469		if (debug_kld)
470			printf("%p %c %-24s %08x -> %08x\n",
471			       where,
472			       (local? 'l': 'g'),
473			       reloctype_to_str(rtype),
474			       before32, *insn32p);
475		break;
476
477	case R_RISCV_LO12_S:
478		error = lookup(lf, symidx, 1, &addr);
479		if (error != 0)
480			return -1;
481
482		val = addr;
483		insn32p = (uint32_t*)where;
484		before32 = *insn32p;
485		*insn32p = insert_imm(*insn32p, addr, 11,  5, 25);
486		*insn32p = insert_imm(*insn32p, addr,  4,  0,  7);
487
488		if (debug_kld)
489			printf("%p %c %-24s %08x -> %08x\n",
490			       where,
491			       (local? 'l': 'g'),
492			       reloctype_to_str(rtype),
493			       before32, *insn32p);
494		break;
495
496	default:
497		printf("kldload: unexpected relocation type %ld\n", rtype);
498		return (-1);
499	}
500
501	return (0);
502}
503
504int
505elf_reloc(linker_file_t lf, Elf_Addr relocbase, const void *data, int type,
506    elf_lookup_fn lookup)
507{
508
509	return (elf_reloc_internal(lf, relocbase, data, type, 0, lookup));
510}
511
512int
513elf_reloc_local(linker_file_t lf, Elf_Addr relocbase, const void *data,
514    int type, elf_lookup_fn lookup)
515{
516
517	return (elf_reloc_internal(lf, relocbase, data, type, 1, lookup));
518}
519
520int
521elf_cpu_load_file(linker_file_t lf __unused)
522{
523
524	return (0);
525}
526
527int
528elf_cpu_unload_file(linker_file_t lf __unused)
529{
530
531	return (0);
532}
533