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