xref: /freebsd/sys/riscv/riscv/elf_machdep.c (revision 716fd348)
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$");
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/reg.h>
48 #include <sys/sysctl.h>
49 #include <sys/sysent.h>
50 #include <sys/imgact_elf.h>
51 #include <sys/syscall.h>
52 #include <sys/signalvar.h>
53 #include <sys/vnode.h>
54 
55 #include <vm/vm.h>
56 #include <vm/pmap.h>
57 #include <vm/vm_param.h>
58 
59 #include <machine/elf.h>
60 #include <machine/md_var.h>
61 
62 static const char *riscv_machine_arch(struct proc *p);
63 
64 u_long elf_hwcap;
65 
66 static struct sysentvec elf64_freebsd_sysvec = {
67 	.sv_size	= SYS_MAXSYSCALL,
68 	.sv_table	= sysent,
69 	.sv_transtrap	= NULL,
70 	.sv_fixup	= __elfN(freebsd_fixup),
71 	.sv_sendsig	= sendsig,
72 	.sv_sigcode	= sigcode,
73 	.sv_szsigcode	= &szsigcode,
74 	.sv_name	= "FreeBSD ELF64",
75 	.sv_coredump	= __elfN(coredump),
76 	.sv_elf_core_osabi = ELFOSABI_FREEBSD,
77 	.sv_elf_core_abi_vendor = FREEBSD_ABI_VENDOR,
78 	.sv_elf_core_prepare_notes = __elfN(prepare_notes),
79 	.sv_imgact_try	= NULL,
80 	.sv_minsigstksz	= MINSIGSTKSZ,
81 	.sv_minuser	= VM_MIN_ADDRESS,
82 	.sv_maxuser	= 0,	/* Filled in during boot. */
83 	.sv_usrstack	= 0,	/* Filled in during boot. */
84 	.sv_psstrings	= 0,	/* Filled in during boot. */
85 	.sv_psstringssz	= sizeof(struct ps_strings),
86 	.sv_stackprot	= VM_PROT_READ | VM_PROT_WRITE,
87 	.sv_copyout_auxargs = __elfN(freebsd_copyout_auxargs),
88 	.sv_copyout_strings	= exec_copyout_strings,
89 	.sv_setregs	= exec_setregs,
90 	.sv_fixlimit	= NULL,
91 	.sv_maxssiz	= NULL,
92 	.sv_flags	= SV_ABI_FREEBSD | SV_LP64 | SV_SHP | SV_TIMEKEEP |
93 	    SV_ASLR | SV_RNG_SEED_VER,
94 	.sv_set_syscall_retval = cpu_set_syscall_retval,
95 	.sv_fetch_syscall_args = cpu_fetch_syscall_args,
96 	.sv_syscallnames = syscallnames,
97 	.sv_shared_page_base = 0,	/* Filled in during boot. */
98 	.sv_shared_page_len = PAGE_SIZE,
99 	.sv_schedtail	= NULL,
100 	.sv_thread_detach = NULL,
101 	.sv_trap	= NULL,
102 	.sv_hwcap	= &elf_hwcap,
103 	.sv_machine_arch = riscv_machine_arch,
104 	.sv_onexec_old	= exec_onexec_old,
105 	.sv_onexit	= exit_onexit,
106 	.sv_regset_begin = SET_BEGIN(__elfN(regset)),
107 	.sv_regset_end  = SET_LIMIT(__elfN(regset)),
108 };
109 INIT_SYSENTVEC(elf64_sysvec, &elf64_freebsd_sysvec);
110 
111 static const char *
112 riscv_machine_arch(struct proc *p)
113 {
114 
115 	if ((p->p_elf_flags & EF_RISCV_FLOAT_ABI_MASK) ==
116 	    EF_RISCV_FLOAT_ABI_SOFT)
117 		return (MACHINE_ARCH "sf");
118 	return (MACHINE_ARCH);
119 }
120 
121 static Elf64_Brandinfo freebsd_brand_info = {
122 	.brand		= ELFOSABI_FREEBSD,
123 	.machine	= EM_RISCV,
124 	.compat_3_brand	= "FreeBSD",
125 	.emul_path	= NULL,
126 	.interp_path	= "/libexec/ld-elf.so.1",
127 	.sysvec		= &elf64_freebsd_sysvec,
128 	.interp_newpath	= NULL,
129 	.brand_note	= &elf64_freebsd_brandnote,
130 	.flags		= BI_CAN_EXEC_DYN | BI_BRAND_NOTE
131 };
132 SYSINIT(elf64, SI_SUB_EXEC, SI_ORDER_FIRST,
133     (sysinit_cfunc_t)elf64_insert_brand_entry, &freebsd_brand_info);
134 
135 static void
136 elf64_register_sysvec(void *arg)
137 {
138 	struct sysentvec *sv;
139 
140 	sv = arg;
141 	switch (pmap_mode) {
142 	case PMAP_MODE_SV48:
143 		sv->sv_maxuser = VM_MAX_USER_ADDRESS_SV48;
144 		sv->sv_usrstack = USRSTACK_SV48;
145 		sv->sv_psstrings = PS_STRINGS_SV48;
146 		sv->sv_shared_page_base = SHAREDPAGE_SV48;
147 		break;
148 	case PMAP_MODE_SV39:
149 		sv->sv_maxuser = VM_MAX_USER_ADDRESS_SV39;
150 		sv->sv_usrstack = USRSTACK_SV39;
151 		sv->sv_psstrings = PS_STRINGS_SV39;
152 		sv->sv_shared_page_base = SHAREDPAGE_SV39;
153 		break;
154 	}
155 }
156 SYSINIT(elf64_register_sysvec, SI_SUB_VM, SI_ORDER_ANY, elf64_register_sysvec,
157     &elf64_freebsd_sysvec);
158 
159 static bool debug_kld;
160 SYSCTL_BOOL(_debug, OID_AUTO, kld_reloc, CTLFLAG_RW, &debug_kld, 0,
161     "Activate debug prints in elf_reloc_internal()");
162 
163 struct type2str_ent {
164 	int type;
165 	const char *str;
166 };
167 
168 void
169 elf64_dump_thread(struct thread *td, void *dst, size_t *off)
170 {
171 
172 }
173 
174 /*
175  * Following 4 functions are used to manipulate bits on 32bit integer value.
176  * FIXME: I implemetend for ease-to-understand rather than for well-optimized.
177  */
178 static uint32_t
179 gen_bitmask(int msb, int lsb)
180 {
181 	uint32_t mask;
182 
183 	if (msb == sizeof(mask) * 8 - 1)
184 		mask = ~0;
185 	else
186 		mask = (1U << (msb + 1)) - 1;
187 
188 	if (lsb > 0)
189 		mask &= ~((1U << lsb) - 1);
190 
191 	return (mask);
192 }
193 
194 static uint32_t
195 extract_bits(uint32_t x, int msb, int lsb)
196 {
197 	uint32_t mask;
198 
199 	mask = gen_bitmask(msb, lsb);
200 
201 	x &= mask;
202 	x >>= lsb;
203 
204 	return (x);
205 }
206 
207 static uint32_t
208 insert_bits(uint32_t d, uint32_t s, int msb, int lsb)
209 {
210 	uint32_t mask;
211 
212 	mask = gen_bitmask(msb, lsb);
213 
214 	d &= ~mask;
215 
216 	s <<= lsb;
217 	s &= mask;
218 
219 	return (d | s);
220 }
221 
222 static uint32_t
223 insert_imm(uint32_t insn, uint32_t imm, int imm_msb, int imm_lsb,
224     int insn_lsb)
225 {
226 	int insn_msb;
227 	uint32_t v;
228 
229 	v = extract_bits(imm, imm_msb, imm_lsb);
230 	insn_msb = (imm_msb - imm_lsb) + insn_lsb;
231 
232 	return (insert_bits(insn, v, insn_msb, insn_lsb));
233 }
234 
235 /*
236  * The RISC-V ISA is designed so that all of immediate values are
237  * sign-extended.
238  * An immediate value is sometimes generated at runtime by adding
239  * 12bit sign integer and 20bit signed integer. This requests 20bit
240  * immediate value to be ajusted if the MSB of the 12bit immediate
241  * value is asserted (sign-extended value is treated as negative value).
242  *
243  * For example, 0x123800 can be calculated by adding upper 20 bit of
244  * 0x124000 and sign-extended 12bit immediate whose bit pattern is
245  * 0x800 as follows:
246  *   0x123800
247  *     = 0x123000 + 0x800
248  *     = (0x123000 + 0x1000) + (-0x1000 + 0x800)
249  *     = (0x123000 + 0x1000) + (0xff...ff800)
250  *     = 0x124000            + sign-extention(0x800)
251  */
252 static uint32_t
253 calc_hi20_imm(uint32_t value)
254 {
255 	/*
256 	 * There is the arithmetical hack that can remove conditional
257 	 * statement. But I implement it in straightforward way.
258 	 */
259 	if ((value & 0x800) != 0)
260 		value += 0x1000;
261 	return (value & ~0xfff);
262 }
263 
264 static const struct type2str_ent t2s[] = {
265 	{ R_RISCV_NONE,		"R_RISCV_NONE"		},
266 	{ R_RISCV_64,		"R_RISCV_64"		},
267 	{ R_RISCV_JUMP_SLOT,	"R_RISCV_JUMP_SLOT"	},
268 	{ R_RISCV_RELATIVE,	"R_RISCV_RELATIVE"	},
269 	{ R_RISCV_JAL,		"R_RISCV_JAL"		},
270 	{ R_RISCV_CALL,		"R_RISCV_CALL"		},
271 	{ R_RISCV_PCREL_HI20,	"R_RISCV_PCREL_HI20"	},
272 	{ R_RISCV_PCREL_LO12_I,	"R_RISCV_PCREL_LO12_I"	},
273 	{ R_RISCV_PCREL_LO12_S,	"R_RISCV_PCREL_LO12_S"	},
274 	{ R_RISCV_HI20,		"R_RISCV_HI20"		},
275 	{ R_RISCV_LO12_I,	"R_RISCV_LO12_I"	},
276 	{ R_RISCV_LO12_S,	"R_RISCV_LO12_S"	},
277 };
278 
279 static const char *
280 reloctype_to_str(int type)
281 {
282 	int i;
283 
284 	for (i = 0; i < sizeof(t2s) / sizeof(t2s[0]); ++i) {
285 		if (type == t2s[i].type)
286 			return t2s[i].str;
287 	}
288 
289 	return "*unknown*";
290 }
291 
292 bool
293 elf_is_ifunc_reloc(Elf_Size r_info __unused)
294 {
295 
296 	return (false);
297 }
298 
299 /*
300  * Currently kernel loadable module for RISCV is compiled with -fPIC option.
301  * (see also additional CFLAGS definition for RISCV in sys/conf/kmod.mk)
302  * Only R_RISCV_64, R_RISCV_JUMP_SLOT and RISCV_RELATIVE are emitted in
303  * the module. Other relocations will be processed when kernel loadable
304  * modules are built in non-PIC.
305  *
306  * FIXME: only RISCV64 is supported.
307  */
308 static int
309 elf_reloc_internal(linker_file_t lf, Elf_Addr relocbase, const void *data,
310     int type, int local, elf_lookup_fn lookup)
311 {
312 	Elf_Size rtype, symidx;
313 	const Elf_Rela *rela;
314 	Elf_Addr val, addr;
315 	Elf64_Addr *where;
316 	Elf_Addr addend;
317 	uint32_t before32_1;
318 	uint32_t before32;
319 	uint64_t before64;
320 	uint32_t *insn32p;
321 	uint32_t imm20;
322 	int error;
323 
324 	switch (type) {
325 	case ELF_RELOC_RELA:
326 		rela = (const Elf_Rela *)data;
327 		where = (Elf_Addr *)(relocbase + rela->r_offset);
328 		insn32p = (uint32_t *)where;
329 		addend = rela->r_addend;
330 		rtype = ELF_R_TYPE(rela->r_info);
331 		symidx = ELF_R_SYM(rela->r_info);
332 		break;
333 	default:
334 		printf("%s:%d unknown reloc type %d\n",
335 		    __FUNCTION__, __LINE__, type);
336 		return (-1);
337 	}
338 
339 	switch (rtype) {
340 	case R_RISCV_NONE:
341 		break;
342 
343 	case R_RISCV_64:
344 	case R_RISCV_JUMP_SLOT:
345 		error = lookup(lf, symidx, 1, &addr);
346 		if (error != 0)
347 			return (-1);
348 
349 		val = addr;
350 		before64 = *where;
351 		if (*where != val)
352 			*where = val;
353 		if (debug_kld)
354 			printf("%p %c %-24s %016lx -> %016lx\n", where,
355 			    (local ? 'l' : 'g'), reloctype_to_str(rtype),
356 			    before64, *where);
357 		break;
358 
359 	case R_RISCV_RELATIVE:
360 		before64 = *where;
361 		*where = elf_relocaddr(lf, relocbase + addend);
362 		if (debug_kld)
363 			printf("%p %c %-24s %016lx -> %016lx\n", where,
364 			    (local ? 'l' : 'g'), reloctype_to_str(rtype),
365 			    before64, *where);
366 		break;
367 
368 	case R_RISCV_JAL:
369 		error = lookup(lf, symidx, 1, &addr);
370 		if (error != 0)
371 			return (-1);
372 
373 		val = addr - (Elf_Addr)where;
374 		if (val <= -(1UL << 20) || (1UL << 20) <= val) {
375 			printf("kldload: huge offset against R_RISCV_JAL\n");
376 			return (-1);
377 		}
378 
379 		before32 = *insn32p;
380 		*insn32p = insert_imm(*insn32p, val, 20, 20, 31);
381 		*insn32p = insert_imm(*insn32p, val, 10,  1, 21);
382 		*insn32p = insert_imm(*insn32p, val, 11, 11, 20);
383 		*insn32p = insert_imm(*insn32p, val, 19, 12, 12);
384 		if (debug_kld)
385 			printf("%p %c %-24s %08x -> %08x\n", where,
386 			    (local ? 'l' : 'g'), reloctype_to_str(rtype),
387 			    before32, *insn32p);
388 		break;
389 
390 	case R_RISCV_CALL:
391 		/*
392 		 * R_RISCV_CALL relocates 8-byte region that consists
393 		 * of the sequence of AUIPC and JALR.
394 		 */
395 		/* Calculate and check the pc relative offset. */
396 		error = lookup(lf, symidx, 1, &addr);
397 		if (error != 0)
398 			return (-1);
399 
400 		val = addr - (Elf_Addr)where;
401 		if (val <= -(1UL << 32) || (1UL << 32) <= val) {
402 			printf("kldload: huge offset against R_RISCV_CALL\n");
403 			return (-1);
404 		}
405 
406 		/* Relocate AUIPC. */
407 		before32 = insn32p[0];
408 		imm20 = calc_hi20_imm(val);
409 		insn32p[0] = insert_imm(insn32p[0], imm20, 31, 12, 12);
410 
411 		/* Relocate JALR. */
412 		before32_1 = insn32p[1];
413 		insn32p[1] = insert_imm(insn32p[1], val, 11,  0, 20);
414 		if (debug_kld)
415 			printf("%p %c %-24s %08x %08x -> %08x %08x\n", where,
416 			    (local ? 'l' : 'g'), reloctype_to_str(rtype),
417 			    before32, insn32p[0], before32_1, insn32p[1]);
418 		break;
419 
420 	case R_RISCV_PCREL_HI20:
421 		error = lookup(lf, symidx, 1, &addr);
422 		if (error != 0)
423 			return (-1);
424 
425 		val = addr - (Elf_Addr)where;
426 		insn32p = (uint32_t *)where;
427 		before32 = *insn32p;
428 		imm20 = calc_hi20_imm(val);
429 		*insn32p = insert_imm(*insn32p, imm20, 31, 12, 12);
430 		if (debug_kld)
431 			printf("%p %c %-24s %08x -> %08x\n", where,
432 			    (local ? 'l' : 'g'), reloctype_to_str(rtype),
433 			    before32, *insn32p);
434 		break;
435 
436 	case R_RISCV_PCREL_LO12_I:
437 		error = lookup(lf, symidx, 1, &addr);
438 		if (error != 0)
439 			return (-1);
440 
441 		val = addr - (Elf_Addr)where;
442 		insn32p = (uint32_t *)where;
443 		before32 = *insn32p;
444 		*insn32p = insert_imm(*insn32p, addr, 11,  0, 20);
445 		if (debug_kld)
446 			printf("%p %c %-24s %08x -> %08x\n", where,
447 			    (local ? 'l' : 'g'), reloctype_to_str(rtype),
448 			    before32, *insn32p);
449 		break;
450 
451 	case R_RISCV_PCREL_LO12_S:
452 		error = lookup(lf, symidx, 1, &addr);
453 		if (error != 0)
454 			return (-1);
455 
456 		val = addr - (Elf_Addr)where;
457 		insn32p = (uint32_t *)where;
458 		before32 = *insn32p;
459 		*insn32p = insert_imm(*insn32p, addr, 11,  5, 25);
460 		*insn32p = insert_imm(*insn32p, addr,  4,  0,  7);
461 		if (debug_kld)
462 			printf("%p %c %-24s %08x -> %08x\n", where,
463 			    (local ? 'l' : 'g'), reloctype_to_str(rtype),
464 			    before32, *insn32p);
465 		break;
466 
467 	case R_RISCV_HI20:
468 		error = lookup(lf, symidx, 1, &addr);
469 		if (error != 0)
470 			return (-1);
471 
472 		val = addr;
473 		insn32p = (uint32_t *)where;
474 		before32 = *insn32p;
475 		imm20 = calc_hi20_imm(val);
476 		*insn32p = insert_imm(*insn32p, imm20, 31, 12, 12);
477 		if (debug_kld)
478 			printf("%p %c %-24s %08x -> %08x\n", where,
479 			    (local ? 'l' : 'g'), reloctype_to_str(rtype),
480 			    before32, *insn32p);
481 		break;
482 
483 	case R_RISCV_LO12_I:
484 		error = lookup(lf, symidx, 1, &addr);
485 		if (error != 0)
486 			return (-1);
487 
488 		val = addr;
489 		insn32p = (uint32_t *)where;
490 		before32 = *insn32p;
491 		*insn32p = insert_imm(*insn32p, addr, 11,  0, 20);
492 		if (debug_kld)
493 			printf("%p %c %-24s %08x -> %08x\n", where,
494 			    (local ? 'l' : 'g'), reloctype_to_str(rtype),
495 			    before32, *insn32p);
496 		break;
497 
498 	case R_RISCV_LO12_S:
499 		error = lookup(lf, symidx, 1, &addr);
500 		if (error != 0)
501 			return (-1);
502 
503 		val = addr;
504 		insn32p = (uint32_t *)where;
505 		before32 = *insn32p;
506 		*insn32p = insert_imm(*insn32p, addr, 11,  5, 25);
507 		*insn32p = insert_imm(*insn32p, addr,  4,  0,  7);
508 		if (debug_kld)
509 			printf("%p %c %-24s %08x -> %08x\n", where,
510 			    (local ? 'l' : 'g'), reloctype_to_str(rtype),
511 			    before32, *insn32p);
512 		break;
513 
514 	default:
515 		printf("kldload: unexpected relocation type %ld, "
516 		    "symbol index %ld\n", rtype, symidx);
517 		return (-1);
518 	}
519 
520 	return (0);
521 }
522 
523 int
524 elf_reloc(linker_file_t lf, Elf_Addr relocbase, const void *data, int type,
525     elf_lookup_fn lookup)
526 {
527 
528 	return (elf_reloc_internal(lf, relocbase, data, type, 0, lookup));
529 }
530 
531 int
532 elf_reloc_local(linker_file_t lf, Elf_Addr relocbase, const void *data,
533     int type, elf_lookup_fn lookup)
534 {
535 
536 	return (elf_reloc_internal(lf, relocbase, data, type, 1, lookup));
537 }
538 
539 int
540 elf_cpu_load_file(linker_file_t lf __unused)
541 {
542 
543 	return (0);
544 }
545 
546 int
547 elf_cpu_unload_file(linker_file_t lf __unused)
548 {
549 
550 	return (0);
551 }
552 
553 int
554 elf_cpu_parse_dynamic(caddr_t loadbase __unused, Elf_Dyn *dynamic __unused)
555 {
556 
557 	return (0);
558 }
559