1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3 * Copyright (c) 2016 Facebook
4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <linux/bpf_mem_alloc.h>
34 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
35 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
36 [_id] = & _name ## _verifier_ops,
37 #define BPF_MAP_TYPE(_id, _ops)
38 #define BPF_LINK_TYPE(_id, _name)
39 #include <linux/bpf_types.h>
45 struct bpf_mem_alloc bpf_global_percpu_ma;
46 static bool bpf_global_percpu_ma_set;
48 /* bpf_check() is a static code analyzer that walks eBPF program
49 * instruction by instruction and updates register/stack state.
50 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
52 * The first pass is depth-first-search to check that the program is a DAG.
53 * It rejects the following programs:
54 * - larger than BPF_MAXINSNS insns
55 * - if loop is present (detected via back-edge)
56 * - unreachable insns exist (shouldn't be a forest. program = one function)
57 * - out of bounds or malformed jumps
58 * The second pass is all possible path descent from the 1st insn.
59 * Since it's analyzing all paths through the program, the length of the
60 * analysis is limited to 64k insn, which may be hit even if total number of
61 * insn is less then 4K, but there are too many branches that change stack/regs.
62 * Number of 'branches to be analyzed' is limited to 1k
64 * On entry to each instruction, each register has a type, and the instruction
65 * changes the types of the registers depending on instruction semantics.
66 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
69 * All registers are 64-bit.
70 * R0 - return register
71 * R1-R5 argument passing registers
72 * R6-R9 callee saved registers
73 * R10 - frame pointer read-only
75 * At the start of BPF program the register R1 contains a pointer to bpf_context
76 * and has type PTR_TO_CTX.
78 * Verifier tracks arithmetic operations on pointers in case:
79 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
80 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
81 * 1st insn copies R10 (which has FRAME_PTR) type into R1
82 * and 2nd arithmetic instruction is pattern matched to recognize
83 * that it wants to construct a pointer to some element within stack.
84 * So after 2nd insn, the register R1 has type PTR_TO_STACK
85 * (and -20 constant is saved for further stack bounds checking).
86 * Meaning that this reg is a pointer to stack plus known immediate constant.
88 * Most of the time the registers have SCALAR_VALUE type, which
89 * means the register has some value, but it's not a valid pointer.
90 * (like pointer plus pointer becomes SCALAR_VALUE type)
92 * When verifier sees load or store instructions the type of base register
93 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
94 * four pointer types recognized by check_mem_access() function.
96 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
97 * and the range of [ptr, ptr + map's value_size) is accessible.
99 * registers used to pass values to function calls are checked against
100 * function argument constraints.
102 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
103 * It means that the register type passed to this function must be
104 * PTR_TO_STACK and it will be used inside the function as
105 * 'pointer to map element key'
107 * For example the argument constraints for bpf_map_lookup_elem():
108 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
109 * .arg1_type = ARG_CONST_MAP_PTR,
110 * .arg2_type = ARG_PTR_TO_MAP_KEY,
112 * ret_type says that this function returns 'pointer to map elem value or null'
113 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
114 * 2nd argument should be a pointer to stack, which will be used inside
115 * the helper function as a pointer to map element key.
117 * On the kernel side the helper function looks like:
118 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
120 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
121 * void *key = (void *) (unsigned long) r2;
124 * here kernel can access 'key' and 'map' pointers safely, knowing that
125 * [key, key + map->key_size) bytes are valid and were initialized on
126 * the stack of eBPF program.
129 * Corresponding eBPF program may look like:
130 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
131 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
132 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
133 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
134 * here verifier looks at prototype of map_lookup_elem() and sees:
135 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
136 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
138 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
139 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
140 * and were initialized prior to this call.
141 * If it's ok, then verifier allows this BPF_CALL insn and looks at
142 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
143 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
144 * returns either pointer to map value or NULL.
146 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
147 * insn, the register holding that pointer in the true branch changes state to
148 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
149 * branch. See check_cond_jmp_op().
151 * After the call R0 is set to return type of the function and registers R1-R5
152 * are set to NOT_INIT to indicate that they are no longer readable.
154 * The following reference types represent a potential reference to a kernel
155 * resource which, after first being allocated, must be checked and freed by
157 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
159 * When the verifier sees a helper call return a reference type, it allocates a
160 * pointer id for the reference and stores it in the current function state.
161 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
162 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
163 * passes through a NULL-check conditional. For the branch wherein the state is
164 * changed to CONST_IMM, the verifier releases the reference.
166 * For each helper function that allocates a reference, such as
167 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
168 * bpf_sk_release(). When a reference type passes into the release function,
169 * the verifier also releases the reference. If any unchecked or unreleased
170 * reference remains at the end of the program, the verifier rejects it.
173 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
174 struct bpf_verifier_stack_elem {
175 /* verifer state is 'st'
176 * before processing instruction 'insn_idx'
177 * and after processing instruction 'prev_insn_idx'
179 struct bpf_verifier_state st;
182 struct bpf_verifier_stack_elem *next;
183 /* length of verifier log at the time this state was pushed on stack */
187 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
188 #define BPF_COMPLEXITY_LIMIT_STATES 64
190 #define BPF_MAP_KEY_POISON (1ULL << 63)
191 #define BPF_MAP_KEY_SEEN (1ULL << 62)
193 #define BPF_MAP_PTR_UNPRIV 1UL
194 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
195 POISON_POINTER_DELTA))
196 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
198 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE 512
200 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
201 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
202 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
203 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
204 static int ref_set_non_owning(struct bpf_verifier_env *env,
205 struct bpf_reg_state *reg);
206 static void specialize_kfunc(struct bpf_verifier_env *env,
207 u32 func_id, u16 offset, unsigned long *addr);
208 static bool is_trusted_reg(const struct bpf_reg_state *reg);
210 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
212 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
215 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
217 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
220 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
221 const struct bpf_map *map, bool unpriv)
223 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
224 unpriv |= bpf_map_ptr_unpriv(aux);
225 aux->map_ptr_state = (unsigned long)map |
226 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
229 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
231 return aux->map_key_state & BPF_MAP_KEY_POISON;
234 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
236 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
239 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
241 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
244 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
246 bool poisoned = bpf_map_key_poisoned(aux);
248 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
249 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
252 static bool bpf_helper_call(const struct bpf_insn *insn)
254 return insn->code == (BPF_JMP | BPF_CALL) &&
258 static bool bpf_pseudo_call(const struct bpf_insn *insn)
260 return insn->code == (BPF_JMP | BPF_CALL) &&
261 insn->src_reg == BPF_PSEUDO_CALL;
264 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
266 return insn->code == (BPF_JMP | BPF_CALL) &&
267 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
270 struct bpf_call_arg_meta {
271 struct bpf_map *map_ptr;
288 struct btf_field *kptr_field;
291 struct bpf_kfunc_call_arg_meta {
296 const struct btf_type *func_proto;
297 const char *func_name;
310 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
311 * generally to pass info about user-defined local kptr types to later
313 * bpf_obj_drop/bpf_percpu_obj_drop
314 * Record the local kptr type to be drop'd
315 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
316 * Record the local kptr type to be refcount_incr'd and use
317 * arg_owning_ref to determine whether refcount_acquire should be
325 struct btf_field *field;
328 struct btf_field *field;
331 enum bpf_dynptr_type type;
334 } initialized_dynptr;
342 struct btf *btf_vmlinux;
344 static const char *btf_type_name(const struct btf *btf, u32 id)
346 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
349 static DEFINE_MUTEX(bpf_verifier_lock);
350 static DEFINE_MUTEX(bpf_percpu_ma_lock);
352 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
354 struct bpf_verifier_env *env = private_data;
357 if (!bpf_verifier_log_needed(&env->log))
361 bpf_verifier_vlog(&env->log, fmt, args);
365 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
366 struct bpf_reg_state *reg,
367 struct bpf_retval_range range, const char *ctx,
368 const char *reg_name)
372 verbose(env, "%s the register %s has", ctx, reg_name);
373 if (reg->smin_value > S64_MIN) {
374 verbose(env, " smin=%lld", reg->smin_value);
377 if (reg->smax_value < S64_MAX) {
378 verbose(env, " smax=%lld", reg->smax_value);
382 verbose(env, " unknown scalar value");
383 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
386 static bool type_may_be_null(u32 type)
388 return type & PTR_MAYBE_NULL;
391 static bool reg_not_null(const struct bpf_reg_state *reg)
393 enum bpf_reg_type type;
396 if (type_may_be_null(type))
399 type = base_type(type);
400 return type == PTR_TO_SOCKET ||
401 type == PTR_TO_TCP_SOCK ||
402 type == PTR_TO_MAP_VALUE ||
403 type == PTR_TO_MAP_KEY ||
404 type == PTR_TO_SOCK_COMMON ||
405 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
409 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
411 struct btf_record *rec = NULL;
412 struct btf_struct_meta *meta;
414 if (reg->type == PTR_TO_MAP_VALUE) {
415 rec = reg->map_ptr->record;
416 } else if (type_is_ptr_alloc_obj(reg->type)) {
417 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
424 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
426 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
428 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
431 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
433 struct bpf_func_info *info;
435 if (!env->prog->aux->func_info)
438 info = &env->prog->aux->func_info[subprog];
439 return btf_type_name(env->prog->aux->btf, info->type_id);
442 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
444 struct bpf_subprog_info *info = subprog_info(env, subprog);
447 info->is_async_cb = true;
448 info->is_exception_cb = true;
451 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
453 return subprog_info(env, subprog)->is_exception_cb;
456 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
458 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
461 static bool type_is_rdonly_mem(u32 type)
463 return type & MEM_RDONLY;
466 static bool is_acquire_function(enum bpf_func_id func_id,
467 const struct bpf_map *map)
469 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
471 if (func_id == BPF_FUNC_sk_lookup_tcp ||
472 func_id == BPF_FUNC_sk_lookup_udp ||
473 func_id == BPF_FUNC_skc_lookup_tcp ||
474 func_id == BPF_FUNC_ringbuf_reserve ||
475 func_id == BPF_FUNC_kptr_xchg)
478 if (func_id == BPF_FUNC_map_lookup_elem &&
479 (map_type == BPF_MAP_TYPE_SOCKMAP ||
480 map_type == BPF_MAP_TYPE_SOCKHASH))
486 static bool is_ptr_cast_function(enum bpf_func_id func_id)
488 return func_id == BPF_FUNC_tcp_sock ||
489 func_id == BPF_FUNC_sk_fullsock ||
490 func_id == BPF_FUNC_skc_to_tcp_sock ||
491 func_id == BPF_FUNC_skc_to_tcp6_sock ||
492 func_id == BPF_FUNC_skc_to_udp6_sock ||
493 func_id == BPF_FUNC_skc_to_mptcp_sock ||
494 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
495 func_id == BPF_FUNC_skc_to_tcp_request_sock;
498 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
500 return func_id == BPF_FUNC_dynptr_data;
503 static bool is_sync_callback_calling_kfunc(u32 btf_id);
504 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
506 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
508 return func_id == BPF_FUNC_for_each_map_elem ||
509 func_id == BPF_FUNC_find_vma ||
510 func_id == BPF_FUNC_loop ||
511 func_id == BPF_FUNC_user_ringbuf_drain;
514 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
516 return func_id == BPF_FUNC_timer_set_callback;
519 static bool is_callback_calling_function(enum bpf_func_id func_id)
521 return is_sync_callback_calling_function(func_id) ||
522 is_async_callback_calling_function(func_id);
525 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
527 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
528 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
531 static bool is_storage_get_function(enum bpf_func_id func_id)
533 return func_id == BPF_FUNC_sk_storage_get ||
534 func_id == BPF_FUNC_inode_storage_get ||
535 func_id == BPF_FUNC_task_storage_get ||
536 func_id == BPF_FUNC_cgrp_storage_get;
539 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
540 const struct bpf_map *map)
542 int ref_obj_uses = 0;
544 if (is_ptr_cast_function(func_id))
546 if (is_acquire_function(func_id, map))
548 if (is_dynptr_ref_function(func_id))
551 return ref_obj_uses > 1;
554 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
556 return BPF_CLASS(insn->code) == BPF_STX &&
557 BPF_MODE(insn->code) == BPF_ATOMIC &&
558 insn->imm == BPF_CMPXCHG;
561 static int __get_spi(s32 off)
563 return (-off - 1) / BPF_REG_SIZE;
566 static struct bpf_func_state *func(struct bpf_verifier_env *env,
567 const struct bpf_reg_state *reg)
569 struct bpf_verifier_state *cur = env->cur_state;
571 return cur->frame[reg->frameno];
574 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
576 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
578 /* We need to check that slots between [spi - nr_slots + 1, spi] are
579 * within [0, allocated_stack).
581 * Please note that the spi grows downwards. For example, a dynptr
582 * takes the size of two stack slots; the first slot will be at
583 * spi and the second slot will be at spi - 1.
585 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
588 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
589 const char *obj_kind, int nr_slots)
593 if (!tnum_is_const(reg->var_off)) {
594 verbose(env, "%s has to be at a constant offset\n", obj_kind);
598 off = reg->off + reg->var_off.value;
599 if (off % BPF_REG_SIZE) {
600 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
604 spi = __get_spi(off);
605 if (spi + 1 < nr_slots) {
606 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
610 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
615 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
617 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
620 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
622 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
625 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
627 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
628 case DYNPTR_TYPE_LOCAL:
629 return BPF_DYNPTR_TYPE_LOCAL;
630 case DYNPTR_TYPE_RINGBUF:
631 return BPF_DYNPTR_TYPE_RINGBUF;
632 case DYNPTR_TYPE_SKB:
633 return BPF_DYNPTR_TYPE_SKB;
634 case DYNPTR_TYPE_XDP:
635 return BPF_DYNPTR_TYPE_XDP;
637 return BPF_DYNPTR_TYPE_INVALID;
641 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
644 case BPF_DYNPTR_TYPE_LOCAL:
645 return DYNPTR_TYPE_LOCAL;
646 case BPF_DYNPTR_TYPE_RINGBUF:
647 return DYNPTR_TYPE_RINGBUF;
648 case BPF_DYNPTR_TYPE_SKB:
649 return DYNPTR_TYPE_SKB;
650 case BPF_DYNPTR_TYPE_XDP:
651 return DYNPTR_TYPE_XDP;
657 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
659 return type == BPF_DYNPTR_TYPE_RINGBUF;
662 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
663 enum bpf_dynptr_type type,
664 bool first_slot, int dynptr_id);
666 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
667 struct bpf_reg_state *reg);
669 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
670 struct bpf_reg_state *sreg1,
671 struct bpf_reg_state *sreg2,
672 enum bpf_dynptr_type type)
674 int id = ++env->id_gen;
676 __mark_dynptr_reg(sreg1, type, true, id);
677 __mark_dynptr_reg(sreg2, type, false, id);
680 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
681 struct bpf_reg_state *reg,
682 enum bpf_dynptr_type type)
684 __mark_dynptr_reg(reg, type, true, ++env->id_gen);
687 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
688 struct bpf_func_state *state, int spi);
690 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
691 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
693 struct bpf_func_state *state = func(env, reg);
694 enum bpf_dynptr_type type;
697 spi = dynptr_get_spi(env, reg);
701 /* We cannot assume both spi and spi - 1 belong to the same dynptr,
702 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
703 * to ensure that for the following example:
706 * So marking spi = 2 should lead to destruction of both d1 and d2. In
707 * case they do belong to same dynptr, second call won't see slot_type
708 * as STACK_DYNPTR and will simply skip destruction.
710 err = destroy_if_dynptr_stack_slot(env, state, spi);
713 err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
717 for (i = 0; i < BPF_REG_SIZE; i++) {
718 state->stack[spi].slot_type[i] = STACK_DYNPTR;
719 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
722 type = arg_to_dynptr_type(arg_type);
723 if (type == BPF_DYNPTR_TYPE_INVALID)
726 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
727 &state->stack[spi - 1].spilled_ptr, type);
729 if (dynptr_type_refcounted(type)) {
730 /* The id is used to track proper releasing */
733 if (clone_ref_obj_id)
734 id = clone_ref_obj_id;
736 id = acquire_reference_state(env, insn_idx);
741 state->stack[spi].spilled_ptr.ref_obj_id = id;
742 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
745 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
746 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
751 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
755 for (i = 0; i < BPF_REG_SIZE; i++) {
756 state->stack[spi].slot_type[i] = STACK_INVALID;
757 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
760 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
761 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
763 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
765 * While we don't allow reading STACK_INVALID, it is still possible to
766 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
767 * helpers or insns can do partial read of that part without failing,
768 * but check_stack_range_initialized, check_stack_read_var_off, and
769 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
770 * the slot conservatively. Hence we need to prevent those liveness
773 * This was not a problem before because STACK_INVALID is only set by
774 * default (where the default reg state has its reg->parent as NULL), or
775 * in clean_live_states after REG_LIVE_DONE (at which point
776 * mark_reg_read won't walk reg->parent chain), but not randomly during
777 * verifier state exploration (like we did above). Hence, for our case
778 * parentage chain will still be live (i.e. reg->parent may be
779 * non-NULL), while earlier reg->parent was NULL, so we need
780 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
781 * done later on reads or by mark_dynptr_read as well to unnecessary
782 * mark registers in verifier state.
784 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
785 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
788 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
790 struct bpf_func_state *state = func(env, reg);
791 int spi, ref_obj_id, i;
793 spi = dynptr_get_spi(env, reg);
797 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
798 invalidate_dynptr(env, state, spi);
802 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
804 /* If the dynptr has a ref_obj_id, then we need to invalidate
807 * 1) Any dynptrs with a matching ref_obj_id (clones)
808 * 2) Any slices derived from this dynptr.
811 /* Invalidate any slices associated with this dynptr */
812 WARN_ON_ONCE(release_reference(env, ref_obj_id));
814 /* Invalidate any dynptr clones */
815 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
816 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
819 /* it should always be the case that if the ref obj id
820 * matches then the stack slot also belongs to a
823 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
824 verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
827 if (state->stack[i].spilled_ptr.dynptr.first_slot)
828 invalidate_dynptr(env, state, i);
834 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
835 struct bpf_reg_state *reg);
837 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
839 if (!env->allow_ptr_leaks)
840 __mark_reg_not_init(env, reg);
842 __mark_reg_unknown(env, reg);
845 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
846 struct bpf_func_state *state, int spi)
848 struct bpf_func_state *fstate;
849 struct bpf_reg_state *dreg;
852 /* We always ensure that STACK_DYNPTR is never set partially,
853 * hence just checking for slot_type[0] is enough. This is
854 * different for STACK_SPILL, where it may be only set for
855 * 1 byte, so code has to use is_spilled_reg.
857 if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
860 /* Reposition spi to first slot */
861 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
864 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
865 verbose(env, "cannot overwrite referenced dynptr\n");
869 mark_stack_slot_scratched(env, spi);
870 mark_stack_slot_scratched(env, spi - 1);
872 /* Writing partially to one dynptr stack slot destroys both. */
873 for (i = 0; i < BPF_REG_SIZE; i++) {
874 state->stack[spi].slot_type[i] = STACK_INVALID;
875 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
878 dynptr_id = state->stack[spi].spilled_ptr.id;
879 /* Invalidate any slices associated with this dynptr */
880 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
881 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
882 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
884 if (dreg->dynptr_id == dynptr_id)
885 mark_reg_invalid(env, dreg);
888 /* Do not release reference state, we are destroying dynptr on stack,
889 * not using some helper to release it. Just reset register.
891 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
892 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
894 /* Same reason as unmark_stack_slots_dynptr above */
895 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
896 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
901 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
905 if (reg->type == CONST_PTR_TO_DYNPTR)
908 spi = dynptr_get_spi(env, reg);
910 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
911 * error because this just means the stack state hasn't been updated yet.
912 * We will do check_mem_access to check and update stack bounds later.
914 if (spi < 0 && spi != -ERANGE)
917 /* We don't need to check if the stack slots are marked by previous
918 * dynptr initializations because we allow overwriting existing unreferenced
919 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
920 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
921 * touching are completely destructed before we reinitialize them for a new
922 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
923 * instead of delaying it until the end where the user will get "Unreleased
929 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
931 struct bpf_func_state *state = func(env, reg);
934 /* This already represents first slot of initialized bpf_dynptr.
936 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
937 * check_func_arg_reg_off's logic, so we don't need to check its
938 * offset and alignment.
940 if (reg->type == CONST_PTR_TO_DYNPTR)
943 spi = dynptr_get_spi(env, reg);
946 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
949 for (i = 0; i < BPF_REG_SIZE; i++) {
950 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
951 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
958 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
959 enum bpf_arg_type arg_type)
961 struct bpf_func_state *state = func(env, reg);
962 enum bpf_dynptr_type dynptr_type;
965 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
966 if (arg_type == ARG_PTR_TO_DYNPTR)
969 dynptr_type = arg_to_dynptr_type(arg_type);
970 if (reg->type == CONST_PTR_TO_DYNPTR) {
971 return reg->dynptr.type == dynptr_type;
973 spi = dynptr_get_spi(env, reg);
976 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
980 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
982 static bool in_rcu_cs(struct bpf_verifier_env *env);
984 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
986 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
987 struct bpf_kfunc_call_arg_meta *meta,
988 struct bpf_reg_state *reg, int insn_idx,
989 struct btf *btf, u32 btf_id, int nr_slots)
991 struct bpf_func_state *state = func(env, reg);
994 spi = iter_get_spi(env, reg, nr_slots);
998 id = acquire_reference_state(env, insn_idx);
1002 for (i = 0; i < nr_slots; i++) {
1003 struct bpf_stack_state *slot = &state->stack[spi - i];
1004 struct bpf_reg_state *st = &slot->spilled_ptr;
1006 __mark_reg_known_zero(st);
1007 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1008 if (is_kfunc_rcu_protected(meta)) {
1010 st->type |= MEM_RCU;
1012 st->type |= PTR_UNTRUSTED;
1014 st->live |= REG_LIVE_WRITTEN;
1015 st->ref_obj_id = i == 0 ? id : 0;
1017 st->iter.btf_id = btf_id;
1018 st->iter.state = BPF_ITER_STATE_ACTIVE;
1021 for (j = 0; j < BPF_REG_SIZE; j++)
1022 slot->slot_type[j] = STACK_ITER;
1024 mark_stack_slot_scratched(env, spi - i);
1030 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1031 struct bpf_reg_state *reg, int nr_slots)
1033 struct bpf_func_state *state = func(env, reg);
1036 spi = iter_get_spi(env, reg, nr_slots);
1040 for (i = 0; i < nr_slots; i++) {
1041 struct bpf_stack_state *slot = &state->stack[spi - i];
1042 struct bpf_reg_state *st = &slot->spilled_ptr;
1045 WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1047 __mark_reg_not_init(env, st);
1049 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1050 st->live |= REG_LIVE_WRITTEN;
1052 for (j = 0; j < BPF_REG_SIZE; j++)
1053 slot->slot_type[j] = STACK_INVALID;
1055 mark_stack_slot_scratched(env, spi - i);
1061 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1062 struct bpf_reg_state *reg, int nr_slots)
1064 struct bpf_func_state *state = func(env, reg);
1067 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1068 * will do check_mem_access to check and update stack bounds later, so
1069 * return true for that case.
1071 spi = iter_get_spi(env, reg, nr_slots);
1077 for (i = 0; i < nr_slots; i++) {
1078 struct bpf_stack_state *slot = &state->stack[spi - i];
1080 for (j = 0; j < BPF_REG_SIZE; j++)
1081 if (slot->slot_type[j] == STACK_ITER)
1088 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1089 struct btf *btf, u32 btf_id, int nr_slots)
1091 struct bpf_func_state *state = func(env, reg);
1094 spi = iter_get_spi(env, reg, nr_slots);
1098 for (i = 0; i < nr_slots; i++) {
1099 struct bpf_stack_state *slot = &state->stack[spi - i];
1100 struct bpf_reg_state *st = &slot->spilled_ptr;
1102 if (st->type & PTR_UNTRUSTED)
1104 /* only main (first) slot has ref_obj_id set */
1105 if (i == 0 && !st->ref_obj_id)
1107 if (i != 0 && st->ref_obj_id)
1109 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1112 for (j = 0; j < BPF_REG_SIZE; j++)
1113 if (slot->slot_type[j] != STACK_ITER)
1120 /* Check if given stack slot is "special":
1121 * - spilled register state (STACK_SPILL);
1122 * - dynptr state (STACK_DYNPTR);
1123 * - iter state (STACK_ITER).
1125 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1127 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1139 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1144 /* The reg state of a pointer or a bounded scalar was saved when
1145 * it was spilled to the stack.
1147 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1149 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1152 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1154 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1155 stack->spilled_ptr.type == SCALAR_VALUE;
1158 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1160 return stack->slot_type[0] == STACK_SPILL &&
1161 stack->spilled_ptr.type == SCALAR_VALUE;
1164 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1165 * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1166 * more precise STACK_ZERO.
1167 * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take
1168 * env->allow_ptr_leaks into account and force STACK_MISC, if necessary.
1170 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1172 if (*stype == STACK_ZERO)
1174 if (env->allow_ptr_leaks && *stype == STACK_INVALID)
1176 *stype = STACK_MISC;
1179 static void scrub_spilled_slot(u8 *stype)
1181 if (*stype != STACK_INVALID)
1182 *stype = STACK_MISC;
1185 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1186 * small to hold src. This is different from krealloc since we don't want to preserve
1187 * the contents of dst.
1189 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1192 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1198 if (ZERO_OR_NULL_PTR(src))
1201 if (unlikely(check_mul_overflow(n, size, &bytes)))
1204 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1205 dst = krealloc(orig, alloc_bytes, flags);
1211 memcpy(dst, src, bytes);
1213 return dst ? dst : ZERO_SIZE_PTR;
1216 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1217 * small to hold new_n items. new items are zeroed out if the array grows.
1219 * Contrary to krealloc_array, does not free arr if new_n is zero.
1221 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1226 if (!new_n || old_n == new_n)
1229 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1230 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1238 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1241 return arr ? arr : ZERO_SIZE_PTR;
1244 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1246 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1247 sizeof(struct bpf_reference_state), GFP_KERNEL);
1251 dst->acquired_refs = src->acquired_refs;
1255 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1257 size_t n = src->allocated_stack / BPF_REG_SIZE;
1259 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1264 dst->allocated_stack = src->allocated_stack;
1268 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1270 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1271 sizeof(struct bpf_reference_state));
1275 state->acquired_refs = n;
1279 /* Possibly update state->allocated_stack to be at least size bytes. Also
1280 * possibly update the function's high-water mark in its bpf_subprog_info.
1282 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1284 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1286 /* The stack size is always a multiple of BPF_REG_SIZE. */
1287 size = round_up(size, BPF_REG_SIZE);
1288 n = size / BPF_REG_SIZE;
1293 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1297 state->allocated_stack = size;
1299 /* update known max for given subprogram */
1300 if (env->subprog_info[state->subprogno].stack_depth < size)
1301 env->subprog_info[state->subprogno].stack_depth = size;
1306 /* Acquire a pointer id from the env and update the state->refs to include
1307 * this new pointer reference.
1308 * On success, returns a valid pointer id to associate with the register
1309 * On failure, returns a negative errno.
1311 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1313 struct bpf_func_state *state = cur_func(env);
1314 int new_ofs = state->acquired_refs;
1317 err = resize_reference_state(state, state->acquired_refs + 1);
1321 state->refs[new_ofs].id = id;
1322 state->refs[new_ofs].insn_idx = insn_idx;
1323 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1328 /* release function corresponding to acquire_reference_state(). Idempotent. */
1329 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1333 last_idx = state->acquired_refs - 1;
1334 for (i = 0; i < state->acquired_refs; i++) {
1335 if (state->refs[i].id == ptr_id) {
1336 /* Cannot release caller references in callbacks */
1337 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1339 if (last_idx && i != last_idx)
1340 memcpy(&state->refs[i], &state->refs[last_idx],
1341 sizeof(*state->refs));
1342 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1343 state->acquired_refs--;
1350 static void free_func_state(struct bpf_func_state *state)
1355 kfree(state->stack);
1359 static void clear_jmp_history(struct bpf_verifier_state *state)
1361 kfree(state->jmp_history);
1362 state->jmp_history = NULL;
1363 state->jmp_history_cnt = 0;
1366 static void free_verifier_state(struct bpf_verifier_state *state,
1371 for (i = 0; i <= state->curframe; i++) {
1372 free_func_state(state->frame[i]);
1373 state->frame[i] = NULL;
1375 clear_jmp_history(state);
1380 /* copy verifier state from src to dst growing dst stack space
1381 * when necessary to accommodate larger src stack
1383 static int copy_func_state(struct bpf_func_state *dst,
1384 const struct bpf_func_state *src)
1388 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1389 err = copy_reference_state(dst, src);
1392 return copy_stack_state(dst, src);
1395 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1396 const struct bpf_verifier_state *src)
1398 struct bpf_func_state *dst;
1401 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1402 src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1404 if (!dst_state->jmp_history)
1406 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1408 /* if dst has more stack frames then src frame, free them, this is also
1409 * necessary in case of exceptional exits using bpf_throw.
1411 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1412 free_func_state(dst_state->frame[i]);
1413 dst_state->frame[i] = NULL;
1415 dst_state->speculative = src->speculative;
1416 dst_state->active_rcu_lock = src->active_rcu_lock;
1417 dst_state->curframe = src->curframe;
1418 dst_state->active_lock.ptr = src->active_lock.ptr;
1419 dst_state->active_lock.id = src->active_lock.id;
1420 dst_state->branches = src->branches;
1421 dst_state->parent = src->parent;
1422 dst_state->first_insn_idx = src->first_insn_idx;
1423 dst_state->last_insn_idx = src->last_insn_idx;
1424 dst_state->dfs_depth = src->dfs_depth;
1425 dst_state->callback_unroll_depth = src->callback_unroll_depth;
1426 dst_state->used_as_loop_entry = src->used_as_loop_entry;
1427 for (i = 0; i <= src->curframe; i++) {
1428 dst = dst_state->frame[i];
1430 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1433 dst_state->frame[i] = dst;
1435 err = copy_func_state(dst, src->frame[i]);
1442 static u32 state_htab_size(struct bpf_verifier_env *env)
1444 return env->prog->len;
1447 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1449 struct bpf_verifier_state *cur = env->cur_state;
1450 struct bpf_func_state *state = cur->frame[cur->curframe];
1452 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1455 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1459 if (a->curframe != b->curframe)
1462 for (fr = a->curframe; fr >= 0; fr--)
1463 if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1469 /* Open coded iterators allow back-edges in the state graph in order to
1470 * check unbounded loops that iterators.
1472 * In is_state_visited() it is necessary to know if explored states are
1473 * part of some loops in order to decide whether non-exact states
1474 * comparison could be used:
1475 * - non-exact states comparison establishes sub-state relation and uses
1476 * read and precision marks to do so, these marks are propagated from
1477 * children states and thus are not guaranteed to be final in a loop;
1478 * - exact states comparison just checks if current and explored states
1479 * are identical (and thus form a back-edge).
1481 * Paper "A New Algorithm for Identifying Loops in Decompilation"
1482 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1483 * algorithm for loop structure detection and gives an overview of
1484 * relevant terminology. It also has helpful illustrations.
1486 * [1] https://api.semanticscholar.org/CorpusID:15784067
1488 * We use a similar algorithm but because loop nested structure is
1489 * irrelevant for verifier ours is significantly simpler and resembles
1490 * strongly connected components algorithm from Sedgewick's textbook.
1492 * Define topmost loop entry as a first node of the loop traversed in a
1493 * depth first search starting from initial state. The goal of the loop
1494 * tracking algorithm is to associate topmost loop entries with states
1495 * derived from these entries.
1497 * For each step in the DFS states traversal algorithm needs to identify
1498 * the following situations:
1500 * initial initial initial
1503 * ... ... .---------> hdr
1506 * cur .-> succ | .------...
1509 * succ '-- cur | ... ...
1519 * (A) successor state of cur (B) successor state of cur or it's entry
1520 * not yet traversed are in current DFS path, thus cur and succ
1521 * are members of the same outermost loop
1529 * .------... .------...
1532 * .-> hdr ... ... ...
1535 * | succ <- cur succ <- cur
1542 * (C) successor state of cur is a part of some loop but this loop
1543 * does not include cur or successor state is not in a loop at all.
1545 * Algorithm could be described as the following python code:
1547 * traversed = set() # Set of traversed nodes
1548 * entries = {} # Mapping from node to loop entry
1549 * depths = {} # Depth level assigned to graph node
1550 * path = set() # Current DFS path
1552 * # Find outermost loop entry known for n
1553 * def get_loop_entry(n):
1554 * h = entries.get(n, None)
1555 * while h in entries and entries[h] != h:
1559 * # Update n's loop entry if h's outermost entry comes
1560 * # before n's outermost entry in current DFS path.
1561 * def update_loop_entry(n, h):
1562 * n1 = get_loop_entry(n) or n
1563 * h1 = get_loop_entry(h) or h
1564 * if h1 in path and depths[h1] <= depths[n1]:
1567 * def dfs(n, depth):
1571 * for succ in G.successors(n):
1572 * if succ not in traversed:
1573 * # Case A: explore succ and update cur's loop entry
1574 * # only if succ's entry is in current DFS path.
1575 * dfs(succ, depth + 1)
1576 * h = get_loop_entry(succ)
1577 * update_loop_entry(n, h)
1579 * # Case B or C depending on `h1 in path` check in update_loop_entry().
1580 * update_loop_entry(n, succ)
1583 * To adapt this algorithm for use with verifier:
1584 * - use st->branch == 0 as a signal that DFS of succ had been finished
1585 * and cur's loop entry has to be updated (case A), handle this in
1586 * update_branch_counts();
1587 * - use st->branch > 0 as a signal that st is in the current DFS path;
1588 * - handle cases B and C in is_state_visited();
1589 * - update topmost loop entry for intermediate states in get_loop_entry().
1591 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1593 struct bpf_verifier_state *topmost = st->loop_entry, *old;
1595 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1596 topmost = topmost->loop_entry;
1597 /* Update loop entries for intermediate states to avoid this
1598 * traversal in future get_loop_entry() calls.
1600 while (st && st->loop_entry != topmost) {
1601 old = st->loop_entry;
1602 st->loop_entry = topmost;
1608 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1610 struct bpf_verifier_state *cur1, *hdr1;
1612 cur1 = get_loop_entry(cur) ?: cur;
1613 hdr1 = get_loop_entry(hdr) ?: hdr;
1614 /* The head1->branches check decides between cases B and C in
1615 * comment for get_loop_entry(). If hdr1->branches == 0 then
1616 * head's topmost loop entry is not in current DFS path,
1617 * hence 'cur' and 'hdr' are not in the same loop and there is
1618 * no need to update cur->loop_entry.
1620 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1621 cur->loop_entry = hdr;
1622 hdr->used_as_loop_entry = true;
1626 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1629 u32 br = --st->branches;
1631 /* br == 0 signals that DFS exploration for 'st' is finished,
1632 * thus it is necessary to update parent's loop entry if it
1633 * turned out that st is a part of some loop.
1634 * This is a part of 'case A' in get_loop_entry() comment.
1636 if (br == 0 && st->parent && st->loop_entry)
1637 update_loop_entry(st->parent, st->loop_entry);
1639 /* WARN_ON(br > 1) technically makes sense here,
1640 * but see comment in push_stack(), hence:
1642 WARN_ONCE((int)br < 0,
1643 "BUG update_branch_counts:branches_to_explore=%d\n",
1651 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1652 int *insn_idx, bool pop_log)
1654 struct bpf_verifier_state *cur = env->cur_state;
1655 struct bpf_verifier_stack_elem *elem, *head = env->head;
1658 if (env->head == NULL)
1662 err = copy_verifier_state(cur, &head->st);
1667 bpf_vlog_reset(&env->log, head->log_pos);
1669 *insn_idx = head->insn_idx;
1671 *prev_insn_idx = head->prev_insn_idx;
1673 free_verifier_state(&head->st, false);
1680 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1681 int insn_idx, int prev_insn_idx,
1684 struct bpf_verifier_state *cur = env->cur_state;
1685 struct bpf_verifier_stack_elem *elem;
1688 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1692 elem->insn_idx = insn_idx;
1693 elem->prev_insn_idx = prev_insn_idx;
1694 elem->next = env->head;
1695 elem->log_pos = env->log.end_pos;
1698 err = copy_verifier_state(&elem->st, cur);
1701 elem->st.speculative |= speculative;
1702 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1703 verbose(env, "The sequence of %d jumps is too complex.\n",
1707 if (elem->st.parent) {
1708 ++elem->st.parent->branches;
1709 /* WARN_ON(branches > 2) technically makes sense here,
1711 * 1. speculative states will bump 'branches' for non-branch
1713 * 2. is_state_visited() heuristics may decide not to create
1714 * a new state for a sequence of branches and all such current
1715 * and cloned states will be pointing to a single parent state
1716 * which might have large 'branches' count.
1721 free_verifier_state(env->cur_state, true);
1722 env->cur_state = NULL;
1723 /* pop all elements and return */
1724 while (!pop_stack(env, NULL, NULL, false));
1728 #define CALLER_SAVED_REGS 6
1729 static const int caller_saved[CALLER_SAVED_REGS] = {
1730 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1733 /* This helper doesn't clear reg->id */
1734 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1736 reg->var_off = tnum_const(imm);
1737 reg->smin_value = (s64)imm;
1738 reg->smax_value = (s64)imm;
1739 reg->umin_value = imm;
1740 reg->umax_value = imm;
1742 reg->s32_min_value = (s32)imm;
1743 reg->s32_max_value = (s32)imm;
1744 reg->u32_min_value = (u32)imm;
1745 reg->u32_max_value = (u32)imm;
1748 /* Mark the unknown part of a register (variable offset or scalar value) as
1749 * known to have the value @imm.
1751 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1753 /* Clear off and union(map_ptr, range) */
1754 memset(((u8 *)reg) + sizeof(reg->type), 0,
1755 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1757 reg->ref_obj_id = 0;
1758 ___mark_reg_known(reg, imm);
1761 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1763 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1764 reg->s32_min_value = (s32)imm;
1765 reg->s32_max_value = (s32)imm;
1766 reg->u32_min_value = (u32)imm;
1767 reg->u32_max_value = (u32)imm;
1770 /* Mark the 'variable offset' part of a register as zero. This should be
1771 * used only on registers holding a pointer type.
1773 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1775 __mark_reg_known(reg, 0);
1778 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1780 __mark_reg_known(reg, 0);
1781 reg->type = SCALAR_VALUE;
1782 /* all scalars are assumed imprecise initially (unless unprivileged,
1783 * in which case everything is forced to be precise)
1785 reg->precise = !env->bpf_capable;
1788 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1789 struct bpf_reg_state *regs, u32 regno)
1791 if (WARN_ON(regno >= MAX_BPF_REG)) {
1792 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1793 /* Something bad happened, let's kill all regs */
1794 for (regno = 0; regno < MAX_BPF_REG; regno++)
1795 __mark_reg_not_init(env, regs + regno);
1798 __mark_reg_known_zero(regs + regno);
1801 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1802 bool first_slot, int dynptr_id)
1804 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1805 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1806 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1808 __mark_reg_known_zero(reg);
1809 reg->type = CONST_PTR_TO_DYNPTR;
1810 /* Give each dynptr a unique id to uniquely associate slices to it. */
1811 reg->id = dynptr_id;
1812 reg->dynptr.type = type;
1813 reg->dynptr.first_slot = first_slot;
1816 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1818 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1819 const struct bpf_map *map = reg->map_ptr;
1821 if (map->inner_map_meta) {
1822 reg->type = CONST_PTR_TO_MAP;
1823 reg->map_ptr = map->inner_map_meta;
1824 /* transfer reg's id which is unique for every map_lookup_elem
1825 * as UID of the inner map.
1827 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1828 reg->map_uid = reg->id;
1829 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1830 reg->type = PTR_TO_XDP_SOCK;
1831 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1832 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1833 reg->type = PTR_TO_SOCKET;
1835 reg->type = PTR_TO_MAP_VALUE;
1840 reg->type &= ~PTR_MAYBE_NULL;
1843 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1844 struct btf_field_graph_root *ds_head)
1846 __mark_reg_known_zero(®s[regno]);
1847 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1848 regs[regno].btf = ds_head->btf;
1849 regs[regno].btf_id = ds_head->value_btf_id;
1850 regs[regno].off = ds_head->node_offset;
1853 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1855 return type_is_pkt_pointer(reg->type);
1858 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1860 return reg_is_pkt_pointer(reg) ||
1861 reg->type == PTR_TO_PACKET_END;
1864 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1866 return base_type(reg->type) == PTR_TO_MEM &&
1867 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1870 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1871 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1872 enum bpf_reg_type which)
1874 /* The register can already have a range from prior markings.
1875 * This is fine as long as it hasn't been advanced from its
1878 return reg->type == which &&
1881 tnum_equals_const(reg->var_off, 0);
1884 /* Reset the min/max bounds of a register */
1885 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1887 reg->smin_value = S64_MIN;
1888 reg->smax_value = S64_MAX;
1889 reg->umin_value = 0;
1890 reg->umax_value = U64_MAX;
1892 reg->s32_min_value = S32_MIN;
1893 reg->s32_max_value = S32_MAX;
1894 reg->u32_min_value = 0;
1895 reg->u32_max_value = U32_MAX;
1898 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1900 reg->smin_value = S64_MIN;
1901 reg->smax_value = S64_MAX;
1902 reg->umin_value = 0;
1903 reg->umax_value = U64_MAX;
1906 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1908 reg->s32_min_value = S32_MIN;
1909 reg->s32_max_value = S32_MAX;
1910 reg->u32_min_value = 0;
1911 reg->u32_max_value = U32_MAX;
1914 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1916 struct tnum var32_off = tnum_subreg(reg->var_off);
1918 /* min signed is max(sign bit) | min(other bits) */
1919 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1920 var32_off.value | (var32_off.mask & S32_MIN));
1921 /* max signed is min(sign bit) | max(other bits) */
1922 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1923 var32_off.value | (var32_off.mask & S32_MAX));
1924 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1925 reg->u32_max_value = min(reg->u32_max_value,
1926 (u32)(var32_off.value | var32_off.mask));
1929 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1931 /* min signed is max(sign bit) | min(other bits) */
1932 reg->smin_value = max_t(s64, reg->smin_value,
1933 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1934 /* max signed is min(sign bit) | max(other bits) */
1935 reg->smax_value = min_t(s64, reg->smax_value,
1936 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1937 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1938 reg->umax_value = min(reg->umax_value,
1939 reg->var_off.value | reg->var_off.mask);
1942 static void __update_reg_bounds(struct bpf_reg_state *reg)
1944 __update_reg32_bounds(reg);
1945 __update_reg64_bounds(reg);
1948 /* Uses signed min/max values to inform unsigned, and vice-versa */
1949 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1951 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32
1952 * bits to improve our u32/s32 boundaries.
1954 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
1955 * u64) is pretty trivial, it's obvious that in u32 we'll also have
1956 * [10, 20] range. But this property holds for any 64-bit range as
1957 * long as upper 32 bits in that entire range of values stay the same.
1959 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
1960 * in decimal) has the same upper 32 bits throughout all the values in
1961 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
1964 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
1965 * following the rules outlined below about u64/s64 correspondence
1966 * (which equally applies to u32 vs s32 correspondence). In general it
1967 * depends on actual hexadecimal values of 32-bit range. They can form
1968 * only valid u32, or only valid s32 ranges in some cases.
1970 * So we use all these insights to derive bounds for subregisters here.
1972 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
1973 /* u64 to u32 casting preserves validity of low 32 bits as
1974 * a range, if upper 32 bits are the same
1976 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
1977 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
1979 if ((s32)reg->umin_value <= (s32)reg->umax_value) {
1980 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
1981 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
1984 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
1985 /* low 32 bits should form a proper u32 range */
1986 if ((u32)reg->smin_value <= (u32)reg->smax_value) {
1987 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
1988 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
1990 /* low 32 bits should form a proper s32 range */
1991 if ((s32)reg->smin_value <= (s32)reg->smax_value) {
1992 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
1993 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
1996 /* Special case where upper bits form a small sequence of two
1997 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
1998 * 0x00000000 is also valid), while lower bits form a proper s32 range
1999 * going from negative numbers to positive numbers. E.g., let's say we
2000 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2001 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2002 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2003 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2004 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2005 * upper 32 bits. As a random example, s64 range
2006 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2007 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2009 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2010 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2011 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2012 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2014 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2015 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2016 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2017 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2019 /* if u32 range forms a valid s32 range (due to matching sign bit),
2020 * try to learn from that
2022 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2023 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2024 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2026 /* If we cannot cross the sign boundary, then signed and unsigned bounds
2027 * are the same, so combine. This works even in the negative case, e.g.
2028 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2030 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2031 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2032 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2036 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2038 /* If u64 range forms a valid s64 range (due to matching sign bit),
2039 * try to learn from that. Let's do a bit of ASCII art to see when
2040 * this is happening. Let's take u64 range first:
2042 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
2043 * |-------------------------------|--------------------------------|
2045 * Valid u64 range is formed when umin and umax are anywhere in the
2046 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2047 * straightforward. Let's see how s64 range maps onto the same range
2048 * of values, annotated below the line for comparison:
2050 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
2051 * |-------------------------------|--------------------------------|
2052 * 0 S64_MAX S64_MIN -1
2054 * So s64 values basically start in the middle and they are logically
2055 * contiguous to the right of it, wrapping around from -1 to 0, and
2056 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2057 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2058 * more visually as mapped to sign-agnostic range of hex values.
2061 * _______________________________________________________________
2063 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
2064 * |-------------------------------|--------------------------------|
2065 * 0 S64_MAX S64_MIN -1
2067 * >------------------------------ ------------------------------->
2068 * s64 continues... s64 end s64 start s64 "midpoint"
2070 * What this means is that, in general, we can't always derive
2071 * something new about u64 from any random s64 range, and vice versa.
2073 * But we can do that in two particular cases. One is when entire
2074 * u64/s64 range is *entirely* contained within left half of the above
2075 * diagram or when it is *entirely* contained in the right half. I.e.:
2077 * |-------------------------------|--------------------------------|
2081 * [A, B] and [C, D] are contained entirely in their respective halves
2082 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2083 * will be non-negative both as u64 and s64 (and in fact it will be
2084 * identical ranges no matter the signedness). [C, D] treated as s64
2085 * will be a range of negative values, while in u64 it will be
2086 * non-negative range of values larger than 0x8000000000000000.
2088 * Now, any other range here can't be represented in both u64 and s64
2089 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2090 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2091 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2092 * for example. Similarly, valid s64 range [D, A] (going from negative
2093 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2094 * ranges as u64. Currently reg_state can't represent two segments per
2095 * numeric domain, so in such situations we can only derive maximal
2096 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2098 * So we use these facts to derive umin/umax from smin/smax and vice
2099 * versa only if they stay within the same "half". This is equivalent
2100 * to checking sign bit: lower half will have sign bit as zero, upper
2101 * half have sign bit 1. Below in code we simplify this by just
2102 * casting umin/umax as smin/smax and checking if they form valid
2103 * range, and vice versa. Those are equivalent checks.
2105 if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2106 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2107 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2109 /* If we cannot cross the sign boundary, then signed and unsigned bounds
2110 * are the same, so combine. This works even in the negative case, e.g.
2111 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2113 if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2114 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2115 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2119 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2121 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2122 * values on both sides of 64-bit range in hope to have tigher range.
2123 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2124 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2125 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2126 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2127 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2128 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2129 * We just need to make sure that derived bounds we are intersecting
2130 * with are well-formed ranges in respecitve s64 or u64 domain, just
2131 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2133 __u64 new_umin, new_umax;
2134 __s64 new_smin, new_smax;
2136 /* u32 -> u64 tightening, it's always well-formed */
2137 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2138 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2139 reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2140 reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2141 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2142 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2143 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2144 reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2145 reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2147 /* if s32 can be treated as valid u32 range, we can use it as well */
2148 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2149 /* s32 -> u64 tightening */
2150 new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2151 new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2152 reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2153 reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2154 /* s32 -> s64 tightening */
2155 new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2156 new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2157 reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2158 reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2162 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2164 __reg32_deduce_bounds(reg);
2165 __reg64_deduce_bounds(reg);
2166 __reg_deduce_mixed_bounds(reg);
2169 /* Attempts to improve var_off based on unsigned min/max information */
2170 static void __reg_bound_offset(struct bpf_reg_state *reg)
2172 struct tnum var64_off = tnum_intersect(reg->var_off,
2173 tnum_range(reg->umin_value,
2175 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2176 tnum_range(reg->u32_min_value,
2177 reg->u32_max_value));
2179 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2182 static void reg_bounds_sync(struct bpf_reg_state *reg)
2184 /* We might have learned new bounds from the var_off. */
2185 __update_reg_bounds(reg);
2186 /* We might have learned something about the sign bit. */
2187 __reg_deduce_bounds(reg);
2188 __reg_deduce_bounds(reg);
2189 /* We might have learned some bits from the bounds. */
2190 __reg_bound_offset(reg);
2191 /* Intersecting with the old var_off might have improved our bounds
2192 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2193 * then new var_off is (0; 0x7f...fc) which improves our umax.
2195 __update_reg_bounds(reg);
2198 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2199 struct bpf_reg_state *reg, const char *ctx)
2203 if (reg->umin_value > reg->umax_value ||
2204 reg->smin_value > reg->smax_value ||
2205 reg->u32_min_value > reg->u32_max_value ||
2206 reg->s32_min_value > reg->s32_max_value) {
2207 msg = "range bounds violation";
2211 if (tnum_is_const(reg->var_off)) {
2212 u64 uval = reg->var_off.value;
2213 s64 sval = (s64)uval;
2215 if (reg->umin_value != uval || reg->umax_value != uval ||
2216 reg->smin_value != sval || reg->smax_value != sval) {
2217 msg = "const tnum out of sync with range bounds";
2222 if (tnum_subreg_is_const(reg->var_off)) {
2223 u32 uval32 = tnum_subreg(reg->var_off).value;
2224 s32 sval32 = (s32)uval32;
2226 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2227 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2228 msg = "const subreg tnum out of sync with range bounds";
2235 verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2236 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2237 ctx, msg, reg->umin_value, reg->umax_value,
2238 reg->smin_value, reg->smax_value,
2239 reg->u32_min_value, reg->u32_max_value,
2240 reg->s32_min_value, reg->s32_max_value,
2241 reg->var_off.value, reg->var_off.mask);
2242 if (env->test_reg_invariants)
2244 __mark_reg_unbounded(reg);
2248 static bool __reg32_bound_s64(s32 a)
2250 return a >= 0 && a <= S32_MAX;
2253 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2255 reg->umin_value = reg->u32_min_value;
2256 reg->umax_value = reg->u32_max_value;
2258 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2259 * be positive otherwise set to worse case bounds and refine later
2262 if (__reg32_bound_s64(reg->s32_min_value) &&
2263 __reg32_bound_s64(reg->s32_max_value)) {
2264 reg->smin_value = reg->s32_min_value;
2265 reg->smax_value = reg->s32_max_value;
2267 reg->smin_value = 0;
2268 reg->smax_value = U32_MAX;
2272 /* Mark a register as having a completely unknown (scalar) value. */
2273 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2276 * Clear type, off, and union(map_ptr, range) and
2277 * padding between 'type' and union
2279 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2280 reg->type = SCALAR_VALUE;
2282 reg->ref_obj_id = 0;
2283 reg->var_off = tnum_unknown;
2285 reg->precise = false;
2286 __mark_reg_unbounded(reg);
2289 /* Mark a register as having a completely unknown (scalar) value,
2290 * initialize .precise as true when not bpf capable.
2292 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2293 struct bpf_reg_state *reg)
2295 __mark_reg_unknown_imprecise(reg);
2296 reg->precise = !env->bpf_capable;
2299 static void mark_reg_unknown(struct bpf_verifier_env *env,
2300 struct bpf_reg_state *regs, u32 regno)
2302 if (WARN_ON(regno >= MAX_BPF_REG)) {
2303 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2304 /* Something bad happened, let's kill all regs except FP */
2305 for (regno = 0; regno < BPF_REG_FP; regno++)
2306 __mark_reg_not_init(env, regs + regno);
2309 __mark_reg_unknown(env, regs + regno);
2312 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2313 struct bpf_reg_state *reg)
2315 __mark_reg_unknown(env, reg);
2316 reg->type = NOT_INIT;
2319 static void mark_reg_not_init(struct bpf_verifier_env *env,
2320 struct bpf_reg_state *regs, u32 regno)
2322 if (WARN_ON(regno >= MAX_BPF_REG)) {
2323 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2324 /* Something bad happened, let's kill all regs except FP */
2325 for (regno = 0; regno < BPF_REG_FP; regno++)
2326 __mark_reg_not_init(env, regs + regno);
2329 __mark_reg_not_init(env, regs + regno);
2332 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2333 struct bpf_reg_state *regs, u32 regno,
2334 enum bpf_reg_type reg_type,
2335 struct btf *btf, u32 btf_id,
2336 enum bpf_type_flag flag)
2338 if (reg_type == SCALAR_VALUE) {
2339 mark_reg_unknown(env, regs, regno);
2342 mark_reg_known_zero(env, regs, regno);
2343 regs[regno].type = PTR_TO_BTF_ID | flag;
2344 regs[regno].btf = btf;
2345 regs[regno].btf_id = btf_id;
2348 #define DEF_NOT_SUBREG (0)
2349 static void init_reg_state(struct bpf_verifier_env *env,
2350 struct bpf_func_state *state)
2352 struct bpf_reg_state *regs = state->regs;
2355 for (i = 0; i < MAX_BPF_REG; i++) {
2356 mark_reg_not_init(env, regs, i);
2357 regs[i].live = REG_LIVE_NONE;
2358 regs[i].parent = NULL;
2359 regs[i].subreg_def = DEF_NOT_SUBREG;
2363 regs[BPF_REG_FP].type = PTR_TO_STACK;
2364 mark_reg_known_zero(env, regs, BPF_REG_FP);
2365 regs[BPF_REG_FP].frameno = state->frameno;
2368 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2370 return (struct bpf_retval_range){ minval, maxval };
2373 #define BPF_MAIN_FUNC (-1)
2374 static void init_func_state(struct bpf_verifier_env *env,
2375 struct bpf_func_state *state,
2376 int callsite, int frameno, int subprogno)
2378 state->callsite = callsite;
2379 state->frameno = frameno;
2380 state->subprogno = subprogno;
2381 state->callback_ret_range = retval_range(0, 0);
2382 init_reg_state(env, state);
2383 mark_verifier_state_scratched(env);
2386 /* Similar to push_stack(), but for async callbacks */
2387 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2388 int insn_idx, int prev_insn_idx,
2391 struct bpf_verifier_stack_elem *elem;
2392 struct bpf_func_state *frame;
2394 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2398 elem->insn_idx = insn_idx;
2399 elem->prev_insn_idx = prev_insn_idx;
2400 elem->next = env->head;
2401 elem->log_pos = env->log.end_pos;
2404 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2406 "The sequence of %d jumps is too complex for async cb.\n",
2410 /* Unlike push_stack() do not copy_verifier_state().
2411 * The caller state doesn't matter.
2412 * This is async callback. It starts in a fresh stack.
2413 * Initialize it similar to do_check_common().
2415 elem->st.branches = 1;
2416 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2419 init_func_state(env, frame,
2420 BPF_MAIN_FUNC /* callsite */,
2421 0 /* frameno within this callchain */,
2422 subprog /* subprog number within this prog */);
2423 elem->st.frame[0] = frame;
2426 free_verifier_state(env->cur_state, true);
2427 env->cur_state = NULL;
2428 /* pop all elements and return */
2429 while (!pop_stack(env, NULL, NULL, false));
2435 SRC_OP, /* register is used as source operand */
2436 DST_OP, /* register is used as destination operand */
2437 DST_OP_NO_MARK /* same as above, check only, don't mark */
2440 static int cmp_subprogs(const void *a, const void *b)
2442 return ((struct bpf_subprog_info *)a)->start -
2443 ((struct bpf_subprog_info *)b)->start;
2446 static int find_subprog(struct bpf_verifier_env *env, int off)
2448 struct bpf_subprog_info *p;
2450 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2451 sizeof(env->subprog_info[0]), cmp_subprogs);
2454 return p - env->subprog_info;
2458 static int add_subprog(struct bpf_verifier_env *env, int off)
2460 int insn_cnt = env->prog->len;
2463 if (off >= insn_cnt || off < 0) {
2464 verbose(env, "call to invalid destination\n");
2467 ret = find_subprog(env, off);
2470 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2471 verbose(env, "too many subprograms\n");
2474 /* determine subprog starts. The end is one before the next starts */
2475 env->subprog_info[env->subprog_cnt++].start = off;
2476 sort(env->subprog_info, env->subprog_cnt,
2477 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2478 return env->subprog_cnt - 1;
2481 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2483 struct bpf_prog_aux *aux = env->prog->aux;
2484 struct btf *btf = aux->btf;
2485 const struct btf_type *t;
2486 u32 main_btf_id, id;
2490 /* Non-zero func_info_cnt implies valid btf */
2491 if (!aux->func_info_cnt)
2493 main_btf_id = aux->func_info[0].type_id;
2495 t = btf_type_by_id(btf, main_btf_id);
2497 verbose(env, "invalid btf id for main subprog in func_info\n");
2501 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2503 ret = PTR_ERR(name);
2504 /* If there is no tag present, there is no exception callback */
2507 else if (ret == -EEXIST)
2508 verbose(env, "multiple exception callback tags for main subprog\n");
2512 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2514 verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2518 t = btf_type_by_id(btf, id);
2519 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2520 verbose(env, "exception callback '%s' must have global linkage\n", name);
2524 for (i = 0; i < aux->func_info_cnt; i++) {
2525 if (aux->func_info[i].type_id != id)
2527 ret = aux->func_info[i].insn_off;
2528 /* Further func_info and subprog checks will also happen
2529 * later, so assume this is the right insn_off for now.
2532 verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2537 verbose(env, "exception callback type id not found in func_info\n");
2543 #define MAX_KFUNC_DESCS 256
2544 #define MAX_KFUNC_BTFS 256
2546 struct bpf_kfunc_desc {
2547 struct btf_func_model func_model;
2554 struct bpf_kfunc_btf {
2556 struct module *module;
2560 struct bpf_kfunc_desc_tab {
2561 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2562 * verification. JITs do lookups by bpf_insn, where func_id may not be
2563 * available, therefore at the end of verification do_misc_fixups()
2564 * sorts this by imm and offset.
2566 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2570 struct bpf_kfunc_btf_tab {
2571 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2575 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2577 const struct bpf_kfunc_desc *d0 = a;
2578 const struct bpf_kfunc_desc *d1 = b;
2580 /* func_id is not greater than BTF_MAX_TYPE */
2581 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2584 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2586 const struct bpf_kfunc_btf *d0 = a;
2587 const struct bpf_kfunc_btf *d1 = b;
2589 return d0->offset - d1->offset;
2592 static const struct bpf_kfunc_desc *
2593 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2595 struct bpf_kfunc_desc desc = {
2599 struct bpf_kfunc_desc_tab *tab;
2601 tab = prog->aux->kfunc_tab;
2602 return bsearch(&desc, tab->descs, tab->nr_descs,
2603 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2606 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2607 u16 btf_fd_idx, u8 **func_addr)
2609 const struct bpf_kfunc_desc *desc;
2611 desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2615 *func_addr = (u8 *)desc->addr;
2619 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2622 struct bpf_kfunc_btf kf_btf = { .offset = offset };
2623 struct bpf_kfunc_btf_tab *tab;
2624 struct bpf_kfunc_btf *b;
2629 tab = env->prog->aux->kfunc_btf_tab;
2630 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2631 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2633 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2634 verbose(env, "too many different module BTFs\n");
2635 return ERR_PTR(-E2BIG);
2638 if (bpfptr_is_null(env->fd_array)) {
2639 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2640 return ERR_PTR(-EPROTO);
2643 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2644 offset * sizeof(btf_fd),
2646 return ERR_PTR(-EFAULT);
2648 btf = btf_get_by_fd(btf_fd);
2650 verbose(env, "invalid module BTF fd specified\n");
2654 if (!btf_is_module(btf)) {
2655 verbose(env, "BTF fd for kfunc is not a module BTF\n");
2657 return ERR_PTR(-EINVAL);
2660 mod = btf_try_get_module(btf);
2663 return ERR_PTR(-ENXIO);
2666 b = &tab->descs[tab->nr_descs++];
2671 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2672 kfunc_btf_cmp_by_off, NULL);
2677 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2682 while (tab->nr_descs--) {
2683 module_put(tab->descs[tab->nr_descs].module);
2684 btf_put(tab->descs[tab->nr_descs].btf);
2689 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2693 /* In the future, this can be allowed to increase limit
2694 * of fd index into fd_array, interpreted as u16.
2696 verbose(env, "negative offset disallowed for kernel module function call\n");
2697 return ERR_PTR(-EINVAL);
2700 return __find_kfunc_desc_btf(env, offset);
2702 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2705 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2707 const struct btf_type *func, *func_proto;
2708 struct bpf_kfunc_btf_tab *btf_tab;
2709 struct bpf_kfunc_desc_tab *tab;
2710 struct bpf_prog_aux *prog_aux;
2711 struct bpf_kfunc_desc *desc;
2712 const char *func_name;
2713 struct btf *desc_btf;
2714 unsigned long call_imm;
2718 prog_aux = env->prog->aux;
2719 tab = prog_aux->kfunc_tab;
2720 btf_tab = prog_aux->kfunc_btf_tab;
2723 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2727 if (!env->prog->jit_requested) {
2728 verbose(env, "JIT is required for calling kernel function\n");
2732 if (!bpf_jit_supports_kfunc_call()) {
2733 verbose(env, "JIT does not support calling kernel function\n");
2737 if (!env->prog->gpl_compatible) {
2738 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2742 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2745 prog_aux->kfunc_tab = tab;
2748 /* func_id == 0 is always invalid, but instead of returning an error, be
2749 * conservative and wait until the code elimination pass before returning
2750 * error, so that invalid calls that get pruned out can be in BPF programs
2751 * loaded from userspace. It is also required that offset be untouched
2754 if (!func_id && !offset)
2757 if (!btf_tab && offset) {
2758 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2761 prog_aux->kfunc_btf_tab = btf_tab;
2764 desc_btf = find_kfunc_desc_btf(env, offset);
2765 if (IS_ERR(desc_btf)) {
2766 verbose(env, "failed to find BTF for kernel function\n");
2767 return PTR_ERR(desc_btf);
2770 if (find_kfunc_desc(env->prog, func_id, offset))
2773 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2774 verbose(env, "too many different kernel function calls\n");
2778 func = btf_type_by_id(desc_btf, func_id);
2779 if (!func || !btf_type_is_func(func)) {
2780 verbose(env, "kernel btf_id %u is not a function\n",
2784 func_proto = btf_type_by_id(desc_btf, func->type);
2785 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2786 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2791 func_name = btf_name_by_offset(desc_btf, func->name_off);
2792 addr = kallsyms_lookup_name(func_name);
2794 verbose(env, "cannot find address for kernel function %s\n",
2798 specialize_kfunc(env, func_id, offset, &addr);
2800 if (bpf_jit_supports_far_kfunc_call()) {
2803 call_imm = BPF_CALL_IMM(addr);
2804 /* Check whether the relative offset overflows desc->imm */
2805 if ((unsigned long)(s32)call_imm != call_imm) {
2806 verbose(env, "address of kernel function %s is out of range\n",
2812 if (bpf_dev_bound_kfunc_id(func_id)) {
2813 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2818 desc = &tab->descs[tab->nr_descs++];
2819 desc->func_id = func_id;
2820 desc->imm = call_imm;
2821 desc->offset = offset;
2823 err = btf_distill_func_proto(&env->log, desc_btf,
2824 func_proto, func_name,
2827 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2828 kfunc_desc_cmp_by_id_off, NULL);
2832 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2834 const struct bpf_kfunc_desc *d0 = a;
2835 const struct bpf_kfunc_desc *d1 = b;
2837 if (d0->imm != d1->imm)
2838 return d0->imm < d1->imm ? -1 : 1;
2839 if (d0->offset != d1->offset)
2840 return d0->offset < d1->offset ? -1 : 1;
2844 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2846 struct bpf_kfunc_desc_tab *tab;
2848 tab = prog->aux->kfunc_tab;
2852 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2853 kfunc_desc_cmp_by_imm_off, NULL);
2856 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2858 return !!prog->aux->kfunc_tab;
2861 const struct btf_func_model *
2862 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2863 const struct bpf_insn *insn)
2865 const struct bpf_kfunc_desc desc = {
2867 .offset = insn->off,
2869 const struct bpf_kfunc_desc *res;
2870 struct bpf_kfunc_desc_tab *tab;
2872 tab = prog->aux->kfunc_tab;
2873 res = bsearch(&desc, tab->descs, tab->nr_descs,
2874 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2876 return res ? &res->func_model : NULL;
2879 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2881 struct bpf_subprog_info *subprog = env->subprog_info;
2882 int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2883 struct bpf_insn *insn = env->prog->insnsi;
2885 /* Add entry function. */
2886 ret = add_subprog(env, 0);
2890 for (i = 0; i < insn_cnt; i++, insn++) {
2891 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2892 !bpf_pseudo_kfunc_call(insn))
2895 if (!env->bpf_capable) {
2896 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2900 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2901 ret = add_subprog(env, i + insn->imm + 1);
2903 ret = add_kfunc_call(env, insn->imm, insn->off);
2909 ret = bpf_find_exception_callback_insn_off(env);
2914 /* If ex_cb_insn > 0, this means that the main program has a subprog
2915 * marked using BTF decl tag to serve as the exception callback.
2918 ret = add_subprog(env, ex_cb_insn);
2921 for (i = 1; i < env->subprog_cnt; i++) {
2922 if (env->subprog_info[i].start != ex_cb_insn)
2924 env->exception_callback_subprog = i;
2925 mark_subprog_exc_cb(env, i);
2930 /* Add a fake 'exit' subprog which could simplify subprog iteration
2931 * logic. 'subprog_cnt' should not be increased.
2933 subprog[env->subprog_cnt].start = insn_cnt;
2935 if (env->log.level & BPF_LOG_LEVEL2)
2936 for (i = 0; i < env->subprog_cnt; i++)
2937 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2942 static int check_subprogs(struct bpf_verifier_env *env)
2944 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2945 struct bpf_subprog_info *subprog = env->subprog_info;
2946 struct bpf_insn *insn = env->prog->insnsi;
2947 int insn_cnt = env->prog->len;
2949 /* now check that all jumps are within the same subprog */
2950 subprog_start = subprog[cur_subprog].start;
2951 subprog_end = subprog[cur_subprog + 1].start;
2952 for (i = 0; i < insn_cnt; i++) {
2953 u8 code = insn[i].code;
2955 if (code == (BPF_JMP | BPF_CALL) &&
2956 insn[i].src_reg == 0 &&
2957 insn[i].imm == BPF_FUNC_tail_call)
2958 subprog[cur_subprog].has_tail_call = true;
2959 if (BPF_CLASS(code) == BPF_LD &&
2960 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2961 subprog[cur_subprog].has_ld_abs = true;
2962 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2964 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2966 if (code == (BPF_JMP32 | BPF_JA))
2967 off = i + insn[i].imm + 1;
2969 off = i + insn[i].off + 1;
2970 if (off < subprog_start || off >= subprog_end) {
2971 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2975 if (i == subprog_end - 1) {
2976 /* to avoid fall-through from one subprog into another
2977 * the last insn of the subprog should be either exit
2978 * or unconditional jump back or bpf_throw call
2980 if (code != (BPF_JMP | BPF_EXIT) &&
2981 code != (BPF_JMP32 | BPF_JA) &&
2982 code != (BPF_JMP | BPF_JA)) {
2983 verbose(env, "last insn is not an exit or jmp\n");
2986 subprog_start = subprog_end;
2988 if (cur_subprog < env->subprog_cnt)
2989 subprog_end = subprog[cur_subprog + 1].start;
2995 /* Parentage chain of this register (or stack slot) should take care of all
2996 * issues like callee-saved registers, stack slot allocation time, etc.
2998 static int mark_reg_read(struct bpf_verifier_env *env,
2999 const struct bpf_reg_state *state,
3000 struct bpf_reg_state *parent, u8 flag)
3002 bool writes = parent == state->parent; /* Observe write marks */
3006 /* if read wasn't screened by an earlier write ... */
3007 if (writes && state->live & REG_LIVE_WRITTEN)
3009 if (parent->live & REG_LIVE_DONE) {
3010 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3011 reg_type_str(env, parent->type),
3012 parent->var_off.value, parent->off);
3015 /* The first condition is more likely to be true than the
3016 * second, checked it first.
3018 if ((parent->live & REG_LIVE_READ) == flag ||
3019 parent->live & REG_LIVE_READ64)
3020 /* The parentage chain never changes and
3021 * this parent was already marked as LIVE_READ.
3022 * There is no need to keep walking the chain again and
3023 * keep re-marking all parents as LIVE_READ.
3024 * This case happens when the same register is read
3025 * multiple times without writes into it in-between.
3026 * Also, if parent has the stronger REG_LIVE_READ64 set,
3027 * then no need to set the weak REG_LIVE_READ32.
3030 /* ... then we depend on parent's value */
3031 parent->live |= flag;
3032 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3033 if (flag == REG_LIVE_READ64)
3034 parent->live &= ~REG_LIVE_READ32;
3036 parent = state->parent;
3041 if (env->longest_mark_read_walk < cnt)
3042 env->longest_mark_read_walk = cnt;
3046 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3048 struct bpf_func_state *state = func(env, reg);
3051 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
3052 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3055 if (reg->type == CONST_PTR_TO_DYNPTR)
3057 spi = dynptr_get_spi(env, reg);
3060 /* Caller ensures dynptr is valid and initialized, which means spi is in
3061 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3064 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3065 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3068 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3069 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3072 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3073 int spi, int nr_slots)
3075 struct bpf_func_state *state = func(env, reg);
3078 for (i = 0; i < nr_slots; i++) {
3079 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3081 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3085 mark_stack_slot_scratched(env, spi - i);
3091 /* This function is supposed to be used by the following 32-bit optimization
3092 * code only. It returns TRUE if the source or destination register operates
3093 * on 64-bit, otherwise return FALSE.
3095 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3096 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3101 class = BPF_CLASS(code);
3103 if (class == BPF_JMP) {
3104 /* BPF_EXIT for "main" will reach here. Return TRUE
3109 if (op == BPF_CALL) {
3110 /* BPF to BPF call will reach here because of marking
3111 * caller saved clobber with DST_OP_NO_MARK for which we
3112 * don't care the register def because they are anyway
3113 * marked as NOT_INIT already.
3115 if (insn->src_reg == BPF_PSEUDO_CALL)
3117 /* Helper call will reach here because of arg type
3118 * check, conservatively return TRUE.
3127 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3130 if (class == BPF_ALU64 || class == BPF_JMP ||
3131 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3134 if (class == BPF_ALU || class == BPF_JMP32)
3137 if (class == BPF_LDX) {
3139 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3140 /* LDX source must be ptr. */
3144 if (class == BPF_STX) {
3145 /* BPF_STX (including atomic variants) has multiple source
3146 * operands, one of which is a ptr. Check whether the caller is
3149 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3151 return BPF_SIZE(code) == BPF_DW;
3154 if (class == BPF_LD) {
3155 u8 mode = BPF_MODE(code);
3158 if (mode == BPF_IMM)
3161 /* Both LD_IND and LD_ABS return 32-bit data. */
3165 /* Implicit ctx ptr. */
3166 if (regno == BPF_REG_6)
3169 /* Explicit source could be any width. */
3173 if (class == BPF_ST)
3174 /* The only source register for BPF_ST is a ptr. */
3177 /* Conservatively return true at default. */
3181 /* Return the regno defined by the insn, or -1. */
3182 static int insn_def_regno(const struct bpf_insn *insn)
3184 switch (BPF_CLASS(insn->code)) {
3190 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3191 (insn->imm & BPF_FETCH)) {
3192 if (insn->imm == BPF_CMPXCHG)
3195 return insn->src_reg;
3200 return insn->dst_reg;
3204 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3205 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3207 int dst_reg = insn_def_regno(insn);
3212 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3215 static void mark_insn_zext(struct bpf_verifier_env *env,
3216 struct bpf_reg_state *reg)
3218 s32 def_idx = reg->subreg_def;
3220 if (def_idx == DEF_NOT_SUBREG)
3223 env->insn_aux_data[def_idx - 1].zext_dst = true;
3224 /* The dst will be zero extended, so won't be sub-register anymore. */
3225 reg->subreg_def = DEF_NOT_SUBREG;
3228 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3229 enum reg_arg_type t)
3231 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3232 struct bpf_reg_state *reg;
3235 if (regno >= MAX_BPF_REG) {
3236 verbose(env, "R%d is invalid\n", regno);
3240 mark_reg_scratched(env, regno);
3243 rw64 = is_reg64(env, insn, regno, reg, t);
3245 /* check whether register used as source operand can be read */
3246 if (reg->type == NOT_INIT) {
3247 verbose(env, "R%d !read_ok\n", regno);
3250 /* We don't need to worry about FP liveness because it's read-only */
3251 if (regno == BPF_REG_FP)
3255 mark_insn_zext(env, reg);
3257 return mark_reg_read(env, reg, reg->parent,
3258 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3260 /* check whether register used as dest operand can be written to */
3261 if (regno == BPF_REG_FP) {
3262 verbose(env, "frame pointer is read only\n");
3265 reg->live |= REG_LIVE_WRITTEN;
3266 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3268 mark_reg_unknown(env, regs, regno);
3273 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3274 enum reg_arg_type t)
3276 struct bpf_verifier_state *vstate = env->cur_state;
3277 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3279 return __check_reg_arg(env, state->regs, regno, t);
3282 static int insn_stack_access_flags(int frameno, int spi)
3284 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3287 static int insn_stack_access_spi(int insn_flags)
3289 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3292 static int insn_stack_access_frameno(int insn_flags)
3294 return insn_flags & INSN_F_FRAMENO_MASK;
3297 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3299 env->insn_aux_data[idx].jmp_point = true;
3302 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3304 return env->insn_aux_data[insn_idx].jmp_point;
3307 /* for any branch, call, exit record the history of jmps in the given state */
3308 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3311 u32 cnt = cur->jmp_history_cnt;
3312 struct bpf_jmp_history_entry *p;
3315 /* combine instruction flags if we already recorded this instruction */
3316 if (env->cur_hist_ent) {
3317 /* atomic instructions push insn_flags twice, for READ and
3318 * WRITE sides, but they should agree on stack slot
3320 WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
3321 (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3322 "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
3323 env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3324 env->cur_hist_ent->flags |= insn_flags;
3329 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3330 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3333 cur->jmp_history = p;
3335 p = &cur->jmp_history[cnt - 1];
3336 p->idx = env->insn_idx;
3337 p->prev_idx = env->prev_insn_idx;
3338 p->flags = insn_flags;
3339 cur->jmp_history_cnt = cnt;
3340 env->cur_hist_ent = p;
3345 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3346 u32 hist_end, int insn_idx)
3348 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3349 return &st->jmp_history[hist_end - 1];
3353 /* Backtrack one insn at a time. If idx is not at the top of recorded
3354 * history then previous instruction came from straight line execution.
3355 * Return -ENOENT if we exhausted all instructions within given state.
3357 * It's legal to have a bit of a looping with the same starting and ending
3358 * insn index within the same state, e.g.: 3->4->5->3, so just because current
3359 * instruction index is the same as state's first_idx doesn't mean we are
3360 * done. If there is still some jump history left, we should keep going. We
3361 * need to take into account that we might have a jump history between given
3362 * state's parent and itself, due to checkpointing. In this case, we'll have
3363 * history entry recording a jump from last instruction of parent state and
3364 * first instruction of given state.
3366 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3371 if (i == st->first_insn_idx) {
3374 if (cnt == 1 && st->jmp_history[0].idx == i)
3378 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3379 i = st->jmp_history[cnt - 1].prev_idx;
3387 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3389 const struct btf_type *func;
3390 struct btf *desc_btf;
3392 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3395 desc_btf = find_kfunc_desc_btf(data, insn->off);
3396 if (IS_ERR(desc_btf))
3399 func = btf_type_by_id(desc_btf, insn->imm);
3400 return btf_name_by_offset(desc_btf, func->name_off);
3403 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3408 static inline void bt_reset(struct backtrack_state *bt)
3410 struct bpf_verifier_env *env = bt->env;
3412 memset(bt, 0, sizeof(*bt));
3416 static inline u32 bt_empty(struct backtrack_state *bt)
3421 for (i = 0; i <= bt->frame; i++)
3422 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3427 static inline int bt_subprog_enter(struct backtrack_state *bt)
3429 if (bt->frame == MAX_CALL_FRAMES - 1) {
3430 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3431 WARN_ONCE(1, "verifier backtracking bug");
3438 static inline int bt_subprog_exit(struct backtrack_state *bt)
3440 if (bt->frame == 0) {
3441 verbose(bt->env, "BUG subprog exit from frame 0\n");
3442 WARN_ONCE(1, "verifier backtracking bug");
3449 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3451 bt->reg_masks[frame] |= 1 << reg;
3454 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3456 bt->reg_masks[frame] &= ~(1 << reg);
3459 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3461 bt_set_frame_reg(bt, bt->frame, reg);
3464 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3466 bt_clear_frame_reg(bt, bt->frame, reg);
3469 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3471 bt->stack_masks[frame] |= 1ull << slot;
3474 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3476 bt->stack_masks[frame] &= ~(1ull << slot);
3479 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3481 return bt->reg_masks[frame];
3484 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3486 return bt->reg_masks[bt->frame];
3489 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3491 return bt->stack_masks[frame];
3494 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3496 return bt->stack_masks[bt->frame];
3499 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3501 return bt->reg_masks[bt->frame] & (1 << reg);
3504 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
3506 return bt->stack_masks[frame] & (1ull << slot);
3509 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3510 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3512 DECLARE_BITMAP(mask, 64);
3518 bitmap_from_u64(mask, reg_mask);
3519 for_each_set_bit(i, mask, 32) {
3520 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3528 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3529 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3531 DECLARE_BITMAP(mask, 64);
3537 bitmap_from_u64(mask, stack_mask);
3538 for_each_set_bit(i, mask, 64) {
3539 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3548 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3550 /* For given verifier state backtrack_insn() is called from the last insn to
3551 * the first insn. Its purpose is to compute a bitmask of registers and
3552 * stack slots that needs precision in the parent verifier state.
3554 * @idx is an index of the instruction we are currently processing;
3555 * @subseq_idx is an index of the subsequent instruction that:
3556 * - *would be* executed next, if jump history is viewed in forward order;
3557 * - *was* processed previously during backtracking.
3559 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3560 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
3562 const struct bpf_insn_cbs cbs = {
3563 .cb_call = disasm_kfunc_name,
3564 .cb_print = verbose,
3565 .private_data = env,
3567 struct bpf_insn *insn = env->prog->insnsi + idx;
3568 u8 class = BPF_CLASS(insn->code);
3569 u8 opcode = BPF_OP(insn->code);
3570 u8 mode = BPF_MODE(insn->code);
3571 u32 dreg = insn->dst_reg;
3572 u32 sreg = insn->src_reg;
3575 if (insn->code == 0)
3577 if (env->log.level & BPF_LOG_LEVEL2) {
3578 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3579 verbose(env, "mark_precise: frame%d: regs=%s ",
3580 bt->frame, env->tmp_str_buf);
3581 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3582 verbose(env, "stack=%s before ", env->tmp_str_buf);
3583 verbose(env, "%d: ", idx);
3584 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3587 if (class == BPF_ALU || class == BPF_ALU64) {
3588 if (!bt_is_reg_set(bt, dreg))
3590 if (opcode == BPF_END || opcode == BPF_NEG) {
3591 /* sreg is reserved and unused
3592 * dreg still need precision before this insn
3595 } else if (opcode == BPF_MOV) {
3596 if (BPF_SRC(insn->code) == BPF_X) {
3597 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3598 * dreg needs precision after this insn
3599 * sreg needs precision before this insn
3601 bt_clear_reg(bt, dreg);
3602 bt_set_reg(bt, sreg);
3605 * dreg needs precision after this insn.
3606 * Corresponding register is already marked
3607 * as precise=true in this verifier state.
3608 * No further markings in parent are necessary
3610 bt_clear_reg(bt, dreg);
3613 if (BPF_SRC(insn->code) == BPF_X) {
3615 * both dreg and sreg need precision
3618 bt_set_reg(bt, sreg);
3620 * dreg still needs precision before this insn
3623 } else if (class == BPF_LDX) {
3624 if (!bt_is_reg_set(bt, dreg))
3626 bt_clear_reg(bt, dreg);
3628 /* scalars can only be spilled into stack w/o losing precision.
3629 * Load from any other memory can be zero extended.
3630 * The desire to keep that precision is already indicated
3631 * by 'precise' mark in corresponding register of this state.
3632 * No further tracking necessary.
3634 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3636 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3637 * that [fp - off] slot contains scalar that needs to be
3638 * tracked with precision
3640 spi = insn_stack_access_spi(hist->flags);
3641 fr = insn_stack_access_frameno(hist->flags);
3642 bt_set_frame_slot(bt, fr, spi);
3643 } else if (class == BPF_STX || class == BPF_ST) {
3644 if (bt_is_reg_set(bt, dreg))
3645 /* stx & st shouldn't be using _scalar_ dst_reg
3646 * to access memory. It means backtracking
3647 * encountered a case of pointer subtraction.
3650 /* scalars can only be spilled into stack */
3651 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3653 spi = insn_stack_access_spi(hist->flags);
3654 fr = insn_stack_access_frameno(hist->flags);
3655 if (!bt_is_frame_slot_set(bt, fr, spi))
3657 bt_clear_frame_slot(bt, fr, spi);
3658 if (class == BPF_STX)
3659 bt_set_reg(bt, sreg);
3660 } else if (class == BPF_JMP || class == BPF_JMP32) {
3661 if (bpf_pseudo_call(insn)) {
3662 int subprog_insn_idx, subprog;
3664 subprog_insn_idx = idx + insn->imm + 1;
3665 subprog = find_subprog(env, subprog_insn_idx);
3669 if (subprog_is_global(env, subprog)) {
3670 /* check that jump history doesn't have any
3671 * extra instructions from subprog; the next
3672 * instruction after call to global subprog
3673 * should be literally next instruction in
3676 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3677 /* r1-r5 are invalidated after subprog call,
3678 * so for global func call it shouldn't be set
3681 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3682 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3683 WARN_ONCE(1, "verifier backtracking bug");
3686 /* global subprog always sets R0 */
3687 bt_clear_reg(bt, BPF_REG_0);
3690 /* static subprog call instruction, which
3691 * means that we are exiting current subprog,
3692 * so only r1-r5 could be still requested as
3693 * precise, r0 and r6-r10 or any stack slot in
3694 * the current frame should be zero by now
3696 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3697 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3698 WARN_ONCE(1, "verifier backtracking bug");
3701 /* we are now tracking register spills correctly,
3702 * so any instance of leftover slots is a bug
3704 if (bt_stack_mask(bt) != 0) {
3705 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3706 WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
3709 /* propagate r1-r5 to the caller */
3710 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3711 if (bt_is_reg_set(bt, i)) {
3712 bt_clear_reg(bt, i);
3713 bt_set_frame_reg(bt, bt->frame - 1, i);
3716 if (bt_subprog_exit(bt))
3720 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3721 /* exit from callback subprog to callback-calling helper or
3722 * kfunc call. Use idx/subseq_idx check to discern it from
3723 * straight line code backtracking.
3724 * Unlike the subprog call handling above, we shouldn't
3725 * propagate precision of r1-r5 (if any requested), as they are
3726 * not actually arguments passed directly to callback subprogs
3728 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3729 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3730 WARN_ONCE(1, "verifier backtracking bug");
3733 if (bt_stack_mask(bt) != 0) {
3734 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3735 WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
3738 /* clear r1-r5 in callback subprog's mask */
3739 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3740 bt_clear_reg(bt, i);
3741 if (bt_subprog_exit(bt))
3744 } else if (opcode == BPF_CALL) {
3745 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3746 * catch this error later. Make backtracking conservative
3749 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3751 /* regular helper call sets R0 */
3752 bt_clear_reg(bt, BPF_REG_0);
3753 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3754 /* if backtracing was looking for registers R1-R5
3755 * they should have been found already.
3757 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3758 WARN_ONCE(1, "verifier backtracking bug");
3761 } else if (opcode == BPF_EXIT) {
3764 /* Backtracking to a nested function call, 'idx' is a part of
3765 * the inner frame 'subseq_idx' is a part of the outer frame.
3766 * In case of a regular function call, instructions giving
3767 * precision to registers R1-R5 should have been found already.
3768 * In case of a callback, it is ok to have R1-R5 marked for
3769 * backtracking, as these registers are set by the function
3770 * invoking callback.
3772 if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3773 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3774 bt_clear_reg(bt, i);
3775 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3776 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3777 WARN_ONCE(1, "verifier backtracking bug");
3781 /* BPF_EXIT in subprog or callback always returns
3782 * right after the call instruction, so by checking
3783 * whether the instruction at subseq_idx-1 is subprog
3784 * call or not we can distinguish actual exit from
3785 * *subprog* from exit from *callback*. In the former
3786 * case, we need to propagate r0 precision, if
3787 * necessary. In the former we never do that.
3789 r0_precise = subseq_idx - 1 >= 0 &&
3790 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3791 bt_is_reg_set(bt, BPF_REG_0);
3793 bt_clear_reg(bt, BPF_REG_0);
3794 if (bt_subprog_enter(bt))
3798 bt_set_reg(bt, BPF_REG_0);
3799 /* r6-r9 and stack slots will stay set in caller frame
3800 * bitmasks until we return back from callee(s)
3803 } else if (BPF_SRC(insn->code) == BPF_X) {
3804 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3807 * Both dreg and sreg need precision before
3808 * this insn. If only sreg was marked precise
3809 * before it would be equally necessary to
3810 * propagate it to dreg.
3812 bt_set_reg(bt, dreg);
3813 bt_set_reg(bt, sreg);
3814 /* else dreg <cond> K
3815 * Only dreg still needs precision before
3816 * this insn, so for the K-based conditional
3817 * there is nothing new to be marked.
3820 } else if (class == BPF_LD) {
3821 if (!bt_is_reg_set(bt, dreg))
3823 bt_clear_reg(bt, dreg);
3824 /* It's ld_imm64 or ld_abs or ld_ind.
3825 * For ld_imm64 no further tracking of precision
3826 * into parent is necessary
3828 if (mode == BPF_IND || mode == BPF_ABS)
3829 /* to be analyzed */
3835 /* the scalar precision tracking algorithm:
3836 * . at the start all registers have precise=false.
3837 * . scalar ranges are tracked as normal through alu and jmp insns.
3838 * . once precise value of the scalar register is used in:
3839 * . ptr + scalar alu
3840 * . if (scalar cond K|scalar)
3841 * . helper_call(.., scalar, ...) where ARG_CONST is expected
3842 * backtrack through the verifier states and mark all registers and
3843 * stack slots with spilled constants that these scalar regisers
3844 * should be precise.
3845 * . during state pruning two registers (or spilled stack slots)
3846 * are equivalent if both are not precise.
3848 * Note the verifier cannot simply walk register parentage chain,
3849 * since many different registers and stack slots could have been
3850 * used to compute single precise scalar.
3852 * The approach of starting with precise=true for all registers and then
3853 * backtrack to mark a register as not precise when the verifier detects
3854 * that program doesn't care about specific value (e.g., when helper
3855 * takes register as ARG_ANYTHING parameter) is not safe.
3857 * It's ok to walk single parentage chain of the verifier states.
3858 * It's possible that this backtracking will go all the way till 1st insn.
3859 * All other branches will be explored for needing precision later.
3861 * The backtracking needs to deal with cases like:
3862 * R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
3865 * if r5 > 0x79f goto pc+7
3866 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3869 * call bpf_perf_event_output#25
3870 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3874 * call foo // uses callee's r6 inside to compute r0
3878 * to track above reg_mask/stack_mask needs to be independent for each frame.
3880 * Also if parent's curframe > frame where backtracking started,
3881 * the verifier need to mark registers in both frames, otherwise callees
3882 * may incorrectly prune callers. This is similar to
3883 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3885 * For now backtracking falls back into conservative marking.
3887 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3888 struct bpf_verifier_state *st)
3890 struct bpf_func_state *func;
3891 struct bpf_reg_state *reg;
3894 if (env->log.level & BPF_LOG_LEVEL2) {
3895 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3899 /* big hammer: mark all scalars precise in this path.
3900 * pop_stack may still get !precise scalars.
3901 * We also skip current state and go straight to first parent state,
3902 * because precision markings in current non-checkpointed state are
3903 * not needed. See why in the comment in __mark_chain_precision below.
3905 for (st = st->parent; st; st = st->parent) {
3906 for (i = 0; i <= st->curframe; i++) {
3907 func = st->frame[i];
3908 for (j = 0; j < BPF_REG_FP; j++) {
3909 reg = &func->regs[j];
3910 if (reg->type != SCALAR_VALUE || reg->precise)
3912 reg->precise = true;
3913 if (env->log.level & BPF_LOG_LEVEL2) {
3914 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3918 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3919 if (!is_spilled_reg(&func->stack[j]))
3921 reg = &func->stack[j].spilled_ptr;
3922 if (reg->type != SCALAR_VALUE || reg->precise)
3924 reg->precise = true;
3925 if (env->log.level & BPF_LOG_LEVEL2) {
3926 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3934 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3936 struct bpf_func_state *func;
3937 struct bpf_reg_state *reg;
3940 for (i = 0; i <= st->curframe; i++) {
3941 func = st->frame[i];
3942 for (j = 0; j < BPF_REG_FP; j++) {
3943 reg = &func->regs[j];
3944 if (reg->type != SCALAR_VALUE)
3946 reg->precise = false;
3948 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3949 if (!is_spilled_reg(&func->stack[j]))
3951 reg = &func->stack[j].spilled_ptr;
3952 if (reg->type != SCALAR_VALUE)
3954 reg->precise = false;
3959 static bool idset_contains(struct bpf_idset *s, u32 id)
3963 for (i = 0; i < s->count; ++i)
3964 if (s->ids[i] == id)
3970 static int idset_push(struct bpf_idset *s, u32 id)
3972 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3974 s->ids[s->count++] = id;
3978 static void idset_reset(struct bpf_idset *s)
3983 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3984 * Mark all registers with these IDs as precise.
3986 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3988 struct bpf_idset *precise_ids = &env->idset_scratch;
3989 struct backtrack_state *bt = &env->bt;
3990 struct bpf_func_state *func;
3991 struct bpf_reg_state *reg;
3992 DECLARE_BITMAP(mask, 64);
3995 idset_reset(precise_ids);
3997 for (fr = bt->frame; fr >= 0; fr--) {
3998 func = st->frame[fr];
4000 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4001 for_each_set_bit(i, mask, 32) {
4002 reg = &func->regs[i];
4003 if (!reg->id || reg->type != SCALAR_VALUE)
4005 if (idset_push(precise_ids, reg->id))
4009 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4010 for_each_set_bit(i, mask, 64) {
4011 if (i >= func->allocated_stack / BPF_REG_SIZE)
4013 if (!is_spilled_scalar_reg(&func->stack[i]))
4015 reg = &func->stack[i].spilled_ptr;
4018 if (idset_push(precise_ids, reg->id))
4023 for (fr = 0; fr <= st->curframe; ++fr) {
4024 func = st->frame[fr];
4026 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4027 reg = &func->regs[i];
4030 if (!idset_contains(precise_ids, reg->id))
4032 bt_set_frame_reg(bt, fr, i);
4034 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4035 if (!is_spilled_scalar_reg(&func->stack[i]))
4037 reg = &func->stack[i].spilled_ptr;
4040 if (!idset_contains(precise_ids, reg->id))
4042 bt_set_frame_slot(bt, fr, i);
4050 * __mark_chain_precision() backtracks BPF program instruction sequence and
4051 * chain of verifier states making sure that register *regno* (if regno >= 0)
4052 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4053 * SCALARS, as well as any other registers and slots that contribute to
4054 * a tracked state of given registers/stack slots, depending on specific BPF
4055 * assembly instructions (see backtrack_insns() for exact instruction handling
4056 * logic). This backtracking relies on recorded jmp_history and is able to
4057 * traverse entire chain of parent states. This process ends only when all the
4058 * necessary registers/slots and their transitive dependencies are marked as
4061 * One important and subtle aspect is that precise marks *do not matter* in
4062 * the currently verified state (current state). It is important to understand
4063 * why this is the case.
4065 * First, note that current state is the state that is not yet "checkpointed",
4066 * i.e., it is not yet put into env->explored_states, and it has no children
4067 * states as well. It's ephemeral, and can end up either a) being discarded if
4068 * compatible explored state is found at some point or BPF_EXIT instruction is
4069 * reached or b) checkpointed and put into env->explored_states, branching out
4070 * into one or more children states.
4072 * In the former case, precise markings in current state are completely
4073 * ignored by state comparison code (see regsafe() for details). Only
4074 * checkpointed ("old") state precise markings are important, and if old
4075 * state's register/slot is precise, regsafe() assumes current state's
4076 * register/slot as precise and checks value ranges exactly and precisely. If
4077 * states turn out to be compatible, current state's necessary precise
4078 * markings and any required parent states' precise markings are enforced
4079 * after the fact with propagate_precision() logic, after the fact. But it's
4080 * important to realize that in this case, even after marking current state
4081 * registers/slots as precise, we immediately discard current state. So what
4082 * actually matters is any of the precise markings propagated into current
4083 * state's parent states, which are always checkpointed (due to b) case above).
4084 * As such, for scenario a) it doesn't matter if current state has precise
4085 * markings set or not.
4087 * Now, for the scenario b), checkpointing and forking into child(ren)
4088 * state(s). Note that before current state gets to checkpointing step, any
4089 * processed instruction always assumes precise SCALAR register/slot
4090 * knowledge: if precise value or range is useful to prune jump branch, BPF
4091 * verifier takes this opportunity enthusiastically. Similarly, when
4092 * register's value is used to calculate offset or memory address, exact
4093 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4094 * what we mentioned above about state comparison ignoring precise markings
4095 * during state comparison, BPF verifier ignores and also assumes precise
4096 * markings *at will* during instruction verification process. But as verifier
4097 * assumes precision, it also propagates any precision dependencies across
4098 * parent states, which are not yet finalized, so can be further restricted
4099 * based on new knowledge gained from restrictions enforced by their children
4100 * states. This is so that once those parent states are finalized, i.e., when
4101 * they have no more active children state, state comparison logic in
4102 * is_state_visited() would enforce strict and precise SCALAR ranges, if
4103 * required for correctness.
4105 * To build a bit more intuition, note also that once a state is checkpointed,
4106 * the path we took to get to that state is not important. This is crucial
4107 * property for state pruning. When state is checkpointed and finalized at
4108 * some instruction index, it can be correctly and safely used to "short
4109 * circuit" any *compatible* state that reaches exactly the same instruction
4110 * index. I.e., if we jumped to that instruction from a completely different
4111 * code path than original finalized state was derived from, it doesn't
4112 * matter, current state can be discarded because from that instruction
4113 * forward having a compatible state will ensure we will safely reach the
4114 * exit. States describe preconditions for further exploration, but completely
4115 * forget the history of how we got here.
4117 * This also means that even if we needed precise SCALAR range to get to
4118 * finalized state, but from that point forward *that same* SCALAR register is
4119 * never used in a precise context (i.e., it's precise value is not needed for
4120 * correctness), it's correct and safe to mark such register as "imprecise"
4121 * (i.e., precise marking set to false). This is what we rely on when we do
4122 * not set precise marking in current state. If no child state requires
4123 * precision for any given SCALAR register, it's safe to dictate that it can
4124 * be imprecise. If any child state does require this register to be precise,
4125 * we'll mark it precise later retroactively during precise markings
4126 * propagation from child state to parent states.
4128 * Skipping precise marking setting in current state is a mild version of
4129 * relying on the above observation. But we can utilize this property even
4130 * more aggressively by proactively forgetting any precise marking in the
4131 * current state (which we inherited from the parent state), right before we
4132 * checkpoint it and branch off into new child state. This is done by
4133 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4134 * finalized states which help in short circuiting more future states.
4136 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4138 struct backtrack_state *bt = &env->bt;
4139 struct bpf_verifier_state *st = env->cur_state;
4140 int first_idx = st->first_insn_idx;
4141 int last_idx = env->insn_idx;
4142 int subseq_idx = -1;
4143 struct bpf_func_state *func;
4144 struct bpf_reg_state *reg;
4145 bool skip_first = true;
4148 if (!env->bpf_capable)
4151 /* set frame number from which we are starting to backtrack */
4152 bt_init(bt, env->cur_state->curframe);
4154 /* Do sanity checks against current state of register and/or stack
4155 * slot, but don't set precise flag in current state, as precision
4156 * tracking in the current state is unnecessary.
4158 func = st->frame[bt->frame];
4160 reg = &func->regs[regno];
4161 if (reg->type != SCALAR_VALUE) {
4162 WARN_ONCE(1, "backtracing misuse");
4165 bt_set_reg(bt, regno);
4172 DECLARE_BITMAP(mask, 64);
4173 u32 history = st->jmp_history_cnt;
4174 struct bpf_jmp_history_entry *hist;
4176 if (env->log.level & BPF_LOG_LEVEL2) {
4177 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4178 bt->frame, last_idx, first_idx, subseq_idx);
4181 /* If some register with scalar ID is marked as precise,
4182 * make sure that all registers sharing this ID are also precise.
4183 * This is needed to estimate effect of find_equal_scalars().
4184 * Do this at the last instruction of each state,
4185 * bpf_reg_state::id fields are valid for these instructions.
4187 * Allows to track precision in situation like below:
4189 * r2 = unknown value
4193 * r1 = r2 // r1 and r2 now share the same ID
4195 * --- state #1 {r1.id = A, r2.id = A} ---
4197 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4199 * --- state #2 {r1.id = A, r2.id = A} ---
4201 * r3 += r1 // need to mark both r1 and r2
4203 if (mark_precise_scalar_ids(env, st))
4207 /* we are at the entry into subprog, which
4208 * is expected for global funcs, but only if
4209 * requested precise registers are R1-R5
4210 * (which are global func's input arguments)
4212 if (st->curframe == 0 &&
4213 st->frame[0]->subprogno > 0 &&
4214 st->frame[0]->callsite == BPF_MAIN_FUNC &&
4215 bt_stack_mask(bt) == 0 &&
4216 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4217 bitmap_from_u64(mask, bt_reg_mask(bt));
4218 for_each_set_bit(i, mask, 32) {
4219 reg = &st->frame[0]->regs[i];
4220 bt_clear_reg(bt, i);
4221 if (reg->type == SCALAR_VALUE)
4222 reg->precise = true;
4227 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4228 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4229 WARN_ONCE(1, "verifier backtracking bug");
4233 for (i = last_idx;;) {
4238 hist = get_jmp_hist_entry(st, history, i);
4239 err = backtrack_insn(env, i, subseq_idx, hist, bt);
4241 if (err == -ENOTSUPP) {
4242 mark_all_scalars_precise(env, env->cur_state);
4249 /* Found assignment(s) into tracked register in this state.
4250 * Since this state is already marked, just return.
4251 * Nothing to be tracked further in the parent state.
4255 i = get_prev_insn_idx(st, i, &history);
4258 if (i >= env->prog->len) {
4259 /* This can happen if backtracking reached insn 0
4260 * and there are still reg_mask or stack_mask
4262 * It means the backtracking missed the spot where
4263 * particular register was initialized with a constant.
4265 verbose(env, "BUG backtracking idx %d\n", i);
4266 WARN_ONCE(1, "verifier backtracking bug");
4274 for (fr = bt->frame; fr >= 0; fr--) {
4275 func = st->frame[fr];
4276 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4277 for_each_set_bit(i, mask, 32) {
4278 reg = &func->regs[i];
4279 if (reg->type != SCALAR_VALUE) {
4280 bt_clear_frame_reg(bt, fr, i);
4284 bt_clear_frame_reg(bt, fr, i);
4286 reg->precise = true;
4289 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4290 for_each_set_bit(i, mask, 64) {
4291 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4292 verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
4293 i, func->allocated_stack / BPF_REG_SIZE);
4294 WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
4298 if (!is_spilled_scalar_reg(&func->stack[i])) {
4299 bt_clear_frame_slot(bt, fr, i);
4302 reg = &func->stack[i].spilled_ptr;
4304 bt_clear_frame_slot(bt, fr, i);
4306 reg->precise = true;
4308 if (env->log.level & BPF_LOG_LEVEL2) {
4309 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4310 bt_frame_reg_mask(bt, fr));
4311 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4312 fr, env->tmp_str_buf);
4313 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4314 bt_frame_stack_mask(bt, fr));
4315 verbose(env, "stack=%s: ", env->tmp_str_buf);
4316 print_verifier_state(env, func, true);
4323 subseq_idx = first_idx;
4324 last_idx = st->last_insn_idx;
4325 first_idx = st->first_insn_idx;
4328 /* if we still have requested precise regs or slots, we missed
4329 * something (e.g., stack access through non-r10 register), so
4330 * fallback to marking all precise
4332 if (!bt_empty(bt)) {
4333 mark_all_scalars_precise(env, env->cur_state);
4340 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4342 return __mark_chain_precision(env, regno);
4345 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4346 * desired reg and stack masks across all relevant frames
4348 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4350 return __mark_chain_precision(env, -1);
4353 static bool is_spillable_regtype(enum bpf_reg_type type)
4355 switch (base_type(type)) {
4356 case PTR_TO_MAP_VALUE:
4360 case PTR_TO_PACKET_META:
4361 case PTR_TO_PACKET_END:
4362 case PTR_TO_FLOW_KEYS:
4363 case CONST_PTR_TO_MAP:
4365 case PTR_TO_SOCK_COMMON:
4366 case PTR_TO_TCP_SOCK:
4367 case PTR_TO_XDP_SOCK:
4372 case PTR_TO_MAP_KEY:
4379 /* Does this register contain a constant zero? */
4380 static bool register_is_null(struct bpf_reg_state *reg)
4382 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4385 /* check if register is a constant scalar value */
4386 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4388 return reg->type == SCALAR_VALUE &&
4389 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4392 /* assuming is_reg_const() is true, return constant value of a register */
4393 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4395 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4398 static bool __is_pointer_value(bool allow_ptr_leaks,
4399 const struct bpf_reg_state *reg)
4401 if (allow_ptr_leaks)
4404 return reg->type != SCALAR_VALUE;
4407 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4408 struct bpf_reg_state *src_reg)
4410 if (src_reg->type == SCALAR_VALUE && !src_reg->id &&
4411 !tnum_is_const(src_reg->var_off))
4412 /* Ensure that src_reg has a valid ID that will be copied to
4413 * dst_reg and then will be used by find_equal_scalars() to
4414 * propagate min/max range.
4416 src_reg->id = ++env->id_gen;
4419 /* Copy src state preserving dst->parent and dst->live fields */
4420 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4422 struct bpf_reg_state *parent = dst->parent;
4423 enum bpf_reg_liveness live = dst->live;
4426 dst->parent = parent;
4430 static void save_register_state(struct bpf_verifier_env *env,
4431 struct bpf_func_state *state,
4432 int spi, struct bpf_reg_state *reg,
4437 copy_register_state(&state->stack[spi].spilled_ptr, reg);
4438 if (size == BPF_REG_SIZE)
4439 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4441 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4442 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4444 /* size < 8 bytes spill */
4446 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4449 static bool is_bpf_st_mem(struct bpf_insn *insn)
4451 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4454 static int get_reg_width(struct bpf_reg_state *reg)
4456 return fls64(reg->umax_value);
4459 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4460 * stack boundary and alignment are checked in check_mem_access()
4462 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4463 /* stack frame we're writing to */
4464 struct bpf_func_state *state,
4465 int off, int size, int value_regno,
4468 struct bpf_func_state *cur; /* state of the current function */
4469 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4470 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4471 struct bpf_reg_state *reg = NULL;
4472 int insn_flags = insn_stack_access_flags(state->frameno, spi);
4474 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4475 * so it's aligned access and [off, off + size) are within stack limits
4477 if (!env->allow_ptr_leaks &&
4478 is_spilled_reg(&state->stack[spi]) &&
4479 size != BPF_REG_SIZE) {
4480 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4484 cur = env->cur_state->frame[env->cur_state->curframe];
4485 if (value_regno >= 0)
4486 reg = &cur->regs[value_regno];
4487 if (!env->bypass_spec_v4) {
4488 bool sanitize = reg && is_spillable_regtype(reg->type);
4490 for (i = 0; i < size; i++) {
4491 u8 type = state->stack[spi].slot_type[i];
4493 if (type != STACK_MISC && type != STACK_ZERO) {
4500 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4503 err = destroy_if_dynptr_stack_slot(env, state, spi);
4507 mark_stack_slot_scratched(env, spi);
4508 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
4509 bool reg_value_fits;
4511 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
4512 /* Make sure that reg had an ID to build a relation on spill. */
4514 assign_scalar_id_before_mov(env, reg);
4515 save_register_state(env, state, spi, reg, size);
4516 /* Break the relation on a narrowing spill. */
4517 if (!reg_value_fits)
4518 state->stack[spi].spilled_ptr.id = 0;
4519 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4521 struct bpf_reg_state fake_reg = {};
4523 __mark_reg_known(&fake_reg, insn->imm);
4524 fake_reg.type = SCALAR_VALUE;
4525 save_register_state(env, state, spi, &fake_reg, size);
4526 } else if (reg && is_spillable_regtype(reg->type)) {
4527 /* register containing pointer is being spilled into stack */
4528 if (size != BPF_REG_SIZE) {
4529 verbose_linfo(env, insn_idx, "; ");
4530 verbose(env, "invalid size of register spill\n");
4533 if (state != cur && reg->type == PTR_TO_STACK) {
4534 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4537 save_register_state(env, state, spi, reg, size);
4539 u8 type = STACK_MISC;
4541 /* regular write of data into stack destroys any spilled ptr */
4542 state->stack[spi].spilled_ptr.type = NOT_INIT;
4543 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4544 if (is_stack_slot_special(&state->stack[spi]))
4545 for (i = 0; i < BPF_REG_SIZE; i++)
4546 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4548 /* only mark the slot as written if all 8 bytes were written
4549 * otherwise read propagation may incorrectly stop too soon
4550 * when stack slots are partially written.
4551 * This heuristic means that read propagation will be
4552 * conservative, since it will add reg_live_read marks
4553 * to stack slots all the way to first state when programs
4554 * writes+reads less than 8 bytes
4556 if (size == BPF_REG_SIZE)
4557 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4559 /* when we zero initialize stack slots mark them as such */
4560 if ((reg && register_is_null(reg)) ||
4561 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4562 /* STACK_ZERO case happened because register spill
4563 * wasn't properly aligned at the stack slot boundary,
4564 * so it's not a register spill anymore; force
4565 * originating register to be precise to make
4566 * STACK_ZERO correct for subsequent states
4568 err = mark_chain_precision(env, value_regno);
4574 /* Mark slots affected by this stack write. */
4575 for (i = 0; i < size; i++)
4576 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
4577 insn_flags = 0; /* not a register spill */
4581 return push_jmp_history(env, env->cur_state, insn_flags);
4585 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4586 * known to contain a variable offset.
4587 * This function checks whether the write is permitted and conservatively
4588 * tracks the effects of the write, considering that each stack slot in the
4589 * dynamic range is potentially written to.
4591 * 'off' includes 'regno->off'.
4592 * 'value_regno' can be -1, meaning that an unknown value is being written to
4595 * Spilled pointers in range are not marked as written because we don't know
4596 * what's going to be actually written. This means that read propagation for
4597 * future reads cannot be terminated by this write.
4599 * For privileged programs, uninitialized stack slots are considered
4600 * initialized by this write (even though we don't know exactly what offsets
4601 * are going to be written to). The idea is that we don't want the verifier to
4602 * reject future reads that access slots written to through variable offsets.
4604 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4605 /* func where register points to */
4606 struct bpf_func_state *state,
4607 int ptr_regno, int off, int size,
4608 int value_regno, int insn_idx)
4610 struct bpf_func_state *cur; /* state of the current function */
4611 int min_off, max_off;
4613 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4614 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4615 bool writing_zero = false;
4616 /* set if the fact that we're writing a zero is used to let any
4617 * stack slots remain STACK_ZERO
4619 bool zero_used = false;
4621 cur = env->cur_state->frame[env->cur_state->curframe];
4622 ptr_reg = &cur->regs[ptr_regno];
4623 min_off = ptr_reg->smin_value + off;
4624 max_off = ptr_reg->smax_value + off + size;
4625 if (value_regno >= 0)
4626 value_reg = &cur->regs[value_regno];
4627 if ((value_reg && register_is_null(value_reg)) ||
4628 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4629 writing_zero = true;
4631 for (i = min_off; i < max_off; i++) {
4635 err = destroy_if_dynptr_stack_slot(env, state, spi);
4640 /* Variable offset writes destroy any spilled pointers in range. */
4641 for (i = min_off; i < max_off; i++) {
4642 u8 new_type, *stype;
4646 spi = slot / BPF_REG_SIZE;
4647 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4648 mark_stack_slot_scratched(env, spi);
4650 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4651 /* Reject the write if range we may write to has not
4652 * been initialized beforehand. If we didn't reject
4653 * here, the ptr status would be erased below (even
4654 * though not all slots are actually overwritten),
4655 * possibly opening the door to leaks.
4657 * We do however catch STACK_INVALID case below, and
4658 * only allow reading possibly uninitialized memory
4659 * later for CAP_PERFMON, as the write may not happen to
4662 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4667 /* If writing_zero and the spi slot contains a spill of value 0,
4668 * maintain the spill type.
4670 if (writing_zero && *stype == STACK_SPILL &&
4671 is_spilled_scalar_reg(&state->stack[spi])) {
4672 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
4674 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
4680 /* Erase all other spilled pointers. */
4681 state->stack[spi].spilled_ptr.type = NOT_INIT;
4683 /* Update the slot type. */
4684 new_type = STACK_MISC;
4685 if (writing_zero && *stype == STACK_ZERO) {
4686 new_type = STACK_ZERO;
4689 /* If the slot is STACK_INVALID, we check whether it's OK to
4690 * pretend that it will be initialized by this write. The slot
4691 * might not actually be written to, and so if we mark it as
4692 * initialized future reads might leak uninitialized memory.
4693 * For privileged programs, we will accept such reads to slots
4694 * that may or may not be written because, if we're reject
4695 * them, the error would be too confusing.
4697 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4698 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4705 /* backtracking doesn't work for STACK_ZERO yet. */
4706 err = mark_chain_precision(env, value_regno);
4713 /* When register 'dst_regno' is assigned some values from stack[min_off,
4714 * max_off), we set the register's type according to the types of the
4715 * respective stack slots. If all the stack values are known to be zeros, then
4716 * so is the destination reg. Otherwise, the register is considered to be
4717 * SCALAR. This function does not deal with register filling; the caller must
4718 * ensure that all spilled registers in the stack range have been marked as
4721 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4722 /* func where src register points to */
4723 struct bpf_func_state *ptr_state,
4724 int min_off, int max_off, int dst_regno)
4726 struct bpf_verifier_state *vstate = env->cur_state;
4727 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4732 for (i = min_off; i < max_off; i++) {
4734 spi = slot / BPF_REG_SIZE;
4735 mark_stack_slot_scratched(env, spi);
4736 stype = ptr_state->stack[spi].slot_type;
4737 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4741 if (zeros == max_off - min_off) {
4742 /* Any access_size read into register is zero extended,
4743 * so the whole register == const_zero.
4745 __mark_reg_const_zero(env, &state->regs[dst_regno]);
4747 /* have read misc data from the stack */
4748 mark_reg_unknown(env, state->regs, dst_regno);
4750 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4753 /* Read the stack at 'off' and put the results into the register indicated by
4754 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4757 * 'dst_regno' can be -1, meaning that the read value is not going to a
4760 * The access is assumed to be within the current stack bounds.
4762 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4763 /* func where src register points to */
4764 struct bpf_func_state *reg_state,
4765 int off, int size, int dst_regno)
4767 struct bpf_verifier_state *vstate = env->cur_state;
4768 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4769 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4770 struct bpf_reg_state *reg;
4772 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
4774 stype = reg_state->stack[spi].slot_type;
4775 reg = ®_state->stack[spi].spilled_ptr;
4777 mark_stack_slot_scratched(env, spi);
4779 if (is_spilled_reg(®_state->stack[spi])) {
4782 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4785 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4786 if (reg->type != SCALAR_VALUE) {
4787 verbose_linfo(env, env->insn_idx, "; ");
4788 verbose(env, "invalid size of register fill\n");
4792 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4796 if (size <= spill_size &&
4797 bpf_stack_narrow_access_ok(off, size, spill_size)) {
4798 /* The earlier check_reg_arg() has decided the
4799 * subreg_def for this insn. Save it first.
4801 s32 subreg_def = state->regs[dst_regno].subreg_def;
4803 copy_register_state(&state->regs[dst_regno], reg);
4804 state->regs[dst_regno].subreg_def = subreg_def;
4806 /* Break the relation on a narrowing fill.
4807 * coerce_reg_to_size will adjust the boundaries.
4809 if (get_reg_width(reg) > size * BITS_PER_BYTE)
4810 state->regs[dst_regno].id = 0;
4812 int spill_cnt = 0, zero_cnt = 0;
4814 for (i = 0; i < size; i++) {
4815 type = stype[(slot - i) % BPF_REG_SIZE];
4816 if (type == STACK_SPILL) {
4820 if (type == STACK_MISC)
4822 if (type == STACK_ZERO) {
4826 if (type == STACK_INVALID && env->allow_uninit_stack)
4828 verbose(env, "invalid read from stack off %d+%d size %d\n",
4833 if (spill_cnt == size &&
4834 tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
4835 __mark_reg_const_zero(env, &state->regs[dst_regno]);
4836 /* this IS register fill, so keep insn_flags */
4837 } else if (zero_cnt == size) {
4838 /* similarly to mark_reg_stack_read(), preserve zeroes */
4839 __mark_reg_const_zero(env, &state->regs[dst_regno]);
4840 insn_flags = 0; /* not restoring original register state */
4842 mark_reg_unknown(env, state->regs, dst_regno);
4843 insn_flags = 0; /* not restoring original register state */
4846 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4847 } else if (dst_regno >= 0) {
4848 /* restore register state from stack */
4849 copy_register_state(&state->regs[dst_regno], reg);
4850 /* mark reg as written since spilled pointer state likely
4851 * has its liveness marks cleared by is_state_visited()
4852 * which resets stack/reg liveness for state transitions
4854 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4855 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4856 /* If dst_regno==-1, the caller is asking us whether
4857 * it is acceptable to use this value as a SCALAR_VALUE
4859 * We must not allow unprivileged callers to do that
4860 * with spilled pointers.
4862 verbose(env, "leaking pointer from stack off %d\n",
4866 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4868 for (i = 0; i < size; i++) {
4869 type = stype[(slot - i) % BPF_REG_SIZE];
4870 if (type == STACK_MISC)
4872 if (type == STACK_ZERO)
4874 if (type == STACK_INVALID && env->allow_uninit_stack)
4876 verbose(env, "invalid read from stack off %d+%d size %d\n",
4880 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4882 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4883 insn_flags = 0; /* we are not restoring spilled register */
4886 return push_jmp_history(env, env->cur_state, insn_flags);
4890 enum bpf_access_src {
4891 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
4892 ACCESS_HELPER = 2, /* the access is performed by a helper */
4895 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4896 int regno, int off, int access_size,
4897 bool zero_size_allowed,
4898 enum bpf_access_src type,
4899 struct bpf_call_arg_meta *meta);
4901 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4903 return cur_regs(env) + regno;
4906 /* Read the stack at 'ptr_regno + off' and put the result into the register
4908 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4909 * but not its variable offset.
4910 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4912 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4913 * filling registers (i.e. reads of spilled register cannot be detected when
4914 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4915 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4916 * offset; for a fixed offset check_stack_read_fixed_off should be used
4919 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4920 int ptr_regno, int off, int size, int dst_regno)
4922 /* The state of the source register. */
4923 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4924 struct bpf_func_state *ptr_state = func(env, reg);
4926 int min_off, max_off;
4928 /* Note that we pass a NULL meta, so raw access will not be permitted.
4930 err = check_stack_range_initialized(env, ptr_regno, off, size,
4931 false, ACCESS_DIRECT, NULL);
4935 min_off = reg->smin_value + off;
4936 max_off = reg->smax_value + off;
4937 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4941 /* check_stack_read dispatches to check_stack_read_fixed_off or
4942 * check_stack_read_var_off.
4944 * The caller must ensure that the offset falls within the allocated stack
4947 * 'dst_regno' is a register which will receive the value from the stack. It
4948 * can be -1, meaning that the read value is not going to a register.
4950 static int check_stack_read(struct bpf_verifier_env *env,
4951 int ptr_regno, int off, int size,
4954 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4955 struct bpf_func_state *state = func(env, reg);
4957 /* Some accesses are only permitted with a static offset. */
4958 bool var_off = !tnum_is_const(reg->var_off);
4960 /* The offset is required to be static when reads don't go to a
4961 * register, in order to not leak pointers (see
4962 * check_stack_read_fixed_off).
4964 if (dst_regno < 0 && var_off) {
4967 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4968 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4972 /* Variable offset is prohibited for unprivileged mode for simplicity
4973 * since it requires corresponding support in Spectre masking for stack
4974 * ALU. See also retrieve_ptr_limit(). The check in
4975 * check_stack_access_for_ptr_arithmetic() called by
4976 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4977 * with variable offsets, therefore no check is required here. Further,
4978 * just checking it here would be insufficient as speculative stack
4979 * writes could still lead to unsafe speculative behaviour.
4982 off += reg->var_off.value;
4983 err = check_stack_read_fixed_off(env, state, off, size,
4986 /* Variable offset stack reads need more conservative handling
4987 * than fixed offset ones. Note that dst_regno >= 0 on this
4990 err = check_stack_read_var_off(env, ptr_regno, off, size,
4997 /* check_stack_write dispatches to check_stack_write_fixed_off or
4998 * check_stack_write_var_off.
5000 * 'ptr_regno' is the register used as a pointer into the stack.
5001 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5002 * 'value_regno' is the register whose value we're writing to the stack. It can
5003 * be -1, meaning that we're not writing from a register.
5005 * The caller must ensure that the offset falls within the maximum stack size.
5007 static int check_stack_write(struct bpf_verifier_env *env,
5008 int ptr_regno, int off, int size,
5009 int value_regno, int insn_idx)
5011 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5012 struct bpf_func_state *state = func(env, reg);
5015 if (tnum_is_const(reg->var_off)) {
5016 off += reg->var_off.value;
5017 err = check_stack_write_fixed_off(env, state, off, size,
5018 value_regno, insn_idx);
5020 /* Variable offset stack reads need more conservative handling
5021 * than fixed offset ones.
5023 err = check_stack_write_var_off(env, state,
5024 ptr_regno, off, size,
5025 value_regno, insn_idx);
5030 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5031 int off, int size, enum bpf_access_type type)
5033 struct bpf_reg_state *regs = cur_regs(env);
5034 struct bpf_map *map = regs[regno].map_ptr;
5035 u32 cap = bpf_map_flags_to_cap(map);
5037 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5038 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5039 map->value_size, off, size);
5043 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5044 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5045 map->value_size, off, size);
5052 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5053 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5054 int off, int size, u32 mem_size,
5055 bool zero_size_allowed)
5057 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5058 struct bpf_reg_state *reg;
5060 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5063 reg = &cur_regs(env)[regno];
5064 switch (reg->type) {
5065 case PTR_TO_MAP_KEY:
5066 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5067 mem_size, off, size);
5069 case PTR_TO_MAP_VALUE:
5070 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5071 mem_size, off, size);
5074 case PTR_TO_PACKET_META:
5075 case PTR_TO_PACKET_END:
5076 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5077 off, size, regno, reg->id, off, mem_size);
5081 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5082 mem_size, off, size);
5088 /* check read/write into a memory region with possible variable offset */
5089 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5090 int off, int size, u32 mem_size,
5091 bool zero_size_allowed)
5093 struct bpf_verifier_state *vstate = env->cur_state;
5094 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5095 struct bpf_reg_state *reg = &state->regs[regno];
5098 /* We may have adjusted the register pointing to memory region, so we
5099 * need to try adding each of min_value and max_value to off
5100 * to make sure our theoretical access will be safe.
5102 * The minimum value is only important with signed
5103 * comparisons where we can't assume the floor of a
5104 * value is 0. If we are using signed variables for our
5105 * index'es we need to make sure that whatever we use
5106 * will have a set floor within our range.
5108 if (reg->smin_value < 0 &&
5109 (reg->smin_value == S64_MIN ||
5110 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5111 reg->smin_value + off < 0)) {
5112 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5116 err = __check_mem_access(env, regno, reg->smin_value + off, size,
5117 mem_size, zero_size_allowed);
5119 verbose(env, "R%d min value is outside of the allowed memory range\n",
5124 /* If we haven't set a max value then we need to bail since we can't be
5125 * sure we won't do bad things.
5126 * If reg->umax_value + off could overflow, treat that as unbounded too.
5128 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5129 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5133 err = __check_mem_access(env, regno, reg->umax_value + off, size,
5134 mem_size, zero_size_allowed);
5136 verbose(env, "R%d max value is outside of the allowed memory range\n",
5144 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5145 const struct bpf_reg_state *reg, int regno,
5148 /* Access to this pointer-typed register or passing it to a helper
5149 * is only allowed in its original, unmodified form.
5153 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5154 reg_type_str(env, reg->type), regno, reg->off);
5158 if (!fixed_off_ok && reg->off) {
5159 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5160 reg_type_str(env, reg->type), regno, reg->off);
5164 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5167 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5168 verbose(env, "variable %s access var_off=%s disallowed\n",
5169 reg_type_str(env, reg->type), tn_buf);
5176 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5177 const struct bpf_reg_state *reg, int regno)
5179 return __check_ptr_off_reg(env, reg, regno, false);
5182 static int map_kptr_match_type(struct bpf_verifier_env *env,
5183 struct btf_field *kptr_field,
5184 struct bpf_reg_state *reg, u32 regno)
5186 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5188 const char *reg_name = "";
5190 if (btf_is_kernel(reg->btf)) {
5191 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5193 /* Only unreferenced case accepts untrusted pointers */
5194 if (kptr_field->type == BPF_KPTR_UNREF)
5195 perm_flags |= PTR_UNTRUSTED;
5197 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5198 if (kptr_field->type == BPF_KPTR_PERCPU)
5199 perm_flags |= MEM_PERCPU;
5202 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5205 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5206 reg_name = btf_type_name(reg->btf, reg->btf_id);
5208 /* For ref_ptr case, release function check should ensure we get one
5209 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5210 * normal store of unreferenced kptr, we must ensure var_off is zero.
5211 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5212 * reg->off and reg->ref_obj_id are not needed here.
5214 if (__check_ptr_off_reg(env, reg, regno, true))
5217 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5218 * we also need to take into account the reg->off.
5220 * We want to support cases like:
5228 * v = func(); // PTR_TO_BTF_ID
5229 * val->foo = v; // reg->off is zero, btf and btf_id match type
5230 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5231 * // first member type of struct after comparison fails
5232 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5235 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5236 * is zero. We must also ensure that btf_struct_ids_match does not walk
5237 * the struct to match type against first member of struct, i.e. reject
5238 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5239 * strict mode to true for type match.
5241 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5242 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5243 kptr_field->type != BPF_KPTR_UNREF))
5247 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5248 reg_type_str(env, reg->type), reg_name);
5249 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5250 if (kptr_field->type == BPF_KPTR_UNREF)
5251 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5258 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5259 * can dereference RCU protected pointers and result is PTR_TRUSTED.
5261 static bool in_rcu_cs(struct bpf_verifier_env *env)
5263 return env->cur_state->active_rcu_lock ||
5264 env->cur_state->active_lock.ptr ||
5265 !env->prog->aux->sleepable;
5268 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5269 BTF_SET_START(rcu_protected_types)
5270 BTF_ID(struct, prog_test_ref_kfunc)
5271 #ifdef CONFIG_CGROUPS
5272 BTF_ID(struct, cgroup)
5274 BTF_ID(struct, bpf_cpumask)
5275 BTF_ID(struct, task_struct)
5276 BTF_SET_END(rcu_protected_types)
5278 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5280 if (!btf_is_kernel(btf))
5282 return btf_id_set_contains(&rcu_protected_types, btf_id);
5285 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5287 struct btf_struct_meta *meta;
5289 if (btf_is_kernel(kptr_field->kptr.btf))
5292 meta = btf_find_struct_meta(kptr_field->kptr.btf,
5293 kptr_field->kptr.btf_id);
5295 return meta ? meta->record : NULL;
5298 static bool rcu_safe_kptr(const struct btf_field *field)
5300 const struct btf_field_kptr *kptr = &field->kptr;
5302 return field->type == BPF_KPTR_PERCPU ||
5303 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5306 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5308 struct btf_record *rec;
5311 ret = PTR_MAYBE_NULL;
5312 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5314 if (kptr_field->type == BPF_KPTR_PERCPU)
5316 else if (!btf_is_kernel(kptr_field->kptr.btf))
5319 rec = kptr_pointee_btf_record(kptr_field);
5320 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5323 ret |= PTR_UNTRUSTED;
5329 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5330 int value_regno, int insn_idx,
5331 struct btf_field *kptr_field)
5333 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5334 int class = BPF_CLASS(insn->code);
5335 struct bpf_reg_state *val_reg;
5337 /* Things we already checked for in check_map_access and caller:
5338 * - Reject cases where variable offset may touch kptr
5339 * - size of access (must be BPF_DW)
5340 * - tnum_is_const(reg->var_off)
5341 * - kptr_field->offset == off + reg->var_off.value
5343 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5344 if (BPF_MODE(insn->code) != BPF_MEM) {
5345 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5349 /* We only allow loading referenced kptr, since it will be marked as
5350 * untrusted, similar to unreferenced kptr.
5352 if (class != BPF_LDX &&
5353 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5354 verbose(env, "store to referenced kptr disallowed\n");
5358 if (class == BPF_LDX) {
5359 val_reg = reg_state(env, value_regno);
5360 /* We can simply mark the value_regno receiving the pointer
5361 * value from map as PTR_TO_BTF_ID, with the correct type.
5363 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5364 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5365 /* For mark_ptr_or_null_reg */
5366 val_reg->id = ++env->id_gen;
5367 } else if (class == BPF_STX) {
5368 val_reg = reg_state(env, value_regno);
5369 if (!register_is_null(val_reg) &&
5370 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5372 } else if (class == BPF_ST) {
5374 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5375 kptr_field->offset);
5379 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5385 /* check read/write into a map element with possible variable offset */
5386 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5387 int off, int size, bool zero_size_allowed,
5388 enum bpf_access_src src)
5390 struct bpf_verifier_state *vstate = env->cur_state;
5391 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5392 struct bpf_reg_state *reg = &state->regs[regno];
5393 struct bpf_map *map = reg->map_ptr;
5394 struct btf_record *rec;
5397 err = check_mem_region_access(env, regno, off, size, map->value_size,
5402 if (IS_ERR_OR_NULL(map->record))
5405 for (i = 0; i < rec->cnt; i++) {
5406 struct btf_field *field = &rec->fields[i];
5407 u32 p = field->offset;
5409 /* If any part of a field can be touched by load/store, reject
5410 * this program. To check that [x1, x2) overlaps with [y1, y2),
5411 * it is sufficient to check x1 < y2 && y1 < x2.
5413 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5414 p < reg->umax_value + off + size) {
5415 switch (field->type) {
5416 case BPF_KPTR_UNREF:
5418 case BPF_KPTR_PERCPU:
5419 if (src != ACCESS_DIRECT) {
5420 verbose(env, "kptr cannot be accessed indirectly by helper\n");
5423 if (!tnum_is_const(reg->var_off)) {
5424 verbose(env, "kptr access cannot have variable offset\n");
5427 if (p != off + reg->var_off.value) {
5428 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5429 p, off + reg->var_off.value);
5432 if (size != bpf_size_to_bytes(BPF_DW)) {
5433 verbose(env, "kptr access size must be BPF_DW\n");
5438 verbose(env, "%s cannot be accessed directly by load/store\n",
5439 btf_field_type_name(field->type));
5447 #define MAX_PACKET_OFF 0xffff
5449 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5450 const struct bpf_call_arg_meta *meta,
5451 enum bpf_access_type t)
5453 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5455 switch (prog_type) {
5456 /* Program types only with direct read access go here! */
5457 case BPF_PROG_TYPE_LWT_IN:
5458 case BPF_PROG_TYPE_LWT_OUT:
5459 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5460 case BPF_PROG_TYPE_SK_REUSEPORT:
5461 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5462 case BPF_PROG_TYPE_CGROUP_SKB:
5467 /* Program types with direct read + write access go here! */
5468 case BPF_PROG_TYPE_SCHED_CLS:
5469 case BPF_PROG_TYPE_SCHED_ACT:
5470 case BPF_PROG_TYPE_XDP:
5471 case BPF_PROG_TYPE_LWT_XMIT:
5472 case BPF_PROG_TYPE_SK_SKB:
5473 case BPF_PROG_TYPE_SK_MSG:
5475 return meta->pkt_access;
5477 env->seen_direct_write = true;
5480 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5482 env->seen_direct_write = true;
5491 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5492 int size, bool zero_size_allowed)
5494 struct bpf_reg_state *regs = cur_regs(env);
5495 struct bpf_reg_state *reg = ®s[regno];
5498 /* We may have added a variable offset to the packet pointer; but any
5499 * reg->range we have comes after that. We are only checking the fixed
5503 /* We don't allow negative numbers, because we aren't tracking enough
5504 * detail to prove they're safe.
5506 if (reg->smin_value < 0) {
5507 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5512 err = reg->range < 0 ? -EINVAL :
5513 __check_mem_access(env, regno, off, size, reg->range,
5516 verbose(env, "R%d offset is outside of the packet\n", regno);
5520 /* __check_mem_access has made sure "off + size - 1" is within u16.
5521 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5522 * otherwise find_good_pkt_pointers would have refused to set range info
5523 * that __check_mem_access would have rejected this pkt access.
5524 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5526 env->prog->aux->max_pkt_offset =
5527 max_t(u32, env->prog->aux->max_pkt_offset,
5528 off + reg->umax_value + size - 1);
5533 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
5534 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5535 enum bpf_access_type t, enum bpf_reg_type *reg_type,
5536 struct btf **btf, u32 *btf_id)
5538 struct bpf_insn_access_aux info = {
5539 .reg_type = *reg_type,
5543 if (env->ops->is_valid_access &&
5544 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5545 /* A non zero info.ctx_field_size indicates that this field is a
5546 * candidate for later verifier transformation to load the whole
5547 * field and then apply a mask when accessed with a narrower
5548 * access than actual ctx access size. A zero info.ctx_field_size
5549 * will only allow for whole field access and rejects any other
5550 * type of narrower access.
5552 *reg_type = info.reg_type;
5554 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5556 *btf_id = info.btf_id;
5558 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5560 /* remember the offset of last byte accessed in ctx */
5561 if (env->prog->aux->max_ctx_offset < off + size)
5562 env->prog->aux->max_ctx_offset = off + size;
5566 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5570 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5573 if (size < 0 || off < 0 ||
5574 (u64)off + size > sizeof(struct bpf_flow_keys)) {
5575 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5582 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5583 u32 regno, int off, int size,
5584 enum bpf_access_type t)
5586 struct bpf_reg_state *regs = cur_regs(env);
5587 struct bpf_reg_state *reg = ®s[regno];
5588 struct bpf_insn_access_aux info = {};
5591 if (reg->smin_value < 0) {
5592 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5597 switch (reg->type) {
5598 case PTR_TO_SOCK_COMMON:
5599 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5602 valid = bpf_sock_is_valid_access(off, size, t, &info);
5604 case PTR_TO_TCP_SOCK:
5605 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5607 case PTR_TO_XDP_SOCK:
5608 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5616 env->insn_aux_data[insn_idx].ctx_field_size =
5617 info.ctx_field_size;
5621 verbose(env, "R%d invalid %s access off=%d size=%d\n",
5622 regno, reg_type_str(env, reg->type), off, size);
5627 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5629 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5632 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5634 const struct bpf_reg_state *reg = reg_state(env, regno);
5636 return reg->type == PTR_TO_CTX;
5639 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5641 const struct bpf_reg_state *reg = reg_state(env, regno);
5643 return type_is_sk_pointer(reg->type);
5646 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5648 const struct bpf_reg_state *reg = reg_state(env, regno);
5650 return type_is_pkt_pointer(reg->type);
5653 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5655 const struct bpf_reg_state *reg = reg_state(env, regno);
5657 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5658 return reg->type == PTR_TO_FLOW_KEYS;
5661 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5663 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5664 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5665 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5667 [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5670 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5672 /* A referenced register is always trusted. */
5673 if (reg->ref_obj_id)
5676 /* Types listed in the reg2btf_ids are always trusted */
5677 if (reg2btf_ids[base_type(reg->type)])
5680 /* If a register is not referenced, it is trusted if it has the
5681 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5682 * other type modifiers may be safe, but we elect to take an opt-in
5683 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5686 * Eventually, we should make PTR_TRUSTED the single source of truth
5687 * for whether a register is trusted.
5689 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5690 !bpf_type_has_unsafe_modifiers(reg->type);
5693 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5695 return reg->type & MEM_RCU;
5698 static void clear_trusted_flags(enum bpf_type_flag *flag)
5700 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5703 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5704 const struct bpf_reg_state *reg,
5705 int off, int size, bool strict)
5707 struct tnum reg_off;
5710 /* Byte size accesses are always allowed. */
5711 if (!strict || size == 1)
5714 /* For platforms that do not have a Kconfig enabling
5715 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5716 * NET_IP_ALIGN is universally set to '2'. And on platforms
5717 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5718 * to this code only in strict mode where we want to emulate
5719 * the NET_IP_ALIGN==2 checking. Therefore use an
5720 * unconditional IP align value of '2'.
5724 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5725 if (!tnum_is_aligned(reg_off, size)) {
5728 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5730 "misaligned packet access off %d+%s+%d+%d size %d\n",
5731 ip_align, tn_buf, reg->off, off, size);
5738 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5739 const struct bpf_reg_state *reg,
5740 const char *pointer_desc,
5741 int off, int size, bool strict)
5743 struct tnum reg_off;
5745 /* Byte size accesses are always allowed. */
5746 if (!strict || size == 1)
5749 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5750 if (!tnum_is_aligned(reg_off, size)) {
5753 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5754 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5755 pointer_desc, tn_buf, reg->off, off, size);
5762 static int check_ptr_alignment(struct bpf_verifier_env *env,
5763 const struct bpf_reg_state *reg, int off,
5764 int size, bool strict_alignment_once)
5766 bool strict = env->strict_alignment || strict_alignment_once;
5767 const char *pointer_desc = "";
5769 switch (reg->type) {
5771 case PTR_TO_PACKET_META:
5772 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5773 * right in front, treat it the very same way.
5775 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5776 case PTR_TO_FLOW_KEYS:
5777 pointer_desc = "flow keys ";
5779 case PTR_TO_MAP_KEY:
5780 pointer_desc = "key ";
5782 case PTR_TO_MAP_VALUE:
5783 pointer_desc = "value ";
5786 pointer_desc = "context ";
5789 pointer_desc = "stack ";
5790 /* The stack spill tracking logic in check_stack_write_fixed_off()
5791 * and check_stack_read_fixed_off() relies on stack accesses being
5797 pointer_desc = "sock ";
5799 case PTR_TO_SOCK_COMMON:
5800 pointer_desc = "sock_common ";
5802 case PTR_TO_TCP_SOCK:
5803 pointer_desc = "tcp_sock ";
5805 case PTR_TO_XDP_SOCK:
5806 pointer_desc = "xdp_sock ";
5811 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5815 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
5817 if (env->prog->jit_requested)
5818 return round_up(stack_depth, 16);
5820 /* round up to 32-bytes, since this is granularity
5821 * of interpreter stack size
5823 return round_up(max_t(u32, stack_depth, 1), 32);
5826 /* starting from main bpf function walk all instructions of the function
5827 * and recursively walk all callees that given function can call.
5828 * Ignore jump and exit insns.
5829 * Since recursion is prevented by check_cfg() this algorithm
5830 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5832 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5834 struct bpf_subprog_info *subprog = env->subprog_info;
5835 struct bpf_insn *insn = env->prog->insnsi;
5836 int depth = 0, frame = 0, i, subprog_end;
5837 bool tail_call_reachable = false;
5838 int ret_insn[MAX_CALL_FRAMES];
5839 int ret_prog[MAX_CALL_FRAMES];
5842 i = subprog[idx].start;
5844 /* protect against potential stack overflow that might happen when
5845 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5846 * depth for such case down to 256 so that the worst case scenario
5847 * would result in 8k stack size (32 which is tailcall limit * 256 =
5850 * To get the idea what might happen, see an example:
5851 * func1 -> sub rsp, 128
5852 * subfunc1 -> sub rsp, 256
5853 * tailcall1 -> add rsp, 256
5854 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5855 * subfunc2 -> sub rsp, 64
5856 * subfunc22 -> sub rsp, 128
5857 * tailcall2 -> add rsp, 128
5858 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5860 * tailcall will unwind the current stack frame but it will not get rid
5861 * of caller's stack as shown on the example above.
5863 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5865 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5869 depth += round_up_stack_depth(env, subprog[idx].stack_depth);
5870 if (depth > MAX_BPF_STACK) {
5871 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5876 subprog_end = subprog[idx + 1].start;
5877 for (; i < subprog_end; i++) {
5878 int next_insn, sidx;
5880 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5883 if (!is_bpf_throw_kfunc(insn + i))
5885 if (subprog[idx].is_cb)
5887 for (int c = 0; c < frame && !err; c++) {
5888 if (subprog[ret_prog[c]].is_cb) {
5896 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5901 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5903 /* remember insn and function to return to */
5904 ret_insn[frame] = i + 1;
5905 ret_prog[frame] = idx;
5907 /* find the callee */
5908 next_insn = i + insn[i].imm + 1;
5909 sidx = find_subprog(env, next_insn);
5911 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5915 if (subprog[sidx].is_async_cb) {
5916 if (subprog[sidx].has_tail_call) {
5917 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5920 /* async callbacks don't increase bpf prog stack size unless called directly */
5921 if (!bpf_pseudo_call(insn + i))
5923 if (subprog[sidx].is_exception_cb) {
5924 verbose(env, "insn %d cannot call exception cb directly\n", i);
5931 if (subprog[idx].has_tail_call)
5932 tail_call_reachable = true;
5935 if (frame >= MAX_CALL_FRAMES) {
5936 verbose(env, "the call stack of %d frames is too deep !\n",
5942 /* if tail call got detected across bpf2bpf calls then mark each of the
5943 * currently present subprog frames as tail call reachable subprogs;
5944 * this info will be utilized by JIT so that we will be preserving the
5945 * tail call counter throughout bpf2bpf calls combined with tailcalls
5947 if (tail_call_reachable)
5948 for (j = 0; j < frame; j++) {
5949 if (subprog[ret_prog[j]].is_exception_cb) {
5950 verbose(env, "cannot tail call within exception cb\n");
5953 subprog[ret_prog[j]].tail_call_reachable = true;
5955 if (subprog[0].tail_call_reachable)
5956 env->prog->aux->tail_call_reachable = true;
5958 /* end of for() loop means the last insn of the 'subprog'
5959 * was reached. Doesn't matter whether it was JA or EXIT
5963 depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
5965 i = ret_insn[frame];
5966 idx = ret_prog[frame];
5970 static int check_max_stack_depth(struct bpf_verifier_env *env)
5972 struct bpf_subprog_info *si = env->subprog_info;
5975 for (int i = 0; i < env->subprog_cnt; i++) {
5976 if (!i || si[i].is_async_cb) {
5977 ret = check_max_stack_depth_subprog(env, i);
5986 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5987 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5988 const struct bpf_insn *insn, int idx)
5990 int start = idx + insn->imm + 1, subprog;
5992 subprog = find_subprog(env, start);
5994 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5998 return env->subprog_info[subprog].stack_depth;
6002 static int __check_buffer_access(struct bpf_verifier_env *env,
6003 const char *buf_info,
6004 const struct bpf_reg_state *reg,
6005 int regno, int off, int size)
6009 "R%d invalid %s buffer access: off=%d, size=%d\n",
6010 regno, buf_info, off, size);
6013 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6016 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6018 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6019 regno, off, tn_buf);
6026 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6027 const struct bpf_reg_state *reg,
6028 int regno, int off, int size)
6032 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6036 if (off + size > env->prog->aux->max_tp_access)
6037 env->prog->aux->max_tp_access = off + size;
6042 static int check_buffer_access(struct bpf_verifier_env *env,
6043 const struct bpf_reg_state *reg,
6044 int regno, int off, int size,
6045 bool zero_size_allowed,
6048 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6051 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6055 if (off + size > *max_access)
6056 *max_access = off + size;
6061 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6062 static void zext_32_to_64(struct bpf_reg_state *reg)
6064 reg->var_off = tnum_subreg(reg->var_off);
6065 __reg_assign_32_into_64(reg);
6068 /* truncate register to smaller size (in bytes)
6069 * must be called with size < BPF_REG_SIZE
6071 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6075 /* clear high bits in bit representation */
6076 reg->var_off = tnum_cast(reg->var_off, size);
6078 /* fix arithmetic bounds */
6079 mask = ((u64)1 << (size * 8)) - 1;
6080 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6081 reg->umin_value &= mask;
6082 reg->umax_value &= mask;
6084 reg->umin_value = 0;
6085 reg->umax_value = mask;
6087 reg->smin_value = reg->umin_value;
6088 reg->smax_value = reg->umax_value;
6090 /* If size is smaller than 32bit register the 32bit register
6091 * values are also truncated so we push 64-bit bounds into
6092 * 32-bit bounds. Above were truncated < 32-bits already.
6095 __mark_reg32_unbounded(reg);
6097 reg_bounds_sync(reg);
6100 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6103 reg->smin_value = reg->s32_min_value = S8_MIN;
6104 reg->smax_value = reg->s32_max_value = S8_MAX;
6105 } else if (size == 2) {
6106 reg->smin_value = reg->s32_min_value = S16_MIN;
6107 reg->smax_value = reg->s32_max_value = S16_MAX;
6110 reg->smin_value = reg->s32_min_value = S32_MIN;
6111 reg->smax_value = reg->s32_max_value = S32_MAX;
6113 reg->umin_value = reg->u32_min_value = 0;
6114 reg->umax_value = U64_MAX;
6115 reg->u32_max_value = U32_MAX;
6116 reg->var_off = tnum_unknown;
6119 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6121 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6122 u64 top_smax_value, top_smin_value;
6123 u64 num_bits = size * 8;
6125 if (tnum_is_const(reg->var_off)) {
6126 u64_cval = reg->var_off.value;
6128 reg->var_off = tnum_const((s8)u64_cval);
6130 reg->var_off = tnum_const((s16)u64_cval);
6133 reg->var_off = tnum_const((s32)u64_cval);
6135 u64_cval = reg->var_off.value;
6136 reg->smax_value = reg->smin_value = u64_cval;
6137 reg->umax_value = reg->umin_value = u64_cval;
6138 reg->s32_max_value = reg->s32_min_value = u64_cval;
6139 reg->u32_max_value = reg->u32_min_value = u64_cval;
6143 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6144 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6146 if (top_smax_value != top_smin_value)
6149 /* find the s64_min and s64_min after sign extension */
6151 init_s64_max = (s8)reg->smax_value;
6152 init_s64_min = (s8)reg->smin_value;
6153 } else if (size == 2) {
6154 init_s64_max = (s16)reg->smax_value;
6155 init_s64_min = (s16)reg->smin_value;
6157 init_s64_max = (s32)reg->smax_value;
6158 init_s64_min = (s32)reg->smin_value;
6161 s64_max = max(init_s64_max, init_s64_min);
6162 s64_min = min(init_s64_max, init_s64_min);
6164 /* both of s64_max/s64_min positive or negative */
6165 if ((s64_max >= 0) == (s64_min >= 0)) {
6166 reg->smin_value = reg->s32_min_value = s64_min;
6167 reg->smax_value = reg->s32_max_value = s64_max;
6168 reg->umin_value = reg->u32_min_value = s64_min;
6169 reg->umax_value = reg->u32_max_value = s64_max;
6170 reg->var_off = tnum_range(s64_min, s64_max);
6175 set_sext64_default_val(reg, size);
6178 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6181 reg->s32_min_value = S8_MIN;
6182 reg->s32_max_value = S8_MAX;
6185 reg->s32_min_value = S16_MIN;
6186 reg->s32_max_value = S16_MAX;
6188 reg->u32_min_value = 0;
6189 reg->u32_max_value = U32_MAX;
6192 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6194 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6195 u32 top_smax_value, top_smin_value;
6196 u32 num_bits = size * 8;
6198 if (tnum_is_const(reg->var_off)) {
6199 u32_val = reg->var_off.value;
6201 reg->var_off = tnum_const((s8)u32_val);
6203 reg->var_off = tnum_const((s16)u32_val);
6205 u32_val = reg->var_off.value;
6206 reg->s32_min_value = reg->s32_max_value = u32_val;
6207 reg->u32_min_value = reg->u32_max_value = u32_val;
6211 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6212 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6214 if (top_smax_value != top_smin_value)
6217 /* find the s32_min and s32_min after sign extension */
6219 init_s32_max = (s8)reg->s32_max_value;
6220 init_s32_min = (s8)reg->s32_min_value;
6223 init_s32_max = (s16)reg->s32_max_value;
6224 init_s32_min = (s16)reg->s32_min_value;
6226 s32_max = max(init_s32_max, init_s32_min);
6227 s32_min = min(init_s32_max, init_s32_min);
6229 if ((s32_min >= 0) == (s32_max >= 0)) {
6230 reg->s32_min_value = s32_min;
6231 reg->s32_max_value = s32_max;
6232 reg->u32_min_value = (u32)s32_min;
6233 reg->u32_max_value = (u32)s32_max;
6238 set_sext32_default_val(reg, size);
6241 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6243 /* A map is considered read-only if the following condition are true:
6245 * 1) BPF program side cannot change any of the map content. The
6246 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6247 * and was set at map creation time.
6248 * 2) The map value(s) have been initialized from user space by a
6249 * loader and then "frozen", such that no new map update/delete
6250 * operations from syscall side are possible for the rest of
6251 * the map's lifetime from that point onwards.
6252 * 3) Any parallel/pending map update/delete operations from syscall
6253 * side have been completed. Only after that point, it's safe to
6254 * assume that map value(s) are immutable.
6256 return (map->map_flags & BPF_F_RDONLY_PROG) &&
6257 READ_ONCE(map->frozen) &&
6258 !bpf_map_write_active(map);
6261 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6268 err = map->ops->map_direct_value_addr(map, &addr, off);
6271 ptr = (void *)(long)addr + off;
6275 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6278 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6281 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6292 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
6293 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
6294 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
6297 * Allow list few fields as RCU trusted or full trusted.
6298 * This logic doesn't allow mix tagging and will be removed once GCC supports
6302 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6303 BTF_TYPE_SAFE_RCU(struct task_struct) {
6304 const cpumask_t *cpus_ptr;
6305 struct css_set __rcu *cgroups;
6306 struct task_struct __rcu *real_parent;
6307 struct task_struct *group_leader;
6310 BTF_TYPE_SAFE_RCU(struct cgroup) {
6311 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6312 struct kernfs_node *kn;
6315 BTF_TYPE_SAFE_RCU(struct css_set) {
6316 struct cgroup *dfl_cgrp;
6319 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6320 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6321 struct file __rcu *exe_file;
6324 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6325 * because bpf prog accessible sockets are SOCK_RCU_FREE.
6327 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6331 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6335 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6336 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6337 struct seq_file *seq;
6340 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6341 struct bpf_iter_meta *meta;
6342 struct task_struct *task;
6345 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6349 BTF_TYPE_SAFE_TRUSTED(struct file) {
6350 struct inode *f_inode;
6353 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6354 /* no negative dentry-s in places where bpf can see it */
6355 struct inode *d_inode;
6358 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6362 static bool type_is_rcu(struct bpf_verifier_env *env,
6363 struct bpf_reg_state *reg,
6364 const char *field_name, u32 btf_id)
6366 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6367 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6368 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6370 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6373 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6374 struct bpf_reg_state *reg,
6375 const char *field_name, u32 btf_id)
6377 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6378 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6379 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6381 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6384 static bool type_is_trusted(struct bpf_verifier_env *env,
6385 struct bpf_reg_state *reg,
6386 const char *field_name, u32 btf_id)
6388 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6389 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6390 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6391 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6392 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6393 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6395 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6398 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6399 struct bpf_reg_state *regs,
6400 int regno, int off, int size,
6401 enum bpf_access_type atype,
6404 struct bpf_reg_state *reg = regs + regno;
6405 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6406 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6407 const char *field_name = NULL;
6408 enum bpf_type_flag flag = 0;
6412 if (!env->allow_ptr_leaks) {
6414 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6418 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6420 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6426 "R%d is ptr_%s invalid negative access: off=%d\n",
6430 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6433 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6435 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6436 regno, tname, off, tn_buf);
6440 if (reg->type & MEM_USER) {
6442 "R%d is ptr_%s access user memory: off=%d\n",
6447 if (reg->type & MEM_PERCPU) {
6449 "R%d is ptr_%s access percpu memory: off=%d\n",
6454 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6455 if (!btf_is_kernel(reg->btf)) {
6456 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6459 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6461 /* Writes are permitted with default btf_struct_access for
6462 * program allocated objects (which always have ref_obj_id > 0),
6463 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6465 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6466 verbose(env, "only read is supported\n");
6470 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6471 !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6472 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6476 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6482 if (ret != PTR_TO_BTF_ID) {
6485 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6486 /* If this is an untrusted pointer, all pointers formed by walking it
6487 * also inherit the untrusted flag.
6489 flag = PTR_UNTRUSTED;
6491 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6492 /* By default any pointer obtained from walking a trusted pointer is no
6493 * longer trusted, unless the field being accessed has explicitly been
6494 * marked as inheriting its parent's state of trust (either full or RCU).
6496 * 'cgroups' pointer is untrusted if task->cgroups dereference
6497 * happened in a sleepable program outside of bpf_rcu_read_lock()
6498 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6499 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6501 * A regular RCU-protected pointer with __rcu tag can also be deemed
6502 * trusted if we are in an RCU CS. Such pointer can be NULL.
6504 if (type_is_trusted(env, reg, field_name, btf_id)) {
6505 flag |= PTR_TRUSTED;
6506 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6507 if (type_is_rcu(env, reg, field_name, btf_id)) {
6508 /* ignore __rcu tag and mark it MEM_RCU */
6510 } else if (flag & MEM_RCU ||
6511 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6512 /* __rcu tagged pointers can be NULL */
6513 flag |= MEM_RCU | PTR_MAYBE_NULL;
6515 /* We always trust them */
6516 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6517 flag & PTR_UNTRUSTED)
6518 flag &= ~PTR_UNTRUSTED;
6519 } else if (flag & (MEM_PERCPU | MEM_USER)) {
6522 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6523 clear_trusted_flags(&flag);
6527 * If not in RCU CS or MEM_RCU pointer can be NULL then
6528 * aggressively mark as untrusted otherwise such
6529 * pointers will be plain PTR_TO_BTF_ID without flags
6530 * and will be allowed to be passed into helpers for
6533 flag = PTR_UNTRUSTED;
6536 /* Old compat. Deprecated */
6537 clear_trusted_flags(&flag);
6540 if (atype == BPF_READ && value_regno >= 0)
6541 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6546 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6547 struct bpf_reg_state *regs,
6548 int regno, int off, int size,
6549 enum bpf_access_type atype,
6552 struct bpf_reg_state *reg = regs + regno;
6553 struct bpf_map *map = reg->map_ptr;
6554 struct bpf_reg_state map_reg;
6555 enum bpf_type_flag flag = 0;
6556 const struct btf_type *t;
6562 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6566 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6567 verbose(env, "map_ptr access not supported for map type %d\n",
6572 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6573 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6575 if (!env->allow_ptr_leaks) {
6577 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6583 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6588 if (atype != BPF_READ) {
6589 verbose(env, "only read from %s is supported\n", tname);
6593 /* Simulate access to a PTR_TO_BTF_ID */
6594 memset(&map_reg, 0, sizeof(map_reg));
6595 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6596 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6600 if (value_regno >= 0)
6601 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6606 /* Check that the stack access at the given offset is within bounds. The
6607 * maximum valid offset is -1.
6609 * The minimum valid offset is -MAX_BPF_STACK for writes, and
6610 * -state->allocated_stack for reads.
6612 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6614 struct bpf_func_state *state,
6615 enum bpf_access_type t)
6619 if (t == BPF_WRITE || env->allow_uninit_stack)
6620 min_valid_off = -MAX_BPF_STACK;
6622 min_valid_off = -state->allocated_stack;
6624 if (off < min_valid_off || off > -1)
6629 /* Check that the stack access at 'regno + off' falls within the maximum stack
6632 * 'off' includes `regno->offset`, but not its dynamic part (if any).
6634 static int check_stack_access_within_bounds(
6635 struct bpf_verifier_env *env,
6636 int regno, int off, int access_size,
6637 enum bpf_access_src src, enum bpf_access_type type)
6639 struct bpf_reg_state *regs = cur_regs(env);
6640 struct bpf_reg_state *reg = regs + regno;
6641 struct bpf_func_state *state = func(env, reg);
6642 s64 min_off, max_off;
6646 if (src == ACCESS_HELPER)
6647 /* We don't know if helpers are reading or writing (or both). */
6648 err_extra = " indirect access to";
6649 else if (type == BPF_READ)
6650 err_extra = " read from";
6652 err_extra = " write to";
6654 if (tnum_is_const(reg->var_off)) {
6655 min_off = (s64)reg->var_off.value + off;
6656 max_off = min_off + access_size;
6658 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6659 reg->smin_value <= -BPF_MAX_VAR_OFF) {
6660 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6664 min_off = reg->smin_value + off;
6665 max_off = reg->smax_value + off + access_size;
6668 err = check_stack_slot_within_bounds(env, min_off, state, type);
6669 if (!err && max_off > 0)
6670 err = -EINVAL; /* out of stack access into non-negative offsets */
6673 if (tnum_is_const(reg->var_off)) {
6674 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6675 err_extra, regno, off, access_size);
6679 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6680 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
6681 err_extra, regno, tn_buf, off, access_size);
6686 /* Note that there is no stack access with offset zero, so the needed stack
6687 * size is -min_off, not -min_off+1.
6689 return grow_stack_state(env, state, -min_off /* size */);
6692 /* check whether memory at (regno + off) is accessible for t = (read | write)
6693 * if t==write, value_regno is a register which value is stored into memory
6694 * if t==read, value_regno is a register which will receive the value from memory
6695 * if t==write && value_regno==-1, some unknown value is stored into memory
6696 * if t==read && value_regno==-1, don't care what we read from memory
6698 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6699 int off, int bpf_size, enum bpf_access_type t,
6700 int value_regno, bool strict_alignment_once, bool is_ldsx)
6702 struct bpf_reg_state *regs = cur_regs(env);
6703 struct bpf_reg_state *reg = regs + regno;
6706 size = bpf_size_to_bytes(bpf_size);
6710 /* alignment checks will add in reg->off themselves */
6711 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6715 /* for access checks, reg->off is just part of off */
6718 if (reg->type == PTR_TO_MAP_KEY) {
6719 if (t == BPF_WRITE) {
6720 verbose(env, "write to change key R%d not allowed\n", regno);
6724 err = check_mem_region_access(env, regno, off, size,
6725 reg->map_ptr->key_size, false);
6728 if (value_regno >= 0)
6729 mark_reg_unknown(env, regs, value_regno);
6730 } else if (reg->type == PTR_TO_MAP_VALUE) {
6731 struct btf_field *kptr_field = NULL;
6733 if (t == BPF_WRITE && value_regno >= 0 &&
6734 is_pointer_value(env, value_regno)) {
6735 verbose(env, "R%d leaks addr into map\n", value_regno);
6738 err = check_map_access_type(env, regno, off, size, t);
6741 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6744 if (tnum_is_const(reg->var_off))
6745 kptr_field = btf_record_find(reg->map_ptr->record,
6746 off + reg->var_off.value, BPF_KPTR);
6748 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6749 } else if (t == BPF_READ && value_regno >= 0) {
6750 struct bpf_map *map = reg->map_ptr;
6752 /* if map is read-only, track its contents as scalars */
6753 if (tnum_is_const(reg->var_off) &&
6754 bpf_map_is_rdonly(map) &&
6755 map->ops->map_direct_value_addr) {
6756 int map_off = off + reg->var_off.value;
6759 err = bpf_map_direct_read(map, map_off, size,
6764 regs[value_regno].type = SCALAR_VALUE;
6765 __mark_reg_known(®s[value_regno], val);
6767 mark_reg_unknown(env, regs, value_regno);
6770 } else if (base_type(reg->type) == PTR_TO_MEM) {
6771 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6773 if (type_may_be_null(reg->type)) {
6774 verbose(env, "R%d invalid mem access '%s'\n", regno,
6775 reg_type_str(env, reg->type));
6779 if (t == BPF_WRITE && rdonly_mem) {
6780 verbose(env, "R%d cannot write into %s\n",
6781 regno, reg_type_str(env, reg->type));
6785 if (t == BPF_WRITE && value_regno >= 0 &&
6786 is_pointer_value(env, value_regno)) {
6787 verbose(env, "R%d leaks addr into mem\n", value_regno);
6791 err = check_mem_region_access(env, regno, off, size,
6792 reg->mem_size, false);
6793 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6794 mark_reg_unknown(env, regs, value_regno);
6795 } else if (reg->type == PTR_TO_CTX) {
6796 enum bpf_reg_type reg_type = SCALAR_VALUE;
6797 struct btf *btf = NULL;
6800 if (t == BPF_WRITE && value_regno >= 0 &&
6801 is_pointer_value(env, value_regno)) {
6802 verbose(env, "R%d leaks addr into ctx\n", value_regno);
6806 err = check_ptr_off_reg(env, reg, regno);
6810 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
6813 verbose_linfo(env, insn_idx, "; ");
6814 if (!err && t == BPF_READ && value_regno >= 0) {
6815 /* ctx access returns either a scalar, or a
6816 * PTR_TO_PACKET[_META,_END]. In the latter
6817 * case, we know the offset is zero.
6819 if (reg_type == SCALAR_VALUE) {
6820 mark_reg_unknown(env, regs, value_regno);
6822 mark_reg_known_zero(env, regs,
6824 if (type_may_be_null(reg_type))
6825 regs[value_regno].id = ++env->id_gen;
6826 /* A load of ctx field could have different
6827 * actual load size with the one encoded in the
6828 * insn. When the dst is PTR, it is for sure not
6831 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6832 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6833 regs[value_regno].btf = btf;
6834 regs[value_regno].btf_id = btf_id;
6837 regs[value_regno].type = reg_type;
6840 } else if (reg->type == PTR_TO_STACK) {
6841 /* Basic bounds checks. */
6842 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6847 err = check_stack_read(env, regno, off, size,
6850 err = check_stack_write(env, regno, off, size,
6851 value_regno, insn_idx);
6852 } else if (reg_is_pkt_pointer(reg)) {
6853 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6854 verbose(env, "cannot write into packet\n");
6857 if (t == BPF_WRITE && value_regno >= 0 &&
6858 is_pointer_value(env, value_regno)) {
6859 verbose(env, "R%d leaks addr into packet\n",
6863 err = check_packet_access(env, regno, off, size, false);
6864 if (!err && t == BPF_READ && value_regno >= 0)
6865 mark_reg_unknown(env, regs, value_regno);
6866 } else if (reg->type == PTR_TO_FLOW_KEYS) {
6867 if (t == BPF_WRITE && value_regno >= 0 &&
6868 is_pointer_value(env, value_regno)) {
6869 verbose(env, "R%d leaks addr into flow keys\n",
6874 err = check_flow_keys_access(env, off, size);
6875 if (!err && t == BPF_READ && value_regno >= 0)
6876 mark_reg_unknown(env, regs, value_regno);
6877 } else if (type_is_sk_pointer(reg->type)) {
6878 if (t == BPF_WRITE) {
6879 verbose(env, "R%d cannot write into %s\n",
6880 regno, reg_type_str(env, reg->type));
6883 err = check_sock_access(env, insn_idx, regno, off, size, t);
6884 if (!err && value_regno >= 0)
6885 mark_reg_unknown(env, regs, value_regno);
6886 } else if (reg->type == PTR_TO_TP_BUFFER) {
6887 err = check_tp_buffer_access(env, reg, regno, off, size);
6888 if (!err && t == BPF_READ && value_regno >= 0)
6889 mark_reg_unknown(env, regs, value_regno);
6890 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6891 !type_may_be_null(reg->type)) {
6892 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6894 } else if (reg->type == CONST_PTR_TO_MAP) {
6895 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6897 } else if (base_type(reg->type) == PTR_TO_BUF) {
6898 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6902 if (t == BPF_WRITE) {
6903 verbose(env, "R%d cannot write into %s\n",
6904 regno, reg_type_str(env, reg->type));
6907 max_access = &env->prog->aux->max_rdonly_access;
6909 max_access = &env->prog->aux->max_rdwr_access;
6912 err = check_buffer_access(env, reg, regno, off, size, false,
6915 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6916 mark_reg_unknown(env, regs, value_regno);
6918 verbose(env, "R%d invalid mem access '%s'\n", regno,
6919 reg_type_str(env, reg->type));
6923 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6924 regs[value_regno].type == SCALAR_VALUE) {
6926 /* b/h/w load zero-extends, mark upper bits as known 0 */
6927 coerce_reg_to_size(®s[value_regno], size);
6929 coerce_reg_to_size_sx(®s[value_regno], size);
6934 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6939 switch (insn->imm) {
6941 case BPF_ADD | BPF_FETCH:
6943 case BPF_AND | BPF_FETCH:
6945 case BPF_OR | BPF_FETCH:
6947 case BPF_XOR | BPF_FETCH:
6952 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6956 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6957 verbose(env, "invalid atomic operand size\n");
6961 /* check src1 operand */
6962 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6966 /* check src2 operand */
6967 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6971 if (insn->imm == BPF_CMPXCHG) {
6972 /* Check comparison of R0 with memory location */
6973 const u32 aux_reg = BPF_REG_0;
6975 err = check_reg_arg(env, aux_reg, SRC_OP);
6979 if (is_pointer_value(env, aux_reg)) {
6980 verbose(env, "R%d leaks addr into mem\n", aux_reg);
6985 if (is_pointer_value(env, insn->src_reg)) {
6986 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6990 if (is_ctx_reg(env, insn->dst_reg) ||
6991 is_pkt_reg(env, insn->dst_reg) ||
6992 is_flow_key_reg(env, insn->dst_reg) ||
6993 is_sk_reg(env, insn->dst_reg)) {
6994 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6996 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7000 if (insn->imm & BPF_FETCH) {
7001 if (insn->imm == BPF_CMPXCHG)
7002 load_reg = BPF_REG_0;
7004 load_reg = insn->src_reg;
7006 /* check and record load of old value */
7007 err = check_reg_arg(env, load_reg, DST_OP);
7011 /* This instruction accesses a memory location but doesn't
7012 * actually load it into a register.
7017 /* Check whether we can read the memory, with second call for fetch
7018 * case to simulate the register fill.
7020 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7021 BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7022 if (!err && load_reg >= 0)
7023 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7024 BPF_SIZE(insn->code), BPF_READ, load_reg,
7029 /* Check whether we can write into the same memory. */
7030 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7031 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7037 /* When register 'regno' is used to read the stack (either directly or through
7038 * a helper function) make sure that it's within stack boundary and, depending
7039 * on the access type and privileges, that all elements of the stack are
7042 * 'off' includes 'regno->off', but not its dynamic part (if any).
7044 * All registers that have been spilled on the stack in the slots within the
7045 * read offsets are marked as read.
7047 static int check_stack_range_initialized(
7048 struct bpf_verifier_env *env, int regno, int off,
7049 int access_size, bool zero_size_allowed,
7050 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7052 struct bpf_reg_state *reg = reg_state(env, regno);
7053 struct bpf_func_state *state = func(env, reg);
7054 int err, min_off, max_off, i, j, slot, spi;
7055 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7056 enum bpf_access_type bounds_check_type;
7057 /* Some accesses can write anything into the stack, others are
7060 bool clobber = false;
7062 if (access_size == 0 && !zero_size_allowed) {
7063 verbose(env, "invalid zero-sized read\n");
7067 if (type == ACCESS_HELPER) {
7068 /* The bounds checks for writes are more permissive than for
7069 * reads. However, if raw_mode is not set, we'll do extra
7072 bounds_check_type = BPF_WRITE;
7075 bounds_check_type = BPF_READ;
7077 err = check_stack_access_within_bounds(env, regno, off, access_size,
7078 type, bounds_check_type);
7083 if (tnum_is_const(reg->var_off)) {
7084 min_off = max_off = reg->var_off.value + off;
7086 /* Variable offset is prohibited for unprivileged mode for
7087 * simplicity since it requires corresponding support in
7088 * Spectre masking for stack ALU.
7089 * See also retrieve_ptr_limit().
7091 if (!env->bypass_spec_v1) {
7094 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7095 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7096 regno, err_extra, tn_buf);
7099 /* Only initialized buffer on stack is allowed to be accessed
7100 * with variable offset. With uninitialized buffer it's hard to
7101 * guarantee that whole memory is marked as initialized on
7102 * helper return since specific bounds are unknown what may
7103 * cause uninitialized stack leaking.
7105 if (meta && meta->raw_mode)
7108 min_off = reg->smin_value + off;
7109 max_off = reg->smax_value + off;
7112 if (meta && meta->raw_mode) {
7113 /* Ensure we won't be overwriting dynptrs when simulating byte
7114 * by byte access in check_helper_call using meta.access_size.
7115 * This would be a problem if we have a helper in the future
7118 * helper(uninit_mem, len, dynptr)
7120 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7121 * may end up writing to dynptr itself when touching memory from
7122 * arg 1. This can be relaxed on a case by case basis for known
7123 * safe cases, but reject due to the possibilitiy of aliasing by
7126 for (i = min_off; i < max_off + access_size; i++) {
7127 int stack_off = -i - 1;
7130 /* raw_mode may write past allocated_stack */
7131 if (state->allocated_stack <= stack_off)
7133 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7134 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7138 meta->access_size = access_size;
7139 meta->regno = regno;
7143 for (i = min_off; i < max_off + access_size; i++) {
7147 spi = slot / BPF_REG_SIZE;
7148 if (state->allocated_stack <= slot) {
7149 verbose(env, "verifier bug: allocated_stack too small");
7153 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7154 if (*stype == STACK_MISC)
7156 if ((*stype == STACK_ZERO) ||
7157 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7159 /* helper can write anything into the stack */
7160 *stype = STACK_MISC;
7165 if (is_spilled_reg(&state->stack[spi]) &&
7166 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7167 env->allow_ptr_leaks)) {
7169 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7170 for (j = 0; j < BPF_REG_SIZE; j++)
7171 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7176 if (tnum_is_const(reg->var_off)) {
7177 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7178 err_extra, regno, min_off, i - min_off, access_size);
7182 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7183 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7184 err_extra, regno, tn_buf, i - min_off, access_size);
7188 /* reading any byte out of 8-byte 'spill_slot' will cause
7189 * the whole slot to be marked as 'read'
7191 mark_reg_read(env, &state->stack[spi].spilled_ptr,
7192 state->stack[spi].spilled_ptr.parent,
7194 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7195 * be sure that whether stack slot is written to or not. Hence,
7196 * we must still conservatively propagate reads upwards even if
7197 * helper may write to the entire memory range.
7203 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7204 int access_size, bool zero_size_allowed,
7205 struct bpf_call_arg_meta *meta)
7207 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7210 switch (base_type(reg->type)) {
7212 case PTR_TO_PACKET_META:
7213 return check_packet_access(env, regno, reg->off, access_size,
7215 case PTR_TO_MAP_KEY:
7216 if (meta && meta->raw_mode) {
7217 verbose(env, "R%d cannot write into %s\n", regno,
7218 reg_type_str(env, reg->type));
7221 return check_mem_region_access(env, regno, reg->off, access_size,
7222 reg->map_ptr->key_size, false);
7223 case PTR_TO_MAP_VALUE:
7224 if (check_map_access_type(env, regno, reg->off, access_size,
7225 meta && meta->raw_mode ? BPF_WRITE :
7228 return check_map_access(env, regno, reg->off, access_size,
7229 zero_size_allowed, ACCESS_HELPER);
7231 if (type_is_rdonly_mem(reg->type)) {
7232 if (meta && meta->raw_mode) {
7233 verbose(env, "R%d cannot write into %s\n", regno,
7234 reg_type_str(env, reg->type));
7238 return check_mem_region_access(env, regno, reg->off,
7239 access_size, reg->mem_size,
7242 if (type_is_rdonly_mem(reg->type)) {
7243 if (meta && meta->raw_mode) {
7244 verbose(env, "R%d cannot write into %s\n", regno,
7245 reg_type_str(env, reg->type));
7249 max_access = &env->prog->aux->max_rdonly_access;
7251 max_access = &env->prog->aux->max_rdwr_access;
7253 return check_buffer_access(env, reg, regno, reg->off,
7254 access_size, zero_size_allowed,
7257 return check_stack_range_initialized(
7259 regno, reg->off, access_size,
7260 zero_size_allowed, ACCESS_HELPER, meta);
7262 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7263 access_size, BPF_READ, -1);
7265 /* in case the function doesn't know how to access the context,
7266 * (because we are in a program of type SYSCALL for example), we
7267 * can not statically check its size.
7268 * Dynamically check it now.
7270 if (!env->ops->convert_ctx_access) {
7271 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7272 int offset = access_size - 1;
7274 /* Allow zero-byte read from PTR_TO_CTX */
7275 if (access_size == 0)
7276 return zero_size_allowed ? 0 : -EACCES;
7278 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7279 atype, -1, false, false);
7283 default: /* scalar_value or invalid ptr */
7284 /* Allow zero-byte read from NULL, regardless of pointer type */
7285 if (zero_size_allowed && access_size == 0 &&
7286 register_is_null(reg))
7289 verbose(env, "R%d type=%s ", regno,
7290 reg_type_str(env, reg->type));
7291 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7296 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7299 * @regno is the register containing the access size. regno-1 is the register
7300 * containing the pointer.
7302 static int check_mem_size_reg(struct bpf_verifier_env *env,
7303 struct bpf_reg_state *reg, u32 regno,
7304 bool zero_size_allowed,
7305 struct bpf_call_arg_meta *meta)
7309 /* This is used to refine r0 return value bounds for helpers
7310 * that enforce this value as an upper bound on return values.
7311 * See do_refine_retval_range() for helpers that can refine
7312 * the return value. C type of helper is u32 so we pull register
7313 * bound from umax_value however, if negative verifier errors
7314 * out. Only upper bounds can be learned because retval is an
7315 * int type and negative retvals are allowed.
7317 meta->msize_max_value = reg->umax_value;
7319 /* The register is SCALAR_VALUE; the access check
7320 * happens using its boundaries.
7322 if (!tnum_is_const(reg->var_off))
7323 /* For unprivileged variable accesses, disable raw
7324 * mode so that the program is required to
7325 * initialize all the memory that the helper could
7326 * just partially fill up.
7330 if (reg->smin_value < 0) {
7331 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7336 if (reg->umin_value == 0 && !zero_size_allowed) {
7337 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7338 regno, reg->umin_value, reg->umax_value);
7342 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7343 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7347 err = check_helper_mem_access(env, regno - 1,
7349 zero_size_allowed, meta);
7351 err = mark_chain_precision(env, regno);
7355 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7356 u32 regno, u32 mem_size)
7358 bool may_be_null = type_may_be_null(reg->type);
7359 struct bpf_reg_state saved_reg;
7360 struct bpf_call_arg_meta meta;
7363 if (register_is_null(reg))
7366 memset(&meta, 0, sizeof(meta));
7367 /* Assuming that the register contains a value check if the memory
7368 * access is safe. Temporarily save and restore the register's state as
7369 * the conversion shouldn't be visible to a caller.
7373 mark_ptr_not_null_reg(reg);
7376 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7377 /* Check access for BPF_WRITE */
7378 meta.raw_mode = true;
7379 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7387 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7390 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7391 bool may_be_null = type_may_be_null(mem_reg->type);
7392 struct bpf_reg_state saved_reg;
7393 struct bpf_call_arg_meta meta;
7396 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7398 memset(&meta, 0, sizeof(meta));
7401 saved_reg = *mem_reg;
7402 mark_ptr_not_null_reg(mem_reg);
7405 err = check_mem_size_reg(env, reg, regno, true, &meta);
7406 /* Check access for BPF_WRITE */
7407 meta.raw_mode = true;
7408 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7411 *mem_reg = saved_reg;
7415 /* Implementation details:
7416 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7417 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7418 * Two bpf_map_lookups (even with the same key) will have different reg->id.
7419 * Two separate bpf_obj_new will also have different reg->id.
7420 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7421 * clears reg->id after value_or_null->value transition, since the verifier only
7422 * cares about the range of access to valid map value pointer and doesn't care
7423 * about actual address of the map element.
7424 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7425 * reg->id > 0 after value_or_null->value transition. By doing so
7426 * two bpf_map_lookups will be considered two different pointers that
7427 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7428 * returned from bpf_obj_new.
7429 * The verifier allows taking only one bpf_spin_lock at a time to avoid
7431 * Since only one bpf_spin_lock is allowed the checks are simpler than
7432 * reg_is_refcounted() logic. The verifier needs to remember only
7433 * one spin_lock instead of array of acquired_refs.
7434 * cur_state->active_lock remembers which map value element or allocated
7435 * object got locked and clears it after bpf_spin_unlock.
7437 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7440 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7441 struct bpf_verifier_state *cur = env->cur_state;
7442 bool is_const = tnum_is_const(reg->var_off);
7443 u64 val = reg->var_off.value;
7444 struct bpf_map *map = NULL;
7445 struct btf *btf = NULL;
7446 struct btf_record *rec;
7450 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7454 if (reg->type == PTR_TO_MAP_VALUE) {
7458 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7466 rec = reg_btf_record(reg);
7467 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7468 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7469 map ? map->name : "kptr");
7472 if (rec->spin_lock_off != val + reg->off) {
7473 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7474 val + reg->off, rec->spin_lock_off);
7478 if (cur->active_lock.ptr) {
7480 "Locking two bpf_spin_locks are not allowed\n");
7484 cur->active_lock.ptr = map;
7486 cur->active_lock.ptr = btf;
7487 cur->active_lock.id = reg->id;
7496 if (!cur->active_lock.ptr) {
7497 verbose(env, "bpf_spin_unlock without taking a lock\n");
7500 if (cur->active_lock.ptr != ptr ||
7501 cur->active_lock.id != reg->id) {
7502 verbose(env, "bpf_spin_unlock of different lock\n");
7506 invalidate_non_owning_refs(env);
7508 cur->active_lock.ptr = NULL;
7509 cur->active_lock.id = 0;
7514 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7515 struct bpf_call_arg_meta *meta)
7517 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7518 bool is_const = tnum_is_const(reg->var_off);
7519 struct bpf_map *map = reg->map_ptr;
7520 u64 val = reg->var_off.value;
7524 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7529 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7533 if (!btf_record_has_field(map->record, BPF_TIMER)) {
7534 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7537 if (map->record->timer_off != val + reg->off) {
7538 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7539 val + reg->off, map->record->timer_off);
7542 if (meta->map_ptr) {
7543 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7546 meta->map_uid = reg->map_uid;
7547 meta->map_ptr = map;
7551 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7552 struct bpf_call_arg_meta *meta)
7554 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7555 struct bpf_map *map_ptr = reg->map_ptr;
7556 struct btf_field *kptr_field;
7559 if (!tnum_is_const(reg->var_off)) {
7561 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7565 if (!map_ptr->btf) {
7566 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7570 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7571 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7575 meta->map_ptr = map_ptr;
7576 kptr_off = reg->off + reg->var_off.value;
7577 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7579 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7582 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7583 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7586 meta->kptr_field = kptr_field;
7590 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7591 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7593 * In both cases we deal with the first 8 bytes, but need to mark the next 8
7594 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7595 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7597 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7598 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7599 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7600 * mutate the view of the dynptr and also possibly destroy it. In the latter
7601 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7602 * memory that dynptr points to.
7604 * The verifier will keep track both levels of mutation (bpf_dynptr's in
7605 * reg->type and the memory's in reg->dynptr.type), but there is no support for
7606 * readonly dynptr view yet, hence only the first case is tracked and checked.
7608 * This is consistent with how C applies the const modifier to a struct object,
7609 * where the pointer itself inside bpf_dynptr becomes const but not what it
7612 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7613 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7615 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7616 enum bpf_arg_type arg_type, int clone_ref_obj_id)
7618 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7621 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7622 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7624 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7625 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7629 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
7630 * constructing a mutable bpf_dynptr object.
7632 * Currently, this is only possible with PTR_TO_STACK
7633 * pointing to a region of at least 16 bytes which doesn't
7634 * contain an existing bpf_dynptr.
7636 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7637 * mutated or destroyed. However, the memory it points to
7640 * None - Points to a initialized dynptr that can be mutated and
7641 * destroyed, including mutation of the memory it points
7644 if (arg_type & MEM_UNINIT) {
7647 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7648 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7652 /* we write BPF_DW bits (8 bytes) at a time */
7653 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7654 err = check_mem_access(env, insn_idx, regno,
7655 i, BPF_DW, BPF_WRITE, -1, false, false);
7660 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7661 } else /* MEM_RDONLY and None case from above */ {
7662 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7663 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7664 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7668 if (!is_dynptr_reg_valid_init(env, reg)) {
7670 "Expected an initialized dynptr as arg #%d\n",
7675 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7676 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7678 "Expected a dynptr of type %s as arg #%d\n",
7679 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7683 err = mark_dynptr_read(env, reg);
7688 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7690 struct bpf_func_state *state = func(env, reg);
7692 return state->stack[spi].spilled_ptr.ref_obj_id;
7695 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7697 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7700 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7702 return meta->kfunc_flags & KF_ITER_NEW;
7705 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7707 return meta->kfunc_flags & KF_ITER_NEXT;
7710 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7712 return meta->kfunc_flags & KF_ITER_DESTROY;
7715 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7717 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7718 * kfunc is iter state pointer
7720 return arg == 0 && is_iter_kfunc(meta);
7723 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7724 struct bpf_kfunc_call_arg_meta *meta)
7726 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7727 const struct btf_type *t;
7728 const struct btf_param *arg;
7729 int spi, err, i, nr_slots;
7732 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7733 arg = &btf_params(meta->func_proto)[0];
7734 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
7735 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
7736 nr_slots = t->size / BPF_REG_SIZE;
7738 if (is_iter_new_kfunc(meta)) {
7739 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7740 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7741 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7742 iter_type_str(meta->btf, btf_id), regno);
7746 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7747 err = check_mem_access(env, insn_idx, regno,
7748 i, BPF_DW, BPF_WRITE, -1, false, false);
7753 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7757 /* iter_next() or iter_destroy() expect initialized iter state*/
7758 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7763 verbose(env, "expected an initialized iter_%s as arg #%d\n",
7764 iter_type_str(meta->btf, btf_id), regno);
7767 verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7773 spi = iter_get_spi(env, reg, nr_slots);
7777 err = mark_iter_read(env, reg, spi, nr_slots);
7781 /* remember meta->iter info for process_iter_next_call() */
7782 meta->iter.spi = spi;
7783 meta->iter.frameno = reg->frameno;
7784 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7786 if (is_iter_destroy_kfunc(meta)) {
7787 err = unmark_stack_slots_iter(env, reg, nr_slots);
7796 /* Look for a previous loop entry at insn_idx: nearest parent state
7797 * stopped at insn_idx with callsites matching those in cur->frame.
7799 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7800 struct bpf_verifier_state *cur,
7803 struct bpf_verifier_state_list *sl;
7804 struct bpf_verifier_state *st;
7806 /* Explored states are pushed in stack order, most recent states come first */
7807 sl = *explored_state(env, insn_idx);
7808 for (; sl; sl = sl->next) {
7809 /* If st->branches != 0 state is a part of current DFS verification path,
7810 * hence cur & st for a loop.
7813 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7814 st->dfs_depth < cur->dfs_depth)
7821 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7822 static bool regs_exact(const struct bpf_reg_state *rold,
7823 const struct bpf_reg_state *rcur,
7824 struct bpf_idmap *idmap);
7826 static void maybe_widen_reg(struct bpf_verifier_env *env,
7827 struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7828 struct bpf_idmap *idmap)
7830 if (rold->type != SCALAR_VALUE)
7832 if (rold->type != rcur->type)
7834 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7836 __mark_reg_unknown(env, rcur);
7839 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7840 struct bpf_verifier_state *old,
7841 struct bpf_verifier_state *cur)
7843 struct bpf_func_state *fold, *fcur;
7846 reset_idmap_scratch(env);
7847 for (fr = old->curframe; fr >= 0; fr--) {
7848 fold = old->frame[fr];
7849 fcur = cur->frame[fr];
7851 for (i = 0; i < MAX_BPF_REG; i++)
7852 maybe_widen_reg(env,
7855 &env->idmap_scratch);
7857 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7858 if (!is_spilled_reg(&fold->stack[i]) ||
7859 !is_spilled_reg(&fcur->stack[i]))
7862 maybe_widen_reg(env,
7863 &fold->stack[i].spilled_ptr,
7864 &fcur->stack[i].spilled_ptr,
7865 &env->idmap_scratch);
7871 /* process_iter_next_call() is called when verifier gets to iterator's next
7872 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7873 * to it as just "iter_next()" in comments below.
7875 * BPF verifier relies on a crucial contract for any iter_next()
7876 * implementation: it should *eventually* return NULL, and once that happens
7877 * it should keep returning NULL. That is, once iterator exhausts elements to
7878 * iterate, it should never reset or spuriously return new elements.
7880 * With the assumption of such contract, process_iter_next_call() simulates
7881 * a fork in the verifier state to validate loop logic correctness and safety
7882 * without having to simulate infinite amount of iterations.
7884 * In current state, we first assume that iter_next() returned NULL and
7885 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7886 * conditions we should not form an infinite loop and should eventually reach
7889 * Besides that, we also fork current state and enqueue it for later
7890 * verification. In a forked state we keep iterator state as ACTIVE
7891 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7892 * also bump iteration depth to prevent erroneous infinite loop detection
7893 * later on (see iter_active_depths_differ() comment for details). In this
7894 * state we assume that we'll eventually loop back to another iter_next()
7895 * calls (it could be in exactly same location or in some other instruction,
7896 * it doesn't matter, we don't make any unnecessary assumptions about this,
7897 * everything revolves around iterator state in a stack slot, not which
7898 * instruction is calling iter_next()). When that happens, we either will come
7899 * to iter_next() with equivalent state and can conclude that next iteration
7900 * will proceed in exactly the same way as we just verified, so it's safe to
7901 * assume that loop converges. If not, we'll go on another iteration
7902 * simulation with a different input state, until all possible starting states
7903 * are validated or we reach maximum number of instructions limit.
7905 * This way, we will either exhaustively discover all possible input states
7906 * that iterator loop can start with and eventually will converge, or we'll
7907 * effectively regress into bounded loop simulation logic and either reach
7908 * maximum number of instructions if loop is not provably convergent, or there
7909 * is some statically known limit on number of iterations (e.g., if there is
7910 * an explicit `if n > 100 then break;` statement somewhere in the loop).
7912 * Iteration convergence logic in is_state_visited() relies on exact
7913 * states comparison, which ignores read and precision marks.
7914 * This is necessary because read and precision marks are not finalized
7915 * while in the loop. Exact comparison might preclude convergence for
7916 * simple programs like below:
7919 * while(iter_next(&it))
7922 * At each iteration step i++ would produce a new distinct state and
7923 * eventually instruction processing limit would be reached.
7925 * To avoid such behavior speculatively forget (widen) range for
7926 * imprecise scalar registers, if those registers were not precise at the
7927 * end of the previous iteration and do not match exactly.
7929 * This is a conservative heuristic that allows to verify wide range of programs,
7930 * however it precludes verification of programs that conjure an
7931 * imprecise value on the first loop iteration and use it as precise on a second.
7932 * For example, the following safe program would fail to verify:
7934 * struct bpf_num_iter it;
7937 * bpf_iter_num_new(&it, 0, 10);
7938 * while (bpf_iter_num_next(&it)) {
7941 * i = 7; // Because i changed verifier would forget
7942 * // it's range on second loop entry.
7944 * arr[i] = 42; // This would fail to verify.
7947 * bpf_iter_num_destroy(&it);
7949 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7950 struct bpf_kfunc_call_arg_meta *meta)
7952 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7953 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7954 struct bpf_reg_state *cur_iter, *queued_iter;
7955 int iter_frameno = meta->iter.frameno;
7956 int iter_spi = meta->iter.spi;
7958 BTF_TYPE_EMIT(struct bpf_iter);
7960 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7962 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7963 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7964 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7965 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7969 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7970 /* Because iter_next() call is a checkpoint is_state_visitied()
7971 * should guarantee parent state with same call sites and insn_idx.
7973 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7974 !same_callsites(cur_st->parent, cur_st)) {
7975 verbose(env, "bug: bad parent state for iter next call");
7978 /* Note cur_st->parent in the call below, it is necessary to skip
7979 * checkpoint created for cur_st by is_state_visited()
7980 * right at this instruction.
7982 prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7983 /* branch out active iter state */
7984 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7988 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7989 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7990 queued_iter->iter.depth++;
7992 widen_imprecise_scalars(env, prev_st, queued_st);
7994 queued_fr = queued_st->frame[queued_st->curframe];
7995 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7998 /* switch to DRAINED state, but keep the depth unchanged */
7999 /* mark current iter state as drained and assume returned NULL */
8000 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8001 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8006 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8008 return type == ARG_CONST_SIZE ||
8009 type == ARG_CONST_SIZE_OR_ZERO;
8012 static bool arg_type_is_release(enum bpf_arg_type type)
8014 return type & OBJ_RELEASE;
8017 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8019 return base_type(type) == ARG_PTR_TO_DYNPTR;
8022 static int int_ptr_type_to_size(enum bpf_arg_type type)
8024 if (type == ARG_PTR_TO_INT)
8026 else if (type == ARG_PTR_TO_LONG)
8032 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8033 const struct bpf_call_arg_meta *meta,
8034 enum bpf_arg_type *arg_type)
8036 if (!meta->map_ptr) {
8037 /* kernel subsystem misconfigured verifier */
8038 verbose(env, "invalid map_ptr to access map->type\n");
8042 switch (meta->map_ptr->map_type) {
8043 case BPF_MAP_TYPE_SOCKMAP:
8044 case BPF_MAP_TYPE_SOCKHASH:
8045 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8046 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8048 verbose(env, "invalid arg_type for sockmap/sockhash\n");
8052 case BPF_MAP_TYPE_BLOOM_FILTER:
8053 if (meta->func_id == BPF_FUNC_map_peek_elem)
8054 *arg_type = ARG_PTR_TO_MAP_VALUE;
8062 struct bpf_reg_types {
8063 const enum bpf_reg_type types[10];
8067 static const struct bpf_reg_types sock_types = {
8077 static const struct bpf_reg_types btf_id_sock_common_types = {
8084 PTR_TO_BTF_ID | PTR_TRUSTED,
8086 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8090 static const struct bpf_reg_types mem_types = {
8098 PTR_TO_MEM | MEM_RINGBUF,
8100 PTR_TO_BTF_ID | PTR_TRUSTED,
8104 static const struct bpf_reg_types int_ptr_types = {
8114 static const struct bpf_reg_types spin_lock_types = {
8117 PTR_TO_BTF_ID | MEM_ALLOC,
8121 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8122 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8123 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8124 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8125 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8126 static const struct bpf_reg_types btf_ptr_types = {
8129 PTR_TO_BTF_ID | PTR_TRUSTED,
8130 PTR_TO_BTF_ID | MEM_RCU,
8133 static const struct bpf_reg_types percpu_btf_ptr_types = {
8135 PTR_TO_BTF_ID | MEM_PERCPU,
8136 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8137 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8140 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8141 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8142 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8143 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8144 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8145 static const struct bpf_reg_types dynptr_types = {
8148 CONST_PTR_TO_DYNPTR,
8152 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8153 [ARG_PTR_TO_MAP_KEY] = &mem_types,
8154 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
8155 [ARG_CONST_SIZE] = &scalar_types,
8156 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
8157 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
8158 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
8159 [ARG_PTR_TO_CTX] = &context_types,
8160 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
8162 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
8164 [ARG_PTR_TO_SOCKET] = &fullsock_types,
8165 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
8166 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
8167 [ARG_PTR_TO_MEM] = &mem_types,
8168 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
8169 [ARG_PTR_TO_INT] = &int_ptr_types,
8170 [ARG_PTR_TO_LONG] = &int_ptr_types,
8171 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
8172 [ARG_PTR_TO_FUNC] = &func_ptr_types,
8173 [ARG_PTR_TO_STACK] = &stack_ptr_types,
8174 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
8175 [ARG_PTR_TO_TIMER] = &timer_types,
8176 [ARG_PTR_TO_KPTR] = &kptr_types,
8177 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
8180 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8181 enum bpf_arg_type arg_type,
8182 const u32 *arg_btf_id,
8183 struct bpf_call_arg_meta *meta)
8185 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8186 enum bpf_reg_type expected, type = reg->type;
8187 const struct bpf_reg_types *compatible;
8190 compatible = compatible_reg_types[base_type(arg_type)];
8192 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8196 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8197 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8199 * Same for MAYBE_NULL:
8201 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8202 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8204 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8206 * Therefore we fold these flags depending on the arg_type before comparison.
8208 if (arg_type & MEM_RDONLY)
8209 type &= ~MEM_RDONLY;
8210 if (arg_type & PTR_MAYBE_NULL)
8211 type &= ~PTR_MAYBE_NULL;
8212 if (base_type(arg_type) == ARG_PTR_TO_MEM)
8213 type &= ~DYNPTR_TYPE_FLAG_MASK;
8215 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) {
8217 type &= ~MEM_PERCPU;
8220 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8221 expected = compatible->types[i];
8222 if (expected == NOT_INIT)
8225 if (type == expected)
8229 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8230 for (j = 0; j + 1 < i; j++)
8231 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8232 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8236 if (base_type(reg->type) != PTR_TO_BTF_ID)
8239 if (compatible == &mem_types) {
8240 if (!(arg_type & MEM_RDONLY)) {
8242 "%s() may write into memory pointed by R%d type=%s\n",
8243 func_id_name(meta->func_id),
8244 regno, reg_type_str(env, reg->type));
8250 switch ((int)reg->type) {
8252 case PTR_TO_BTF_ID | PTR_TRUSTED:
8253 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
8254 case PTR_TO_BTF_ID | MEM_RCU:
8255 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8256 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8258 /* For bpf_sk_release, it needs to match against first member
8259 * 'struct sock_common', hence make an exception for it. This
8260 * allows bpf_sk_release to work for multiple socket types.
8262 bool strict_type_match = arg_type_is_release(arg_type) &&
8263 meta->func_id != BPF_FUNC_sk_release;
8265 if (type_may_be_null(reg->type) &&
8266 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8267 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8272 if (!compatible->btf_id) {
8273 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8276 arg_btf_id = compatible->btf_id;
8279 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8280 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8283 if (arg_btf_id == BPF_PTR_POISON) {
8284 verbose(env, "verifier internal error:");
8285 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8290 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8291 btf_vmlinux, *arg_btf_id,
8292 strict_type_match)) {
8293 verbose(env, "R%d is of type %s but %s is expected\n",
8294 regno, btf_type_name(reg->btf, reg->btf_id),
8295 btf_type_name(btf_vmlinux, *arg_btf_id));
8301 case PTR_TO_BTF_ID | MEM_ALLOC:
8302 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8303 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8304 meta->func_id != BPF_FUNC_kptr_xchg) {
8305 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8308 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8309 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8313 case PTR_TO_BTF_ID | MEM_PERCPU:
8314 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8315 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8316 /* Handled by helper specific checks */
8319 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8325 static struct btf_field *
8326 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8328 struct btf_field *field;
8329 struct btf_record *rec;
8331 rec = reg_btf_record(reg);
8335 field = btf_record_find(rec, off, fields);
8342 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8343 const struct bpf_reg_state *reg, int regno,
8344 enum bpf_arg_type arg_type)
8346 u32 type = reg->type;
8348 /* When referenced register is passed to release function, its fixed
8351 * We will check arg_type_is_release reg has ref_obj_id when storing
8352 * meta->release_regno.
8354 if (arg_type_is_release(arg_type)) {
8355 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8356 * may not directly point to the object being released, but to
8357 * dynptr pointing to such object, which might be at some offset
8358 * on the stack. In that case, we simply to fallback to the
8361 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8364 /* Doing check_ptr_off_reg check for the offset will catch this
8365 * because fixed_off_ok is false, but checking here allows us
8366 * to give the user a better error message.
8369 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8373 return __check_ptr_off_reg(env, reg, regno, false);
8377 /* Pointer types where both fixed and variable offset is explicitly allowed: */
8380 case PTR_TO_PACKET_META:
8381 case PTR_TO_MAP_KEY:
8382 case PTR_TO_MAP_VALUE:
8384 case PTR_TO_MEM | MEM_RDONLY:
8385 case PTR_TO_MEM | MEM_RINGBUF:
8387 case PTR_TO_BUF | MEM_RDONLY:
8390 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8394 case PTR_TO_BTF_ID | MEM_ALLOC:
8395 case PTR_TO_BTF_ID | PTR_TRUSTED:
8396 case PTR_TO_BTF_ID | MEM_RCU:
8397 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8398 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8399 /* When referenced PTR_TO_BTF_ID is passed to release function,
8400 * its fixed offset must be 0. In the other cases, fixed offset
8401 * can be non-zero. This was already checked above. So pass
8402 * fixed_off_ok as true to allow fixed offset for all other
8403 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8404 * still need to do checks instead of returning.
8406 return __check_ptr_off_reg(env, reg, regno, true);
8408 return __check_ptr_off_reg(env, reg, regno, false);
8412 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8413 const struct bpf_func_proto *fn,
8414 struct bpf_reg_state *regs)
8416 struct bpf_reg_state *state = NULL;
8419 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8420 if (arg_type_is_dynptr(fn->arg_type[i])) {
8422 verbose(env, "verifier internal error: multiple dynptr args\n");
8425 state = ®s[BPF_REG_1 + i];
8429 verbose(env, "verifier internal error: no dynptr arg found\n");
8434 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8436 struct bpf_func_state *state = func(env, reg);
8439 if (reg->type == CONST_PTR_TO_DYNPTR)
8441 spi = dynptr_get_spi(env, reg);
8444 return state->stack[spi].spilled_ptr.id;
8447 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8449 struct bpf_func_state *state = func(env, reg);
8452 if (reg->type == CONST_PTR_TO_DYNPTR)
8453 return reg->ref_obj_id;
8454 spi = dynptr_get_spi(env, reg);
8457 return state->stack[spi].spilled_ptr.ref_obj_id;
8460 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8461 struct bpf_reg_state *reg)
8463 struct bpf_func_state *state = func(env, reg);
8466 if (reg->type == CONST_PTR_TO_DYNPTR)
8467 return reg->dynptr.type;
8469 spi = __get_spi(reg->off);
8471 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8472 return BPF_DYNPTR_TYPE_INVALID;
8475 return state->stack[spi].spilled_ptr.dynptr.type;
8478 static int check_reg_const_str(struct bpf_verifier_env *env,
8479 struct bpf_reg_state *reg, u32 regno)
8481 struct bpf_map *map = reg->map_ptr;
8487 if (reg->type != PTR_TO_MAP_VALUE)
8490 if (!bpf_map_is_rdonly(map)) {
8491 verbose(env, "R%d does not point to a readonly map'\n", regno);
8495 if (!tnum_is_const(reg->var_off)) {
8496 verbose(env, "R%d is not a constant address'\n", regno);
8500 if (!map->ops->map_direct_value_addr) {
8501 verbose(env, "no direct value access support for this map type\n");
8505 err = check_map_access(env, regno, reg->off,
8506 map->value_size - reg->off, false,
8511 map_off = reg->off + reg->var_off.value;
8512 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8514 verbose(env, "direct value access on string failed\n");
8518 str_ptr = (char *)(long)(map_addr);
8519 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8520 verbose(env, "string is not zero-terminated\n");
8526 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8527 struct bpf_call_arg_meta *meta,
8528 const struct bpf_func_proto *fn,
8531 u32 regno = BPF_REG_1 + arg;
8532 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8533 enum bpf_arg_type arg_type = fn->arg_type[arg];
8534 enum bpf_reg_type type = reg->type;
8535 u32 *arg_btf_id = NULL;
8538 if (arg_type == ARG_DONTCARE)
8541 err = check_reg_arg(env, regno, SRC_OP);
8545 if (arg_type == ARG_ANYTHING) {
8546 if (is_pointer_value(env, regno)) {
8547 verbose(env, "R%d leaks addr into helper function\n",
8554 if (type_is_pkt_pointer(type) &&
8555 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8556 verbose(env, "helper access to the packet is not allowed\n");
8560 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8561 err = resolve_map_arg_type(env, meta, &arg_type);
8566 if (register_is_null(reg) && type_may_be_null(arg_type))
8567 /* A NULL register has a SCALAR_VALUE type, so skip
8570 goto skip_type_check;
8572 /* arg_btf_id and arg_size are in a union. */
8573 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8574 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8575 arg_btf_id = fn->arg_btf_id[arg];
8577 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8581 err = check_func_arg_reg_off(env, reg, regno, arg_type);
8586 if (arg_type_is_release(arg_type)) {
8587 if (arg_type_is_dynptr(arg_type)) {
8588 struct bpf_func_state *state = func(env, reg);
8591 /* Only dynptr created on stack can be released, thus
8592 * the get_spi and stack state checks for spilled_ptr
8593 * should only be done before process_dynptr_func for
8596 if (reg->type == PTR_TO_STACK) {
8597 spi = dynptr_get_spi(env, reg);
8598 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8599 verbose(env, "arg %d is an unacquired reference\n", regno);
8603 verbose(env, "cannot release unowned const bpf_dynptr\n");
8606 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8607 verbose(env, "R%d must be referenced when passed to release function\n",
8611 if (meta->release_regno) {
8612 verbose(env, "verifier internal error: more than one release argument\n");
8615 meta->release_regno = regno;
8618 if (reg->ref_obj_id) {
8619 if (meta->ref_obj_id) {
8620 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8621 regno, reg->ref_obj_id,
8625 meta->ref_obj_id = reg->ref_obj_id;
8628 switch (base_type(arg_type)) {
8629 case ARG_CONST_MAP_PTR:
8630 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8631 if (meta->map_ptr) {
8632 /* Use map_uid (which is unique id of inner map) to reject:
8633 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8634 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8635 * if (inner_map1 && inner_map2) {
8636 * timer = bpf_map_lookup_elem(inner_map1);
8638 * // mismatch would have been allowed
8639 * bpf_timer_init(timer, inner_map2);
8642 * Comparing map_ptr is enough to distinguish normal and outer maps.
8644 if (meta->map_ptr != reg->map_ptr ||
8645 meta->map_uid != reg->map_uid) {
8647 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8648 meta->map_uid, reg->map_uid);
8652 meta->map_ptr = reg->map_ptr;
8653 meta->map_uid = reg->map_uid;
8655 case ARG_PTR_TO_MAP_KEY:
8656 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8657 * check that [key, key + map->key_size) are within
8658 * stack limits and initialized
8660 if (!meta->map_ptr) {
8661 /* in function declaration map_ptr must come before
8662 * map_key, so that it's verified and known before
8663 * we have to check map_key here. Otherwise it means
8664 * that kernel subsystem misconfigured verifier
8666 verbose(env, "invalid map_ptr to access map->key\n");
8669 err = check_helper_mem_access(env, regno,
8670 meta->map_ptr->key_size, false,
8673 case ARG_PTR_TO_MAP_VALUE:
8674 if (type_may_be_null(arg_type) && register_is_null(reg))
8677 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8678 * check [value, value + map->value_size) validity
8680 if (!meta->map_ptr) {
8681 /* kernel subsystem misconfigured verifier */
8682 verbose(env, "invalid map_ptr to access map->value\n");
8685 meta->raw_mode = arg_type & MEM_UNINIT;
8686 err = check_helper_mem_access(env, regno,
8687 meta->map_ptr->value_size, false,
8690 case ARG_PTR_TO_PERCPU_BTF_ID:
8692 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8695 meta->ret_btf = reg->btf;
8696 meta->ret_btf_id = reg->btf_id;
8698 case ARG_PTR_TO_SPIN_LOCK:
8699 if (in_rbtree_lock_required_cb(env)) {
8700 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8703 if (meta->func_id == BPF_FUNC_spin_lock) {
8704 err = process_spin_lock(env, regno, true);
8707 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8708 err = process_spin_lock(env, regno, false);
8712 verbose(env, "verifier internal error\n");
8716 case ARG_PTR_TO_TIMER:
8717 err = process_timer_func(env, regno, meta);
8721 case ARG_PTR_TO_FUNC:
8722 meta->subprogno = reg->subprogno;
8724 case ARG_PTR_TO_MEM:
8725 /* The access to this pointer is only checked when we hit the
8726 * next is_mem_size argument below.
8728 meta->raw_mode = arg_type & MEM_UNINIT;
8729 if (arg_type & MEM_FIXED_SIZE) {
8730 err = check_helper_mem_access(env, regno,
8731 fn->arg_size[arg], false,
8735 case ARG_CONST_SIZE:
8736 err = check_mem_size_reg(env, reg, regno, false, meta);
8738 case ARG_CONST_SIZE_OR_ZERO:
8739 err = check_mem_size_reg(env, reg, regno, true, meta);
8741 case ARG_PTR_TO_DYNPTR:
8742 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8746 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8747 if (!tnum_is_const(reg->var_off)) {
8748 verbose(env, "R%d is not a known constant'\n",
8752 meta->mem_size = reg->var_off.value;
8753 err = mark_chain_precision(env, regno);
8757 case ARG_PTR_TO_INT:
8758 case ARG_PTR_TO_LONG:
8760 int size = int_ptr_type_to_size(arg_type);
8762 err = check_helper_mem_access(env, regno, size, false, meta);
8765 err = check_ptr_alignment(env, reg, 0, size, true);
8768 case ARG_PTR_TO_CONST_STR:
8770 err = check_reg_const_str(env, reg, regno);
8775 case ARG_PTR_TO_KPTR:
8776 err = process_kptr_func(env, regno, meta);
8785 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8787 enum bpf_attach_type eatype = env->prog->expected_attach_type;
8788 enum bpf_prog_type type = resolve_prog_type(env->prog);
8790 if (func_id != BPF_FUNC_map_update_elem)
8793 /* It's not possible to get access to a locked struct sock in these
8794 * contexts, so updating is safe.
8797 case BPF_PROG_TYPE_TRACING:
8798 if (eatype == BPF_TRACE_ITER)
8801 case BPF_PROG_TYPE_SOCKET_FILTER:
8802 case BPF_PROG_TYPE_SCHED_CLS:
8803 case BPF_PROG_TYPE_SCHED_ACT:
8804 case BPF_PROG_TYPE_XDP:
8805 case BPF_PROG_TYPE_SK_REUSEPORT:
8806 case BPF_PROG_TYPE_FLOW_DISSECTOR:
8807 case BPF_PROG_TYPE_SK_LOOKUP:
8813 verbose(env, "cannot update sockmap in this context\n");
8817 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8819 return env->prog->jit_requested &&
8820 bpf_jit_supports_subprog_tailcalls();
8823 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8824 struct bpf_map *map, int func_id)
8829 /* We need a two way check, first is from map perspective ... */
8830 switch (map->map_type) {
8831 case BPF_MAP_TYPE_PROG_ARRAY:
8832 if (func_id != BPF_FUNC_tail_call)
8835 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8836 if (func_id != BPF_FUNC_perf_event_read &&
8837 func_id != BPF_FUNC_perf_event_output &&
8838 func_id != BPF_FUNC_skb_output &&
8839 func_id != BPF_FUNC_perf_event_read_value &&
8840 func_id != BPF_FUNC_xdp_output)
8843 case BPF_MAP_TYPE_RINGBUF:
8844 if (func_id != BPF_FUNC_ringbuf_output &&
8845 func_id != BPF_FUNC_ringbuf_reserve &&
8846 func_id != BPF_FUNC_ringbuf_query &&
8847 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8848 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8849 func_id != BPF_FUNC_ringbuf_discard_dynptr)
8852 case BPF_MAP_TYPE_USER_RINGBUF:
8853 if (func_id != BPF_FUNC_user_ringbuf_drain)
8856 case BPF_MAP_TYPE_STACK_TRACE:
8857 if (func_id != BPF_FUNC_get_stackid)
8860 case BPF_MAP_TYPE_CGROUP_ARRAY:
8861 if (func_id != BPF_FUNC_skb_under_cgroup &&
8862 func_id != BPF_FUNC_current_task_under_cgroup)
8865 case BPF_MAP_TYPE_CGROUP_STORAGE:
8866 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8867 if (func_id != BPF_FUNC_get_local_storage)
8870 case BPF_MAP_TYPE_DEVMAP:
8871 case BPF_MAP_TYPE_DEVMAP_HASH:
8872 if (func_id != BPF_FUNC_redirect_map &&
8873 func_id != BPF_FUNC_map_lookup_elem)
8876 /* Restrict bpf side of cpumap and xskmap, open when use-cases
8879 case BPF_MAP_TYPE_CPUMAP:
8880 if (func_id != BPF_FUNC_redirect_map)
8883 case BPF_MAP_TYPE_XSKMAP:
8884 if (func_id != BPF_FUNC_redirect_map &&
8885 func_id != BPF_FUNC_map_lookup_elem)
8888 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8889 case BPF_MAP_TYPE_HASH_OF_MAPS:
8890 if (func_id != BPF_FUNC_map_lookup_elem)
8893 case BPF_MAP_TYPE_SOCKMAP:
8894 if (func_id != BPF_FUNC_sk_redirect_map &&
8895 func_id != BPF_FUNC_sock_map_update &&
8896 func_id != BPF_FUNC_map_delete_elem &&
8897 func_id != BPF_FUNC_msg_redirect_map &&
8898 func_id != BPF_FUNC_sk_select_reuseport &&
8899 func_id != BPF_FUNC_map_lookup_elem &&
8900 !may_update_sockmap(env, func_id))
8903 case BPF_MAP_TYPE_SOCKHASH:
8904 if (func_id != BPF_FUNC_sk_redirect_hash &&
8905 func_id != BPF_FUNC_sock_hash_update &&
8906 func_id != BPF_FUNC_map_delete_elem &&
8907 func_id != BPF_FUNC_msg_redirect_hash &&
8908 func_id != BPF_FUNC_sk_select_reuseport &&
8909 func_id != BPF_FUNC_map_lookup_elem &&
8910 !may_update_sockmap(env, func_id))
8913 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8914 if (func_id != BPF_FUNC_sk_select_reuseport)
8917 case BPF_MAP_TYPE_QUEUE:
8918 case BPF_MAP_TYPE_STACK:
8919 if (func_id != BPF_FUNC_map_peek_elem &&
8920 func_id != BPF_FUNC_map_pop_elem &&
8921 func_id != BPF_FUNC_map_push_elem)
8924 case BPF_MAP_TYPE_SK_STORAGE:
8925 if (func_id != BPF_FUNC_sk_storage_get &&
8926 func_id != BPF_FUNC_sk_storage_delete &&
8927 func_id != BPF_FUNC_kptr_xchg)
8930 case BPF_MAP_TYPE_INODE_STORAGE:
8931 if (func_id != BPF_FUNC_inode_storage_get &&
8932 func_id != BPF_FUNC_inode_storage_delete &&
8933 func_id != BPF_FUNC_kptr_xchg)
8936 case BPF_MAP_TYPE_TASK_STORAGE:
8937 if (func_id != BPF_FUNC_task_storage_get &&
8938 func_id != BPF_FUNC_task_storage_delete &&
8939 func_id != BPF_FUNC_kptr_xchg)
8942 case BPF_MAP_TYPE_CGRP_STORAGE:
8943 if (func_id != BPF_FUNC_cgrp_storage_get &&
8944 func_id != BPF_FUNC_cgrp_storage_delete &&
8945 func_id != BPF_FUNC_kptr_xchg)
8948 case BPF_MAP_TYPE_BLOOM_FILTER:
8949 if (func_id != BPF_FUNC_map_peek_elem &&
8950 func_id != BPF_FUNC_map_push_elem)
8957 /* ... and second from the function itself. */
8959 case BPF_FUNC_tail_call:
8960 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8962 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8963 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8967 case BPF_FUNC_perf_event_read:
8968 case BPF_FUNC_perf_event_output:
8969 case BPF_FUNC_perf_event_read_value:
8970 case BPF_FUNC_skb_output:
8971 case BPF_FUNC_xdp_output:
8972 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8975 case BPF_FUNC_ringbuf_output:
8976 case BPF_FUNC_ringbuf_reserve:
8977 case BPF_FUNC_ringbuf_query:
8978 case BPF_FUNC_ringbuf_reserve_dynptr:
8979 case BPF_FUNC_ringbuf_submit_dynptr:
8980 case BPF_FUNC_ringbuf_discard_dynptr:
8981 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8984 case BPF_FUNC_user_ringbuf_drain:
8985 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8988 case BPF_FUNC_get_stackid:
8989 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8992 case BPF_FUNC_current_task_under_cgroup:
8993 case BPF_FUNC_skb_under_cgroup:
8994 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8997 case BPF_FUNC_redirect_map:
8998 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8999 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9000 map->map_type != BPF_MAP_TYPE_CPUMAP &&
9001 map->map_type != BPF_MAP_TYPE_XSKMAP)
9004 case BPF_FUNC_sk_redirect_map:
9005 case BPF_FUNC_msg_redirect_map:
9006 case BPF_FUNC_sock_map_update:
9007 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9010 case BPF_FUNC_sk_redirect_hash:
9011 case BPF_FUNC_msg_redirect_hash:
9012 case BPF_FUNC_sock_hash_update:
9013 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
9016 case BPF_FUNC_get_local_storage:
9017 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9018 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9021 case BPF_FUNC_sk_select_reuseport:
9022 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9023 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9024 map->map_type != BPF_MAP_TYPE_SOCKHASH)
9027 case BPF_FUNC_map_pop_elem:
9028 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9029 map->map_type != BPF_MAP_TYPE_STACK)
9032 case BPF_FUNC_map_peek_elem:
9033 case BPF_FUNC_map_push_elem:
9034 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9035 map->map_type != BPF_MAP_TYPE_STACK &&
9036 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9039 case BPF_FUNC_map_lookup_percpu_elem:
9040 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9041 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9042 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9045 case BPF_FUNC_sk_storage_get:
9046 case BPF_FUNC_sk_storage_delete:
9047 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9050 case BPF_FUNC_inode_storage_get:
9051 case BPF_FUNC_inode_storage_delete:
9052 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9055 case BPF_FUNC_task_storage_get:
9056 case BPF_FUNC_task_storage_delete:
9057 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9060 case BPF_FUNC_cgrp_storage_get:
9061 case BPF_FUNC_cgrp_storage_delete:
9062 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9071 verbose(env, "cannot pass map_type %d into func %s#%d\n",
9072 map->map_type, func_id_name(func_id), func_id);
9076 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9080 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9082 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9084 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9086 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9088 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9091 /* We only support one arg being in raw mode at the moment,
9092 * which is sufficient for the helper functions we have
9098 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9100 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9101 bool has_size = fn->arg_size[arg] != 0;
9102 bool is_next_size = false;
9104 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9105 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9107 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9108 return is_next_size;
9110 return has_size == is_next_size || is_next_size == is_fixed;
9113 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9115 /* bpf_xxx(..., buf, len) call will access 'len'
9116 * bytes from memory 'buf'. Both arg types need
9117 * to be paired, so make sure there's no buggy
9118 * helper function specification.
9120 if (arg_type_is_mem_size(fn->arg1_type) ||
9121 check_args_pair_invalid(fn, 0) ||
9122 check_args_pair_invalid(fn, 1) ||
9123 check_args_pair_invalid(fn, 2) ||
9124 check_args_pair_invalid(fn, 3) ||
9125 check_args_pair_invalid(fn, 4))
9131 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9135 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9136 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9137 return !!fn->arg_btf_id[i];
9138 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9139 return fn->arg_btf_id[i] == BPF_PTR_POISON;
9140 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9141 /* arg_btf_id and arg_size are in a union. */
9142 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9143 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9150 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9152 return check_raw_mode_ok(fn) &&
9153 check_arg_pair_ok(fn) &&
9154 check_btf_id_ok(fn) ? 0 : -EINVAL;
9157 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9158 * are now invalid, so turn them into unknown SCALAR_VALUE.
9160 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9161 * since these slices point to packet data.
9163 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9165 struct bpf_func_state *state;
9166 struct bpf_reg_state *reg;
9168 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9169 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9170 mark_reg_invalid(env, reg);
9176 BEYOND_PKT_END = -2,
9179 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9181 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9182 struct bpf_reg_state *reg = &state->regs[regn];
9184 if (reg->type != PTR_TO_PACKET)
9185 /* PTR_TO_PACKET_META is not supported yet */
9188 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9189 * How far beyond pkt_end it goes is unknown.
9190 * if (!range_open) it's the case of pkt >= pkt_end
9191 * if (range_open) it's the case of pkt > pkt_end
9192 * hence this pointer is at least 1 byte bigger than pkt_end
9195 reg->range = BEYOND_PKT_END;
9197 reg->range = AT_PKT_END;
9200 /* The pointer with the specified id has released its reference to kernel
9201 * resources. Identify all copies of the same pointer and clear the reference.
9203 static int release_reference(struct bpf_verifier_env *env,
9206 struct bpf_func_state *state;
9207 struct bpf_reg_state *reg;
9210 err = release_reference_state(cur_func(env), ref_obj_id);
9214 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9215 if (reg->ref_obj_id == ref_obj_id)
9216 mark_reg_invalid(env, reg);
9222 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9224 struct bpf_func_state *unused;
9225 struct bpf_reg_state *reg;
9227 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9228 if (type_is_non_owning_ref(reg->type))
9229 mark_reg_invalid(env, reg);
9233 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9234 struct bpf_reg_state *regs)
9238 /* after the call registers r0 - r5 were scratched */
9239 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9240 mark_reg_not_init(env, regs, caller_saved[i]);
9241 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9245 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9246 struct bpf_func_state *caller,
9247 struct bpf_func_state *callee,
9250 static int set_callee_state(struct bpf_verifier_env *env,
9251 struct bpf_func_state *caller,
9252 struct bpf_func_state *callee, int insn_idx);
9254 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9255 set_callee_state_fn set_callee_state_cb,
9256 struct bpf_verifier_state *state)
9258 struct bpf_func_state *caller, *callee;
9261 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9262 verbose(env, "the call stack of %d frames is too deep\n",
9263 state->curframe + 2);
9267 if (state->frame[state->curframe + 1]) {
9268 verbose(env, "verifier bug. Frame %d already allocated\n",
9269 state->curframe + 1);
9273 caller = state->frame[state->curframe];
9274 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9277 state->frame[state->curframe + 1] = callee;
9279 /* callee cannot access r0, r6 - r9 for reading and has to write
9280 * into its own stack before reading from it.
9281 * callee can read/write into caller's stack
9283 init_func_state(env, callee,
9284 /* remember the callsite, it will be used by bpf_exit */
9286 state->curframe + 1 /* frameno within this callchain */,
9287 subprog /* subprog number within this prog */);
9288 /* Transfer references to the callee */
9289 err = copy_reference_state(callee, caller);
9290 err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9294 /* only increment it after check_reg_arg() finished */
9300 free_func_state(callee);
9301 state->frame[state->curframe + 1] = NULL;
9305 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9306 const struct btf *btf,
9307 struct bpf_reg_state *regs)
9309 struct bpf_subprog_info *sub = subprog_info(env, subprog);
9310 struct bpf_verifier_log *log = &env->log;
9314 ret = btf_prepare_func_args(env, subprog);
9318 /* check that BTF function arguments match actual types that the
9321 for (i = 0; i < sub->arg_cnt; i++) {
9323 struct bpf_reg_state *reg = ®s[regno];
9324 struct bpf_subprog_arg_info *arg = &sub->args[i];
9326 if (arg->arg_type == ARG_ANYTHING) {
9327 if (reg->type != SCALAR_VALUE) {
9328 bpf_log(log, "R%d is not a scalar\n", regno);
9331 } else if (arg->arg_type == ARG_PTR_TO_CTX) {
9332 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9335 /* If function expects ctx type in BTF check that caller
9336 * is passing PTR_TO_CTX.
9338 if (reg->type != PTR_TO_CTX) {
9339 bpf_log(log, "arg#%d expects pointer to ctx\n", i);
9342 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9343 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9346 if (check_mem_reg(env, reg, regno, arg->mem_size))
9348 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
9349 bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
9352 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
9353 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
9356 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
9357 struct bpf_call_arg_meta meta;
9360 if (register_is_null(reg) && type_may_be_null(arg->arg_type))
9363 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
9364 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
9365 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
9369 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
9378 /* Compare BTF of a function call with given bpf_reg_state.
9380 * EFAULT - there is a verifier bug. Abort verification.
9381 * EINVAL - there is a type mismatch or BTF is not available.
9382 * 0 - BTF matches with what bpf_reg_state expects.
9383 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9385 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9386 struct bpf_reg_state *regs)
9388 struct bpf_prog *prog = env->prog;
9389 struct btf *btf = prog->aux->btf;
9393 if (!prog->aux->func_info)
9396 btf_id = prog->aux->func_info[subprog].type_id;
9400 if (prog->aux->func_info_aux[subprog].unreliable)
9403 err = btf_check_func_arg_match(env, subprog, btf, regs);
9404 /* Compiler optimizations can remove arguments from static functions
9405 * or mismatched type can be passed into a global function.
9406 * In such cases mark the function as unreliable from BTF point of view.
9409 prog->aux->func_info_aux[subprog].unreliable = true;
9413 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9414 int insn_idx, int subprog,
9415 set_callee_state_fn set_callee_state_cb)
9417 struct bpf_verifier_state *state = env->cur_state, *callback_state;
9418 struct bpf_func_state *caller, *callee;
9421 caller = state->frame[state->curframe];
9422 err = btf_check_subprog_call(env, subprog, caller->regs);
9426 /* set_callee_state is used for direct subprog calls, but we are
9427 * interested in validating only BPF helpers that can call subprogs as
9430 env->subprog_info[subprog].is_cb = true;
9431 if (bpf_pseudo_kfunc_call(insn) &&
9432 !is_sync_callback_calling_kfunc(insn->imm)) {
9433 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9434 func_id_name(insn->imm), insn->imm);
9436 } else if (!bpf_pseudo_kfunc_call(insn) &&
9437 !is_callback_calling_function(insn->imm)) { /* helper */
9438 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9439 func_id_name(insn->imm), insn->imm);
9443 if (insn->code == (BPF_JMP | BPF_CALL) &&
9444 insn->src_reg == 0 &&
9445 insn->imm == BPF_FUNC_timer_set_callback) {
9446 struct bpf_verifier_state *async_cb;
9448 /* there is no real recursion here. timer callbacks are async */
9449 env->subprog_info[subprog].is_async_cb = true;
9450 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9454 callee = async_cb->frame[0];
9455 callee->async_entry_cnt = caller->async_entry_cnt + 1;
9457 /* Convert bpf_timer_set_callback() args into timer callback args */
9458 err = set_callee_state_cb(env, caller, callee, insn_idx);
9465 /* for callback functions enqueue entry to callback and
9466 * proceed with next instruction within current frame.
9468 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9469 if (!callback_state)
9472 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9477 callback_state->callback_unroll_depth++;
9478 callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9479 caller->callback_depth = 0;
9483 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9486 struct bpf_verifier_state *state = env->cur_state;
9487 struct bpf_func_state *caller;
9488 int err, subprog, target_insn;
9490 target_insn = *insn_idx + insn->imm + 1;
9491 subprog = find_subprog(env, target_insn);
9493 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9497 caller = state->frame[state->curframe];
9498 err = btf_check_subprog_call(env, subprog, caller->regs);
9501 if (subprog_is_global(env, subprog)) {
9502 const char *sub_name = subprog_name(env, subprog);
9504 /* Only global subprogs cannot be called with a lock held. */
9505 if (env->cur_state->active_lock.ptr) {
9506 verbose(env, "global function calls are not allowed while holding a lock,\n"
9507 "use static function instead\n");
9512 verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9517 verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9519 /* mark global subprog for verifying after main prog */
9520 subprog_aux(env, subprog)->called = true;
9521 clear_caller_saved_regs(env, caller->regs);
9523 /* All global functions return a 64-bit SCALAR_VALUE */
9524 mark_reg_unknown(env, caller->regs, BPF_REG_0);
9525 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9527 /* continue with next insn after call */
9531 /* for regular function entry setup new frame and continue
9534 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9538 clear_caller_saved_regs(env, caller->regs);
9540 /* and go analyze first insn of the callee */
9541 *insn_idx = env->subprog_info[subprog].start - 1;
9543 if (env->log.level & BPF_LOG_LEVEL) {
9544 verbose(env, "caller:\n");
9545 print_verifier_state(env, caller, true);
9546 verbose(env, "callee:\n");
9547 print_verifier_state(env, state->frame[state->curframe], true);
9553 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9554 struct bpf_func_state *caller,
9555 struct bpf_func_state *callee)
9557 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9558 * void *callback_ctx, u64 flags);
9559 * callback_fn(struct bpf_map *map, void *key, void *value,
9560 * void *callback_ctx);
9562 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9564 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9565 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9566 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9568 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9569 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9570 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9572 /* pointer to stack or null */
9573 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9576 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9580 static int set_callee_state(struct bpf_verifier_env *env,
9581 struct bpf_func_state *caller,
9582 struct bpf_func_state *callee, int insn_idx)
9586 /* copy r1 - r5 args that callee can access. The copy includes parent
9587 * pointers, which connects us up to the liveness chain
9589 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9590 callee->regs[i] = caller->regs[i];
9594 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9595 struct bpf_func_state *caller,
9596 struct bpf_func_state *callee,
9599 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9600 struct bpf_map *map;
9603 if (bpf_map_ptr_poisoned(insn_aux)) {
9604 verbose(env, "tail_call abusing map_ptr\n");
9608 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9609 if (!map->ops->map_set_for_each_callback_args ||
9610 !map->ops->map_for_each_callback) {
9611 verbose(env, "callback function not allowed for map\n");
9615 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9619 callee->in_callback_fn = true;
9620 callee->callback_ret_range = retval_range(0, 1);
9624 static int set_loop_callback_state(struct bpf_verifier_env *env,
9625 struct bpf_func_state *caller,
9626 struct bpf_func_state *callee,
9629 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9631 * callback_fn(u32 index, void *callback_ctx);
9633 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9634 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9637 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9638 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9639 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9641 callee->in_callback_fn = true;
9642 callee->callback_ret_range = retval_range(0, 1);
9646 static int set_timer_callback_state(struct bpf_verifier_env *env,
9647 struct bpf_func_state *caller,
9648 struct bpf_func_state *callee,
9651 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9653 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9654 * callback_fn(struct bpf_map *map, void *key, void *value);
9656 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9657 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9658 callee->regs[BPF_REG_1].map_ptr = map_ptr;
9660 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9661 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9662 callee->regs[BPF_REG_2].map_ptr = map_ptr;
9664 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9665 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9666 callee->regs[BPF_REG_3].map_ptr = map_ptr;
9669 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9670 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9671 callee->in_async_callback_fn = true;
9672 callee->callback_ret_range = retval_range(0, 1);
9676 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9677 struct bpf_func_state *caller,
9678 struct bpf_func_state *callee,
9681 /* bpf_find_vma(struct task_struct *task, u64 addr,
9682 * void *callback_fn, void *callback_ctx, u64 flags)
9683 * (callback_fn)(struct task_struct *task,
9684 * struct vm_area_struct *vma, void *callback_ctx);
9686 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9688 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9689 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9690 callee->regs[BPF_REG_2].btf = btf_vmlinux;
9691 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
9693 /* pointer to stack or null */
9694 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9697 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9698 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9699 callee->in_callback_fn = true;
9700 callee->callback_ret_range = retval_range(0, 1);
9704 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9705 struct bpf_func_state *caller,
9706 struct bpf_func_state *callee,
9709 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9710 * callback_ctx, u64 flags);
9711 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9713 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9714 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9715 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9718 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9719 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9720 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9722 callee->in_callback_fn = true;
9723 callee->callback_ret_range = retval_range(0, 1);
9727 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9728 struct bpf_func_state *caller,
9729 struct bpf_func_state *callee,
9732 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9733 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9735 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9736 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9737 * by this point, so look at 'root'
9739 struct btf_field *field;
9741 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9743 if (!field || !field->graph_root.value_btf_id)
9746 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9747 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9748 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9749 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9751 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9752 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9753 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9754 callee->in_callback_fn = true;
9755 callee->callback_ret_range = retval_range(0, 1);
9759 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9761 /* Are we currently verifying the callback for a rbtree helper that must
9762 * be called with lock held? If so, no need to complain about unreleased
9765 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9767 struct bpf_verifier_state *state = env->cur_state;
9768 struct bpf_insn *insn = env->prog->insnsi;
9769 struct bpf_func_state *callee;
9772 if (!state->curframe)
9775 callee = state->frame[state->curframe];
9777 if (!callee->in_callback_fn)
9780 kfunc_btf_id = insn[callee->callsite].imm;
9781 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9784 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
9786 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
9789 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9791 struct bpf_verifier_state *state = env->cur_state, *prev_st;
9792 struct bpf_func_state *caller, *callee;
9793 struct bpf_reg_state *r0;
9794 bool in_callback_fn;
9797 callee = state->frame[state->curframe];
9798 r0 = &callee->regs[BPF_REG_0];
9799 if (r0->type == PTR_TO_STACK) {
9800 /* technically it's ok to return caller's stack pointer
9801 * (or caller's caller's pointer) back to the caller,
9802 * since these pointers are valid. Only current stack
9803 * pointer will be invalid as soon as function exits,
9804 * but let's be conservative
9806 verbose(env, "cannot return stack pointer to the caller\n");
9810 caller = state->frame[state->curframe - 1];
9811 if (callee->in_callback_fn) {
9812 if (r0->type != SCALAR_VALUE) {
9813 verbose(env, "R0 not a scalar value\n");
9817 /* we are going to rely on register's precise value */
9818 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9819 err = err ?: mark_chain_precision(env, BPF_REG_0);
9823 /* enforce R0 return value range */
9824 if (!retval_range_within(callee->callback_ret_range, r0)) {
9825 verbose_invalid_scalar(env, r0, callee->callback_ret_range,
9826 "At callback return", "R0");
9829 if (!calls_callback(env, callee->callsite)) {
9830 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9831 *insn_idx, callee->callsite);
9835 /* return to the caller whatever r0 had in the callee */
9836 caller->regs[BPF_REG_0] = *r0;
9839 /* callback_fn frame should have released its own additions to parent's
9840 * reference state at this point, or check_reference_leak would
9841 * complain, hence it must be the same as the caller. There is no need
9844 if (!callee->in_callback_fn) {
9845 /* Transfer references to the caller */
9846 err = copy_reference_state(caller, callee);
9851 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9852 * there function call logic would reschedule callback visit. If iteration
9853 * converges is_state_visited() would prune that visit eventually.
9855 in_callback_fn = callee->in_callback_fn;
9857 *insn_idx = callee->callsite;
9859 *insn_idx = callee->callsite + 1;
9861 if (env->log.level & BPF_LOG_LEVEL) {
9862 verbose(env, "returning from callee:\n");
9863 print_verifier_state(env, callee, true);
9864 verbose(env, "to caller at %d:\n", *insn_idx);
9865 print_verifier_state(env, caller, true);
9867 /* clear everything in the callee. In case of exceptional exits using
9868 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
9869 free_func_state(callee);
9870 state->frame[state->curframe--] = NULL;
9872 /* for callbacks widen imprecise scalars to make programs like below verify:
9874 * struct ctx { int i; }
9875 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9877 * struct ctx = { .i = 0; }
9878 * bpf_loop(100, cb, &ctx, 0);
9880 * This is similar to what is done in process_iter_next_call() for open
9883 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9885 err = widen_imprecise_scalars(env, prev_st, state);
9892 static int do_refine_retval_range(struct bpf_verifier_env *env,
9893 struct bpf_reg_state *regs, int ret_type,
9895 struct bpf_call_arg_meta *meta)
9897 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
9899 if (ret_type != RET_INTEGER)
9903 case BPF_FUNC_get_stack:
9904 case BPF_FUNC_get_task_stack:
9905 case BPF_FUNC_probe_read_str:
9906 case BPF_FUNC_probe_read_kernel_str:
9907 case BPF_FUNC_probe_read_user_str:
9908 ret_reg->smax_value = meta->msize_max_value;
9909 ret_reg->s32_max_value = meta->msize_max_value;
9910 ret_reg->smin_value = -MAX_ERRNO;
9911 ret_reg->s32_min_value = -MAX_ERRNO;
9912 reg_bounds_sync(ret_reg);
9914 case BPF_FUNC_get_smp_processor_id:
9915 ret_reg->umax_value = nr_cpu_ids - 1;
9916 ret_reg->u32_max_value = nr_cpu_ids - 1;
9917 ret_reg->smax_value = nr_cpu_ids - 1;
9918 ret_reg->s32_max_value = nr_cpu_ids - 1;
9919 ret_reg->umin_value = 0;
9920 ret_reg->u32_min_value = 0;
9921 ret_reg->smin_value = 0;
9922 ret_reg->s32_min_value = 0;
9923 reg_bounds_sync(ret_reg);
9927 return reg_bounds_sanity_check(env, ret_reg, "retval");
9931 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9932 int func_id, int insn_idx)
9934 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9935 struct bpf_map *map = meta->map_ptr;
9937 if (func_id != BPF_FUNC_tail_call &&
9938 func_id != BPF_FUNC_map_lookup_elem &&
9939 func_id != BPF_FUNC_map_update_elem &&
9940 func_id != BPF_FUNC_map_delete_elem &&
9941 func_id != BPF_FUNC_map_push_elem &&
9942 func_id != BPF_FUNC_map_pop_elem &&
9943 func_id != BPF_FUNC_map_peek_elem &&
9944 func_id != BPF_FUNC_for_each_map_elem &&
9945 func_id != BPF_FUNC_redirect_map &&
9946 func_id != BPF_FUNC_map_lookup_percpu_elem)
9950 verbose(env, "kernel subsystem misconfigured verifier\n");
9954 /* In case of read-only, some additional restrictions
9955 * need to be applied in order to prevent altering the
9956 * state of the map from program side.
9958 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9959 (func_id == BPF_FUNC_map_delete_elem ||
9960 func_id == BPF_FUNC_map_update_elem ||
9961 func_id == BPF_FUNC_map_push_elem ||
9962 func_id == BPF_FUNC_map_pop_elem)) {
9963 verbose(env, "write into map forbidden\n");
9967 if (!BPF_MAP_PTR(aux->map_ptr_state))
9968 bpf_map_ptr_store(aux, meta->map_ptr,
9969 !meta->map_ptr->bypass_spec_v1);
9970 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9971 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9972 !meta->map_ptr->bypass_spec_v1);
9977 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9978 int func_id, int insn_idx)
9980 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9981 struct bpf_reg_state *regs = cur_regs(env), *reg;
9982 struct bpf_map *map = meta->map_ptr;
9986 if (func_id != BPF_FUNC_tail_call)
9988 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9989 verbose(env, "kernel subsystem misconfigured verifier\n");
9993 reg = ®s[BPF_REG_3];
9994 val = reg->var_off.value;
9995 max = map->max_entries;
9997 if (!(is_reg_const(reg, false) && val < max)) {
9998 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10002 err = mark_chain_precision(env, BPF_REG_3);
10005 if (bpf_map_key_unseen(aux))
10006 bpf_map_key_store(aux, val);
10007 else if (!bpf_map_key_poisoned(aux) &&
10008 bpf_map_key_immediate(aux) != val)
10009 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10013 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
10015 struct bpf_func_state *state = cur_func(env);
10016 bool refs_lingering = false;
10019 if (!exception_exit && state->frameno && !state->in_callback_fn)
10022 for (i = 0; i < state->acquired_refs; i++) {
10023 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
10025 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
10026 state->refs[i].id, state->refs[i].insn_idx);
10027 refs_lingering = true;
10029 return refs_lingering ? -EINVAL : 0;
10032 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10033 struct bpf_reg_state *regs)
10035 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
10036 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
10037 struct bpf_map *fmt_map = fmt_reg->map_ptr;
10038 struct bpf_bprintf_data data = {};
10039 int err, fmt_map_off, num_args;
10043 /* data must be an array of u64 */
10044 if (data_len_reg->var_off.value % 8)
10046 num_args = data_len_reg->var_off.value / 8;
10048 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10049 * and map_direct_value_addr is set.
10051 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
10052 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10055 verbose(env, "verifier bug\n");
10058 fmt = (char *)(long)fmt_addr + fmt_map_off;
10060 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10061 * can focus on validating the format specifiers.
10063 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10065 verbose(env, "Invalid format string\n");
10070 static int check_get_func_ip(struct bpf_verifier_env *env)
10072 enum bpf_prog_type type = resolve_prog_type(env->prog);
10073 int func_id = BPF_FUNC_get_func_ip;
10075 if (type == BPF_PROG_TYPE_TRACING) {
10076 if (!bpf_prog_has_trampoline(env->prog)) {
10077 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10078 func_id_name(func_id), func_id);
10082 } else if (type == BPF_PROG_TYPE_KPROBE) {
10086 verbose(env, "func %s#%d not supported for program type %d\n",
10087 func_id_name(func_id), func_id, type);
10091 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10093 return &env->insn_aux_data[env->insn_idx];
10096 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10098 struct bpf_reg_state *regs = cur_regs(env);
10099 struct bpf_reg_state *reg = ®s[BPF_REG_4];
10100 bool reg_is_null = register_is_null(reg);
10103 mark_chain_precision(env, BPF_REG_4);
10105 return reg_is_null;
10108 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10110 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10112 if (!state->initialized) {
10113 state->initialized = 1;
10114 state->fit_for_inline = loop_flag_is_zero(env);
10115 state->callback_subprogno = subprogno;
10119 if (!state->fit_for_inline)
10122 state->fit_for_inline = (loop_flag_is_zero(env) &&
10123 state->callback_subprogno == subprogno);
10126 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10129 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10130 bool returns_cpu_specific_alloc_ptr = false;
10131 const struct bpf_func_proto *fn = NULL;
10132 enum bpf_return_type ret_type;
10133 enum bpf_type_flag ret_flag;
10134 struct bpf_reg_state *regs;
10135 struct bpf_call_arg_meta meta;
10136 int insn_idx = *insn_idx_p;
10138 int i, err, func_id;
10140 /* find function prototype */
10141 func_id = insn->imm;
10142 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
10143 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
10148 if (env->ops->get_func_proto)
10149 fn = env->ops->get_func_proto(func_id, env->prog);
10151 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
10156 /* eBPF programs must be GPL compatible to use GPL-ed functions */
10157 if (!env->prog->gpl_compatible && fn->gpl_only) {
10158 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10162 if (fn->allowed && !fn->allowed(env->prog)) {
10163 verbose(env, "helper call is not allowed in probe\n");
10167 if (!env->prog->aux->sleepable && fn->might_sleep) {
10168 verbose(env, "helper call might sleep in a non-sleepable prog\n");
10172 /* With LD_ABS/IND some JITs save/restore skb from r1. */
10173 changes_data = bpf_helper_changes_pkt_data(fn->func);
10174 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10175 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10176 func_id_name(func_id), func_id);
10180 memset(&meta, 0, sizeof(meta));
10181 meta.pkt_access = fn->pkt_access;
10183 err = check_func_proto(fn, func_id);
10185 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10186 func_id_name(func_id), func_id);
10190 if (env->cur_state->active_rcu_lock) {
10191 if (fn->might_sleep) {
10192 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10193 func_id_name(func_id), func_id);
10197 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10198 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10201 meta.func_id = func_id;
10203 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10204 err = check_func_arg(env, i, &meta, fn, insn_idx);
10209 err = record_func_map(env, &meta, func_id, insn_idx);
10213 err = record_func_key(env, &meta, func_id, insn_idx);
10217 /* Mark slots with STACK_MISC in case of raw mode, stack offset
10218 * is inferred from register state.
10220 for (i = 0; i < meta.access_size; i++) {
10221 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10222 BPF_WRITE, -1, false, false);
10227 regs = cur_regs(env);
10229 if (meta.release_regno) {
10231 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10232 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10233 * is safe to do directly.
10235 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10236 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10237 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10240 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
10241 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10242 u32 ref_obj_id = meta.ref_obj_id;
10243 bool in_rcu = in_rcu_cs(env);
10244 struct bpf_func_state *state;
10245 struct bpf_reg_state *reg;
10247 err = release_reference_state(cur_func(env), ref_obj_id);
10249 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10250 if (reg->ref_obj_id == ref_obj_id) {
10251 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10252 reg->ref_obj_id = 0;
10253 reg->type &= ~MEM_ALLOC;
10254 reg->type |= MEM_RCU;
10256 mark_reg_invalid(env, reg);
10261 } else if (meta.ref_obj_id) {
10262 err = release_reference(env, meta.ref_obj_id);
10263 } else if (register_is_null(®s[meta.release_regno])) {
10264 /* meta.ref_obj_id can only be 0 if register that is meant to be
10265 * released is NULL, which must be > R0.
10270 verbose(env, "func %s#%d reference has not been acquired before\n",
10271 func_id_name(func_id), func_id);
10277 case BPF_FUNC_tail_call:
10278 err = check_reference_leak(env, false);
10280 verbose(env, "tail_call would lead to reference leak\n");
10284 case BPF_FUNC_get_local_storage:
10285 /* check that flags argument in get_local_storage(map, flags) is 0,
10286 * this is required because get_local_storage() can't return an error.
10288 if (!register_is_null(®s[BPF_REG_2])) {
10289 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10293 case BPF_FUNC_for_each_map_elem:
10294 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10295 set_map_elem_callback_state);
10297 case BPF_FUNC_timer_set_callback:
10298 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10299 set_timer_callback_state);
10301 case BPF_FUNC_find_vma:
10302 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10303 set_find_vma_callback_state);
10305 case BPF_FUNC_snprintf:
10306 err = check_bpf_snprintf_call(env, regs);
10308 case BPF_FUNC_loop:
10309 update_loop_inline_state(env, meta.subprogno);
10310 /* Verifier relies on R1 value to determine if bpf_loop() iteration
10311 * is finished, thus mark it precise.
10313 err = mark_chain_precision(env, BPF_REG_1);
10316 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10317 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10318 set_loop_callback_state);
10320 cur_func(env)->callback_depth = 0;
10321 if (env->log.level & BPF_LOG_LEVEL2)
10322 verbose(env, "frame%d bpf_loop iteration limit reached\n",
10323 env->cur_state->curframe);
10326 case BPF_FUNC_dynptr_from_mem:
10327 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10328 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10329 reg_type_str(env, regs[BPF_REG_1].type));
10333 case BPF_FUNC_set_retval:
10334 if (prog_type == BPF_PROG_TYPE_LSM &&
10335 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10336 if (!env->prog->aux->attach_func_proto->type) {
10337 /* Make sure programs that attach to void
10338 * hooks don't try to modify return value.
10340 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10345 case BPF_FUNC_dynptr_data:
10347 struct bpf_reg_state *reg;
10348 int id, ref_obj_id;
10350 reg = get_dynptr_arg_reg(env, fn, regs);
10355 if (meta.dynptr_id) {
10356 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10359 if (meta.ref_obj_id) {
10360 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10364 id = dynptr_id(env, reg);
10366 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10370 ref_obj_id = dynptr_ref_obj_id(env, reg);
10371 if (ref_obj_id < 0) {
10372 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10376 meta.dynptr_id = id;
10377 meta.ref_obj_id = ref_obj_id;
10381 case BPF_FUNC_dynptr_write:
10383 enum bpf_dynptr_type dynptr_type;
10384 struct bpf_reg_state *reg;
10386 reg = get_dynptr_arg_reg(env, fn, regs);
10390 dynptr_type = dynptr_get_type(env, reg);
10391 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10394 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10395 /* this will trigger clear_all_pkt_pointers(), which will
10396 * invalidate all dynptr slices associated with the skb
10398 changes_data = true;
10402 case BPF_FUNC_per_cpu_ptr:
10403 case BPF_FUNC_this_cpu_ptr:
10405 struct bpf_reg_state *reg = ®s[BPF_REG_1];
10406 const struct btf_type *type;
10408 if (reg->type & MEM_RCU) {
10409 type = btf_type_by_id(reg->btf, reg->btf_id);
10410 if (!type || !btf_type_is_struct(type)) {
10411 verbose(env, "Helper has invalid btf/btf_id in R1\n");
10414 returns_cpu_specific_alloc_ptr = true;
10415 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10419 case BPF_FUNC_user_ringbuf_drain:
10420 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10421 set_user_ringbuf_callback_state);
10428 /* reset caller saved regs */
10429 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10430 mark_reg_not_init(env, regs, caller_saved[i]);
10431 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10434 /* helper call returns 64-bit value. */
10435 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10437 /* update return register (already marked as written above) */
10438 ret_type = fn->ret_type;
10439 ret_flag = type_flag(ret_type);
10441 switch (base_type(ret_type)) {
10443 /* sets type to SCALAR_VALUE */
10444 mark_reg_unknown(env, regs, BPF_REG_0);
10447 regs[BPF_REG_0].type = NOT_INIT;
10449 case RET_PTR_TO_MAP_VALUE:
10450 /* There is no offset yet applied, variable or fixed */
10451 mark_reg_known_zero(env, regs, BPF_REG_0);
10452 /* remember map_ptr, so that check_map_access()
10453 * can check 'value_size' boundary of memory access
10454 * to map element returned from bpf_map_lookup_elem()
10456 if (meta.map_ptr == NULL) {
10458 "kernel subsystem misconfigured verifier\n");
10461 regs[BPF_REG_0].map_ptr = meta.map_ptr;
10462 regs[BPF_REG_0].map_uid = meta.map_uid;
10463 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10464 if (!type_may_be_null(ret_type) &&
10465 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10466 regs[BPF_REG_0].id = ++env->id_gen;
10469 case RET_PTR_TO_SOCKET:
10470 mark_reg_known_zero(env, regs, BPF_REG_0);
10471 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10473 case RET_PTR_TO_SOCK_COMMON:
10474 mark_reg_known_zero(env, regs, BPF_REG_0);
10475 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10477 case RET_PTR_TO_TCP_SOCK:
10478 mark_reg_known_zero(env, regs, BPF_REG_0);
10479 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10481 case RET_PTR_TO_MEM:
10482 mark_reg_known_zero(env, regs, BPF_REG_0);
10483 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10484 regs[BPF_REG_0].mem_size = meta.mem_size;
10486 case RET_PTR_TO_MEM_OR_BTF_ID:
10488 const struct btf_type *t;
10490 mark_reg_known_zero(env, regs, BPF_REG_0);
10491 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10492 if (!btf_type_is_struct(t)) {
10494 const struct btf_type *ret;
10497 /* resolve the type size of ksym. */
10498 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10500 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10501 verbose(env, "unable to resolve the size of type '%s': %ld\n",
10502 tname, PTR_ERR(ret));
10505 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10506 regs[BPF_REG_0].mem_size = tsize;
10508 if (returns_cpu_specific_alloc_ptr) {
10509 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10511 /* MEM_RDONLY may be carried from ret_flag, but it
10512 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10513 * it will confuse the check of PTR_TO_BTF_ID in
10514 * check_mem_access().
10516 ret_flag &= ~MEM_RDONLY;
10517 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10520 regs[BPF_REG_0].btf = meta.ret_btf;
10521 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10525 case RET_PTR_TO_BTF_ID:
10527 struct btf *ret_btf;
10530 mark_reg_known_zero(env, regs, BPF_REG_0);
10531 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10532 if (func_id == BPF_FUNC_kptr_xchg) {
10533 ret_btf = meta.kptr_field->kptr.btf;
10534 ret_btf_id = meta.kptr_field->kptr.btf_id;
10535 if (!btf_is_kernel(ret_btf)) {
10536 regs[BPF_REG_0].type |= MEM_ALLOC;
10537 if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10538 regs[BPF_REG_0].type |= MEM_PERCPU;
10541 if (fn->ret_btf_id == BPF_PTR_POISON) {
10542 verbose(env, "verifier internal error:");
10543 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10544 func_id_name(func_id));
10547 ret_btf = btf_vmlinux;
10548 ret_btf_id = *fn->ret_btf_id;
10550 if (ret_btf_id == 0) {
10551 verbose(env, "invalid return type %u of func %s#%d\n",
10552 base_type(ret_type), func_id_name(func_id),
10556 regs[BPF_REG_0].btf = ret_btf;
10557 regs[BPF_REG_0].btf_id = ret_btf_id;
10561 verbose(env, "unknown return type %u of func %s#%d\n",
10562 base_type(ret_type), func_id_name(func_id), func_id);
10566 if (type_may_be_null(regs[BPF_REG_0].type))
10567 regs[BPF_REG_0].id = ++env->id_gen;
10569 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10570 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10571 func_id_name(func_id), func_id);
10575 if (is_dynptr_ref_function(func_id))
10576 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10578 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10579 /* For release_reference() */
10580 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10581 } else if (is_acquire_function(func_id, meta.map_ptr)) {
10582 int id = acquire_reference_state(env, insn_idx);
10586 /* For mark_ptr_or_null_reg() */
10587 regs[BPF_REG_0].id = id;
10588 /* For release_reference() */
10589 regs[BPF_REG_0].ref_obj_id = id;
10592 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
10596 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10600 if ((func_id == BPF_FUNC_get_stack ||
10601 func_id == BPF_FUNC_get_task_stack) &&
10602 !env->prog->has_callchain_buf) {
10603 const char *err_str;
10605 #ifdef CONFIG_PERF_EVENTS
10606 err = get_callchain_buffers(sysctl_perf_event_max_stack);
10607 err_str = "cannot get callchain buffer for func %s#%d\n";
10610 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10613 verbose(env, err_str, func_id_name(func_id), func_id);
10617 env->prog->has_callchain_buf = true;
10620 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10621 env->prog->call_get_stack = true;
10623 if (func_id == BPF_FUNC_get_func_ip) {
10624 if (check_get_func_ip(env))
10626 env->prog->call_get_func_ip = true;
10630 clear_all_pkt_pointers(env);
10634 /* mark_btf_func_reg_size() is used when the reg size is determined by
10635 * the BTF func_proto's return value size and argument.
10637 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10640 struct bpf_reg_state *reg = &cur_regs(env)[regno];
10642 if (regno == BPF_REG_0) {
10643 /* Function return value */
10644 reg->live |= REG_LIVE_WRITTEN;
10645 reg->subreg_def = reg_size == sizeof(u64) ?
10646 DEF_NOT_SUBREG : env->insn_idx + 1;
10648 /* Function argument */
10649 if (reg_size == sizeof(u64)) {
10650 mark_insn_zext(env, reg);
10651 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10653 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10658 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10660 return meta->kfunc_flags & KF_ACQUIRE;
10663 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10665 return meta->kfunc_flags & KF_RELEASE;
10668 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10670 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10673 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10675 return meta->kfunc_flags & KF_SLEEPABLE;
10678 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10680 return meta->kfunc_flags & KF_DESTRUCTIVE;
10683 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10685 return meta->kfunc_flags & KF_RCU;
10688 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10690 return meta->kfunc_flags & KF_RCU_PROTECTED;
10693 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10694 const struct btf_param *arg,
10695 const struct bpf_reg_state *reg)
10697 const struct btf_type *t;
10699 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10700 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10703 return btf_param_match_suffix(btf, arg, "__sz");
10706 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10707 const struct btf_param *arg,
10708 const struct bpf_reg_state *reg)
10710 const struct btf_type *t;
10712 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10713 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10716 return btf_param_match_suffix(btf, arg, "__szk");
10719 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10721 return btf_param_match_suffix(btf, arg, "__opt");
10724 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10726 return btf_param_match_suffix(btf, arg, "__k");
10729 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10731 return btf_param_match_suffix(btf, arg, "__ign");
10734 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10736 return btf_param_match_suffix(btf, arg, "__alloc");
10739 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10741 return btf_param_match_suffix(btf, arg, "__uninit");
10744 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10746 return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
10749 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10751 return btf_param_match_suffix(btf, arg, "__nullable");
10754 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
10756 return btf_param_match_suffix(btf, arg, "__str");
10759 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10760 const struct btf_param *arg,
10763 int len, target_len = strlen(name);
10764 const char *param_name;
10766 param_name = btf_name_by_offset(btf, arg->name_off);
10767 if (str_is_empty(param_name))
10769 len = strlen(param_name);
10770 if (len != target_len)
10772 if (strcmp(param_name, name))
10780 KF_ARG_LIST_HEAD_ID,
10781 KF_ARG_LIST_NODE_ID,
10786 BTF_ID_LIST(kf_arg_btf_ids)
10787 BTF_ID(struct, bpf_dynptr_kern)
10788 BTF_ID(struct, bpf_list_head)
10789 BTF_ID(struct, bpf_list_node)
10790 BTF_ID(struct, bpf_rb_root)
10791 BTF_ID(struct, bpf_rb_node)
10793 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10794 const struct btf_param *arg, int type)
10796 const struct btf_type *t;
10799 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10802 if (!btf_type_is_ptr(t))
10804 t = btf_type_skip_modifiers(btf, t->type, &res_id);
10807 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10810 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10812 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10815 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10817 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10820 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10822 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10825 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10827 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10830 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10832 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10835 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10836 const struct btf_param *arg)
10838 const struct btf_type *t;
10840 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10847 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10848 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10849 const struct btf *btf,
10850 const struct btf_type *t, int rec)
10852 const struct btf_type *member_type;
10853 const struct btf_member *member;
10856 if (!btf_type_is_struct(t))
10859 for_each_member(i, t, member) {
10860 const struct btf_array *array;
10862 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10863 if (btf_type_is_struct(member_type)) {
10865 verbose(env, "max struct nesting depth exceeded\n");
10868 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10872 if (btf_type_is_array(member_type)) {
10873 array = btf_array(member_type);
10874 if (!array->nelems)
10876 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10877 if (!btf_type_is_scalar(member_type))
10881 if (!btf_type_is_scalar(member_type))
10887 enum kfunc_ptr_arg_type {
10889 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
10890 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10891 KF_ARG_PTR_TO_DYNPTR,
10892 KF_ARG_PTR_TO_ITER,
10893 KF_ARG_PTR_TO_LIST_HEAD,
10894 KF_ARG_PTR_TO_LIST_NODE,
10895 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
10897 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
10898 KF_ARG_PTR_TO_CALLBACK,
10899 KF_ARG_PTR_TO_RB_ROOT,
10900 KF_ARG_PTR_TO_RB_NODE,
10901 KF_ARG_PTR_TO_NULL,
10902 KF_ARG_PTR_TO_CONST_STR,
10905 enum special_kfunc_type {
10906 KF_bpf_obj_new_impl,
10907 KF_bpf_obj_drop_impl,
10908 KF_bpf_refcount_acquire_impl,
10909 KF_bpf_list_push_front_impl,
10910 KF_bpf_list_push_back_impl,
10911 KF_bpf_list_pop_front,
10912 KF_bpf_list_pop_back,
10913 KF_bpf_cast_to_kern_ctx,
10914 KF_bpf_rdonly_cast,
10915 KF_bpf_rcu_read_lock,
10916 KF_bpf_rcu_read_unlock,
10917 KF_bpf_rbtree_remove,
10918 KF_bpf_rbtree_add_impl,
10919 KF_bpf_rbtree_first,
10920 KF_bpf_dynptr_from_skb,
10921 KF_bpf_dynptr_from_xdp,
10922 KF_bpf_dynptr_slice,
10923 KF_bpf_dynptr_slice_rdwr,
10924 KF_bpf_dynptr_clone,
10925 KF_bpf_percpu_obj_new_impl,
10926 KF_bpf_percpu_obj_drop_impl,
10928 KF_bpf_iter_css_task_new,
10931 BTF_SET_START(special_kfunc_set)
10932 BTF_ID(func, bpf_obj_new_impl)
10933 BTF_ID(func, bpf_obj_drop_impl)
10934 BTF_ID(func, bpf_refcount_acquire_impl)
10935 BTF_ID(func, bpf_list_push_front_impl)
10936 BTF_ID(func, bpf_list_push_back_impl)
10937 BTF_ID(func, bpf_list_pop_front)
10938 BTF_ID(func, bpf_list_pop_back)
10939 BTF_ID(func, bpf_cast_to_kern_ctx)
10940 BTF_ID(func, bpf_rdonly_cast)
10941 BTF_ID(func, bpf_rbtree_remove)
10942 BTF_ID(func, bpf_rbtree_add_impl)
10943 BTF_ID(func, bpf_rbtree_first)
10944 BTF_ID(func, bpf_dynptr_from_skb)
10945 BTF_ID(func, bpf_dynptr_from_xdp)
10946 BTF_ID(func, bpf_dynptr_slice)
10947 BTF_ID(func, bpf_dynptr_slice_rdwr)
10948 BTF_ID(func, bpf_dynptr_clone)
10949 BTF_ID(func, bpf_percpu_obj_new_impl)
10950 BTF_ID(func, bpf_percpu_obj_drop_impl)
10951 BTF_ID(func, bpf_throw)
10952 #ifdef CONFIG_CGROUPS
10953 BTF_ID(func, bpf_iter_css_task_new)
10955 BTF_SET_END(special_kfunc_set)
10957 BTF_ID_LIST(special_kfunc_list)
10958 BTF_ID(func, bpf_obj_new_impl)
10959 BTF_ID(func, bpf_obj_drop_impl)
10960 BTF_ID(func, bpf_refcount_acquire_impl)
10961 BTF_ID(func, bpf_list_push_front_impl)
10962 BTF_ID(func, bpf_list_push_back_impl)
10963 BTF_ID(func, bpf_list_pop_front)
10964 BTF_ID(func, bpf_list_pop_back)
10965 BTF_ID(func, bpf_cast_to_kern_ctx)
10966 BTF_ID(func, bpf_rdonly_cast)
10967 BTF_ID(func, bpf_rcu_read_lock)
10968 BTF_ID(func, bpf_rcu_read_unlock)
10969 BTF_ID(func, bpf_rbtree_remove)
10970 BTF_ID(func, bpf_rbtree_add_impl)
10971 BTF_ID(func, bpf_rbtree_first)
10972 BTF_ID(func, bpf_dynptr_from_skb)
10973 BTF_ID(func, bpf_dynptr_from_xdp)
10974 BTF_ID(func, bpf_dynptr_slice)
10975 BTF_ID(func, bpf_dynptr_slice_rdwr)
10976 BTF_ID(func, bpf_dynptr_clone)
10977 BTF_ID(func, bpf_percpu_obj_new_impl)
10978 BTF_ID(func, bpf_percpu_obj_drop_impl)
10979 BTF_ID(func, bpf_throw)
10980 #ifdef CONFIG_CGROUPS
10981 BTF_ID(func, bpf_iter_css_task_new)
10986 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10988 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10989 meta->arg_owning_ref) {
10993 return meta->kfunc_flags & KF_RET_NULL;
10996 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10998 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
11001 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
11003 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11006 static enum kfunc_ptr_arg_type
11007 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
11008 struct bpf_kfunc_call_arg_meta *meta,
11009 const struct btf_type *t, const struct btf_type *ref_t,
11010 const char *ref_tname, const struct btf_param *args,
11011 int argno, int nargs)
11013 u32 regno = argno + 1;
11014 struct bpf_reg_state *regs = cur_regs(env);
11015 struct bpf_reg_state *reg = ®s[regno];
11016 bool arg_mem_size = false;
11018 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
11019 return KF_ARG_PTR_TO_CTX;
11021 /* In this function, we verify the kfunc's BTF as per the argument type,
11022 * leaving the rest of the verification with respect to the register
11023 * type to our caller. When a set of conditions hold in the BTF type of
11024 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11026 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
11027 return KF_ARG_PTR_TO_CTX;
11029 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
11030 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11032 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
11033 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11035 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
11036 return KF_ARG_PTR_TO_DYNPTR;
11038 if (is_kfunc_arg_iter(meta, argno))
11039 return KF_ARG_PTR_TO_ITER;
11041 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
11042 return KF_ARG_PTR_TO_LIST_HEAD;
11044 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
11045 return KF_ARG_PTR_TO_LIST_NODE;
11047 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
11048 return KF_ARG_PTR_TO_RB_ROOT;
11050 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
11051 return KF_ARG_PTR_TO_RB_NODE;
11053 if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
11054 return KF_ARG_PTR_TO_CONST_STR;
11056 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11057 if (!btf_type_is_struct(ref_t)) {
11058 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11059 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11062 return KF_ARG_PTR_TO_BTF_ID;
11065 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11066 return KF_ARG_PTR_TO_CALLBACK;
11068 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11069 return KF_ARG_PTR_TO_NULL;
11071 if (argno + 1 < nargs &&
11072 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
11073 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
11074 arg_mem_size = true;
11076 /* This is the catch all argument type of register types supported by
11077 * check_helper_mem_access. However, we only allow when argument type is
11078 * pointer to scalar, or struct composed (recursively) of scalars. When
11079 * arg_mem_size is true, the pointer can be void *.
11081 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11082 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11083 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11084 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11087 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11090 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11091 struct bpf_reg_state *reg,
11092 const struct btf_type *ref_t,
11093 const char *ref_tname, u32 ref_id,
11094 struct bpf_kfunc_call_arg_meta *meta,
11097 const struct btf_type *reg_ref_t;
11098 bool strict_type_match = false;
11099 const struct btf *reg_btf;
11100 const char *reg_ref_tname;
11103 if (base_type(reg->type) == PTR_TO_BTF_ID) {
11104 reg_btf = reg->btf;
11105 reg_ref_id = reg->btf_id;
11107 reg_btf = btf_vmlinux;
11108 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11111 /* Enforce strict type matching for calls to kfuncs that are acquiring
11112 * or releasing a reference, or are no-cast aliases. We do _not_
11113 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11114 * as we want to enable BPF programs to pass types that are bitwise
11115 * equivalent without forcing them to explicitly cast with something
11116 * like bpf_cast_to_kern_ctx().
11118 * For example, say we had a type like the following:
11120 * struct bpf_cpumask {
11121 * cpumask_t cpumask;
11122 * refcount_t usage;
11125 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11126 * to a struct cpumask, so it would be safe to pass a struct
11127 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11129 * The philosophy here is similar to how we allow scalars of different
11130 * types to be passed to kfuncs as long as the size is the same. The
11131 * only difference here is that we're simply allowing
11132 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11135 if (is_kfunc_acquire(meta) ||
11136 (is_kfunc_release(meta) && reg->ref_obj_id) ||
11137 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11138 strict_type_match = true;
11140 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
11142 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
11143 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11144 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
11145 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11146 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11147 btf_type_str(reg_ref_t), reg_ref_tname);
11153 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11155 struct bpf_verifier_state *state = env->cur_state;
11156 struct btf_record *rec = reg_btf_record(reg);
11158 if (!state->active_lock.ptr) {
11159 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11163 if (type_flag(reg->type) & NON_OWN_REF) {
11164 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11168 reg->type |= NON_OWN_REF;
11169 if (rec->refcount_off >= 0)
11170 reg->type |= MEM_RCU;
11175 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11177 struct bpf_func_state *state, *unused;
11178 struct bpf_reg_state *reg;
11181 state = cur_func(env);
11184 verbose(env, "verifier internal error: ref_obj_id is zero for "
11185 "owning -> non-owning conversion\n");
11189 for (i = 0; i < state->acquired_refs; i++) {
11190 if (state->refs[i].id != ref_obj_id)
11193 /* Clear ref_obj_id here so release_reference doesn't clobber
11196 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11197 if (reg->ref_obj_id == ref_obj_id) {
11198 reg->ref_obj_id = 0;
11199 ref_set_non_owning(env, reg);
11205 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11209 /* Implementation details:
11211 * Each register points to some region of memory, which we define as an
11212 * allocation. Each allocation may embed a bpf_spin_lock which protects any
11213 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11214 * allocation. The lock and the data it protects are colocated in the same
11217 * Hence, everytime a register holds a pointer value pointing to such
11218 * allocation, the verifier preserves a unique reg->id for it.
11220 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11221 * bpf_spin_lock is called.
11223 * To enable this, lock state in the verifier captures two values:
11224 * active_lock.ptr = Register's type specific pointer
11225 * active_lock.id = A unique ID for each register pointer value
11227 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11228 * supported register types.
11230 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11231 * allocated objects is the reg->btf pointer.
11233 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11234 * can establish the provenance of the map value statically for each distinct
11235 * lookup into such maps. They always contain a single map value hence unique
11236 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11238 * So, in case of global variables, they use array maps with max_entries = 1,
11239 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11240 * into the same map value as max_entries is 1, as described above).
11242 * In case of inner map lookups, the inner map pointer has same map_ptr as the
11243 * outer map pointer (in verifier context), but each lookup into an inner map
11244 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11245 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11246 * will get different reg->id assigned to each lookup, hence different
11249 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11250 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11251 * returned from bpf_obj_new. Each allocation receives a new reg->id.
11253 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11258 switch ((int)reg->type) {
11259 case PTR_TO_MAP_VALUE:
11260 ptr = reg->map_ptr;
11262 case PTR_TO_BTF_ID | MEM_ALLOC:
11266 verbose(env, "verifier internal error: unknown reg type for lock check\n");
11271 if (!env->cur_state->active_lock.ptr)
11273 if (env->cur_state->active_lock.ptr != ptr ||
11274 env->cur_state->active_lock.id != id) {
11275 verbose(env, "held lock and object are not in the same allocation\n");
11281 static bool is_bpf_list_api_kfunc(u32 btf_id)
11283 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11284 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11285 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11286 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11289 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11291 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11292 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11293 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11296 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11298 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11299 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11302 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11304 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11307 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11309 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11310 insn->imm == special_kfunc_list[KF_bpf_throw];
11313 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11315 return is_bpf_rbtree_api_kfunc(btf_id);
11318 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11319 enum btf_field_type head_field_type,
11324 switch (head_field_type) {
11325 case BPF_LIST_HEAD:
11326 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11329 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11332 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11333 btf_field_type_name(head_field_type));
11338 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11339 btf_field_type_name(head_field_type));
11343 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11344 enum btf_field_type node_field_type,
11349 switch (node_field_type) {
11350 case BPF_LIST_NODE:
11351 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11352 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11355 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11356 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11359 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11360 btf_field_type_name(node_field_type));
11365 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11366 btf_field_type_name(node_field_type));
11371 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11372 struct bpf_reg_state *reg, u32 regno,
11373 struct bpf_kfunc_call_arg_meta *meta,
11374 enum btf_field_type head_field_type,
11375 struct btf_field **head_field)
11377 const char *head_type_name;
11378 struct btf_field *field;
11379 struct btf_record *rec;
11382 if (meta->btf != btf_vmlinux) {
11383 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11387 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11390 head_type_name = btf_field_type_name(head_field_type);
11391 if (!tnum_is_const(reg->var_off)) {
11393 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11394 regno, head_type_name);
11398 rec = reg_btf_record(reg);
11399 head_off = reg->off + reg->var_off.value;
11400 field = btf_record_find(rec, head_off, head_field_type);
11402 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11406 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11407 if (check_reg_allocation_locked(env, reg)) {
11408 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11409 rec->spin_lock_off, head_type_name);
11414 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11417 *head_field = field;
11421 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11422 struct bpf_reg_state *reg, u32 regno,
11423 struct bpf_kfunc_call_arg_meta *meta)
11425 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11426 &meta->arg_list_head.field);
11429 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11430 struct bpf_reg_state *reg, u32 regno,
11431 struct bpf_kfunc_call_arg_meta *meta)
11433 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11434 &meta->arg_rbtree_root.field);
11438 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11439 struct bpf_reg_state *reg, u32 regno,
11440 struct bpf_kfunc_call_arg_meta *meta,
11441 enum btf_field_type head_field_type,
11442 enum btf_field_type node_field_type,
11443 struct btf_field **node_field)
11445 const char *node_type_name;
11446 const struct btf_type *et, *t;
11447 struct btf_field *field;
11450 if (meta->btf != btf_vmlinux) {
11451 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11455 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11458 node_type_name = btf_field_type_name(node_field_type);
11459 if (!tnum_is_const(reg->var_off)) {
11461 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11462 regno, node_type_name);
11466 node_off = reg->off + reg->var_off.value;
11467 field = reg_find_field_offset(reg, node_off, node_field_type);
11468 if (!field || field->offset != node_off) {
11469 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11473 field = *node_field;
11475 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11476 t = btf_type_by_id(reg->btf, reg->btf_id);
11477 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11478 field->graph_root.value_btf_id, true)) {
11479 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11480 "in struct %s, but arg is at offset=%d in struct %s\n",
11481 btf_field_type_name(head_field_type),
11482 btf_field_type_name(node_field_type),
11483 field->graph_root.node_offset,
11484 btf_name_by_offset(field->graph_root.btf, et->name_off),
11485 node_off, btf_name_by_offset(reg->btf, t->name_off));
11488 meta->arg_btf = reg->btf;
11489 meta->arg_btf_id = reg->btf_id;
11491 if (node_off != field->graph_root.node_offset) {
11492 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11493 node_off, btf_field_type_name(node_field_type),
11494 field->graph_root.node_offset,
11495 btf_name_by_offset(field->graph_root.btf, et->name_off));
11502 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11503 struct bpf_reg_state *reg, u32 regno,
11504 struct bpf_kfunc_call_arg_meta *meta)
11506 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11507 BPF_LIST_HEAD, BPF_LIST_NODE,
11508 &meta->arg_list_head.field);
11511 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11512 struct bpf_reg_state *reg, u32 regno,
11513 struct bpf_kfunc_call_arg_meta *meta)
11515 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11516 BPF_RB_ROOT, BPF_RB_NODE,
11517 &meta->arg_rbtree_root.field);
11521 * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11522 * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11523 * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11524 * them can only be attached to some specific hook points.
11526 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11528 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11530 switch (prog_type) {
11531 case BPF_PROG_TYPE_LSM:
11533 case BPF_PROG_TYPE_TRACING:
11534 if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11538 return env->prog->aux->sleepable;
11542 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11545 const char *func_name = meta->func_name, *ref_tname;
11546 const struct btf *btf = meta->btf;
11547 const struct btf_param *args;
11548 struct btf_record *rec;
11552 args = (const struct btf_param *)(meta->func_proto + 1);
11553 nargs = btf_type_vlen(meta->func_proto);
11554 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11555 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11556 MAX_BPF_FUNC_REG_ARGS);
11560 /* Check that BTF function arguments match actual types that the
11563 for (i = 0; i < nargs; i++) {
11564 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
11565 const struct btf_type *t, *ref_t, *resolve_ret;
11566 enum bpf_arg_type arg_type = ARG_DONTCARE;
11567 u32 regno = i + 1, ref_id, type_size;
11568 bool is_ret_buf_sz = false;
11571 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11573 if (is_kfunc_arg_ignore(btf, &args[i]))
11576 if (btf_type_is_scalar(t)) {
11577 if (reg->type != SCALAR_VALUE) {
11578 verbose(env, "R%d is not a scalar\n", regno);
11582 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11583 if (meta->arg_constant.found) {
11584 verbose(env, "verifier internal error: only one constant argument permitted\n");
11587 if (!tnum_is_const(reg->var_off)) {
11588 verbose(env, "R%d must be a known constant\n", regno);
11591 ret = mark_chain_precision(env, regno);
11594 meta->arg_constant.found = true;
11595 meta->arg_constant.value = reg->var_off.value;
11596 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11597 meta->r0_rdonly = true;
11598 is_ret_buf_sz = true;
11599 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11600 is_ret_buf_sz = true;
11603 if (is_ret_buf_sz) {
11604 if (meta->r0_size) {
11605 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11609 if (!tnum_is_const(reg->var_off)) {
11610 verbose(env, "R%d is not a const\n", regno);
11614 meta->r0_size = reg->var_off.value;
11615 ret = mark_chain_precision(env, regno);
11622 if (!btf_type_is_ptr(t)) {
11623 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11627 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11628 (register_is_null(reg) || type_may_be_null(reg->type)) &&
11629 !is_kfunc_arg_nullable(meta->btf, &args[i])) {
11630 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11634 if (reg->ref_obj_id) {
11635 if (is_kfunc_release(meta) && meta->ref_obj_id) {
11636 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11637 regno, reg->ref_obj_id,
11641 meta->ref_obj_id = reg->ref_obj_id;
11642 if (is_kfunc_release(meta))
11643 meta->release_regno = regno;
11646 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11647 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11649 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11650 if (kf_arg_type < 0)
11651 return kf_arg_type;
11653 switch (kf_arg_type) {
11654 case KF_ARG_PTR_TO_NULL:
11656 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11657 case KF_ARG_PTR_TO_BTF_ID:
11658 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11661 if (!is_trusted_reg(reg)) {
11662 if (!is_kfunc_rcu(meta)) {
11663 verbose(env, "R%d must be referenced or trusted\n", regno);
11666 if (!is_rcu_reg(reg)) {
11667 verbose(env, "R%d must be a rcu pointer\n", regno);
11673 case KF_ARG_PTR_TO_CTX:
11674 /* Trusted arguments have the same offset checks as release arguments */
11675 arg_type |= OBJ_RELEASE;
11677 case KF_ARG_PTR_TO_DYNPTR:
11678 case KF_ARG_PTR_TO_ITER:
11679 case KF_ARG_PTR_TO_LIST_HEAD:
11680 case KF_ARG_PTR_TO_LIST_NODE:
11681 case KF_ARG_PTR_TO_RB_ROOT:
11682 case KF_ARG_PTR_TO_RB_NODE:
11683 case KF_ARG_PTR_TO_MEM:
11684 case KF_ARG_PTR_TO_MEM_SIZE:
11685 case KF_ARG_PTR_TO_CALLBACK:
11686 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11687 case KF_ARG_PTR_TO_CONST_STR:
11688 /* Trusted by default */
11695 if (is_kfunc_release(meta) && reg->ref_obj_id)
11696 arg_type |= OBJ_RELEASE;
11697 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11701 switch (kf_arg_type) {
11702 case KF_ARG_PTR_TO_CTX:
11703 if (reg->type != PTR_TO_CTX) {
11704 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11708 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11709 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11712 meta->ret_btf_id = ret;
11715 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11716 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
11717 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
11718 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
11721 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
11722 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
11723 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
11727 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11730 if (!reg->ref_obj_id) {
11731 verbose(env, "allocated object must be referenced\n");
11734 if (meta->btf == btf_vmlinux) {
11735 meta->arg_btf = reg->btf;
11736 meta->arg_btf_id = reg->btf_id;
11739 case KF_ARG_PTR_TO_DYNPTR:
11741 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11742 int clone_ref_obj_id = 0;
11744 if (reg->type != PTR_TO_STACK &&
11745 reg->type != CONST_PTR_TO_DYNPTR) {
11746 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11750 if (reg->type == CONST_PTR_TO_DYNPTR)
11751 dynptr_arg_type |= MEM_RDONLY;
11753 if (is_kfunc_arg_uninit(btf, &args[i]))
11754 dynptr_arg_type |= MEM_UNINIT;
11756 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11757 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11758 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11759 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11760 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11761 (dynptr_arg_type & MEM_UNINIT)) {
11762 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11764 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11765 verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11769 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11770 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11771 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11772 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11777 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11781 if (!(dynptr_arg_type & MEM_UNINIT)) {
11782 int id = dynptr_id(env, reg);
11785 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11788 meta->initialized_dynptr.id = id;
11789 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11790 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11795 case KF_ARG_PTR_TO_ITER:
11796 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
11797 if (!check_css_task_iter_allowlist(env)) {
11798 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
11802 ret = process_iter_arg(env, regno, insn_idx, meta);
11806 case KF_ARG_PTR_TO_LIST_HEAD:
11807 if (reg->type != PTR_TO_MAP_VALUE &&
11808 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11809 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11812 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11813 verbose(env, "allocated object must be referenced\n");
11816 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11820 case KF_ARG_PTR_TO_RB_ROOT:
11821 if (reg->type != PTR_TO_MAP_VALUE &&
11822 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11823 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11826 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11827 verbose(env, "allocated object must be referenced\n");
11830 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11834 case KF_ARG_PTR_TO_LIST_NODE:
11835 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11836 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11839 if (!reg->ref_obj_id) {
11840 verbose(env, "allocated object must be referenced\n");
11843 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11847 case KF_ARG_PTR_TO_RB_NODE:
11848 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11849 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11850 verbose(env, "rbtree_remove node input must be non-owning ref\n");
11853 if (in_rbtree_lock_required_cb(env)) {
11854 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11858 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11859 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11862 if (!reg->ref_obj_id) {
11863 verbose(env, "allocated object must be referenced\n");
11868 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11872 case KF_ARG_PTR_TO_BTF_ID:
11873 /* Only base_type is checked, further checks are done here */
11874 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11875 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11876 !reg2btf_ids[base_type(reg->type)]) {
11877 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11878 verbose(env, "expected %s or socket\n",
11879 reg_type_str(env, base_type(reg->type) |
11880 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11883 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11887 case KF_ARG_PTR_TO_MEM:
11888 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11889 if (IS_ERR(resolve_ret)) {
11890 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11891 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11894 ret = check_mem_reg(env, reg, regno, type_size);
11898 case KF_ARG_PTR_TO_MEM_SIZE:
11900 struct bpf_reg_state *buff_reg = ®s[regno];
11901 const struct btf_param *buff_arg = &args[i];
11902 struct bpf_reg_state *size_reg = ®s[regno + 1];
11903 const struct btf_param *size_arg = &args[i + 1];
11905 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11906 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11908 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11913 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11914 if (meta->arg_constant.found) {
11915 verbose(env, "verifier internal error: only one constant argument permitted\n");
11918 if (!tnum_is_const(size_reg->var_off)) {
11919 verbose(env, "R%d must be a known constant\n", regno + 1);
11922 meta->arg_constant.found = true;
11923 meta->arg_constant.value = size_reg->var_off.value;
11926 /* Skip next '__sz' or '__szk' argument */
11930 case KF_ARG_PTR_TO_CALLBACK:
11931 if (reg->type != PTR_TO_FUNC) {
11932 verbose(env, "arg%d expected pointer to func\n", i);
11935 meta->subprogno = reg->subprogno;
11937 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11938 if (!type_is_ptr_alloc_obj(reg->type)) {
11939 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11942 if (!type_is_non_owning_ref(reg->type))
11943 meta->arg_owning_ref = true;
11945 rec = reg_btf_record(reg);
11947 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11951 if (rec->refcount_off < 0) {
11952 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11956 meta->arg_btf = reg->btf;
11957 meta->arg_btf_id = reg->btf_id;
11959 case KF_ARG_PTR_TO_CONST_STR:
11960 if (reg->type != PTR_TO_MAP_VALUE) {
11961 verbose(env, "arg#%d doesn't point to a const string\n", i);
11964 ret = check_reg_const_str(env, reg, regno);
11971 if (is_kfunc_release(meta) && !meta->release_regno) {
11972 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11980 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11981 struct bpf_insn *insn,
11982 struct bpf_kfunc_call_arg_meta *meta,
11983 const char **kfunc_name)
11985 const struct btf_type *func, *func_proto;
11986 u32 func_id, *kfunc_flags;
11987 const char *func_name;
11988 struct btf *desc_btf;
11991 *kfunc_name = NULL;
11996 desc_btf = find_kfunc_desc_btf(env, insn->off);
11997 if (IS_ERR(desc_btf))
11998 return PTR_ERR(desc_btf);
12000 func_id = insn->imm;
12001 func = btf_type_by_id(desc_btf, func_id);
12002 func_name = btf_name_by_offset(desc_btf, func->name_off);
12004 *kfunc_name = func_name;
12005 func_proto = btf_type_by_id(desc_btf, func->type);
12007 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
12008 if (!kfunc_flags) {
12012 memset(meta, 0, sizeof(*meta));
12013 meta->btf = desc_btf;
12014 meta->func_id = func_id;
12015 meta->kfunc_flags = *kfunc_flags;
12016 meta->func_proto = func_proto;
12017 meta->func_name = func_name;
12022 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
12024 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12027 const struct btf_type *t, *ptr_type;
12028 u32 i, nargs, ptr_type_id, release_ref_obj_id;
12029 struct bpf_reg_state *regs = cur_regs(env);
12030 const char *func_name, *ptr_type_name;
12031 bool sleepable, rcu_lock, rcu_unlock;
12032 struct bpf_kfunc_call_arg_meta meta;
12033 struct bpf_insn_aux_data *insn_aux;
12034 int err, insn_idx = *insn_idx_p;
12035 const struct btf_param *args;
12036 const struct btf_type *ret_t;
12037 struct btf *desc_btf;
12039 /* skip for now, but return error when we find this in fixup_kfunc_call */
12043 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
12044 if (err == -EACCES && func_name)
12045 verbose(env, "calling kernel function %s is not allowed\n", func_name);
12048 desc_btf = meta.btf;
12049 insn_aux = &env->insn_aux_data[insn_idx];
12051 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
12053 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12054 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12058 sleepable = is_kfunc_sleepable(&meta);
12059 if (sleepable && !env->prog->aux->sleepable) {
12060 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12064 /* Check the arguments */
12065 err = check_kfunc_args(env, &meta, insn_idx);
12069 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12070 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12071 set_rbtree_add_callback_state);
12073 verbose(env, "kfunc %s#%d failed callback verification\n",
12074 func_name, meta.func_id);
12079 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
12080 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
12082 if (env->cur_state->active_rcu_lock) {
12083 struct bpf_func_state *state;
12084 struct bpf_reg_state *reg;
12085 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
12087 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
12088 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
12093 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
12095 } else if (rcu_unlock) {
12096 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
12097 if (reg->type & MEM_RCU) {
12098 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
12099 reg->type |= PTR_UNTRUSTED;
12102 env->cur_state->active_rcu_lock = false;
12103 } else if (sleepable) {
12104 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
12107 } else if (rcu_lock) {
12108 env->cur_state->active_rcu_lock = true;
12109 } else if (rcu_unlock) {
12110 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
12114 /* In case of release function, we get register number of refcounted
12115 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
12117 if (meta.release_regno) {
12118 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
12120 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12121 func_name, meta.func_id);
12126 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12127 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12128 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12129 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
12130 insn_aux->insert_off = regs[BPF_REG_2].off;
12131 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
12132 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
12134 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
12135 func_name, meta.func_id);
12139 err = release_reference(env, release_ref_obj_id);
12141 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12142 func_name, meta.func_id);
12147 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12148 if (!bpf_jit_supports_exceptions()) {
12149 verbose(env, "JIT does not support calling kfunc %s#%d\n",
12150 func_name, meta.func_id);
12153 env->seen_exception = true;
12155 /* In the case of the default callback, the cookie value passed
12156 * to bpf_throw becomes the return value of the program.
12158 if (!env->exception_callback_subprog) {
12159 err = check_return_code(env, BPF_REG_1, "R1");
12165 for (i = 0; i < CALLER_SAVED_REGS; i++)
12166 mark_reg_not_init(env, regs, caller_saved[i]);
12168 /* Check return type */
12169 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
12171 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
12172 /* Only exception is bpf_obj_new_impl */
12173 if (meta.btf != btf_vmlinux ||
12174 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
12175 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
12176 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
12177 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12182 if (btf_type_is_scalar(t)) {
12183 mark_reg_unknown(env, regs, BPF_REG_0);
12184 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12185 } else if (btf_type_is_ptr(t)) {
12186 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12188 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12189 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12190 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12191 struct btf_struct_meta *struct_meta;
12192 struct btf *ret_btf;
12195 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12198 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12199 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12203 ret_btf = env->prog->aux->btf;
12204 ret_btf_id = meta.arg_constant.value;
12206 /* This may be NULL due to user not supplying a BTF */
12208 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12212 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12213 if (!ret_t || !__btf_type_is_struct(ret_t)) {
12214 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12218 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12219 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
12220 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
12221 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
12225 if (!bpf_global_percpu_ma_set) {
12226 mutex_lock(&bpf_percpu_ma_lock);
12227 if (!bpf_global_percpu_ma_set) {
12228 /* Charge memory allocated with bpf_global_percpu_ma to
12229 * root memcg. The obj_cgroup for root memcg is NULL.
12231 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
12233 bpf_global_percpu_ma_set = true;
12235 mutex_unlock(&bpf_percpu_ma_lock);
12240 mutex_lock(&bpf_percpu_ma_lock);
12241 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
12242 mutex_unlock(&bpf_percpu_ma_lock);
12247 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12248 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12249 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12250 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12255 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12260 mark_reg_known_zero(env, regs, BPF_REG_0);
12261 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12262 regs[BPF_REG_0].btf = ret_btf;
12263 regs[BPF_REG_0].btf_id = ret_btf_id;
12264 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12265 regs[BPF_REG_0].type |= MEM_PERCPU;
12267 insn_aux->obj_new_size = ret_t->size;
12268 insn_aux->kptr_struct_meta = struct_meta;
12269 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12270 mark_reg_known_zero(env, regs, BPF_REG_0);
12271 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12272 regs[BPF_REG_0].btf = meta.arg_btf;
12273 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12275 insn_aux->kptr_struct_meta =
12276 btf_find_struct_meta(meta.arg_btf,
12278 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12279 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12280 struct btf_field *field = meta.arg_list_head.field;
12282 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12283 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12284 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12285 struct btf_field *field = meta.arg_rbtree_root.field;
12287 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12288 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12289 mark_reg_known_zero(env, regs, BPF_REG_0);
12290 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12291 regs[BPF_REG_0].btf = desc_btf;
12292 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12293 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12294 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12295 if (!ret_t || !btf_type_is_struct(ret_t)) {
12297 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12301 mark_reg_known_zero(env, regs, BPF_REG_0);
12302 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12303 regs[BPF_REG_0].btf = desc_btf;
12304 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12305 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12306 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12307 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12309 mark_reg_known_zero(env, regs, BPF_REG_0);
12311 if (!meta.arg_constant.found) {
12312 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12316 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12318 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12319 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12321 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12322 regs[BPF_REG_0].type |= MEM_RDONLY;
12324 /* this will set env->seen_direct_write to true */
12325 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12326 verbose(env, "the prog does not allow writes to packet data\n");
12331 if (!meta.initialized_dynptr.id) {
12332 verbose(env, "verifier internal error: no dynptr id\n");
12335 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12337 /* we don't need to set BPF_REG_0's ref obj id
12338 * because packet slices are not refcounted (see
12339 * dynptr_type_refcounted)
12342 verbose(env, "kernel function %s unhandled dynamic return type\n",
12346 } else if (!__btf_type_is_struct(ptr_type)) {
12347 if (!meta.r0_size) {
12350 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12352 meta.r0_rdonly = true;
12355 if (!meta.r0_size) {
12356 ptr_type_name = btf_name_by_offset(desc_btf,
12357 ptr_type->name_off);
12359 "kernel function %s returns pointer type %s %s is not supported\n",
12361 btf_type_str(ptr_type),
12366 mark_reg_known_zero(env, regs, BPF_REG_0);
12367 regs[BPF_REG_0].type = PTR_TO_MEM;
12368 regs[BPF_REG_0].mem_size = meta.r0_size;
12370 if (meta.r0_rdonly)
12371 regs[BPF_REG_0].type |= MEM_RDONLY;
12373 /* Ensures we don't access the memory after a release_reference() */
12374 if (meta.ref_obj_id)
12375 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12377 mark_reg_known_zero(env, regs, BPF_REG_0);
12378 regs[BPF_REG_0].btf = desc_btf;
12379 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12380 regs[BPF_REG_0].btf_id = ptr_type_id;
12383 if (is_kfunc_ret_null(&meta)) {
12384 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12385 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12386 regs[BPF_REG_0].id = ++env->id_gen;
12388 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12389 if (is_kfunc_acquire(&meta)) {
12390 int id = acquire_reference_state(env, insn_idx);
12394 if (is_kfunc_ret_null(&meta))
12395 regs[BPF_REG_0].id = id;
12396 regs[BPF_REG_0].ref_obj_id = id;
12397 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12398 ref_set_non_owning(env, ®s[BPF_REG_0]);
12401 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
12402 regs[BPF_REG_0].id = ++env->id_gen;
12403 } else if (btf_type_is_void(t)) {
12404 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12405 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12406 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12407 insn_aux->kptr_struct_meta =
12408 btf_find_struct_meta(meta.arg_btf,
12414 nargs = btf_type_vlen(meta.func_proto);
12415 args = (const struct btf_param *)(meta.func_proto + 1);
12416 for (i = 0; i < nargs; i++) {
12419 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12420 if (btf_type_is_ptr(t))
12421 mark_btf_func_reg_size(env, regno, sizeof(void *));
12423 /* scalar. ensured by btf_check_kfunc_arg_match() */
12424 mark_btf_func_reg_size(env, regno, t->size);
12427 if (is_iter_next_kfunc(&meta)) {
12428 err = process_iter_next_call(env, insn_idx, &meta);
12436 static bool signed_add_overflows(s64 a, s64 b)
12438 /* Do the add in u64, where overflow is well-defined */
12439 s64 res = (s64)((u64)a + (u64)b);
12446 static bool signed_add32_overflows(s32 a, s32 b)
12448 /* Do the add in u32, where overflow is well-defined */
12449 s32 res = (s32)((u32)a + (u32)b);
12456 static bool signed_sub_overflows(s64 a, s64 b)
12458 /* Do the sub in u64, where overflow is well-defined */
12459 s64 res = (s64)((u64)a - (u64)b);
12466 static bool signed_sub32_overflows(s32 a, s32 b)
12468 /* Do the sub in u32, where overflow is well-defined */
12469 s32 res = (s32)((u32)a - (u32)b);
12476 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12477 const struct bpf_reg_state *reg,
12478 enum bpf_reg_type type)
12480 bool known = tnum_is_const(reg->var_off);
12481 s64 val = reg->var_off.value;
12482 s64 smin = reg->smin_value;
12484 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12485 verbose(env, "math between %s pointer and %lld is not allowed\n",
12486 reg_type_str(env, type), val);
12490 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12491 verbose(env, "%s pointer offset %d is not allowed\n",
12492 reg_type_str(env, type), reg->off);
12496 if (smin == S64_MIN) {
12497 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12498 reg_type_str(env, type));
12502 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12503 verbose(env, "value %lld makes %s pointer be out of bounds\n",
12504 smin, reg_type_str(env, type));
12512 REASON_BOUNDS = -1,
12519 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12520 u32 *alu_limit, bool mask_to_left)
12522 u32 max = 0, ptr_limit = 0;
12524 switch (ptr_reg->type) {
12526 /* Offset 0 is out-of-bounds, but acceptable start for the
12527 * left direction, see BPF_REG_FP. Also, unknown scalar
12528 * offset where we would need to deal with min/max bounds is
12529 * currently prohibited for unprivileged.
12531 max = MAX_BPF_STACK + mask_to_left;
12532 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12534 case PTR_TO_MAP_VALUE:
12535 max = ptr_reg->map_ptr->value_size;
12536 ptr_limit = (mask_to_left ?
12537 ptr_reg->smin_value :
12538 ptr_reg->umax_value) + ptr_reg->off;
12541 return REASON_TYPE;
12544 if (ptr_limit >= max)
12545 return REASON_LIMIT;
12546 *alu_limit = ptr_limit;
12550 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12551 const struct bpf_insn *insn)
12553 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12556 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12557 u32 alu_state, u32 alu_limit)
12559 /* If we arrived here from different branches with different
12560 * state or limits to sanitize, then this won't work.
12562 if (aux->alu_state &&
12563 (aux->alu_state != alu_state ||
12564 aux->alu_limit != alu_limit))
12565 return REASON_PATHS;
12567 /* Corresponding fixup done in do_misc_fixups(). */
12568 aux->alu_state = alu_state;
12569 aux->alu_limit = alu_limit;
12573 static int sanitize_val_alu(struct bpf_verifier_env *env,
12574 struct bpf_insn *insn)
12576 struct bpf_insn_aux_data *aux = cur_aux(env);
12578 if (can_skip_alu_sanitation(env, insn))
12581 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12584 static bool sanitize_needed(u8 opcode)
12586 return opcode == BPF_ADD || opcode == BPF_SUB;
12589 struct bpf_sanitize_info {
12590 struct bpf_insn_aux_data aux;
12594 static struct bpf_verifier_state *
12595 sanitize_speculative_path(struct bpf_verifier_env *env,
12596 const struct bpf_insn *insn,
12597 u32 next_idx, u32 curr_idx)
12599 struct bpf_verifier_state *branch;
12600 struct bpf_reg_state *regs;
12602 branch = push_stack(env, next_idx, curr_idx, true);
12603 if (branch && insn) {
12604 regs = branch->frame[branch->curframe]->regs;
12605 if (BPF_SRC(insn->code) == BPF_K) {
12606 mark_reg_unknown(env, regs, insn->dst_reg);
12607 } else if (BPF_SRC(insn->code) == BPF_X) {
12608 mark_reg_unknown(env, regs, insn->dst_reg);
12609 mark_reg_unknown(env, regs, insn->src_reg);
12615 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12616 struct bpf_insn *insn,
12617 const struct bpf_reg_state *ptr_reg,
12618 const struct bpf_reg_state *off_reg,
12619 struct bpf_reg_state *dst_reg,
12620 struct bpf_sanitize_info *info,
12621 const bool commit_window)
12623 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12624 struct bpf_verifier_state *vstate = env->cur_state;
12625 bool off_is_imm = tnum_is_const(off_reg->var_off);
12626 bool off_is_neg = off_reg->smin_value < 0;
12627 bool ptr_is_dst_reg = ptr_reg == dst_reg;
12628 u8 opcode = BPF_OP(insn->code);
12629 u32 alu_state, alu_limit;
12630 struct bpf_reg_state tmp;
12634 if (can_skip_alu_sanitation(env, insn))
12637 /* We already marked aux for masking from non-speculative
12638 * paths, thus we got here in the first place. We only care
12639 * to explore bad access from here.
12641 if (vstate->speculative)
12644 if (!commit_window) {
12645 if (!tnum_is_const(off_reg->var_off) &&
12646 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12647 return REASON_BOUNDS;
12649 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
12650 (opcode == BPF_SUB && !off_is_neg);
12653 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12657 if (commit_window) {
12658 /* In commit phase we narrow the masking window based on
12659 * the observed pointer move after the simulated operation.
12661 alu_state = info->aux.alu_state;
12662 alu_limit = abs(info->aux.alu_limit - alu_limit);
12664 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12665 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12666 alu_state |= ptr_is_dst_reg ?
12667 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12669 /* Limit pruning on unknown scalars to enable deep search for
12670 * potential masking differences from other program paths.
12673 env->explore_alu_limits = true;
12676 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12680 /* If we're in commit phase, we're done here given we already
12681 * pushed the truncated dst_reg into the speculative verification
12684 * Also, when register is a known constant, we rewrite register-based
12685 * operation to immediate-based, and thus do not need masking (and as
12686 * a consequence, do not need to simulate the zero-truncation either).
12688 if (commit_window || off_is_imm)
12691 /* Simulate and find potential out-of-bounds access under
12692 * speculative execution from truncation as a result of
12693 * masking when off was not within expected range. If off
12694 * sits in dst, then we temporarily need to move ptr there
12695 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12696 * for cases where we use K-based arithmetic in one direction
12697 * and truncated reg-based in the other in order to explore
12700 if (!ptr_is_dst_reg) {
12702 copy_register_state(dst_reg, ptr_reg);
12704 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12706 if (!ptr_is_dst_reg && ret)
12708 return !ret ? REASON_STACK : 0;
12711 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12713 struct bpf_verifier_state *vstate = env->cur_state;
12715 /* If we simulate paths under speculation, we don't update the
12716 * insn as 'seen' such that when we verify unreachable paths in
12717 * the non-speculative domain, sanitize_dead_code() can still
12718 * rewrite/sanitize them.
12720 if (!vstate->speculative)
12721 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12724 static int sanitize_err(struct bpf_verifier_env *env,
12725 const struct bpf_insn *insn, int reason,
12726 const struct bpf_reg_state *off_reg,
12727 const struct bpf_reg_state *dst_reg)
12729 static const char *err = "pointer arithmetic with it prohibited for !root";
12730 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12731 u32 dst = insn->dst_reg, src = insn->src_reg;
12734 case REASON_BOUNDS:
12735 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12736 off_reg == dst_reg ? dst : src, err);
12739 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12740 off_reg == dst_reg ? src : dst, err);
12743 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12747 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12751 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12755 verbose(env, "verifier internal error: unknown reason (%d)\n",
12763 /* check that stack access falls within stack limits and that 'reg' doesn't
12764 * have a variable offset.
12766 * Variable offset is prohibited for unprivileged mode for simplicity since it
12767 * requires corresponding support in Spectre masking for stack ALU. See also
12768 * retrieve_ptr_limit().
12771 * 'off' includes 'reg->off'.
12773 static int check_stack_access_for_ptr_arithmetic(
12774 struct bpf_verifier_env *env,
12776 const struct bpf_reg_state *reg,
12779 if (!tnum_is_const(reg->var_off)) {
12782 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12783 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12784 regno, tn_buf, off);
12788 if (off >= 0 || off < -MAX_BPF_STACK) {
12789 verbose(env, "R%d stack pointer arithmetic goes out of range, "
12790 "prohibited for !root; off=%d\n", regno, off);
12797 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12798 const struct bpf_insn *insn,
12799 const struct bpf_reg_state *dst_reg)
12801 u32 dst = insn->dst_reg;
12803 /* For unprivileged we require that resulting offset must be in bounds
12804 * in order to be able to sanitize access later on.
12806 if (env->bypass_spec_v1)
12809 switch (dst_reg->type) {
12811 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12812 dst_reg->off + dst_reg->var_off.value))
12815 case PTR_TO_MAP_VALUE:
12816 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12817 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12818 "prohibited for !root\n", dst);
12829 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12830 * Caller should also handle BPF_MOV case separately.
12831 * If we return -EACCES, caller may want to try again treating pointer as a
12832 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
12834 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12835 struct bpf_insn *insn,
12836 const struct bpf_reg_state *ptr_reg,
12837 const struct bpf_reg_state *off_reg)
12839 struct bpf_verifier_state *vstate = env->cur_state;
12840 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12841 struct bpf_reg_state *regs = state->regs, *dst_reg;
12842 bool known = tnum_is_const(off_reg->var_off);
12843 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12844 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12845 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12846 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12847 struct bpf_sanitize_info info = {};
12848 u8 opcode = BPF_OP(insn->code);
12849 u32 dst = insn->dst_reg;
12852 dst_reg = ®s[dst];
12854 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12855 smin_val > smax_val || umin_val > umax_val) {
12856 /* Taint dst register if offset had invalid bounds derived from
12857 * e.g. dead branches.
12859 __mark_reg_unknown(env, dst_reg);
12863 if (BPF_CLASS(insn->code) != BPF_ALU64) {
12864 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12865 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12866 __mark_reg_unknown(env, dst_reg);
12871 "R%d 32-bit pointer arithmetic prohibited\n",
12876 if (ptr_reg->type & PTR_MAYBE_NULL) {
12877 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12878 dst, reg_type_str(env, ptr_reg->type));
12882 switch (base_type(ptr_reg->type)) {
12884 case PTR_TO_MAP_VALUE:
12885 case PTR_TO_MAP_KEY:
12887 case PTR_TO_PACKET_META:
12888 case PTR_TO_PACKET:
12889 case PTR_TO_TP_BUFFER:
12890 case PTR_TO_BTF_ID:
12894 case CONST_PTR_TO_DYNPTR:
12896 case PTR_TO_FLOW_KEYS:
12900 case CONST_PTR_TO_MAP:
12901 /* smin_val represents the known value */
12902 if (known && smin_val == 0 && opcode == BPF_ADD)
12906 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12907 dst, reg_type_str(env, ptr_reg->type));
12911 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12912 * The id may be overwritten later if we create a new variable offset.
12914 dst_reg->type = ptr_reg->type;
12915 dst_reg->id = ptr_reg->id;
12917 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12918 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12921 /* pointer types do not carry 32-bit bounds at the moment. */
12922 __mark_reg32_unbounded(dst_reg);
12924 if (sanitize_needed(opcode)) {
12925 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12928 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12933 /* We can take a fixed offset as long as it doesn't overflow
12934 * the s32 'off' field
12936 if (known && (ptr_reg->off + smin_val ==
12937 (s64)(s32)(ptr_reg->off + smin_val))) {
12938 /* pointer += K. Accumulate it into fixed offset */
12939 dst_reg->smin_value = smin_ptr;
12940 dst_reg->smax_value = smax_ptr;
12941 dst_reg->umin_value = umin_ptr;
12942 dst_reg->umax_value = umax_ptr;
12943 dst_reg->var_off = ptr_reg->var_off;
12944 dst_reg->off = ptr_reg->off + smin_val;
12945 dst_reg->raw = ptr_reg->raw;
12948 /* A new variable offset is created. Note that off_reg->off
12949 * == 0, since it's a scalar.
12950 * dst_reg gets the pointer type and since some positive
12951 * integer value was added to the pointer, give it a new 'id'
12952 * if it's a PTR_TO_PACKET.
12953 * this creates a new 'base' pointer, off_reg (variable) gets
12954 * added into the variable offset, and we copy the fixed offset
12957 if (signed_add_overflows(smin_ptr, smin_val) ||
12958 signed_add_overflows(smax_ptr, smax_val)) {
12959 dst_reg->smin_value = S64_MIN;
12960 dst_reg->smax_value = S64_MAX;
12962 dst_reg->smin_value = smin_ptr + smin_val;
12963 dst_reg->smax_value = smax_ptr + smax_val;
12965 if (umin_ptr + umin_val < umin_ptr ||
12966 umax_ptr + umax_val < umax_ptr) {
12967 dst_reg->umin_value = 0;
12968 dst_reg->umax_value = U64_MAX;
12970 dst_reg->umin_value = umin_ptr + umin_val;
12971 dst_reg->umax_value = umax_ptr + umax_val;
12973 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12974 dst_reg->off = ptr_reg->off;
12975 dst_reg->raw = ptr_reg->raw;
12976 if (reg_is_pkt_pointer(ptr_reg)) {
12977 dst_reg->id = ++env->id_gen;
12978 /* something was added to pkt_ptr, set range to zero */
12979 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12983 if (dst_reg == off_reg) {
12984 /* scalar -= pointer. Creates an unknown scalar */
12985 verbose(env, "R%d tried to subtract pointer from scalar\n",
12989 /* We don't allow subtraction from FP, because (according to
12990 * test_verifier.c test "invalid fp arithmetic", JITs might not
12991 * be able to deal with it.
12993 if (ptr_reg->type == PTR_TO_STACK) {
12994 verbose(env, "R%d subtraction from stack pointer prohibited\n",
12998 if (known && (ptr_reg->off - smin_val ==
12999 (s64)(s32)(ptr_reg->off - smin_val))) {
13000 /* pointer -= K. Subtract it from fixed offset */
13001 dst_reg->smin_value = smin_ptr;
13002 dst_reg->smax_value = smax_ptr;
13003 dst_reg->umin_value = umin_ptr;
13004 dst_reg->umax_value = umax_ptr;
13005 dst_reg->var_off = ptr_reg->var_off;
13006 dst_reg->id = ptr_reg->id;
13007 dst_reg->off = ptr_reg->off - smin_val;
13008 dst_reg->raw = ptr_reg->raw;
13011 /* A new variable offset is created. If the subtrahend is known
13012 * nonnegative, then any reg->range we had before is still good.
13014 if (signed_sub_overflows(smin_ptr, smax_val) ||
13015 signed_sub_overflows(smax_ptr, smin_val)) {
13016 /* Overflow possible, we know nothing */
13017 dst_reg->smin_value = S64_MIN;
13018 dst_reg->smax_value = S64_MAX;
13020 dst_reg->smin_value = smin_ptr - smax_val;
13021 dst_reg->smax_value = smax_ptr - smin_val;
13023 if (umin_ptr < umax_val) {
13024 /* Overflow possible, we know nothing */
13025 dst_reg->umin_value = 0;
13026 dst_reg->umax_value = U64_MAX;
13028 /* Cannot overflow (as long as bounds are consistent) */
13029 dst_reg->umin_value = umin_ptr - umax_val;
13030 dst_reg->umax_value = umax_ptr - umin_val;
13032 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
13033 dst_reg->off = ptr_reg->off;
13034 dst_reg->raw = ptr_reg->raw;
13035 if (reg_is_pkt_pointer(ptr_reg)) {
13036 dst_reg->id = ++env->id_gen;
13037 /* something was added to pkt_ptr, set range to zero */
13039 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13045 /* bitwise ops on pointers are troublesome, prohibit. */
13046 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
13047 dst, bpf_alu_string[opcode >> 4]);
13050 /* other operators (e.g. MUL,LSH) produce non-pointer results */
13051 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
13052 dst, bpf_alu_string[opcode >> 4]);
13056 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
13058 reg_bounds_sync(dst_reg);
13059 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
13061 if (sanitize_needed(opcode)) {
13062 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13065 return sanitize_err(env, insn, ret, off_reg, dst_reg);
13071 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13072 struct bpf_reg_state *src_reg)
13074 s32 smin_val = src_reg->s32_min_value;
13075 s32 smax_val = src_reg->s32_max_value;
13076 u32 umin_val = src_reg->u32_min_value;
13077 u32 umax_val = src_reg->u32_max_value;
13079 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
13080 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
13081 dst_reg->s32_min_value = S32_MIN;
13082 dst_reg->s32_max_value = S32_MAX;
13084 dst_reg->s32_min_value += smin_val;
13085 dst_reg->s32_max_value += smax_val;
13087 if (dst_reg->u32_min_value + umin_val < umin_val ||
13088 dst_reg->u32_max_value + umax_val < umax_val) {
13089 dst_reg->u32_min_value = 0;
13090 dst_reg->u32_max_value = U32_MAX;
13092 dst_reg->u32_min_value += umin_val;
13093 dst_reg->u32_max_value += umax_val;
13097 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13098 struct bpf_reg_state *src_reg)
13100 s64 smin_val = src_reg->smin_value;
13101 s64 smax_val = src_reg->smax_value;
13102 u64 umin_val = src_reg->umin_value;
13103 u64 umax_val = src_reg->umax_value;
13105 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
13106 signed_add_overflows(dst_reg->smax_value, smax_val)) {
13107 dst_reg->smin_value = S64_MIN;
13108 dst_reg->smax_value = S64_MAX;
13110 dst_reg->smin_value += smin_val;
13111 dst_reg->smax_value += smax_val;
13113 if (dst_reg->umin_value + umin_val < umin_val ||
13114 dst_reg->umax_value + umax_val < umax_val) {
13115 dst_reg->umin_value = 0;
13116 dst_reg->umax_value = U64_MAX;
13118 dst_reg->umin_value += umin_val;
13119 dst_reg->umax_value += umax_val;
13123 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13124 struct bpf_reg_state *src_reg)
13126 s32 smin_val = src_reg->s32_min_value;
13127 s32 smax_val = src_reg->s32_max_value;
13128 u32 umin_val = src_reg->u32_min_value;
13129 u32 umax_val = src_reg->u32_max_value;
13131 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
13132 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
13133 /* Overflow possible, we know nothing */
13134 dst_reg->s32_min_value = S32_MIN;
13135 dst_reg->s32_max_value = S32_MAX;
13137 dst_reg->s32_min_value -= smax_val;
13138 dst_reg->s32_max_value -= smin_val;
13140 if (dst_reg->u32_min_value < umax_val) {
13141 /* Overflow possible, we know nothing */
13142 dst_reg->u32_min_value = 0;
13143 dst_reg->u32_max_value = U32_MAX;
13145 /* Cannot overflow (as long as bounds are consistent) */
13146 dst_reg->u32_min_value -= umax_val;
13147 dst_reg->u32_max_value -= umin_val;
13151 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13152 struct bpf_reg_state *src_reg)
13154 s64 smin_val = src_reg->smin_value;
13155 s64 smax_val = src_reg->smax_value;
13156 u64 umin_val = src_reg->umin_value;
13157 u64 umax_val = src_reg->umax_value;
13159 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
13160 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
13161 /* Overflow possible, we know nothing */
13162 dst_reg->smin_value = S64_MIN;
13163 dst_reg->smax_value = S64_MAX;
13165 dst_reg->smin_value -= smax_val;
13166 dst_reg->smax_value -= smin_val;
13168 if (dst_reg->umin_value < umax_val) {
13169 /* Overflow possible, we know nothing */
13170 dst_reg->umin_value = 0;
13171 dst_reg->umax_value = U64_MAX;
13173 /* Cannot overflow (as long as bounds are consistent) */
13174 dst_reg->umin_value -= umax_val;
13175 dst_reg->umax_value -= umin_val;
13179 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13180 struct bpf_reg_state *src_reg)
13182 s32 smin_val = src_reg->s32_min_value;
13183 u32 umin_val = src_reg->u32_min_value;
13184 u32 umax_val = src_reg->u32_max_value;
13186 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13187 /* Ain't nobody got time to multiply that sign */
13188 __mark_reg32_unbounded(dst_reg);
13191 /* Both values are positive, so we can work with unsigned and
13192 * copy the result to signed (unless it exceeds S32_MAX).
13194 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13195 /* Potential overflow, we know nothing */
13196 __mark_reg32_unbounded(dst_reg);
13199 dst_reg->u32_min_value *= umin_val;
13200 dst_reg->u32_max_value *= umax_val;
13201 if (dst_reg->u32_max_value > S32_MAX) {
13202 /* Overflow possible, we know nothing */
13203 dst_reg->s32_min_value = S32_MIN;
13204 dst_reg->s32_max_value = S32_MAX;
13206 dst_reg->s32_min_value = dst_reg->u32_min_value;
13207 dst_reg->s32_max_value = dst_reg->u32_max_value;
13211 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13212 struct bpf_reg_state *src_reg)
13214 s64 smin_val = src_reg->smin_value;
13215 u64 umin_val = src_reg->umin_value;
13216 u64 umax_val = src_reg->umax_value;
13218 if (smin_val < 0 || dst_reg->smin_value < 0) {
13219 /* Ain't nobody got time to multiply that sign */
13220 __mark_reg64_unbounded(dst_reg);
13223 /* Both values are positive, so we can work with unsigned and
13224 * copy the result to signed (unless it exceeds S64_MAX).
13226 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13227 /* Potential overflow, we know nothing */
13228 __mark_reg64_unbounded(dst_reg);
13231 dst_reg->umin_value *= umin_val;
13232 dst_reg->umax_value *= umax_val;
13233 if (dst_reg->umax_value > S64_MAX) {
13234 /* Overflow possible, we know nothing */
13235 dst_reg->smin_value = S64_MIN;
13236 dst_reg->smax_value = S64_MAX;
13238 dst_reg->smin_value = dst_reg->umin_value;
13239 dst_reg->smax_value = dst_reg->umax_value;
13243 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13244 struct bpf_reg_state *src_reg)
13246 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13247 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13248 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13249 s32 smin_val = src_reg->s32_min_value;
13250 u32 umax_val = src_reg->u32_max_value;
13252 if (src_known && dst_known) {
13253 __mark_reg32_known(dst_reg, var32_off.value);
13257 /* We get our minimum from the var_off, since that's inherently
13258 * bitwise. Our maximum is the minimum of the operands' maxima.
13260 dst_reg->u32_min_value = var32_off.value;
13261 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13262 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13263 /* Lose signed bounds when ANDing negative numbers,
13264 * ain't nobody got time for that.
13266 dst_reg->s32_min_value = S32_MIN;
13267 dst_reg->s32_max_value = S32_MAX;
13269 /* ANDing two positives gives a positive, so safe to
13270 * cast result into s64.
13272 dst_reg->s32_min_value = dst_reg->u32_min_value;
13273 dst_reg->s32_max_value = dst_reg->u32_max_value;
13277 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13278 struct bpf_reg_state *src_reg)
13280 bool src_known = tnum_is_const(src_reg->var_off);
13281 bool dst_known = tnum_is_const(dst_reg->var_off);
13282 s64 smin_val = src_reg->smin_value;
13283 u64 umax_val = src_reg->umax_value;
13285 if (src_known && dst_known) {
13286 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13290 /* We get our minimum from the var_off, since that's inherently
13291 * bitwise. Our maximum is the minimum of the operands' maxima.
13293 dst_reg->umin_value = dst_reg->var_off.value;
13294 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13295 if (dst_reg->smin_value < 0 || smin_val < 0) {
13296 /* Lose signed bounds when ANDing negative numbers,
13297 * ain't nobody got time for that.
13299 dst_reg->smin_value = S64_MIN;
13300 dst_reg->smax_value = S64_MAX;
13302 /* ANDing two positives gives a positive, so safe to
13303 * cast result into s64.
13305 dst_reg->smin_value = dst_reg->umin_value;
13306 dst_reg->smax_value = dst_reg->umax_value;
13308 /* We may learn something more from the var_off */
13309 __update_reg_bounds(dst_reg);
13312 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13313 struct bpf_reg_state *src_reg)
13315 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13316 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13317 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13318 s32 smin_val = src_reg->s32_min_value;
13319 u32 umin_val = src_reg->u32_min_value;
13321 if (src_known && dst_known) {
13322 __mark_reg32_known(dst_reg, var32_off.value);
13326 /* We get our maximum from the var_off, and our minimum is the
13327 * maximum of the operands' minima
13329 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13330 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13331 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13332 /* Lose signed bounds when ORing negative numbers,
13333 * ain't nobody got time for that.
13335 dst_reg->s32_min_value = S32_MIN;
13336 dst_reg->s32_max_value = S32_MAX;
13338 /* ORing two positives gives a positive, so safe to
13339 * cast result into s64.
13341 dst_reg->s32_min_value = dst_reg->u32_min_value;
13342 dst_reg->s32_max_value = dst_reg->u32_max_value;
13346 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13347 struct bpf_reg_state *src_reg)
13349 bool src_known = tnum_is_const(src_reg->var_off);
13350 bool dst_known = tnum_is_const(dst_reg->var_off);
13351 s64 smin_val = src_reg->smin_value;
13352 u64 umin_val = src_reg->umin_value;
13354 if (src_known && dst_known) {
13355 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13359 /* We get our maximum from the var_off, and our minimum is the
13360 * maximum of the operands' minima
13362 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13363 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13364 if (dst_reg->smin_value < 0 || smin_val < 0) {
13365 /* Lose signed bounds when ORing negative numbers,
13366 * ain't nobody got time for that.
13368 dst_reg->smin_value = S64_MIN;
13369 dst_reg->smax_value = S64_MAX;
13371 /* ORing two positives gives a positive, so safe to
13372 * cast result into s64.
13374 dst_reg->smin_value = dst_reg->umin_value;
13375 dst_reg->smax_value = dst_reg->umax_value;
13377 /* We may learn something more from the var_off */
13378 __update_reg_bounds(dst_reg);
13381 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13382 struct bpf_reg_state *src_reg)
13384 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13385 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13386 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13387 s32 smin_val = src_reg->s32_min_value;
13389 if (src_known && dst_known) {
13390 __mark_reg32_known(dst_reg, var32_off.value);
13394 /* We get both minimum and maximum from the var32_off. */
13395 dst_reg->u32_min_value = var32_off.value;
13396 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13398 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13399 /* XORing two positive sign numbers gives a positive,
13400 * so safe to cast u32 result into s32.
13402 dst_reg->s32_min_value = dst_reg->u32_min_value;
13403 dst_reg->s32_max_value = dst_reg->u32_max_value;
13405 dst_reg->s32_min_value = S32_MIN;
13406 dst_reg->s32_max_value = S32_MAX;
13410 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13411 struct bpf_reg_state *src_reg)
13413 bool src_known = tnum_is_const(src_reg->var_off);
13414 bool dst_known = tnum_is_const(dst_reg->var_off);
13415 s64 smin_val = src_reg->smin_value;
13417 if (src_known && dst_known) {
13418 /* dst_reg->var_off.value has been updated earlier */
13419 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13423 /* We get both minimum and maximum from the var_off. */
13424 dst_reg->umin_value = dst_reg->var_off.value;
13425 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13427 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13428 /* XORing two positive sign numbers gives a positive,
13429 * so safe to cast u64 result into s64.
13431 dst_reg->smin_value = dst_reg->umin_value;
13432 dst_reg->smax_value = dst_reg->umax_value;
13434 dst_reg->smin_value = S64_MIN;
13435 dst_reg->smax_value = S64_MAX;
13438 __update_reg_bounds(dst_reg);
13441 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13442 u64 umin_val, u64 umax_val)
13444 /* We lose all sign bit information (except what we can pick
13447 dst_reg->s32_min_value = S32_MIN;
13448 dst_reg->s32_max_value = S32_MAX;
13449 /* If we might shift our top bit out, then we know nothing */
13450 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13451 dst_reg->u32_min_value = 0;
13452 dst_reg->u32_max_value = U32_MAX;
13454 dst_reg->u32_min_value <<= umin_val;
13455 dst_reg->u32_max_value <<= umax_val;
13459 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13460 struct bpf_reg_state *src_reg)
13462 u32 umax_val = src_reg->u32_max_value;
13463 u32 umin_val = src_reg->u32_min_value;
13464 /* u32 alu operation will zext upper bits */
13465 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13467 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13468 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13469 /* Not required but being careful mark reg64 bounds as unknown so
13470 * that we are forced to pick them up from tnum and zext later and
13471 * if some path skips this step we are still safe.
13473 __mark_reg64_unbounded(dst_reg);
13474 __update_reg32_bounds(dst_reg);
13477 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13478 u64 umin_val, u64 umax_val)
13480 /* Special case <<32 because it is a common compiler pattern to sign
13481 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13482 * positive we know this shift will also be positive so we can track
13483 * bounds correctly. Otherwise we lose all sign bit information except
13484 * what we can pick up from var_off. Perhaps we can generalize this
13485 * later to shifts of any length.
13487 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13488 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13490 dst_reg->smax_value = S64_MAX;
13492 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13493 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13495 dst_reg->smin_value = S64_MIN;
13497 /* If we might shift our top bit out, then we know nothing */
13498 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13499 dst_reg->umin_value = 0;
13500 dst_reg->umax_value = U64_MAX;
13502 dst_reg->umin_value <<= umin_val;
13503 dst_reg->umax_value <<= umax_val;
13507 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13508 struct bpf_reg_state *src_reg)
13510 u64 umax_val = src_reg->umax_value;
13511 u64 umin_val = src_reg->umin_value;
13513 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
13514 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13515 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13517 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13518 /* We may learn something more from the var_off */
13519 __update_reg_bounds(dst_reg);
13522 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13523 struct bpf_reg_state *src_reg)
13525 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13526 u32 umax_val = src_reg->u32_max_value;
13527 u32 umin_val = src_reg->u32_min_value;
13529 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13530 * be negative, then either:
13531 * 1) src_reg might be zero, so the sign bit of the result is
13532 * unknown, so we lose our signed bounds
13533 * 2) it's known negative, thus the unsigned bounds capture the
13535 * 3) the signed bounds cross zero, so they tell us nothing
13537 * If the value in dst_reg is known nonnegative, then again the
13538 * unsigned bounds capture the signed bounds.
13539 * Thus, in all cases it suffices to blow away our signed bounds
13540 * and rely on inferring new ones from the unsigned bounds and
13541 * var_off of the result.
13543 dst_reg->s32_min_value = S32_MIN;
13544 dst_reg->s32_max_value = S32_MAX;
13546 dst_reg->var_off = tnum_rshift(subreg, umin_val);
13547 dst_reg->u32_min_value >>= umax_val;
13548 dst_reg->u32_max_value >>= umin_val;
13550 __mark_reg64_unbounded(dst_reg);
13551 __update_reg32_bounds(dst_reg);
13554 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13555 struct bpf_reg_state *src_reg)
13557 u64 umax_val = src_reg->umax_value;
13558 u64 umin_val = src_reg->umin_value;
13560 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13561 * be negative, then either:
13562 * 1) src_reg might be zero, so the sign bit of the result is
13563 * unknown, so we lose our signed bounds
13564 * 2) it's known negative, thus the unsigned bounds capture the
13566 * 3) the signed bounds cross zero, so they tell us nothing
13568 * If the value in dst_reg is known nonnegative, then again the
13569 * unsigned bounds capture the signed bounds.
13570 * Thus, in all cases it suffices to blow away our signed bounds
13571 * and rely on inferring new ones from the unsigned bounds and
13572 * var_off of the result.
13574 dst_reg->smin_value = S64_MIN;
13575 dst_reg->smax_value = S64_MAX;
13576 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13577 dst_reg->umin_value >>= umax_val;
13578 dst_reg->umax_value >>= umin_val;
13580 /* Its not easy to operate on alu32 bounds here because it depends
13581 * on bits being shifted in. Take easy way out and mark unbounded
13582 * so we can recalculate later from tnum.
13584 __mark_reg32_unbounded(dst_reg);
13585 __update_reg_bounds(dst_reg);
13588 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13589 struct bpf_reg_state *src_reg)
13591 u64 umin_val = src_reg->u32_min_value;
13593 /* Upon reaching here, src_known is true and
13594 * umax_val is equal to umin_val.
13596 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13597 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13599 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13601 /* blow away the dst_reg umin_value/umax_value and rely on
13602 * dst_reg var_off to refine the result.
13604 dst_reg->u32_min_value = 0;
13605 dst_reg->u32_max_value = U32_MAX;
13607 __mark_reg64_unbounded(dst_reg);
13608 __update_reg32_bounds(dst_reg);
13611 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13612 struct bpf_reg_state *src_reg)
13614 u64 umin_val = src_reg->umin_value;
13616 /* Upon reaching here, src_known is true and umax_val is equal
13619 dst_reg->smin_value >>= umin_val;
13620 dst_reg->smax_value >>= umin_val;
13622 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13624 /* blow away the dst_reg umin_value/umax_value and rely on
13625 * dst_reg var_off to refine the result.
13627 dst_reg->umin_value = 0;
13628 dst_reg->umax_value = U64_MAX;
13630 /* Its not easy to operate on alu32 bounds here because it depends
13631 * on bits being shifted in from upper 32-bits. Take easy way out
13632 * and mark unbounded so we can recalculate later from tnum.
13634 __mark_reg32_unbounded(dst_reg);
13635 __update_reg_bounds(dst_reg);
13638 /* WARNING: This function does calculations on 64-bit values, but the actual
13639 * execution may occur on 32-bit values. Therefore, things like bitshifts
13640 * need extra checks in the 32-bit case.
13642 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13643 struct bpf_insn *insn,
13644 struct bpf_reg_state *dst_reg,
13645 struct bpf_reg_state src_reg)
13647 struct bpf_reg_state *regs = cur_regs(env);
13648 u8 opcode = BPF_OP(insn->code);
13650 s64 smin_val, smax_val;
13651 u64 umin_val, umax_val;
13652 s32 s32_min_val, s32_max_val;
13653 u32 u32_min_val, u32_max_val;
13654 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13655 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13658 smin_val = src_reg.smin_value;
13659 smax_val = src_reg.smax_value;
13660 umin_val = src_reg.umin_value;
13661 umax_val = src_reg.umax_value;
13663 s32_min_val = src_reg.s32_min_value;
13664 s32_max_val = src_reg.s32_max_value;
13665 u32_min_val = src_reg.u32_min_value;
13666 u32_max_val = src_reg.u32_max_value;
13669 src_known = tnum_subreg_is_const(src_reg.var_off);
13671 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13672 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13673 /* Taint dst register if offset had invalid bounds
13674 * derived from e.g. dead branches.
13676 __mark_reg_unknown(env, dst_reg);
13680 src_known = tnum_is_const(src_reg.var_off);
13682 (smin_val != smax_val || umin_val != umax_val)) ||
13683 smin_val > smax_val || umin_val > umax_val) {
13684 /* Taint dst register if offset had invalid bounds
13685 * derived from e.g. dead branches.
13687 __mark_reg_unknown(env, dst_reg);
13693 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13694 __mark_reg_unknown(env, dst_reg);
13698 if (sanitize_needed(opcode)) {
13699 ret = sanitize_val_alu(env, insn);
13701 return sanitize_err(env, insn, ret, NULL, NULL);
13704 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13705 * There are two classes of instructions: The first class we track both
13706 * alu32 and alu64 sign/unsigned bounds independently this provides the
13707 * greatest amount of precision when alu operations are mixed with jmp32
13708 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13709 * and BPF_OR. This is possible because these ops have fairly easy to
13710 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13711 * See alu32 verifier tests for examples. The second class of
13712 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13713 * with regards to tracking sign/unsigned bounds because the bits may
13714 * cross subreg boundaries in the alu64 case. When this happens we mark
13715 * the reg unbounded in the subreg bound space and use the resulting
13716 * tnum to calculate an approximation of the sign/unsigned bounds.
13720 scalar32_min_max_add(dst_reg, &src_reg);
13721 scalar_min_max_add(dst_reg, &src_reg);
13722 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13725 scalar32_min_max_sub(dst_reg, &src_reg);
13726 scalar_min_max_sub(dst_reg, &src_reg);
13727 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13730 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13731 scalar32_min_max_mul(dst_reg, &src_reg);
13732 scalar_min_max_mul(dst_reg, &src_reg);
13735 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13736 scalar32_min_max_and(dst_reg, &src_reg);
13737 scalar_min_max_and(dst_reg, &src_reg);
13740 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13741 scalar32_min_max_or(dst_reg, &src_reg);
13742 scalar_min_max_or(dst_reg, &src_reg);
13745 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13746 scalar32_min_max_xor(dst_reg, &src_reg);
13747 scalar_min_max_xor(dst_reg, &src_reg);
13750 if (umax_val >= insn_bitness) {
13751 /* Shifts greater than 31 or 63 are undefined.
13752 * This includes shifts by a negative number.
13754 mark_reg_unknown(env, regs, insn->dst_reg);
13758 scalar32_min_max_lsh(dst_reg, &src_reg);
13760 scalar_min_max_lsh(dst_reg, &src_reg);
13763 if (umax_val >= insn_bitness) {
13764 /* Shifts greater than 31 or 63 are undefined.
13765 * This includes shifts by a negative number.
13767 mark_reg_unknown(env, regs, insn->dst_reg);
13771 scalar32_min_max_rsh(dst_reg, &src_reg);
13773 scalar_min_max_rsh(dst_reg, &src_reg);
13776 if (umax_val >= insn_bitness) {
13777 /* Shifts greater than 31 or 63 are undefined.
13778 * This includes shifts by a negative number.
13780 mark_reg_unknown(env, regs, insn->dst_reg);
13784 scalar32_min_max_arsh(dst_reg, &src_reg);
13786 scalar_min_max_arsh(dst_reg, &src_reg);
13789 mark_reg_unknown(env, regs, insn->dst_reg);
13793 /* ALU32 ops are zero extended into 64bit register */
13795 zext_32_to_64(dst_reg);
13796 reg_bounds_sync(dst_reg);
13800 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13803 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13804 struct bpf_insn *insn)
13806 struct bpf_verifier_state *vstate = env->cur_state;
13807 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13808 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13809 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13810 u8 opcode = BPF_OP(insn->code);
13813 dst_reg = ®s[insn->dst_reg];
13815 if (dst_reg->type != SCALAR_VALUE)
13818 /* Make sure ID is cleared otherwise dst_reg min/max could be
13819 * incorrectly propagated into other registers by find_equal_scalars()
13822 if (BPF_SRC(insn->code) == BPF_X) {
13823 src_reg = ®s[insn->src_reg];
13824 if (src_reg->type != SCALAR_VALUE) {
13825 if (dst_reg->type != SCALAR_VALUE) {
13826 /* Combining two pointers by any ALU op yields
13827 * an arbitrary scalar. Disallow all math except
13828 * pointer subtraction
13830 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13831 mark_reg_unknown(env, regs, insn->dst_reg);
13834 verbose(env, "R%d pointer %s pointer prohibited\n",
13836 bpf_alu_string[opcode >> 4]);
13839 /* scalar += pointer
13840 * This is legal, but we have to reverse our
13841 * src/dest handling in computing the range
13843 err = mark_chain_precision(env, insn->dst_reg);
13846 return adjust_ptr_min_max_vals(env, insn,
13849 } else if (ptr_reg) {
13850 /* pointer += scalar */
13851 err = mark_chain_precision(env, insn->src_reg);
13854 return adjust_ptr_min_max_vals(env, insn,
13856 } else if (dst_reg->precise) {
13857 /* if dst_reg is precise, src_reg should be precise as well */
13858 err = mark_chain_precision(env, insn->src_reg);
13863 /* Pretend the src is a reg with a known value, since we only
13864 * need to be able to read from this state.
13866 off_reg.type = SCALAR_VALUE;
13867 __mark_reg_known(&off_reg, insn->imm);
13868 src_reg = &off_reg;
13869 if (ptr_reg) /* pointer += K */
13870 return adjust_ptr_min_max_vals(env, insn,
13874 /* Got here implies adding two SCALAR_VALUEs */
13875 if (WARN_ON_ONCE(ptr_reg)) {
13876 print_verifier_state(env, state, true);
13877 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13880 if (WARN_ON(!src_reg)) {
13881 print_verifier_state(env, state, true);
13882 verbose(env, "verifier internal error: no src_reg\n");
13885 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13888 /* check validity of 32-bit and 64-bit arithmetic operations */
13889 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13891 struct bpf_reg_state *regs = cur_regs(env);
13892 u8 opcode = BPF_OP(insn->code);
13895 if (opcode == BPF_END || opcode == BPF_NEG) {
13896 if (opcode == BPF_NEG) {
13897 if (BPF_SRC(insn->code) != BPF_K ||
13898 insn->src_reg != BPF_REG_0 ||
13899 insn->off != 0 || insn->imm != 0) {
13900 verbose(env, "BPF_NEG uses reserved fields\n");
13904 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13905 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13906 (BPF_CLASS(insn->code) == BPF_ALU64 &&
13907 BPF_SRC(insn->code) != BPF_TO_LE)) {
13908 verbose(env, "BPF_END uses reserved fields\n");
13913 /* check src operand */
13914 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13918 if (is_pointer_value(env, insn->dst_reg)) {
13919 verbose(env, "R%d pointer arithmetic prohibited\n",
13924 /* check dest operand */
13925 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13929 } else if (opcode == BPF_MOV) {
13931 if (BPF_SRC(insn->code) == BPF_X) {
13932 if (insn->imm != 0) {
13933 verbose(env, "BPF_MOV uses reserved fields\n");
13937 if (BPF_CLASS(insn->code) == BPF_ALU) {
13938 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13939 verbose(env, "BPF_MOV uses reserved fields\n");
13943 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13945 verbose(env, "BPF_MOV uses reserved fields\n");
13950 /* check src operand */
13951 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13955 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13956 verbose(env, "BPF_MOV uses reserved fields\n");
13961 /* check dest operand, mark as required later */
13962 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13966 if (BPF_SRC(insn->code) == BPF_X) {
13967 struct bpf_reg_state *src_reg = regs + insn->src_reg;
13968 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13970 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13971 if (insn->off == 0) {
13973 * copy register state to dest reg
13975 assign_scalar_id_before_mov(env, src_reg);
13976 copy_register_state(dst_reg, src_reg);
13977 dst_reg->live |= REG_LIVE_WRITTEN;
13978 dst_reg->subreg_def = DEF_NOT_SUBREG;
13980 /* case: R1 = (s8, s16 s32)R2 */
13981 if (is_pointer_value(env, insn->src_reg)) {
13983 "R%d sign-extension part of pointer\n",
13986 } else if (src_reg->type == SCALAR_VALUE) {
13989 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13991 assign_scalar_id_before_mov(env, src_reg);
13992 copy_register_state(dst_reg, src_reg);
13995 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13996 dst_reg->live |= REG_LIVE_WRITTEN;
13997 dst_reg->subreg_def = DEF_NOT_SUBREG;
13999 mark_reg_unknown(env, regs, insn->dst_reg);
14003 /* R1 = (u32) R2 */
14004 if (is_pointer_value(env, insn->src_reg)) {
14006 "R%d partial copy of pointer\n",
14009 } else if (src_reg->type == SCALAR_VALUE) {
14010 if (insn->off == 0) {
14011 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
14013 if (is_src_reg_u32)
14014 assign_scalar_id_before_mov(env, src_reg);
14015 copy_register_state(dst_reg, src_reg);
14016 /* Make sure ID is cleared if src_reg is not in u32
14017 * range otherwise dst_reg min/max could be incorrectly
14018 * propagated into src_reg by find_equal_scalars()
14020 if (!is_src_reg_u32)
14022 dst_reg->live |= REG_LIVE_WRITTEN;
14023 dst_reg->subreg_def = env->insn_idx + 1;
14025 /* case: W1 = (s8, s16)W2 */
14026 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14029 assign_scalar_id_before_mov(env, src_reg);
14030 copy_register_state(dst_reg, src_reg);
14033 dst_reg->live |= REG_LIVE_WRITTEN;
14034 dst_reg->subreg_def = env->insn_idx + 1;
14035 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
14038 mark_reg_unknown(env, regs,
14041 zext_32_to_64(dst_reg);
14042 reg_bounds_sync(dst_reg);
14046 * remember the value we stored into this reg
14048 /* clear any state __mark_reg_known doesn't set */
14049 mark_reg_unknown(env, regs, insn->dst_reg);
14050 regs[insn->dst_reg].type = SCALAR_VALUE;
14051 if (BPF_CLASS(insn->code) == BPF_ALU64) {
14052 __mark_reg_known(regs + insn->dst_reg,
14055 __mark_reg_known(regs + insn->dst_reg,
14060 } else if (opcode > BPF_END) {
14061 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
14064 } else { /* all other ALU ops: and, sub, xor, add, ... */
14066 if (BPF_SRC(insn->code) == BPF_X) {
14067 if (insn->imm != 0 || insn->off > 1 ||
14068 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14069 verbose(env, "BPF_ALU uses reserved fields\n");
14072 /* check src1 operand */
14073 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14077 if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
14078 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14079 verbose(env, "BPF_ALU uses reserved fields\n");
14084 /* check src2 operand */
14085 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14089 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
14090 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
14091 verbose(env, "div by zero\n");
14095 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
14096 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
14097 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
14099 if (insn->imm < 0 || insn->imm >= size) {
14100 verbose(env, "invalid shift %d\n", insn->imm);
14105 /* check dest operand */
14106 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14107 err = err ?: adjust_reg_min_max_vals(env, insn);
14112 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu");
14115 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
14116 struct bpf_reg_state *dst_reg,
14117 enum bpf_reg_type type,
14118 bool range_right_open)
14120 struct bpf_func_state *state;
14121 struct bpf_reg_state *reg;
14124 if (dst_reg->off < 0 ||
14125 (dst_reg->off == 0 && range_right_open))
14126 /* This doesn't give us any range */
14129 if (dst_reg->umax_value > MAX_PACKET_OFF ||
14130 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
14131 /* Risk of overflow. For instance, ptr + (1<<63) may be less
14132 * than pkt_end, but that's because it's also less than pkt.
14136 new_range = dst_reg->off;
14137 if (range_right_open)
14140 /* Examples for register markings:
14142 * pkt_data in dst register:
14146 * if (r2 > pkt_end) goto <handle exception>
14151 * if (r2 < pkt_end) goto <access okay>
14152 * <handle exception>
14155 * r2 == dst_reg, pkt_end == src_reg
14156 * r2=pkt(id=n,off=8,r=0)
14157 * r3=pkt(id=n,off=0,r=0)
14159 * pkt_data in src register:
14163 * if (pkt_end >= r2) goto <access okay>
14164 * <handle exception>
14168 * if (pkt_end <= r2) goto <handle exception>
14172 * pkt_end == dst_reg, r2 == src_reg
14173 * r2=pkt(id=n,off=8,r=0)
14174 * r3=pkt(id=n,off=0,r=0)
14176 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14177 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14178 * and [r3, r3 + 8-1) respectively is safe to access depending on
14182 /* If our ids match, then we must have the same max_value. And we
14183 * don't care about the other reg's fixed offset, since if it's too big
14184 * the range won't allow anything.
14185 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14187 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14188 if (reg->type == type && reg->id == dst_reg->id)
14189 /* keep the maximum range already checked */
14190 reg->range = max(reg->range, new_range);
14195 * <reg1> <op> <reg2>, currently assuming reg2 is a constant
14197 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14198 u8 opcode, bool is_jmp32)
14200 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
14201 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
14202 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
14203 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
14204 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
14205 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
14206 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
14207 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
14208 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
14209 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
14213 /* constants, umin/umax and smin/smax checks would be
14214 * redundant in this case because they all should match
14216 if (tnum_is_const(t1) && tnum_is_const(t2))
14217 return t1.value == t2.value;
14218 /* non-overlapping ranges */
14219 if (umin1 > umax2 || umax1 < umin2)
14221 if (smin1 > smax2 || smax1 < smin2)
14224 /* if 64-bit ranges are inconclusive, see if we can
14225 * utilize 32-bit subrange knowledge to eliminate
14226 * branches that can't be taken a priori
14228 if (reg1->u32_min_value > reg2->u32_max_value ||
14229 reg1->u32_max_value < reg2->u32_min_value)
14231 if (reg1->s32_min_value > reg2->s32_max_value ||
14232 reg1->s32_max_value < reg2->s32_min_value)
14237 /* constants, umin/umax and smin/smax checks would be
14238 * redundant in this case because they all should match
14240 if (tnum_is_const(t1) && tnum_is_const(t2))
14241 return t1.value != t2.value;
14242 /* non-overlapping ranges */
14243 if (umin1 > umax2 || umax1 < umin2)
14245 if (smin1 > smax2 || smax1 < smin2)
14248 /* if 64-bit ranges are inconclusive, see if we can
14249 * utilize 32-bit subrange knowledge to eliminate
14250 * branches that can't be taken a priori
14252 if (reg1->u32_min_value > reg2->u32_max_value ||
14253 reg1->u32_max_value < reg2->u32_min_value)
14255 if (reg1->s32_min_value > reg2->s32_max_value ||
14256 reg1->s32_max_value < reg2->s32_min_value)
14261 if (!is_reg_const(reg2, is_jmp32)) {
14265 if (!is_reg_const(reg2, is_jmp32))
14267 if ((~t1.mask & t1.value) & t2.value)
14269 if (!((t1.mask | t1.value) & t2.value))
14275 else if (umax1 <= umin2)
14281 else if (smax1 <= smin2)
14287 else if (umin1 >= umax2)
14293 else if (smin1 >= smax2)
14297 if (umin1 >= umax2)
14299 else if (umax1 < umin2)
14303 if (smin1 >= smax2)
14305 else if (smax1 < smin2)
14309 if (umax1 <= umin2)
14311 else if (umin1 > umax2)
14315 if (smax1 <= smin2)
14317 else if (smin1 > smax2)
14325 static int flip_opcode(u32 opcode)
14327 /* How can we transform "a <op> b" into "b <op> a"? */
14328 static const u8 opcode_flip[16] = {
14329 /* these stay the same */
14330 [BPF_JEQ >> 4] = BPF_JEQ,
14331 [BPF_JNE >> 4] = BPF_JNE,
14332 [BPF_JSET >> 4] = BPF_JSET,
14333 /* these swap "lesser" and "greater" (L and G in the opcodes) */
14334 [BPF_JGE >> 4] = BPF_JLE,
14335 [BPF_JGT >> 4] = BPF_JLT,
14336 [BPF_JLE >> 4] = BPF_JGE,
14337 [BPF_JLT >> 4] = BPF_JGT,
14338 [BPF_JSGE >> 4] = BPF_JSLE,
14339 [BPF_JSGT >> 4] = BPF_JSLT,
14340 [BPF_JSLE >> 4] = BPF_JSGE,
14341 [BPF_JSLT >> 4] = BPF_JSGT
14343 return opcode_flip[opcode >> 4];
14346 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14347 struct bpf_reg_state *src_reg,
14350 struct bpf_reg_state *pkt;
14352 if (src_reg->type == PTR_TO_PACKET_END) {
14354 } else if (dst_reg->type == PTR_TO_PACKET_END) {
14356 opcode = flip_opcode(opcode);
14361 if (pkt->range >= 0)
14366 /* pkt <= pkt_end */
14369 /* pkt > pkt_end */
14370 if (pkt->range == BEYOND_PKT_END)
14371 /* pkt has at last one extra byte beyond pkt_end */
14372 return opcode == BPF_JGT;
14375 /* pkt < pkt_end */
14378 /* pkt >= pkt_end */
14379 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14380 return opcode == BPF_JGE;
14386 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
14388 * 1 - branch will be taken and "goto target" will be executed
14389 * 0 - branch will not be taken and fall-through to next insn
14390 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
14393 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14394 u8 opcode, bool is_jmp32)
14396 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
14397 return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
14399 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
14402 /* arrange that reg2 is a scalar, and reg1 is a pointer */
14403 if (!is_reg_const(reg2, is_jmp32)) {
14404 opcode = flip_opcode(opcode);
14407 /* and ensure that reg2 is a constant */
14408 if (!is_reg_const(reg2, is_jmp32))
14411 if (!reg_not_null(reg1))
14414 /* If pointer is valid tests against zero will fail so we can
14415 * use this to direct branch taken.
14417 val = reg_const_value(reg2, is_jmp32);
14431 /* now deal with two scalars, but not necessarily constants */
14432 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
14435 /* Opcode that corresponds to a *false* branch condition.
14436 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
14438 static u8 rev_opcode(u8 opcode)
14441 case BPF_JEQ: return BPF_JNE;
14442 case BPF_JNE: return BPF_JEQ;
14443 /* JSET doesn't have it's reverse opcode in BPF, so add
14444 * BPF_X flag to denote the reverse of that operation
14446 case BPF_JSET: return BPF_JSET | BPF_X;
14447 case BPF_JSET | BPF_X: return BPF_JSET;
14448 case BPF_JGE: return BPF_JLT;
14449 case BPF_JGT: return BPF_JLE;
14450 case BPF_JLE: return BPF_JGT;
14451 case BPF_JLT: return BPF_JGE;
14452 case BPF_JSGE: return BPF_JSLT;
14453 case BPF_JSGT: return BPF_JSLE;
14454 case BPF_JSLE: return BPF_JSGT;
14455 case BPF_JSLT: return BPF_JSGE;
14460 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
14461 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14462 u8 opcode, bool is_jmp32)
14471 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14472 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14473 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14474 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14475 reg2->u32_min_value = reg1->u32_min_value;
14476 reg2->u32_max_value = reg1->u32_max_value;
14477 reg2->s32_min_value = reg1->s32_min_value;
14478 reg2->s32_max_value = reg1->s32_max_value;
14480 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
14481 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14482 reg2->var_off = tnum_with_subreg(reg2->var_off, t);
14484 reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
14485 reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14486 reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
14487 reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14488 reg2->umin_value = reg1->umin_value;
14489 reg2->umax_value = reg1->umax_value;
14490 reg2->smin_value = reg1->smin_value;
14491 reg2->smax_value = reg1->smax_value;
14493 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
14494 reg2->var_off = reg1->var_off;
14498 if (!is_reg_const(reg2, is_jmp32))
14500 if (!is_reg_const(reg2, is_jmp32))
14503 /* try to recompute the bound of reg1 if reg2 is a const and
14504 * is exactly the edge of reg1.
14506 val = reg_const_value(reg2, is_jmp32);
14508 /* u32_min_value is not equal to 0xffffffff at this point,
14509 * because otherwise u32_max_value is 0xffffffff as well,
14510 * in such a case both reg1 and reg2 would be constants,
14511 * jump would be predicted and reg_set_min_max() won't
14514 * Same reasoning works for all {u,s}{min,max}{32,64} cases
14517 if (reg1->u32_min_value == (u32)val)
14518 reg1->u32_min_value++;
14519 if (reg1->u32_max_value == (u32)val)
14520 reg1->u32_max_value--;
14521 if (reg1->s32_min_value == (s32)val)
14522 reg1->s32_min_value++;
14523 if (reg1->s32_max_value == (s32)val)
14524 reg1->s32_max_value--;
14526 if (reg1->umin_value == (u64)val)
14527 reg1->umin_value++;
14528 if (reg1->umax_value == (u64)val)
14529 reg1->umax_value--;
14530 if (reg1->smin_value == (s64)val)
14531 reg1->smin_value++;
14532 if (reg1->smax_value == (s64)val)
14533 reg1->smax_value--;
14537 if (!is_reg_const(reg2, is_jmp32))
14539 if (!is_reg_const(reg2, is_jmp32))
14541 val = reg_const_value(reg2, is_jmp32);
14542 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
14543 * requires single bit to learn something useful. E.g., if we
14544 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
14545 * are actually set? We can learn something definite only if
14546 * it's a single-bit value to begin with.
14548 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
14549 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
14550 * bit 1 is set, which we can readily use in adjustments.
14552 if (!is_power_of_2(val))
14555 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
14556 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14558 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
14561 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
14562 if (!is_reg_const(reg2, is_jmp32))
14564 if (!is_reg_const(reg2, is_jmp32))
14566 val = reg_const_value(reg2, is_jmp32);
14568 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
14569 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14571 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
14576 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14577 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14579 reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14580 reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
14585 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
14586 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
14588 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
14589 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
14594 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14595 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14597 reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14598 reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
14603 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
14604 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
14606 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
14607 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
14614 /* just reuse LE/LT logic above */
14615 opcode = flip_opcode(opcode);
14623 /* Adjusts the register min/max values in the case that the dst_reg and
14624 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
14625 * check, in which case we havea fake SCALAR_VALUE representing insn->imm).
14626 * Technically we can do similar adjustments for pointers to the same object,
14627 * but we don't support that right now.
14629 static int reg_set_min_max(struct bpf_verifier_env *env,
14630 struct bpf_reg_state *true_reg1,
14631 struct bpf_reg_state *true_reg2,
14632 struct bpf_reg_state *false_reg1,
14633 struct bpf_reg_state *false_reg2,
14634 u8 opcode, bool is_jmp32)
14638 /* If either register is a pointer, we can't learn anything about its
14639 * variable offset from the compare (unless they were a pointer into
14640 * the same object, but we don't bother with that).
14642 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
14645 /* fallthrough (FALSE) branch */
14646 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
14647 reg_bounds_sync(false_reg1);
14648 reg_bounds_sync(false_reg2);
14650 /* jump (TRUE) branch */
14651 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
14652 reg_bounds_sync(true_reg1);
14653 reg_bounds_sync(true_reg2);
14655 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
14656 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
14657 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
14658 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
14662 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14663 struct bpf_reg_state *reg, u32 id,
14666 if (type_may_be_null(reg->type) && reg->id == id &&
14667 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14668 /* Old offset (both fixed and variable parts) should have been
14669 * known-zero, because we don't allow pointer arithmetic on
14670 * pointers that might be NULL. If we see this happening, don't
14671 * convert the register.
14673 * But in some cases, some helpers that return local kptrs
14674 * advance offset for the returned pointer. In those cases, it
14675 * is fine to expect to see reg->off.
14677 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14679 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14680 WARN_ON_ONCE(reg->off))
14684 reg->type = SCALAR_VALUE;
14685 /* We don't need id and ref_obj_id from this point
14686 * onwards anymore, thus we should better reset it,
14687 * so that state pruning has chances to take effect.
14690 reg->ref_obj_id = 0;
14695 mark_ptr_not_null_reg(reg);
14697 if (!reg_may_point_to_spin_lock(reg)) {
14698 /* For not-NULL ptr, reg->ref_obj_id will be reset
14699 * in release_reference().
14701 * reg->id is still used by spin_lock ptr. Other
14702 * than spin_lock ptr type, reg->id can be reset.
14709 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14710 * be folded together at some point.
14712 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14715 struct bpf_func_state *state = vstate->frame[vstate->curframe];
14716 struct bpf_reg_state *regs = state->regs, *reg;
14717 u32 ref_obj_id = regs[regno].ref_obj_id;
14718 u32 id = regs[regno].id;
14720 if (ref_obj_id && ref_obj_id == id && is_null)
14721 /* regs[regno] is in the " == NULL" branch.
14722 * No one could have freed the reference state before
14723 * doing the NULL check.
14725 WARN_ON_ONCE(release_reference_state(state, id));
14727 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14728 mark_ptr_or_null_reg(state, reg, id, is_null);
14732 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14733 struct bpf_reg_state *dst_reg,
14734 struct bpf_reg_state *src_reg,
14735 struct bpf_verifier_state *this_branch,
14736 struct bpf_verifier_state *other_branch)
14738 if (BPF_SRC(insn->code) != BPF_X)
14741 /* Pointers are always 64-bit. */
14742 if (BPF_CLASS(insn->code) == BPF_JMP32)
14745 switch (BPF_OP(insn->code)) {
14747 if ((dst_reg->type == PTR_TO_PACKET &&
14748 src_reg->type == PTR_TO_PACKET_END) ||
14749 (dst_reg->type == PTR_TO_PACKET_META &&
14750 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14751 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14752 find_good_pkt_pointers(this_branch, dst_reg,
14753 dst_reg->type, false);
14754 mark_pkt_end(other_branch, insn->dst_reg, true);
14755 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14756 src_reg->type == PTR_TO_PACKET) ||
14757 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14758 src_reg->type == PTR_TO_PACKET_META)) {
14759 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
14760 find_good_pkt_pointers(other_branch, src_reg,
14761 src_reg->type, true);
14762 mark_pkt_end(this_branch, insn->src_reg, false);
14768 if ((dst_reg->type == PTR_TO_PACKET &&
14769 src_reg->type == PTR_TO_PACKET_END) ||
14770 (dst_reg->type == PTR_TO_PACKET_META &&
14771 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14772 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14773 find_good_pkt_pointers(other_branch, dst_reg,
14774 dst_reg->type, true);
14775 mark_pkt_end(this_branch, insn->dst_reg, false);
14776 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14777 src_reg->type == PTR_TO_PACKET) ||
14778 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14779 src_reg->type == PTR_TO_PACKET_META)) {
14780 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
14781 find_good_pkt_pointers(this_branch, src_reg,
14782 src_reg->type, false);
14783 mark_pkt_end(other_branch, insn->src_reg, true);
14789 if ((dst_reg->type == PTR_TO_PACKET &&
14790 src_reg->type == PTR_TO_PACKET_END) ||
14791 (dst_reg->type == PTR_TO_PACKET_META &&
14792 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14793 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14794 find_good_pkt_pointers(this_branch, dst_reg,
14795 dst_reg->type, true);
14796 mark_pkt_end(other_branch, insn->dst_reg, false);
14797 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14798 src_reg->type == PTR_TO_PACKET) ||
14799 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14800 src_reg->type == PTR_TO_PACKET_META)) {
14801 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14802 find_good_pkt_pointers(other_branch, src_reg,
14803 src_reg->type, false);
14804 mark_pkt_end(this_branch, insn->src_reg, true);
14810 if ((dst_reg->type == PTR_TO_PACKET &&
14811 src_reg->type == PTR_TO_PACKET_END) ||
14812 (dst_reg->type == PTR_TO_PACKET_META &&
14813 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14814 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14815 find_good_pkt_pointers(other_branch, dst_reg,
14816 dst_reg->type, false);
14817 mark_pkt_end(this_branch, insn->dst_reg, true);
14818 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14819 src_reg->type == PTR_TO_PACKET) ||
14820 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14821 src_reg->type == PTR_TO_PACKET_META)) {
14822 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14823 find_good_pkt_pointers(this_branch, src_reg,
14824 src_reg->type, true);
14825 mark_pkt_end(other_branch, insn->src_reg, false);
14837 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14838 struct bpf_reg_state *known_reg)
14840 struct bpf_func_state *state;
14841 struct bpf_reg_state *reg;
14843 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14844 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14845 copy_register_state(reg, known_reg);
14849 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14850 struct bpf_insn *insn, int *insn_idx)
14852 struct bpf_verifier_state *this_branch = env->cur_state;
14853 struct bpf_verifier_state *other_branch;
14854 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14855 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14856 struct bpf_reg_state *eq_branch_regs;
14857 struct bpf_reg_state fake_reg = {};
14858 u8 opcode = BPF_OP(insn->code);
14863 /* Only conditional jumps are expected to reach here. */
14864 if (opcode == BPF_JA || opcode > BPF_JSLE) {
14865 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14869 /* check src2 operand */
14870 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14874 dst_reg = ®s[insn->dst_reg];
14875 if (BPF_SRC(insn->code) == BPF_X) {
14876 if (insn->imm != 0) {
14877 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14881 /* check src1 operand */
14882 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14886 src_reg = ®s[insn->src_reg];
14887 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14888 is_pointer_value(env, insn->src_reg)) {
14889 verbose(env, "R%d pointer comparison prohibited\n",
14894 if (insn->src_reg != BPF_REG_0) {
14895 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14898 src_reg = &fake_reg;
14899 src_reg->type = SCALAR_VALUE;
14900 __mark_reg_known(src_reg, insn->imm);
14903 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14904 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
14906 /* If we get here with a dst_reg pointer type it is because
14907 * above is_branch_taken() special cased the 0 comparison.
14909 if (!__is_pointer_value(false, dst_reg))
14910 err = mark_chain_precision(env, insn->dst_reg);
14911 if (BPF_SRC(insn->code) == BPF_X && !err &&
14912 !__is_pointer_value(false, src_reg))
14913 err = mark_chain_precision(env, insn->src_reg);
14919 /* Only follow the goto, ignore fall-through. If needed, push
14920 * the fall-through branch for simulation under speculative
14923 if (!env->bypass_spec_v1 &&
14924 !sanitize_speculative_path(env, insn, *insn_idx + 1,
14927 if (env->log.level & BPF_LOG_LEVEL)
14928 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14929 *insn_idx += insn->off;
14931 } else if (pred == 0) {
14932 /* Only follow the fall-through branch, since that's where the
14933 * program will go. If needed, push the goto branch for
14934 * simulation under speculative execution.
14936 if (!env->bypass_spec_v1 &&
14937 !sanitize_speculative_path(env, insn,
14938 *insn_idx + insn->off + 1,
14941 if (env->log.level & BPF_LOG_LEVEL)
14942 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14946 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14950 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14952 if (BPF_SRC(insn->code) == BPF_X) {
14953 err = reg_set_min_max(env,
14954 &other_branch_regs[insn->dst_reg],
14955 &other_branch_regs[insn->src_reg],
14956 dst_reg, src_reg, opcode, is_jmp32);
14957 } else /* BPF_SRC(insn->code) == BPF_K */ {
14958 err = reg_set_min_max(env,
14959 &other_branch_regs[insn->dst_reg],
14960 src_reg /* fake one */,
14961 dst_reg, src_reg /* same fake one */,
14967 if (BPF_SRC(insn->code) == BPF_X &&
14968 src_reg->type == SCALAR_VALUE && src_reg->id &&
14969 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14970 find_equal_scalars(this_branch, src_reg);
14971 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14973 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14974 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14975 find_equal_scalars(this_branch, dst_reg);
14976 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14979 /* if one pointer register is compared to another pointer
14980 * register check if PTR_MAYBE_NULL could be lifted.
14981 * E.g. register A - maybe null
14982 * register B - not null
14983 * for JNE A, B, ... - A is not null in the false branch;
14984 * for JEQ A, B, ... - A is not null in the true branch.
14986 * Since PTR_TO_BTF_ID points to a kernel struct that does
14987 * not need to be null checked by the BPF program, i.e.,
14988 * could be null even without PTR_MAYBE_NULL marking, so
14989 * only propagate nullness when neither reg is that type.
14991 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14992 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14993 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14994 base_type(src_reg->type) != PTR_TO_BTF_ID &&
14995 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14996 eq_branch_regs = NULL;
14999 eq_branch_regs = other_branch_regs;
15002 eq_branch_regs = regs;
15008 if (eq_branch_regs) {
15009 if (type_may_be_null(src_reg->type))
15010 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
15012 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
15016 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
15017 * NOTE: these optimizations below are related with pointer comparison
15018 * which will never be JMP32.
15020 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
15021 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
15022 type_may_be_null(dst_reg->type)) {
15023 /* Mark all identical registers in each branch as either
15024 * safe or unknown depending R == 0 or R != 0 conditional.
15026 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
15027 opcode == BPF_JNE);
15028 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
15029 opcode == BPF_JEQ);
15030 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
15031 this_branch, other_branch) &&
15032 is_pointer_value(env, insn->dst_reg)) {
15033 verbose(env, "R%d pointer comparison prohibited\n",
15037 if (env->log.level & BPF_LOG_LEVEL)
15038 print_insn_state(env, this_branch->frame[this_branch->curframe]);
15042 /* verify BPF_LD_IMM64 instruction */
15043 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
15045 struct bpf_insn_aux_data *aux = cur_aux(env);
15046 struct bpf_reg_state *regs = cur_regs(env);
15047 struct bpf_reg_state *dst_reg;
15048 struct bpf_map *map;
15051 if (BPF_SIZE(insn->code) != BPF_DW) {
15052 verbose(env, "invalid BPF_LD_IMM insn\n");
15055 if (insn->off != 0) {
15056 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
15060 err = check_reg_arg(env, insn->dst_reg, DST_OP);
15064 dst_reg = ®s[insn->dst_reg];
15065 if (insn->src_reg == 0) {
15066 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
15068 dst_reg->type = SCALAR_VALUE;
15069 __mark_reg_known(®s[insn->dst_reg], imm);
15073 /* All special src_reg cases are listed below. From this point onwards
15074 * we either succeed and assign a corresponding dst_reg->type after
15075 * zeroing the offset, or fail and reject the program.
15077 mark_reg_known_zero(env, regs, insn->dst_reg);
15079 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
15080 dst_reg->type = aux->btf_var.reg_type;
15081 switch (base_type(dst_reg->type)) {
15083 dst_reg->mem_size = aux->btf_var.mem_size;
15085 case PTR_TO_BTF_ID:
15086 dst_reg->btf = aux->btf_var.btf;
15087 dst_reg->btf_id = aux->btf_var.btf_id;
15090 verbose(env, "bpf verifier is misconfigured\n");
15096 if (insn->src_reg == BPF_PSEUDO_FUNC) {
15097 struct bpf_prog_aux *aux = env->prog->aux;
15098 u32 subprogno = find_subprog(env,
15099 env->insn_idx + insn->imm + 1);
15101 if (!aux->func_info) {
15102 verbose(env, "missing btf func_info\n");
15105 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
15106 verbose(env, "callback function not static\n");
15110 dst_reg->type = PTR_TO_FUNC;
15111 dst_reg->subprogno = subprogno;
15115 map = env->used_maps[aux->map_index];
15116 dst_reg->map_ptr = map;
15118 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15119 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15120 dst_reg->type = PTR_TO_MAP_VALUE;
15121 dst_reg->off = aux->map_off;
15122 WARN_ON_ONCE(map->max_entries != 1);
15123 /* We want reg->id to be same (0) as map_value is not distinct */
15124 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15125 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15126 dst_reg->type = CONST_PTR_TO_MAP;
15128 verbose(env, "bpf verifier is misconfigured\n");
15135 static bool may_access_skb(enum bpf_prog_type type)
15138 case BPF_PROG_TYPE_SOCKET_FILTER:
15139 case BPF_PROG_TYPE_SCHED_CLS:
15140 case BPF_PROG_TYPE_SCHED_ACT:
15147 /* verify safety of LD_ABS|LD_IND instructions:
15148 * - they can only appear in the programs where ctx == skb
15149 * - since they are wrappers of function calls, they scratch R1-R5 registers,
15150 * preserve R6-R9, and store return value into R0
15153 * ctx == skb == R6 == CTX
15156 * SRC == any register
15157 * IMM == 32-bit immediate
15160 * R0 - 8/16/32-bit skb data converted to cpu endianness
15162 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15164 struct bpf_reg_state *regs = cur_regs(env);
15165 static const int ctx_reg = BPF_REG_6;
15166 u8 mode = BPF_MODE(insn->code);
15169 if (!may_access_skb(resolve_prog_type(env->prog))) {
15170 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15174 if (!env->ops->gen_ld_abs) {
15175 verbose(env, "bpf verifier is misconfigured\n");
15179 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15180 BPF_SIZE(insn->code) == BPF_DW ||
15181 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15182 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
15186 /* check whether implicit source operand (register R6) is readable */
15187 err = check_reg_arg(env, ctx_reg, SRC_OP);
15191 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15192 * gen_ld_abs() may terminate the program at runtime, leading to
15195 err = check_reference_leak(env, false);
15197 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15201 if (env->cur_state->active_lock.ptr) {
15202 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15206 if (env->cur_state->active_rcu_lock) {
15207 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15211 if (regs[ctx_reg].type != PTR_TO_CTX) {
15213 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
15217 if (mode == BPF_IND) {
15218 /* check explicit source operand */
15219 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15224 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
15228 /* reset caller saved regs to unreadable */
15229 for (i = 0; i < CALLER_SAVED_REGS; i++) {
15230 mark_reg_not_init(env, regs, caller_saved[i]);
15231 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15234 /* mark destination R0 register as readable, since it contains
15235 * the value fetched from the packet.
15236 * Already marked as written above.
15238 mark_reg_unknown(env, regs, BPF_REG_0);
15239 /* ld_abs load up to 32-bit skb data. */
15240 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
15244 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
15246 const char *exit_ctx = "At program exit";
15247 struct tnum enforce_attach_type_range = tnum_unknown;
15248 const struct bpf_prog *prog = env->prog;
15249 struct bpf_reg_state *reg;
15250 struct bpf_retval_range range = retval_range(0, 1);
15251 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15253 struct bpf_func_state *frame = env->cur_state->frame[0];
15254 const bool is_subprog = frame->subprogno;
15256 /* LSM and struct_ops func-ptr's return type could be "void" */
15257 if (!is_subprog || frame->in_exception_callback_fn) {
15258 switch (prog_type) {
15259 case BPF_PROG_TYPE_LSM:
15260 if (prog->expected_attach_type == BPF_LSM_CGROUP)
15261 /* See below, can be 0 or 0-1 depending on hook. */
15264 case BPF_PROG_TYPE_STRUCT_OPS:
15265 if (!prog->aux->attach_func_proto->type)
15273 /* eBPF calling convention is such that R0 is used
15274 * to return the value from eBPF program.
15275 * Make sure that it's readable at this time
15276 * of bpf_exit, which means that program wrote
15277 * something into it earlier
15279 err = check_reg_arg(env, regno, SRC_OP);
15283 if (is_pointer_value(env, regno)) {
15284 verbose(env, "R%d leaks addr as return value\n", regno);
15288 reg = cur_regs(env) + regno;
15290 if (frame->in_async_callback_fn) {
15291 /* enforce return zero from async callbacks like timer */
15292 exit_ctx = "At async callback return";
15293 range = retval_range(0, 0);
15294 goto enforce_retval;
15297 if (is_subprog && !frame->in_exception_callback_fn) {
15298 if (reg->type != SCALAR_VALUE) {
15299 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15300 regno, reg_type_str(env, reg->type));
15306 switch (prog_type) {
15307 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15308 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15309 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15310 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15311 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15312 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15313 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15314 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15315 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15316 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15317 range = retval_range(1, 1);
15318 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15319 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15320 range = retval_range(0, 3);
15322 case BPF_PROG_TYPE_CGROUP_SKB:
15323 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15324 range = retval_range(0, 3);
15325 enforce_attach_type_range = tnum_range(2, 3);
15328 case BPF_PROG_TYPE_CGROUP_SOCK:
15329 case BPF_PROG_TYPE_SOCK_OPS:
15330 case BPF_PROG_TYPE_CGROUP_DEVICE:
15331 case BPF_PROG_TYPE_CGROUP_SYSCTL:
15332 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15334 case BPF_PROG_TYPE_RAW_TRACEPOINT:
15335 if (!env->prog->aux->attach_btf_id)
15337 range = retval_range(0, 0);
15339 case BPF_PROG_TYPE_TRACING:
15340 switch (env->prog->expected_attach_type) {
15341 case BPF_TRACE_FENTRY:
15342 case BPF_TRACE_FEXIT:
15343 range = retval_range(0, 0);
15345 case BPF_TRACE_RAW_TP:
15346 case BPF_MODIFY_RETURN:
15348 case BPF_TRACE_ITER:
15354 case BPF_PROG_TYPE_SK_LOOKUP:
15355 range = retval_range(SK_DROP, SK_PASS);
15358 case BPF_PROG_TYPE_LSM:
15359 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15360 /* Regular BPF_PROG_TYPE_LSM programs can return
15365 if (!env->prog->aux->attach_func_proto->type) {
15366 /* Make sure programs that attach to void
15367 * hooks don't try to modify return value.
15369 range = retval_range(1, 1);
15373 case BPF_PROG_TYPE_NETFILTER:
15374 range = retval_range(NF_DROP, NF_ACCEPT);
15376 case BPF_PROG_TYPE_EXT:
15377 /* freplace program can return anything as its return value
15378 * depends on the to-be-replaced kernel func or bpf program.
15385 if (reg->type != SCALAR_VALUE) {
15386 verbose(env, "%s the register R%d is not a known value (%s)\n",
15387 exit_ctx, regno, reg_type_str(env, reg->type));
15391 err = mark_chain_precision(env, regno);
15395 if (!retval_range_within(range, reg)) {
15396 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
15398 prog->expected_attach_type == BPF_LSM_CGROUP &&
15399 prog_type == BPF_PROG_TYPE_LSM &&
15400 !prog->aux->attach_func_proto->type)
15401 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15405 if (!tnum_is_unknown(enforce_attach_type_range) &&
15406 tnum_in(enforce_attach_type_range, reg->var_off))
15407 env->prog->enforce_expected_attach_type = 1;
15411 /* non-recursive DFS pseudo code
15412 * 1 procedure DFS-iterative(G,v):
15413 * 2 label v as discovered
15414 * 3 let S be a stack
15416 * 5 while S is not empty
15418 * 7 if t is what we're looking for:
15420 * 9 for all edges e in G.adjacentEdges(t) do
15421 * 10 if edge e is already labelled
15422 * 11 continue with the next edge
15423 * 12 w <- G.adjacentVertex(t,e)
15424 * 13 if vertex w is not discovered and not explored
15425 * 14 label e as tree-edge
15426 * 15 label w as discovered
15429 * 18 else if vertex w is discovered
15430 * 19 label e as back-edge
15432 * 21 // vertex w is explored
15433 * 22 label e as forward- or cross-edge
15434 * 23 label t as explored
15438 * 0x10 - discovered
15439 * 0x11 - discovered and fall-through edge labelled
15440 * 0x12 - discovered and fall-through and branch edges labelled
15451 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15453 env->insn_aux_data[idx].prune_point = true;
15456 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15458 return env->insn_aux_data[insn_idx].prune_point;
15461 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15463 env->insn_aux_data[idx].force_checkpoint = true;
15466 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15468 return env->insn_aux_data[insn_idx].force_checkpoint;
15471 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15473 env->insn_aux_data[idx].calls_callback = true;
15476 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15478 return env->insn_aux_data[insn_idx].calls_callback;
15482 DONE_EXPLORING = 0,
15483 KEEP_EXPLORING = 1,
15486 /* t, w, e - match pseudo-code above:
15487 * t - index of current instruction
15488 * w - next instruction
15491 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15493 int *insn_stack = env->cfg.insn_stack;
15494 int *insn_state = env->cfg.insn_state;
15496 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15497 return DONE_EXPLORING;
15499 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15500 return DONE_EXPLORING;
15502 if (w < 0 || w >= env->prog->len) {
15503 verbose_linfo(env, t, "%d: ", t);
15504 verbose(env, "jump out of range from insn %d to %d\n", t, w);
15509 /* mark branch target for state pruning */
15510 mark_prune_point(env, w);
15511 mark_jmp_point(env, w);
15514 if (insn_state[w] == 0) {
15516 insn_state[t] = DISCOVERED | e;
15517 insn_state[w] = DISCOVERED;
15518 if (env->cfg.cur_stack >= env->prog->len)
15520 insn_stack[env->cfg.cur_stack++] = w;
15521 return KEEP_EXPLORING;
15522 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15523 if (env->bpf_capable)
15524 return DONE_EXPLORING;
15525 verbose_linfo(env, t, "%d: ", t);
15526 verbose_linfo(env, w, "%d: ", w);
15527 verbose(env, "back-edge from insn %d to %d\n", t, w);
15529 } else if (insn_state[w] == EXPLORED) {
15530 /* forward- or cross-edge */
15531 insn_state[t] = DISCOVERED | e;
15533 verbose(env, "insn state internal bug\n");
15536 return DONE_EXPLORING;
15539 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15540 struct bpf_verifier_env *env,
15545 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15546 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15550 mark_prune_point(env, t + insn_sz);
15551 /* when we exit from subprog, we need to record non-linear history */
15552 mark_jmp_point(env, t + insn_sz);
15554 if (visit_callee) {
15555 mark_prune_point(env, t);
15556 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15561 /* Visits the instruction at index t and returns one of the following:
15562 * < 0 - an error occurred
15563 * DONE_EXPLORING - the instruction was fully explored
15564 * KEEP_EXPLORING - there is still work to be done before it is fully explored
15566 static int visit_insn(int t, struct bpf_verifier_env *env)
15568 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15569 int ret, off, insn_sz;
15571 if (bpf_pseudo_func(insn))
15572 return visit_func_call_insn(t, insns, env, true);
15574 /* All non-branch instructions have a single fall-through edge. */
15575 if (BPF_CLASS(insn->code) != BPF_JMP &&
15576 BPF_CLASS(insn->code) != BPF_JMP32) {
15577 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15578 return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15581 switch (BPF_OP(insn->code)) {
15583 return DONE_EXPLORING;
15586 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15587 /* Mark this call insn as a prune point to trigger
15588 * is_state_visited() check before call itself is
15589 * processed by __check_func_call(). Otherwise new
15590 * async state will be pushed for further exploration.
15592 mark_prune_point(env, t);
15593 /* For functions that invoke callbacks it is not known how many times
15594 * callback would be called. Verifier models callback calling functions
15595 * by repeatedly visiting callback bodies and returning to origin call
15597 * In order to stop such iteration verifier needs to identify when a
15598 * state identical some state from a previous iteration is reached.
15599 * Check below forces creation of checkpoint before callback calling
15600 * instruction to allow search for such identical states.
15602 if (is_sync_callback_calling_insn(insn)) {
15603 mark_calls_callback(env, t);
15604 mark_force_checkpoint(env, t);
15605 mark_prune_point(env, t);
15606 mark_jmp_point(env, t);
15608 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15609 struct bpf_kfunc_call_arg_meta meta;
15611 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15612 if (ret == 0 && is_iter_next_kfunc(&meta)) {
15613 mark_prune_point(env, t);
15614 /* Checking and saving state checkpoints at iter_next() call
15615 * is crucial for fast convergence of open-coded iterator loop
15616 * logic, so we need to force it. If we don't do that,
15617 * is_state_visited() might skip saving a checkpoint, causing
15618 * unnecessarily long sequence of not checkpointed
15619 * instructions and jumps, leading to exhaustion of jump
15620 * history buffer, and potentially other undesired outcomes.
15621 * It is expected that with correct open-coded iterators
15622 * convergence will happen quickly, so we don't run a risk of
15623 * exhausting memory.
15625 mark_force_checkpoint(env, t);
15628 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15631 if (BPF_SRC(insn->code) != BPF_K)
15634 if (BPF_CLASS(insn->code) == BPF_JMP)
15639 /* unconditional jump with single edge */
15640 ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15644 mark_prune_point(env, t + off + 1);
15645 mark_jmp_point(env, t + off + 1);
15650 /* conditional jump with two edges */
15651 mark_prune_point(env, t);
15653 ret = push_insn(t, t + 1, FALLTHROUGH, env);
15657 return push_insn(t, t + insn->off + 1, BRANCH, env);
15661 /* non-recursive depth-first-search to detect loops in BPF program
15662 * loop == back-edge in directed graph
15664 static int check_cfg(struct bpf_verifier_env *env)
15666 int insn_cnt = env->prog->len;
15667 int *insn_stack, *insn_state;
15668 int ex_insn_beg, i, ret = 0;
15669 bool ex_done = false;
15671 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15675 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15677 kvfree(insn_state);
15681 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15682 insn_stack[0] = 0; /* 0 is the first instruction */
15683 env->cfg.cur_stack = 1;
15686 while (env->cfg.cur_stack > 0) {
15687 int t = insn_stack[env->cfg.cur_stack - 1];
15689 ret = visit_insn(t, env);
15691 case DONE_EXPLORING:
15692 insn_state[t] = EXPLORED;
15693 env->cfg.cur_stack--;
15695 case KEEP_EXPLORING:
15699 verbose(env, "visit_insn internal bug\n");
15706 if (env->cfg.cur_stack < 0) {
15707 verbose(env, "pop stack internal bug\n");
15712 if (env->exception_callback_subprog && !ex_done) {
15713 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
15715 insn_state[ex_insn_beg] = DISCOVERED;
15716 insn_stack[0] = ex_insn_beg;
15717 env->cfg.cur_stack = 1;
15722 for (i = 0; i < insn_cnt; i++) {
15723 struct bpf_insn *insn = &env->prog->insnsi[i];
15725 if (insn_state[i] != EXPLORED) {
15726 verbose(env, "unreachable insn %d\n", i);
15730 if (bpf_is_ldimm64(insn)) {
15731 if (insn_state[i + 1] != 0) {
15732 verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15736 i++; /* skip second half of ldimm64 */
15739 ret = 0; /* cfg looks good */
15742 kvfree(insn_state);
15743 kvfree(insn_stack);
15744 env->cfg.insn_state = env->cfg.insn_stack = NULL;
15748 static int check_abnormal_return(struct bpf_verifier_env *env)
15752 for (i = 1; i < env->subprog_cnt; i++) {
15753 if (env->subprog_info[i].has_ld_abs) {
15754 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15757 if (env->subprog_info[i].has_tail_call) {
15758 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15765 /* The minimum supported BTF func info size */
15766 #define MIN_BPF_FUNCINFO_SIZE 8
15767 #define MAX_FUNCINFO_REC_SIZE 252
15769 static int check_btf_func_early(struct bpf_verifier_env *env,
15770 const union bpf_attr *attr,
15773 u32 krec_size = sizeof(struct bpf_func_info);
15774 const struct btf_type *type, *func_proto;
15775 u32 i, nfuncs, urec_size, min_size;
15776 struct bpf_func_info *krecord;
15777 struct bpf_prog *prog;
15778 const struct btf *btf;
15779 u32 prev_offset = 0;
15783 nfuncs = attr->func_info_cnt;
15785 if (check_abnormal_return(env))
15790 urec_size = attr->func_info_rec_size;
15791 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15792 urec_size > MAX_FUNCINFO_REC_SIZE ||
15793 urec_size % sizeof(u32)) {
15794 verbose(env, "invalid func info rec size %u\n", urec_size);
15799 btf = prog->aux->btf;
15801 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15802 min_size = min_t(u32, krec_size, urec_size);
15804 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15808 for (i = 0; i < nfuncs; i++) {
15809 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15811 if (ret == -E2BIG) {
15812 verbose(env, "nonzero tailing record in func info");
15813 /* set the size kernel expects so loader can zero
15814 * out the rest of the record.
15816 if (copy_to_bpfptr_offset(uattr,
15817 offsetof(union bpf_attr, func_info_rec_size),
15818 &min_size, sizeof(min_size)))
15824 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15829 /* check insn_off */
15832 if (krecord[i].insn_off) {
15834 "nonzero insn_off %u for the first func info record",
15835 krecord[i].insn_off);
15838 } else if (krecord[i].insn_off <= prev_offset) {
15840 "same or smaller insn offset (%u) than previous func info record (%u)",
15841 krecord[i].insn_off, prev_offset);
15845 /* check type_id */
15846 type = btf_type_by_id(btf, krecord[i].type_id);
15847 if (!type || !btf_type_is_func(type)) {
15848 verbose(env, "invalid type id %d in func info",
15849 krecord[i].type_id);
15853 func_proto = btf_type_by_id(btf, type->type);
15854 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15855 /* btf_func_check() already verified it during BTF load */
15858 prev_offset = krecord[i].insn_off;
15859 bpfptr_add(&urecord, urec_size);
15862 prog->aux->func_info = krecord;
15863 prog->aux->func_info_cnt = nfuncs;
15871 static int check_btf_func(struct bpf_verifier_env *env,
15872 const union bpf_attr *attr,
15875 const struct btf_type *type, *func_proto, *ret_type;
15876 u32 i, nfuncs, urec_size;
15877 struct bpf_func_info *krecord;
15878 struct bpf_func_info_aux *info_aux = NULL;
15879 struct bpf_prog *prog;
15880 const struct btf *btf;
15882 bool scalar_return;
15885 nfuncs = attr->func_info_cnt;
15887 if (check_abnormal_return(env))
15891 if (nfuncs != env->subprog_cnt) {
15892 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15896 urec_size = attr->func_info_rec_size;
15899 btf = prog->aux->btf;
15901 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15903 krecord = prog->aux->func_info;
15904 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15908 for (i = 0; i < nfuncs; i++) {
15909 /* check insn_off */
15912 if (env->subprog_info[i].start != krecord[i].insn_off) {
15913 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15917 /* Already checked type_id */
15918 type = btf_type_by_id(btf, krecord[i].type_id);
15919 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15920 /* Already checked func_proto */
15921 func_proto = btf_type_by_id(btf, type->type);
15923 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15925 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15926 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15927 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15930 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15931 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15935 bpfptr_add(&urecord, urec_size);
15938 prog->aux->func_info_aux = info_aux;
15946 static void adjust_btf_func(struct bpf_verifier_env *env)
15948 struct bpf_prog_aux *aux = env->prog->aux;
15951 if (!aux->func_info)
15954 /* func_info is not available for hidden subprogs */
15955 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
15956 aux->func_info[i].insn_off = env->subprog_info[i].start;
15959 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
15960 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
15962 static int check_btf_line(struct bpf_verifier_env *env,
15963 const union bpf_attr *attr,
15966 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15967 struct bpf_subprog_info *sub;
15968 struct bpf_line_info *linfo;
15969 struct bpf_prog *prog;
15970 const struct btf *btf;
15974 nr_linfo = attr->line_info_cnt;
15977 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15980 rec_size = attr->line_info_rec_size;
15981 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15982 rec_size > MAX_LINEINFO_REC_SIZE ||
15983 rec_size & (sizeof(u32) - 1))
15986 /* Need to zero it in case the userspace may
15987 * pass in a smaller bpf_line_info object.
15989 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15990 GFP_KERNEL | __GFP_NOWARN);
15995 btf = prog->aux->btf;
15998 sub = env->subprog_info;
15999 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
16000 expected_size = sizeof(struct bpf_line_info);
16001 ncopy = min_t(u32, expected_size, rec_size);
16002 for (i = 0; i < nr_linfo; i++) {
16003 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
16005 if (err == -E2BIG) {
16006 verbose(env, "nonzero tailing record in line_info");
16007 if (copy_to_bpfptr_offset(uattr,
16008 offsetof(union bpf_attr, line_info_rec_size),
16009 &expected_size, sizeof(expected_size)))
16015 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
16021 * Check insn_off to ensure
16022 * 1) strictly increasing AND
16023 * 2) bounded by prog->len
16025 * The linfo[0].insn_off == 0 check logically falls into
16026 * the later "missing bpf_line_info for func..." case
16027 * because the first linfo[0].insn_off must be the
16028 * first sub also and the first sub must have
16029 * subprog_info[0].start == 0.
16031 if ((i && linfo[i].insn_off <= prev_offset) ||
16032 linfo[i].insn_off >= prog->len) {
16033 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
16034 i, linfo[i].insn_off, prev_offset,
16040 if (!prog->insnsi[linfo[i].insn_off].code) {
16042 "Invalid insn code at line_info[%u].insn_off\n",
16048 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
16049 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
16050 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
16055 if (s != env->subprog_cnt) {
16056 if (linfo[i].insn_off == sub[s].start) {
16057 sub[s].linfo_idx = i;
16059 } else if (sub[s].start < linfo[i].insn_off) {
16060 verbose(env, "missing bpf_line_info for func#%u\n", s);
16066 prev_offset = linfo[i].insn_off;
16067 bpfptr_add(&ulinfo, rec_size);
16070 if (s != env->subprog_cnt) {
16071 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
16072 env->subprog_cnt - s, s);
16077 prog->aux->linfo = linfo;
16078 prog->aux->nr_linfo = nr_linfo;
16087 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
16088 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
16090 static int check_core_relo(struct bpf_verifier_env *env,
16091 const union bpf_attr *attr,
16094 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
16095 struct bpf_core_relo core_relo = {};
16096 struct bpf_prog *prog = env->prog;
16097 const struct btf *btf = prog->aux->btf;
16098 struct bpf_core_ctx ctx = {
16102 bpfptr_t u_core_relo;
16105 nr_core_relo = attr->core_relo_cnt;
16108 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
16111 rec_size = attr->core_relo_rec_size;
16112 if (rec_size < MIN_CORE_RELO_SIZE ||
16113 rec_size > MAX_CORE_RELO_SIZE ||
16114 rec_size % sizeof(u32))
16117 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
16118 expected_size = sizeof(struct bpf_core_relo);
16119 ncopy = min_t(u32, expected_size, rec_size);
16121 /* Unlike func_info and line_info, copy and apply each CO-RE
16122 * relocation record one at a time.
16124 for (i = 0; i < nr_core_relo; i++) {
16125 /* future proofing when sizeof(bpf_core_relo) changes */
16126 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
16128 if (err == -E2BIG) {
16129 verbose(env, "nonzero tailing record in core_relo");
16130 if (copy_to_bpfptr_offset(uattr,
16131 offsetof(union bpf_attr, core_relo_rec_size),
16132 &expected_size, sizeof(expected_size)))
16138 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16143 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16144 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16145 i, core_relo.insn_off, prog->len);
16150 err = bpf_core_apply(&ctx, &core_relo, i,
16151 &prog->insnsi[core_relo.insn_off / 8]);
16154 bpfptr_add(&u_core_relo, rec_size);
16159 static int check_btf_info_early(struct bpf_verifier_env *env,
16160 const union bpf_attr *attr,
16166 if (!attr->func_info_cnt && !attr->line_info_cnt) {
16167 if (check_abnormal_return(env))
16172 btf = btf_get_by_fd(attr->prog_btf_fd);
16174 return PTR_ERR(btf);
16175 if (btf_is_kernel(btf)) {
16179 env->prog->aux->btf = btf;
16181 err = check_btf_func_early(env, attr, uattr);
16187 static int check_btf_info(struct bpf_verifier_env *env,
16188 const union bpf_attr *attr,
16193 if (!attr->func_info_cnt && !attr->line_info_cnt) {
16194 if (check_abnormal_return(env))
16199 err = check_btf_func(env, attr, uattr);
16203 err = check_btf_line(env, attr, uattr);
16207 err = check_core_relo(env, attr, uattr);
16214 /* check %cur's range satisfies %old's */
16215 static bool range_within(struct bpf_reg_state *old,
16216 struct bpf_reg_state *cur)
16218 return old->umin_value <= cur->umin_value &&
16219 old->umax_value >= cur->umax_value &&
16220 old->smin_value <= cur->smin_value &&
16221 old->smax_value >= cur->smax_value &&
16222 old->u32_min_value <= cur->u32_min_value &&
16223 old->u32_max_value >= cur->u32_max_value &&
16224 old->s32_min_value <= cur->s32_min_value &&
16225 old->s32_max_value >= cur->s32_max_value;
16228 /* If in the old state two registers had the same id, then they need to have
16229 * the same id in the new state as well. But that id could be different from
16230 * the old state, so we need to track the mapping from old to new ids.
16231 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
16232 * regs with old id 5 must also have new id 9 for the new state to be safe. But
16233 * regs with a different old id could still have new id 9, we don't care about
16235 * So we look through our idmap to see if this old id has been seen before. If
16236 * so, we require the new id to match; otherwise, we add the id pair to the map.
16238 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16240 struct bpf_id_pair *map = idmap->map;
16243 /* either both IDs should be set or both should be zero */
16244 if (!!old_id != !!cur_id)
16247 if (old_id == 0) /* cur_id == 0 as well */
16250 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
16252 /* Reached an empty slot; haven't seen this id before */
16253 map[i].old = old_id;
16254 map[i].cur = cur_id;
16257 if (map[i].old == old_id)
16258 return map[i].cur == cur_id;
16259 if (map[i].cur == cur_id)
16262 /* We ran out of idmap slots, which should be impossible */
16267 /* Similar to check_ids(), but allocate a unique temporary ID
16268 * for 'old_id' or 'cur_id' of zero.
16269 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
16271 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16273 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
16274 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
16276 return check_ids(old_id, cur_id, idmap);
16279 static void clean_func_state(struct bpf_verifier_env *env,
16280 struct bpf_func_state *st)
16282 enum bpf_reg_liveness live;
16285 for (i = 0; i < BPF_REG_FP; i++) {
16286 live = st->regs[i].live;
16287 /* liveness must not touch this register anymore */
16288 st->regs[i].live |= REG_LIVE_DONE;
16289 if (!(live & REG_LIVE_READ))
16290 /* since the register is unused, clear its state
16291 * to make further comparison simpler
16293 __mark_reg_not_init(env, &st->regs[i]);
16296 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
16297 live = st->stack[i].spilled_ptr.live;
16298 /* liveness must not touch this stack slot anymore */
16299 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
16300 if (!(live & REG_LIVE_READ)) {
16301 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
16302 for (j = 0; j < BPF_REG_SIZE; j++)
16303 st->stack[i].slot_type[j] = STACK_INVALID;
16308 static void clean_verifier_state(struct bpf_verifier_env *env,
16309 struct bpf_verifier_state *st)
16313 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
16314 /* all regs in this state in all frames were already marked */
16317 for (i = 0; i <= st->curframe; i++)
16318 clean_func_state(env, st->frame[i]);
16321 /* the parentage chains form a tree.
16322 * the verifier states are added to state lists at given insn and
16323 * pushed into state stack for future exploration.
16324 * when the verifier reaches bpf_exit insn some of the verifer states
16325 * stored in the state lists have their final liveness state already,
16326 * but a lot of states will get revised from liveness point of view when
16327 * the verifier explores other branches.
16330 * 2: if r1 == 100 goto pc+1
16333 * when the verifier reaches exit insn the register r0 in the state list of
16334 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
16335 * of insn 2 and goes exploring further. At the insn 4 it will walk the
16336 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
16338 * Since the verifier pushes the branch states as it sees them while exploring
16339 * the program the condition of walking the branch instruction for the second
16340 * time means that all states below this branch were already explored and
16341 * their final liveness marks are already propagated.
16342 * Hence when the verifier completes the search of state list in is_state_visited()
16343 * we can call this clean_live_states() function to mark all liveness states
16344 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16345 * will not be used.
16346 * This function also clears the registers and stack for states that !READ
16347 * to simplify state merging.
16349 * Important note here that walking the same branch instruction in the callee
16350 * doesn't meant that the states are DONE. The verifier has to compare
16353 static void clean_live_states(struct bpf_verifier_env *env, int insn,
16354 struct bpf_verifier_state *cur)
16356 struct bpf_verifier_state_list *sl;
16358 sl = *explored_state(env, insn);
16360 if (sl->state.branches)
16362 if (sl->state.insn_idx != insn ||
16363 !same_callsites(&sl->state, cur))
16365 clean_verifier_state(env, &sl->state);
16371 static bool regs_exact(const struct bpf_reg_state *rold,
16372 const struct bpf_reg_state *rcur,
16373 struct bpf_idmap *idmap)
16375 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16376 check_ids(rold->id, rcur->id, idmap) &&
16377 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16380 /* Returns true if (rold safe implies rcur safe) */
16381 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
16382 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
16385 return regs_exact(rold, rcur, idmap);
16387 if (!(rold->live & REG_LIVE_READ))
16388 /* explored state didn't use this */
16390 if (rold->type == NOT_INIT)
16391 /* explored state can't have used this */
16393 if (rcur->type == NOT_INIT)
16396 /* Enforce that register types have to match exactly, including their
16397 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16400 * One can make a point that using a pointer register as unbounded
16401 * SCALAR would be technically acceptable, but this could lead to
16402 * pointer leaks because scalars are allowed to leak while pointers
16403 * are not. We could make this safe in special cases if root is
16404 * calling us, but it's probably not worth the hassle.
16406 * Also, register types that are *not* MAYBE_NULL could technically be
16407 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16408 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16409 * to the same map).
16410 * However, if the old MAYBE_NULL register then got NULL checked,
16411 * doing so could have affected others with the same id, and we can't
16412 * check for that because we lost the id when we converted to
16413 * a non-MAYBE_NULL variant.
16414 * So, as a general rule we don't allow mixing MAYBE_NULL and
16415 * non-MAYBE_NULL registers as well.
16417 if (rold->type != rcur->type)
16420 switch (base_type(rold->type)) {
16422 if (env->explore_alu_limits) {
16423 /* explore_alu_limits disables tnum_in() and range_within()
16424 * logic and requires everything to be strict
16426 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16427 check_scalar_ids(rold->id, rcur->id, idmap);
16429 if (!rold->precise)
16431 /* Why check_ids() for scalar registers?
16433 * Consider the following BPF code:
16434 * 1: r6 = ... unbound scalar, ID=a ...
16435 * 2: r7 = ... unbound scalar, ID=b ...
16436 * 3: if (r6 > r7) goto +1
16438 * 5: if (r6 > X) goto ...
16439 * 6: ... memory operation using r7 ...
16441 * First verification path is [1-6]:
16442 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16443 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16444 * r7 <= X, because r6 and r7 share same id.
16445 * Next verification path is [1-4, 6].
16447 * Instruction (6) would be reached in two states:
16448 * I. r6{.id=b}, r7{.id=b} via path 1-6;
16449 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16451 * Use check_ids() to distinguish these states.
16453 * Also verify that new value satisfies old value range knowledge.
16455 return range_within(rold, rcur) &&
16456 tnum_in(rold->var_off, rcur->var_off) &&
16457 check_scalar_ids(rold->id, rcur->id, idmap);
16458 case PTR_TO_MAP_KEY:
16459 case PTR_TO_MAP_VALUE:
16462 case PTR_TO_TP_BUFFER:
16463 /* If the new min/max/var_off satisfy the old ones and
16464 * everything else matches, we are OK.
16466 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16467 range_within(rold, rcur) &&
16468 tnum_in(rold->var_off, rcur->var_off) &&
16469 check_ids(rold->id, rcur->id, idmap) &&
16470 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16471 case PTR_TO_PACKET_META:
16472 case PTR_TO_PACKET:
16473 /* We must have at least as much range as the old ptr
16474 * did, so that any accesses which were safe before are
16475 * still safe. This is true even if old range < old off,
16476 * since someone could have accessed through (ptr - k), or
16477 * even done ptr -= k in a register, to get a safe access.
16479 if (rold->range > rcur->range)
16481 /* If the offsets don't match, we can't trust our alignment;
16482 * nor can we be sure that we won't fall out of range.
16484 if (rold->off != rcur->off)
16486 /* id relations must be preserved */
16487 if (!check_ids(rold->id, rcur->id, idmap))
16489 /* new val must satisfy old val knowledge */
16490 return range_within(rold, rcur) &&
16491 tnum_in(rold->var_off, rcur->var_off);
16493 /* two stack pointers are equal only if they're pointing to
16494 * the same stack frame, since fp-8 in foo != fp-8 in bar
16496 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16498 return regs_exact(rold, rcur, idmap);
16502 static struct bpf_reg_state unbound_reg;
16504 static __init int unbound_reg_init(void)
16506 __mark_reg_unknown_imprecise(&unbound_reg);
16507 unbound_reg.live |= REG_LIVE_READ;
16510 late_initcall(unbound_reg_init);
16512 static bool is_stack_all_misc(struct bpf_verifier_env *env,
16513 struct bpf_stack_state *stack)
16517 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
16518 if ((stack->slot_type[i] == STACK_MISC) ||
16519 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
16527 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
16528 struct bpf_stack_state *stack)
16530 if (is_spilled_scalar_reg64(stack))
16531 return &stack->spilled_ptr;
16533 if (is_stack_all_misc(env, stack))
16534 return &unbound_reg;
16539 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16540 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16544 /* walk slots of the explored stack and ignore any additional
16545 * slots in the current stack, since explored(safe) state
16548 for (i = 0; i < old->allocated_stack; i++) {
16549 struct bpf_reg_state *old_reg, *cur_reg;
16551 spi = i / BPF_REG_SIZE;
16554 old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16555 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16558 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16559 i += BPF_REG_SIZE - 1;
16560 /* explored state didn't use this */
16564 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16567 if (env->allow_uninit_stack &&
16568 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16571 /* explored stack has more populated slots than current stack
16572 * and these slots were used
16574 if (i >= cur->allocated_stack)
16577 /* 64-bit scalar spill vs all slots MISC and vice versa.
16578 * Load from all slots MISC produces unbound scalar.
16579 * Construct a fake register for such stack and call
16580 * regsafe() to ensure scalar ids are compared.
16582 old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
16583 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
16584 if (old_reg && cur_reg) {
16585 if (!regsafe(env, old_reg, cur_reg, idmap, exact))
16587 i += BPF_REG_SIZE - 1;
16591 /* if old state was safe with misc data in the stack
16592 * it will be safe with zero-initialized stack.
16593 * The opposite is not true
16595 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16596 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16598 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16599 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16600 /* Ex: old explored (safe) state has STACK_SPILL in
16601 * this stack slot, but current has STACK_MISC ->
16602 * this verifier states are not equivalent,
16603 * return false to continue verification of this path
16606 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16608 /* Both old and cur are having same slot_type */
16609 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16611 /* when explored and current stack slot are both storing
16612 * spilled registers, check that stored pointers types
16613 * are the same as well.
16614 * Ex: explored safe path could have stored
16615 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16616 * but current path has stored:
16617 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16618 * such verifier states are not equivalent.
16619 * return false to continue verification of this path
16621 if (!regsafe(env, &old->stack[spi].spilled_ptr,
16622 &cur->stack[spi].spilled_ptr, idmap, exact))
16626 old_reg = &old->stack[spi].spilled_ptr;
16627 cur_reg = &cur->stack[spi].spilled_ptr;
16628 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16629 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16630 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16634 old_reg = &old->stack[spi].spilled_ptr;
16635 cur_reg = &cur->stack[spi].spilled_ptr;
16636 /* iter.depth is not compared between states as it
16637 * doesn't matter for correctness and would otherwise
16638 * prevent convergence; we maintain it only to prevent
16639 * infinite loop check triggering, see
16640 * iter_active_depths_differ()
16642 if (old_reg->iter.btf != cur_reg->iter.btf ||
16643 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16644 old_reg->iter.state != cur_reg->iter.state ||
16645 /* ignore {old_reg,cur_reg}->iter.depth, see above */
16646 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16651 case STACK_INVALID:
16653 /* Ensure that new unhandled slot types return false by default */
16661 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16662 struct bpf_idmap *idmap)
16666 if (old->acquired_refs != cur->acquired_refs)
16669 for (i = 0; i < old->acquired_refs; i++) {
16670 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16677 /* compare two verifier states
16679 * all states stored in state_list are known to be valid, since
16680 * verifier reached 'bpf_exit' instruction through them
16682 * this function is called when verifier exploring different branches of
16683 * execution popped from the state stack. If it sees an old state that has
16684 * more strict register state and more strict stack state then this execution
16685 * branch doesn't need to be explored further, since verifier already
16686 * concluded that more strict state leads to valid finish.
16688 * Therefore two states are equivalent if register state is more conservative
16689 * and explored stack state is more conservative than the current one.
16692 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16693 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16695 * In other words if current stack state (one being explored) has more
16696 * valid slots than old one that already passed validation, it means
16697 * the verifier can stop exploring and conclude that current state is valid too
16699 * Similarly with registers. If explored state has register type as invalid
16700 * whereas register type in current state is meaningful, it means that
16701 * the current state will reach 'bpf_exit' instruction safely
16703 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16704 struct bpf_func_state *cur, bool exact)
16708 for (i = 0; i < MAX_BPF_REG; i++)
16709 if (!regsafe(env, &old->regs[i], &cur->regs[i],
16710 &env->idmap_scratch, exact))
16713 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16716 if (!refsafe(old, cur, &env->idmap_scratch))
16722 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16724 env->idmap_scratch.tmp_id_gen = env->id_gen;
16725 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16728 static bool states_equal(struct bpf_verifier_env *env,
16729 struct bpf_verifier_state *old,
16730 struct bpf_verifier_state *cur,
16735 if (old->curframe != cur->curframe)
16738 reset_idmap_scratch(env);
16740 /* Verification state from speculative execution simulation
16741 * must never prune a non-speculative execution one.
16743 if (old->speculative && !cur->speculative)
16746 if (old->active_lock.ptr != cur->active_lock.ptr)
16749 /* Old and cur active_lock's have to be either both present
16752 if (!!old->active_lock.id != !!cur->active_lock.id)
16755 if (old->active_lock.id &&
16756 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16759 if (old->active_rcu_lock != cur->active_rcu_lock)
16762 /* for states to be equal callsites have to be the same
16763 * and all frame states need to be equivalent
16765 for (i = 0; i <= old->curframe; i++) {
16766 if (old->frame[i]->callsite != cur->frame[i]->callsite)
16768 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16774 /* Return 0 if no propagation happened. Return negative error code if error
16775 * happened. Otherwise, return the propagated bit.
16777 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16778 struct bpf_reg_state *reg,
16779 struct bpf_reg_state *parent_reg)
16781 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16782 u8 flag = reg->live & REG_LIVE_READ;
16785 /* When comes here, read flags of PARENT_REG or REG could be any of
16786 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16787 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16789 if (parent_flag == REG_LIVE_READ64 ||
16790 /* Or if there is no read flag from REG. */
16792 /* Or if the read flag from REG is the same as PARENT_REG. */
16793 parent_flag == flag)
16796 err = mark_reg_read(env, reg, parent_reg, flag);
16803 /* A write screens off any subsequent reads; but write marks come from the
16804 * straight-line code between a state and its parent. When we arrive at an
16805 * equivalent state (jump target or such) we didn't arrive by the straight-line
16806 * code, so read marks in the state must propagate to the parent regardless
16807 * of the state's write marks. That's what 'parent == state->parent' comparison
16808 * in mark_reg_read() is for.
16810 static int propagate_liveness(struct bpf_verifier_env *env,
16811 const struct bpf_verifier_state *vstate,
16812 struct bpf_verifier_state *vparent)
16814 struct bpf_reg_state *state_reg, *parent_reg;
16815 struct bpf_func_state *state, *parent;
16816 int i, frame, err = 0;
16818 if (vparent->curframe != vstate->curframe) {
16819 WARN(1, "propagate_live: parent frame %d current frame %d\n",
16820 vparent->curframe, vstate->curframe);
16823 /* Propagate read liveness of registers... */
16824 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16825 for (frame = 0; frame <= vstate->curframe; frame++) {
16826 parent = vparent->frame[frame];
16827 state = vstate->frame[frame];
16828 parent_reg = parent->regs;
16829 state_reg = state->regs;
16830 /* We don't need to worry about FP liveness, it's read-only */
16831 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16832 err = propagate_liveness_reg(env, &state_reg[i],
16836 if (err == REG_LIVE_READ64)
16837 mark_insn_zext(env, &parent_reg[i]);
16840 /* Propagate stack slots. */
16841 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16842 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16843 parent_reg = &parent->stack[i].spilled_ptr;
16844 state_reg = &state->stack[i].spilled_ptr;
16845 err = propagate_liveness_reg(env, state_reg,
16854 /* find precise scalars in the previous equivalent state and
16855 * propagate them into the current state
16857 static int propagate_precision(struct bpf_verifier_env *env,
16858 const struct bpf_verifier_state *old)
16860 struct bpf_reg_state *state_reg;
16861 struct bpf_func_state *state;
16862 int i, err = 0, fr;
16865 for (fr = old->curframe; fr >= 0; fr--) {
16866 state = old->frame[fr];
16867 state_reg = state->regs;
16869 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16870 if (state_reg->type != SCALAR_VALUE ||
16871 !state_reg->precise ||
16872 !(state_reg->live & REG_LIVE_READ))
16874 if (env->log.level & BPF_LOG_LEVEL2) {
16876 verbose(env, "frame %d: propagating r%d", fr, i);
16878 verbose(env, ",r%d", i);
16880 bt_set_frame_reg(&env->bt, fr, i);
16884 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16885 if (!is_spilled_reg(&state->stack[i]))
16887 state_reg = &state->stack[i].spilled_ptr;
16888 if (state_reg->type != SCALAR_VALUE ||
16889 !state_reg->precise ||
16890 !(state_reg->live & REG_LIVE_READ))
16892 if (env->log.level & BPF_LOG_LEVEL2) {
16894 verbose(env, "frame %d: propagating fp%d",
16895 fr, (-i - 1) * BPF_REG_SIZE);
16897 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16899 bt_set_frame_slot(&env->bt, fr, i);
16903 verbose(env, "\n");
16906 err = mark_chain_precision_batch(env);
16913 static bool states_maybe_looping(struct bpf_verifier_state *old,
16914 struct bpf_verifier_state *cur)
16916 struct bpf_func_state *fold, *fcur;
16917 int i, fr = cur->curframe;
16919 if (old->curframe != fr)
16922 fold = old->frame[fr];
16923 fcur = cur->frame[fr];
16924 for (i = 0; i < MAX_BPF_REG; i++)
16925 if (memcmp(&fold->regs[i], &fcur->regs[i],
16926 offsetof(struct bpf_reg_state, parent)))
16931 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16933 return env->insn_aux_data[insn_idx].is_iter_next;
16936 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16937 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16938 * states to match, which otherwise would look like an infinite loop. So while
16939 * iter_next() calls are taken care of, we still need to be careful and
16940 * prevent erroneous and too eager declaration of "ininite loop", when
16941 * iterators are involved.
16943 * Here's a situation in pseudo-BPF assembly form:
16945 * 0: again: ; set up iter_next() call args
16946 * 1: r1 = &it ; <CHECKPOINT HERE>
16947 * 2: call bpf_iter_num_next ; this is iter_next() call
16948 * 3: if r0 == 0 goto done
16949 * 4: ... something useful here ...
16950 * 5: goto again ; another iteration
16953 * 8: call bpf_iter_num_destroy ; clean up iter state
16956 * This is a typical loop. Let's assume that we have a prune point at 1:,
16957 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16958 * again`, assuming other heuristics don't get in a way).
16960 * When we first time come to 1:, let's say we have some state X. We proceed
16961 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16962 * Now we come back to validate that forked ACTIVE state. We proceed through
16963 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16964 * are converging. But the problem is that we don't know that yet, as this
16965 * convergence has to happen at iter_next() call site only. So if nothing is
16966 * done, at 1: verifier will use bounded loop logic and declare infinite
16967 * looping (and would be *technically* correct, if not for iterator's
16968 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16969 * don't want that. So what we do in process_iter_next_call() when we go on
16970 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16971 * a different iteration. So when we suspect an infinite loop, we additionally
16972 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16973 * pretend we are not looping and wait for next iter_next() call.
16975 * This only applies to ACTIVE state. In DRAINED state we don't expect to
16976 * loop, because that would actually mean infinite loop, as DRAINED state is
16977 * "sticky", and so we'll keep returning into the same instruction with the
16978 * same state (at least in one of possible code paths).
16980 * This approach allows to keep infinite loop heuristic even in the face of
16981 * active iterator. E.g., C snippet below is and will be detected as
16982 * inifintely looping:
16984 * struct bpf_iter_num it;
16987 * bpf_iter_num_new(&it, 0, 10);
16988 * while ((p = bpf_iter_num_next(&t))) {
16990 * while (x--) {} // <<-- infinite loop here
16994 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16996 struct bpf_reg_state *slot, *cur_slot;
16997 struct bpf_func_state *state;
17000 for (fr = old->curframe; fr >= 0; fr--) {
17001 state = old->frame[fr];
17002 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17003 if (state->stack[i].slot_type[0] != STACK_ITER)
17006 slot = &state->stack[i].spilled_ptr;
17007 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
17010 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
17011 if (cur_slot->iter.depth != slot->iter.depth)
17018 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
17020 struct bpf_verifier_state_list *new_sl;
17021 struct bpf_verifier_state_list *sl, **pprev;
17022 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
17023 int i, j, n, err, states_cnt = 0;
17024 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
17025 bool add_new_state = force_new_state;
17028 /* bpf progs typically have pruning point every 4 instructions
17029 * http://vger.kernel.org/bpfconf2019.html#session-1
17030 * Do not add new state for future pruning if the verifier hasn't seen
17031 * at least 2 jumps and at least 8 instructions.
17032 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
17033 * In tests that amounts to up to 50% reduction into total verifier
17034 * memory consumption and 20% verifier time speedup.
17036 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
17037 env->insn_processed - env->prev_insn_processed >= 8)
17038 add_new_state = true;
17040 pprev = explored_state(env, insn_idx);
17043 clean_live_states(env, insn_idx, cur);
17047 if (sl->state.insn_idx != insn_idx)
17050 if (sl->state.branches) {
17051 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
17053 if (frame->in_async_callback_fn &&
17054 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
17055 /* Different async_entry_cnt means that the verifier is
17056 * processing another entry into async callback.
17057 * Seeing the same state is not an indication of infinite
17058 * loop or infinite recursion.
17059 * But finding the same state doesn't mean that it's safe
17060 * to stop processing the current state. The previous state
17061 * hasn't yet reached bpf_exit, since state.branches > 0.
17062 * Checking in_async_callback_fn alone is not enough either.
17063 * Since the verifier still needs to catch infinite loops
17064 * inside async callbacks.
17066 goto skip_inf_loop_check;
17068 /* BPF open-coded iterators loop detection is special.
17069 * states_maybe_looping() logic is too simplistic in detecting
17070 * states that *might* be equivalent, because it doesn't know
17071 * about ID remapping, so don't even perform it.
17072 * See process_iter_next_call() and iter_active_depths_differ()
17073 * for overview of the logic. When current and one of parent
17074 * states are detected as equivalent, it's a good thing: we prove
17075 * convergence and can stop simulating further iterations.
17076 * It's safe to assume that iterator loop will finish, taking into
17077 * account iter_next() contract of eventually returning
17078 * sticky NULL result.
17080 * Note, that states have to be compared exactly in this case because
17081 * read and precision marks might not be finalized inside the loop.
17082 * E.g. as in the program below:
17085 * 2. r6 = bpf_get_prandom_u32()
17086 * 3. while (bpf_iter_num_next(&fp[-8])) {
17087 * 4. if (r6 != 42) {
17089 * 6. r6 = bpf_get_prandom_u32()
17094 * 11. r8 = *(u64 *)(r0 + 0)
17095 * 12. r6 = bpf_get_prandom_u32()
17098 * Here verifier would first visit path 1-3, create a checkpoint at 3
17099 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
17100 * not have read or precision mark for r7 yet, thus inexact states
17101 * comparison would discard current state with r7=-32
17102 * => unsafe memory access at 11 would not be caught.
17104 if (is_iter_next_insn(env, insn_idx)) {
17105 if (states_equal(env, &sl->state, cur, true)) {
17106 struct bpf_func_state *cur_frame;
17107 struct bpf_reg_state *iter_state, *iter_reg;
17110 cur_frame = cur->frame[cur->curframe];
17111 /* btf_check_iter_kfuncs() enforces that
17112 * iter state pointer is always the first arg
17114 iter_reg = &cur_frame->regs[BPF_REG_1];
17115 /* current state is valid due to states_equal(),
17116 * so we can assume valid iter and reg state,
17117 * no need for extra (re-)validations
17119 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
17120 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
17121 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
17122 update_loop_entry(cur, &sl->state);
17126 goto skip_inf_loop_check;
17128 if (calls_callback(env, insn_idx)) {
17129 if (states_equal(env, &sl->state, cur, true))
17131 goto skip_inf_loop_check;
17133 /* attempt to detect infinite loop to avoid unnecessary doomed work */
17134 if (states_maybe_looping(&sl->state, cur) &&
17135 states_equal(env, &sl->state, cur, true) &&
17136 !iter_active_depths_differ(&sl->state, cur) &&
17137 sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
17138 verbose_linfo(env, insn_idx, "; ");
17139 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
17140 verbose(env, "cur state:");
17141 print_verifier_state(env, cur->frame[cur->curframe], true);
17142 verbose(env, "old state:");
17143 print_verifier_state(env, sl->state.frame[cur->curframe], true);
17146 /* if the verifier is processing a loop, avoid adding new state
17147 * too often, since different loop iterations have distinct
17148 * states and may not help future pruning.
17149 * This threshold shouldn't be too low to make sure that
17150 * a loop with large bound will be rejected quickly.
17151 * The most abusive loop will be:
17153 * if r1 < 1000000 goto pc-2
17154 * 1M insn_procssed limit / 100 == 10k peak states.
17155 * This threshold shouldn't be too high either, since states
17156 * at the end of the loop are likely to be useful in pruning.
17158 skip_inf_loop_check:
17159 if (!force_new_state &&
17160 env->jmps_processed - env->prev_jmps_processed < 20 &&
17161 env->insn_processed - env->prev_insn_processed < 100)
17162 add_new_state = false;
17165 /* If sl->state is a part of a loop and this loop's entry is a part of
17166 * current verification path then states have to be compared exactly.
17167 * 'force_exact' is needed to catch the following case:
17169 * initial Here state 'succ' was processed first,
17170 * | it was eventually tracked to produce a
17171 * V state identical to 'hdr'.
17172 * .---------> hdr All branches from 'succ' had been explored
17173 * | | and thus 'succ' has its .branches == 0.
17175 * | .------... Suppose states 'cur' and 'succ' correspond
17176 * | | | to the same instruction + callsites.
17177 * | V V In such case it is necessary to check
17178 * | ... ... if 'succ' and 'cur' are states_equal().
17179 * | | | If 'succ' and 'cur' are a part of the
17180 * | V V same loop exact flag has to be set.
17181 * | succ <- cur To check if that is the case, verify
17182 * | | if loop entry of 'succ' is in current
17188 * Additional details are in the comment before get_loop_entry().
17190 loop_entry = get_loop_entry(&sl->state);
17191 force_exact = loop_entry && loop_entry->branches > 0;
17192 if (states_equal(env, &sl->state, cur, force_exact)) {
17194 update_loop_entry(cur, loop_entry);
17197 /* reached equivalent register/stack state,
17198 * prune the search.
17199 * Registers read by the continuation are read by us.
17200 * If we have any write marks in env->cur_state, they
17201 * will prevent corresponding reads in the continuation
17202 * from reaching our parent (an explored_state). Our
17203 * own state will get the read marks recorded, but
17204 * they'll be immediately forgotten as we're pruning
17205 * this state and will pop a new one.
17207 err = propagate_liveness(env, &sl->state, cur);
17209 /* if previous state reached the exit with precision and
17210 * current state is equivalent to it (except precsion marks)
17211 * the precision needs to be propagated back in
17212 * the current state.
17214 if (is_jmp_point(env, env->insn_idx))
17215 err = err ? : push_jmp_history(env, cur, 0);
17216 err = err ? : propagate_precision(env, &sl->state);
17222 /* when new state is not going to be added do not increase miss count.
17223 * Otherwise several loop iterations will remove the state
17224 * recorded earlier. The goal of these heuristics is to have
17225 * states from some iterations of the loop (some in the beginning
17226 * and some at the end) to help pruning.
17230 /* heuristic to determine whether this state is beneficial
17231 * to keep checking from state equivalence point of view.
17232 * Higher numbers increase max_states_per_insn and verification time,
17233 * but do not meaningfully decrease insn_processed.
17234 * 'n' controls how many times state could miss before eviction.
17235 * Use bigger 'n' for checkpoints because evicting checkpoint states
17236 * too early would hinder iterator convergence.
17238 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
17239 if (sl->miss_cnt > sl->hit_cnt * n + n) {
17240 /* the state is unlikely to be useful. Remove it to
17241 * speed up verification
17244 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
17245 !sl->state.used_as_loop_entry) {
17246 u32 br = sl->state.branches;
17249 "BUG live_done but branches_to_explore %d\n",
17251 free_verifier_state(&sl->state, false);
17253 env->peak_states--;
17255 /* cannot free this state, since parentage chain may
17256 * walk it later. Add it for free_list instead to
17257 * be freed at the end of verification
17259 sl->next = env->free_list;
17260 env->free_list = sl;
17270 if (env->max_states_per_insn < states_cnt)
17271 env->max_states_per_insn = states_cnt;
17273 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
17276 if (!add_new_state)
17279 /* There were no equivalent states, remember the current one.
17280 * Technically the current state is not proven to be safe yet,
17281 * but it will either reach outer most bpf_exit (which means it's safe)
17282 * or it will be rejected. When there are no loops the verifier won't be
17283 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
17284 * again on the way to bpf_exit.
17285 * When looping the sl->state.branches will be > 0 and this state
17286 * will not be considered for equivalence until branches == 0.
17288 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
17291 env->total_states++;
17292 env->peak_states++;
17293 env->prev_jmps_processed = env->jmps_processed;
17294 env->prev_insn_processed = env->insn_processed;
17296 /* forget precise markings we inherited, see __mark_chain_precision */
17297 if (env->bpf_capable)
17298 mark_all_scalars_imprecise(env, cur);
17300 /* add new state to the head of linked list */
17301 new = &new_sl->state;
17302 err = copy_verifier_state(new, cur);
17304 free_verifier_state(new, false);
17308 new->insn_idx = insn_idx;
17309 WARN_ONCE(new->branches != 1,
17310 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
17313 cur->first_insn_idx = insn_idx;
17314 cur->dfs_depth = new->dfs_depth + 1;
17315 clear_jmp_history(cur);
17316 new_sl->next = *explored_state(env, insn_idx);
17317 *explored_state(env, insn_idx) = new_sl;
17318 /* connect new state to parentage chain. Current frame needs all
17319 * registers connected. Only r6 - r9 of the callers are alive (pushed
17320 * to the stack implicitly by JITs) so in callers' frames connect just
17321 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
17322 * the state of the call instruction (with WRITTEN set), and r0 comes
17323 * from callee with its full parentage chain, anyway.
17325 /* clear write marks in current state: the writes we did are not writes
17326 * our child did, so they don't screen off its reads from us.
17327 * (There are no read marks in current state, because reads always mark
17328 * their parent and current state never has children yet. Only
17329 * explored_states can get read marks.)
17331 for (j = 0; j <= cur->curframe; j++) {
17332 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
17333 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
17334 for (i = 0; i < BPF_REG_FP; i++)
17335 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
17338 /* all stack frames are accessible from callee, clear them all */
17339 for (j = 0; j <= cur->curframe; j++) {
17340 struct bpf_func_state *frame = cur->frame[j];
17341 struct bpf_func_state *newframe = new->frame[j];
17343 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
17344 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
17345 frame->stack[i].spilled_ptr.parent =
17346 &newframe->stack[i].spilled_ptr;
17352 /* Return true if it's OK to have the same insn return a different type. */
17353 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17355 switch (base_type(type)) {
17357 case PTR_TO_SOCKET:
17358 case PTR_TO_SOCK_COMMON:
17359 case PTR_TO_TCP_SOCK:
17360 case PTR_TO_XDP_SOCK:
17361 case PTR_TO_BTF_ID:
17368 /* If an instruction was previously used with particular pointer types, then we
17369 * need to be careful to avoid cases such as the below, where it may be ok
17370 * for one branch accessing the pointer, but not ok for the other branch:
17375 * R1 = some_other_valid_ptr;
17378 * R2 = *(u32 *)(R1 + 0);
17380 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17382 return src != prev && (!reg_type_mismatch_ok(src) ||
17383 !reg_type_mismatch_ok(prev));
17386 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17387 bool allow_trust_missmatch)
17389 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17391 if (*prev_type == NOT_INIT) {
17392 /* Saw a valid insn
17393 * dst_reg = *(u32 *)(src_reg + off)
17394 * save type to validate intersecting paths
17397 } else if (reg_type_mismatch(type, *prev_type)) {
17398 /* Abuser program is trying to use the same insn
17399 * dst_reg = *(u32*) (src_reg + off)
17400 * with different pointer types:
17401 * src_reg == ctx in one branch and
17402 * src_reg == stack|map in some other branch.
17405 if (allow_trust_missmatch &&
17406 base_type(type) == PTR_TO_BTF_ID &&
17407 base_type(*prev_type) == PTR_TO_BTF_ID) {
17409 * Have to support a use case when one path through
17410 * the program yields TRUSTED pointer while another
17411 * is UNTRUSTED. Fallback to UNTRUSTED to generate
17412 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17414 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17416 verbose(env, "same insn cannot be used with different pointers\n");
17424 static int do_check(struct bpf_verifier_env *env)
17426 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17427 struct bpf_verifier_state *state = env->cur_state;
17428 struct bpf_insn *insns = env->prog->insnsi;
17429 struct bpf_reg_state *regs;
17430 int insn_cnt = env->prog->len;
17431 bool do_print_state = false;
17432 int prev_insn_idx = -1;
17435 bool exception_exit = false;
17436 struct bpf_insn *insn;
17440 /* reset current history entry on each new instruction */
17441 env->cur_hist_ent = NULL;
17443 env->prev_insn_idx = prev_insn_idx;
17444 if (env->insn_idx >= insn_cnt) {
17445 verbose(env, "invalid insn idx %d insn_cnt %d\n",
17446 env->insn_idx, insn_cnt);
17450 insn = &insns[env->insn_idx];
17451 class = BPF_CLASS(insn->code);
17453 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17455 "BPF program is too large. Processed %d insn\n",
17456 env->insn_processed);
17460 state->last_insn_idx = env->prev_insn_idx;
17462 if (is_prune_point(env, env->insn_idx)) {
17463 err = is_state_visited(env, env->insn_idx);
17467 /* found equivalent state, can prune the search */
17468 if (env->log.level & BPF_LOG_LEVEL) {
17469 if (do_print_state)
17470 verbose(env, "\nfrom %d to %d%s: safe\n",
17471 env->prev_insn_idx, env->insn_idx,
17472 env->cur_state->speculative ?
17473 " (speculative execution)" : "");
17475 verbose(env, "%d: safe\n", env->insn_idx);
17477 goto process_bpf_exit;
17481 if (is_jmp_point(env, env->insn_idx)) {
17482 err = push_jmp_history(env, state, 0);
17487 if (signal_pending(current))
17490 if (need_resched())
17493 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17494 verbose(env, "\nfrom %d to %d%s:",
17495 env->prev_insn_idx, env->insn_idx,
17496 env->cur_state->speculative ?
17497 " (speculative execution)" : "");
17498 print_verifier_state(env, state->frame[state->curframe], true);
17499 do_print_state = false;
17502 if (env->log.level & BPF_LOG_LEVEL) {
17503 const struct bpf_insn_cbs cbs = {
17504 .cb_call = disasm_kfunc_name,
17505 .cb_print = verbose,
17506 .private_data = env,
17509 if (verifier_state_scratched(env))
17510 print_insn_state(env, state->frame[state->curframe]);
17512 verbose_linfo(env, env->insn_idx, "; ");
17513 env->prev_log_pos = env->log.end_pos;
17514 verbose(env, "%d: ", env->insn_idx);
17515 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17516 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17517 env->prev_log_pos = env->log.end_pos;
17520 if (bpf_prog_is_offloaded(env->prog->aux)) {
17521 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17522 env->prev_insn_idx);
17527 regs = cur_regs(env);
17528 sanitize_mark_insn_seen(env);
17529 prev_insn_idx = env->insn_idx;
17531 if (class == BPF_ALU || class == BPF_ALU64) {
17532 err = check_alu_op(env, insn);
17536 } else if (class == BPF_LDX) {
17537 enum bpf_reg_type src_reg_type;
17539 /* check for reserved fields is already done */
17541 /* check src operand */
17542 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17546 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17550 src_reg_type = regs[insn->src_reg].type;
17552 /* check that memory (src_reg + off) is readable,
17553 * the state of dst_reg will be updated by this func
17555 err = check_mem_access(env, env->insn_idx, insn->src_reg,
17556 insn->off, BPF_SIZE(insn->code),
17557 BPF_READ, insn->dst_reg, false,
17558 BPF_MODE(insn->code) == BPF_MEMSX);
17559 err = err ?: save_aux_ptr_type(env, src_reg_type, true);
17560 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx");
17563 } else if (class == BPF_STX) {
17564 enum bpf_reg_type dst_reg_type;
17566 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17567 err = check_atomic(env, env->insn_idx, insn);
17574 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17575 verbose(env, "BPF_STX uses reserved fields\n");
17579 /* check src1 operand */
17580 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17583 /* check src2 operand */
17584 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17588 dst_reg_type = regs[insn->dst_reg].type;
17590 /* check that memory (dst_reg + off) is writeable */
17591 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17592 insn->off, BPF_SIZE(insn->code),
17593 BPF_WRITE, insn->src_reg, false, false);
17597 err = save_aux_ptr_type(env, dst_reg_type, false);
17600 } else if (class == BPF_ST) {
17601 enum bpf_reg_type dst_reg_type;
17603 if (BPF_MODE(insn->code) != BPF_MEM ||
17604 insn->src_reg != BPF_REG_0) {
17605 verbose(env, "BPF_ST uses reserved fields\n");
17608 /* check src operand */
17609 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17613 dst_reg_type = regs[insn->dst_reg].type;
17615 /* check that memory (dst_reg + off) is writeable */
17616 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17617 insn->off, BPF_SIZE(insn->code),
17618 BPF_WRITE, -1, false, false);
17622 err = save_aux_ptr_type(env, dst_reg_type, false);
17625 } else if (class == BPF_JMP || class == BPF_JMP32) {
17626 u8 opcode = BPF_OP(insn->code);
17628 env->jmps_processed++;
17629 if (opcode == BPF_CALL) {
17630 if (BPF_SRC(insn->code) != BPF_K ||
17631 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17632 && insn->off != 0) ||
17633 (insn->src_reg != BPF_REG_0 &&
17634 insn->src_reg != BPF_PSEUDO_CALL &&
17635 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17636 insn->dst_reg != BPF_REG_0 ||
17637 class == BPF_JMP32) {
17638 verbose(env, "BPF_CALL uses reserved fields\n");
17642 if (env->cur_state->active_lock.ptr) {
17643 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17644 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17645 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17646 verbose(env, "function calls are not allowed while holding a lock\n");
17650 if (insn->src_reg == BPF_PSEUDO_CALL) {
17651 err = check_func_call(env, insn, &env->insn_idx);
17652 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17653 err = check_kfunc_call(env, insn, &env->insn_idx);
17654 if (!err && is_bpf_throw_kfunc(insn)) {
17655 exception_exit = true;
17656 goto process_bpf_exit_full;
17659 err = check_helper_call(env, insn, &env->insn_idx);
17664 mark_reg_scratched(env, BPF_REG_0);
17665 } else if (opcode == BPF_JA) {
17666 if (BPF_SRC(insn->code) != BPF_K ||
17667 insn->src_reg != BPF_REG_0 ||
17668 insn->dst_reg != BPF_REG_0 ||
17669 (class == BPF_JMP && insn->imm != 0) ||
17670 (class == BPF_JMP32 && insn->off != 0)) {
17671 verbose(env, "BPF_JA uses reserved fields\n");
17675 if (class == BPF_JMP)
17676 env->insn_idx += insn->off + 1;
17678 env->insn_idx += insn->imm + 1;
17681 } else if (opcode == BPF_EXIT) {
17682 if (BPF_SRC(insn->code) != BPF_K ||
17684 insn->src_reg != BPF_REG_0 ||
17685 insn->dst_reg != BPF_REG_0 ||
17686 class == BPF_JMP32) {
17687 verbose(env, "BPF_EXIT uses reserved fields\n");
17690 process_bpf_exit_full:
17691 if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) {
17692 verbose(env, "bpf_spin_unlock is missing\n");
17696 if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) {
17697 verbose(env, "bpf_rcu_read_unlock is missing\n");
17701 /* We must do check_reference_leak here before
17702 * prepare_func_exit to handle the case when
17703 * state->curframe > 0, it may be a callback
17704 * function, for which reference_state must
17705 * match caller reference state when it exits.
17707 err = check_reference_leak(env, exception_exit);
17711 /* The side effect of the prepare_func_exit
17712 * which is being skipped is that it frees
17713 * bpf_func_state. Typically, process_bpf_exit
17714 * will only be hit with outermost exit.
17715 * copy_verifier_state in pop_stack will handle
17716 * freeing of any extra bpf_func_state left over
17717 * from not processing all nested function
17718 * exits. We also skip return code checks as
17719 * they are not needed for exceptional exits.
17721 if (exception_exit)
17722 goto process_bpf_exit;
17724 if (state->curframe) {
17725 /* exit from nested function */
17726 err = prepare_func_exit(env, &env->insn_idx);
17729 do_print_state = true;
17733 err = check_return_code(env, BPF_REG_0, "R0");
17737 mark_verifier_state_scratched(env);
17738 update_branch_counts(env, env->cur_state);
17739 err = pop_stack(env, &prev_insn_idx,
17740 &env->insn_idx, pop_log);
17742 if (err != -ENOENT)
17746 do_print_state = true;
17750 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17754 } else if (class == BPF_LD) {
17755 u8 mode = BPF_MODE(insn->code);
17757 if (mode == BPF_ABS || mode == BPF_IND) {
17758 err = check_ld_abs(env, insn);
17762 } else if (mode == BPF_IMM) {
17763 err = check_ld_imm(env, insn);
17768 sanitize_mark_insn_seen(env);
17770 verbose(env, "invalid BPF_LD mode\n");
17774 verbose(env, "unknown insn class %d\n", class);
17784 static int find_btf_percpu_datasec(struct btf *btf)
17786 const struct btf_type *t;
17791 * Both vmlinux and module each have their own ".data..percpu"
17792 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17793 * types to look at only module's own BTF types.
17795 n = btf_nr_types(btf);
17796 if (btf_is_module(btf))
17797 i = btf_nr_types(btf_vmlinux);
17801 for(; i < n; i++) {
17802 t = btf_type_by_id(btf, i);
17803 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17806 tname = btf_name_by_offset(btf, t->name_off);
17807 if (!strcmp(tname, ".data..percpu"))
17814 /* replace pseudo btf_id with kernel symbol address */
17815 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17816 struct bpf_insn *insn,
17817 struct bpf_insn_aux_data *aux)
17819 const struct btf_var_secinfo *vsi;
17820 const struct btf_type *datasec;
17821 struct btf_mod_pair *btf_mod;
17822 const struct btf_type *t;
17823 const char *sym_name;
17824 bool percpu = false;
17825 u32 type, id = insn->imm;
17829 int i, btf_fd, err;
17831 btf_fd = insn[1].imm;
17833 btf = btf_get_by_fd(btf_fd);
17835 verbose(env, "invalid module BTF object FD specified.\n");
17839 if (!btf_vmlinux) {
17840 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17847 t = btf_type_by_id(btf, id);
17849 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17854 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17855 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17860 sym_name = btf_name_by_offset(btf, t->name_off);
17861 addr = kallsyms_lookup_name(sym_name);
17863 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17868 insn[0].imm = (u32)addr;
17869 insn[1].imm = addr >> 32;
17871 if (btf_type_is_func(t)) {
17872 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17873 aux->btf_var.mem_size = 0;
17877 datasec_id = find_btf_percpu_datasec(btf);
17878 if (datasec_id > 0) {
17879 datasec = btf_type_by_id(btf, datasec_id);
17880 for_each_vsi(i, datasec, vsi) {
17881 if (vsi->type == id) {
17889 t = btf_type_skip_modifiers(btf, type, NULL);
17891 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17892 aux->btf_var.btf = btf;
17893 aux->btf_var.btf_id = type;
17894 } else if (!btf_type_is_struct(t)) {
17895 const struct btf_type *ret;
17899 /* resolve the type size of ksym. */
17900 ret = btf_resolve_size(btf, t, &tsize);
17902 tname = btf_name_by_offset(btf, t->name_off);
17903 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17904 tname, PTR_ERR(ret));
17908 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17909 aux->btf_var.mem_size = tsize;
17911 aux->btf_var.reg_type = PTR_TO_BTF_ID;
17912 aux->btf_var.btf = btf;
17913 aux->btf_var.btf_id = type;
17916 /* check whether we recorded this BTF (and maybe module) already */
17917 for (i = 0; i < env->used_btf_cnt; i++) {
17918 if (env->used_btfs[i].btf == btf) {
17924 if (env->used_btf_cnt >= MAX_USED_BTFS) {
17929 btf_mod = &env->used_btfs[env->used_btf_cnt];
17930 btf_mod->btf = btf;
17931 btf_mod->module = NULL;
17933 /* if we reference variables from kernel module, bump its refcount */
17934 if (btf_is_module(btf)) {
17935 btf_mod->module = btf_try_get_module(btf);
17936 if (!btf_mod->module) {
17942 env->used_btf_cnt++;
17950 static bool is_tracing_prog_type(enum bpf_prog_type type)
17953 case BPF_PROG_TYPE_KPROBE:
17954 case BPF_PROG_TYPE_TRACEPOINT:
17955 case BPF_PROG_TYPE_PERF_EVENT:
17956 case BPF_PROG_TYPE_RAW_TRACEPOINT:
17957 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17964 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17965 struct bpf_map *map,
17966 struct bpf_prog *prog)
17969 enum bpf_prog_type prog_type = resolve_prog_type(prog);
17971 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17972 btf_record_has_field(map->record, BPF_RB_ROOT)) {
17973 if (is_tracing_prog_type(prog_type)) {
17974 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17979 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17980 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17981 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17985 if (is_tracing_prog_type(prog_type)) {
17986 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17991 if (btf_record_has_field(map->record, BPF_TIMER)) {
17992 if (is_tracing_prog_type(prog_type)) {
17993 verbose(env, "tracing progs cannot use bpf_timer yet\n");
17998 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17999 !bpf_offload_prog_map_match(prog, map)) {
18000 verbose(env, "offload device mismatch between prog and map\n");
18004 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
18005 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
18009 if (prog->aux->sleepable)
18010 switch (map->map_type) {
18011 case BPF_MAP_TYPE_HASH:
18012 case BPF_MAP_TYPE_LRU_HASH:
18013 case BPF_MAP_TYPE_ARRAY:
18014 case BPF_MAP_TYPE_PERCPU_HASH:
18015 case BPF_MAP_TYPE_PERCPU_ARRAY:
18016 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
18017 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
18018 case BPF_MAP_TYPE_HASH_OF_MAPS:
18019 case BPF_MAP_TYPE_RINGBUF:
18020 case BPF_MAP_TYPE_USER_RINGBUF:
18021 case BPF_MAP_TYPE_INODE_STORAGE:
18022 case BPF_MAP_TYPE_SK_STORAGE:
18023 case BPF_MAP_TYPE_TASK_STORAGE:
18024 case BPF_MAP_TYPE_CGRP_STORAGE:
18025 case BPF_MAP_TYPE_QUEUE:
18026 case BPF_MAP_TYPE_STACK:
18030 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
18037 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
18039 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
18040 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
18043 /* find and rewrite pseudo imm in ld_imm64 instructions:
18045 * 1. if it accesses map FD, replace it with actual map pointer.
18046 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
18048 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
18050 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
18052 struct bpf_insn *insn = env->prog->insnsi;
18053 int insn_cnt = env->prog->len;
18056 err = bpf_prog_calc_tag(env->prog);
18060 for (i = 0; i < insn_cnt; i++, insn++) {
18061 if (BPF_CLASS(insn->code) == BPF_LDX &&
18062 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
18064 verbose(env, "BPF_LDX uses reserved fields\n");
18068 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
18069 struct bpf_insn_aux_data *aux;
18070 struct bpf_map *map;
18075 if (i == insn_cnt - 1 || insn[1].code != 0 ||
18076 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
18077 insn[1].off != 0) {
18078 verbose(env, "invalid bpf_ld_imm64 insn\n");
18082 if (insn[0].src_reg == 0)
18083 /* valid generic load 64-bit imm */
18086 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
18087 aux = &env->insn_aux_data[i];
18088 err = check_pseudo_btf_id(env, insn, aux);
18094 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
18095 aux = &env->insn_aux_data[i];
18096 aux->ptr_type = PTR_TO_FUNC;
18100 /* In final convert_pseudo_ld_imm64() step, this is
18101 * converted into regular 64-bit imm load insn.
18103 switch (insn[0].src_reg) {
18104 case BPF_PSEUDO_MAP_VALUE:
18105 case BPF_PSEUDO_MAP_IDX_VALUE:
18107 case BPF_PSEUDO_MAP_FD:
18108 case BPF_PSEUDO_MAP_IDX:
18109 if (insn[1].imm == 0)
18113 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
18117 switch (insn[0].src_reg) {
18118 case BPF_PSEUDO_MAP_IDX_VALUE:
18119 case BPF_PSEUDO_MAP_IDX:
18120 if (bpfptr_is_null(env->fd_array)) {
18121 verbose(env, "fd_idx without fd_array is invalid\n");
18124 if (copy_from_bpfptr_offset(&fd, env->fd_array,
18125 insn[0].imm * sizeof(fd),
18135 map = __bpf_map_get(f);
18137 verbose(env, "fd %d is not pointing to valid bpf_map\n",
18139 return PTR_ERR(map);
18142 err = check_map_prog_compatibility(env, map, env->prog);
18148 aux = &env->insn_aux_data[i];
18149 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
18150 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
18151 addr = (unsigned long)map;
18153 u32 off = insn[1].imm;
18155 if (off >= BPF_MAX_VAR_OFF) {
18156 verbose(env, "direct value offset of %u is not allowed\n", off);
18161 if (!map->ops->map_direct_value_addr) {
18162 verbose(env, "no direct value access support for this map type\n");
18167 err = map->ops->map_direct_value_addr(map, &addr, off);
18169 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
18170 map->value_size, off);
18175 aux->map_off = off;
18179 insn[0].imm = (u32)addr;
18180 insn[1].imm = addr >> 32;
18182 /* check whether we recorded this map already */
18183 for (j = 0; j < env->used_map_cnt; j++) {
18184 if (env->used_maps[j] == map) {
18185 aux->map_index = j;
18191 if (env->used_map_cnt >= MAX_USED_MAPS) {
18196 if (env->prog->aux->sleepable)
18197 atomic64_inc(&map->sleepable_refcnt);
18198 /* hold the map. If the program is rejected by verifier,
18199 * the map will be released by release_maps() or it
18200 * will be used by the valid program until it's unloaded
18201 * and all maps are released in bpf_free_used_maps()
18205 aux->map_index = env->used_map_cnt;
18206 env->used_maps[env->used_map_cnt++] = map;
18208 if (bpf_map_is_cgroup_storage(map) &&
18209 bpf_cgroup_storage_assign(env->prog->aux, map)) {
18210 verbose(env, "only one cgroup storage of each type is allowed\n");
18222 /* Basic sanity check before we invest more work here. */
18223 if (!bpf_opcode_in_insntable(insn->code)) {
18224 verbose(env, "unknown opcode %02x\n", insn->code);
18229 /* now all pseudo BPF_LD_IMM64 instructions load valid
18230 * 'struct bpf_map *' into a register instead of user map_fd.
18231 * These pointers will be used later by verifier to validate map access.
18236 /* drop refcnt of maps used by the rejected program */
18237 static void release_maps(struct bpf_verifier_env *env)
18239 __bpf_free_used_maps(env->prog->aux, env->used_maps,
18240 env->used_map_cnt);
18243 /* drop refcnt of maps used by the rejected program */
18244 static void release_btfs(struct bpf_verifier_env *env)
18246 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
18247 env->used_btf_cnt);
18250 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
18251 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
18253 struct bpf_insn *insn = env->prog->insnsi;
18254 int insn_cnt = env->prog->len;
18257 for (i = 0; i < insn_cnt; i++, insn++) {
18258 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18260 if (insn->src_reg == BPF_PSEUDO_FUNC)
18266 /* single env->prog->insni[off] instruction was replaced with the range
18267 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
18268 * [0, off) and [off, end) to new locations, so the patched range stays zero
18270 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
18271 struct bpf_insn_aux_data *new_data,
18272 struct bpf_prog *new_prog, u32 off, u32 cnt)
18274 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
18275 struct bpf_insn *insn = new_prog->insnsi;
18276 u32 old_seen = old_data[off].seen;
18280 /* aux info at OFF always needs adjustment, no matter fast path
18281 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
18282 * original insn at old prog.
18284 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
18288 prog_len = new_prog->len;
18290 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
18291 memcpy(new_data + off + cnt - 1, old_data + off,
18292 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
18293 for (i = off; i < off + cnt - 1; i++) {
18294 /* Expand insni[off]'s seen count to the patched range. */
18295 new_data[i].seen = old_seen;
18296 new_data[i].zext_dst = insn_has_def32(env, insn + i);
18298 env->insn_aux_data = new_data;
18302 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
18308 /* NOTE: fake 'exit' subprog should be updated as well. */
18309 for (i = 0; i <= env->subprog_cnt; i++) {
18310 if (env->subprog_info[i].start <= off)
18312 env->subprog_info[i].start += len - 1;
18316 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
18318 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
18319 int i, sz = prog->aux->size_poke_tab;
18320 struct bpf_jit_poke_descriptor *desc;
18322 for (i = 0; i < sz; i++) {
18324 if (desc->insn_idx <= off)
18326 desc->insn_idx += len - 1;
18330 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
18331 const struct bpf_insn *patch, u32 len)
18333 struct bpf_prog *new_prog;
18334 struct bpf_insn_aux_data *new_data = NULL;
18337 new_data = vzalloc(array_size(env->prog->len + len - 1,
18338 sizeof(struct bpf_insn_aux_data)));
18343 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
18344 if (IS_ERR(new_prog)) {
18345 if (PTR_ERR(new_prog) == -ERANGE)
18347 "insn %d cannot be patched due to 16-bit range\n",
18348 env->insn_aux_data[off].orig_idx);
18352 adjust_insn_aux_data(env, new_data, new_prog, off, len);
18353 adjust_subprog_starts(env, off, len);
18354 adjust_poke_descs(new_prog, off, len);
18358 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
18363 /* find first prog starting at or after off (first to remove) */
18364 for (i = 0; i < env->subprog_cnt; i++)
18365 if (env->subprog_info[i].start >= off)
18367 /* find first prog starting at or after off + cnt (first to stay) */
18368 for (j = i; j < env->subprog_cnt; j++)
18369 if (env->subprog_info[j].start >= off + cnt)
18371 /* if j doesn't start exactly at off + cnt, we are just removing
18372 * the front of previous prog
18374 if (env->subprog_info[j].start != off + cnt)
18378 struct bpf_prog_aux *aux = env->prog->aux;
18381 /* move fake 'exit' subprog as well */
18382 move = env->subprog_cnt + 1 - j;
18384 memmove(env->subprog_info + i,
18385 env->subprog_info + j,
18386 sizeof(*env->subprog_info) * move);
18387 env->subprog_cnt -= j - i;
18389 /* remove func_info */
18390 if (aux->func_info) {
18391 move = aux->func_info_cnt - j;
18393 memmove(aux->func_info + i,
18394 aux->func_info + j,
18395 sizeof(*aux->func_info) * move);
18396 aux->func_info_cnt -= j - i;
18397 /* func_info->insn_off is set after all code rewrites,
18398 * in adjust_btf_func() - no need to adjust
18402 /* convert i from "first prog to remove" to "first to adjust" */
18403 if (env->subprog_info[i].start == off)
18407 /* update fake 'exit' subprog as well */
18408 for (; i <= env->subprog_cnt; i++)
18409 env->subprog_info[i].start -= cnt;
18414 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18417 struct bpf_prog *prog = env->prog;
18418 u32 i, l_off, l_cnt, nr_linfo;
18419 struct bpf_line_info *linfo;
18421 nr_linfo = prog->aux->nr_linfo;
18425 linfo = prog->aux->linfo;
18427 /* find first line info to remove, count lines to be removed */
18428 for (i = 0; i < nr_linfo; i++)
18429 if (linfo[i].insn_off >= off)
18434 for (; i < nr_linfo; i++)
18435 if (linfo[i].insn_off < off + cnt)
18440 /* First live insn doesn't match first live linfo, it needs to "inherit"
18441 * last removed linfo. prog is already modified, so prog->len == off
18442 * means no live instructions after (tail of the program was removed).
18444 if (prog->len != off && l_cnt &&
18445 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18447 linfo[--i].insn_off = off + cnt;
18450 /* remove the line info which refer to the removed instructions */
18452 memmove(linfo + l_off, linfo + i,
18453 sizeof(*linfo) * (nr_linfo - i));
18455 prog->aux->nr_linfo -= l_cnt;
18456 nr_linfo = prog->aux->nr_linfo;
18459 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
18460 for (i = l_off; i < nr_linfo; i++)
18461 linfo[i].insn_off -= cnt;
18463 /* fix up all subprogs (incl. 'exit') which start >= off */
18464 for (i = 0; i <= env->subprog_cnt; i++)
18465 if (env->subprog_info[i].linfo_idx > l_off) {
18466 /* program may have started in the removed region but
18467 * may not be fully removed
18469 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18470 env->subprog_info[i].linfo_idx -= l_cnt;
18472 env->subprog_info[i].linfo_idx = l_off;
18478 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18480 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18481 unsigned int orig_prog_len = env->prog->len;
18484 if (bpf_prog_is_offloaded(env->prog->aux))
18485 bpf_prog_offload_remove_insns(env, off, cnt);
18487 err = bpf_remove_insns(env->prog, off, cnt);
18491 err = adjust_subprog_starts_after_remove(env, off, cnt);
18495 err = bpf_adj_linfo_after_remove(env, off, cnt);
18499 memmove(aux_data + off, aux_data + off + cnt,
18500 sizeof(*aux_data) * (orig_prog_len - off - cnt));
18505 /* The verifier does more data flow analysis than llvm and will not
18506 * explore branches that are dead at run time. Malicious programs can
18507 * have dead code too. Therefore replace all dead at-run-time code
18510 * Just nops are not optimal, e.g. if they would sit at the end of the
18511 * program and through another bug we would manage to jump there, then
18512 * we'd execute beyond program memory otherwise. Returning exception
18513 * code also wouldn't work since we can have subprogs where the dead
18514 * code could be located.
18516 static void sanitize_dead_code(struct bpf_verifier_env *env)
18518 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18519 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18520 struct bpf_insn *insn = env->prog->insnsi;
18521 const int insn_cnt = env->prog->len;
18524 for (i = 0; i < insn_cnt; i++) {
18525 if (aux_data[i].seen)
18527 memcpy(insn + i, &trap, sizeof(trap));
18528 aux_data[i].zext_dst = false;
18532 static bool insn_is_cond_jump(u8 code)
18537 if (BPF_CLASS(code) == BPF_JMP32)
18538 return op != BPF_JA;
18540 if (BPF_CLASS(code) != BPF_JMP)
18543 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18546 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18548 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18549 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18550 struct bpf_insn *insn = env->prog->insnsi;
18551 const int insn_cnt = env->prog->len;
18554 for (i = 0; i < insn_cnt; i++, insn++) {
18555 if (!insn_is_cond_jump(insn->code))
18558 if (!aux_data[i + 1].seen)
18559 ja.off = insn->off;
18560 else if (!aux_data[i + 1 + insn->off].seen)
18565 if (bpf_prog_is_offloaded(env->prog->aux))
18566 bpf_prog_offload_replace_insn(env, i, &ja);
18568 memcpy(insn, &ja, sizeof(ja));
18572 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18574 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18575 int insn_cnt = env->prog->len;
18578 for (i = 0; i < insn_cnt; i++) {
18582 while (i + j < insn_cnt && !aux_data[i + j].seen)
18587 err = verifier_remove_insns(env, i, j);
18590 insn_cnt = env->prog->len;
18596 static int opt_remove_nops(struct bpf_verifier_env *env)
18598 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18599 struct bpf_insn *insn = env->prog->insnsi;
18600 int insn_cnt = env->prog->len;
18603 for (i = 0; i < insn_cnt; i++) {
18604 if (memcmp(&insn[i], &ja, sizeof(ja)))
18607 err = verifier_remove_insns(env, i, 1);
18617 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18618 const union bpf_attr *attr)
18620 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18621 struct bpf_insn_aux_data *aux = env->insn_aux_data;
18622 int i, patch_len, delta = 0, len = env->prog->len;
18623 struct bpf_insn *insns = env->prog->insnsi;
18624 struct bpf_prog *new_prog;
18627 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18628 zext_patch[1] = BPF_ZEXT_REG(0);
18629 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18630 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18631 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18632 for (i = 0; i < len; i++) {
18633 int adj_idx = i + delta;
18634 struct bpf_insn insn;
18637 insn = insns[adj_idx];
18638 load_reg = insn_def_regno(&insn);
18639 if (!aux[adj_idx].zext_dst) {
18647 class = BPF_CLASS(code);
18648 if (load_reg == -1)
18651 /* NOTE: arg "reg" (the fourth one) is only used for
18652 * BPF_STX + SRC_OP, so it is safe to pass NULL
18655 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18656 if (class == BPF_LD &&
18657 BPF_MODE(code) == BPF_IMM)
18662 /* ctx load could be transformed into wider load. */
18663 if (class == BPF_LDX &&
18664 aux[adj_idx].ptr_type == PTR_TO_CTX)
18667 imm_rnd = get_random_u32();
18668 rnd_hi32_patch[0] = insn;
18669 rnd_hi32_patch[1].imm = imm_rnd;
18670 rnd_hi32_patch[3].dst_reg = load_reg;
18671 patch = rnd_hi32_patch;
18673 goto apply_patch_buffer;
18676 /* Add in an zero-extend instruction if a) the JIT has requested
18677 * it or b) it's a CMPXCHG.
18679 * The latter is because: BPF_CMPXCHG always loads a value into
18680 * R0, therefore always zero-extends. However some archs'
18681 * equivalent instruction only does this load when the
18682 * comparison is successful. This detail of CMPXCHG is
18683 * orthogonal to the general zero-extension behaviour of the
18684 * CPU, so it's treated independently of bpf_jit_needs_zext.
18686 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18689 /* Zero-extension is done by the caller. */
18690 if (bpf_pseudo_kfunc_call(&insn))
18693 if (WARN_ON(load_reg == -1)) {
18694 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18698 zext_patch[0] = insn;
18699 zext_patch[1].dst_reg = load_reg;
18700 zext_patch[1].src_reg = load_reg;
18701 patch = zext_patch;
18703 apply_patch_buffer:
18704 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18707 env->prog = new_prog;
18708 insns = new_prog->insnsi;
18709 aux = env->insn_aux_data;
18710 delta += patch_len - 1;
18716 /* convert load instructions that access fields of a context type into a
18717 * sequence of instructions that access fields of the underlying structure:
18718 * struct __sk_buff -> struct sk_buff
18719 * struct bpf_sock_ops -> struct sock
18721 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18723 const struct bpf_verifier_ops *ops = env->ops;
18724 int i, cnt, size, ctx_field_size, delta = 0;
18725 const int insn_cnt = env->prog->len;
18726 struct bpf_insn insn_buf[16], *insn;
18727 u32 target_size, size_default, off;
18728 struct bpf_prog *new_prog;
18729 enum bpf_access_type type;
18730 bool is_narrower_load;
18732 if (ops->gen_prologue || env->seen_direct_write) {
18733 if (!ops->gen_prologue) {
18734 verbose(env, "bpf verifier is misconfigured\n");
18737 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18739 if (cnt >= ARRAY_SIZE(insn_buf)) {
18740 verbose(env, "bpf verifier is misconfigured\n");
18743 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18747 env->prog = new_prog;
18752 if (bpf_prog_is_offloaded(env->prog->aux))
18755 insn = env->prog->insnsi + delta;
18757 for (i = 0; i < insn_cnt; i++, insn++) {
18758 bpf_convert_ctx_access_t convert_ctx_access;
18761 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18762 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18763 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18764 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18765 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18766 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18767 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18769 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18770 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18771 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18772 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18773 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18774 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18775 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18776 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18782 if (type == BPF_WRITE &&
18783 env->insn_aux_data[i + delta].sanitize_stack_spill) {
18784 struct bpf_insn patch[] = {
18789 cnt = ARRAY_SIZE(patch);
18790 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18795 env->prog = new_prog;
18796 insn = new_prog->insnsi + i + delta;
18800 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18802 if (!ops->convert_ctx_access)
18804 convert_ctx_access = ops->convert_ctx_access;
18806 case PTR_TO_SOCKET:
18807 case PTR_TO_SOCK_COMMON:
18808 convert_ctx_access = bpf_sock_convert_ctx_access;
18810 case PTR_TO_TCP_SOCK:
18811 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18813 case PTR_TO_XDP_SOCK:
18814 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18816 case PTR_TO_BTF_ID:
18817 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18818 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18819 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18820 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18821 * any faults for loads into such types. BPF_WRITE is disallowed
18824 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18825 if (type == BPF_READ) {
18826 if (BPF_MODE(insn->code) == BPF_MEM)
18827 insn->code = BPF_LDX | BPF_PROBE_MEM |
18828 BPF_SIZE((insn)->code);
18830 insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18831 BPF_SIZE((insn)->code);
18832 env->prog->aux->num_exentries++;
18839 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18840 size = BPF_LDST_BYTES(insn);
18841 mode = BPF_MODE(insn->code);
18843 /* If the read access is a narrower load of the field,
18844 * convert to a 4/8-byte load, to minimum program type specific
18845 * convert_ctx_access changes. If conversion is successful,
18846 * we will apply proper mask to the result.
18848 is_narrower_load = size < ctx_field_size;
18849 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18851 if (is_narrower_load) {
18854 if (type == BPF_WRITE) {
18855 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18860 if (ctx_field_size == 4)
18862 else if (ctx_field_size == 8)
18863 size_code = BPF_DW;
18865 insn->off = off & ~(size_default - 1);
18866 insn->code = BPF_LDX | BPF_MEM | size_code;
18870 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18872 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18873 (ctx_field_size && !target_size)) {
18874 verbose(env, "bpf verifier is misconfigured\n");
18878 if (is_narrower_load && size < target_size) {
18879 u8 shift = bpf_ctx_narrow_access_offset(
18880 off, size, size_default) * 8;
18881 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18882 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18885 if (ctx_field_size <= 4) {
18887 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18890 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18891 (1 << size * 8) - 1);
18894 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18897 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18898 (1ULL << size * 8) - 1);
18901 if (mode == BPF_MEMSX)
18902 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18903 insn->dst_reg, insn->dst_reg,
18906 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18912 /* keep walking new program and skip insns we just inserted */
18913 env->prog = new_prog;
18914 insn = new_prog->insnsi + i + delta;
18920 static int jit_subprogs(struct bpf_verifier_env *env)
18922 struct bpf_prog *prog = env->prog, **func, *tmp;
18923 int i, j, subprog_start, subprog_end = 0, len, subprog;
18924 struct bpf_map *map_ptr;
18925 struct bpf_insn *insn;
18926 void *old_bpf_func;
18927 int err, num_exentries;
18929 if (env->subprog_cnt <= 1)
18932 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18933 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18936 /* Upon error here we cannot fall back to interpreter but
18937 * need a hard reject of the program. Thus -EFAULT is
18938 * propagated in any case.
18940 subprog = find_subprog(env, i + insn->imm + 1);
18942 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18943 i + insn->imm + 1);
18946 /* temporarily remember subprog id inside insn instead of
18947 * aux_data, since next loop will split up all insns into funcs
18949 insn->off = subprog;
18950 /* remember original imm in case JIT fails and fallback
18951 * to interpreter will be needed
18953 env->insn_aux_data[i].call_imm = insn->imm;
18954 /* point imm to __bpf_call_base+1 from JITs point of view */
18956 if (bpf_pseudo_func(insn))
18957 /* jit (e.g. x86_64) may emit fewer instructions
18958 * if it learns a u32 imm is the same as a u64 imm.
18959 * Force a non zero here.
18964 err = bpf_prog_alloc_jited_linfo(prog);
18966 goto out_undo_insn;
18969 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18971 goto out_undo_insn;
18973 for (i = 0; i < env->subprog_cnt; i++) {
18974 subprog_start = subprog_end;
18975 subprog_end = env->subprog_info[i + 1].start;
18977 len = subprog_end - subprog_start;
18978 /* bpf_prog_run() doesn't call subprogs directly,
18979 * hence main prog stats include the runtime of subprogs.
18980 * subprogs don't have IDs and not reachable via prog_get_next_id
18981 * func[i]->stats will never be accessed and stays NULL
18983 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18986 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18987 len * sizeof(struct bpf_insn));
18988 func[i]->type = prog->type;
18989 func[i]->len = len;
18990 if (bpf_prog_calc_tag(func[i]))
18992 func[i]->is_func = 1;
18993 func[i]->aux->func_idx = i;
18994 /* Below members will be freed only at prog->aux */
18995 func[i]->aux->btf = prog->aux->btf;
18996 func[i]->aux->func_info = prog->aux->func_info;
18997 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18998 func[i]->aux->poke_tab = prog->aux->poke_tab;
18999 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
19001 for (j = 0; j < prog->aux->size_poke_tab; j++) {
19002 struct bpf_jit_poke_descriptor *poke;
19004 poke = &prog->aux->poke_tab[j];
19005 if (poke->insn_idx < subprog_end &&
19006 poke->insn_idx >= subprog_start)
19007 poke->aux = func[i]->aux;
19010 func[i]->aux->name[0] = 'F';
19011 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
19012 func[i]->jit_requested = 1;
19013 func[i]->blinding_requested = prog->blinding_requested;
19014 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
19015 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
19016 func[i]->aux->linfo = prog->aux->linfo;
19017 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
19018 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
19019 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
19021 insn = func[i]->insnsi;
19022 for (j = 0; j < func[i]->len; j++, insn++) {
19023 if (BPF_CLASS(insn->code) == BPF_LDX &&
19024 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
19025 BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
19028 func[i]->aux->num_exentries = num_exentries;
19029 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
19030 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
19032 func[i]->aux->exception_boundary = env->seen_exception;
19033 func[i] = bpf_int_jit_compile(func[i]);
19034 if (!func[i]->jited) {
19041 /* at this point all bpf functions were successfully JITed
19042 * now populate all bpf_calls with correct addresses and
19043 * run last pass of JIT
19045 for (i = 0; i < env->subprog_cnt; i++) {
19046 insn = func[i]->insnsi;
19047 for (j = 0; j < func[i]->len; j++, insn++) {
19048 if (bpf_pseudo_func(insn)) {
19049 subprog = insn->off;
19050 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
19051 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
19054 if (!bpf_pseudo_call(insn))
19056 subprog = insn->off;
19057 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
19060 /* we use the aux data to keep a list of the start addresses
19061 * of the JITed images for each function in the program
19063 * for some architectures, such as powerpc64, the imm field
19064 * might not be large enough to hold the offset of the start
19065 * address of the callee's JITed image from __bpf_call_base
19067 * in such cases, we can lookup the start address of a callee
19068 * by using its subprog id, available from the off field of
19069 * the call instruction, as an index for this list
19071 func[i]->aux->func = func;
19072 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19073 func[i]->aux->real_func_cnt = env->subprog_cnt;
19075 for (i = 0; i < env->subprog_cnt; i++) {
19076 old_bpf_func = func[i]->bpf_func;
19077 tmp = bpf_int_jit_compile(func[i]);
19078 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
19079 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
19086 /* finally lock prog and jit images for all functions and
19087 * populate kallsysm. Begin at the first subprogram, since
19088 * bpf_prog_load will add the kallsyms for the main program.
19090 for (i = 1; i < env->subprog_cnt; i++) {
19091 bpf_prog_lock_ro(func[i]);
19092 bpf_prog_kallsyms_add(func[i]);
19095 /* Last step: make now unused interpreter insns from main
19096 * prog consistent for later dump requests, so they can
19097 * later look the same as if they were interpreted only.
19099 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19100 if (bpf_pseudo_func(insn)) {
19101 insn[0].imm = env->insn_aux_data[i].call_imm;
19102 insn[1].imm = insn->off;
19106 if (!bpf_pseudo_call(insn))
19108 insn->off = env->insn_aux_data[i].call_imm;
19109 subprog = find_subprog(env, i + insn->off + 1);
19110 insn->imm = subprog;
19114 prog->bpf_func = func[0]->bpf_func;
19115 prog->jited_len = func[0]->jited_len;
19116 prog->aux->extable = func[0]->aux->extable;
19117 prog->aux->num_exentries = func[0]->aux->num_exentries;
19118 prog->aux->func = func;
19119 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19120 prog->aux->real_func_cnt = env->subprog_cnt;
19121 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
19122 prog->aux->exception_boundary = func[0]->aux->exception_boundary;
19123 bpf_prog_jit_attempt_done(prog);
19126 /* We failed JIT'ing, so at this point we need to unregister poke
19127 * descriptors from subprogs, so that kernel is not attempting to
19128 * patch it anymore as we're freeing the subprog JIT memory.
19130 for (i = 0; i < prog->aux->size_poke_tab; i++) {
19131 map_ptr = prog->aux->poke_tab[i].tail_call.map;
19132 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
19134 /* At this point we're guaranteed that poke descriptors are not
19135 * live anymore. We can just unlink its descriptor table as it's
19136 * released with the main prog.
19138 for (i = 0; i < env->subprog_cnt; i++) {
19141 func[i]->aux->poke_tab = NULL;
19142 bpf_jit_free(func[i]);
19146 /* cleanup main prog to be interpreted */
19147 prog->jit_requested = 0;
19148 prog->blinding_requested = 0;
19149 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19150 if (!bpf_pseudo_call(insn))
19153 insn->imm = env->insn_aux_data[i].call_imm;
19155 bpf_prog_jit_attempt_done(prog);
19159 static int fixup_call_args(struct bpf_verifier_env *env)
19161 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19162 struct bpf_prog *prog = env->prog;
19163 struct bpf_insn *insn = prog->insnsi;
19164 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
19169 if (env->prog->jit_requested &&
19170 !bpf_prog_is_offloaded(env->prog->aux)) {
19171 err = jit_subprogs(env);
19174 if (err == -EFAULT)
19177 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19178 if (has_kfunc_call) {
19179 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
19182 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
19183 /* When JIT fails the progs with bpf2bpf calls and tail_calls
19184 * have to be rejected, since interpreter doesn't support them yet.
19186 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
19189 for (i = 0; i < prog->len; i++, insn++) {
19190 if (bpf_pseudo_func(insn)) {
19191 /* When JIT fails the progs with callback calls
19192 * have to be rejected, since interpreter doesn't support them yet.
19194 verbose(env, "callbacks are not allowed in non-JITed programs\n");
19198 if (!bpf_pseudo_call(insn))
19200 depth = get_callee_stack_depth(env, insn, i);
19203 bpf_patch_call_args(insn, depth);
19210 /* replace a generic kfunc with a specialized version if necessary */
19211 static void specialize_kfunc(struct bpf_verifier_env *env,
19212 u32 func_id, u16 offset, unsigned long *addr)
19214 struct bpf_prog *prog = env->prog;
19215 bool seen_direct_write;
19219 if (bpf_dev_bound_kfunc_id(func_id)) {
19220 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19222 *addr = (unsigned long)xdp_kfunc;
19225 /* fallback to default kfunc when not supported by netdev */
19231 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19232 seen_direct_write = env->seen_direct_write;
19233 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19236 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19238 /* restore env->seen_direct_write to its original value, since
19239 * may_access_direct_pkt_data mutates it
19241 env->seen_direct_write = seen_direct_write;
19245 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19246 u16 struct_meta_reg,
19247 u16 node_offset_reg,
19248 struct bpf_insn *insn,
19249 struct bpf_insn *insn_buf,
19252 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19253 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19255 insn_buf[0] = addr[0];
19256 insn_buf[1] = addr[1];
19257 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19258 insn_buf[3] = *insn;
19262 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19263 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
19265 const struct bpf_kfunc_desc *desc;
19268 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19274 /* insn->imm has the btf func_id. Replace it with an offset relative to
19275 * __bpf_call_base, unless the JIT needs to call functions that are
19276 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
19278 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
19280 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
19285 if (!bpf_jit_supports_far_kfunc_call())
19286 insn->imm = BPF_CALL_IMM(desc->addr);
19289 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
19290 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
19291 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19292 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19293 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
19295 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
19296 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19301 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19302 insn_buf[1] = addr[0];
19303 insn_buf[2] = addr[1];
19304 insn_buf[3] = *insn;
19306 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
19307 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
19308 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
19309 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19310 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19312 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
19313 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19318 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
19319 !kptr_struct_meta) {
19320 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19325 insn_buf[0] = addr[0];
19326 insn_buf[1] = addr[1];
19327 insn_buf[2] = *insn;
19329 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
19330 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
19331 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19332 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19333 int struct_meta_reg = BPF_REG_3;
19334 int node_offset_reg = BPF_REG_4;
19336 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
19337 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19338 struct_meta_reg = BPF_REG_4;
19339 node_offset_reg = BPF_REG_5;
19342 if (!kptr_struct_meta) {
19343 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19348 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19349 node_offset_reg, insn, insn_buf, cnt);
19350 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19351 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19352 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19358 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
19359 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
19361 struct bpf_subprog_info *info = env->subprog_info;
19362 int cnt = env->subprog_cnt;
19363 struct bpf_prog *prog;
19365 /* We only reserve one slot for hidden subprogs in subprog_info. */
19366 if (env->hidden_subprog_cnt) {
19367 verbose(env, "verifier internal error: only one hidden subprog supported\n");
19370 /* We're not patching any existing instruction, just appending the new
19371 * ones for the hidden subprog. Hence all of the adjustment operations
19372 * in bpf_patch_insn_data are no-ops.
19374 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
19378 info[cnt + 1].start = info[cnt].start;
19379 info[cnt].start = prog->len - len + 1;
19380 env->subprog_cnt++;
19381 env->hidden_subprog_cnt++;
19385 /* Do various post-verification rewrites in a single program pass.
19386 * These rewrites simplify JIT and interpreter implementations.
19388 static int do_misc_fixups(struct bpf_verifier_env *env)
19390 struct bpf_prog *prog = env->prog;
19391 enum bpf_attach_type eatype = prog->expected_attach_type;
19392 enum bpf_prog_type prog_type = resolve_prog_type(prog);
19393 struct bpf_insn *insn = prog->insnsi;
19394 const struct bpf_func_proto *fn;
19395 const int insn_cnt = prog->len;
19396 const struct bpf_map_ops *ops;
19397 struct bpf_insn_aux_data *aux;
19398 struct bpf_insn insn_buf[16];
19399 struct bpf_prog *new_prog;
19400 struct bpf_map *map_ptr;
19401 int i, ret, cnt, delta = 0;
19403 if (env->seen_exception && !env->exception_callback_subprog) {
19404 struct bpf_insn patch[] = {
19405 env->prog->insnsi[insn_cnt - 1],
19406 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
19410 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
19414 insn = prog->insnsi;
19416 env->exception_callback_subprog = env->subprog_cnt - 1;
19417 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */
19418 mark_subprog_exc_cb(env, env->exception_callback_subprog);
19421 for (i = 0; i < insn_cnt; i++, insn++) {
19422 /* Make divide-by-zero exceptions impossible. */
19423 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
19424 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
19425 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
19426 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
19427 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
19428 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
19429 struct bpf_insn *patchlet;
19430 struct bpf_insn chk_and_div[] = {
19431 /* [R,W]x div 0 -> 0 */
19432 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19433 BPF_JNE | BPF_K, insn->src_reg,
19435 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
19436 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19439 struct bpf_insn chk_and_mod[] = {
19440 /* [R,W]x mod 0 -> [R,W]x */
19441 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19442 BPF_JEQ | BPF_K, insn->src_reg,
19443 0, 1 + (is64 ? 0 : 1), 0),
19445 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19446 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
19449 patchlet = isdiv ? chk_and_div : chk_and_mod;
19450 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
19451 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
19453 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
19458 env->prog = prog = new_prog;
19459 insn = new_prog->insnsi + i + delta;
19463 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
19464 if (BPF_CLASS(insn->code) == BPF_LD &&
19465 (BPF_MODE(insn->code) == BPF_ABS ||
19466 BPF_MODE(insn->code) == BPF_IND)) {
19467 cnt = env->ops->gen_ld_abs(insn, insn_buf);
19468 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19469 verbose(env, "bpf verifier is misconfigured\n");
19473 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19478 env->prog = prog = new_prog;
19479 insn = new_prog->insnsi + i + delta;
19483 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
19484 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
19485 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
19486 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
19487 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
19488 struct bpf_insn *patch = &insn_buf[0];
19489 bool issrc, isneg, isimm;
19492 aux = &env->insn_aux_data[i + delta];
19493 if (!aux->alu_state ||
19494 aux->alu_state == BPF_ALU_NON_POINTER)
19497 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
19498 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
19499 BPF_ALU_SANITIZE_SRC;
19500 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
19502 off_reg = issrc ? insn->src_reg : insn->dst_reg;
19504 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19507 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19508 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19509 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
19510 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
19511 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
19512 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
19513 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
19516 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
19517 insn->src_reg = BPF_REG_AX;
19519 insn->code = insn->code == code_add ?
19520 code_sub : code_add;
19522 if (issrc && isneg && !isimm)
19523 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19524 cnt = patch - insn_buf;
19526 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19531 env->prog = prog = new_prog;
19532 insn = new_prog->insnsi + i + delta;
19536 if (insn->code != (BPF_JMP | BPF_CALL))
19538 if (insn->src_reg == BPF_PSEUDO_CALL)
19540 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19541 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19547 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19552 env->prog = prog = new_prog;
19553 insn = new_prog->insnsi + i + delta;
19557 if (insn->imm == BPF_FUNC_get_route_realm)
19558 prog->dst_needed = 1;
19559 if (insn->imm == BPF_FUNC_get_prandom_u32)
19560 bpf_user_rnd_init_once();
19561 if (insn->imm == BPF_FUNC_override_return)
19562 prog->kprobe_override = 1;
19563 if (insn->imm == BPF_FUNC_tail_call) {
19564 /* If we tail call into other programs, we
19565 * cannot make any assumptions since they can
19566 * be replaced dynamically during runtime in
19567 * the program array.
19569 prog->cb_access = 1;
19570 if (!allow_tail_call_in_subprogs(env))
19571 prog->aux->stack_depth = MAX_BPF_STACK;
19572 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19574 /* mark bpf_tail_call as different opcode to avoid
19575 * conditional branch in the interpreter for every normal
19576 * call and to prevent accidental JITing by JIT compiler
19577 * that doesn't support bpf_tail_call yet
19580 insn->code = BPF_JMP | BPF_TAIL_CALL;
19582 aux = &env->insn_aux_data[i + delta];
19583 if (env->bpf_capable && !prog->blinding_requested &&
19584 prog->jit_requested &&
19585 !bpf_map_key_poisoned(aux) &&
19586 !bpf_map_ptr_poisoned(aux) &&
19587 !bpf_map_ptr_unpriv(aux)) {
19588 struct bpf_jit_poke_descriptor desc = {
19589 .reason = BPF_POKE_REASON_TAIL_CALL,
19590 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19591 .tail_call.key = bpf_map_key_immediate(aux),
19592 .insn_idx = i + delta,
19595 ret = bpf_jit_add_poke_descriptor(prog, &desc);
19597 verbose(env, "adding tail call poke descriptor failed\n");
19601 insn->imm = ret + 1;
19605 if (!bpf_map_ptr_unpriv(aux))
19608 /* instead of changing every JIT dealing with tail_call
19609 * emit two extra insns:
19610 * if (index >= max_entries) goto out;
19611 * index &= array->index_mask;
19612 * to avoid out-of-bounds cpu speculation
19614 if (bpf_map_ptr_poisoned(aux)) {
19615 verbose(env, "tail_call abusing map_ptr\n");
19619 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19620 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19621 map_ptr->max_entries, 2);
19622 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19623 container_of(map_ptr,
19626 insn_buf[2] = *insn;
19628 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19633 env->prog = prog = new_prog;
19634 insn = new_prog->insnsi + i + delta;
19638 if (insn->imm == BPF_FUNC_timer_set_callback) {
19639 /* The verifier will process callback_fn as many times as necessary
19640 * with different maps and the register states prepared by
19641 * set_timer_callback_state will be accurate.
19643 * The following use case is valid:
19644 * map1 is shared by prog1, prog2, prog3.
19645 * prog1 calls bpf_timer_init for some map1 elements
19646 * prog2 calls bpf_timer_set_callback for some map1 elements.
19647 * Those that were not bpf_timer_init-ed will return -EINVAL.
19648 * prog3 calls bpf_timer_start for some map1 elements.
19649 * Those that were not both bpf_timer_init-ed and
19650 * bpf_timer_set_callback-ed will return -EINVAL.
19652 struct bpf_insn ld_addrs[2] = {
19653 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19656 insn_buf[0] = ld_addrs[0];
19657 insn_buf[1] = ld_addrs[1];
19658 insn_buf[2] = *insn;
19661 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19666 env->prog = prog = new_prog;
19667 insn = new_prog->insnsi + i + delta;
19668 goto patch_call_imm;
19671 if (is_storage_get_function(insn->imm)) {
19672 if (!env->prog->aux->sleepable ||
19673 env->insn_aux_data[i + delta].storage_get_func_atomic)
19674 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19676 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19677 insn_buf[1] = *insn;
19680 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19685 env->prog = prog = new_prog;
19686 insn = new_prog->insnsi + i + delta;
19687 goto patch_call_imm;
19690 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
19691 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
19692 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
19693 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
19695 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
19696 insn_buf[1] = *insn;
19699 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19704 env->prog = prog = new_prog;
19705 insn = new_prog->insnsi + i + delta;
19706 goto patch_call_imm;
19709 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19710 * and other inlining handlers are currently limited to 64 bit
19713 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19714 (insn->imm == BPF_FUNC_map_lookup_elem ||
19715 insn->imm == BPF_FUNC_map_update_elem ||
19716 insn->imm == BPF_FUNC_map_delete_elem ||
19717 insn->imm == BPF_FUNC_map_push_elem ||
19718 insn->imm == BPF_FUNC_map_pop_elem ||
19719 insn->imm == BPF_FUNC_map_peek_elem ||
19720 insn->imm == BPF_FUNC_redirect_map ||
19721 insn->imm == BPF_FUNC_for_each_map_elem ||
19722 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19723 aux = &env->insn_aux_data[i + delta];
19724 if (bpf_map_ptr_poisoned(aux))
19725 goto patch_call_imm;
19727 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19728 ops = map_ptr->ops;
19729 if (insn->imm == BPF_FUNC_map_lookup_elem &&
19730 ops->map_gen_lookup) {
19731 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19732 if (cnt == -EOPNOTSUPP)
19733 goto patch_map_ops_generic;
19734 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19735 verbose(env, "bpf verifier is misconfigured\n");
19739 new_prog = bpf_patch_insn_data(env, i + delta,
19745 env->prog = prog = new_prog;
19746 insn = new_prog->insnsi + i + delta;
19750 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19751 (void *(*)(struct bpf_map *map, void *key))NULL));
19752 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19753 (long (*)(struct bpf_map *map, void *key))NULL));
19754 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19755 (long (*)(struct bpf_map *map, void *key, void *value,
19757 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19758 (long (*)(struct bpf_map *map, void *value,
19760 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19761 (long (*)(struct bpf_map *map, void *value))NULL));
19762 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19763 (long (*)(struct bpf_map *map, void *value))NULL));
19764 BUILD_BUG_ON(!__same_type(ops->map_redirect,
19765 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19766 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19767 (long (*)(struct bpf_map *map,
19768 bpf_callback_t callback_fn,
19769 void *callback_ctx,
19771 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19772 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19774 patch_map_ops_generic:
19775 switch (insn->imm) {
19776 case BPF_FUNC_map_lookup_elem:
19777 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19779 case BPF_FUNC_map_update_elem:
19780 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19782 case BPF_FUNC_map_delete_elem:
19783 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19785 case BPF_FUNC_map_push_elem:
19786 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19788 case BPF_FUNC_map_pop_elem:
19789 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19791 case BPF_FUNC_map_peek_elem:
19792 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19794 case BPF_FUNC_redirect_map:
19795 insn->imm = BPF_CALL_IMM(ops->map_redirect);
19797 case BPF_FUNC_for_each_map_elem:
19798 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19800 case BPF_FUNC_map_lookup_percpu_elem:
19801 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19805 goto patch_call_imm;
19808 /* Implement bpf_jiffies64 inline. */
19809 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19810 insn->imm == BPF_FUNC_jiffies64) {
19811 struct bpf_insn ld_jiffies_addr[2] = {
19812 BPF_LD_IMM64(BPF_REG_0,
19813 (unsigned long)&jiffies),
19816 insn_buf[0] = ld_jiffies_addr[0];
19817 insn_buf[1] = ld_jiffies_addr[1];
19818 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19822 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19828 env->prog = prog = new_prog;
19829 insn = new_prog->insnsi + i + delta;
19833 /* Implement bpf_get_func_arg inline. */
19834 if (prog_type == BPF_PROG_TYPE_TRACING &&
19835 insn->imm == BPF_FUNC_get_func_arg) {
19836 /* Load nr_args from ctx - 8 */
19837 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19838 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19839 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19840 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19841 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19842 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19843 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19844 insn_buf[7] = BPF_JMP_A(1);
19845 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19848 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19853 env->prog = prog = new_prog;
19854 insn = new_prog->insnsi + i + delta;
19858 /* Implement bpf_get_func_ret inline. */
19859 if (prog_type == BPF_PROG_TYPE_TRACING &&
19860 insn->imm == BPF_FUNC_get_func_ret) {
19861 if (eatype == BPF_TRACE_FEXIT ||
19862 eatype == BPF_MODIFY_RETURN) {
19863 /* Load nr_args from ctx - 8 */
19864 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19865 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19866 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19867 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19868 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19869 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19872 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19876 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19881 env->prog = prog = new_prog;
19882 insn = new_prog->insnsi + i + delta;
19886 /* Implement get_func_arg_cnt inline. */
19887 if (prog_type == BPF_PROG_TYPE_TRACING &&
19888 insn->imm == BPF_FUNC_get_func_arg_cnt) {
19889 /* Load nr_args from ctx - 8 */
19890 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19892 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19896 env->prog = prog = new_prog;
19897 insn = new_prog->insnsi + i + delta;
19901 /* Implement bpf_get_func_ip inline. */
19902 if (prog_type == BPF_PROG_TYPE_TRACING &&
19903 insn->imm == BPF_FUNC_get_func_ip) {
19904 /* Load IP address from ctx - 16 */
19905 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19907 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19911 env->prog = prog = new_prog;
19912 insn = new_prog->insnsi + i + delta;
19916 /* Implement bpf_kptr_xchg inline */
19917 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19918 insn->imm == BPF_FUNC_kptr_xchg &&
19919 bpf_jit_supports_ptr_xchg()) {
19920 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
19921 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
19924 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19929 env->prog = prog = new_prog;
19930 insn = new_prog->insnsi + i + delta;
19934 fn = env->ops->get_func_proto(insn->imm, env->prog);
19935 /* all functions that have prototype and verifier allowed
19936 * programs to call them, must be real in-kernel functions
19940 "kernel subsystem misconfigured func %s#%d\n",
19941 func_id_name(insn->imm), insn->imm);
19944 insn->imm = fn->func - __bpf_call_base;
19947 /* Since poke tab is now finalized, publish aux to tracker. */
19948 for (i = 0; i < prog->aux->size_poke_tab; i++) {
19949 map_ptr = prog->aux->poke_tab[i].tail_call.map;
19950 if (!map_ptr->ops->map_poke_track ||
19951 !map_ptr->ops->map_poke_untrack ||
19952 !map_ptr->ops->map_poke_run) {
19953 verbose(env, "bpf verifier is misconfigured\n");
19957 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19959 verbose(env, "tracking tail call prog failed\n");
19964 sort_kfunc_descs_by_imm_off(env->prog);
19969 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19972 u32 callback_subprogno,
19975 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19976 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19977 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19978 int reg_loop_max = BPF_REG_6;
19979 int reg_loop_cnt = BPF_REG_7;
19980 int reg_loop_ctx = BPF_REG_8;
19982 struct bpf_prog *new_prog;
19983 u32 callback_start;
19984 u32 call_insn_offset;
19985 s32 callback_offset;
19987 /* This represents an inlined version of bpf_iter.c:bpf_loop,
19988 * be careful to modify this code in sync.
19990 struct bpf_insn insn_buf[] = {
19991 /* Return error and jump to the end of the patch if
19992 * expected number of iterations is too big.
19994 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19995 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19996 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19997 /* spill R6, R7, R8 to use these as loop vars */
19998 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19999 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
20000 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
20001 /* initialize loop vars */
20002 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
20003 BPF_MOV32_IMM(reg_loop_cnt, 0),
20004 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
20006 * if reg_loop_cnt >= reg_loop_max skip the loop body
20008 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
20010 * correct callback offset would be set after patching
20012 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
20013 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
20015 /* increment loop counter */
20016 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
20017 /* jump to loop header if callback returned 0 */
20018 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
20019 /* return value of bpf_loop,
20020 * set R0 to the number of iterations
20022 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
20023 /* restore original values of R6, R7, R8 */
20024 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
20025 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
20026 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
20029 *cnt = ARRAY_SIZE(insn_buf);
20030 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
20034 /* callback start is known only after patching */
20035 callback_start = env->subprog_info[callback_subprogno].start;
20036 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
20037 call_insn_offset = position + 12;
20038 callback_offset = callback_start - call_insn_offset - 1;
20039 new_prog->insnsi[call_insn_offset].imm = callback_offset;
20044 static bool is_bpf_loop_call(struct bpf_insn *insn)
20046 return insn->code == (BPF_JMP | BPF_CALL) &&
20047 insn->src_reg == 0 &&
20048 insn->imm == BPF_FUNC_loop;
20051 /* For all sub-programs in the program (including main) check
20052 * insn_aux_data to see if there are bpf_loop calls that require
20053 * inlining. If such calls are found the calls are replaced with a
20054 * sequence of instructions produced by `inline_bpf_loop` function and
20055 * subprog stack_depth is increased by the size of 3 registers.
20056 * This stack space is used to spill values of the R6, R7, R8. These
20057 * registers are used to store the loop bound, counter and context
20060 static int optimize_bpf_loop(struct bpf_verifier_env *env)
20062 struct bpf_subprog_info *subprogs = env->subprog_info;
20063 int i, cur_subprog = 0, cnt, delta = 0;
20064 struct bpf_insn *insn = env->prog->insnsi;
20065 int insn_cnt = env->prog->len;
20066 u16 stack_depth = subprogs[cur_subprog].stack_depth;
20067 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20068 u16 stack_depth_extra = 0;
20070 for (i = 0; i < insn_cnt; i++, insn++) {
20071 struct bpf_loop_inline_state *inline_state =
20072 &env->insn_aux_data[i + delta].loop_inline_state;
20074 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
20075 struct bpf_prog *new_prog;
20077 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
20078 new_prog = inline_bpf_loop(env,
20080 -(stack_depth + stack_depth_extra),
20081 inline_state->callback_subprogno,
20087 env->prog = new_prog;
20088 insn = new_prog->insnsi + i + delta;
20091 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
20092 subprogs[cur_subprog].stack_depth += stack_depth_extra;
20094 stack_depth = subprogs[cur_subprog].stack_depth;
20095 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20096 stack_depth_extra = 0;
20100 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20105 static void free_states(struct bpf_verifier_env *env)
20107 struct bpf_verifier_state_list *sl, *sln;
20110 sl = env->free_list;
20113 free_verifier_state(&sl->state, false);
20117 env->free_list = NULL;
20119 if (!env->explored_states)
20122 for (i = 0; i < state_htab_size(env); i++) {
20123 sl = env->explored_states[i];
20127 free_verifier_state(&sl->state, false);
20131 env->explored_states[i] = NULL;
20135 static int do_check_common(struct bpf_verifier_env *env, int subprog)
20137 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20138 struct bpf_subprog_info *sub = subprog_info(env, subprog);
20139 struct bpf_verifier_state *state;
20140 struct bpf_reg_state *regs;
20143 env->prev_linfo = NULL;
20146 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
20149 state->curframe = 0;
20150 state->speculative = false;
20151 state->branches = 1;
20152 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
20153 if (!state->frame[0]) {
20157 env->cur_state = state;
20158 init_func_state(env, state->frame[0],
20159 BPF_MAIN_FUNC /* callsite */,
20162 state->first_insn_idx = env->subprog_info[subprog].start;
20163 state->last_insn_idx = -1;
20165 regs = state->frame[state->curframe]->regs;
20166 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
20167 const char *sub_name = subprog_name(env, subprog);
20168 struct bpf_subprog_arg_info *arg;
20169 struct bpf_reg_state *reg;
20171 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
20172 ret = btf_prepare_func_args(env, subprog);
20176 if (subprog_is_exc_cb(env, subprog)) {
20177 state->frame[0]->in_exception_callback_fn = true;
20178 /* We have already ensured that the callback returns an integer, just
20179 * like all global subprogs. We need to determine it only has a single
20182 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
20183 verbose(env, "exception cb only supports single integer argument\n");
20188 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
20189 arg = &sub->args[i - BPF_REG_1];
20192 if (arg->arg_type == ARG_PTR_TO_CTX) {
20193 reg->type = PTR_TO_CTX;
20194 mark_reg_known_zero(env, regs, i);
20195 } else if (arg->arg_type == ARG_ANYTHING) {
20196 reg->type = SCALAR_VALUE;
20197 mark_reg_unknown(env, regs, i);
20198 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
20199 /* assume unspecial LOCAL dynptr type */
20200 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
20201 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
20202 reg->type = PTR_TO_MEM;
20203 if (arg->arg_type & PTR_MAYBE_NULL)
20204 reg->type |= PTR_MAYBE_NULL;
20205 mark_reg_known_zero(env, regs, i);
20206 reg->mem_size = arg->mem_size;
20207 reg->id = ++env->id_gen;
20208 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
20209 reg->type = PTR_TO_BTF_ID;
20210 if (arg->arg_type & PTR_MAYBE_NULL)
20211 reg->type |= PTR_MAYBE_NULL;
20212 if (arg->arg_type & PTR_UNTRUSTED)
20213 reg->type |= PTR_UNTRUSTED;
20214 if (arg->arg_type & PTR_TRUSTED)
20215 reg->type |= PTR_TRUSTED;
20216 mark_reg_known_zero(env, regs, i);
20217 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
20218 reg->btf_id = arg->btf_id;
20219 reg->id = ++env->id_gen;
20221 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
20222 i - BPF_REG_1, arg->arg_type);
20228 /* if main BPF program has associated BTF info, validate that
20229 * it's matching expected signature, and otherwise mark BTF
20230 * info for main program as unreliable
20232 if (env->prog->aux->func_info_aux) {
20233 ret = btf_prepare_func_args(env, 0);
20234 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
20235 env->prog->aux->func_info_aux[0].unreliable = true;
20238 /* 1st arg to a function */
20239 regs[BPF_REG_1].type = PTR_TO_CTX;
20240 mark_reg_known_zero(env, regs, BPF_REG_1);
20243 ret = do_check(env);
20245 /* check for NULL is necessary, since cur_state can be freed inside
20246 * do_check() under memory pressure.
20248 if (env->cur_state) {
20249 free_verifier_state(env->cur_state, true);
20250 env->cur_state = NULL;
20252 while (!pop_stack(env, NULL, NULL, false));
20253 if (!ret && pop_log)
20254 bpf_vlog_reset(&env->log, 0);
20259 /* Lazily verify all global functions based on their BTF, if they are called
20260 * from main BPF program or any of subprograms transitively.
20261 * BPF global subprogs called from dead code are not validated.
20262 * All callable global functions must pass verification.
20263 * Otherwise the whole program is rejected.
20274 * foo() will be verified first for R1=any_scalar_value. During verification it
20275 * will be assumed that bar() already verified successfully and call to bar()
20276 * from foo() will be checked for type match only. Later bar() will be verified
20277 * independently to check that it's safe for R1=any_scalar_value.
20279 static int do_check_subprogs(struct bpf_verifier_env *env)
20281 struct bpf_prog_aux *aux = env->prog->aux;
20282 struct bpf_func_info_aux *sub_aux;
20283 int i, ret, new_cnt;
20285 if (!aux->func_info)
20288 /* exception callback is presumed to be always called */
20289 if (env->exception_callback_subprog)
20290 subprog_aux(env, env->exception_callback_subprog)->called = true;
20294 for (i = 1; i < env->subprog_cnt; i++) {
20295 if (!subprog_is_global(env, i))
20298 sub_aux = subprog_aux(env, i);
20299 if (!sub_aux->called || sub_aux->verified)
20302 env->insn_idx = env->subprog_info[i].start;
20303 WARN_ON_ONCE(env->insn_idx == 0);
20304 ret = do_check_common(env, i);
20307 } else if (env->log.level & BPF_LOG_LEVEL) {
20308 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
20309 i, subprog_name(env, i));
20312 /* We verified new global subprog, it might have called some
20313 * more global subprogs that we haven't verified yet, so we
20314 * need to do another pass over subprogs to verify those.
20316 sub_aux->verified = true;
20320 /* We can't loop forever as we verify at least one global subprog on
20329 static int do_check_main(struct bpf_verifier_env *env)
20334 ret = do_check_common(env, 0);
20336 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20341 static void print_verification_stats(struct bpf_verifier_env *env)
20345 if (env->log.level & BPF_LOG_STATS) {
20346 verbose(env, "verification time %lld usec\n",
20347 div_u64(env->verification_time, 1000));
20348 verbose(env, "stack depth ");
20349 for (i = 0; i < env->subprog_cnt; i++) {
20350 u32 depth = env->subprog_info[i].stack_depth;
20352 verbose(env, "%d", depth);
20353 if (i + 1 < env->subprog_cnt)
20356 verbose(env, "\n");
20358 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
20359 "total_states %d peak_states %d mark_read %d\n",
20360 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
20361 env->max_states_per_insn, env->total_states,
20362 env->peak_states, env->longest_mark_read_walk);
20365 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
20367 const struct btf_type *t, *func_proto;
20368 const struct bpf_struct_ops_desc *st_ops_desc;
20369 const struct bpf_struct_ops *st_ops;
20370 const struct btf_member *member;
20371 struct bpf_prog *prog = env->prog;
20372 u32 btf_id, member_idx;
20376 if (!prog->gpl_compatible) {
20377 verbose(env, "struct ops programs must have a GPL compatible license\n");
20381 if (!prog->aux->attach_btf_id)
20384 btf = prog->aux->attach_btf;
20385 if (btf_is_module(btf)) {
20386 /* Make sure st_ops is valid through the lifetime of env */
20387 env->attach_btf_mod = btf_try_get_module(btf);
20388 if (!env->attach_btf_mod) {
20389 verbose(env, "struct_ops module %s is not found\n",
20390 btf_get_name(btf));
20395 btf_id = prog->aux->attach_btf_id;
20396 st_ops_desc = bpf_struct_ops_find(btf, btf_id);
20397 if (!st_ops_desc) {
20398 verbose(env, "attach_btf_id %u is not a supported struct\n",
20402 st_ops = st_ops_desc->st_ops;
20404 t = st_ops_desc->type;
20405 member_idx = prog->expected_attach_type;
20406 if (member_idx >= btf_type_vlen(t)) {
20407 verbose(env, "attach to invalid member idx %u of struct %s\n",
20408 member_idx, st_ops->name);
20412 member = &btf_type_member(t)[member_idx];
20413 mname = btf_name_by_offset(btf, member->name_off);
20414 func_proto = btf_type_resolve_func_ptr(btf, member->type,
20417 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
20418 mname, member_idx, st_ops->name);
20422 if (st_ops->check_member) {
20423 int err = st_ops->check_member(t, member, prog);
20426 verbose(env, "attach to unsupported member %s of struct %s\n",
20427 mname, st_ops->name);
20432 /* btf_ctx_access() used this to provide argument type info */
20433 prog->aux->ctx_arg_info =
20434 st_ops_desc->arg_info[member_idx].info;
20435 prog->aux->ctx_arg_info_size =
20436 st_ops_desc->arg_info[member_idx].cnt;
20438 prog->aux->attach_func_proto = func_proto;
20439 prog->aux->attach_func_name = mname;
20440 env->ops = st_ops->verifier_ops;
20444 #define SECURITY_PREFIX "security_"
20446 static int check_attach_modify_return(unsigned long addr, const char *func_name)
20448 if (within_error_injection_list(addr) ||
20449 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
20455 /* list of non-sleepable functions that are otherwise on
20456 * ALLOW_ERROR_INJECTION list
20458 BTF_SET_START(btf_non_sleepable_error_inject)
20459 /* Three functions below can be called from sleepable and non-sleepable context.
20460 * Assume non-sleepable from bpf safety point of view.
20462 BTF_ID(func, __filemap_add_folio)
20463 BTF_ID(func, should_fail_alloc_page)
20464 BTF_ID(func, should_failslab)
20465 BTF_SET_END(btf_non_sleepable_error_inject)
20467 static int check_non_sleepable_error_inject(u32 btf_id)
20469 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
20472 int bpf_check_attach_target(struct bpf_verifier_log *log,
20473 const struct bpf_prog *prog,
20474 const struct bpf_prog *tgt_prog,
20476 struct bpf_attach_target_info *tgt_info)
20478 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
20479 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
20480 const char prefix[] = "btf_trace_";
20481 int ret = 0, subprog = -1, i;
20482 const struct btf_type *t;
20483 bool conservative = true;
20487 struct module *mod = NULL;
20490 bpf_log(log, "Tracing programs must provide btf_id\n");
20493 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
20496 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
20499 t = btf_type_by_id(btf, btf_id);
20501 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
20504 tname = btf_name_by_offset(btf, t->name_off);
20506 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
20510 struct bpf_prog_aux *aux = tgt_prog->aux;
20512 if (bpf_prog_is_dev_bound(prog->aux) &&
20513 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
20514 bpf_log(log, "Target program bound device mismatch");
20518 for (i = 0; i < aux->func_info_cnt; i++)
20519 if (aux->func_info[i].type_id == btf_id) {
20523 if (subprog == -1) {
20524 bpf_log(log, "Subprog %s doesn't exist\n", tname);
20527 if (aux->func && aux->func[subprog]->aux->exception_cb) {
20529 "%s programs cannot attach to exception callback\n",
20530 prog_extension ? "Extension" : "FENTRY/FEXIT");
20533 conservative = aux->func_info_aux[subprog].unreliable;
20534 if (prog_extension) {
20535 if (conservative) {
20537 "Cannot replace static functions\n");
20540 if (!prog->jit_requested) {
20542 "Extension programs should be JITed\n");
20546 if (!tgt_prog->jited) {
20547 bpf_log(log, "Can attach to only JITed progs\n");
20550 if (prog_tracing) {
20551 if (aux->attach_tracing_prog) {
20553 * Target program is an fentry/fexit which is already attached
20554 * to another tracing program. More levels of nesting
20555 * attachment are not allowed.
20557 bpf_log(log, "Cannot nest tracing program attach more than once\n");
20560 } else if (tgt_prog->type == prog->type) {
20562 * To avoid potential call chain cycles, prevent attaching of a
20563 * program extension to another extension. It's ok to attach
20564 * fentry/fexit to extension program.
20566 bpf_log(log, "Cannot recursively attach\n");
20569 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
20571 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
20572 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
20573 /* Program extensions can extend all program types
20574 * except fentry/fexit. The reason is the following.
20575 * The fentry/fexit programs are used for performance
20576 * analysis, stats and can be attached to any program
20577 * type. When extension program is replacing XDP function
20578 * it is necessary to allow performance analysis of all
20579 * functions. Both original XDP program and its program
20580 * extension. Hence attaching fentry/fexit to
20581 * BPF_PROG_TYPE_EXT is allowed. If extending of
20582 * fentry/fexit was allowed it would be possible to create
20583 * long call chain fentry->extension->fentry->extension
20584 * beyond reasonable stack size. Hence extending fentry
20587 bpf_log(log, "Cannot extend fentry/fexit\n");
20591 if (prog_extension) {
20592 bpf_log(log, "Cannot replace kernel functions\n");
20597 switch (prog->expected_attach_type) {
20598 case BPF_TRACE_RAW_TP:
20601 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
20604 if (!btf_type_is_typedef(t)) {
20605 bpf_log(log, "attach_btf_id %u is not a typedef\n",
20609 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
20610 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
20614 tname += sizeof(prefix) - 1;
20615 t = btf_type_by_id(btf, t->type);
20616 if (!btf_type_is_ptr(t))
20617 /* should never happen in valid vmlinux build */
20619 t = btf_type_by_id(btf, t->type);
20620 if (!btf_type_is_func_proto(t))
20621 /* should never happen in valid vmlinux build */
20625 case BPF_TRACE_ITER:
20626 if (!btf_type_is_func(t)) {
20627 bpf_log(log, "attach_btf_id %u is not a function\n",
20631 t = btf_type_by_id(btf, t->type);
20632 if (!btf_type_is_func_proto(t))
20634 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20639 if (!prog_extension)
20642 case BPF_MODIFY_RETURN:
20644 case BPF_LSM_CGROUP:
20645 case BPF_TRACE_FENTRY:
20646 case BPF_TRACE_FEXIT:
20647 if (!btf_type_is_func(t)) {
20648 bpf_log(log, "attach_btf_id %u is not a function\n",
20652 if (prog_extension &&
20653 btf_check_type_match(log, prog, btf, t))
20655 t = btf_type_by_id(btf, t->type);
20656 if (!btf_type_is_func_proto(t))
20659 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
20660 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
20661 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
20664 if (tgt_prog && conservative)
20667 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20673 addr = (long) tgt_prog->bpf_func;
20675 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20677 if (btf_is_module(btf)) {
20678 mod = btf_try_get_module(btf);
20680 addr = find_kallsyms_symbol_value(mod, tname);
20684 addr = kallsyms_lookup_name(tname);
20689 "The address of function %s cannot be found\n",
20695 if (prog->aux->sleepable) {
20697 switch (prog->type) {
20698 case BPF_PROG_TYPE_TRACING:
20700 /* fentry/fexit/fmod_ret progs can be sleepable if they are
20701 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20703 if (!check_non_sleepable_error_inject(btf_id) &&
20704 within_error_injection_list(addr))
20706 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
20707 * in the fmodret id set with the KF_SLEEPABLE flag.
20710 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20713 if (flags && (*flags & KF_SLEEPABLE))
20717 case BPF_PROG_TYPE_LSM:
20718 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
20719 * Only some of them are sleepable.
20721 if (bpf_lsm_is_sleepable_hook(btf_id))
20729 bpf_log(log, "%s is not sleepable\n", tname);
20732 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20735 bpf_log(log, "can't modify return codes of BPF programs\n");
20739 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20740 !check_attach_modify_return(addr, tname))
20744 bpf_log(log, "%s() is not modifiable\n", tname);
20751 tgt_info->tgt_addr = addr;
20752 tgt_info->tgt_name = tname;
20753 tgt_info->tgt_type = t;
20754 tgt_info->tgt_mod = mod;
20758 BTF_SET_START(btf_id_deny)
20761 BTF_ID(func, migrate_disable)
20762 BTF_ID(func, migrate_enable)
20764 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20765 BTF_ID(func, rcu_read_unlock_strict)
20767 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20768 BTF_ID(func, preempt_count_add)
20769 BTF_ID(func, preempt_count_sub)
20771 #ifdef CONFIG_PREEMPT_RCU
20772 BTF_ID(func, __rcu_read_lock)
20773 BTF_ID(func, __rcu_read_unlock)
20775 BTF_SET_END(btf_id_deny)
20777 static bool can_be_sleepable(struct bpf_prog *prog)
20779 if (prog->type == BPF_PROG_TYPE_TRACING) {
20780 switch (prog->expected_attach_type) {
20781 case BPF_TRACE_FENTRY:
20782 case BPF_TRACE_FEXIT:
20783 case BPF_MODIFY_RETURN:
20784 case BPF_TRACE_ITER:
20790 return prog->type == BPF_PROG_TYPE_LSM ||
20791 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20792 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20795 static int check_attach_btf_id(struct bpf_verifier_env *env)
20797 struct bpf_prog *prog = env->prog;
20798 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20799 struct bpf_attach_target_info tgt_info = {};
20800 u32 btf_id = prog->aux->attach_btf_id;
20801 struct bpf_trampoline *tr;
20805 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20806 if (prog->aux->sleepable)
20807 /* attach_btf_id checked to be zero already */
20809 verbose(env, "Syscall programs can only be sleepable\n");
20813 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20814 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20818 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20819 return check_struct_ops_btf_id(env);
20821 if (prog->type != BPF_PROG_TYPE_TRACING &&
20822 prog->type != BPF_PROG_TYPE_LSM &&
20823 prog->type != BPF_PROG_TYPE_EXT)
20826 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20830 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20831 /* to make freplace equivalent to their targets, they need to
20832 * inherit env->ops and expected_attach_type for the rest of the
20835 env->ops = bpf_verifier_ops[tgt_prog->type];
20836 prog->expected_attach_type = tgt_prog->expected_attach_type;
20839 /* store info about the attachment target that will be used later */
20840 prog->aux->attach_func_proto = tgt_info.tgt_type;
20841 prog->aux->attach_func_name = tgt_info.tgt_name;
20842 prog->aux->mod = tgt_info.tgt_mod;
20845 prog->aux->saved_dst_prog_type = tgt_prog->type;
20846 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20849 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20850 prog->aux->attach_btf_trace = true;
20852 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20853 if (!bpf_iter_prog_supported(prog))
20858 if (prog->type == BPF_PROG_TYPE_LSM) {
20859 ret = bpf_lsm_verify_prog(&env->log, prog);
20862 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
20863 btf_id_set_contains(&btf_id_deny, btf_id)) {
20867 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20868 tr = bpf_trampoline_get(key, &tgt_info);
20872 if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20873 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20875 prog->aux->dst_trampoline = tr;
20879 struct btf *bpf_get_btf_vmlinux(void)
20881 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20882 mutex_lock(&bpf_verifier_lock);
20884 btf_vmlinux = btf_parse_vmlinux();
20885 mutex_unlock(&bpf_verifier_lock);
20887 return btf_vmlinux;
20890 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20892 u64 start_time = ktime_get_ns();
20893 struct bpf_verifier_env *env;
20894 int i, len, ret = -EINVAL, err;
20898 /* no program is valid */
20899 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20902 /* 'struct bpf_verifier_env' can be global, but since it's not small,
20903 * allocate/free it every time bpf_check() is called
20905 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20911 len = (*prog)->len;
20912 env->insn_aux_data =
20913 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20915 if (!env->insn_aux_data)
20917 for (i = 0; i < len; i++)
20918 env->insn_aux_data[i].orig_idx = i;
20920 env->ops = bpf_verifier_ops[env->prog->type];
20921 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20923 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
20924 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
20925 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
20926 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
20927 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
20929 bpf_get_btf_vmlinux();
20931 /* grab the mutex to protect few globals used by verifier */
20933 mutex_lock(&bpf_verifier_lock);
20935 /* user could have requested verbose verifier output
20936 * and supplied buffer to store the verification trace
20938 ret = bpf_vlog_init(&env->log, attr->log_level,
20939 (char __user *) (unsigned long) attr->log_buf,
20944 mark_verifier_state_clean(env);
20946 if (IS_ERR(btf_vmlinux)) {
20947 /* Either gcc or pahole or kernel are broken. */
20948 verbose(env, "in-kernel BTF is malformed\n");
20949 ret = PTR_ERR(btf_vmlinux);
20950 goto skip_full_check;
20953 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20954 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20955 env->strict_alignment = true;
20956 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20957 env->strict_alignment = false;
20960 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20961 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
20963 env->explored_states = kvcalloc(state_htab_size(env),
20964 sizeof(struct bpf_verifier_state_list *),
20967 if (!env->explored_states)
20968 goto skip_full_check;
20970 ret = check_btf_info_early(env, attr, uattr);
20972 goto skip_full_check;
20974 ret = add_subprog_and_kfunc(env);
20976 goto skip_full_check;
20978 ret = check_subprogs(env);
20980 goto skip_full_check;
20982 ret = check_btf_info(env, attr, uattr);
20984 goto skip_full_check;
20986 ret = check_attach_btf_id(env);
20988 goto skip_full_check;
20990 ret = resolve_pseudo_ldimm64(env);
20992 goto skip_full_check;
20994 if (bpf_prog_is_offloaded(env->prog->aux)) {
20995 ret = bpf_prog_offload_verifier_prep(env->prog);
20997 goto skip_full_check;
21000 ret = check_cfg(env);
21002 goto skip_full_check;
21004 ret = do_check_main(env);
21005 ret = ret ?: do_check_subprogs(env);
21007 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
21008 ret = bpf_prog_offload_finalize(env);
21011 kvfree(env->explored_states);
21014 ret = check_max_stack_depth(env);
21016 /* instruction rewrites happen after this point */
21018 ret = optimize_bpf_loop(env);
21022 opt_hard_wire_dead_code_branches(env);
21024 ret = opt_remove_dead_code(env);
21026 ret = opt_remove_nops(env);
21029 sanitize_dead_code(env);
21033 /* program is valid, convert *(u32*)(ctx + off) accesses */
21034 ret = convert_ctx_accesses(env);
21037 ret = do_misc_fixups(env);
21039 /* do 32-bit optimization after insn patching has done so those patched
21040 * insns could be handled correctly.
21042 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
21043 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
21044 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
21049 ret = fixup_call_args(env);
21051 env->verification_time = ktime_get_ns() - start_time;
21052 print_verification_stats(env);
21053 env->prog->aux->verified_insns = env->insn_processed;
21055 /* preserve original error even if log finalization is successful */
21056 err = bpf_vlog_finalize(&env->log, &log_true_size);
21060 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
21061 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
21062 &log_true_size, sizeof(log_true_size))) {
21064 goto err_release_maps;
21068 goto err_release_maps;
21070 if (env->used_map_cnt) {
21071 /* if program passed verifier, update used_maps in bpf_prog_info */
21072 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
21073 sizeof(env->used_maps[0]),
21076 if (!env->prog->aux->used_maps) {
21078 goto err_release_maps;
21081 memcpy(env->prog->aux->used_maps, env->used_maps,
21082 sizeof(env->used_maps[0]) * env->used_map_cnt);
21083 env->prog->aux->used_map_cnt = env->used_map_cnt;
21085 if (env->used_btf_cnt) {
21086 /* if program passed verifier, update used_btfs in bpf_prog_aux */
21087 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
21088 sizeof(env->used_btfs[0]),
21090 if (!env->prog->aux->used_btfs) {
21092 goto err_release_maps;
21095 memcpy(env->prog->aux->used_btfs, env->used_btfs,
21096 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
21097 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
21099 if (env->used_map_cnt || env->used_btf_cnt) {
21100 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
21101 * bpf_ld_imm64 instructions
21103 convert_pseudo_ld_imm64(env);
21106 adjust_btf_func(env);
21109 if (!env->prog->aux->used_maps)
21110 /* if we didn't copy map pointers into bpf_prog_info, release
21111 * them now. Otherwise free_used_maps() will release them.
21114 if (!env->prog->aux->used_btfs)
21117 /* extension progs temporarily inherit the attach_type of their targets
21118 for verification purposes, so set it back to zero before returning
21120 if (env->prog->type == BPF_PROG_TYPE_EXT)
21121 env->prog->expected_attach_type = 0;
21125 module_put(env->attach_btf_mod);
21128 mutex_unlock(&bpf_verifier_lock);
21129 vfree(env->insn_aux_data);