1 // SPDX-License-Identifier: GPL-2.0 2 /* Converted from tools/testing/selftests/bpf/verifier/map_ret_val.c */ 3 4 #include <linux/bpf.h> 5 #include <bpf/bpf_helpers.h> 6 #include "../../../include/linux/filter.h" 7 #include "bpf_misc.h" 8 9 struct { 10 __uint(type, BPF_MAP_TYPE_HASH); 11 __uint(max_entries, 1); 12 __type(key, long long); 13 __type(value, long long); 14 } map_hash_8b SEC(".maps"); 15 16 SEC("socket") 17 __description("invalid map_fd for function call") 18 __failure __msg("fd 0 is not pointing to valid bpf_map") 19 __failure_unpriv 20 __naked void map_fd_for_function_call(void) 21 { 22 asm volatile (" \ 23 r2 = 0; \ 24 *(u64*)(r10 - 8) = r2; \ 25 r2 = r10; \ 26 r2 += -8; \ 27 .8byte %[ld_map_fd]; \ 28 .8byte 0; \ 29 call %[bpf_map_delete_elem]; \ 30 exit; \ 31 " : 32 : __imm(bpf_map_delete_elem), 33 __imm_insn(ld_map_fd, BPF_RAW_INSN(BPF_LD | BPF_DW | BPF_IMM, BPF_REG_1, BPF_PSEUDO_MAP_FD, 0, 0)) 34 : __clobber_all); 35 } 36 37 SEC("socket") 38 __description("don't check return value before access") 39 __failure __msg("R0 invalid mem access 'map_value_or_null'") 40 __failure_unpriv 41 __naked void check_return_value_before_access(void) 42 { 43 asm volatile (" \ 44 r1 = 0; \ 45 *(u64*)(r10 - 8) = r1; \ 46 r2 = r10; \ 47 r2 += -8; \ 48 r1 = %[map_hash_8b] ll; \ 49 call %[bpf_map_lookup_elem]; \ 50 r1 = 0; \ 51 *(u64*)(r0 + 0) = r1; \ 52 exit; \ 53 " : 54 : __imm(bpf_map_lookup_elem), 55 __imm_addr(map_hash_8b) 56 : __clobber_all); 57 } 58 59 SEC("socket") 60 __description("access memory with incorrect alignment") 61 __failure __msg("misaligned value access") 62 __failure_unpriv 63 __flag(BPF_F_STRICT_ALIGNMENT) 64 __naked void access_memory_with_incorrect_alignment_1(void) 65 { 66 asm volatile (" \ 67 r1 = 0; \ 68 *(u64*)(r10 - 8) = r1; \ 69 r2 = r10; \ 70 r2 += -8; \ 71 r1 = %[map_hash_8b] ll; \ 72 call %[bpf_map_lookup_elem]; \ 73 if r0 == 0 goto l0_%=; \ 74 r1 = 0; \ 75 *(u64*)(r0 + 4) = r1; \ 76 l0_%=: exit; \ 77 " : 78 : __imm(bpf_map_lookup_elem), 79 __imm_addr(map_hash_8b) 80 : __clobber_all); 81 } 82 83 SEC("socket") 84 __description("sometimes access memory with incorrect alignment") 85 __failure __msg("R0 invalid mem access") 86 __msg_unpriv("R0 leaks addr") 87 __flag(BPF_F_STRICT_ALIGNMENT) 88 __naked void access_memory_with_incorrect_alignment_2(void) 89 { 90 asm volatile (" \ 91 r1 = 0; \ 92 *(u64*)(r10 - 8) = r1; \ 93 r2 = r10; \ 94 r2 += -8; \ 95 r1 = %[map_hash_8b] ll; \ 96 call %[bpf_map_lookup_elem]; \ 97 if r0 == 0 goto l0_%=; \ 98 r1 = 0; \ 99 *(u64*)(r0 + 0) = r1; \ 100 exit; \ 101 l0_%=: r1 = 1; \ 102 *(u64*)(r0 + 0) = r1; \ 103 exit; \ 104 " : 105 : __imm(bpf_map_lookup_elem), 106 __imm_addr(map_hash_8b) 107 : __clobber_all); 108 } 109 110 char _license[] SEC("license") = "GPL"; 111