| 1 | /* SPDX-License-Identifier: GPL-2.0 */ |
| 2 | /* |
| 3 | * Clang Control Flow Integrity (CFI) support. |
| 4 | * |
| 5 | * Copyright (C) 2022 Google LLC |
| 6 | */ |
| 7 | #ifndef _LINUX_CFI_H |
| 8 | #define _LINUX_CFI_H |
| 9 | |
| 10 | #include <linux/bug.h> |
| 11 | #include <linux/module.h> |
| 12 | #include <asm/cfi.h> |
| 13 | |
| 14 | #ifdef CONFIG_CFI |
| 15 | extern bool cfi_warn; |
| 16 | |
| 17 | enum bug_trap_type report_cfi_failure(struct pt_regs *regs, unsigned long addr, |
| 18 | unsigned long *target, u32 type); |
| 19 | |
| 20 | static inline enum bug_trap_type report_cfi_failure_noaddr(struct pt_regs *regs, |
| 21 | unsigned long addr) |
| 22 | { |
| 23 | return report_cfi_failure(regs, addr, NULL, 0); |
| 24 | } |
| 25 | |
| 26 | #ifndef cfi_get_offset |
| 27 | /* |
| 28 | * Returns the CFI prefix offset. By default, the compiler emits only |
| 29 | * a 4-byte CFI type hash before the function. If an architecture |
| 30 | * uses -fpatchable-function-entry=N,M where M>0 to change the prefix |
| 31 | * offset, they must override this function. |
| 32 | */ |
| 33 | static inline int cfi_get_offset(void) |
| 34 | { |
| 35 | return 4; |
| 36 | } |
| 37 | #endif |
| 38 | |
| 39 | #ifndef cfi_get_func_hash |
| 40 | static inline u32 cfi_get_func_hash(void *func) |
| 41 | { |
| 42 | u32 hash; |
| 43 | |
| 44 | if (get_kernel_nofault(hash, func - cfi_get_offset())) |
| 45 | return 0; |
| 46 | |
| 47 | return hash; |
| 48 | } |
| 49 | #endif |
| 50 | |
| 51 | /* CFI type hashes for BPF function types */ |
| 52 | extern u32 cfi_bpf_hash; |
| 53 | extern u32 cfi_bpf_subprog_hash; |
| 54 | |
| 55 | #else /* CONFIG_CFI */ |
| 56 | |
| 57 | static inline int cfi_get_offset(void) { return 0; } |
| 58 | static inline u32 cfi_get_func_hash(void *func) { return 0; } |
| 59 | |
| 60 | #define cfi_bpf_hash 0U |
| 61 | #define cfi_bpf_subprog_hash 0U |
| 62 | |
| 63 | #endif /* CONFIG_CFI */ |
| 64 | |
| 65 | #ifdef CONFIG_ARCH_USES_CFI_TRAPS |
| 66 | bool is_cfi_trap(unsigned long addr); |
| 67 | #else |
| 68 | static inline bool is_cfi_trap(unsigned long addr) { return false; } |
| 69 | #endif |
| 70 | |
| 71 | #ifdef CONFIG_MODULES |
| 72 | #ifdef CONFIG_ARCH_USES_CFI_TRAPS |
| 73 | void module_cfi_finalize(const Elf_Ehdr *hdr, const Elf_Shdr *sechdrs, |
| 74 | struct module *mod); |
| 75 | #else |
| 76 | static inline void module_cfi_finalize(const Elf_Ehdr *hdr, |
| 77 | const Elf_Shdr *sechdrs, |
| 78 | struct module *mod) {} |
| 79 | #endif /* CONFIG_ARCH_USES_CFI_TRAPS */ |
| 80 | #endif /* CONFIG_MODULES */ |
| 81 | |
| 82 | #ifndef CFI_NOSEAL |
| 83 | #define CFI_NOSEAL(x) |
| 84 | #endif |
| 85 | |
| 86 | #endif /* _LINUX_CFI_H */ |
| 87 | |