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