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