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