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