1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Clang Control Flow Integrity (CFI) support.
4 *
5 * Copyright (C) 2023 Google LLC
6 */
7 #include <asm/cfi.h>
8 #include <asm/insn.h>
9
10 /*
11 * Returns the target address and the expected type when regs->epc points
12 * to a compiler-generated CFI trap.
13 */
decode_cfi_insn(struct pt_regs * regs,unsigned long * target,u32 * type)14 static bool decode_cfi_insn(struct pt_regs *regs, unsigned long *target,
15 u32 *type)
16 {
17 unsigned long *regs_ptr = (unsigned long *)regs;
18 int rs1_num;
19 u32 insn;
20
21 *target = *type = 0;
22
23 /*
24 * The compiler generates the following instruction sequence
25 * for indirect call checks:
26 *
27 * lw t1, -4(<reg>)
28 * lui t2, <hi20>
29 * addiw t2, t2, <lo12>
30 * beq t1, t2, .Ltmp1
31 * ebreak ; <- regs->epc
32 * .Ltmp1:
33 * jalr <reg>
34 *
35 * We can read the expected type and the target address from the
36 * registers passed to the beq/jalr instructions.
37 */
38 if (get_kernel_nofault(insn, (void *)regs->epc - 4))
39 return false;
40 if (!riscv_insn_is_beq(insn))
41 return false;
42
43 *type = (u32)regs_ptr[RV_EXTRACT_RS1_REG(insn)];
44
45 if (get_kernel_nofault(insn, (void *)regs->epc) ||
46 get_kernel_nofault(insn, (void *)regs->epc + GET_INSN_LENGTH(insn)))
47 return false;
48
49 if (riscv_insn_is_jalr(insn))
50 rs1_num = RV_EXTRACT_RS1_REG(insn);
51 else if (riscv_insn_is_c_jalr(insn))
52 rs1_num = RVC_EXTRACT_C2_RS1_REG(insn);
53 else
54 return false;
55
56 *target = regs_ptr[rs1_num];
57
58 return true;
59 }
60
61 /*
62 * Checks if the ebreak trap is because of a CFI failure, and handles the trap
63 * if needed. Returns a bug_trap_type value similarly to report_bug.
64 */
handle_cfi_failure(struct pt_regs * regs)65 enum bug_trap_type handle_cfi_failure(struct pt_regs *regs)
66 {
67 unsigned long target;
68 u32 type;
69
70 if (!is_cfi_trap(regs->epc))
71 return BUG_TRAP_TYPE_NONE;
72
73 if (!decode_cfi_insn(regs, &target, &type))
74 return report_cfi_failure_noaddr(regs, regs->epc);
75
76 return report_cfi_failure(regs, regs->epc, &target, type);
77 }
78