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 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1159 * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1160 * more precise STACK_ZERO.
1161 * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take
1162 * env->allow_ptr_leaks into account and force STACK_MISC, if necessary.
1164 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1166 if (*stype == STACK_ZERO)
1168 if (env->allow_ptr_leaks && *stype == STACK_INVALID)
1170 *stype = STACK_MISC;
1173 static void scrub_spilled_slot(u8 *stype)
1175 if (*stype != STACK_INVALID)
1176 *stype = STACK_MISC;
1179 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1180 * small to hold src. This is different from krealloc since we don't want to preserve
1181 * the contents of dst.
1183 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1186 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1192 if (ZERO_OR_NULL_PTR(src))
1195 if (unlikely(check_mul_overflow(n, size, &bytes)))
1198 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1199 dst = krealloc(orig, alloc_bytes, flags);
1205 memcpy(dst, src, bytes);
1207 return dst ? dst : ZERO_SIZE_PTR;
1210 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1211 * small to hold new_n items. new items are zeroed out if the array grows.
1213 * Contrary to krealloc_array, does not free arr if new_n is zero.
1215 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1220 if (!new_n || old_n == new_n)
1223 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1224 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1232 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1235 return arr ? arr : ZERO_SIZE_PTR;
1238 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1240 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1241 sizeof(struct bpf_reference_state), GFP_KERNEL);
1245 dst->acquired_refs = src->acquired_refs;
1249 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1251 size_t n = src->allocated_stack / BPF_REG_SIZE;
1253 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1258 dst->allocated_stack = src->allocated_stack;
1262 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1264 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1265 sizeof(struct bpf_reference_state));
1269 state->acquired_refs = n;
1273 /* Possibly update state->allocated_stack to be at least size bytes. Also
1274 * possibly update the function's high-water mark in its bpf_subprog_info.
1276 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1278 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1280 /* The stack size is always a multiple of BPF_REG_SIZE. */
1281 size = round_up(size, BPF_REG_SIZE);
1282 n = size / BPF_REG_SIZE;
1287 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1291 state->allocated_stack = size;
1293 /* update known max for given subprogram */
1294 if (env->subprog_info[state->subprogno].stack_depth < size)
1295 env->subprog_info[state->subprogno].stack_depth = size;
1300 /* Acquire a pointer id from the env and update the state->refs to include
1301 * this new pointer reference.
1302 * On success, returns a valid pointer id to associate with the register
1303 * On failure, returns a negative errno.
1305 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1307 struct bpf_func_state *state = cur_func(env);
1308 int new_ofs = state->acquired_refs;
1311 err = resize_reference_state(state, state->acquired_refs + 1);
1315 state->refs[new_ofs].id = id;
1316 state->refs[new_ofs].insn_idx = insn_idx;
1317 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1322 /* release function corresponding to acquire_reference_state(). Idempotent. */
1323 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1327 last_idx = state->acquired_refs - 1;
1328 for (i = 0; i < state->acquired_refs; i++) {
1329 if (state->refs[i].id == ptr_id) {
1330 /* Cannot release caller references in callbacks */
1331 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1333 if (last_idx && i != last_idx)
1334 memcpy(&state->refs[i], &state->refs[last_idx],
1335 sizeof(*state->refs));
1336 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1337 state->acquired_refs--;
1344 static void free_func_state(struct bpf_func_state *state)
1349 kfree(state->stack);
1353 static void clear_jmp_history(struct bpf_verifier_state *state)
1355 kfree(state->jmp_history);
1356 state->jmp_history = NULL;
1357 state->jmp_history_cnt = 0;
1360 static void free_verifier_state(struct bpf_verifier_state *state,
1365 for (i = 0; i <= state->curframe; i++) {
1366 free_func_state(state->frame[i]);
1367 state->frame[i] = NULL;
1369 clear_jmp_history(state);
1374 /* copy verifier state from src to dst growing dst stack space
1375 * when necessary to accommodate larger src stack
1377 static int copy_func_state(struct bpf_func_state *dst,
1378 const struct bpf_func_state *src)
1382 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1383 err = copy_reference_state(dst, src);
1386 return copy_stack_state(dst, src);
1389 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1390 const struct bpf_verifier_state *src)
1392 struct bpf_func_state *dst;
1395 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1396 src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1398 if (!dst_state->jmp_history)
1400 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1402 /* if dst has more stack frames then src frame, free them, this is also
1403 * necessary in case of exceptional exits using bpf_throw.
1405 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1406 free_func_state(dst_state->frame[i]);
1407 dst_state->frame[i] = NULL;
1409 dst_state->speculative = src->speculative;
1410 dst_state->active_rcu_lock = src->active_rcu_lock;
1411 dst_state->curframe = src->curframe;
1412 dst_state->active_lock.ptr = src->active_lock.ptr;
1413 dst_state->active_lock.id = src->active_lock.id;
1414 dst_state->branches = src->branches;
1415 dst_state->parent = src->parent;
1416 dst_state->first_insn_idx = src->first_insn_idx;
1417 dst_state->last_insn_idx = src->last_insn_idx;
1418 dst_state->dfs_depth = src->dfs_depth;
1419 dst_state->callback_unroll_depth = src->callback_unroll_depth;
1420 dst_state->used_as_loop_entry = src->used_as_loop_entry;
1421 for (i = 0; i <= src->curframe; i++) {
1422 dst = dst_state->frame[i];
1424 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1427 dst_state->frame[i] = dst;
1429 err = copy_func_state(dst, src->frame[i]);
1436 static u32 state_htab_size(struct bpf_verifier_env *env)
1438 return env->prog->len;
1441 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1443 struct bpf_verifier_state *cur = env->cur_state;
1444 struct bpf_func_state *state = cur->frame[cur->curframe];
1446 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1449 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1453 if (a->curframe != b->curframe)
1456 for (fr = a->curframe; fr >= 0; fr--)
1457 if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1463 /* Open coded iterators allow back-edges in the state graph in order to
1464 * check unbounded loops that iterators.
1466 * In is_state_visited() it is necessary to know if explored states are
1467 * part of some loops in order to decide whether non-exact states
1468 * comparison could be used:
1469 * - non-exact states comparison establishes sub-state relation and uses
1470 * read and precision marks to do so, these marks are propagated from
1471 * children states and thus are not guaranteed to be final in a loop;
1472 * - exact states comparison just checks if current and explored states
1473 * are identical (and thus form a back-edge).
1475 * Paper "A New Algorithm for Identifying Loops in Decompilation"
1476 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1477 * algorithm for loop structure detection and gives an overview of
1478 * relevant terminology. It also has helpful illustrations.
1480 * [1] https://api.semanticscholar.org/CorpusID:15784067
1482 * We use a similar algorithm but because loop nested structure is
1483 * irrelevant for verifier ours is significantly simpler and resembles
1484 * strongly connected components algorithm from Sedgewick's textbook.
1486 * Define topmost loop entry as a first node of the loop traversed in a
1487 * depth first search starting from initial state. The goal of the loop
1488 * tracking algorithm is to associate topmost loop entries with states
1489 * derived from these entries.
1491 * For each step in the DFS states traversal algorithm needs to identify
1492 * the following situations:
1494 * initial initial initial
1497 * ... ... .---------> hdr
1500 * cur .-> succ | .------...
1503 * succ '-- cur | ... ...
1513 * (A) successor state of cur (B) successor state of cur or it's entry
1514 * not yet traversed are in current DFS path, thus cur and succ
1515 * are members of the same outermost loop
1523 * .------... .------...
1526 * .-> hdr ... ... ...
1529 * | succ <- cur succ <- cur
1536 * (C) successor state of cur is a part of some loop but this loop
1537 * does not include cur or successor state is not in a loop at all.
1539 * Algorithm could be described as the following python code:
1541 * traversed = set() # Set of traversed nodes
1542 * entries = {} # Mapping from node to loop entry
1543 * depths = {} # Depth level assigned to graph node
1544 * path = set() # Current DFS path
1546 * # Find outermost loop entry known for n
1547 * def get_loop_entry(n):
1548 * h = entries.get(n, None)
1549 * while h in entries and entries[h] != h:
1553 * # Update n's loop entry if h's outermost entry comes
1554 * # before n's outermost entry in current DFS path.
1555 * def update_loop_entry(n, h):
1556 * n1 = get_loop_entry(n) or n
1557 * h1 = get_loop_entry(h) or h
1558 * if h1 in path and depths[h1] <= depths[n1]:
1561 * def dfs(n, depth):
1565 * for succ in G.successors(n):
1566 * if succ not in traversed:
1567 * # Case A: explore succ and update cur's loop entry
1568 * # only if succ's entry is in current DFS path.
1569 * dfs(succ, depth + 1)
1570 * h = get_loop_entry(succ)
1571 * update_loop_entry(n, h)
1573 * # Case B or C depending on `h1 in path` check in update_loop_entry().
1574 * update_loop_entry(n, succ)
1577 * To adapt this algorithm for use with verifier:
1578 * - use st->branch == 0 as a signal that DFS of succ had been finished
1579 * and cur's loop entry has to be updated (case A), handle this in
1580 * update_branch_counts();
1581 * - use st->branch > 0 as a signal that st is in the current DFS path;
1582 * - handle cases B and C in is_state_visited();
1583 * - update topmost loop entry for intermediate states in get_loop_entry().
1585 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1587 struct bpf_verifier_state *topmost = st->loop_entry, *old;
1589 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1590 topmost = topmost->loop_entry;
1591 /* Update loop entries for intermediate states to avoid this
1592 * traversal in future get_loop_entry() calls.
1594 while (st && st->loop_entry != topmost) {
1595 old = st->loop_entry;
1596 st->loop_entry = topmost;
1602 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1604 struct bpf_verifier_state *cur1, *hdr1;
1606 cur1 = get_loop_entry(cur) ?: cur;
1607 hdr1 = get_loop_entry(hdr) ?: hdr;
1608 /* The head1->branches check decides between cases B and C in
1609 * comment for get_loop_entry(). If hdr1->branches == 0 then
1610 * head's topmost loop entry is not in current DFS path,
1611 * hence 'cur' and 'hdr' are not in the same loop and there is
1612 * no need to update cur->loop_entry.
1614 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1615 cur->loop_entry = hdr;
1616 hdr->used_as_loop_entry = true;
1620 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1623 u32 br = --st->branches;
1625 /* br == 0 signals that DFS exploration for 'st' is finished,
1626 * thus it is necessary to update parent's loop entry if it
1627 * turned out that st is a part of some loop.
1628 * This is a part of 'case A' in get_loop_entry() comment.
1630 if (br == 0 && st->parent && st->loop_entry)
1631 update_loop_entry(st->parent, st->loop_entry);
1633 /* WARN_ON(br > 1) technically makes sense here,
1634 * but see comment in push_stack(), hence:
1636 WARN_ONCE((int)br < 0,
1637 "BUG update_branch_counts:branches_to_explore=%d\n",
1645 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1646 int *insn_idx, bool pop_log)
1648 struct bpf_verifier_state *cur = env->cur_state;
1649 struct bpf_verifier_stack_elem *elem, *head = env->head;
1652 if (env->head == NULL)
1656 err = copy_verifier_state(cur, &head->st);
1661 bpf_vlog_reset(&env->log, head->log_pos);
1663 *insn_idx = head->insn_idx;
1665 *prev_insn_idx = head->prev_insn_idx;
1667 free_verifier_state(&head->st, false);
1674 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1675 int insn_idx, int prev_insn_idx,
1678 struct bpf_verifier_state *cur = env->cur_state;
1679 struct bpf_verifier_stack_elem *elem;
1682 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1686 elem->insn_idx = insn_idx;
1687 elem->prev_insn_idx = prev_insn_idx;
1688 elem->next = env->head;
1689 elem->log_pos = env->log.end_pos;
1692 err = copy_verifier_state(&elem->st, cur);
1695 elem->st.speculative |= speculative;
1696 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1697 verbose(env, "The sequence of %d jumps is too complex.\n",
1701 if (elem->st.parent) {
1702 ++elem->st.parent->branches;
1703 /* WARN_ON(branches > 2) technically makes sense here,
1705 * 1. speculative states will bump 'branches' for non-branch
1707 * 2. is_state_visited() heuristics may decide not to create
1708 * a new state for a sequence of branches and all such current
1709 * and cloned states will be pointing to a single parent state
1710 * which might have large 'branches' count.
1715 free_verifier_state(env->cur_state, true);
1716 env->cur_state = NULL;
1717 /* pop all elements and return */
1718 while (!pop_stack(env, NULL, NULL, false));
1722 #define CALLER_SAVED_REGS 6
1723 static const int caller_saved[CALLER_SAVED_REGS] = {
1724 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1727 /* This helper doesn't clear reg->id */
1728 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1730 reg->var_off = tnum_const(imm);
1731 reg->smin_value = (s64)imm;
1732 reg->smax_value = (s64)imm;
1733 reg->umin_value = imm;
1734 reg->umax_value = imm;
1736 reg->s32_min_value = (s32)imm;
1737 reg->s32_max_value = (s32)imm;
1738 reg->u32_min_value = (u32)imm;
1739 reg->u32_max_value = (u32)imm;
1742 /* Mark the unknown part of a register (variable offset or scalar value) as
1743 * known to have the value @imm.
1745 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1747 /* Clear off and union(map_ptr, range) */
1748 memset(((u8 *)reg) + sizeof(reg->type), 0,
1749 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1751 reg->ref_obj_id = 0;
1752 ___mark_reg_known(reg, imm);
1755 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1757 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1758 reg->s32_min_value = (s32)imm;
1759 reg->s32_max_value = (s32)imm;
1760 reg->u32_min_value = (u32)imm;
1761 reg->u32_max_value = (u32)imm;
1764 /* Mark the 'variable offset' part of a register as zero. This should be
1765 * used only on registers holding a pointer type.
1767 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1769 __mark_reg_known(reg, 0);
1772 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1774 __mark_reg_known(reg, 0);
1775 reg->type = SCALAR_VALUE;
1776 /* all scalars are assumed imprecise initially (unless unprivileged,
1777 * in which case everything is forced to be precise)
1779 reg->precise = !env->bpf_capable;
1782 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1783 struct bpf_reg_state *regs, u32 regno)
1785 if (WARN_ON(regno >= MAX_BPF_REG)) {
1786 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1787 /* Something bad happened, let's kill all regs */
1788 for (regno = 0; regno < MAX_BPF_REG; regno++)
1789 __mark_reg_not_init(env, regs + regno);
1792 __mark_reg_known_zero(regs + regno);
1795 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1796 bool first_slot, int dynptr_id)
1798 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1799 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1800 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1802 __mark_reg_known_zero(reg);
1803 reg->type = CONST_PTR_TO_DYNPTR;
1804 /* Give each dynptr a unique id to uniquely associate slices to it. */
1805 reg->id = dynptr_id;
1806 reg->dynptr.type = type;
1807 reg->dynptr.first_slot = first_slot;
1810 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1812 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1813 const struct bpf_map *map = reg->map_ptr;
1815 if (map->inner_map_meta) {
1816 reg->type = CONST_PTR_TO_MAP;
1817 reg->map_ptr = map->inner_map_meta;
1818 /* transfer reg's id which is unique for every map_lookup_elem
1819 * as UID of the inner map.
1821 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1822 reg->map_uid = reg->id;
1823 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1824 reg->type = PTR_TO_XDP_SOCK;
1825 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1826 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1827 reg->type = PTR_TO_SOCKET;
1829 reg->type = PTR_TO_MAP_VALUE;
1834 reg->type &= ~PTR_MAYBE_NULL;
1837 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1838 struct btf_field_graph_root *ds_head)
1840 __mark_reg_known_zero(®s[regno]);
1841 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1842 regs[regno].btf = ds_head->btf;
1843 regs[regno].btf_id = ds_head->value_btf_id;
1844 regs[regno].off = ds_head->node_offset;
1847 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1849 return type_is_pkt_pointer(reg->type);
1852 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1854 return reg_is_pkt_pointer(reg) ||
1855 reg->type == PTR_TO_PACKET_END;
1858 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1860 return base_type(reg->type) == PTR_TO_MEM &&
1861 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1864 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1865 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1866 enum bpf_reg_type which)
1868 /* The register can already have a range from prior markings.
1869 * This is fine as long as it hasn't been advanced from its
1872 return reg->type == which &&
1875 tnum_equals_const(reg->var_off, 0);
1878 /* Reset the min/max bounds of a register */
1879 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1881 reg->smin_value = S64_MIN;
1882 reg->smax_value = S64_MAX;
1883 reg->umin_value = 0;
1884 reg->umax_value = U64_MAX;
1886 reg->s32_min_value = S32_MIN;
1887 reg->s32_max_value = S32_MAX;
1888 reg->u32_min_value = 0;
1889 reg->u32_max_value = U32_MAX;
1892 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1894 reg->smin_value = S64_MIN;
1895 reg->smax_value = S64_MAX;
1896 reg->umin_value = 0;
1897 reg->umax_value = U64_MAX;
1900 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1902 reg->s32_min_value = S32_MIN;
1903 reg->s32_max_value = S32_MAX;
1904 reg->u32_min_value = 0;
1905 reg->u32_max_value = U32_MAX;
1908 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1910 struct tnum var32_off = tnum_subreg(reg->var_off);
1912 /* min signed is max(sign bit) | min(other bits) */
1913 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1914 var32_off.value | (var32_off.mask & S32_MIN));
1915 /* max signed is min(sign bit) | max(other bits) */
1916 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1917 var32_off.value | (var32_off.mask & S32_MAX));
1918 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1919 reg->u32_max_value = min(reg->u32_max_value,
1920 (u32)(var32_off.value | var32_off.mask));
1923 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1925 /* min signed is max(sign bit) | min(other bits) */
1926 reg->smin_value = max_t(s64, reg->smin_value,
1927 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1928 /* max signed is min(sign bit) | max(other bits) */
1929 reg->smax_value = min_t(s64, reg->smax_value,
1930 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1931 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1932 reg->umax_value = min(reg->umax_value,
1933 reg->var_off.value | reg->var_off.mask);
1936 static void __update_reg_bounds(struct bpf_reg_state *reg)
1938 __update_reg32_bounds(reg);
1939 __update_reg64_bounds(reg);
1942 /* Uses signed min/max values to inform unsigned, and vice-versa */
1943 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1945 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32
1946 * bits to improve our u32/s32 boundaries.
1948 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
1949 * u64) is pretty trivial, it's obvious that in u32 we'll also have
1950 * [10, 20] range. But this property holds for any 64-bit range as
1951 * long as upper 32 bits in that entire range of values stay the same.
1953 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
1954 * in decimal) has the same upper 32 bits throughout all the values in
1955 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
1958 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
1959 * following the rules outlined below about u64/s64 correspondence
1960 * (which equally applies to u32 vs s32 correspondence). In general it
1961 * depends on actual hexadecimal values of 32-bit range. They can form
1962 * only valid u32, or only valid s32 ranges in some cases.
1964 * So we use all these insights to derive bounds for subregisters here.
1966 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
1967 /* u64 to u32 casting preserves validity of low 32 bits as
1968 * a range, if upper 32 bits are the same
1970 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
1971 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
1973 if ((s32)reg->umin_value <= (s32)reg->umax_value) {
1974 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
1975 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
1978 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
1979 /* low 32 bits should form a proper u32 range */
1980 if ((u32)reg->smin_value <= (u32)reg->smax_value) {
1981 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
1982 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
1984 /* low 32 bits should form a proper s32 range */
1985 if ((s32)reg->smin_value <= (s32)reg->smax_value) {
1986 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
1987 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
1990 /* Special case where upper bits form a small sequence of two
1991 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
1992 * 0x00000000 is also valid), while lower bits form a proper s32 range
1993 * going from negative numbers to positive numbers. E.g., let's say we
1994 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
1995 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
1996 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
1997 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
1998 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
1999 * upper 32 bits. As a random example, s64 range
2000 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2001 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2003 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2004 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2005 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2006 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2008 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2009 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2010 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2011 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2013 /* if u32 range forms a valid s32 range (due to matching sign bit),
2014 * try to learn from that
2016 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2017 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2018 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2020 /* If we cannot cross the sign boundary, then signed and unsigned bounds
2021 * are the same, so combine. This works even in the negative case, e.g.
2022 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2024 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2025 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2026 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2030 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2032 /* If u64 range forms a valid s64 range (due to matching sign bit),
2033 * try to learn from that. Let's do a bit of ASCII art to see when
2034 * this is happening. Let's take u64 range first:
2036 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
2037 * |-------------------------------|--------------------------------|
2039 * Valid u64 range is formed when umin and umax are anywhere in the
2040 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2041 * straightforward. Let's see how s64 range maps onto the same range
2042 * of values, annotated below the line for comparison:
2044 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
2045 * |-------------------------------|--------------------------------|
2046 * 0 S64_MAX S64_MIN -1
2048 * So s64 values basically start in the middle and they are logically
2049 * contiguous to the right of it, wrapping around from -1 to 0, and
2050 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2051 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2052 * more visually as mapped to sign-agnostic range of hex values.
2055 * _______________________________________________________________
2057 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
2058 * |-------------------------------|--------------------------------|
2059 * 0 S64_MAX S64_MIN -1
2061 * >------------------------------ ------------------------------->
2062 * s64 continues... s64 end s64 start s64 "midpoint"
2064 * What this means is that, in general, we can't always derive
2065 * something new about u64 from any random s64 range, and vice versa.
2067 * But we can do that in two particular cases. One is when entire
2068 * u64/s64 range is *entirely* contained within left half of the above
2069 * diagram or when it is *entirely* contained in the right half. I.e.:
2071 * |-------------------------------|--------------------------------|
2075 * [A, B] and [C, D] are contained entirely in their respective halves
2076 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2077 * will be non-negative both as u64 and s64 (and in fact it will be
2078 * identical ranges no matter the signedness). [C, D] treated as s64
2079 * will be a range of negative values, while in u64 it will be
2080 * non-negative range of values larger than 0x8000000000000000.
2082 * Now, any other range here can't be represented in both u64 and s64
2083 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2084 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2085 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2086 * for example. Similarly, valid s64 range [D, A] (going from negative
2087 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2088 * ranges as u64. Currently reg_state can't represent two segments per
2089 * numeric domain, so in such situations we can only derive maximal
2090 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2092 * So we use these facts to derive umin/umax from smin/smax and vice
2093 * versa only if they stay within the same "half". This is equivalent
2094 * to checking sign bit: lower half will have sign bit as zero, upper
2095 * half have sign bit 1. Below in code we simplify this by just
2096 * casting umin/umax as smin/smax and checking if they form valid
2097 * range, and vice versa. Those are equivalent checks.
2099 if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2100 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2101 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2103 /* If we cannot cross the sign boundary, then signed and unsigned bounds
2104 * are the same, so combine. This works even in the negative case, e.g.
2105 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2107 if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2108 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2109 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2113 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2115 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2116 * values on both sides of 64-bit range in hope to have tigher range.
2117 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2118 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2119 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2120 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2121 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2122 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2123 * We just need to make sure that derived bounds we are intersecting
2124 * with are well-formed ranges in respecitve s64 or u64 domain, just
2125 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2127 __u64 new_umin, new_umax;
2128 __s64 new_smin, new_smax;
2130 /* u32 -> u64 tightening, it's always well-formed */
2131 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2132 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2133 reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2134 reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2135 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2136 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2137 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2138 reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2139 reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2141 /* if s32 can be treated as valid u32 range, we can use it as well */
2142 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2143 /* s32 -> u64 tightening */
2144 new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2145 new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2146 reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2147 reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2148 /* s32 -> s64 tightening */
2149 new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2150 new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2151 reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2152 reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2156 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2158 __reg32_deduce_bounds(reg);
2159 __reg64_deduce_bounds(reg);
2160 __reg_deduce_mixed_bounds(reg);
2163 /* Attempts to improve var_off based on unsigned min/max information */
2164 static void __reg_bound_offset(struct bpf_reg_state *reg)
2166 struct tnum var64_off = tnum_intersect(reg->var_off,
2167 tnum_range(reg->umin_value,
2169 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2170 tnum_range(reg->u32_min_value,
2171 reg->u32_max_value));
2173 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2176 static void reg_bounds_sync(struct bpf_reg_state *reg)
2178 /* We might have learned new bounds from the var_off. */
2179 __update_reg_bounds(reg);
2180 /* We might have learned something about the sign bit. */
2181 __reg_deduce_bounds(reg);
2182 __reg_deduce_bounds(reg);
2183 /* We might have learned some bits from the bounds. */
2184 __reg_bound_offset(reg);
2185 /* Intersecting with the old var_off might have improved our bounds
2186 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2187 * then new var_off is (0; 0x7f...fc) which improves our umax.
2189 __update_reg_bounds(reg);
2192 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2193 struct bpf_reg_state *reg, const char *ctx)
2197 if (reg->umin_value > reg->umax_value ||
2198 reg->smin_value > reg->smax_value ||
2199 reg->u32_min_value > reg->u32_max_value ||
2200 reg->s32_min_value > reg->s32_max_value) {
2201 msg = "range bounds violation";
2205 if (tnum_is_const(reg->var_off)) {
2206 u64 uval = reg->var_off.value;
2207 s64 sval = (s64)uval;
2209 if (reg->umin_value != uval || reg->umax_value != uval ||
2210 reg->smin_value != sval || reg->smax_value != sval) {
2211 msg = "const tnum out of sync with range bounds";
2216 if (tnum_subreg_is_const(reg->var_off)) {
2217 u32 uval32 = tnum_subreg(reg->var_off).value;
2218 s32 sval32 = (s32)uval32;
2220 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2221 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2222 msg = "const subreg tnum out of sync with range bounds";
2229 verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2230 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2231 ctx, msg, reg->umin_value, reg->umax_value,
2232 reg->smin_value, reg->smax_value,
2233 reg->u32_min_value, reg->u32_max_value,
2234 reg->s32_min_value, reg->s32_max_value,
2235 reg->var_off.value, reg->var_off.mask);
2236 if (env->test_reg_invariants)
2238 __mark_reg_unbounded(reg);
2242 static bool __reg32_bound_s64(s32 a)
2244 return a >= 0 && a <= S32_MAX;
2247 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2249 reg->umin_value = reg->u32_min_value;
2250 reg->umax_value = reg->u32_max_value;
2252 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2253 * be positive otherwise set to worse case bounds and refine later
2256 if (__reg32_bound_s64(reg->s32_min_value) &&
2257 __reg32_bound_s64(reg->s32_max_value)) {
2258 reg->smin_value = reg->s32_min_value;
2259 reg->smax_value = reg->s32_max_value;
2261 reg->smin_value = 0;
2262 reg->smax_value = U32_MAX;
2266 /* Mark a register as having a completely unknown (scalar) value. */
2267 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2268 struct bpf_reg_state *reg)
2271 * Clear type, off, and union(map_ptr, range) and
2272 * padding between 'type' and union
2274 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2275 reg->type = SCALAR_VALUE;
2277 reg->ref_obj_id = 0;
2278 reg->var_off = tnum_unknown;
2280 reg->precise = !env->bpf_capable;
2281 __mark_reg_unbounded(reg);
2284 static void mark_reg_unknown(struct bpf_verifier_env *env,
2285 struct bpf_reg_state *regs, u32 regno)
2287 if (WARN_ON(regno >= MAX_BPF_REG)) {
2288 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2289 /* Something bad happened, let's kill all regs except FP */
2290 for (regno = 0; regno < BPF_REG_FP; regno++)
2291 __mark_reg_not_init(env, regs + regno);
2294 __mark_reg_unknown(env, regs + regno);
2297 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2298 struct bpf_reg_state *reg)
2300 __mark_reg_unknown(env, reg);
2301 reg->type = NOT_INIT;
2304 static void mark_reg_not_init(struct bpf_verifier_env *env,
2305 struct bpf_reg_state *regs, u32 regno)
2307 if (WARN_ON(regno >= MAX_BPF_REG)) {
2308 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2309 /* Something bad happened, let's kill all regs except FP */
2310 for (regno = 0; regno < BPF_REG_FP; regno++)
2311 __mark_reg_not_init(env, regs + regno);
2314 __mark_reg_not_init(env, regs + regno);
2317 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2318 struct bpf_reg_state *regs, u32 regno,
2319 enum bpf_reg_type reg_type,
2320 struct btf *btf, u32 btf_id,
2321 enum bpf_type_flag flag)
2323 if (reg_type == SCALAR_VALUE) {
2324 mark_reg_unknown(env, regs, regno);
2327 mark_reg_known_zero(env, regs, regno);
2328 regs[regno].type = PTR_TO_BTF_ID | flag;
2329 regs[regno].btf = btf;
2330 regs[regno].btf_id = btf_id;
2333 #define DEF_NOT_SUBREG (0)
2334 static void init_reg_state(struct bpf_verifier_env *env,
2335 struct bpf_func_state *state)
2337 struct bpf_reg_state *regs = state->regs;
2340 for (i = 0; i < MAX_BPF_REG; i++) {
2341 mark_reg_not_init(env, regs, i);
2342 regs[i].live = REG_LIVE_NONE;
2343 regs[i].parent = NULL;
2344 regs[i].subreg_def = DEF_NOT_SUBREG;
2348 regs[BPF_REG_FP].type = PTR_TO_STACK;
2349 mark_reg_known_zero(env, regs, BPF_REG_FP);
2350 regs[BPF_REG_FP].frameno = state->frameno;
2353 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2355 return (struct bpf_retval_range){ minval, maxval };
2358 #define BPF_MAIN_FUNC (-1)
2359 static void init_func_state(struct bpf_verifier_env *env,
2360 struct bpf_func_state *state,
2361 int callsite, int frameno, int subprogno)
2363 state->callsite = callsite;
2364 state->frameno = frameno;
2365 state->subprogno = subprogno;
2366 state->callback_ret_range = retval_range(0, 0);
2367 init_reg_state(env, state);
2368 mark_verifier_state_scratched(env);
2371 /* Similar to push_stack(), but for async callbacks */
2372 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2373 int insn_idx, int prev_insn_idx,
2376 struct bpf_verifier_stack_elem *elem;
2377 struct bpf_func_state *frame;
2379 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2383 elem->insn_idx = insn_idx;
2384 elem->prev_insn_idx = prev_insn_idx;
2385 elem->next = env->head;
2386 elem->log_pos = env->log.end_pos;
2389 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2391 "The sequence of %d jumps is too complex for async cb.\n",
2395 /* Unlike push_stack() do not copy_verifier_state().
2396 * The caller state doesn't matter.
2397 * This is async callback. It starts in a fresh stack.
2398 * Initialize it similar to do_check_common().
2400 elem->st.branches = 1;
2401 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2404 init_func_state(env, frame,
2405 BPF_MAIN_FUNC /* callsite */,
2406 0 /* frameno within this callchain */,
2407 subprog /* subprog number within this prog */);
2408 elem->st.frame[0] = frame;
2411 free_verifier_state(env->cur_state, true);
2412 env->cur_state = NULL;
2413 /* pop all elements and return */
2414 while (!pop_stack(env, NULL, NULL, false));
2420 SRC_OP, /* register is used as source operand */
2421 DST_OP, /* register is used as destination operand */
2422 DST_OP_NO_MARK /* same as above, check only, don't mark */
2425 static int cmp_subprogs(const void *a, const void *b)
2427 return ((struct bpf_subprog_info *)a)->start -
2428 ((struct bpf_subprog_info *)b)->start;
2431 static int find_subprog(struct bpf_verifier_env *env, int off)
2433 struct bpf_subprog_info *p;
2435 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2436 sizeof(env->subprog_info[0]), cmp_subprogs);
2439 return p - env->subprog_info;
2443 static int add_subprog(struct bpf_verifier_env *env, int off)
2445 int insn_cnt = env->prog->len;
2448 if (off >= insn_cnt || off < 0) {
2449 verbose(env, "call to invalid destination\n");
2452 ret = find_subprog(env, off);
2455 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2456 verbose(env, "too many subprograms\n");
2459 /* determine subprog starts. The end is one before the next starts */
2460 env->subprog_info[env->subprog_cnt++].start = off;
2461 sort(env->subprog_info, env->subprog_cnt,
2462 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2463 return env->subprog_cnt - 1;
2466 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2468 struct bpf_prog_aux *aux = env->prog->aux;
2469 struct btf *btf = aux->btf;
2470 const struct btf_type *t;
2471 u32 main_btf_id, id;
2475 /* Non-zero func_info_cnt implies valid btf */
2476 if (!aux->func_info_cnt)
2478 main_btf_id = aux->func_info[0].type_id;
2480 t = btf_type_by_id(btf, main_btf_id);
2482 verbose(env, "invalid btf id for main subprog in func_info\n");
2486 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2488 ret = PTR_ERR(name);
2489 /* If there is no tag present, there is no exception callback */
2492 else if (ret == -EEXIST)
2493 verbose(env, "multiple exception callback tags for main subprog\n");
2497 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2499 verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2503 t = btf_type_by_id(btf, id);
2504 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2505 verbose(env, "exception callback '%s' must have global linkage\n", name);
2509 for (i = 0; i < aux->func_info_cnt; i++) {
2510 if (aux->func_info[i].type_id != id)
2512 ret = aux->func_info[i].insn_off;
2513 /* Further func_info and subprog checks will also happen
2514 * later, so assume this is the right insn_off for now.
2517 verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2522 verbose(env, "exception callback type id not found in func_info\n");
2528 #define MAX_KFUNC_DESCS 256
2529 #define MAX_KFUNC_BTFS 256
2531 struct bpf_kfunc_desc {
2532 struct btf_func_model func_model;
2539 struct bpf_kfunc_btf {
2541 struct module *module;
2545 struct bpf_kfunc_desc_tab {
2546 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2547 * verification. JITs do lookups by bpf_insn, where func_id may not be
2548 * available, therefore at the end of verification do_misc_fixups()
2549 * sorts this by imm and offset.
2551 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2555 struct bpf_kfunc_btf_tab {
2556 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2560 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2562 const struct bpf_kfunc_desc *d0 = a;
2563 const struct bpf_kfunc_desc *d1 = b;
2565 /* func_id is not greater than BTF_MAX_TYPE */
2566 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2569 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2571 const struct bpf_kfunc_btf *d0 = a;
2572 const struct bpf_kfunc_btf *d1 = b;
2574 return d0->offset - d1->offset;
2577 static const struct bpf_kfunc_desc *
2578 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2580 struct bpf_kfunc_desc desc = {
2584 struct bpf_kfunc_desc_tab *tab;
2586 tab = prog->aux->kfunc_tab;
2587 return bsearch(&desc, tab->descs, tab->nr_descs,
2588 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2591 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2592 u16 btf_fd_idx, u8 **func_addr)
2594 const struct bpf_kfunc_desc *desc;
2596 desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2600 *func_addr = (u8 *)desc->addr;
2604 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2607 struct bpf_kfunc_btf kf_btf = { .offset = offset };
2608 struct bpf_kfunc_btf_tab *tab;
2609 struct bpf_kfunc_btf *b;
2614 tab = env->prog->aux->kfunc_btf_tab;
2615 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2616 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2618 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2619 verbose(env, "too many different module BTFs\n");
2620 return ERR_PTR(-E2BIG);
2623 if (bpfptr_is_null(env->fd_array)) {
2624 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2625 return ERR_PTR(-EPROTO);
2628 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2629 offset * sizeof(btf_fd),
2631 return ERR_PTR(-EFAULT);
2633 btf = btf_get_by_fd(btf_fd);
2635 verbose(env, "invalid module BTF fd specified\n");
2639 if (!btf_is_module(btf)) {
2640 verbose(env, "BTF fd for kfunc is not a module BTF\n");
2642 return ERR_PTR(-EINVAL);
2645 mod = btf_try_get_module(btf);
2648 return ERR_PTR(-ENXIO);
2651 b = &tab->descs[tab->nr_descs++];
2656 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2657 kfunc_btf_cmp_by_off, NULL);
2662 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2667 while (tab->nr_descs--) {
2668 module_put(tab->descs[tab->nr_descs].module);
2669 btf_put(tab->descs[tab->nr_descs].btf);
2674 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2678 /* In the future, this can be allowed to increase limit
2679 * of fd index into fd_array, interpreted as u16.
2681 verbose(env, "negative offset disallowed for kernel module function call\n");
2682 return ERR_PTR(-EINVAL);
2685 return __find_kfunc_desc_btf(env, offset);
2687 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2690 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2692 const struct btf_type *func, *func_proto;
2693 struct bpf_kfunc_btf_tab *btf_tab;
2694 struct bpf_kfunc_desc_tab *tab;
2695 struct bpf_prog_aux *prog_aux;
2696 struct bpf_kfunc_desc *desc;
2697 const char *func_name;
2698 struct btf *desc_btf;
2699 unsigned long call_imm;
2703 prog_aux = env->prog->aux;
2704 tab = prog_aux->kfunc_tab;
2705 btf_tab = prog_aux->kfunc_btf_tab;
2708 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2712 if (!env->prog->jit_requested) {
2713 verbose(env, "JIT is required for calling kernel function\n");
2717 if (!bpf_jit_supports_kfunc_call()) {
2718 verbose(env, "JIT does not support calling kernel function\n");
2722 if (!env->prog->gpl_compatible) {
2723 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2727 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2730 prog_aux->kfunc_tab = tab;
2733 /* func_id == 0 is always invalid, but instead of returning an error, be
2734 * conservative and wait until the code elimination pass before returning
2735 * error, so that invalid calls that get pruned out can be in BPF programs
2736 * loaded from userspace. It is also required that offset be untouched
2739 if (!func_id && !offset)
2742 if (!btf_tab && offset) {
2743 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2746 prog_aux->kfunc_btf_tab = btf_tab;
2749 desc_btf = find_kfunc_desc_btf(env, offset);
2750 if (IS_ERR(desc_btf)) {
2751 verbose(env, "failed to find BTF for kernel function\n");
2752 return PTR_ERR(desc_btf);
2755 if (find_kfunc_desc(env->prog, func_id, offset))
2758 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2759 verbose(env, "too many different kernel function calls\n");
2763 func = btf_type_by_id(desc_btf, func_id);
2764 if (!func || !btf_type_is_func(func)) {
2765 verbose(env, "kernel btf_id %u is not a function\n",
2769 func_proto = btf_type_by_id(desc_btf, func->type);
2770 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2771 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2776 func_name = btf_name_by_offset(desc_btf, func->name_off);
2777 addr = kallsyms_lookup_name(func_name);
2779 verbose(env, "cannot find address for kernel function %s\n",
2783 specialize_kfunc(env, func_id, offset, &addr);
2785 if (bpf_jit_supports_far_kfunc_call()) {
2788 call_imm = BPF_CALL_IMM(addr);
2789 /* Check whether the relative offset overflows desc->imm */
2790 if ((unsigned long)(s32)call_imm != call_imm) {
2791 verbose(env, "address of kernel function %s is out of range\n",
2797 if (bpf_dev_bound_kfunc_id(func_id)) {
2798 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2803 desc = &tab->descs[tab->nr_descs++];
2804 desc->func_id = func_id;
2805 desc->imm = call_imm;
2806 desc->offset = offset;
2808 err = btf_distill_func_proto(&env->log, desc_btf,
2809 func_proto, func_name,
2812 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2813 kfunc_desc_cmp_by_id_off, NULL);
2817 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2819 const struct bpf_kfunc_desc *d0 = a;
2820 const struct bpf_kfunc_desc *d1 = b;
2822 if (d0->imm != d1->imm)
2823 return d0->imm < d1->imm ? -1 : 1;
2824 if (d0->offset != d1->offset)
2825 return d0->offset < d1->offset ? -1 : 1;
2829 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2831 struct bpf_kfunc_desc_tab *tab;
2833 tab = prog->aux->kfunc_tab;
2837 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2838 kfunc_desc_cmp_by_imm_off, NULL);
2841 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2843 return !!prog->aux->kfunc_tab;
2846 const struct btf_func_model *
2847 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2848 const struct bpf_insn *insn)
2850 const struct bpf_kfunc_desc desc = {
2852 .offset = insn->off,
2854 const struct bpf_kfunc_desc *res;
2855 struct bpf_kfunc_desc_tab *tab;
2857 tab = prog->aux->kfunc_tab;
2858 res = bsearch(&desc, tab->descs, tab->nr_descs,
2859 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2861 return res ? &res->func_model : NULL;
2864 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2866 struct bpf_subprog_info *subprog = env->subprog_info;
2867 int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2868 struct bpf_insn *insn = env->prog->insnsi;
2870 /* Add entry function. */
2871 ret = add_subprog(env, 0);
2875 for (i = 0; i < insn_cnt; i++, insn++) {
2876 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2877 !bpf_pseudo_kfunc_call(insn))
2880 if (!env->bpf_capable) {
2881 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2885 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2886 ret = add_subprog(env, i + insn->imm + 1);
2888 ret = add_kfunc_call(env, insn->imm, insn->off);
2894 ret = bpf_find_exception_callback_insn_off(env);
2899 /* If ex_cb_insn > 0, this means that the main program has a subprog
2900 * marked using BTF decl tag to serve as the exception callback.
2903 ret = add_subprog(env, ex_cb_insn);
2906 for (i = 1; i < env->subprog_cnt; i++) {
2907 if (env->subprog_info[i].start != ex_cb_insn)
2909 env->exception_callback_subprog = i;
2910 mark_subprog_exc_cb(env, i);
2915 /* Add a fake 'exit' subprog which could simplify subprog iteration
2916 * logic. 'subprog_cnt' should not be increased.
2918 subprog[env->subprog_cnt].start = insn_cnt;
2920 if (env->log.level & BPF_LOG_LEVEL2)
2921 for (i = 0; i < env->subprog_cnt; i++)
2922 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2927 static int check_subprogs(struct bpf_verifier_env *env)
2929 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2930 struct bpf_subprog_info *subprog = env->subprog_info;
2931 struct bpf_insn *insn = env->prog->insnsi;
2932 int insn_cnt = env->prog->len;
2934 /* now check that all jumps are within the same subprog */
2935 subprog_start = subprog[cur_subprog].start;
2936 subprog_end = subprog[cur_subprog + 1].start;
2937 for (i = 0; i < insn_cnt; i++) {
2938 u8 code = insn[i].code;
2940 if (code == (BPF_JMP | BPF_CALL) &&
2941 insn[i].src_reg == 0 &&
2942 insn[i].imm == BPF_FUNC_tail_call)
2943 subprog[cur_subprog].has_tail_call = true;
2944 if (BPF_CLASS(code) == BPF_LD &&
2945 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2946 subprog[cur_subprog].has_ld_abs = true;
2947 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2949 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2951 if (code == (BPF_JMP32 | BPF_JA))
2952 off = i + insn[i].imm + 1;
2954 off = i + insn[i].off + 1;
2955 if (off < subprog_start || off >= subprog_end) {
2956 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2960 if (i == subprog_end - 1) {
2961 /* to avoid fall-through from one subprog into another
2962 * the last insn of the subprog should be either exit
2963 * or unconditional jump back or bpf_throw call
2965 if (code != (BPF_JMP | BPF_EXIT) &&
2966 code != (BPF_JMP32 | BPF_JA) &&
2967 code != (BPF_JMP | BPF_JA)) {
2968 verbose(env, "last insn is not an exit or jmp\n");
2971 subprog_start = subprog_end;
2973 if (cur_subprog < env->subprog_cnt)
2974 subprog_end = subprog[cur_subprog + 1].start;
2980 /* Parentage chain of this register (or stack slot) should take care of all
2981 * issues like callee-saved registers, stack slot allocation time, etc.
2983 static int mark_reg_read(struct bpf_verifier_env *env,
2984 const struct bpf_reg_state *state,
2985 struct bpf_reg_state *parent, u8 flag)
2987 bool writes = parent == state->parent; /* Observe write marks */
2991 /* if read wasn't screened by an earlier write ... */
2992 if (writes && state->live & REG_LIVE_WRITTEN)
2994 if (parent->live & REG_LIVE_DONE) {
2995 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2996 reg_type_str(env, parent->type),
2997 parent->var_off.value, parent->off);
3000 /* The first condition is more likely to be true than the
3001 * second, checked it first.
3003 if ((parent->live & REG_LIVE_READ) == flag ||
3004 parent->live & REG_LIVE_READ64)
3005 /* The parentage chain never changes and
3006 * this parent was already marked as LIVE_READ.
3007 * There is no need to keep walking the chain again and
3008 * keep re-marking all parents as LIVE_READ.
3009 * This case happens when the same register is read
3010 * multiple times without writes into it in-between.
3011 * Also, if parent has the stronger REG_LIVE_READ64 set,
3012 * then no need to set the weak REG_LIVE_READ32.
3015 /* ... then we depend on parent's value */
3016 parent->live |= flag;
3017 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3018 if (flag == REG_LIVE_READ64)
3019 parent->live &= ~REG_LIVE_READ32;
3021 parent = state->parent;
3026 if (env->longest_mark_read_walk < cnt)
3027 env->longest_mark_read_walk = cnt;
3031 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3033 struct bpf_func_state *state = func(env, reg);
3036 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
3037 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3040 if (reg->type == CONST_PTR_TO_DYNPTR)
3042 spi = dynptr_get_spi(env, reg);
3045 /* Caller ensures dynptr is valid and initialized, which means spi is in
3046 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3049 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3050 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3053 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3054 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3057 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3058 int spi, int nr_slots)
3060 struct bpf_func_state *state = func(env, reg);
3063 for (i = 0; i < nr_slots; i++) {
3064 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3066 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3070 mark_stack_slot_scratched(env, spi - i);
3076 /* This function is supposed to be used by the following 32-bit optimization
3077 * code only. It returns TRUE if the source or destination register operates
3078 * on 64-bit, otherwise return FALSE.
3080 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3081 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3086 class = BPF_CLASS(code);
3088 if (class == BPF_JMP) {
3089 /* BPF_EXIT for "main" will reach here. Return TRUE
3094 if (op == BPF_CALL) {
3095 /* BPF to BPF call will reach here because of marking
3096 * caller saved clobber with DST_OP_NO_MARK for which we
3097 * don't care the register def because they are anyway
3098 * marked as NOT_INIT already.
3100 if (insn->src_reg == BPF_PSEUDO_CALL)
3102 /* Helper call will reach here because of arg type
3103 * check, conservatively return TRUE.
3112 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3115 if (class == BPF_ALU64 || class == BPF_JMP ||
3116 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3119 if (class == BPF_ALU || class == BPF_JMP32)
3122 if (class == BPF_LDX) {
3124 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3125 /* LDX source must be ptr. */
3129 if (class == BPF_STX) {
3130 /* BPF_STX (including atomic variants) has multiple source
3131 * operands, one of which is a ptr. Check whether the caller is
3134 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3136 return BPF_SIZE(code) == BPF_DW;
3139 if (class == BPF_LD) {
3140 u8 mode = BPF_MODE(code);
3143 if (mode == BPF_IMM)
3146 /* Both LD_IND and LD_ABS return 32-bit data. */
3150 /* Implicit ctx ptr. */
3151 if (regno == BPF_REG_6)
3154 /* Explicit source could be any width. */
3158 if (class == BPF_ST)
3159 /* The only source register for BPF_ST is a ptr. */
3162 /* Conservatively return true at default. */
3166 /* Return the regno defined by the insn, or -1. */
3167 static int insn_def_regno(const struct bpf_insn *insn)
3169 switch (BPF_CLASS(insn->code)) {
3175 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3176 (insn->imm & BPF_FETCH)) {
3177 if (insn->imm == BPF_CMPXCHG)
3180 return insn->src_reg;
3185 return insn->dst_reg;
3189 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3190 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3192 int dst_reg = insn_def_regno(insn);
3197 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3200 static void mark_insn_zext(struct bpf_verifier_env *env,
3201 struct bpf_reg_state *reg)
3203 s32 def_idx = reg->subreg_def;
3205 if (def_idx == DEF_NOT_SUBREG)
3208 env->insn_aux_data[def_idx - 1].zext_dst = true;
3209 /* The dst will be zero extended, so won't be sub-register anymore. */
3210 reg->subreg_def = DEF_NOT_SUBREG;
3213 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3214 enum reg_arg_type t)
3216 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3217 struct bpf_reg_state *reg;
3220 if (regno >= MAX_BPF_REG) {
3221 verbose(env, "R%d is invalid\n", regno);
3225 mark_reg_scratched(env, regno);
3228 rw64 = is_reg64(env, insn, regno, reg, t);
3230 /* check whether register used as source operand can be read */
3231 if (reg->type == NOT_INIT) {
3232 verbose(env, "R%d !read_ok\n", regno);
3235 /* We don't need to worry about FP liveness because it's read-only */
3236 if (regno == BPF_REG_FP)
3240 mark_insn_zext(env, reg);
3242 return mark_reg_read(env, reg, reg->parent,
3243 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3245 /* check whether register used as dest operand can be written to */
3246 if (regno == BPF_REG_FP) {
3247 verbose(env, "frame pointer is read only\n");
3250 reg->live |= REG_LIVE_WRITTEN;
3251 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3253 mark_reg_unknown(env, regs, regno);
3258 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3259 enum reg_arg_type t)
3261 struct bpf_verifier_state *vstate = env->cur_state;
3262 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3264 return __check_reg_arg(env, state->regs, regno, t);
3267 static int insn_stack_access_flags(int frameno, int spi)
3269 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3272 static int insn_stack_access_spi(int insn_flags)
3274 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3277 static int insn_stack_access_frameno(int insn_flags)
3279 return insn_flags & INSN_F_FRAMENO_MASK;
3282 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3284 env->insn_aux_data[idx].jmp_point = true;
3287 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3289 return env->insn_aux_data[insn_idx].jmp_point;
3292 /* for any branch, call, exit record the history of jmps in the given state */
3293 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3296 u32 cnt = cur->jmp_history_cnt;
3297 struct bpf_jmp_history_entry *p;
3300 /* combine instruction flags if we already recorded this instruction */
3301 if (env->cur_hist_ent) {
3302 /* atomic instructions push insn_flags twice, for READ and
3303 * WRITE sides, but they should agree on stack slot
3305 WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
3306 (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3307 "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
3308 env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3309 env->cur_hist_ent->flags |= insn_flags;
3314 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3315 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3318 cur->jmp_history = p;
3320 p = &cur->jmp_history[cnt - 1];
3321 p->idx = env->insn_idx;
3322 p->prev_idx = env->prev_insn_idx;
3323 p->flags = insn_flags;
3324 cur->jmp_history_cnt = cnt;
3325 env->cur_hist_ent = p;
3330 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3331 u32 hist_end, int insn_idx)
3333 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3334 return &st->jmp_history[hist_end - 1];
3338 /* Backtrack one insn at a time. If idx is not at the top of recorded
3339 * history then previous instruction came from straight line execution.
3340 * Return -ENOENT if we exhausted all instructions within given state.
3342 * It's legal to have a bit of a looping with the same starting and ending
3343 * insn index within the same state, e.g.: 3->4->5->3, so just because current
3344 * instruction index is the same as state's first_idx doesn't mean we are
3345 * done. If there is still some jump history left, we should keep going. We
3346 * need to take into account that we might have a jump history between given
3347 * state's parent and itself, due to checkpointing. In this case, we'll have
3348 * history entry recording a jump from last instruction of parent state and
3349 * first instruction of given state.
3351 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3356 if (i == st->first_insn_idx) {
3359 if (cnt == 1 && st->jmp_history[0].idx == i)
3363 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3364 i = st->jmp_history[cnt - 1].prev_idx;
3372 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3374 const struct btf_type *func;
3375 struct btf *desc_btf;
3377 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3380 desc_btf = find_kfunc_desc_btf(data, insn->off);
3381 if (IS_ERR(desc_btf))
3384 func = btf_type_by_id(desc_btf, insn->imm);
3385 return btf_name_by_offset(desc_btf, func->name_off);
3388 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3393 static inline void bt_reset(struct backtrack_state *bt)
3395 struct bpf_verifier_env *env = bt->env;
3397 memset(bt, 0, sizeof(*bt));
3401 static inline u32 bt_empty(struct backtrack_state *bt)
3406 for (i = 0; i <= bt->frame; i++)
3407 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3412 static inline int bt_subprog_enter(struct backtrack_state *bt)
3414 if (bt->frame == MAX_CALL_FRAMES - 1) {
3415 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3416 WARN_ONCE(1, "verifier backtracking bug");
3423 static inline int bt_subprog_exit(struct backtrack_state *bt)
3425 if (bt->frame == 0) {
3426 verbose(bt->env, "BUG subprog exit from frame 0\n");
3427 WARN_ONCE(1, "verifier backtracking bug");
3434 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3436 bt->reg_masks[frame] |= 1 << reg;
3439 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3441 bt->reg_masks[frame] &= ~(1 << reg);
3444 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3446 bt_set_frame_reg(bt, bt->frame, reg);
3449 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3451 bt_clear_frame_reg(bt, bt->frame, reg);
3454 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3456 bt->stack_masks[frame] |= 1ull << slot;
3459 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3461 bt->stack_masks[frame] &= ~(1ull << slot);
3464 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3466 return bt->reg_masks[frame];
3469 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3471 return bt->reg_masks[bt->frame];
3474 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3476 return bt->stack_masks[frame];
3479 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3481 return bt->stack_masks[bt->frame];
3484 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3486 return bt->reg_masks[bt->frame] & (1 << reg);
3489 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
3491 return bt->stack_masks[frame] & (1ull << slot);
3494 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3495 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3497 DECLARE_BITMAP(mask, 64);
3503 bitmap_from_u64(mask, reg_mask);
3504 for_each_set_bit(i, mask, 32) {
3505 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3513 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3514 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3516 DECLARE_BITMAP(mask, 64);
3522 bitmap_from_u64(mask, stack_mask);
3523 for_each_set_bit(i, mask, 64) {
3524 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3533 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3535 /* For given verifier state backtrack_insn() is called from the last insn to
3536 * the first insn. Its purpose is to compute a bitmask of registers and
3537 * stack slots that needs precision in the parent verifier state.
3539 * @idx is an index of the instruction we are currently processing;
3540 * @subseq_idx is an index of the subsequent instruction that:
3541 * - *would be* executed next, if jump history is viewed in forward order;
3542 * - *was* processed previously during backtracking.
3544 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3545 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
3547 const struct bpf_insn_cbs cbs = {
3548 .cb_call = disasm_kfunc_name,
3549 .cb_print = verbose,
3550 .private_data = env,
3552 struct bpf_insn *insn = env->prog->insnsi + idx;
3553 u8 class = BPF_CLASS(insn->code);
3554 u8 opcode = BPF_OP(insn->code);
3555 u8 mode = BPF_MODE(insn->code);
3556 u32 dreg = insn->dst_reg;
3557 u32 sreg = insn->src_reg;
3560 if (insn->code == 0)
3562 if (env->log.level & BPF_LOG_LEVEL2) {
3563 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3564 verbose(env, "mark_precise: frame%d: regs=%s ",
3565 bt->frame, env->tmp_str_buf);
3566 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3567 verbose(env, "stack=%s before ", env->tmp_str_buf);
3568 verbose(env, "%d: ", idx);
3569 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3572 if (class == BPF_ALU || class == BPF_ALU64) {
3573 if (!bt_is_reg_set(bt, dreg))
3575 if (opcode == BPF_END || opcode == BPF_NEG) {
3576 /* sreg is reserved and unused
3577 * dreg still need precision before this insn
3580 } else if (opcode == BPF_MOV) {
3581 if (BPF_SRC(insn->code) == BPF_X) {
3582 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3583 * dreg needs precision after this insn
3584 * sreg needs precision before this insn
3586 bt_clear_reg(bt, dreg);
3587 bt_set_reg(bt, sreg);
3590 * dreg needs precision after this insn.
3591 * Corresponding register is already marked
3592 * as precise=true in this verifier state.
3593 * No further markings in parent are necessary
3595 bt_clear_reg(bt, dreg);
3598 if (BPF_SRC(insn->code) == BPF_X) {
3600 * both dreg and sreg need precision
3603 bt_set_reg(bt, sreg);
3605 * dreg still needs precision before this insn
3608 } else if (class == BPF_LDX) {
3609 if (!bt_is_reg_set(bt, dreg))
3611 bt_clear_reg(bt, dreg);
3613 /* scalars can only be spilled into stack w/o losing precision.
3614 * Load from any other memory can be zero extended.
3615 * The desire to keep that precision is already indicated
3616 * by 'precise' mark in corresponding register of this state.
3617 * No further tracking necessary.
3619 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3621 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3622 * that [fp - off] slot contains scalar that needs to be
3623 * tracked with precision
3625 spi = insn_stack_access_spi(hist->flags);
3626 fr = insn_stack_access_frameno(hist->flags);
3627 bt_set_frame_slot(bt, fr, spi);
3628 } else if (class == BPF_STX || class == BPF_ST) {
3629 if (bt_is_reg_set(bt, dreg))
3630 /* stx & st shouldn't be using _scalar_ dst_reg
3631 * to access memory. It means backtracking
3632 * encountered a case of pointer subtraction.
3635 /* scalars can only be spilled into stack */
3636 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3638 spi = insn_stack_access_spi(hist->flags);
3639 fr = insn_stack_access_frameno(hist->flags);
3640 if (!bt_is_frame_slot_set(bt, fr, spi))
3642 bt_clear_frame_slot(bt, fr, spi);
3643 if (class == BPF_STX)
3644 bt_set_reg(bt, sreg);
3645 } else if (class == BPF_JMP || class == BPF_JMP32) {
3646 if (bpf_pseudo_call(insn)) {
3647 int subprog_insn_idx, subprog;
3649 subprog_insn_idx = idx + insn->imm + 1;
3650 subprog = find_subprog(env, subprog_insn_idx);
3654 if (subprog_is_global(env, subprog)) {
3655 /* check that jump history doesn't have any
3656 * extra instructions from subprog; the next
3657 * instruction after call to global subprog
3658 * should be literally next instruction in
3661 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3662 /* r1-r5 are invalidated after subprog call,
3663 * so for global func call it shouldn't be set
3666 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3667 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3668 WARN_ONCE(1, "verifier backtracking bug");
3671 /* global subprog always sets R0 */
3672 bt_clear_reg(bt, BPF_REG_0);
3675 /* static subprog call instruction, which
3676 * means that we are exiting current subprog,
3677 * so only r1-r5 could be still requested as
3678 * precise, r0 and r6-r10 or any stack slot in
3679 * the current frame should be zero by now
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 /* we are now tracking register spills correctly,
3687 * so any instance of leftover slots is a bug
3689 if (bt_stack_mask(bt) != 0) {
3690 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3691 WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
3694 /* propagate r1-r5 to the caller */
3695 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3696 if (bt_is_reg_set(bt, i)) {
3697 bt_clear_reg(bt, i);
3698 bt_set_frame_reg(bt, bt->frame - 1, i);
3701 if (bt_subprog_exit(bt))
3705 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3706 /* exit from callback subprog to callback-calling helper or
3707 * kfunc call. Use idx/subseq_idx check to discern it from
3708 * straight line code backtracking.
3709 * Unlike the subprog call handling above, we shouldn't
3710 * propagate precision of r1-r5 (if any requested), as they are
3711 * not actually arguments passed directly to callback subprogs
3713 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3714 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3715 WARN_ONCE(1, "verifier backtracking bug");
3718 if (bt_stack_mask(bt) != 0) {
3719 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3720 WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
3723 /* clear r1-r5 in callback subprog's mask */
3724 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3725 bt_clear_reg(bt, i);
3726 if (bt_subprog_exit(bt))
3729 } else if (opcode == BPF_CALL) {
3730 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3731 * catch this error later. Make backtracking conservative
3734 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3736 /* regular helper call sets R0 */
3737 bt_clear_reg(bt, BPF_REG_0);
3738 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3739 /* if backtracing was looking for registers R1-R5
3740 * they should have been found already.
3742 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3743 WARN_ONCE(1, "verifier backtracking bug");
3746 } else if (opcode == BPF_EXIT) {
3749 /* Backtracking to a nested function call, 'idx' is a part of
3750 * the inner frame 'subseq_idx' is a part of the outer frame.
3751 * In case of a regular function call, instructions giving
3752 * precision to registers R1-R5 should have been found already.
3753 * In case of a callback, it is ok to have R1-R5 marked for
3754 * backtracking, as these registers are set by the function
3755 * invoking callback.
3757 if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3758 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3759 bt_clear_reg(bt, i);
3760 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3761 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3762 WARN_ONCE(1, "verifier backtracking bug");
3766 /* BPF_EXIT in subprog or callback always returns
3767 * right after the call instruction, so by checking
3768 * whether the instruction at subseq_idx-1 is subprog
3769 * call or not we can distinguish actual exit from
3770 * *subprog* from exit from *callback*. In the former
3771 * case, we need to propagate r0 precision, if
3772 * necessary. In the former we never do that.
3774 r0_precise = subseq_idx - 1 >= 0 &&
3775 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3776 bt_is_reg_set(bt, BPF_REG_0);
3778 bt_clear_reg(bt, BPF_REG_0);
3779 if (bt_subprog_enter(bt))
3783 bt_set_reg(bt, BPF_REG_0);
3784 /* r6-r9 and stack slots will stay set in caller frame
3785 * bitmasks until we return back from callee(s)
3788 } else if (BPF_SRC(insn->code) == BPF_X) {
3789 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3792 * Both dreg and sreg need precision before
3793 * this insn. If only sreg was marked precise
3794 * before it would be equally necessary to
3795 * propagate it to dreg.
3797 bt_set_reg(bt, dreg);
3798 bt_set_reg(bt, sreg);
3799 /* else dreg <cond> K
3800 * Only dreg still needs precision before
3801 * this insn, so for the K-based conditional
3802 * there is nothing new to be marked.
3805 } else if (class == BPF_LD) {
3806 if (!bt_is_reg_set(bt, dreg))
3808 bt_clear_reg(bt, dreg);
3809 /* It's ld_imm64 or ld_abs or ld_ind.
3810 * For ld_imm64 no further tracking of precision
3811 * into parent is necessary
3813 if (mode == BPF_IND || mode == BPF_ABS)
3814 /* to be analyzed */
3820 /* the scalar precision tracking algorithm:
3821 * . at the start all registers have precise=false.
3822 * . scalar ranges are tracked as normal through alu and jmp insns.
3823 * . once precise value of the scalar register is used in:
3824 * . ptr + scalar alu
3825 * . if (scalar cond K|scalar)
3826 * . helper_call(.., scalar, ...) where ARG_CONST is expected
3827 * backtrack through the verifier states and mark all registers and
3828 * stack slots with spilled constants that these scalar regisers
3829 * should be precise.
3830 * . during state pruning two registers (or spilled stack slots)
3831 * are equivalent if both are not precise.
3833 * Note the verifier cannot simply walk register parentage chain,
3834 * since many different registers and stack slots could have been
3835 * used to compute single precise scalar.
3837 * The approach of starting with precise=true for all registers and then
3838 * backtrack to mark a register as not precise when the verifier detects
3839 * that program doesn't care about specific value (e.g., when helper
3840 * takes register as ARG_ANYTHING parameter) is not safe.
3842 * It's ok to walk single parentage chain of the verifier states.
3843 * It's possible that this backtracking will go all the way till 1st insn.
3844 * All other branches will be explored for needing precision later.
3846 * The backtracking needs to deal with cases like:
3847 * 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)
3850 * if r5 > 0x79f goto pc+7
3851 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3854 * call bpf_perf_event_output#25
3855 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3859 * call foo // uses callee's r6 inside to compute r0
3863 * to track above reg_mask/stack_mask needs to be independent for each frame.
3865 * Also if parent's curframe > frame where backtracking started,
3866 * the verifier need to mark registers in both frames, otherwise callees
3867 * may incorrectly prune callers. This is similar to
3868 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3870 * For now backtracking falls back into conservative marking.
3872 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3873 struct bpf_verifier_state *st)
3875 struct bpf_func_state *func;
3876 struct bpf_reg_state *reg;
3879 if (env->log.level & BPF_LOG_LEVEL2) {
3880 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3884 /* big hammer: mark all scalars precise in this path.
3885 * pop_stack may still get !precise scalars.
3886 * We also skip current state and go straight to first parent state,
3887 * because precision markings in current non-checkpointed state are
3888 * not needed. See why in the comment in __mark_chain_precision below.
3890 for (st = st->parent; st; st = st->parent) {
3891 for (i = 0; i <= st->curframe; i++) {
3892 func = st->frame[i];
3893 for (j = 0; j < BPF_REG_FP; j++) {
3894 reg = &func->regs[j];
3895 if (reg->type != SCALAR_VALUE || reg->precise)
3897 reg->precise = true;
3898 if (env->log.level & BPF_LOG_LEVEL2) {
3899 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3903 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3904 if (!is_spilled_reg(&func->stack[j]))
3906 reg = &func->stack[j].spilled_ptr;
3907 if (reg->type != SCALAR_VALUE || reg->precise)
3909 reg->precise = true;
3910 if (env->log.level & BPF_LOG_LEVEL2) {
3911 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3919 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3921 struct bpf_func_state *func;
3922 struct bpf_reg_state *reg;
3925 for (i = 0; i <= st->curframe; i++) {
3926 func = st->frame[i];
3927 for (j = 0; j < BPF_REG_FP; j++) {
3928 reg = &func->regs[j];
3929 if (reg->type != SCALAR_VALUE)
3931 reg->precise = false;
3933 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3934 if (!is_spilled_reg(&func->stack[j]))
3936 reg = &func->stack[j].spilled_ptr;
3937 if (reg->type != SCALAR_VALUE)
3939 reg->precise = false;
3944 static bool idset_contains(struct bpf_idset *s, u32 id)
3948 for (i = 0; i < s->count; ++i)
3949 if (s->ids[i] == id)
3955 static int idset_push(struct bpf_idset *s, u32 id)
3957 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3959 s->ids[s->count++] = id;
3963 static void idset_reset(struct bpf_idset *s)
3968 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3969 * Mark all registers with these IDs as precise.
3971 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3973 struct bpf_idset *precise_ids = &env->idset_scratch;
3974 struct backtrack_state *bt = &env->bt;
3975 struct bpf_func_state *func;
3976 struct bpf_reg_state *reg;
3977 DECLARE_BITMAP(mask, 64);
3980 idset_reset(precise_ids);
3982 for (fr = bt->frame; fr >= 0; fr--) {
3983 func = st->frame[fr];
3985 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3986 for_each_set_bit(i, mask, 32) {
3987 reg = &func->regs[i];
3988 if (!reg->id || reg->type != SCALAR_VALUE)
3990 if (idset_push(precise_ids, reg->id))
3994 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3995 for_each_set_bit(i, mask, 64) {
3996 if (i >= func->allocated_stack / BPF_REG_SIZE)
3998 if (!is_spilled_scalar_reg(&func->stack[i]))
4000 reg = &func->stack[i].spilled_ptr;
4003 if (idset_push(precise_ids, reg->id))
4008 for (fr = 0; fr <= st->curframe; ++fr) {
4009 func = st->frame[fr];
4011 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4012 reg = &func->regs[i];
4015 if (!idset_contains(precise_ids, reg->id))
4017 bt_set_frame_reg(bt, fr, i);
4019 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4020 if (!is_spilled_scalar_reg(&func->stack[i]))
4022 reg = &func->stack[i].spilled_ptr;
4025 if (!idset_contains(precise_ids, reg->id))
4027 bt_set_frame_slot(bt, fr, i);
4035 * __mark_chain_precision() backtracks BPF program instruction sequence and
4036 * chain of verifier states making sure that register *regno* (if regno >= 0)
4037 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4038 * SCALARS, as well as any other registers and slots that contribute to
4039 * a tracked state of given registers/stack slots, depending on specific BPF
4040 * assembly instructions (see backtrack_insns() for exact instruction handling
4041 * logic). This backtracking relies on recorded jmp_history and is able to
4042 * traverse entire chain of parent states. This process ends only when all the
4043 * necessary registers/slots and their transitive dependencies are marked as
4046 * One important and subtle aspect is that precise marks *do not matter* in
4047 * the currently verified state (current state). It is important to understand
4048 * why this is the case.
4050 * First, note that current state is the state that is not yet "checkpointed",
4051 * i.e., it is not yet put into env->explored_states, and it has no children
4052 * states as well. It's ephemeral, and can end up either a) being discarded if
4053 * compatible explored state is found at some point or BPF_EXIT instruction is
4054 * reached or b) checkpointed and put into env->explored_states, branching out
4055 * into one or more children states.
4057 * In the former case, precise markings in current state are completely
4058 * ignored by state comparison code (see regsafe() for details). Only
4059 * checkpointed ("old") state precise markings are important, and if old
4060 * state's register/slot is precise, regsafe() assumes current state's
4061 * register/slot as precise and checks value ranges exactly and precisely. If
4062 * states turn out to be compatible, current state's necessary precise
4063 * markings and any required parent states' precise markings are enforced
4064 * after the fact with propagate_precision() logic, after the fact. But it's
4065 * important to realize that in this case, even after marking current state
4066 * registers/slots as precise, we immediately discard current state. So what
4067 * actually matters is any of the precise markings propagated into current
4068 * state's parent states, which are always checkpointed (due to b) case above).
4069 * As such, for scenario a) it doesn't matter if current state has precise
4070 * markings set or not.
4072 * Now, for the scenario b), checkpointing and forking into child(ren)
4073 * state(s). Note that before current state gets to checkpointing step, any
4074 * processed instruction always assumes precise SCALAR register/slot
4075 * knowledge: if precise value or range is useful to prune jump branch, BPF
4076 * verifier takes this opportunity enthusiastically. Similarly, when
4077 * register's value is used to calculate offset or memory address, exact
4078 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4079 * what we mentioned above about state comparison ignoring precise markings
4080 * during state comparison, BPF verifier ignores and also assumes precise
4081 * markings *at will* during instruction verification process. But as verifier
4082 * assumes precision, it also propagates any precision dependencies across
4083 * parent states, which are not yet finalized, so can be further restricted
4084 * based on new knowledge gained from restrictions enforced by their children
4085 * states. This is so that once those parent states are finalized, i.e., when
4086 * they have no more active children state, state comparison logic in
4087 * is_state_visited() would enforce strict and precise SCALAR ranges, if
4088 * required for correctness.
4090 * To build a bit more intuition, note also that once a state is checkpointed,
4091 * the path we took to get to that state is not important. This is crucial
4092 * property for state pruning. When state is checkpointed and finalized at
4093 * some instruction index, it can be correctly and safely used to "short
4094 * circuit" any *compatible* state that reaches exactly the same instruction
4095 * index. I.e., if we jumped to that instruction from a completely different
4096 * code path than original finalized state was derived from, it doesn't
4097 * matter, current state can be discarded because from that instruction
4098 * forward having a compatible state will ensure we will safely reach the
4099 * exit. States describe preconditions for further exploration, but completely
4100 * forget the history of how we got here.
4102 * This also means that even if we needed precise SCALAR range to get to
4103 * finalized state, but from that point forward *that same* SCALAR register is
4104 * never used in a precise context (i.e., it's precise value is not needed for
4105 * correctness), it's correct and safe to mark such register as "imprecise"
4106 * (i.e., precise marking set to false). This is what we rely on when we do
4107 * not set precise marking in current state. If no child state requires
4108 * precision for any given SCALAR register, it's safe to dictate that it can
4109 * be imprecise. If any child state does require this register to be precise,
4110 * we'll mark it precise later retroactively during precise markings
4111 * propagation from child state to parent states.
4113 * Skipping precise marking setting in current state is a mild version of
4114 * relying on the above observation. But we can utilize this property even
4115 * more aggressively by proactively forgetting any precise marking in the
4116 * current state (which we inherited from the parent state), right before we
4117 * checkpoint it and branch off into new child state. This is done by
4118 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4119 * finalized states which help in short circuiting more future states.
4121 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4123 struct backtrack_state *bt = &env->bt;
4124 struct bpf_verifier_state *st = env->cur_state;
4125 int first_idx = st->first_insn_idx;
4126 int last_idx = env->insn_idx;
4127 int subseq_idx = -1;
4128 struct bpf_func_state *func;
4129 struct bpf_reg_state *reg;
4130 bool skip_first = true;
4133 if (!env->bpf_capable)
4136 /* set frame number from which we are starting to backtrack */
4137 bt_init(bt, env->cur_state->curframe);
4139 /* Do sanity checks against current state of register and/or stack
4140 * slot, but don't set precise flag in current state, as precision
4141 * tracking in the current state is unnecessary.
4143 func = st->frame[bt->frame];
4145 reg = &func->regs[regno];
4146 if (reg->type != SCALAR_VALUE) {
4147 WARN_ONCE(1, "backtracing misuse");
4150 bt_set_reg(bt, regno);
4157 DECLARE_BITMAP(mask, 64);
4158 u32 history = st->jmp_history_cnt;
4159 struct bpf_jmp_history_entry *hist;
4161 if (env->log.level & BPF_LOG_LEVEL2) {
4162 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4163 bt->frame, last_idx, first_idx, subseq_idx);
4166 /* If some register with scalar ID is marked as precise,
4167 * make sure that all registers sharing this ID are also precise.
4168 * This is needed to estimate effect of find_equal_scalars().
4169 * Do this at the last instruction of each state,
4170 * bpf_reg_state::id fields are valid for these instructions.
4172 * Allows to track precision in situation like below:
4174 * r2 = unknown value
4178 * r1 = r2 // r1 and r2 now share the same ID
4180 * --- state #1 {r1.id = A, r2.id = A} ---
4182 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4184 * --- state #2 {r1.id = A, r2.id = A} ---
4186 * r3 += r1 // need to mark both r1 and r2
4188 if (mark_precise_scalar_ids(env, st))
4192 /* we are at the entry into subprog, which
4193 * is expected for global funcs, but only if
4194 * requested precise registers are R1-R5
4195 * (which are global func's input arguments)
4197 if (st->curframe == 0 &&
4198 st->frame[0]->subprogno > 0 &&
4199 st->frame[0]->callsite == BPF_MAIN_FUNC &&
4200 bt_stack_mask(bt) == 0 &&
4201 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4202 bitmap_from_u64(mask, bt_reg_mask(bt));
4203 for_each_set_bit(i, mask, 32) {
4204 reg = &st->frame[0]->regs[i];
4205 bt_clear_reg(bt, i);
4206 if (reg->type == SCALAR_VALUE)
4207 reg->precise = true;
4212 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4213 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4214 WARN_ONCE(1, "verifier backtracking bug");
4218 for (i = last_idx;;) {
4223 hist = get_jmp_hist_entry(st, history, i);
4224 err = backtrack_insn(env, i, subseq_idx, hist, bt);
4226 if (err == -ENOTSUPP) {
4227 mark_all_scalars_precise(env, env->cur_state);
4234 /* Found assignment(s) into tracked register in this state.
4235 * Since this state is already marked, just return.
4236 * Nothing to be tracked further in the parent state.
4240 i = get_prev_insn_idx(st, i, &history);
4243 if (i >= env->prog->len) {
4244 /* This can happen if backtracking reached insn 0
4245 * and there are still reg_mask or stack_mask
4247 * It means the backtracking missed the spot where
4248 * particular register was initialized with a constant.
4250 verbose(env, "BUG backtracking idx %d\n", i);
4251 WARN_ONCE(1, "verifier backtracking bug");
4259 for (fr = bt->frame; fr >= 0; fr--) {
4260 func = st->frame[fr];
4261 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4262 for_each_set_bit(i, mask, 32) {
4263 reg = &func->regs[i];
4264 if (reg->type != SCALAR_VALUE) {
4265 bt_clear_frame_reg(bt, fr, i);
4269 bt_clear_frame_reg(bt, fr, i);
4271 reg->precise = true;
4274 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4275 for_each_set_bit(i, mask, 64) {
4276 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4277 verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
4278 i, func->allocated_stack / BPF_REG_SIZE);
4279 WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
4283 if (!is_spilled_scalar_reg(&func->stack[i])) {
4284 bt_clear_frame_slot(bt, fr, i);
4287 reg = &func->stack[i].spilled_ptr;
4289 bt_clear_frame_slot(bt, fr, i);
4291 reg->precise = true;
4293 if (env->log.level & BPF_LOG_LEVEL2) {
4294 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4295 bt_frame_reg_mask(bt, fr));
4296 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4297 fr, env->tmp_str_buf);
4298 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4299 bt_frame_stack_mask(bt, fr));
4300 verbose(env, "stack=%s: ", env->tmp_str_buf);
4301 print_verifier_state(env, func, true);
4308 subseq_idx = first_idx;
4309 last_idx = st->last_insn_idx;
4310 first_idx = st->first_insn_idx;
4313 /* if we still have requested precise regs or slots, we missed
4314 * something (e.g., stack access through non-r10 register), so
4315 * fallback to marking all precise
4317 if (!bt_empty(bt)) {
4318 mark_all_scalars_precise(env, env->cur_state);
4325 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4327 return __mark_chain_precision(env, regno);
4330 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4331 * desired reg and stack masks across all relevant frames
4333 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4335 return __mark_chain_precision(env, -1);
4338 static bool is_spillable_regtype(enum bpf_reg_type type)
4340 switch (base_type(type)) {
4341 case PTR_TO_MAP_VALUE:
4345 case PTR_TO_PACKET_META:
4346 case PTR_TO_PACKET_END:
4347 case PTR_TO_FLOW_KEYS:
4348 case CONST_PTR_TO_MAP:
4350 case PTR_TO_SOCK_COMMON:
4351 case PTR_TO_TCP_SOCK:
4352 case PTR_TO_XDP_SOCK:
4357 case PTR_TO_MAP_KEY:
4364 /* Does this register contain a constant zero? */
4365 static bool register_is_null(struct bpf_reg_state *reg)
4367 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4370 /* check if register is a constant scalar value */
4371 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4373 return reg->type == SCALAR_VALUE &&
4374 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4377 /* assuming is_reg_const() is true, return constant value of a register */
4378 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4380 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4383 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4385 return tnum_is_unknown(reg->var_off) &&
4386 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4387 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4388 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4389 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4392 static bool register_is_bounded(struct bpf_reg_state *reg)
4394 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4397 static bool __is_pointer_value(bool allow_ptr_leaks,
4398 const struct bpf_reg_state *reg)
4400 if (allow_ptr_leaks)
4403 return reg->type != SCALAR_VALUE;
4406 /* Copy src state preserving dst->parent and dst->live fields */
4407 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4409 struct bpf_reg_state *parent = dst->parent;
4410 enum bpf_reg_liveness live = dst->live;
4413 dst->parent = parent;
4417 static void save_register_state(struct bpf_verifier_env *env,
4418 struct bpf_func_state *state,
4419 int spi, struct bpf_reg_state *reg,
4424 copy_register_state(&state->stack[spi].spilled_ptr, reg);
4425 if (size == BPF_REG_SIZE)
4426 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4428 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4429 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4431 /* size < 8 bytes spill */
4433 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4436 static bool is_bpf_st_mem(struct bpf_insn *insn)
4438 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4441 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4442 * stack boundary and alignment are checked in check_mem_access()
4444 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4445 /* stack frame we're writing to */
4446 struct bpf_func_state *state,
4447 int off, int size, int value_regno,
4450 struct bpf_func_state *cur; /* state of the current function */
4451 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4452 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4453 struct bpf_reg_state *reg = NULL;
4454 int insn_flags = insn_stack_access_flags(state->frameno, spi);
4456 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4457 * so it's aligned access and [off, off + size) are within stack limits
4459 if (!env->allow_ptr_leaks &&
4460 is_spilled_reg(&state->stack[spi]) &&
4461 size != BPF_REG_SIZE) {
4462 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4466 cur = env->cur_state->frame[env->cur_state->curframe];
4467 if (value_regno >= 0)
4468 reg = &cur->regs[value_regno];
4469 if (!env->bypass_spec_v4) {
4470 bool sanitize = reg && is_spillable_regtype(reg->type);
4472 for (i = 0; i < size; i++) {
4473 u8 type = state->stack[spi].slot_type[i];
4475 if (type != STACK_MISC && type != STACK_ZERO) {
4482 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4485 err = destroy_if_dynptr_stack_slot(env, state, spi);
4489 mark_stack_slot_scratched(env, spi);
4490 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && env->bpf_capable) {
4491 save_register_state(env, state, spi, reg, size);
4492 /* Break the relation on a narrowing spill. */
4493 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4494 state->stack[spi].spilled_ptr.id = 0;
4495 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4496 insn->imm != 0 && env->bpf_capable) {
4497 struct bpf_reg_state fake_reg = {};
4499 __mark_reg_known(&fake_reg, insn->imm);
4500 fake_reg.type = SCALAR_VALUE;
4501 save_register_state(env, state, spi, &fake_reg, size);
4502 } else if (reg && is_spillable_regtype(reg->type)) {
4503 /* register containing pointer is being spilled into stack */
4504 if (size != BPF_REG_SIZE) {
4505 verbose_linfo(env, insn_idx, "; ");
4506 verbose(env, "invalid size of register spill\n");
4509 if (state != cur && reg->type == PTR_TO_STACK) {
4510 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4513 save_register_state(env, state, spi, reg, size);
4515 u8 type = STACK_MISC;
4517 /* regular write of data into stack destroys any spilled ptr */
4518 state->stack[spi].spilled_ptr.type = NOT_INIT;
4519 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4520 if (is_stack_slot_special(&state->stack[spi]))
4521 for (i = 0; i < BPF_REG_SIZE; i++)
4522 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4524 /* only mark the slot as written if all 8 bytes were written
4525 * otherwise read propagation may incorrectly stop too soon
4526 * when stack slots are partially written.
4527 * This heuristic means that read propagation will be
4528 * conservative, since it will add reg_live_read marks
4529 * to stack slots all the way to first state when programs
4530 * writes+reads less than 8 bytes
4532 if (size == BPF_REG_SIZE)
4533 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4535 /* when we zero initialize stack slots mark them as such */
4536 if ((reg && register_is_null(reg)) ||
4537 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4538 /* STACK_ZERO case happened because register spill
4539 * wasn't properly aligned at the stack slot boundary,
4540 * so it's not a register spill anymore; force
4541 * originating register to be precise to make
4542 * STACK_ZERO correct for subsequent states
4544 err = mark_chain_precision(env, value_regno);
4550 /* Mark slots affected by this stack write. */
4551 for (i = 0; i < size; i++)
4552 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
4553 insn_flags = 0; /* not a register spill */
4557 return push_jmp_history(env, env->cur_state, insn_flags);
4561 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4562 * known to contain a variable offset.
4563 * This function checks whether the write is permitted and conservatively
4564 * tracks the effects of the write, considering that each stack slot in the
4565 * dynamic range is potentially written to.
4567 * 'off' includes 'regno->off'.
4568 * 'value_regno' can be -1, meaning that an unknown value is being written to
4571 * Spilled pointers in range are not marked as written because we don't know
4572 * what's going to be actually written. This means that read propagation for
4573 * future reads cannot be terminated by this write.
4575 * For privileged programs, uninitialized stack slots are considered
4576 * initialized by this write (even though we don't know exactly what offsets
4577 * are going to be written to). The idea is that we don't want the verifier to
4578 * reject future reads that access slots written to through variable offsets.
4580 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4581 /* func where register points to */
4582 struct bpf_func_state *state,
4583 int ptr_regno, int off, int size,
4584 int value_regno, int insn_idx)
4586 struct bpf_func_state *cur; /* state of the current function */
4587 int min_off, max_off;
4589 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4590 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4591 bool writing_zero = false;
4592 /* set if the fact that we're writing a zero is used to let any
4593 * stack slots remain STACK_ZERO
4595 bool zero_used = false;
4597 cur = env->cur_state->frame[env->cur_state->curframe];
4598 ptr_reg = &cur->regs[ptr_regno];
4599 min_off = ptr_reg->smin_value + off;
4600 max_off = ptr_reg->smax_value + off + size;
4601 if (value_regno >= 0)
4602 value_reg = &cur->regs[value_regno];
4603 if ((value_reg && register_is_null(value_reg)) ||
4604 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4605 writing_zero = true;
4607 for (i = min_off; i < max_off; i++) {
4611 err = destroy_if_dynptr_stack_slot(env, state, spi);
4616 /* Variable offset writes destroy any spilled pointers in range. */
4617 for (i = min_off; i < max_off; i++) {
4618 u8 new_type, *stype;
4622 spi = slot / BPF_REG_SIZE;
4623 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4624 mark_stack_slot_scratched(env, spi);
4626 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4627 /* Reject the write if range we may write to has not
4628 * been initialized beforehand. If we didn't reject
4629 * here, the ptr status would be erased below (even
4630 * though not all slots are actually overwritten),
4631 * possibly opening the door to leaks.
4633 * We do however catch STACK_INVALID case below, and
4634 * only allow reading possibly uninitialized memory
4635 * later for CAP_PERFMON, as the write may not happen to
4638 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4643 /* Erase all spilled pointers. */
4644 state->stack[spi].spilled_ptr.type = NOT_INIT;
4646 /* Update the slot type. */
4647 new_type = STACK_MISC;
4648 if (writing_zero && *stype == STACK_ZERO) {
4649 new_type = STACK_ZERO;
4652 /* If the slot is STACK_INVALID, we check whether it's OK to
4653 * pretend that it will be initialized by this write. The slot
4654 * might not actually be written to, and so if we mark it as
4655 * initialized future reads might leak uninitialized memory.
4656 * For privileged programs, we will accept such reads to slots
4657 * that may or may not be written because, if we're reject
4658 * them, the error would be too confusing.
4660 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4661 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4668 /* backtracking doesn't work for STACK_ZERO yet. */
4669 err = mark_chain_precision(env, value_regno);
4676 /* When register 'dst_regno' is assigned some values from stack[min_off,
4677 * max_off), we set the register's type according to the types of the
4678 * respective stack slots. If all the stack values are known to be zeros, then
4679 * so is the destination reg. Otherwise, the register is considered to be
4680 * SCALAR. This function does not deal with register filling; the caller must
4681 * ensure that all spilled registers in the stack range have been marked as
4684 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4685 /* func where src register points to */
4686 struct bpf_func_state *ptr_state,
4687 int min_off, int max_off, int dst_regno)
4689 struct bpf_verifier_state *vstate = env->cur_state;
4690 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4695 for (i = min_off; i < max_off; i++) {
4697 spi = slot / BPF_REG_SIZE;
4698 mark_stack_slot_scratched(env, spi);
4699 stype = ptr_state->stack[spi].slot_type;
4700 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4704 if (zeros == max_off - min_off) {
4705 /* Any access_size read into register is zero extended,
4706 * so the whole register == const_zero.
4708 __mark_reg_const_zero(env, &state->regs[dst_regno]);
4710 /* have read misc data from the stack */
4711 mark_reg_unknown(env, state->regs, dst_regno);
4713 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4716 /* Read the stack at 'off' and put the results into the register indicated by
4717 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4720 * 'dst_regno' can be -1, meaning that the read value is not going to a
4723 * The access is assumed to be within the current stack bounds.
4725 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4726 /* func where src register points to */
4727 struct bpf_func_state *reg_state,
4728 int off, int size, int dst_regno)
4730 struct bpf_verifier_state *vstate = env->cur_state;
4731 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4732 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4733 struct bpf_reg_state *reg;
4735 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
4737 stype = reg_state->stack[spi].slot_type;
4738 reg = ®_state->stack[spi].spilled_ptr;
4740 mark_stack_slot_scratched(env, spi);
4742 if (is_spilled_reg(®_state->stack[spi])) {
4745 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4748 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4749 if (reg->type != SCALAR_VALUE) {
4750 verbose_linfo(env, env->insn_idx, "; ");
4751 verbose(env, "invalid size of register fill\n");
4755 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4759 if (!(off % BPF_REG_SIZE) && size == spill_size) {
4760 /* The earlier check_reg_arg() has decided the
4761 * subreg_def for this insn. Save it first.
4763 s32 subreg_def = state->regs[dst_regno].subreg_def;
4765 copy_register_state(&state->regs[dst_regno], reg);
4766 state->regs[dst_regno].subreg_def = subreg_def;
4768 int spill_cnt = 0, zero_cnt = 0;
4770 for (i = 0; i < size; i++) {
4771 type = stype[(slot - i) % BPF_REG_SIZE];
4772 if (type == STACK_SPILL) {
4776 if (type == STACK_MISC)
4778 if (type == STACK_ZERO) {
4782 if (type == STACK_INVALID && env->allow_uninit_stack)
4784 verbose(env, "invalid read from stack off %d+%d size %d\n",
4789 if (spill_cnt == size &&
4790 tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
4791 __mark_reg_const_zero(env, &state->regs[dst_regno]);
4792 /* this IS register fill, so keep insn_flags */
4793 } else if (zero_cnt == size) {
4794 /* similarly to mark_reg_stack_read(), preserve zeroes */
4795 __mark_reg_const_zero(env, &state->regs[dst_regno]);
4796 insn_flags = 0; /* not restoring original register state */
4798 mark_reg_unknown(env, state->regs, dst_regno);
4799 insn_flags = 0; /* not restoring original register state */
4802 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4803 } else if (dst_regno >= 0) {
4804 /* restore register state from stack */
4805 copy_register_state(&state->regs[dst_regno], reg);
4806 /* mark reg as written since spilled pointer state likely
4807 * has its liveness marks cleared by is_state_visited()
4808 * which resets stack/reg liveness for state transitions
4810 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4811 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4812 /* If dst_regno==-1, the caller is asking us whether
4813 * it is acceptable to use this value as a SCALAR_VALUE
4815 * We must not allow unprivileged callers to do that
4816 * with spilled pointers.
4818 verbose(env, "leaking pointer from stack off %d\n",
4822 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4824 for (i = 0; i < size; i++) {
4825 type = stype[(slot - i) % BPF_REG_SIZE];
4826 if (type == STACK_MISC)
4828 if (type == STACK_ZERO)
4830 if (type == STACK_INVALID && env->allow_uninit_stack)
4832 verbose(env, "invalid read from stack off %d+%d size %d\n",
4836 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4838 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4839 insn_flags = 0; /* we are not restoring spilled register */
4842 return push_jmp_history(env, env->cur_state, insn_flags);
4846 enum bpf_access_src {
4847 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
4848 ACCESS_HELPER = 2, /* the access is performed by a helper */
4851 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4852 int regno, int off, int access_size,
4853 bool zero_size_allowed,
4854 enum bpf_access_src type,
4855 struct bpf_call_arg_meta *meta);
4857 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4859 return cur_regs(env) + regno;
4862 /* Read the stack at 'ptr_regno + off' and put the result into the register
4864 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4865 * but not its variable offset.
4866 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4868 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4869 * filling registers (i.e. reads of spilled register cannot be detected when
4870 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4871 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4872 * offset; for a fixed offset check_stack_read_fixed_off should be used
4875 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4876 int ptr_regno, int off, int size, int dst_regno)
4878 /* The state of the source register. */
4879 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4880 struct bpf_func_state *ptr_state = func(env, reg);
4882 int min_off, max_off;
4884 /* Note that we pass a NULL meta, so raw access will not be permitted.
4886 err = check_stack_range_initialized(env, ptr_regno, off, size,
4887 false, ACCESS_DIRECT, NULL);
4891 min_off = reg->smin_value + off;
4892 max_off = reg->smax_value + off;
4893 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4897 /* check_stack_read dispatches to check_stack_read_fixed_off or
4898 * check_stack_read_var_off.
4900 * The caller must ensure that the offset falls within the allocated stack
4903 * 'dst_regno' is a register which will receive the value from the stack. It
4904 * can be -1, meaning that the read value is not going to a register.
4906 static int check_stack_read(struct bpf_verifier_env *env,
4907 int ptr_regno, int off, int size,
4910 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4911 struct bpf_func_state *state = func(env, reg);
4913 /* Some accesses are only permitted with a static offset. */
4914 bool var_off = !tnum_is_const(reg->var_off);
4916 /* The offset is required to be static when reads don't go to a
4917 * register, in order to not leak pointers (see
4918 * check_stack_read_fixed_off).
4920 if (dst_regno < 0 && var_off) {
4923 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4924 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4928 /* Variable offset is prohibited for unprivileged mode for simplicity
4929 * since it requires corresponding support in Spectre masking for stack
4930 * ALU. See also retrieve_ptr_limit(). The check in
4931 * check_stack_access_for_ptr_arithmetic() called by
4932 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4933 * with variable offsets, therefore no check is required here. Further,
4934 * just checking it here would be insufficient as speculative stack
4935 * writes could still lead to unsafe speculative behaviour.
4938 off += reg->var_off.value;
4939 err = check_stack_read_fixed_off(env, state, off, size,
4942 /* Variable offset stack reads need more conservative handling
4943 * than fixed offset ones. Note that dst_regno >= 0 on this
4946 err = check_stack_read_var_off(env, ptr_regno, off, size,
4953 /* check_stack_write dispatches to check_stack_write_fixed_off or
4954 * check_stack_write_var_off.
4956 * 'ptr_regno' is the register used as a pointer into the stack.
4957 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4958 * 'value_regno' is the register whose value we're writing to the stack. It can
4959 * be -1, meaning that we're not writing from a register.
4961 * The caller must ensure that the offset falls within the maximum stack size.
4963 static int check_stack_write(struct bpf_verifier_env *env,
4964 int ptr_regno, int off, int size,
4965 int value_regno, int insn_idx)
4967 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4968 struct bpf_func_state *state = func(env, reg);
4971 if (tnum_is_const(reg->var_off)) {
4972 off += reg->var_off.value;
4973 err = check_stack_write_fixed_off(env, state, off, size,
4974 value_regno, insn_idx);
4976 /* Variable offset stack reads need more conservative handling
4977 * than fixed offset ones.
4979 err = check_stack_write_var_off(env, state,
4980 ptr_regno, off, size,
4981 value_regno, insn_idx);
4986 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4987 int off, int size, enum bpf_access_type type)
4989 struct bpf_reg_state *regs = cur_regs(env);
4990 struct bpf_map *map = regs[regno].map_ptr;
4991 u32 cap = bpf_map_flags_to_cap(map);
4993 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4994 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4995 map->value_size, off, size);
4999 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5000 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5001 map->value_size, off, size);
5008 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5009 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5010 int off, int size, u32 mem_size,
5011 bool zero_size_allowed)
5013 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5014 struct bpf_reg_state *reg;
5016 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5019 reg = &cur_regs(env)[regno];
5020 switch (reg->type) {
5021 case PTR_TO_MAP_KEY:
5022 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5023 mem_size, off, size);
5025 case PTR_TO_MAP_VALUE:
5026 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5027 mem_size, off, size);
5030 case PTR_TO_PACKET_META:
5031 case PTR_TO_PACKET_END:
5032 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5033 off, size, regno, reg->id, off, mem_size);
5037 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5038 mem_size, off, size);
5044 /* check read/write into a memory region with possible variable offset */
5045 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5046 int off, int size, u32 mem_size,
5047 bool zero_size_allowed)
5049 struct bpf_verifier_state *vstate = env->cur_state;
5050 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5051 struct bpf_reg_state *reg = &state->regs[regno];
5054 /* We may have adjusted the register pointing to memory region, so we
5055 * need to try adding each of min_value and max_value to off
5056 * to make sure our theoretical access will be safe.
5058 * The minimum value is only important with signed
5059 * comparisons where we can't assume the floor of a
5060 * value is 0. If we are using signed variables for our
5061 * index'es we need to make sure that whatever we use
5062 * will have a set floor within our range.
5064 if (reg->smin_value < 0 &&
5065 (reg->smin_value == S64_MIN ||
5066 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5067 reg->smin_value + off < 0)) {
5068 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5072 err = __check_mem_access(env, regno, reg->smin_value + off, size,
5073 mem_size, zero_size_allowed);
5075 verbose(env, "R%d min value is outside of the allowed memory range\n",
5080 /* If we haven't set a max value then we need to bail since we can't be
5081 * sure we won't do bad things.
5082 * If reg->umax_value + off could overflow, treat that as unbounded too.
5084 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5085 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5089 err = __check_mem_access(env, regno, reg->umax_value + off, size,
5090 mem_size, zero_size_allowed);
5092 verbose(env, "R%d max value is outside of the allowed memory range\n",
5100 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5101 const struct bpf_reg_state *reg, int regno,
5104 /* Access to this pointer-typed register or passing it to a helper
5105 * is only allowed in its original, unmodified form.
5109 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5110 reg_type_str(env, reg->type), regno, reg->off);
5114 if (!fixed_off_ok && reg->off) {
5115 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5116 reg_type_str(env, reg->type), regno, reg->off);
5120 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5123 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5124 verbose(env, "variable %s access var_off=%s disallowed\n",
5125 reg_type_str(env, reg->type), tn_buf);
5132 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5133 const struct bpf_reg_state *reg, int regno)
5135 return __check_ptr_off_reg(env, reg, regno, false);
5138 static int map_kptr_match_type(struct bpf_verifier_env *env,
5139 struct btf_field *kptr_field,
5140 struct bpf_reg_state *reg, u32 regno)
5142 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5144 const char *reg_name = "";
5146 if (btf_is_kernel(reg->btf)) {
5147 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5149 /* Only unreferenced case accepts untrusted pointers */
5150 if (kptr_field->type == BPF_KPTR_UNREF)
5151 perm_flags |= PTR_UNTRUSTED;
5153 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5154 if (kptr_field->type == BPF_KPTR_PERCPU)
5155 perm_flags |= MEM_PERCPU;
5158 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5161 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5162 reg_name = btf_type_name(reg->btf, reg->btf_id);
5164 /* For ref_ptr case, release function check should ensure we get one
5165 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5166 * normal store of unreferenced kptr, we must ensure var_off is zero.
5167 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5168 * reg->off and reg->ref_obj_id are not needed here.
5170 if (__check_ptr_off_reg(env, reg, regno, true))
5173 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5174 * we also need to take into account the reg->off.
5176 * We want to support cases like:
5184 * v = func(); // PTR_TO_BTF_ID
5185 * val->foo = v; // reg->off is zero, btf and btf_id match type
5186 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5187 * // first member type of struct after comparison fails
5188 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5191 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5192 * is zero. We must also ensure that btf_struct_ids_match does not walk
5193 * the struct to match type against first member of struct, i.e. reject
5194 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5195 * strict mode to true for type match.
5197 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5198 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5199 kptr_field->type != BPF_KPTR_UNREF))
5203 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5204 reg_type_str(env, reg->type), reg_name);
5205 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5206 if (kptr_field->type == BPF_KPTR_UNREF)
5207 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5214 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5215 * can dereference RCU protected pointers and result is PTR_TRUSTED.
5217 static bool in_rcu_cs(struct bpf_verifier_env *env)
5219 return env->cur_state->active_rcu_lock ||
5220 env->cur_state->active_lock.ptr ||
5221 !env->prog->aux->sleepable;
5224 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5225 BTF_SET_START(rcu_protected_types)
5226 BTF_ID(struct, prog_test_ref_kfunc)
5227 #ifdef CONFIG_CGROUPS
5228 BTF_ID(struct, cgroup)
5230 BTF_ID(struct, bpf_cpumask)
5231 BTF_ID(struct, task_struct)
5232 BTF_SET_END(rcu_protected_types)
5234 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5236 if (!btf_is_kernel(btf))
5238 return btf_id_set_contains(&rcu_protected_types, btf_id);
5241 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5243 struct btf_struct_meta *meta;
5245 if (btf_is_kernel(kptr_field->kptr.btf))
5248 meta = btf_find_struct_meta(kptr_field->kptr.btf,
5249 kptr_field->kptr.btf_id);
5251 return meta ? meta->record : NULL;
5254 static bool rcu_safe_kptr(const struct btf_field *field)
5256 const struct btf_field_kptr *kptr = &field->kptr;
5258 return field->type == BPF_KPTR_PERCPU ||
5259 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5262 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5264 struct btf_record *rec;
5267 ret = PTR_MAYBE_NULL;
5268 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5270 if (kptr_field->type == BPF_KPTR_PERCPU)
5272 else if (!btf_is_kernel(kptr_field->kptr.btf))
5275 rec = kptr_pointee_btf_record(kptr_field);
5276 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5279 ret |= PTR_UNTRUSTED;
5285 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5286 int value_regno, int insn_idx,
5287 struct btf_field *kptr_field)
5289 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5290 int class = BPF_CLASS(insn->code);
5291 struct bpf_reg_state *val_reg;
5293 /* Things we already checked for in check_map_access and caller:
5294 * - Reject cases where variable offset may touch kptr
5295 * - size of access (must be BPF_DW)
5296 * - tnum_is_const(reg->var_off)
5297 * - kptr_field->offset == off + reg->var_off.value
5299 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5300 if (BPF_MODE(insn->code) != BPF_MEM) {
5301 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5305 /* We only allow loading referenced kptr, since it will be marked as
5306 * untrusted, similar to unreferenced kptr.
5308 if (class != BPF_LDX &&
5309 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5310 verbose(env, "store to referenced kptr disallowed\n");
5314 if (class == BPF_LDX) {
5315 val_reg = reg_state(env, value_regno);
5316 /* We can simply mark the value_regno receiving the pointer
5317 * value from map as PTR_TO_BTF_ID, with the correct type.
5319 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5320 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5321 /* For mark_ptr_or_null_reg */
5322 val_reg->id = ++env->id_gen;
5323 } else if (class == BPF_STX) {
5324 val_reg = reg_state(env, value_regno);
5325 if (!register_is_null(val_reg) &&
5326 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5328 } else if (class == BPF_ST) {
5330 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5331 kptr_field->offset);
5335 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5341 /* check read/write into a map element with possible variable offset */
5342 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5343 int off, int size, bool zero_size_allowed,
5344 enum bpf_access_src src)
5346 struct bpf_verifier_state *vstate = env->cur_state;
5347 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5348 struct bpf_reg_state *reg = &state->regs[regno];
5349 struct bpf_map *map = reg->map_ptr;
5350 struct btf_record *rec;
5353 err = check_mem_region_access(env, regno, off, size, map->value_size,
5358 if (IS_ERR_OR_NULL(map->record))
5361 for (i = 0; i < rec->cnt; i++) {
5362 struct btf_field *field = &rec->fields[i];
5363 u32 p = field->offset;
5365 /* If any part of a field can be touched by load/store, reject
5366 * this program. To check that [x1, x2) overlaps with [y1, y2),
5367 * it is sufficient to check x1 < y2 && y1 < x2.
5369 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5370 p < reg->umax_value + off + size) {
5371 switch (field->type) {
5372 case BPF_KPTR_UNREF:
5374 case BPF_KPTR_PERCPU:
5375 if (src != ACCESS_DIRECT) {
5376 verbose(env, "kptr cannot be accessed indirectly by helper\n");
5379 if (!tnum_is_const(reg->var_off)) {
5380 verbose(env, "kptr access cannot have variable offset\n");
5383 if (p != off + reg->var_off.value) {
5384 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5385 p, off + reg->var_off.value);
5388 if (size != bpf_size_to_bytes(BPF_DW)) {
5389 verbose(env, "kptr access size must be BPF_DW\n");
5394 verbose(env, "%s cannot be accessed directly by load/store\n",
5395 btf_field_type_name(field->type));
5403 #define MAX_PACKET_OFF 0xffff
5405 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5406 const struct bpf_call_arg_meta *meta,
5407 enum bpf_access_type t)
5409 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5411 switch (prog_type) {
5412 /* Program types only with direct read access go here! */
5413 case BPF_PROG_TYPE_LWT_IN:
5414 case BPF_PROG_TYPE_LWT_OUT:
5415 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5416 case BPF_PROG_TYPE_SK_REUSEPORT:
5417 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5418 case BPF_PROG_TYPE_CGROUP_SKB:
5423 /* Program types with direct read + write access go here! */
5424 case BPF_PROG_TYPE_SCHED_CLS:
5425 case BPF_PROG_TYPE_SCHED_ACT:
5426 case BPF_PROG_TYPE_XDP:
5427 case BPF_PROG_TYPE_LWT_XMIT:
5428 case BPF_PROG_TYPE_SK_SKB:
5429 case BPF_PROG_TYPE_SK_MSG:
5431 return meta->pkt_access;
5433 env->seen_direct_write = true;
5436 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5438 env->seen_direct_write = true;
5447 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5448 int size, bool zero_size_allowed)
5450 struct bpf_reg_state *regs = cur_regs(env);
5451 struct bpf_reg_state *reg = ®s[regno];
5454 /* We may have added a variable offset to the packet pointer; but any
5455 * reg->range we have comes after that. We are only checking the fixed
5459 /* We don't allow negative numbers, because we aren't tracking enough
5460 * detail to prove they're safe.
5462 if (reg->smin_value < 0) {
5463 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5468 err = reg->range < 0 ? -EINVAL :
5469 __check_mem_access(env, regno, off, size, reg->range,
5472 verbose(env, "R%d offset is outside of the packet\n", regno);
5476 /* __check_mem_access has made sure "off + size - 1" is within u16.
5477 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5478 * otherwise find_good_pkt_pointers would have refused to set range info
5479 * that __check_mem_access would have rejected this pkt access.
5480 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5482 env->prog->aux->max_pkt_offset =
5483 max_t(u32, env->prog->aux->max_pkt_offset,
5484 off + reg->umax_value + size - 1);
5489 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
5490 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5491 enum bpf_access_type t, enum bpf_reg_type *reg_type,
5492 struct btf **btf, u32 *btf_id)
5494 struct bpf_insn_access_aux info = {
5495 .reg_type = *reg_type,
5499 if (env->ops->is_valid_access &&
5500 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5501 /* A non zero info.ctx_field_size indicates that this field is a
5502 * candidate for later verifier transformation to load the whole
5503 * field and then apply a mask when accessed with a narrower
5504 * access than actual ctx access size. A zero info.ctx_field_size
5505 * will only allow for whole field access and rejects any other
5506 * type of narrower access.
5508 *reg_type = info.reg_type;
5510 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5512 *btf_id = info.btf_id;
5514 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5516 /* remember the offset of last byte accessed in ctx */
5517 if (env->prog->aux->max_ctx_offset < off + size)
5518 env->prog->aux->max_ctx_offset = off + size;
5522 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5526 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5529 if (size < 0 || off < 0 ||
5530 (u64)off + size > sizeof(struct bpf_flow_keys)) {
5531 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5538 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5539 u32 regno, int off, int size,
5540 enum bpf_access_type t)
5542 struct bpf_reg_state *regs = cur_regs(env);
5543 struct bpf_reg_state *reg = ®s[regno];
5544 struct bpf_insn_access_aux info = {};
5547 if (reg->smin_value < 0) {
5548 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5553 switch (reg->type) {
5554 case PTR_TO_SOCK_COMMON:
5555 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5558 valid = bpf_sock_is_valid_access(off, size, t, &info);
5560 case PTR_TO_TCP_SOCK:
5561 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5563 case PTR_TO_XDP_SOCK:
5564 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5572 env->insn_aux_data[insn_idx].ctx_field_size =
5573 info.ctx_field_size;
5577 verbose(env, "R%d invalid %s access off=%d size=%d\n",
5578 regno, reg_type_str(env, reg->type), off, size);
5583 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5585 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5588 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5590 const struct bpf_reg_state *reg = reg_state(env, regno);
5592 return reg->type == PTR_TO_CTX;
5595 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5597 const struct bpf_reg_state *reg = reg_state(env, regno);
5599 return type_is_sk_pointer(reg->type);
5602 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5604 const struct bpf_reg_state *reg = reg_state(env, regno);
5606 return type_is_pkt_pointer(reg->type);
5609 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5611 const struct bpf_reg_state *reg = reg_state(env, regno);
5613 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5614 return reg->type == PTR_TO_FLOW_KEYS;
5617 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5619 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5620 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5621 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5623 [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5626 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5628 /* A referenced register is always trusted. */
5629 if (reg->ref_obj_id)
5632 /* Types listed in the reg2btf_ids are always trusted */
5633 if (reg2btf_ids[base_type(reg->type)])
5636 /* If a register is not referenced, it is trusted if it has the
5637 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5638 * other type modifiers may be safe, but we elect to take an opt-in
5639 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5642 * Eventually, we should make PTR_TRUSTED the single source of truth
5643 * for whether a register is trusted.
5645 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5646 !bpf_type_has_unsafe_modifiers(reg->type);
5649 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5651 return reg->type & MEM_RCU;
5654 static void clear_trusted_flags(enum bpf_type_flag *flag)
5656 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5659 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5660 const struct bpf_reg_state *reg,
5661 int off, int size, bool strict)
5663 struct tnum reg_off;
5666 /* Byte size accesses are always allowed. */
5667 if (!strict || size == 1)
5670 /* For platforms that do not have a Kconfig enabling
5671 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5672 * NET_IP_ALIGN is universally set to '2'. And on platforms
5673 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5674 * to this code only in strict mode where we want to emulate
5675 * the NET_IP_ALIGN==2 checking. Therefore use an
5676 * unconditional IP align value of '2'.
5680 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5681 if (!tnum_is_aligned(reg_off, size)) {
5684 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5686 "misaligned packet access off %d+%s+%d+%d size %d\n",
5687 ip_align, tn_buf, reg->off, off, size);
5694 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5695 const struct bpf_reg_state *reg,
5696 const char *pointer_desc,
5697 int off, int size, bool strict)
5699 struct tnum reg_off;
5701 /* Byte size accesses are always allowed. */
5702 if (!strict || size == 1)
5705 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5706 if (!tnum_is_aligned(reg_off, size)) {
5709 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5710 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5711 pointer_desc, tn_buf, reg->off, off, size);
5718 static int check_ptr_alignment(struct bpf_verifier_env *env,
5719 const struct bpf_reg_state *reg, int off,
5720 int size, bool strict_alignment_once)
5722 bool strict = env->strict_alignment || strict_alignment_once;
5723 const char *pointer_desc = "";
5725 switch (reg->type) {
5727 case PTR_TO_PACKET_META:
5728 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5729 * right in front, treat it the very same way.
5731 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5732 case PTR_TO_FLOW_KEYS:
5733 pointer_desc = "flow keys ";
5735 case PTR_TO_MAP_KEY:
5736 pointer_desc = "key ";
5738 case PTR_TO_MAP_VALUE:
5739 pointer_desc = "value ";
5742 pointer_desc = "context ";
5745 pointer_desc = "stack ";
5746 /* The stack spill tracking logic in check_stack_write_fixed_off()
5747 * and check_stack_read_fixed_off() relies on stack accesses being
5753 pointer_desc = "sock ";
5755 case PTR_TO_SOCK_COMMON:
5756 pointer_desc = "sock_common ";
5758 case PTR_TO_TCP_SOCK:
5759 pointer_desc = "tcp_sock ";
5761 case PTR_TO_XDP_SOCK:
5762 pointer_desc = "xdp_sock ";
5767 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5771 /* starting from main bpf function walk all instructions of the function
5772 * and recursively walk all callees that given function can call.
5773 * Ignore jump and exit insns.
5774 * Since recursion is prevented by check_cfg() this algorithm
5775 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5777 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5779 struct bpf_subprog_info *subprog = env->subprog_info;
5780 struct bpf_insn *insn = env->prog->insnsi;
5781 int depth = 0, frame = 0, i, subprog_end;
5782 bool tail_call_reachable = false;
5783 int ret_insn[MAX_CALL_FRAMES];
5784 int ret_prog[MAX_CALL_FRAMES];
5787 i = subprog[idx].start;
5789 /* protect against potential stack overflow that might happen when
5790 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5791 * depth for such case down to 256 so that the worst case scenario
5792 * would result in 8k stack size (32 which is tailcall limit * 256 =
5795 * To get the idea what might happen, see an example:
5796 * func1 -> sub rsp, 128
5797 * subfunc1 -> sub rsp, 256
5798 * tailcall1 -> add rsp, 256
5799 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5800 * subfunc2 -> sub rsp, 64
5801 * subfunc22 -> sub rsp, 128
5802 * tailcall2 -> add rsp, 128
5803 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5805 * tailcall will unwind the current stack frame but it will not get rid
5806 * of caller's stack as shown on the example above.
5808 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5810 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5814 /* round up to 32-bytes, since this is granularity
5815 * of interpreter stack size
5817 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5818 if (depth > MAX_BPF_STACK) {
5819 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5824 subprog_end = subprog[idx + 1].start;
5825 for (; i < subprog_end; i++) {
5826 int next_insn, sidx;
5828 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5831 if (!is_bpf_throw_kfunc(insn + i))
5833 if (subprog[idx].is_cb)
5835 for (int c = 0; c < frame && !err; c++) {
5836 if (subprog[ret_prog[c]].is_cb) {
5844 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5849 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5851 /* remember insn and function to return to */
5852 ret_insn[frame] = i + 1;
5853 ret_prog[frame] = idx;
5855 /* find the callee */
5856 next_insn = i + insn[i].imm + 1;
5857 sidx = find_subprog(env, next_insn);
5859 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5863 if (subprog[sidx].is_async_cb) {
5864 if (subprog[sidx].has_tail_call) {
5865 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5868 /* async callbacks don't increase bpf prog stack size unless called directly */
5869 if (!bpf_pseudo_call(insn + i))
5871 if (subprog[sidx].is_exception_cb) {
5872 verbose(env, "insn %d cannot call exception cb directly\n", i);
5879 if (subprog[idx].has_tail_call)
5880 tail_call_reachable = true;
5883 if (frame >= MAX_CALL_FRAMES) {
5884 verbose(env, "the call stack of %d frames is too deep !\n",
5890 /* if tail call got detected across bpf2bpf calls then mark each of the
5891 * currently present subprog frames as tail call reachable subprogs;
5892 * this info will be utilized by JIT so that we will be preserving the
5893 * tail call counter throughout bpf2bpf calls combined with tailcalls
5895 if (tail_call_reachable)
5896 for (j = 0; j < frame; j++) {
5897 if (subprog[ret_prog[j]].is_exception_cb) {
5898 verbose(env, "cannot tail call within exception cb\n");
5901 subprog[ret_prog[j]].tail_call_reachable = true;
5903 if (subprog[0].tail_call_reachable)
5904 env->prog->aux->tail_call_reachable = true;
5906 /* end of for() loop means the last insn of the 'subprog'
5907 * was reached. Doesn't matter whether it was JA or EXIT
5911 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5913 i = ret_insn[frame];
5914 idx = ret_prog[frame];
5918 static int check_max_stack_depth(struct bpf_verifier_env *env)
5920 struct bpf_subprog_info *si = env->subprog_info;
5923 for (int i = 0; i < env->subprog_cnt; i++) {
5924 if (!i || si[i].is_async_cb) {
5925 ret = check_max_stack_depth_subprog(env, i);
5934 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5935 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5936 const struct bpf_insn *insn, int idx)
5938 int start = idx + insn->imm + 1, subprog;
5940 subprog = find_subprog(env, start);
5942 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5946 return env->subprog_info[subprog].stack_depth;
5950 static int __check_buffer_access(struct bpf_verifier_env *env,
5951 const char *buf_info,
5952 const struct bpf_reg_state *reg,
5953 int regno, int off, int size)
5957 "R%d invalid %s buffer access: off=%d, size=%d\n",
5958 regno, buf_info, off, size);
5961 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5964 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5966 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5967 regno, off, tn_buf);
5974 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5975 const struct bpf_reg_state *reg,
5976 int regno, int off, int size)
5980 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5984 if (off + size > env->prog->aux->max_tp_access)
5985 env->prog->aux->max_tp_access = off + size;
5990 static int check_buffer_access(struct bpf_verifier_env *env,
5991 const struct bpf_reg_state *reg,
5992 int regno, int off, int size,
5993 bool zero_size_allowed,
5996 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5999 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6003 if (off + size > *max_access)
6004 *max_access = off + size;
6009 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6010 static void zext_32_to_64(struct bpf_reg_state *reg)
6012 reg->var_off = tnum_subreg(reg->var_off);
6013 __reg_assign_32_into_64(reg);
6016 /* truncate register to smaller size (in bytes)
6017 * must be called with size < BPF_REG_SIZE
6019 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6023 /* clear high bits in bit representation */
6024 reg->var_off = tnum_cast(reg->var_off, size);
6026 /* fix arithmetic bounds */
6027 mask = ((u64)1 << (size * 8)) - 1;
6028 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6029 reg->umin_value &= mask;
6030 reg->umax_value &= mask;
6032 reg->umin_value = 0;
6033 reg->umax_value = mask;
6035 reg->smin_value = reg->umin_value;
6036 reg->smax_value = reg->umax_value;
6038 /* If size is smaller than 32bit register the 32bit register
6039 * values are also truncated so we push 64-bit bounds into
6040 * 32-bit bounds. Above were truncated < 32-bits already.
6043 __mark_reg32_unbounded(reg);
6044 reg_bounds_sync(reg);
6048 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6051 reg->smin_value = reg->s32_min_value = S8_MIN;
6052 reg->smax_value = reg->s32_max_value = S8_MAX;
6053 } else if (size == 2) {
6054 reg->smin_value = reg->s32_min_value = S16_MIN;
6055 reg->smax_value = reg->s32_max_value = S16_MAX;
6058 reg->smin_value = reg->s32_min_value = S32_MIN;
6059 reg->smax_value = reg->s32_max_value = S32_MAX;
6061 reg->umin_value = reg->u32_min_value = 0;
6062 reg->umax_value = U64_MAX;
6063 reg->u32_max_value = U32_MAX;
6064 reg->var_off = tnum_unknown;
6067 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6069 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6070 u64 top_smax_value, top_smin_value;
6071 u64 num_bits = size * 8;
6073 if (tnum_is_const(reg->var_off)) {
6074 u64_cval = reg->var_off.value;
6076 reg->var_off = tnum_const((s8)u64_cval);
6078 reg->var_off = tnum_const((s16)u64_cval);
6081 reg->var_off = tnum_const((s32)u64_cval);
6083 u64_cval = reg->var_off.value;
6084 reg->smax_value = reg->smin_value = u64_cval;
6085 reg->umax_value = reg->umin_value = u64_cval;
6086 reg->s32_max_value = reg->s32_min_value = u64_cval;
6087 reg->u32_max_value = reg->u32_min_value = u64_cval;
6091 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6092 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6094 if (top_smax_value != top_smin_value)
6097 /* find the s64_min and s64_min after sign extension */
6099 init_s64_max = (s8)reg->smax_value;
6100 init_s64_min = (s8)reg->smin_value;
6101 } else if (size == 2) {
6102 init_s64_max = (s16)reg->smax_value;
6103 init_s64_min = (s16)reg->smin_value;
6105 init_s64_max = (s32)reg->smax_value;
6106 init_s64_min = (s32)reg->smin_value;
6109 s64_max = max(init_s64_max, init_s64_min);
6110 s64_min = min(init_s64_max, init_s64_min);
6112 /* both of s64_max/s64_min positive or negative */
6113 if ((s64_max >= 0) == (s64_min >= 0)) {
6114 reg->smin_value = reg->s32_min_value = s64_min;
6115 reg->smax_value = reg->s32_max_value = s64_max;
6116 reg->umin_value = reg->u32_min_value = s64_min;
6117 reg->umax_value = reg->u32_max_value = s64_max;
6118 reg->var_off = tnum_range(s64_min, s64_max);
6123 set_sext64_default_val(reg, size);
6126 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6129 reg->s32_min_value = S8_MIN;
6130 reg->s32_max_value = S8_MAX;
6133 reg->s32_min_value = S16_MIN;
6134 reg->s32_max_value = S16_MAX;
6136 reg->u32_min_value = 0;
6137 reg->u32_max_value = U32_MAX;
6140 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6142 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6143 u32 top_smax_value, top_smin_value;
6144 u32 num_bits = size * 8;
6146 if (tnum_is_const(reg->var_off)) {
6147 u32_val = reg->var_off.value;
6149 reg->var_off = tnum_const((s8)u32_val);
6151 reg->var_off = tnum_const((s16)u32_val);
6153 u32_val = reg->var_off.value;
6154 reg->s32_min_value = reg->s32_max_value = u32_val;
6155 reg->u32_min_value = reg->u32_max_value = u32_val;
6159 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6160 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6162 if (top_smax_value != top_smin_value)
6165 /* find the s32_min and s32_min after sign extension */
6167 init_s32_max = (s8)reg->s32_max_value;
6168 init_s32_min = (s8)reg->s32_min_value;
6171 init_s32_max = (s16)reg->s32_max_value;
6172 init_s32_min = (s16)reg->s32_min_value;
6174 s32_max = max(init_s32_max, init_s32_min);
6175 s32_min = min(init_s32_max, init_s32_min);
6177 if ((s32_min >= 0) == (s32_max >= 0)) {
6178 reg->s32_min_value = s32_min;
6179 reg->s32_max_value = s32_max;
6180 reg->u32_min_value = (u32)s32_min;
6181 reg->u32_max_value = (u32)s32_max;
6186 set_sext32_default_val(reg, size);
6189 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6191 /* A map is considered read-only if the following condition are true:
6193 * 1) BPF program side cannot change any of the map content. The
6194 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6195 * and was set at map creation time.
6196 * 2) The map value(s) have been initialized from user space by a
6197 * loader and then "frozen", such that no new map update/delete
6198 * operations from syscall side are possible for the rest of
6199 * the map's lifetime from that point onwards.
6200 * 3) Any parallel/pending map update/delete operations from syscall
6201 * side have been completed. Only after that point, it's safe to
6202 * assume that map value(s) are immutable.
6204 return (map->map_flags & BPF_F_RDONLY_PROG) &&
6205 READ_ONCE(map->frozen) &&
6206 !bpf_map_write_active(map);
6209 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6216 err = map->ops->map_direct_value_addr(map, &addr, off);
6219 ptr = (void *)(long)addr + off;
6223 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6226 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6229 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6240 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
6241 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
6242 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
6245 * Allow list few fields as RCU trusted or full trusted.
6246 * This logic doesn't allow mix tagging and will be removed once GCC supports
6250 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6251 BTF_TYPE_SAFE_RCU(struct task_struct) {
6252 const cpumask_t *cpus_ptr;
6253 struct css_set __rcu *cgroups;
6254 struct task_struct __rcu *real_parent;
6255 struct task_struct *group_leader;
6258 BTF_TYPE_SAFE_RCU(struct cgroup) {
6259 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6260 struct kernfs_node *kn;
6263 BTF_TYPE_SAFE_RCU(struct css_set) {
6264 struct cgroup *dfl_cgrp;
6267 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6268 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6269 struct file __rcu *exe_file;
6272 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6273 * because bpf prog accessible sockets are SOCK_RCU_FREE.
6275 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6279 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6283 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6284 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6285 struct seq_file *seq;
6288 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6289 struct bpf_iter_meta *meta;
6290 struct task_struct *task;
6293 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6297 BTF_TYPE_SAFE_TRUSTED(struct file) {
6298 struct inode *f_inode;
6301 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6302 /* no negative dentry-s in places where bpf can see it */
6303 struct inode *d_inode;
6306 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6310 static bool type_is_rcu(struct bpf_verifier_env *env,
6311 struct bpf_reg_state *reg,
6312 const char *field_name, u32 btf_id)
6314 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6315 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6316 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6318 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6321 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6322 struct bpf_reg_state *reg,
6323 const char *field_name, u32 btf_id)
6325 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6326 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6327 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6329 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6332 static bool type_is_trusted(struct bpf_verifier_env *env,
6333 struct bpf_reg_state *reg,
6334 const char *field_name, u32 btf_id)
6336 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6337 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6338 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6339 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6340 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6341 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6343 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6346 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6347 struct bpf_reg_state *regs,
6348 int regno, int off, int size,
6349 enum bpf_access_type atype,
6352 struct bpf_reg_state *reg = regs + regno;
6353 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6354 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6355 const char *field_name = NULL;
6356 enum bpf_type_flag flag = 0;
6360 if (!env->allow_ptr_leaks) {
6362 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6366 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6368 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6374 "R%d is ptr_%s invalid negative access: off=%d\n",
6378 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6381 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6383 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6384 regno, tname, off, tn_buf);
6388 if (reg->type & MEM_USER) {
6390 "R%d is ptr_%s access user memory: off=%d\n",
6395 if (reg->type & MEM_PERCPU) {
6397 "R%d is ptr_%s access percpu memory: off=%d\n",
6402 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6403 if (!btf_is_kernel(reg->btf)) {
6404 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6407 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6409 /* Writes are permitted with default btf_struct_access for
6410 * program allocated objects (which always have ref_obj_id > 0),
6411 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6413 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6414 verbose(env, "only read is supported\n");
6418 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6419 !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6420 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6424 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6430 if (ret != PTR_TO_BTF_ID) {
6433 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6434 /* If this is an untrusted pointer, all pointers formed by walking it
6435 * also inherit the untrusted flag.
6437 flag = PTR_UNTRUSTED;
6439 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6440 /* By default any pointer obtained from walking a trusted pointer is no
6441 * longer trusted, unless the field being accessed has explicitly been
6442 * marked as inheriting its parent's state of trust (either full or RCU).
6444 * 'cgroups' pointer is untrusted if task->cgroups dereference
6445 * happened in a sleepable program outside of bpf_rcu_read_lock()
6446 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6447 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6449 * A regular RCU-protected pointer with __rcu tag can also be deemed
6450 * trusted if we are in an RCU CS. Such pointer can be NULL.
6452 if (type_is_trusted(env, reg, field_name, btf_id)) {
6453 flag |= PTR_TRUSTED;
6454 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6455 if (type_is_rcu(env, reg, field_name, btf_id)) {
6456 /* ignore __rcu tag and mark it MEM_RCU */
6458 } else if (flag & MEM_RCU ||
6459 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6460 /* __rcu tagged pointers can be NULL */
6461 flag |= MEM_RCU | PTR_MAYBE_NULL;
6463 /* We always trust them */
6464 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6465 flag & PTR_UNTRUSTED)
6466 flag &= ~PTR_UNTRUSTED;
6467 } else if (flag & (MEM_PERCPU | MEM_USER)) {
6470 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6471 clear_trusted_flags(&flag);
6475 * If not in RCU CS or MEM_RCU pointer can be NULL then
6476 * aggressively mark as untrusted otherwise such
6477 * pointers will be plain PTR_TO_BTF_ID without flags
6478 * and will be allowed to be passed into helpers for
6481 flag = PTR_UNTRUSTED;
6484 /* Old compat. Deprecated */
6485 clear_trusted_flags(&flag);
6488 if (atype == BPF_READ && value_regno >= 0)
6489 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6494 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6495 struct bpf_reg_state *regs,
6496 int regno, int off, int size,
6497 enum bpf_access_type atype,
6500 struct bpf_reg_state *reg = regs + regno;
6501 struct bpf_map *map = reg->map_ptr;
6502 struct bpf_reg_state map_reg;
6503 enum bpf_type_flag flag = 0;
6504 const struct btf_type *t;
6510 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6514 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6515 verbose(env, "map_ptr access not supported for map type %d\n",
6520 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6521 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6523 if (!env->allow_ptr_leaks) {
6525 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6531 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6536 if (atype != BPF_READ) {
6537 verbose(env, "only read from %s is supported\n", tname);
6541 /* Simulate access to a PTR_TO_BTF_ID */
6542 memset(&map_reg, 0, sizeof(map_reg));
6543 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6544 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6548 if (value_regno >= 0)
6549 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6554 /* Check that the stack access at the given offset is within bounds. The
6555 * maximum valid offset is -1.
6557 * The minimum valid offset is -MAX_BPF_STACK for writes, and
6558 * -state->allocated_stack for reads.
6560 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6562 struct bpf_func_state *state,
6563 enum bpf_access_type t)
6567 if (t == BPF_WRITE || env->allow_uninit_stack)
6568 min_valid_off = -MAX_BPF_STACK;
6570 min_valid_off = -state->allocated_stack;
6572 if (off < min_valid_off || off > -1)
6577 /* Check that the stack access at 'regno + off' falls within the maximum stack
6580 * 'off' includes `regno->offset`, but not its dynamic part (if any).
6582 static int check_stack_access_within_bounds(
6583 struct bpf_verifier_env *env,
6584 int regno, int off, int access_size,
6585 enum bpf_access_src src, enum bpf_access_type type)
6587 struct bpf_reg_state *regs = cur_regs(env);
6588 struct bpf_reg_state *reg = regs + regno;
6589 struct bpf_func_state *state = func(env, reg);
6590 s64 min_off, max_off;
6594 if (src == ACCESS_HELPER)
6595 /* We don't know if helpers are reading or writing (or both). */
6596 err_extra = " indirect access to";
6597 else if (type == BPF_READ)
6598 err_extra = " read from";
6600 err_extra = " write to";
6602 if (tnum_is_const(reg->var_off)) {
6603 min_off = (s64)reg->var_off.value + off;
6604 max_off = min_off + access_size;
6606 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6607 reg->smin_value <= -BPF_MAX_VAR_OFF) {
6608 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6612 min_off = reg->smin_value + off;
6613 max_off = reg->smax_value + off + access_size;
6616 err = check_stack_slot_within_bounds(env, min_off, state, type);
6617 if (!err && max_off > 0)
6618 err = -EINVAL; /* out of stack access into non-negative offsets */
6621 if (tnum_is_const(reg->var_off)) {
6622 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6623 err_extra, regno, off, access_size);
6627 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6628 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
6629 err_extra, regno, tn_buf, off, access_size);
6634 /* Note that there is no stack access with offset zero, so the needed stack
6635 * size is -min_off, not -min_off+1.
6637 return grow_stack_state(env, state, -min_off /* size */);
6640 /* check whether memory at (regno + off) is accessible for t = (read | write)
6641 * if t==write, value_regno is a register which value is stored into memory
6642 * if t==read, value_regno is a register which will receive the value from memory
6643 * if t==write && value_regno==-1, some unknown value is stored into memory
6644 * if t==read && value_regno==-1, don't care what we read from memory
6646 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6647 int off, int bpf_size, enum bpf_access_type t,
6648 int value_regno, bool strict_alignment_once, bool is_ldsx)
6650 struct bpf_reg_state *regs = cur_regs(env);
6651 struct bpf_reg_state *reg = regs + regno;
6654 size = bpf_size_to_bytes(bpf_size);
6658 /* alignment checks will add in reg->off themselves */
6659 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6663 /* for access checks, reg->off is just part of off */
6666 if (reg->type == PTR_TO_MAP_KEY) {
6667 if (t == BPF_WRITE) {
6668 verbose(env, "write to change key R%d not allowed\n", regno);
6672 err = check_mem_region_access(env, regno, off, size,
6673 reg->map_ptr->key_size, false);
6676 if (value_regno >= 0)
6677 mark_reg_unknown(env, regs, value_regno);
6678 } else if (reg->type == PTR_TO_MAP_VALUE) {
6679 struct btf_field *kptr_field = NULL;
6681 if (t == BPF_WRITE && value_regno >= 0 &&
6682 is_pointer_value(env, value_regno)) {
6683 verbose(env, "R%d leaks addr into map\n", value_regno);
6686 err = check_map_access_type(env, regno, off, size, t);
6689 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6692 if (tnum_is_const(reg->var_off))
6693 kptr_field = btf_record_find(reg->map_ptr->record,
6694 off + reg->var_off.value, BPF_KPTR);
6696 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6697 } else if (t == BPF_READ && value_regno >= 0) {
6698 struct bpf_map *map = reg->map_ptr;
6700 /* if map is read-only, track its contents as scalars */
6701 if (tnum_is_const(reg->var_off) &&
6702 bpf_map_is_rdonly(map) &&
6703 map->ops->map_direct_value_addr) {
6704 int map_off = off + reg->var_off.value;
6707 err = bpf_map_direct_read(map, map_off, size,
6712 regs[value_regno].type = SCALAR_VALUE;
6713 __mark_reg_known(®s[value_regno], val);
6715 mark_reg_unknown(env, regs, value_regno);
6718 } else if (base_type(reg->type) == PTR_TO_MEM) {
6719 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6721 if (type_may_be_null(reg->type)) {
6722 verbose(env, "R%d invalid mem access '%s'\n", regno,
6723 reg_type_str(env, reg->type));
6727 if (t == BPF_WRITE && rdonly_mem) {
6728 verbose(env, "R%d cannot write into %s\n",
6729 regno, reg_type_str(env, reg->type));
6733 if (t == BPF_WRITE && value_regno >= 0 &&
6734 is_pointer_value(env, value_regno)) {
6735 verbose(env, "R%d leaks addr into mem\n", value_regno);
6739 err = check_mem_region_access(env, regno, off, size,
6740 reg->mem_size, false);
6741 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6742 mark_reg_unknown(env, regs, value_regno);
6743 } else if (reg->type == PTR_TO_CTX) {
6744 enum bpf_reg_type reg_type = SCALAR_VALUE;
6745 struct btf *btf = NULL;
6748 if (t == BPF_WRITE && value_regno >= 0 &&
6749 is_pointer_value(env, value_regno)) {
6750 verbose(env, "R%d leaks addr into ctx\n", value_regno);
6754 err = check_ptr_off_reg(env, reg, regno);
6758 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
6761 verbose_linfo(env, insn_idx, "; ");
6762 if (!err && t == BPF_READ && value_regno >= 0) {
6763 /* ctx access returns either a scalar, or a
6764 * PTR_TO_PACKET[_META,_END]. In the latter
6765 * case, we know the offset is zero.
6767 if (reg_type == SCALAR_VALUE) {
6768 mark_reg_unknown(env, regs, value_regno);
6770 mark_reg_known_zero(env, regs,
6772 if (type_may_be_null(reg_type))
6773 regs[value_regno].id = ++env->id_gen;
6774 /* A load of ctx field could have different
6775 * actual load size with the one encoded in the
6776 * insn. When the dst is PTR, it is for sure not
6779 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6780 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6781 regs[value_regno].btf = btf;
6782 regs[value_regno].btf_id = btf_id;
6785 regs[value_regno].type = reg_type;
6788 } else if (reg->type == PTR_TO_STACK) {
6789 /* Basic bounds checks. */
6790 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6795 err = check_stack_read(env, regno, off, size,
6798 err = check_stack_write(env, regno, off, size,
6799 value_regno, insn_idx);
6800 } else if (reg_is_pkt_pointer(reg)) {
6801 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6802 verbose(env, "cannot write into packet\n");
6805 if (t == BPF_WRITE && value_regno >= 0 &&
6806 is_pointer_value(env, value_regno)) {
6807 verbose(env, "R%d leaks addr into packet\n",
6811 err = check_packet_access(env, regno, off, size, false);
6812 if (!err && t == BPF_READ && value_regno >= 0)
6813 mark_reg_unknown(env, regs, value_regno);
6814 } else if (reg->type == PTR_TO_FLOW_KEYS) {
6815 if (t == BPF_WRITE && value_regno >= 0 &&
6816 is_pointer_value(env, value_regno)) {
6817 verbose(env, "R%d leaks addr into flow keys\n",
6822 err = check_flow_keys_access(env, off, size);
6823 if (!err && t == BPF_READ && value_regno >= 0)
6824 mark_reg_unknown(env, regs, value_regno);
6825 } else if (type_is_sk_pointer(reg->type)) {
6826 if (t == BPF_WRITE) {
6827 verbose(env, "R%d cannot write into %s\n",
6828 regno, reg_type_str(env, reg->type));
6831 err = check_sock_access(env, insn_idx, regno, off, size, t);
6832 if (!err && value_regno >= 0)
6833 mark_reg_unknown(env, regs, value_regno);
6834 } else if (reg->type == PTR_TO_TP_BUFFER) {
6835 err = check_tp_buffer_access(env, reg, regno, off, size);
6836 if (!err && t == BPF_READ && value_regno >= 0)
6837 mark_reg_unknown(env, regs, value_regno);
6838 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6839 !type_may_be_null(reg->type)) {
6840 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6842 } else if (reg->type == CONST_PTR_TO_MAP) {
6843 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6845 } else if (base_type(reg->type) == PTR_TO_BUF) {
6846 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6850 if (t == BPF_WRITE) {
6851 verbose(env, "R%d cannot write into %s\n",
6852 regno, reg_type_str(env, reg->type));
6855 max_access = &env->prog->aux->max_rdonly_access;
6857 max_access = &env->prog->aux->max_rdwr_access;
6860 err = check_buffer_access(env, reg, regno, off, size, false,
6863 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6864 mark_reg_unknown(env, regs, value_regno);
6866 verbose(env, "R%d invalid mem access '%s'\n", regno,
6867 reg_type_str(env, reg->type));
6871 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6872 regs[value_regno].type == SCALAR_VALUE) {
6874 /* b/h/w load zero-extends, mark upper bits as known 0 */
6875 coerce_reg_to_size(®s[value_regno], size);
6877 coerce_reg_to_size_sx(®s[value_regno], size);
6882 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6887 switch (insn->imm) {
6889 case BPF_ADD | BPF_FETCH:
6891 case BPF_AND | BPF_FETCH:
6893 case BPF_OR | BPF_FETCH:
6895 case BPF_XOR | BPF_FETCH:
6900 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6904 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6905 verbose(env, "invalid atomic operand size\n");
6909 /* check src1 operand */
6910 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6914 /* check src2 operand */
6915 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6919 if (insn->imm == BPF_CMPXCHG) {
6920 /* Check comparison of R0 with memory location */
6921 const u32 aux_reg = BPF_REG_0;
6923 err = check_reg_arg(env, aux_reg, SRC_OP);
6927 if (is_pointer_value(env, aux_reg)) {
6928 verbose(env, "R%d leaks addr into mem\n", aux_reg);
6933 if (is_pointer_value(env, insn->src_reg)) {
6934 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6938 if (is_ctx_reg(env, insn->dst_reg) ||
6939 is_pkt_reg(env, insn->dst_reg) ||
6940 is_flow_key_reg(env, insn->dst_reg) ||
6941 is_sk_reg(env, insn->dst_reg)) {
6942 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6944 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6948 if (insn->imm & BPF_FETCH) {
6949 if (insn->imm == BPF_CMPXCHG)
6950 load_reg = BPF_REG_0;
6952 load_reg = insn->src_reg;
6954 /* check and record load of old value */
6955 err = check_reg_arg(env, load_reg, DST_OP);
6959 /* This instruction accesses a memory location but doesn't
6960 * actually load it into a register.
6965 /* Check whether we can read the memory, with second call for fetch
6966 * case to simulate the register fill.
6968 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6969 BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6970 if (!err && load_reg >= 0)
6971 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6972 BPF_SIZE(insn->code), BPF_READ, load_reg,
6977 /* Check whether we can write into the same memory. */
6978 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6979 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6985 /* When register 'regno' is used to read the stack (either directly or through
6986 * a helper function) make sure that it's within stack boundary and, depending
6987 * on the access type and privileges, that all elements of the stack are
6990 * 'off' includes 'regno->off', but not its dynamic part (if any).
6992 * All registers that have been spilled on the stack in the slots within the
6993 * read offsets are marked as read.
6995 static int check_stack_range_initialized(
6996 struct bpf_verifier_env *env, int regno, int off,
6997 int access_size, bool zero_size_allowed,
6998 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7000 struct bpf_reg_state *reg = reg_state(env, regno);
7001 struct bpf_func_state *state = func(env, reg);
7002 int err, min_off, max_off, i, j, slot, spi;
7003 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7004 enum bpf_access_type bounds_check_type;
7005 /* Some accesses can write anything into the stack, others are
7008 bool clobber = false;
7010 if (access_size == 0 && !zero_size_allowed) {
7011 verbose(env, "invalid zero-sized read\n");
7015 if (type == ACCESS_HELPER) {
7016 /* The bounds checks for writes are more permissive than for
7017 * reads. However, if raw_mode is not set, we'll do extra
7020 bounds_check_type = BPF_WRITE;
7023 bounds_check_type = BPF_READ;
7025 err = check_stack_access_within_bounds(env, regno, off, access_size,
7026 type, bounds_check_type);
7031 if (tnum_is_const(reg->var_off)) {
7032 min_off = max_off = reg->var_off.value + off;
7034 /* Variable offset is prohibited for unprivileged mode for
7035 * simplicity since it requires corresponding support in
7036 * Spectre masking for stack ALU.
7037 * See also retrieve_ptr_limit().
7039 if (!env->bypass_spec_v1) {
7042 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7043 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7044 regno, err_extra, tn_buf);
7047 /* Only initialized buffer on stack is allowed to be accessed
7048 * with variable offset. With uninitialized buffer it's hard to
7049 * guarantee that whole memory is marked as initialized on
7050 * helper return since specific bounds are unknown what may
7051 * cause uninitialized stack leaking.
7053 if (meta && meta->raw_mode)
7056 min_off = reg->smin_value + off;
7057 max_off = reg->smax_value + off;
7060 if (meta && meta->raw_mode) {
7061 /* Ensure we won't be overwriting dynptrs when simulating byte
7062 * by byte access in check_helper_call using meta.access_size.
7063 * This would be a problem if we have a helper in the future
7066 * helper(uninit_mem, len, dynptr)
7068 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7069 * may end up writing to dynptr itself when touching memory from
7070 * arg 1. This can be relaxed on a case by case basis for known
7071 * safe cases, but reject due to the possibilitiy of aliasing by
7074 for (i = min_off; i < max_off + access_size; i++) {
7075 int stack_off = -i - 1;
7078 /* raw_mode may write past allocated_stack */
7079 if (state->allocated_stack <= stack_off)
7081 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7082 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7086 meta->access_size = access_size;
7087 meta->regno = regno;
7091 for (i = min_off; i < max_off + access_size; i++) {
7095 spi = slot / BPF_REG_SIZE;
7096 if (state->allocated_stack <= slot) {
7097 verbose(env, "verifier bug: allocated_stack too small");
7101 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7102 if (*stype == STACK_MISC)
7104 if ((*stype == STACK_ZERO) ||
7105 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7107 /* helper can write anything into the stack */
7108 *stype = STACK_MISC;
7113 if (is_spilled_reg(&state->stack[spi]) &&
7114 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7115 env->allow_ptr_leaks)) {
7117 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7118 for (j = 0; j < BPF_REG_SIZE; j++)
7119 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7124 if (tnum_is_const(reg->var_off)) {
7125 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7126 err_extra, regno, min_off, i - min_off, access_size);
7130 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7131 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7132 err_extra, regno, tn_buf, i - min_off, access_size);
7136 /* reading any byte out of 8-byte 'spill_slot' will cause
7137 * the whole slot to be marked as 'read'
7139 mark_reg_read(env, &state->stack[spi].spilled_ptr,
7140 state->stack[spi].spilled_ptr.parent,
7142 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7143 * be sure that whether stack slot is written to or not. Hence,
7144 * we must still conservatively propagate reads upwards even if
7145 * helper may write to the entire memory range.
7151 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7152 int access_size, bool zero_size_allowed,
7153 struct bpf_call_arg_meta *meta)
7155 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7158 switch (base_type(reg->type)) {
7160 case PTR_TO_PACKET_META:
7161 return check_packet_access(env, regno, reg->off, access_size,
7163 case PTR_TO_MAP_KEY:
7164 if (meta && meta->raw_mode) {
7165 verbose(env, "R%d cannot write into %s\n", regno,
7166 reg_type_str(env, reg->type));
7169 return check_mem_region_access(env, regno, reg->off, access_size,
7170 reg->map_ptr->key_size, false);
7171 case PTR_TO_MAP_VALUE:
7172 if (check_map_access_type(env, regno, reg->off, access_size,
7173 meta && meta->raw_mode ? BPF_WRITE :
7176 return check_map_access(env, regno, reg->off, access_size,
7177 zero_size_allowed, ACCESS_HELPER);
7179 if (type_is_rdonly_mem(reg->type)) {
7180 if (meta && meta->raw_mode) {
7181 verbose(env, "R%d cannot write into %s\n", regno,
7182 reg_type_str(env, reg->type));
7186 return check_mem_region_access(env, regno, reg->off,
7187 access_size, reg->mem_size,
7190 if (type_is_rdonly_mem(reg->type)) {
7191 if (meta && meta->raw_mode) {
7192 verbose(env, "R%d cannot write into %s\n", regno,
7193 reg_type_str(env, reg->type));
7197 max_access = &env->prog->aux->max_rdonly_access;
7199 max_access = &env->prog->aux->max_rdwr_access;
7201 return check_buffer_access(env, reg, regno, reg->off,
7202 access_size, zero_size_allowed,
7205 return check_stack_range_initialized(
7207 regno, reg->off, access_size,
7208 zero_size_allowed, ACCESS_HELPER, meta);
7210 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7211 access_size, BPF_READ, -1);
7213 /* in case the function doesn't know how to access the context,
7214 * (because we are in a program of type SYSCALL for example), we
7215 * can not statically check its size.
7216 * Dynamically check it now.
7218 if (!env->ops->convert_ctx_access) {
7219 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7220 int offset = access_size - 1;
7222 /* Allow zero-byte read from PTR_TO_CTX */
7223 if (access_size == 0)
7224 return zero_size_allowed ? 0 : -EACCES;
7226 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7227 atype, -1, false, false);
7231 default: /* scalar_value or invalid ptr */
7232 /* Allow zero-byte read from NULL, regardless of pointer type */
7233 if (zero_size_allowed && access_size == 0 &&
7234 register_is_null(reg))
7237 verbose(env, "R%d type=%s ", regno,
7238 reg_type_str(env, reg->type));
7239 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7244 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7247 * @regno is the register containing the access size. regno-1 is the register
7248 * containing the pointer.
7250 static int check_mem_size_reg(struct bpf_verifier_env *env,
7251 struct bpf_reg_state *reg, u32 regno,
7252 bool zero_size_allowed,
7253 struct bpf_call_arg_meta *meta)
7257 /* This is used to refine r0 return value bounds for helpers
7258 * that enforce this value as an upper bound on return values.
7259 * See do_refine_retval_range() for helpers that can refine
7260 * the return value. C type of helper is u32 so we pull register
7261 * bound from umax_value however, if negative verifier errors
7262 * out. Only upper bounds can be learned because retval is an
7263 * int type and negative retvals are allowed.
7265 meta->msize_max_value = reg->umax_value;
7267 /* The register is SCALAR_VALUE; the access check
7268 * happens using its boundaries.
7270 if (!tnum_is_const(reg->var_off))
7271 /* For unprivileged variable accesses, disable raw
7272 * mode so that the program is required to
7273 * initialize all the memory that the helper could
7274 * just partially fill up.
7278 if (reg->smin_value < 0) {
7279 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7284 if (reg->umin_value == 0 && !zero_size_allowed) {
7285 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7286 regno, reg->umin_value, reg->umax_value);
7290 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7291 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7295 err = check_helper_mem_access(env, regno - 1,
7297 zero_size_allowed, meta);
7299 err = mark_chain_precision(env, regno);
7303 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7304 u32 regno, u32 mem_size)
7306 bool may_be_null = type_may_be_null(reg->type);
7307 struct bpf_reg_state saved_reg;
7308 struct bpf_call_arg_meta meta;
7311 if (register_is_null(reg))
7314 memset(&meta, 0, sizeof(meta));
7315 /* Assuming that the register contains a value check if the memory
7316 * access is safe. Temporarily save and restore the register's state as
7317 * the conversion shouldn't be visible to a caller.
7321 mark_ptr_not_null_reg(reg);
7324 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7325 /* Check access for BPF_WRITE */
7326 meta.raw_mode = true;
7327 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7335 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7338 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7339 bool may_be_null = type_may_be_null(mem_reg->type);
7340 struct bpf_reg_state saved_reg;
7341 struct bpf_call_arg_meta meta;
7344 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7346 memset(&meta, 0, sizeof(meta));
7349 saved_reg = *mem_reg;
7350 mark_ptr_not_null_reg(mem_reg);
7353 err = check_mem_size_reg(env, reg, regno, true, &meta);
7354 /* Check access for BPF_WRITE */
7355 meta.raw_mode = true;
7356 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7359 *mem_reg = saved_reg;
7363 /* Implementation details:
7364 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7365 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7366 * Two bpf_map_lookups (even with the same key) will have different reg->id.
7367 * Two separate bpf_obj_new will also have different reg->id.
7368 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7369 * clears reg->id after value_or_null->value transition, since the verifier only
7370 * cares about the range of access to valid map value pointer and doesn't care
7371 * about actual address of the map element.
7372 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7373 * reg->id > 0 after value_or_null->value transition. By doing so
7374 * two bpf_map_lookups will be considered two different pointers that
7375 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7376 * returned from bpf_obj_new.
7377 * The verifier allows taking only one bpf_spin_lock at a time to avoid
7379 * Since only one bpf_spin_lock is allowed the checks are simpler than
7380 * reg_is_refcounted() logic. The verifier needs to remember only
7381 * one spin_lock instead of array of acquired_refs.
7382 * cur_state->active_lock remembers which map value element or allocated
7383 * object got locked and clears it after bpf_spin_unlock.
7385 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7388 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7389 struct bpf_verifier_state *cur = env->cur_state;
7390 bool is_const = tnum_is_const(reg->var_off);
7391 u64 val = reg->var_off.value;
7392 struct bpf_map *map = NULL;
7393 struct btf *btf = NULL;
7394 struct btf_record *rec;
7398 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7402 if (reg->type == PTR_TO_MAP_VALUE) {
7406 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7414 rec = reg_btf_record(reg);
7415 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7416 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7417 map ? map->name : "kptr");
7420 if (rec->spin_lock_off != val + reg->off) {
7421 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7422 val + reg->off, rec->spin_lock_off);
7426 if (cur->active_lock.ptr) {
7428 "Locking two bpf_spin_locks are not allowed\n");
7432 cur->active_lock.ptr = map;
7434 cur->active_lock.ptr = btf;
7435 cur->active_lock.id = reg->id;
7444 if (!cur->active_lock.ptr) {
7445 verbose(env, "bpf_spin_unlock without taking a lock\n");
7448 if (cur->active_lock.ptr != ptr ||
7449 cur->active_lock.id != reg->id) {
7450 verbose(env, "bpf_spin_unlock of different lock\n");
7454 invalidate_non_owning_refs(env);
7456 cur->active_lock.ptr = NULL;
7457 cur->active_lock.id = 0;
7462 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7463 struct bpf_call_arg_meta *meta)
7465 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7466 bool is_const = tnum_is_const(reg->var_off);
7467 struct bpf_map *map = reg->map_ptr;
7468 u64 val = reg->var_off.value;
7472 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7477 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7481 if (!btf_record_has_field(map->record, BPF_TIMER)) {
7482 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7485 if (map->record->timer_off != val + reg->off) {
7486 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7487 val + reg->off, map->record->timer_off);
7490 if (meta->map_ptr) {
7491 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7494 meta->map_uid = reg->map_uid;
7495 meta->map_ptr = map;
7499 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7500 struct bpf_call_arg_meta *meta)
7502 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7503 struct bpf_map *map_ptr = reg->map_ptr;
7504 struct btf_field *kptr_field;
7507 if (!tnum_is_const(reg->var_off)) {
7509 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7513 if (!map_ptr->btf) {
7514 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7518 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7519 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7523 meta->map_ptr = map_ptr;
7524 kptr_off = reg->off + reg->var_off.value;
7525 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7527 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7530 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7531 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7534 meta->kptr_field = kptr_field;
7538 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7539 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7541 * In both cases we deal with the first 8 bytes, but need to mark the next 8
7542 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7543 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7545 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7546 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7547 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7548 * mutate the view of the dynptr and also possibly destroy it. In the latter
7549 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7550 * memory that dynptr points to.
7552 * The verifier will keep track both levels of mutation (bpf_dynptr's in
7553 * reg->type and the memory's in reg->dynptr.type), but there is no support for
7554 * readonly dynptr view yet, hence only the first case is tracked and checked.
7556 * This is consistent with how C applies the const modifier to a struct object,
7557 * where the pointer itself inside bpf_dynptr becomes const but not what it
7560 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7561 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7563 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7564 enum bpf_arg_type arg_type, int clone_ref_obj_id)
7566 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7569 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7570 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7572 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7573 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7577 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
7578 * constructing a mutable bpf_dynptr object.
7580 * Currently, this is only possible with PTR_TO_STACK
7581 * pointing to a region of at least 16 bytes which doesn't
7582 * contain an existing bpf_dynptr.
7584 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7585 * mutated or destroyed. However, the memory it points to
7588 * None - Points to a initialized dynptr that can be mutated and
7589 * destroyed, including mutation of the memory it points
7592 if (arg_type & MEM_UNINIT) {
7595 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7596 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7600 /* we write BPF_DW bits (8 bytes) at a time */
7601 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7602 err = check_mem_access(env, insn_idx, regno,
7603 i, BPF_DW, BPF_WRITE, -1, false, false);
7608 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7609 } else /* MEM_RDONLY and None case from above */ {
7610 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7611 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7612 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7616 if (!is_dynptr_reg_valid_init(env, reg)) {
7618 "Expected an initialized dynptr as arg #%d\n",
7623 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7624 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7626 "Expected a dynptr of type %s as arg #%d\n",
7627 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7631 err = mark_dynptr_read(env, reg);
7636 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7638 struct bpf_func_state *state = func(env, reg);
7640 return state->stack[spi].spilled_ptr.ref_obj_id;
7643 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7645 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7648 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7650 return meta->kfunc_flags & KF_ITER_NEW;
7653 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7655 return meta->kfunc_flags & KF_ITER_NEXT;
7658 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7660 return meta->kfunc_flags & KF_ITER_DESTROY;
7663 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7665 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7666 * kfunc is iter state pointer
7668 return arg == 0 && is_iter_kfunc(meta);
7671 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7672 struct bpf_kfunc_call_arg_meta *meta)
7674 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7675 const struct btf_type *t;
7676 const struct btf_param *arg;
7677 int spi, err, i, nr_slots;
7680 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7681 arg = &btf_params(meta->func_proto)[0];
7682 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
7683 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
7684 nr_slots = t->size / BPF_REG_SIZE;
7686 if (is_iter_new_kfunc(meta)) {
7687 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7688 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7689 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7690 iter_type_str(meta->btf, btf_id), regno);
7694 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7695 err = check_mem_access(env, insn_idx, regno,
7696 i, BPF_DW, BPF_WRITE, -1, false, false);
7701 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7705 /* iter_next() or iter_destroy() expect initialized iter state*/
7706 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7711 verbose(env, "expected an initialized iter_%s as arg #%d\n",
7712 iter_type_str(meta->btf, btf_id), regno);
7715 verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7721 spi = iter_get_spi(env, reg, nr_slots);
7725 err = mark_iter_read(env, reg, spi, nr_slots);
7729 /* remember meta->iter info for process_iter_next_call() */
7730 meta->iter.spi = spi;
7731 meta->iter.frameno = reg->frameno;
7732 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7734 if (is_iter_destroy_kfunc(meta)) {
7735 err = unmark_stack_slots_iter(env, reg, nr_slots);
7744 /* Look for a previous loop entry at insn_idx: nearest parent state
7745 * stopped at insn_idx with callsites matching those in cur->frame.
7747 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7748 struct bpf_verifier_state *cur,
7751 struct bpf_verifier_state_list *sl;
7752 struct bpf_verifier_state *st;
7754 /* Explored states are pushed in stack order, most recent states come first */
7755 sl = *explored_state(env, insn_idx);
7756 for (; sl; sl = sl->next) {
7757 /* If st->branches != 0 state is a part of current DFS verification path,
7758 * hence cur & st for a loop.
7761 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7762 st->dfs_depth < cur->dfs_depth)
7769 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7770 static bool regs_exact(const struct bpf_reg_state *rold,
7771 const struct bpf_reg_state *rcur,
7772 struct bpf_idmap *idmap);
7774 static void maybe_widen_reg(struct bpf_verifier_env *env,
7775 struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7776 struct bpf_idmap *idmap)
7778 if (rold->type != SCALAR_VALUE)
7780 if (rold->type != rcur->type)
7782 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7784 __mark_reg_unknown(env, rcur);
7787 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7788 struct bpf_verifier_state *old,
7789 struct bpf_verifier_state *cur)
7791 struct bpf_func_state *fold, *fcur;
7794 reset_idmap_scratch(env);
7795 for (fr = old->curframe; fr >= 0; fr--) {
7796 fold = old->frame[fr];
7797 fcur = cur->frame[fr];
7799 for (i = 0; i < MAX_BPF_REG; i++)
7800 maybe_widen_reg(env,
7803 &env->idmap_scratch);
7805 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7806 if (!is_spilled_reg(&fold->stack[i]) ||
7807 !is_spilled_reg(&fcur->stack[i]))
7810 maybe_widen_reg(env,
7811 &fold->stack[i].spilled_ptr,
7812 &fcur->stack[i].spilled_ptr,
7813 &env->idmap_scratch);
7819 /* process_iter_next_call() is called when verifier gets to iterator's next
7820 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7821 * to it as just "iter_next()" in comments below.
7823 * BPF verifier relies on a crucial contract for any iter_next()
7824 * implementation: it should *eventually* return NULL, and once that happens
7825 * it should keep returning NULL. That is, once iterator exhausts elements to
7826 * iterate, it should never reset or spuriously return new elements.
7828 * With the assumption of such contract, process_iter_next_call() simulates
7829 * a fork in the verifier state to validate loop logic correctness and safety
7830 * without having to simulate infinite amount of iterations.
7832 * In current state, we first assume that iter_next() returned NULL and
7833 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7834 * conditions we should not form an infinite loop and should eventually reach
7837 * Besides that, we also fork current state and enqueue it for later
7838 * verification. In a forked state we keep iterator state as ACTIVE
7839 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7840 * also bump iteration depth to prevent erroneous infinite loop detection
7841 * later on (see iter_active_depths_differ() comment for details). In this
7842 * state we assume that we'll eventually loop back to another iter_next()
7843 * calls (it could be in exactly same location or in some other instruction,
7844 * it doesn't matter, we don't make any unnecessary assumptions about this,
7845 * everything revolves around iterator state in a stack slot, not which
7846 * instruction is calling iter_next()). When that happens, we either will come
7847 * to iter_next() with equivalent state and can conclude that next iteration
7848 * will proceed in exactly the same way as we just verified, so it's safe to
7849 * assume that loop converges. If not, we'll go on another iteration
7850 * simulation with a different input state, until all possible starting states
7851 * are validated or we reach maximum number of instructions limit.
7853 * This way, we will either exhaustively discover all possible input states
7854 * that iterator loop can start with and eventually will converge, or we'll
7855 * effectively regress into bounded loop simulation logic and either reach
7856 * maximum number of instructions if loop is not provably convergent, or there
7857 * is some statically known limit on number of iterations (e.g., if there is
7858 * an explicit `if n > 100 then break;` statement somewhere in the loop).
7860 * Iteration convergence logic in is_state_visited() relies on exact
7861 * states comparison, which ignores read and precision marks.
7862 * This is necessary because read and precision marks are not finalized
7863 * while in the loop. Exact comparison might preclude convergence for
7864 * simple programs like below:
7867 * while(iter_next(&it))
7870 * At each iteration step i++ would produce a new distinct state and
7871 * eventually instruction processing limit would be reached.
7873 * To avoid such behavior speculatively forget (widen) range for
7874 * imprecise scalar registers, if those registers were not precise at the
7875 * end of the previous iteration and do not match exactly.
7877 * This is a conservative heuristic that allows to verify wide range of programs,
7878 * however it precludes verification of programs that conjure an
7879 * imprecise value on the first loop iteration and use it as precise on a second.
7880 * For example, the following safe program would fail to verify:
7882 * struct bpf_num_iter it;
7885 * bpf_iter_num_new(&it, 0, 10);
7886 * while (bpf_iter_num_next(&it)) {
7889 * i = 7; // Because i changed verifier would forget
7890 * // it's range on second loop entry.
7892 * arr[i] = 42; // This would fail to verify.
7895 * bpf_iter_num_destroy(&it);
7897 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7898 struct bpf_kfunc_call_arg_meta *meta)
7900 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7901 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7902 struct bpf_reg_state *cur_iter, *queued_iter;
7903 int iter_frameno = meta->iter.frameno;
7904 int iter_spi = meta->iter.spi;
7906 BTF_TYPE_EMIT(struct bpf_iter);
7908 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7910 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7911 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7912 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7913 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7917 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7918 /* Because iter_next() call is a checkpoint is_state_visitied()
7919 * should guarantee parent state with same call sites and insn_idx.
7921 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7922 !same_callsites(cur_st->parent, cur_st)) {
7923 verbose(env, "bug: bad parent state for iter next call");
7926 /* Note cur_st->parent in the call below, it is necessary to skip
7927 * checkpoint created for cur_st by is_state_visited()
7928 * right at this instruction.
7930 prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7931 /* branch out active iter state */
7932 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7936 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7937 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7938 queued_iter->iter.depth++;
7940 widen_imprecise_scalars(env, prev_st, queued_st);
7942 queued_fr = queued_st->frame[queued_st->curframe];
7943 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7946 /* switch to DRAINED state, but keep the depth unchanged */
7947 /* mark current iter state as drained and assume returned NULL */
7948 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7949 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
7954 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7956 return type == ARG_CONST_SIZE ||
7957 type == ARG_CONST_SIZE_OR_ZERO;
7960 static bool arg_type_is_release(enum bpf_arg_type type)
7962 return type & OBJ_RELEASE;
7965 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7967 return base_type(type) == ARG_PTR_TO_DYNPTR;
7970 static int int_ptr_type_to_size(enum bpf_arg_type type)
7972 if (type == ARG_PTR_TO_INT)
7974 else if (type == ARG_PTR_TO_LONG)
7980 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7981 const struct bpf_call_arg_meta *meta,
7982 enum bpf_arg_type *arg_type)
7984 if (!meta->map_ptr) {
7985 /* kernel subsystem misconfigured verifier */
7986 verbose(env, "invalid map_ptr to access map->type\n");
7990 switch (meta->map_ptr->map_type) {
7991 case BPF_MAP_TYPE_SOCKMAP:
7992 case BPF_MAP_TYPE_SOCKHASH:
7993 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7994 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7996 verbose(env, "invalid arg_type for sockmap/sockhash\n");
8000 case BPF_MAP_TYPE_BLOOM_FILTER:
8001 if (meta->func_id == BPF_FUNC_map_peek_elem)
8002 *arg_type = ARG_PTR_TO_MAP_VALUE;
8010 struct bpf_reg_types {
8011 const enum bpf_reg_type types[10];
8015 static const struct bpf_reg_types sock_types = {
8025 static const struct bpf_reg_types btf_id_sock_common_types = {
8032 PTR_TO_BTF_ID | PTR_TRUSTED,
8034 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8038 static const struct bpf_reg_types mem_types = {
8046 PTR_TO_MEM | MEM_RINGBUF,
8048 PTR_TO_BTF_ID | PTR_TRUSTED,
8052 static const struct bpf_reg_types int_ptr_types = {
8062 static const struct bpf_reg_types spin_lock_types = {
8065 PTR_TO_BTF_ID | MEM_ALLOC,
8069 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8070 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8071 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8072 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8073 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8074 static const struct bpf_reg_types btf_ptr_types = {
8077 PTR_TO_BTF_ID | PTR_TRUSTED,
8078 PTR_TO_BTF_ID | MEM_RCU,
8081 static const struct bpf_reg_types percpu_btf_ptr_types = {
8083 PTR_TO_BTF_ID | MEM_PERCPU,
8084 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8085 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8088 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8089 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8090 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8091 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8092 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8093 static const struct bpf_reg_types dynptr_types = {
8096 CONST_PTR_TO_DYNPTR,
8100 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8101 [ARG_PTR_TO_MAP_KEY] = &mem_types,
8102 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
8103 [ARG_CONST_SIZE] = &scalar_types,
8104 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
8105 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
8106 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
8107 [ARG_PTR_TO_CTX] = &context_types,
8108 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
8110 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
8112 [ARG_PTR_TO_SOCKET] = &fullsock_types,
8113 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
8114 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
8115 [ARG_PTR_TO_MEM] = &mem_types,
8116 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
8117 [ARG_PTR_TO_INT] = &int_ptr_types,
8118 [ARG_PTR_TO_LONG] = &int_ptr_types,
8119 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
8120 [ARG_PTR_TO_FUNC] = &func_ptr_types,
8121 [ARG_PTR_TO_STACK] = &stack_ptr_types,
8122 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
8123 [ARG_PTR_TO_TIMER] = &timer_types,
8124 [ARG_PTR_TO_KPTR] = &kptr_types,
8125 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
8128 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8129 enum bpf_arg_type arg_type,
8130 const u32 *arg_btf_id,
8131 struct bpf_call_arg_meta *meta)
8133 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8134 enum bpf_reg_type expected, type = reg->type;
8135 const struct bpf_reg_types *compatible;
8138 compatible = compatible_reg_types[base_type(arg_type)];
8140 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8144 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8145 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8147 * Same for MAYBE_NULL:
8149 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8150 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8152 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8154 * Therefore we fold these flags depending on the arg_type before comparison.
8156 if (arg_type & MEM_RDONLY)
8157 type &= ~MEM_RDONLY;
8158 if (arg_type & PTR_MAYBE_NULL)
8159 type &= ~PTR_MAYBE_NULL;
8160 if (base_type(arg_type) == ARG_PTR_TO_MEM)
8161 type &= ~DYNPTR_TYPE_FLAG_MASK;
8163 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) {
8165 type &= ~MEM_PERCPU;
8168 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8169 expected = compatible->types[i];
8170 if (expected == NOT_INIT)
8173 if (type == expected)
8177 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8178 for (j = 0; j + 1 < i; j++)
8179 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8180 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8184 if (base_type(reg->type) != PTR_TO_BTF_ID)
8187 if (compatible == &mem_types) {
8188 if (!(arg_type & MEM_RDONLY)) {
8190 "%s() may write into memory pointed by R%d type=%s\n",
8191 func_id_name(meta->func_id),
8192 regno, reg_type_str(env, reg->type));
8198 switch ((int)reg->type) {
8200 case PTR_TO_BTF_ID | PTR_TRUSTED:
8201 case PTR_TO_BTF_ID | MEM_RCU:
8202 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8203 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8205 /* For bpf_sk_release, it needs to match against first member
8206 * 'struct sock_common', hence make an exception for it. This
8207 * allows bpf_sk_release to work for multiple socket types.
8209 bool strict_type_match = arg_type_is_release(arg_type) &&
8210 meta->func_id != BPF_FUNC_sk_release;
8212 if (type_may_be_null(reg->type) &&
8213 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8214 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8219 if (!compatible->btf_id) {
8220 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8223 arg_btf_id = compatible->btf_id;
8226 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8227 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8230 if (arg_btf_id == BPF_PTR_POISON) {
8231 verbose(env, "verifier internal error:");
8232 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8237 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8238 btf_vmlinux, *arg_btf_id,
8239 strict_type_match)) {
8240 verbose(env, "R%d is of type %s but %s is expected\n",
8241 regno, btf_type_name(reg->btf, reg->btf_id),
8242 btf_type_name(btf_vmlinux, *arg_btf_id));
8248 case PTR_TO_BTF_ID | MEM_ALLOC:
8249 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8250 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8251 meta->func_id != BPF_FUNC_kptr_xchg) {
8252 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8255 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8256 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8260 case PTR_TO_BTF_ID | MEM_PERCPU:
8261 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8262 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8263 /* Handled by helper specific checks */
8266 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8272 static struct btf_field *
8273 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8275 struct btf_field *field;
8276 struct btf_record *rec;
8278 rec = reg_btf_record(reg);
8282 field = btf_record_find(rec, off, fields);
8289 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8290 const struct bpf_reg_state *reg, int regno,
8291 enum bpf_arg_type arg_type)
8293 u32 type = reg->type;
8295 /* When referenced register is passed to release function, its fixed
8298 * We will check arg_type_is_release reg has ref_obj_id when storing
8299 * meta->release_regno.
8301 if (arg_type_is_release(arg_type)) {
8302 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8303 * may not directly point to the object being released, but to
8304 * dynptr pointing to such object, which might be at some offset
8305 * on the stack. In that case, we simply to fallback to the
8308 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8311 /* Doing check_ptr_off_reg check for the offset will catch this
8312 * because fixed_off_ok is false, but checking here allows us
8313 * to give the user a better error message.
8316 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8320 return __check_ptr_off_reg(env, reg, regno, false);
8324 /* Pointer types where both fixed and variable offset is explicitly allowed: */
8327 case PTR_TO_PACKET_META:
8328 case PTR_TO_MAP_KEY:
8329 case PTR_TO_MAP_VALUE:
8331 case PTR_TO_MEM | MEM_RDONLY:
8332 case PTR_TO_MEM | MEM_RINGBUF:
8334 case PTR_TO_BUF | MEM_RDONLY:
8337 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8341 case PTR_TO_BTF_ID | MEM_ALLOC:
8342 case PTR_TO_BTF_ID | PTR_TRUSTED:
8343 case PTR_TO_BTF_ID | MEM_RCU:
8344 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8345 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8346 /* When referenced PTR_TO_BTF_ID is passed to release function,
8347 * its fixed offset must be 0. In the other cases, fixed offset
8348 * can be non-zero. This was already checked above. So pass
8349 * fixed_off_ok as true to allow fixed offset for all other
8350 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8351 * still need to do checks instead of returning.
8353 return __check_ptr_off_reg(env, reg, regno, true);
8355 return __check_ptr_off_reg(env, reg, regno, false);
8359 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8360 const struct bpf_func_proto *fn,
8361 struct bpf_reg_state *regs)
8363 struct bpf_reg_state *state = NULL;
8366 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8367 if (arg_type_is_dynptr(fn->arg_type[i])) {
8369 verbose(env, "verifier internal error: multiple dynptr args\n");
8372 state = ®s[BPF_REG_1 + i];
8376 verbose(env, "verifier internal error: no dynptr arg found\n");
8381 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8383 struct bpf_func_state *state = func(env, reg);
8386 if (reg->type == CONST_PTR_TO_DYNPTR)
8388 spi = dynptr_get_spi(env, reg);
8391 return state->stack[spi].spilled_ptr.id;
8394 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8396 struct bpf_func_state *state = func(env, reg);
8399 if (reg->type == CONST_PTR_TO_DYNPTR)
8400 return reg->ref_obj_id;
8401 spi = dynptr_get_spi(env, reg);
8404 return state->stack[spi].spilled_ptr.ref_obj_id;
8407 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8408 struct bpf_reg_state *reg)
8410 struct bpf_func_state *state = func(env, reg);
8413 if (reg->type == CONST_PTR_TO_DYNPTR)
8414 return reg->dynptr.type;
8416 spi = __get_spi(reg->off);
8418 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8419 return BPF_DYNPTR_TYPE_INVALID;
8422 return state->stack[spi].spilled_ptr.dynptr.type;
8425 static int check_reg_const_str(struct bpf_verifier_env *env,
8426 struct bpf_reg_state *reg, u32 regno)
8428 struct bpf_map *map = reg->map_ptr;
8434 if (reg->type != PTR_TO_MAP_VALUE)
8437 if (!bpf_map_is_rdonly(map)) {
8438 verbose(env, "R%d does not point to a readonly map'\n", regno);
8442 if (!tnum_is_const(reg->var_off)) {
8443 verbose(env, "R%d is not a constant address'\n", regno);
8447 if (!map->ops->map_direct_value_addr) {
8448 verbose(env, "no direct value access support for this map type\n");
8452 err = check_map_access(env, regno, reg->off,
8453 map->value_size - reg->off, false,
8458 map_off = reg->off + reg->var_off.value;
8459 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8461 verbose(env, "direct value access on string failed\n");
8465 str_ptr = (char *)(long)(map_addr);
8466 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8467 verbose(env, "string is not zero-terminated\n");
8473 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8474 struct bpf_call_arg_meta *meta,
8475 const struct bpf_func_proto *fn,
8478 u32 regno = BPF_REG_1 + arg;
8479 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8480 enum bpf_arg_type arg_type = fn->arg_type[arg];
8481 enum bpf_reg_type type = reg->type;
8482 u32 *arg_btf_id = NULL;
8485 if (arg_type == ARG_DONTCARE)
8488 err = check_reg_arg(env, regno, SRC_OP);
8492 if (arg_type == ARG_ANYTHING) {
8493 if (is_pointer_value(env, regno)) {
8494 verbose(env, "R%d leaks addr into helper function\n",
8501 if (type_is_pkt_pointer(type) &&
8502 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8503 verbose(env, "helper access to the packet is not allowed\n");
8507 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8508 err = resolve_map_arg_type(env, meta, &arg_type);
8513 if (register_is_null(reg) && type_may_be_null(arg_type))
8514 /* A NULL register has a SCALAR_VALUE type, so skip
8517 goto skip_type_check;
8519 /* arg_btf_id and arg_size are in a union. */
8520 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8521 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8522 arg_btf_id = fn->arg_btf_id[arg];
8524 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8528 err = check_func_arg_reg_off(env, reg, regno, arg_type);
8533 if (arg_type_is_release(arg_type)) {
8534 if (arg_type_is_dynptr(arg_type)) {
8535 struct bpf_func_state *state = func(env, reg);
8538 /* Only dynptr created on stack can be released, thus
8539 * the get_spi and stack state checks for spilled_ptr
8540 * should only be done before process_dynptr_func for
8543 if (reg->type == PTR_TO_STACK) {
8544 spi = dynptr_get_spi(env, reg);
8545 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8546 verbose(env, "arg %d is an unacquired reference\n", regno);
8550 verbose(env, "cannot release unowned const bpf_dynptr\n");
8553 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8554 verbose(env, "R%d must be referenced when passed to release function\n",
8558 if (meta->release_regno) {
8559 verbose(env, "verifier internal error: more than one release argument\n");
8562 meta->release_regno = regno;
8565 if (reg->ref_obj_id) {
8566 if (meta->ref_obj_id) {
8567 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8568 regno, reg->ref_obj_id,
8572 meta->ref_obj_id = reg->ref_obj_id;
8575 switch (base_type(arg_type)) {
8576 case ARG_CONST_MAP_PTR:
8577 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8578 if (meta->map_ptr) {
8579 /* Use map_uid (which is unique id of inner map) to reject:
8580 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8581 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8582 * if (inner_map1 && inner_map2) {
8583 * timer = bpf_map_lookup_elem(inner_map1);
8585 * // mismatch would have been allowed
8586 * bpf_timer_init(timer, inner_map2);
8589 * Comparing map_ptr is enough to distinguish normal and outer maps.
8591 if (meta->map_ptr != reg->map_ptr ||
8592 meta->map_uid != reg->map_uid) {
8594 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8595 meta->map_uid, reg->map_uid);
8599 meta->map_ptr = reg->map_ptr;
8600 meta->map_uid = reg->map_uid;
8602 case ARG_PTR_TO_MAP_KEY:
8603 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8604 * check that [key, key + map->key_size) are within
8605 * stack limits and initialized
8607 if (!meta->map_ptr) {
8608 /* in function declaration map_ptr must come before
8609 * map_key, so that it's verified and known before
8610 * we have to check map_key here. Otherwise it means
8611 * that kernel subsystem misconfigured verifier
8613 verbose(env, "invalid map_ptr to access map->key\n");
8616 err = check_helper_mem_access(env, regno,
8617 meta->map_ptr->key_size, false,
8620 case ARG_PTR_TO_MAP_VALUE:
8621 if (type_may_be_null(arg_type) && register_is_null(reg))
8624 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8625 * check [value, value + map->value_size) validity
8627 if (!meta->map_ptr) {
8628 /* kernel subsystem misconfigured verifier */
8629 verbose(env, "invalid map_ptr to access map->value\n");
8632 meta->raw_mode = arg_type & MEM_UNINIT;
8633 err = check_helper_mem_access(env, regno,
8634 meta->map_ptr->value_size, false,
8637 case ARG_PTR_TO_PERCPU_BTF_ID:
8639 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8642 meta->ret_btf = reg->btf;
8643 meta->ret_btf_id = reg->btf_id;
8645 case ARG_PTR_TO_SPIN_LOCK:
8646 if (in_rbtree_lock_required_cb(env)) {
8647 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8650 if (meta->func_id == BPF_FUNC_spin_lock) {
8651 err = process_spin_lock(env, regno, true);
8654 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8655 err = process_spin_lock(env, regno, false);
8659 verbose(env, "verifier internal error\n");
8663 case ARG_PTR_TO_TIMER:
8664 err = process_timer_func(env, regno, meta);
8668 case ARG_PTR_TO_FUNC:
8669 meta->subprogno = reg->subprogno;
8671 case ARG_PTR_TO_MEM:
8672 /* The access to this pointer is only checked when we hit the
8673 * next is_mem_size argument below.
8675 meta->raw_mode = arg_type & MEM_UNINIT;
8676 if (arg_type & MEM_FIXED_SIZE) {
8677 err = check_helper_mem_access(env, regno,
8678 fn->arg_size[arg], false,
8682 case ARG_CONST_SIZE:
8683 err = check_mem_size_reg(env, reg, regno, false, meta);
8685 case ARG_CONST_SIZE_OR_ZERO:
8686 err = check_mem_size_reg(env, reg, regno, true, meta);
8688 case ARG_PTR_TO_DYNPTR:
8689 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8693 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8694 if (!tnum_is_const(reg->var_off)) {
8695 verbose(env, "R%d is not a known constant'\n",
8699 meta->mem_size = reg->var_off.value;
8700 err = mark_chain_precision(env, regno);
8704 case ARG_PTR_TO_INT:
8705 case ARG_PTR_TO_LONG:
8707 int size = int_ptr_type_to_size(arg_type);
8709 err = check_helper_mem_access(env, regno, size, false, meta);
8712 err = check_ptr_alignment(env, reg, 0, size, true);
8715 case ARG_PTR_TO_CONST_STR:
8717 err = check_reg_const_str(env, reg, regno);
8722 case ARG_PTR_TO_KPTR:
8723 err = process_kptr_func(env, regno, meta);
8732 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8734 enum bpf_attach_type eatype = env->prog->expected_attach_type;
8735 enum bpf_prog_type type = resolve_prog_type(env->prog);
8737 if (func_id != BPF_FUNC_map_update_elem)
8740 /* It's not possible to get access to a locked struct sock in these
8741 * contexts, so updating is safe.
8744 case BPF_PROG_TYPE_TRACING:
8745 if (eatype == BPF_TRACE_ITER)
8748 case BPF_PROG_TYPE_SOCKET_FILTER:
8749 case BPF_PROG_TYPE_SCHED_CLS:
8750 case BPF_PROG_TYPE_SCHED_ACT:
8751 case BPF_PROG_TYPE_XDP:
8752 case BPF_PROG_TYPE_SK_REUSEPORT:
8753 case BPF_PROG_TYPE_FLOW_DISSECTOR:
8754 case BPF_PROG_TYPE_SK_LOOKUP:
8760 verbose(env, "cannot update sockmap in this context\n");
8764 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8766 return env->prog->jit_requested &&
8767 bpf_jit_supports_subprog_tailcalls();
8770 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8771 struct bpf_map *map, int func_id)
8776 /* We need a two way check, first is from map perspective ... */
8777 switch (map->map_type) {
8778 case BPF_MAP_TYPE_PROG_ARRAY:
8779 if (func_id != BPF_FUNC_tail_call)
8782 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8783 if (func_id != BPF_FUNC_perf_event_read &&
8784 func_id != BPF_FUNC_perf_event_output &&
8785 func_id != BPF_FUNC_skb_output &&
8786 func_id != BPF_FUNC_perf_event_read_value &&
8787 func_id != BPF_FUNC_xdp_output)
8790 case BPF_MAP_TYPE_RINGBUF:
8791 if (func_id != BPF_FUNC_ringbuf_output &&
8792 func_id != BPF_FUNC_ringbuf_reserve &&
8793 func_id != BPF_FUNC_ringbuf_query &&
8794 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8795 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8796 func_id != BPF_FUNC_ringbuf_discard_dynptr)
8799 case BPF_MAP_TYPE_USER_RINGBUF:
8800 if (func_id != BPF_FUNC_user_ringbuf_drain)
8803 case BPF_MAP_TYPE_STACK_TRACE:
8804 if (func_id != BPF_FUNC_get_stackid)
8807 case BPF_MAP_TYPE_CGROUP_ARRAY:
8808 if (func_id != BPF_FUNC_skb_under_cgroup &&
8809 func_id != BPF_FUNC_current_task_under_cgroup)
8812 case BPF_MAP_TYPE_CGROUP_STORAGE:
8813 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8814 if (func_id != BPF_FUNC_get_local_storage)
8817 case BPF_MAP_TYPE_DEVMAP:
8818 case BPF_MAP_TYPE_DEVMAP_HASH:
8819 if (func_id != BPF_FUNC_redirect_map &&
8820 func_id != BPF_FUNC_map_lookup_elem)
8823 /* Restrict bpf side of cpumap and xskmap, open when use-cases
8826 case BPF_MAP_TYPE_CPUMAP:
8827 if (func_id != BPF_FUNC_redirect_map)
8830 case BPF_MAP_TYPE_XSKMAP:
8831 if (func_id != BPF_FUNC_redirect_map &&
8832 func_id != BPF_FUNC_map_lookup_elem)
8835 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8836 case BPF_MAP_TYPE_HASH_OF_MAPS:
8837 if (func_id != BPF_FUNC_map_lookup_elem)
8840 case BPF_MAP_TYPE_SOCKMAP:
8841 if (func_id != BPF_FUNC_sk_redirect_map &&
8842 func_id != BPF_FUNC_sock_map_update &&
8843 func_id != BPF_FUNC_map_delete_elem &&
8844 func_id != BPF_FUNC_msg_redirect_map &&
8845 func_id != BPF_FUNC_sk_select_reuseport &&
8846 func_id != BPF_FUNC_map_lookup_elem &&
8847 !may_update_sockmap(env, func_id))
8850 case BPF_MAP_TYPE_SOCKHASH:
8851 if (func_id != BPF_FUNC_sk_redirect_hash &&
8852 func_id != BPF_FUNC_sock_hash_update &&
8853 func_id != BPF_FUNC_map_delete_elem &&
8854 func_id != BPF_FUNC_msg_redirect_hash &&
8855 func_id != BPF_FUNC_sk_select_reuseport &&
8856 func_id != BPF_FUNC_map_lookup_elem &&
8857 !may_update_sockmap(env, func_id))
8860 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8861 if (func_id != BPF_FUNC_sk_select_reuseport)
8864 case BPF_MAP_TYPE_QUEUE:
8865 case BPF_MAP_TYPE_STACK:
8866 if (func_id != BPF_FUNC_map_peek_elem &&
8867 func_id != BPF_FUNC_map_pop_elem &&
8868 func_id != BPF_FUNC_map_push_elem)
8871 case BPF_MAP_TYPE_SK_STORAGE:
8872 if (func_id != BPF_FUNC_sk_storage_get &&
8873 func_id != BPF_FUNC_sk_storage_delete &&
8874 func_id != BPF_FUNC_kptr_xchg)
8877 case BPF_MAP_TYPE_INODE_STORAGE:
8878 if (func_id != BPF_FUNC_inode_storage_get &&
8879 func_id != BPF_FUNC_inode_storage_delete &&
8880 func_id != BPF_FUNC_kptr_xchg)
8883 case BPF_MAP_TYPE_TASK_STORAGE:
8884 if (func_id != BPF_FUNC_task_storage_get &&
8885 func_id != BPF_FUNC_task_storage_delete &&
8886 func_id != BPF_FUNC_kptr_xchg)
8889 case BPF_MAP_TYPE_CGRP_STORAGE:
8890 if (func_id != BPF_FUNC_cgrp_storage_get &&
8891 func_id != BPF_FUNC_cgrp_storage_delete &&
8892 func_id != BPF_FUNC_kptr_xchg)
8895 case BPF_MAP_TYPE_BLOOM_FILTER:
8896 if (func_id != BPF_FUNC_map_peek_elem &&
8897 func_id != BPF_FUNC_map_push_elem)
8904 /* ... and second from the function itself. */
8906 case BPF_FUNC_tail_call:
8907 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8909 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8910 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8914 case BPF_FUNC_perf_event_read:
8915 case BPF_FUNC_perf_event_output:
8916 case BPF_FUNC_perf_event_read_value:
8917 case BPF_FUNC_skb_output:
8918 case BPF_FUNC_xdp_output:
8919 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8922 case BPF_FUNC_ringbuf_output:
8923 case BPF_FUNC_ringbuf_reserve:
8924 case BPF_FUNC_ringbuf_query:
8925 case BPF_FUNC_ringbuf_reserve_dynptr:
8926 case BPF_FUNC_ringbuf_submit_dynptr:
8927 case BPF_FUNC_ringbuf_discard_dynptr:
8928 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8931 case BPF_FUNC_user_ringbuf_drain:
8932 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8935 case BPF_FUNC_get_stackid:
8936 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8939 case BPF_FUNC_current_task_under_cgroup:
8940 case BPF_FUNC_skb_under_cgroup:
8941 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8944 case BPF_FUNC_redirect_map:
8945 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8946 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8947 map->map_type != BPF_MAP_TYPE_CPUMAP &&
8948 map->map_type != BPF_MAP_TYPE_XSKMAP)
8951 case BPF_FUNC_sk_redirect_map:
8952 case BPF_FUNC_msg_redirect_map:
8953 case BPF_FUNC_sock_map_update:
8954 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8957 case BPF_FUNC_sk_redirect_hash:
8958 case BPF_FUNC_msg_redirect_hash:
8959 case BPF_FUNC_sock_hash_update:
8960 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8963 case BPF_FUNC_get_local_storage:
8964 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8965 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8968 case BPF_FUNC_sk_select_reuseport:
8969 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8970 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8971 map->map_type != BPF_MAP_TYPE_SOCKHASH)
8974 case BPF_FUNC_map_pop_elem:
8975 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8976 map->map_type != BPF_MAP_TYPE_STACK)
8979 case BPF_FUNC_map_peek_elem:
8980 case BPF_FUNC_map_push_elem:
8981 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8982 map->map_type != BPF_MAP_TYPE_STACK &&
8983 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8986 case BPF_FUNC_map_lookup_percpu_elem:
8987 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8988 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8989 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8992 case BPF_FUNC_sk_storage_get:
8993 case BPF_FUNC_sk_storage_delete:
8994 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8997 case BPF_FUNC_inode_storage_get:
8998 case BPF_FUNC_inode_storage_delete:
8999 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9002 case BPF_FUNC_task_storage_get:
9003 case BPF_FUNC_task_storage_delete:
9004 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9007 case BPF_FUNC_cgrp_storage_get:
9008 case BPF_FUNC_cgrp_storage_delete:
9009 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9018 verbose(env, "cannot pass map_type %d into func %s#%d\n",
9019 map->map_type, func_id_name(func_id), func_id);
9023 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9027 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9029 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9031 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9033 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9035 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9038 /* We only support one arg being in raw mode at the moment,
9039 * which is sufficient for the helper functions we have
9045 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9047 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9048 bool has_size = fn->arg_size[arg] != 0;
9049 bool is_next_size = false;
9051 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9052 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9054 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9055 return is_next_size;
9057 return has_size == is_next_size || is_next_size == is_fixed;
9060 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9062 /* bpf_xxx(..., buf, len) call will access 'len'
9063 * bytes from memory 'buf'. Both arg types need
9064 * to be paired, so make sure there's no buggy
9065 * helper function specification.
9067 if (arg_type_is_mem_size(fn->arg1_type) ||
9068 check_args_pair_invalid(fn, 0) ||
9069 check_args_pair_invalid(fn, 1) ||
9070 check_args_pair_invalid(fn, 2) ||
9071 check_args_pair_invalid(fn, 3) ||
9072 check_args_pair_invalid(fn, 4))
9078 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9082 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9083 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9084 return !!fn->arg_btf_id[i];
9085 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9086 return fn->arg_btf_id[i] == BPF_PTR_POISON;
9087 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9088 /* arg_btf_id and arg_size are in a union. */
9089 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9090 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9097 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9099 return check_raw_mode_ok(fn) &&
9100 check_arg_pair_ok(fn) &&
9101 check_btf_id_ok(fn) ? 0 : -EINVAL;
9104 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9105 * are now invalid, so turn them into unknown SCALAR_VALUE.
9107 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9108 * since these slices point to packet data.
9110 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9112 struct bpf_func_state *state;
9113 struct bpf_reg_state *reg;
9115 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9116 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9117 mark_reg_invalid(env, reg);
9123 BEYOND_PKT_END = -2,
9126 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9128 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9129 struct bpf_reg_state *reg = &state->regs[regn];
9131 if (reg->type != PTR_TO_PACKET)
9132 /* PTR_TO_PACKET_META is not supported yet */
9135 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9136 * How far beyond pkt_end it goes is unknown.
9137 * if (!range_open) it's the case of pkt >= pkt_end
9138 * if (range_open) it's the case of pkt > pkt_end
9139 * hence this pointer is at least 1 byte bigger than pkt_end
9142 reg->range = BEYOND_PKT_END;
9144 reg->range = AT_PKT_END;
9147 /* The pointer with the specified id has released its reference to kernel
9148 * resources. Identify all copies of the same pointer and clear the reference.
9150 static int release_reference(struct bpf_verifier_env *env,
9153 struct bpf_func_state *state;
9154 struct bpf_reg_state *reg;
9157 err = release_reference_state(cur_func(env), ref_obj_id);
9161 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9162 if (reg->ref_obj_id == ref_obj_id)
9163 mark_reg_invalid(env, reg);
9169 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9171 struct bpf_func_state *unused;
9172 struct bpf_reg_state *reg;
9174 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9175 if (type_is_non_owning_ref(reg->type))
9176 mark_reg_invalid(env, reg);
9180 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9181 struct bpf_reg_state *regs)
9185 /* after the call registers r0 - r5 were scratched */
9186 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9187 mark_reg_not_init(env, regs, caller_saved[i]);
9188 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9192 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9193 struct bpf_func_state *caller,
9194 struct bpf_func_state *callee,
9197 static int set_callee_state(struct bpf_verifier_env *env,
9198 struct bpf_func_state *caller,
9199 struct bpf_func_state *callee, int insn_idx);
9201 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9202 set_callee_state_fn set_callee_state_cb,
9203 struct bpf_verifier_state *state)
9205 struct bpf_func_state *caller, *callee;
9208 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9209 verbose(env, "the call stack of %d frames is too deep\n",
9210 state->curframe + 2);
9214 if (state->frame[state->curframe + 1]) {
9215 verbose(env, "verifier bug. Frame %d already allocated\n",
9216 state->curframe + 1);
9220 caller = state->frame[state->curframe];
9221 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9224 state->frame[state->curframe + 1] = callee;
9226 /* callee cannot access r0, r6 - r9 for reading and has to write
9227 * into its own stack before reading from it.
9228 * callee can read/write into caller's stack
9230 init_func_state(env, callee,
9231 /* remember the callsite, it will be used by bpf_exit */
9233 state->curframe + 1 /* frameno within this callchain */,
9234 subprog /* subprog number within this prog */);
9235 /* Transfer references to the callee */
9236 err = copy_reference_state(callee, caller);
9237 err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9241 /* only increment it after check_reg_arg() finished */
9247 free_func_state(callee);
9248 state->frame[state->curframe + 1] = NULL;
9252 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9253 const struct btf *btf,
9254 struct bpf_reg_state *regs)
9256 struct bpf_subprog_info *sub = subprog_info(env, subprog);
9257 struct bpf_verifier_log *log = &env->log;
9261 ret = btf_prepare_func_args(env, subprog);
9265 /* check that BTF function arguments match actual types that the
9268 for (i = 0; i < sub->arg_cnt; i++) {
9270 struct bpf_reg_state *reg = ®s[regno];
9271 struct bpf_subprog_arg_info *arg = &sub->args[i];
9273 if (arg->arg_type == ARG_ANYTHING) {
9274 if (reg->type != SCALAR_VALUE) {
9275 bpf_log(log, "R%d is not a scalar\n", regno);
9278 } else if (arg->arg_type == ARG_PTR_TO_CTX) {
9279 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9282 /* If function expects ctx type in BTF check that caller
9283 * is passing PTR_TO_CTX.
9285 if (reg->type != PTR_TO_CTX) {
9286 bpf_log(log, "arg#%d expects pointer to ctx\n", i);
9289 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9290 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9293 if (check_mem_reg(env, reg, regno, arg->mem_size))
9295 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
9296 bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
9299 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
9300 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
9304 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
9313 /* Compare BTF of a function call with given bpf_reg_state.
9315 * EFAULT - there is a verifier bug. Abort verification.
9316 * EINVAL - there is a type mismatch or BTF is not available.
9317 * 0 - BTF matches with what bpf_reg_state expects.
9318 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9320 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9321 struct bpf_reg_state *regs)
9323 struct bpf_prog *prog = env->prog;
9324 struct btf *btf = prog->aux->btf;
9328 if (!prog->aux->func_info)
9331 btf_id = prog->aux->func_info[subprog].type_id;
9335 if (prog->aux->func_info_aux[subprog].unreliable)
9338 err = btf_check_func_arg_match(env, subprog, btf, regs);
9339 /* Compiler optimizations can remove arguments from static functions
9340 * or mismatched type can be passed into a global function.
9341 * In such cases mark the function as unreliable from BTF point of view.
9344 prog->aux->func_info_aux[subprog].unreliable = true;
9348 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9349 int insn_idx, int subprog,
9350 set_callee_state_fn set_callee_state_cb)
9352 struct bpf_verifier_state *state = env->cur_state, *callback_state;
9353 struct bpf_func_state *caller, *callee;
9356 caller = state->frame[state->curframe];
9357 err = btf_check_subprog_call(env, subprog, caller->regs);
9361 /* set_callee_state is used for direct subprog calls, but we are
9362 * interested in validating only BPF helpers that can call subprogs as
9365 env->subprog_info[subprog].is_cb = true;
9366 if (bpf_pseudo_kfunc_call(insn) &&
9367 !is_sync_callback_calling_kfunc(insn->imm)) {
9368 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9369 func_id_name(insn->imm), insn->imm);
9371 } else if (!bpf_pseudo_kfunc_call(insn) &&
9372 !is_callback_calling_function(insn->imm)) { /* helper */
9373 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9374 func_id_name(insn->imm), insn->imm);
9378 if (insn->code == (BPF_JMP | BPF_CALL) &&
9379 insn->src_reg == 0 &&
9380 insn->imm == BPF_FUNC_timer_set_callback) {
9381 struct bpf_verifier_state *async_cb;
9383 /* there is no real recursion here. timer callbacks are async */
9384 env->subprog_info[subprog].is_async_cb = true;
9385 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9389 callee = async_cb->frame[0];
9390 callee->async_entry_cnt = caller->async_entry_cnt + 1;
9392 /* Convert bpf_timer_set_callback() args into timer callback args */
9393 err = set_callee_state_cb(env, caller, callee, insn_idx);
9400 /* for callback functions enqueue entry to callback and
9401 * proceed with next instruction within current frame.
9403 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9404 if (!callback_state)
9407 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9412 callback_state->callback_unroll_depth++;
9413 callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9414 caller->callback_depth = 0;
9418 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9421 struct bpf_verifier_state *state = env->cur_state;
9422 struct bpf_func_state *caller;
9423 int err, subprog, target_insn;
9425 target_insn = *insn_idx + insn->imm + 1;
9426 subprog = find_subprog(env, target_insn);
9428 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9432 caller = state->frame[state->curframe];
9433 err = btf_check_subprog_call(env, subprog, caller->regs);
9436 if (subprog_is_global(env, subprog)) {
9437 const char *sub_name = subprog_name(env, subprog);
9440 verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9445 verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9447 /* mark global subprog for verifying after main prog */
9448 subprog_aux(env, subprog)->called = true;
9449 clear_caller_saved_regs(env, caller->regs);
9451 /* All global functions return a 64-bit SCALAR_VALUE */
9452 mark_reg_unknown(env, caller->regs, BPF_REG_0);
9453 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9455 /* continue with next insn after call */
9459 /* for regular function entry setup new frame and continue
9462 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9466 clear_caller_saved_regs(env, caller->regs);
9468 /* and go analyze first insn of the callee */
9469 *insn_idx = env->subprog_info[subprog].start - 1;
9471 if (env->log.level & BPF_LOG_LEVEL) {
9472 verbose(env, "caller:\n");
9473 print_verifier_state(env, caller, true);
9474 verbose(env, "callee:\n");
9475 print_verifier_state(env, state->frame[state->curframe], true);
9481 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9482 struct bpf_func_state *caller,
9483 struct bpf_func_state *callee)
9485 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9486 * void *callback_ctx, u64 flags);
9487 * callback_fn(struct bpf_map *map, void *key, void *value,
9488 * void *callback_ctx);
9490 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9492 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9493 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9494 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9496 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9497 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9498 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9500 /* pointer to stack or null */
9501 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9504 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9508 static int set_callee_state(struct bpf_verifier_env *env,
9509 struct bpf_func_state *caller,
9510 struct bpf_func_state *callee, int insn_idx)
9514 /* copy r1 - r5 args that callee can access. The copy includes parent
9515 * pointers, which connects us up to the liveness chain
9517 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9518 callee->regs[i] = caller->regs[i];
9522 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9523 struct bpf_func_state *caller,
9524 struct bpf_func_state *callee,
9527 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9528 struct bpf_map *map;
9531 if (bpf_map_ptr_poisoned(insn_aux)) {
9532 verbose(env, "tail_call abusing map_ptr\n");
9536 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9537 if (!map->ops->map_set_for_each_callback_args ||
9538 !map->ops->map_for_each_callback) {
9539 verbose(env, "callback function not allowed for map\n");
9543 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9547 callee->in_callback_fn = true;
9548 callee->callback_ret_range = retval_range(0, 1);
9552 static int set_loop_callback_state(struct bpf_verifier_env *env,
9553 struct bpf_func_state *caller,
9554 struct bpf_func_state *callee,
9557 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9559 * callback_fn(u32 index, void *callback_ctx);
9561 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9562 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9565 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9566 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9567 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9569 callee->in_callback_fn = true;
9570 callee->callback_ret_range = retval_range(0, 1);
9574 static int set_timer_callback_state(struct bpf_verifier_env *env,
9575 struct bpf_func_state *caller,
9576 struct bpf_func_state *callee,
9579 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9581 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9582 * callback_fn(struct bpf_map *map, void *key, void *value);
9584 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9585 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9586 callee->regs[BPF_REG_1].map_ptr = map_ptr;
9588 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9589 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9590 callee->regs[BPF_REG_2].map_ptr = map_ptr;
9592 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9593 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9594 callee->regs[BPF_REG_3].map_ptr = map_ptr;
9597 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9598 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9599 callee->in_async_callback_fn = true;
9600 callee->callback_ret_range = retval_range(0, 1);
9604 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9605 struct bpf_func_state *caller,
9606 struct bpf_func_state *callee,
9609 /* bpf_find_vma(struct task_struct *task, u64 addr,
9610 * void *callback_fn, void *callback_ctx, u64 flags)
9611 * (callback_fn)(struct task_struct *task,
9612 * struct vm_area_struct *vma, void *callback_ctx);
9614 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9616 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9617 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9618 callee->regs[BPF_REG_2].btf = btf_vmlinux;
9619 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
9621 /* pointer to stack or null */
9622 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9625 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9626 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9627 callee->in_callback_fn = true;
9628 callee->callback_ret_range = retval_range(0, 1);
9632 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9633 struct bpf_func_state *caller,
9634 struct bpf_func_state *callee,
9637 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9638 * callback_ctx, u64 flags);
9639 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9641 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9642 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9643 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9646 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9647 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9648 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9650 callee->in_callback_fn = true;
9651 callee->callback_ret_range = retval_range(0, 1);
9655 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9656 struct bpf_func_state *caller,
9657 struct bpf_func_state *callee,
9660 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9661 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9663 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9664 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9665 * by this point, so look at 'root'
9667 struct btf_field *field;
9669 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9671 if (!field || !field->graph_root.value_btf_id)
9674 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9675 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9676 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9677 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9679 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9680 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9681 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9682 callee->in_callback_fn = true;
9683 callee->callback_ret_range = retval_range(0, 1);
9687 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9689 /* Are we currently verifying the callback for a rbtree helper that must
9690 * be called with lock held? If so, no need to complain about unreleased
9693 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9695 struct bpf_verifier_state *state = env->cur_state;
9696 struct bpf_insn *insn = env->prog->insnsi;
9697 struct bpf_func_state *callee;
9700 if (!state->curframe)
9703 callee = state->frame[state->curframe];
9705 if (!callee->in_callback_fn)
9708 kfunc_btf_id = insn[callee->callsite].imm;
9709 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9712 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
9714 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
9717 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9719 struct bpf_verifier_state *state = env->cur_state, *prev_st;
9720 struct bpf_func_state *caller, *callee;
9721 struct bpf_reg_state *r0;
9722 bool in_callback_fn;
9725 callee = state->frame[state->curframe];
9726 r0 = &callee->regs[BPF_REG_0];
9727 if (r0->type == PTR_TO_STACK) {
9728 /* technically it's ok to return caller's stack pointer
9729 * (or caller's caller's pointer) back to the caller,
9730 * since these pointers are valid. Only current stack
9731 * pointer will be invalid as soon as function exits,
9732 * but let's be conservative
9734 verbose(env, "cannot return stack pointer to the caller\n");
9738 caller = state->frame[state->curframe - 1];
9739 if (callee->in_callback_fn) {
9740 if (r0->type != SCALAR_VALUE) {
9741 verbose(env, "R0 not a scalar value\n");
9745 /* we are going to rely on register's precise value */
9746 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9747 err = err ?: mark_chain_precision(env, BPF_REG_0);
9751 /* enforce R0 return value range */
9752 if (!retval_range_within(callee->callback_ret_range, r0)) {
9753 verbose_invalid_scalar(env, r0, callee->callback_ret_range,
9754 "At callback return", "R0");
9757 if (!calls_callback(env, callee->callsite)) {
9758 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9759 *insn_idx, callee->callsite);
9763 /* return to the caller whatever r0 had in the callee */
9764 caller->regs[BPF_REG_0] = *r0;
9767 /* callback_fn frame should have released its own additions to parent's
9768 * reference state at this point, or check_reference_leak would
9769 * complain, hence it must be the same as the caller. There is no need
9772 if (!callee->in_callback_fn) {
9773 /* Transfer references to the caller */
9774 err = copy_reference_state(caller, callee);
9779 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9780 * there function call logic would reschedule callback visit. If iteration
9781 * converges is_state_visited() would prune that visit eventually.
9783 in_callback_fn = callee->in_callback_fn;
9785 *insn_idx = callee->callsite;
9787 *insn_idx = callee->callsite + 1;
9789 if (env->log.level & BPF_LOG_LEVEL) {
9790 verbose(env, "returning from callee:\n");
9791 print_verifier_state(env, callee, true);
9792 verbose(env, "to caller at %d:\n", *insn_idx);
9793 print_verifier_state(env, caller, true);
9795 /* clear everything in the callee. In case of exceptional exits using
9796 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
9797 free_func_state(callee);
9798 state->frame[state->curframe--] = NULL;
9800 /* for callbacks widen imprecise scalars to make programs like below verify:
9802 * struct ctx { int i; }
9803 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9805 * struct ctx = { .i = 0; }
9806 * bpf_loop(100, cb, &ctx, 0);
9808 * This is similar to what is done in process_iter_next_call() for open
9811 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9813 err = widen_imprecise_scalars(env, prev_st, state);
9820 static int do_refine_retval_range(struct bpf_verifier_env *env,
9821 struct bpf_reg_state *regs, int ret_type,
9823 struct bpf_call_arg_meta *meta)
9825 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
9827 if (ret_type != RET_INTEGER)
9831 case BPF_FUNC_get_stack:
9832 case BPF_FUNC_get_task_stack:
9833 case BPF_FUNC_probe_read_str:
9834 case BPF_FUNC_probe_read_kernel_str:
9835 case BPF_FUNC_probe_read_user_str:
9836 ret_reg->smax_value = meta->msize_max_value;
9837 ret_reg->s32_max_value = meta->msize_max_value;
9838 ret_reg->smin_value = -MAX_ERRNO;
9839 ret_reg->s32_min_value = -MAX_ERRNO;
9840 reg_bounds_sync(ret_reg);
9842 case BPF_FUNC_get_smp_processor_id:
9843 ret_reg->umax_value = nr_cpu_ids - 1;
9844 ret_reg->u32_max_value = nr_cpu_ids - 1;
9845 ret_reg->smax_value = nr_cpu_ids - 1;
9846 ret_reg->s32_max_value = nr_cpu_ids - 1;
9847 ret_reg->umin_value = 0;
9848 ret_reg->u32_min_value = 0;
9849 ret_reg->smin_value = 0;
9850 ret_reg->s32_min_value = 0;
9851 reg_bounds_sync(ret_reg);
9855 return reg_bounds_sanity_check(env, ret_reg, "retval");
9859 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9860 int func_id, int insn_idx)
9862 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9863 struct bpf_map *map = meta->map_ptr;
9865 if (func_id != BPF_FUNC_tail_call &&
9866 func_id != BPF_FUNC_map_lookup_elem &&
9867 func_id != BPF_FUNC_map_update_elem &&
9868 func_id != BPF_FUNC_map_delete_elem &&
9869 func_id != BPF_FUNC_map_push_elem &&
9870 func_id != BPF_FUNC_map_pop_elem &&
9871 func_id != BPF_FUNC_map_peek_elem &&
9872 func_id != BPF_FUNC_for_each_map_elem &&
9873 func_id != BPF_FUNC_redirect_map &&
9874 func_id != BPF_FUNC_map_lookup_percpu_elem)
9878 verbose(env, "kernel subsystem misconfigured verifier\n");
9882 /* In case of read-only, some additional restrictions
9883 * need to be applied in order to prevent altering the
9884 * state of the map from program side.
9886 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9887 (func_id == BPF_FUNC_map_delete_elem ||
9888 func_id == BPF_FUNC_map_update_elem ||
9889 func_id == BPF_FUNC_map_push_elem ||
9890 func_id == BPF_FUNC_map_pop_elem)) {
9891 verbose(env, "write into map forbidden\n");
9895 if (!BPF_MAP_PTR(aux->map_ptr_state))
9896 bpf_map_ptr_store(aux, meta->map_ptr,
9897 !meta->map_ptr->bypass_spec_v1);
9898 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9899 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9900 !meta->map_ptr->bypass_spec_v1);
9905 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9906 int func_id, int insn_idx)
9908 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9909 struct bpf_reg_state *regs = cur_regs(env), *reg;
9910 struct bpf_map *map = meta->map_ptr;
9914 if (func_id != BPF_FUNC_tail_call)
9916 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9917 verbose(env, "kernel subsystem misconfigured verifier\n");
9921 reg = ®s[BPF_REG_3];
9922 val = reg->var_off.value;
9923 max = map->max_entries;
9925 if (!(is_reg_const(reg, false) && val < max)) {
9926 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9930 err = mark_chain_precision(env, BPF_REG_3);
9933 if (bpf_map_key_unseen(aux))
9934 bpf_map_key_store(aux, val);
9935 else if (!bpf_map_key_poisoned(aux) &&
9936 bpf_map_key_immediate(aux) != val)
9937 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9941 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
9943 struct bpf_func_state *state = cur_func(env);
9944 bool refs_lingering = false;
9947 if (!exception_exit && state->frameno && !state->in_callback_fn)
9950 for (i = 0; i < state->acquired_refs; i++) {
9951 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9953 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9954 state->refs[i].id, state->refs[i].insn_idx);
9955 refs_lingering = true;
9957 return refs_lingering ? -EINVAL : 0;
9960 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9961 struct bpf_reg_state *regs)
9963 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
9964 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
9965 struct bpf_map *fmt_map = fmt_reg->map_ptr;
9966 struct bpf_bprintf_data data = {};
9967 int err, fmt_map_off, num_args;
9971 /* data must be an array of u64 */
9972 if (data_len_reg->var_off.value % 8)
9974 num_args = data_len_reg->var_off.value / 8;
9976 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9977 * and map_direct_value_addr is set.
9979 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9980 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9983 verbose(env, "verifier bug\n");
9986 fmt = (char *)(long)fmt_addr + fmt_map_off;
9988 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9989 * can focus on validating the format specifiers.
9991 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9993 verbose(env, "Invalid format string\n");
9998 static int check_get_func_ip(struct bpf_verifier_env *env)
10000 enum bpf_prog_type type = resolve_prog_type(env->prog);
10001 int func_id = BPF_FUNC_get_func_ip;
10003 if (type == BPF_PROG_TYPE_TRACING) {
10004 if (!bpf_prog_has_trampoline(env->prog)) {
10005 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10006 func_id_name(func_id), func_id);
10010 } else if (type == BPF_PROG_TYPE_KPROBE) {
10014 verbose(env, "func %s#%d not supported for program type %d\n",
10015 func_id_name(func_id), func_id, type);
10019 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10021 return &env->insn_aux_data[env->insn_idx];
10024 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10026 struct bpf_reg_state *regs = cur_regs(env);
10027 struct bpf_reg_state *reg = ®s[BPF_REG_4];
10028 bool reg_is_null = register_is_null(reg);
10031 mark_chain_precision(env, BPF_REG_4);
10033 return reg_is_null;
10036 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10038 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10040 if (!state->initialized) {
10041 state->initialized = 1;
10042 state->fit_for_inline = loop_flag_is_zero(env);
10043 state->callback_subprogno = subprogno;
10047 if (!state->fit_for_inline)
10050 state->fit_for_inline = (loop_flag_is_zero(env) &&
10051 state->callback_subprogno == subprogno);
10054 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10057 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10058 bool returns_cpu_specific_alloc_ptr = false;
10059 const struct bpf_func_proto *fn = NULL;
10060 enum bpf_return_type ret_type;
10061 enum bpf_type_flag ret_flag;
10062 struct bpf_reg_state *regs;
10063 struct bpf_call_arg_meta meta;
10064 int insn_idx = *insn_idx_p;
10066 int i, err, func_id;
10068 /* find function prototype */
10069 func_id = insn->imm;
10070 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
10071 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
10076 if (env->ops->get_func_proto)
10077 fn = env->ops->get_func_proto(func_id, env->prog);
10079 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
10084 /* eBPF programs must be GPL compatible to use GPL-ed functions */
10085 if (!env->prog->gpl_compatible && fn->gpl_only) {
10086 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10090 if (fn->allowed && !fn->allowed(env->prog)) {
10091 verbose(env, "helper call is not allowed in probe\n");
10095 if (!env->prog->aux->sleepable && fn->might_sleep) {
10096 verbose(env, "helper call might sleep in a non-sleepable prog\n");
10100 /* With LD_ABS/IND some JITs save/restore skb from r1. */
10101 changes_data = bpf_helper_changes_pkt_data(fn->func);
10102 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10103 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10104 func_id_name(func_id), func_id);
10108 memset(&meta, 0, sizeof(meta));
10109 meta.pkt_access = fn->pkt_access;
10111 err = check_func_proto(fn, func_id);
10113 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10114 func_id_name(func_id), func_id);
10118 if (env->cur_state->active_rcu_lock) {
10119 if (fn->might_sleep) {
10120 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10121 func_id_name(func_id), func_id);
10125 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10126 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10129 meta.func_id = func_id;
10131 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10132 err = check_func_arg(env, i, &meta, fn, insn_idx);
10137 err = record_func_map(env, &meta, func_id, insn_idx);
10141 err = record_func_key(env, &meta, func_id, insn_idx);
10145 /* Mark slots with STACK_MISC in case of raw mode, stack offset
10146 * is inferred from register state.
10148 for (i = 0; i < meta.access_size; i++) {
10149 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10150 BPF_WRITE, -1, false, false);
10155 regs = cur_regs(env);
10157 if (meta.release_regno) {
10159 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10160 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10161 * is safe to do directly.
10163 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10164 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10165 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10168 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
10169 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10170 u32 ref_obj_id = meta.ref_obj_id;
10171 bool in_rcu = in_rcu_cs(env);
10172 struct bpf_func_state *state;
10173 struct bpf_reg_state *reg;
10175 err = release_reference_state(cur_func(env), ref_obj_id);
10177 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10178 if (reg->ref_obj_id == ref_obj_id) {
10179 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10180 reg->ref_obj_id = 0;
10181 reg->type &= ~MEM_ALLOC;
10182 reg->type |= MEM_RCU;
10184 mark_reg_invalid(env, reg);
10189 } else if (meta.ref_obj_id) {
10190 err = release_reference(env, meta.ref_obj_id);
10191 } else if (register_is_null(®s[meta.release_regno])) {
10192 /* meta.ref_obj_id can only be 0 if register that is meant to be
10193 * released is NULL, which must be > R0.
10198 verbose(env, "func %s#%d reference has not been acquired before\n",
10199 func_id_name(func_id), func_id);
10205 case BPF_FUNC_tail_call:
10206 err = check_reference_leak(env, false);
10208 verbose(env, "tail_call would lead to reference leak\n");
10212 case BPF_FUNC_get_local_storage:
10213 /* check that flags argument in get_local_storage(map, flags) is 0,
10214 * this is required because get_local_storage() can't return an error.
10216 if (!register_is_null(®s[BPF_REG_2])) {
10217 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10221 case BPF_FUNC_for_each_map_elem:
10222 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10223 set_map_elem_callback_state);
10225 case BPF_FUNC_timer_set_callback:
10226 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10227 set_timer_callback_state);
10229 case BPF_FUNC_find_vma:
10230 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10231 set_find_vma_callback_state);
10233 case BPF_FUNC_snprintf:
10234 err = check_bpf_snprintf_call(env, regs);
10236 case BPF_FUNC_loop:
10237 update_loop_inline_state(env, meta.subprogno);
10238 /* Verifier relies on R1 value to determine if bpf_loop() iteration
10239 * is finished, thus mark it precise.
10241 err = mark_chain_precision(env, BPF_REG_1);
10244 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10245 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10246 set_loop_callback_state);
10248 cur_func(env)->callback_depth = 0;
10249 if (env->log.level & BPF_LOG_LEVEL2)
10250 verbose(env, "frame%d bpf_loop iteration limit reached\n",
10251 env->cur_state->curframe);
10254 case BPF_FUNC_dynptr_from_mem:
10255 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10256 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10257 reg_type_str(env, regs[BPF_REG_1].type));
10261 case BPF_FUNC_set_retval:
10262 if (prog_type == BPF_PROG_TYPE_LSM &&
10263 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10264 if (!env->prog->aux->attach_func_proto->type) {
10265 /* Make sure programs that attach to void
10266 * hooks don't try to modify return value.
10268 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10273 case BPF_FUNC_dynptr_data:
10275 struct bpf_reg_state *reg;
10276 int id, ref_obj_id;
10278 reg = get_dynptr_arg_reg(env, fn, regs);
10283 if (meta.dynptr_id) {
10284 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10287 if (meta.ref_obj_id) {
10288 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10292 id = dynptr_id(env, reg);
10294 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10298 ref_obj_id = dynptr_ref_obj_id(env, reg);
10299 if (ref_obj_id < 0) {
10300 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10304 meta.dynptr_id = id;
10305 meta.ref_obj_id = ref_obj_id;
10309 case BPF_FUNC_dynptr_write:
10311 enum bpf_dynptr_type dynptr_type;
10312 struct bpf_reg_state *reg;
10314 reg = get_dynptr_arg_reg(env, fn, regs);
10318 dynptr_type = dynptr_get_type(env, reg);
10319 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10322 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10323 /* this will trigger clear_all_pkt_pointers(), which will
10324 * invalidate all dynptr slices associated with the skb
10326 changes_data = true;
10330 case BPF_FUNC_per_cpu_ptr:
10331 case BPF_FUNC_this_cpu_ptr:
10333 struct bpf_reg_state *reg = ®s[BPF_REG_1];
10334 const struct btf_type *type;
10336 if (reg->type & MEM_RCU) {
10337 type = btf_type_by_id(reg->btf, reg->btf_id);
10338 if (!type || !btf_type_is_struct(type)) {
10339 verbose(env, "Helper has invalid btf/btf_id in R1\n");
10342 returns_cpu_specific_alloc_ptr = true;
10343 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10347 case BPF_FUNC_user_ringbuf_drain:
10348 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10349 set_user_ringbuf_callback_state);
10356 /* reset caller saved regs */
10357 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10358 mark_reg_not_init(env, regs, caller_saved[i]);
10359 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10362 /* helper call returns 64-bit value. */
10363 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10365 /* update return register (already marked as written above) */
10366 ret_type = fn->ret_type;
10367 ret_flag = type_flag(ret_type);
10369 switch (base_type(ret_type)) {
10371 /* sets type to SCALAR_VALUE */
10372 mark_reg_unknown(env, regs, BPF_REG_0);
10375 regs[BPF_REG_0].type = NOT_INIT;
10377 case RET_PTR_TO_MAP_VALUE:
10378 /* There is no offset yet applied, variable or fixed */
10379 mark_reg_known_zero(env, regs, BPF_REG_0);
10380 /* remember map_ptr, so that check_map_access()
10381 * can check 'value_size' boundary of memory access
10382 * to map element returned from bpf_map_lookup_elem()
10384 if (meta.map_ptr == NULL) {
10386 "kernel subsystem misconfigured verifier\n");
10389 regs[BPF_REG_0].map_ptr = meta.map_ptr;
10390 regs[BPF_REG_0].map_uid = meta.map_uid;
10391 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10392 if (!type_may_be_null(ret_type) &&
10393 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10394 regs[BPF_REG_0].id = ++env->id_gen;
10397 case RET_PTR_TO_SOCKET:
10398 mark_reg_known_zero(env, regs, BPF_REG_0);
10399 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10401 case RET_PTR_TO_SOCK_COMMON:
10402 mark_reg_known_zero(env, regs, BPF_REG_0);
10403 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10405 case RET_PTR_TO_TCP_SOCK:
10406 mark_reg_known_zero(env, regs, BPF_REG_0);
10407 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10409 case RET_PTR_TO_MEM:
10410 mark_reg_known_zero(env, regs, BPF_REG_0);
10411 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10412 regs[BPF_REG_0].mem_size = meta.mem_size;
10414 case RET_PTR_TO_MEM_OR_BTF_ID:
10416 const struct btf_type *t;
10418 mark_reg_known_zero(env, regs, BPF_REG_0);
10419 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10420 if (!btf_type_is_struct(t)) {
10422 const struct btf_type *ret;
10425 /* resolve the type size of ksym. */
10426 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10428 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10429 verbose(env, "unable to resolve the size of type '%s': %ld\n",
10430 tname, PTR_ERR(ret));
10433 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10434 regs[BPF_REG_0].mem_size = tsize;
10436 if (returns_cpu_specific_alloc_ptr) {
10437 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10439 /* MEM_RDONLY may be carried from ret_flag, but it
10440 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10441 * it will confuse the check of PTR_TO_BTF_ID in
10442 * check_mem_access().
10444 ret_flag &= ~MEM_RDONLY;
10445 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10448 regs[BPF_REG_0].btf = meta.ret_btf;
10449 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10453 case RET_PTR_TO_BTF_ID:
10455 struct btf *ret_btf;
10458 mark_reg_known_zero(env, regs, BPF_REG_0);
10459 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10460 if (func_id == BPF_FUNC_kptr_xchg) {
10461 ret_btf = meta.kptr_field->kptr.btf;
10462 ret_btf_id = meta.kptr_field->kptr.btf_id;
10463 if (!btf_is_kernel(ret_btf)) {
10464 regs[BPF_REG_0].type |= MEM_ALLOC;
10465 if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10466 regs[BPF_REG_0].type |= MEM_PERCPU;
10469 if (fn->ret_btf_id == BPF_PTR_POISON) {
10470 verbose(env, "verifier internal error:");
10471 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10472 func_id_name(func_id));
10475 ret_btf = btf_vmlinux;
10476 ret_btf_id = *fn->ret_btf_id;
10478 if (ret_btf_id == 0) {
10479 verbose(env, "invalid return type %u of func %s#%d\n",
10480 base_type(ret_type), func_id_name(func_id),
10484 regs[BPF_REG_0].btf = ret_btf;
10485 regs[BPF_REG_0].btf_id = ret_btf_id;
10489 verbose(env, "unknown return type %u of func %s#%d\n",
10490 base_type(ret_type), func_id_name(func_id), func_id);
10494 if (type_may_be_null(regs[BPF_REG_0].type))
10495 regs[BPF_REG_0].id = ++env->id_gen;
10497 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10498 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10499 func_id_name(func_id), func_id);
10503 if (is_dynptr_ref_function(func_id))
10504 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10506 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10507 /* For release_reference() */
10508 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10509 } else if (is_acquire_function(func_id, meta.map_ptr)) {
10510 int id = acquire_reference_state(env, insn_idx);
10514 /* For mark_ptr_or_null_reg() */
10515 regs[BPF_REG_0].id = id;
10516 /* For release_reference() */
10517 regs[BPF_REG_0].ref_obj_id = id;
10520 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
10524 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10528 if ((func_id == BPF_FUNC_get_stack ||
10529 func_id == BPF_FUNC_get_task_stack) &&
10530 !env->prog->has_callchain_buf) {
10531 const char *err_str;
10533 #ifdef CONFIG_PERF_EVENTS
10534 err = get_callchain_buffers(sysctl_perf_event_max_stack);
10535 err_str = "cannot get callchain buffer for func %s#%d\n";
10538 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10541 verbose(env, err_str, func_id_name(func_id), func_id);
10545 env->prog->has_callchain_buf = true;
10548 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10549 env->prog->call_get_stack = true;
10551 if (func_id == BPF_FUNC_get_func_ip) {
10552 if (check_get_func_ip(env))
10554 env->prog->call_get_func_ip = true;
10558 clear_all_pkt_pointers(env);
10562 /* mark_btf_func_reg_size() is used when the reg size is determined by
10563 * the BTF func_proto's return value size and argument.
10565 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10568 struct bpf_reg_state *reg = &cur_regs(env)[regno];
10570 if (regno == BPF_REG_0) {
10571 /* Function return value */
10572 reg->live |= REG_LIVE_WRITTEN;
10573 reg->subreg_def = reg_size == sizeof(u64) ?
10574 DEF_NOT_SUBREG : env->insn_idx + 1;
10576 /* Function argument */
10577 if (reg_size == sizeof(u64)) {
10578 mark_insn_zext(env, reg);
10579 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10581 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10586 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10588 return meta->kfunc_flags & KF_ACQUIRE;
10591 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10593 return meta->kfunc_flags & KF_RELEASE;
10596 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10598 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10601 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10603 return meta->kfunc_flags & KF_SLEEPABLE;
10606 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10608 return meta->kfunc_flags & KF_DESTRUCTIVE;
10611 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10613 return meta->kfunc_flags & KF_RCU;
10616 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10618 return meta->kfunc_flags & KF_RCU_PROTECTED;
10621 static bool __kfunc_param_match_suffix(const struct btf *btf,
10622 const struct btf_param *arg,
10623 const char *suffix)
10625 int suffix_len = strlen(suffix), len;
10626 const char *param_name;
10628 /* In the future, this can be ported to use BTF tagging */
10629 param_name = btf_name_by_offset(btf, arg->name_off);
10630 if (str_is_empty(param_name))
10632 len = strlen(param_name);
10633 if (len < suffix_len)
10635 param_name += len - suffix_len;
10636 return !strncmp(param_name, suffix, suffix_len);
10639 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10640 const struct btf_param *arg,
10641 const struct bpf_reg_state *reg)
10643 const struct btf_type *t;
10645 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10646 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10649 return __kfunc_param_match_suffix(btf, arg, "__sz");
10652 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10653 const struct btf_param *arg,
10654 const struct bpf_reg_state *reg)
10656 const struct btf_type *t;
10658 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10659 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10662 return __kfunc_param_match_suffix(btf, arg, "__szk");
10665 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10667 return __kfunc_param_match_suffix(btf, arg, "__opt");
10670 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10672 return __kfunc_param_match_suffix(btf, arg, "__k");
10675 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10677 return __kfunc_param_match_suffix(btf, arg, "__ign");
10680 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10682 return __kfunc_param_match_suffix(btf, arg, "__alloc");
10685 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10687 return __kfunc_param_match_suffix(btf, arg, "__uninit");
10690 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10692 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10695 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10697 return __kfunc_param_match_suffix(btf, arg, "__nullable");
10700 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
10702 return __kfunc_param_match_suffix(btf, arg, "__str");
10705 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10706 const struct btf_param *arg,
10709 int len, target_len = strlen(name);
10710 const char *param_name;
10712 param_name = btf_name_by_offset(btf, arg->name_off);
10713 if (str_is_empty(param_name))
10715 len = strlen(param_name);
10716 if (len != target_len)
10718 if (strcmp(param_name, name))
10726 KF_ARG_LIST_HEAD_ID,
10727 KF_ARG_LIST_NODE_ID,
10732 BTF_ID_LIST(kf_arg_btf_ids)
10733 BTF_ID(struct, bpf_dynptr_kern)
10734 BTF_ID(struct, bpf_list_head)
10735 BTF_ID(struct, bpf_list_node)
10736 BTF_ID(struct, bpf_rb_root)
10737 BTF_ID(struct, bpf_rb_node)
10739 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10740 const struct btf_param *arg, int type)
10742 const struct btf_type *t;
10745 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10748 if (!btf_type_is_ptr(t))
10750 t = btf_type_skip_modifiers(btf, t->type, &res_id);
10753 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10756 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10758 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10761 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10763 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10766 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10768 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10771 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10773 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10776 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10778 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10781 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10782 const struct btf_param *arg)
10784 const struct btf_type *t;
10786 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10793 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10794 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10795 const struct btf *btf,
10796 const struct btf_type *t, int rec)
10798 const struct btf_type *member_type;
10799 const struct btf_member *member;
10802 if (!btf_type_is_struct(t))
10805 for_each_member(i, t, member) {
10806 const struct btf_array *array;
10808 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10809 if (btf_type_is_struct(member_type)) {
10811 verbose(env, "max struct nesting depth exceeded\n");
10814 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10818 if (btf_type_is_array(member_type)) {
10819 array = btf_array(member_type);
10820 if (!array->nelems)
10822 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10823 if (!btf_type_is_scalar(member_type))
10827 if (!btf_type_is_scalar(member_type))
10833 enum kfunc_ptr_arg_type {
10835 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
10836 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10837 KF_ARG_PTR_TO_DYNPTR,
10838 KF_ARG_PTR_TO_ITER,
10839 KF_ARG_PTR_TO_LIST_HEAD,
10840 KF_ARG_PTR_TO_LIST_NODE,
10841 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
10843 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
10844 KF_ARG_PTR_TO_CALLBACK,
10845 KF_ARG_PTR_TO_RB_ROOT,
10846 KF_ARG_PTR_TO_RB_NODE,
10847 KF_ARG_PTR_TO_NULL,
10848 KF_ARG_PTR_TO_CONST_STR,
10851 enum special_kfunc_type {
10852 KF_bpf_obj_new_impl,
10853 KF_bpf_obj_drop_impl,
10854 KF_bpf_refcount_acquire_impl,
10855 KF_bpf_list_push_front_impl,
10856 KF_bpf_list_push_back_impl,
10857 KF_bpf_list_pop_front,
10858 KF_bpf_list_pop_back,
10859 KF_bpf_cast_to_kern_ctx,
10860 KF_bpf_rdonly_cast,
10861 KF_bpf_rcu_read_lock,
10862 KF_bpf_rcu_read_unlock,
10863 KF_bpf_rbtree_remove,
10864 KF_bpf_rbtree_add_impl,
10865 KF_bpf_rbtree_first,
10866 KF_bpf_dynptr_from_skb,
10867 KF_bpf_dynptr_from_xdp,
10868 KF_bpf_dynptr_slice,
10869 KF_bpf_dynptr_slice_rdwr,
10870 KF_bpf_dynptr_clone,
10871 KF_bpf_percpu_obj_new_impl,
10872 KF_bpf_percpu_obj_drop_impl,
10874 KF_bpf_iter_css_task_new,
10877 BTF_SET_START(special_kfunc_set)
10878 BTF_ID(func, bpf_obj_new_impl)
10879 BTF_ID(func, bpf_obj_drop_impl)
10880 BTF_ID(func, bpf_refcount_acquire_impl)
10881 BTF_ID(func, bpf_list_push_front_impl)
10882 BTF_ID(func, bpf_list_push_back_impl)
10883 BTF_ID(func, bpf_list_pop_front)
10884 BTF_ID(func, bpf_list_pop_back)
10885 BTF_ID(func, bpf_cast_to_kern_ctx)
10886 BTF_ID(func, bpf_rdonly_cast)
10887 BTF_ID(func, bpf_rbtree_remove)
10888 BTF_ID(func, bpf_rbtree_add_impl)
10889 BTF_ID(func, bpf_rbtree_first)
10890 BTF_ID(func, bpf_dynptr_from_skb)
10891 BTF_ID(func, bpf_dynptr_from_xdp)
10892 BTF_ID(func, bpf_dynptr_slice)
10893 BTF_ID(func, bpf_dynptr_slice_rdwr)
10894 BTF_ID(func, bpf_dynptr_clone)
10895 BTF_ID(func, bpf_percpu_obj_new_impl)
10896 BTF_ID(func, bpf_percpu_obj_drop_impl)
10897 BTF_ID(func, bpf_throw)
10898 #ifdef CONFIG_CGROUPS
10899 BTF_ID(func, bpf_iter_css_task_new)
10901 BTF_SET_END(special_kfunc_set)
10903 BTF_ID_LIST(special_kfunc_list)
10904 BTF_ID(func, bpf_obj_new_impl)
10905 BTF_ID(func, bpf_obj_drop_impl)
10906 BTF_ID(func, bpf_refcount_acquire_impl)
10907 BTF_ID(func, bpf_list_push_front_impl)
10908 BTF_ID(func, bpf_list_push_back_impl)
10909 BTF_ID(func, bpf_list_pop_front)
10910 BTF_ID(func, bpf_list_pop_back)
10911 BTF_ID(func, bpf_cast_to_kern_ctx)
10912 BTF_ID(func, bpf_rdonly_cast)
10913 BTF_ID(func, bpf_rcu_read_lock)
10914 BTF_ID(func, bpf_rcu_read_unlock)
10915 BTF_ID(func, bpf_rbtree_remove)
10916 BTF_ID(func, bpf_rbtree_add_impl)
10917 BTF_ID(func, bpf_rbtree_first)
10918 BTF_ID(func, bpf_dynptr_from_skb)
10919 BTF_ID(func, bpf_dynptr_from_xdp)
10920 BTF_ID(func, bpf_dynptr_slice)
10921 BTF_ID(func, bpf_dynptr_slice_rdwr)
10922 BTF_ID(func, bpf_dynptr_clone)
10923 BTF_ID(func, bpf_percpu_obj_new_impl)
10924 BTF_ID(func, bpf_percpu_obj_drop_impl)
10925 BTF_ID(func, bpf_throw)
10926 #ifdef CONFIG_CGROUPS
10927 BTF_ID(func, bpf_iter_css_task_new)
10932 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10934 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10935 meta->arg_owning_ref) {
10939 return meta->kfunc_flags & KF_RET_NULL;
10942 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10944 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10947 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10949 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10952 static enum kfunc_ptr_arg_type
10953 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10954 struct bpf_kfunc_call_arg_meta *meta,
10955 const struct btf_type *t, const struct btf_type *ref_t,
10956 const char *ref_tname, const struct btf_param *args,
10957 int argno, int nargs)
10959 u32 regno = argno + 1;
10960 struct bpf_reg_state *regs = cur_regs(env);
10961 struct bpf_reg_state *reg = ®s[regno];
10962 bool arg_mem_size = false;
10964 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10965 return KF_ARG_PTR_TO_CTX;
10967 /* In this function, we verify the kfunc's BTF as per the argument type,
10968 * leaving the rest of the verification with respect to the register
10969 * type to our caller. When a set of conditions hold in the BTF type of
10970 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10972 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10973 return KF_ARG_PTR_TO_CTX;
10975 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10976 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10978 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10979 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10981 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10982 return KF_ARG_PTR_TO_DYNPTR;
10984 if (is_kfunc_arg_iter(meta, argno))
10985 return KF_ARG_PTR_TO_ITER;
10987 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10988 return KF_ARG_PTR_TO_LIST_HEAD;
10990 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10991 return KF_ARG_PTR_TO_LIST_NODE;
10993 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10994 return KF_ARG_PTR_TO_RB_ROOT;
10996 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10997 return KF_ARG_PTR_TO_RB_NODE;
10999 if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
11000 return KF_ARG_PTR_TO_CONST_STR;
11002 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11003 if (!btf_type_is_struct(ref_t)) {
11004 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11005 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11008 return KF_ARG_PTR_TO_BTF_ID;
11011 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11012 return KF_ARG_PTR_TO_CALLBACK;
11014 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11015 return KF_ARG_PTR_TO_NULL;
11017 if (argno + 1 < nargs &&
11018 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
11019 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
11020 arg_mem_size = true;
11022 /* This is the catch all argument type of register types supported by
11023 * check_helper_mem_access. However, we only allow when argument type is
11024 * pointer to scalar, or struct composed (recursively) of scalars. When
11025 * arg_mem_size is true, the pointer can be void *.
11027 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11028 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11029 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11030 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11033 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11036 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11037 struct bpf_reg_state *reg,
11038 const struct btf_type *ref_t,
11039 const char *ref_tname, u32 ref_id,
11040 struct bpf_kfunc_call_arg_meta *meta,
11043 const struct btf_type *reg_ref_t;
11044 bool strict_type_match = false;
11045 const struct btf *reg_btf;
11046 const char *reg_ref_tname;
11049 if (base_type(reg->type) == PTR_TO_BTF_ID) {
11050 reg_btf = reg->btf;
11051 reg_ref_id = reg->btf_id;
11053 reg_btf = btf_vmlinux;
11054 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11057 /* Enforce strict type matching for calls to kfuncs that are acquiring
11058 * or releasing a reference, or are no-cast aliases. We do _not_
11059 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11060 * as we want to enable BPF programs to pass types that are bitwise
11061 * equivalent without forcing them to explicitly cast with something
11062 * like bpf_cast_to_kern_ctx().
11064 * For example, say we had a type like the following:
11066 * struct bpf_cpumask {
11067 * cpumask_t cpumask;
11068 * refcount_t usage;
11071 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11072 * to a struct cpumask, so it would be safe to pass a struct
11073 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11075 * The philosophy here is similar to how we allow scalars of different
11076 * types to be passed to kfuncs as long as the size is the same. The
11077 * only difference here is that we're simply allowing
11078 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11081 if (is_kfunc_acquire(meta) ||
11082 (is_kfunc_release(meta) && reg->ref_obj_id) ||
11083 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11084 strict_type_match = true;
11086 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
11088 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
11089 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11090 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
11091 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11092 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11093 btf_type_str(reg_ref_t), reg_ref_tname);
11099 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11101 struct bpf_verifier_state *state = env->cur_state;
11102 struct btf_record *rec = reg_btf_record(reg);
11104 if (!state->active_lock.ptr) {
11105 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11109 if (type_flag(reg->type) & NON_OWN_REF) {
11110 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11114 reg->type |= NON_OWN_REF;
11115 if (rec->refcount_off >= 0)
11116 reg->type |= MEM_RCU;
11121 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11123 struct bpf_func_state *state, *unused;
11124 struct bpf_reg_state *reg;
11127 state = cur_func(env);
11130 verbose(env, "verifier internal error: ref_obj_id is zero for "
11131 "owning -> non-owning conversion\n");
11135 for (i = 0; i < state->acquired_refs; i++) {
11136 if (state->refs[i].id != ref_obj_id)
11139 /* Clear ref_obj_id here so release_reference doesn't clobber
11142 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11143 if (reg->ref_obj_id == ref_obj_id) {
11144 reg->ref_obj_id = 0;
11145 ref_set_non_owning(env, reg);
11151 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11155 /* Implementation details:
11157 * Each register points to some region of memory, which we define as an
11158 * allocation. Each allocation may embed a bpf_spin_lock which protects any
11159 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11160 * allocation. The lock and the data it protects are colocated in the same
11163 * Hence, everytime a register holds a pointer value pointing to such
11164 * allocation, the verifier preserves a unique reg->id for it.
11166 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11167 * bpf_spin_lock is called.
11169 * To enable this, lock state in the verifier captures two values:
11170 * active_lock.ptr = Register's type specific pointer
11171 * active_lock.id = A unique ID for each register pointer value
11173 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11174 * supported register types.
11176 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11177 * allocated objects is the reg->btf pointer.
11179 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11180 * can establish the provenance of the map value statically for each distinct
11181 * lookup into such maps. They always contain a single map value hence unique
11182 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11184 * So, in case of global variables, they use array maps with max_entries = 1,
11185 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11186 * into the same map value as max_entries is 1, as described above).
11188 * In case of inner map lookups, the inner map pointer has same map_ptr as the
11189 * outer map pointer (in verifier context), but each lookup into an inner map
11190 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11191 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11192 * will get different reg->id assigned to each lookup, hence different
11195 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11196 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11197 * returned from bpf_obj_new. Each allocation receives a new reg->id.
11199 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11204 switch ((int)reg->type) {
11205 case PTR_TO_MAP_VALUE:
11206 ptr = reg->map_ptr;
11208 case PTR_TO_BTF_ID | MEM_ALLOC:
11212 verbose(env, "verifier internal error: unknown reg type for lock check\n");
11217 if (!env->cur_state->active_lock.ptr)
11219 if (env->cur_state->active_lock.ptr != ptr ||
11220 env->cur_state->active_lock.id != id) {
11221 verbose(env, "held lock and object are not in the same allocation\n");
11227 static bool is_bpf_list_api_kfunc(u32 btf_id)
11229 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11230 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11231 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11232 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11235 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11237 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11238 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11239 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11242 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11244 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11245 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11248 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11250 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11253 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11255 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11256 insn->imm == special_kfunc_list[KF_bpf_throw];
11259 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11261 return is_bpf_rbtree_api_kfunc(btf_id);
11264 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11265 enum btf_field_type head_field_type,
11270 switch (head_field_type) {
11271 case BPF_LIST_HEAD:
11272 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11275 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11278 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11279 btf_field_type_name(head_field_type));
11284 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11285 btf_field_type_name(head_field_type));
11289 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11290 enum btf_field_type node_field_type,
11295 switch (node_field_type) {
11296 case BPF_LIST_NODE:
11297 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11298 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11301 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11302 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11305 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11306 btf_field_type_name(node_field_type));
11311 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11312 btf_field_type_name(node_field_type));
11317 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11318 struct bpf_reg_state *reg, u32 regno,
11319 struct bpf_kfunc_call_arg_meta *meta,
11320 enum btf_field_type head_field_type,
11321 struct btf_field **head_field)
11323 const char *head_type_name;
11324 struct btf_field *field;
11325 struct btf_record *rec;
11328 if (meta->btf != btf_vmlinux) {
11329 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11333 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11336 head_type_name = btf_field_type_name(head_field_type);
11337 if (!tnum_is_const(reg->var_off)) {
11339 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11340 regno, head_type_name);
11344 rec = reg_btf_record(reg);
11345 head_off = reg->off + reg->var_off.value;
11346 field = btf_record_find(rec, head_off, head_field_type);
11348 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11352 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11353 if (check_reg_allocation_locked(env, reg)) {
11354 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11355 rec->spin_lock_off, head_type_name);
11360 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11363 *head_field = field;
11367 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11368 struct bpf_reg_state *reg, u32 regno,
11369 struct bpf_kfunc_call_arg_meta *meta)
11371 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11372 &meta->arg_list_head.field);
11375 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11376 struct bpf_reg_state *reg, u32 regno,
11377 struct bpf_kfunc_call_arg_meta *meta)
11379 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11380 &meta->arg_rbtree_root.field);
11384 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11385 struct bpf_reg_state *reg, u32 regno,
11386 struct bpf_kfunc_call_arg_meta *meta,
11387 enum btf_field_type head_field_type,
11388 enum btf_field_type node_field_type,
11389 struct btf_field **node_field)
11391 const char *node_type_name;
11392 const struct btf_type *et, *t;
11393 struct btf_field *field;
11396 if (meta->btf != btf_vmlinux) {
11397 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11401 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11404 node_type_name = btf_field_type_name(node_field_type);
11405 if (!tnum_is_const(reg->var_off)) {
11407 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11408 regno, node_type_name);
11412 node_off = reg->off + reg->var_off.value;
11413 field = reg_find_field_offset(reg, node_off, node_field_type);
11414 if (!field || field->offset != node_off) {
11415 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11419 field = *node_field;
11421 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11422 t = btf_type_by_id(reg->btf, reg->btf_id);
11423 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11424 field->graph_root.value_btf_id, true)) {
11425 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11426 "in struct %s, but arg is at offset=%d in struct %s\n",
11427 btf_field_type_name(head_field_type),
11428 btf_field_type_name(node_field_type),
11429 field->graph_root.node_offset,
11430 btf_name_by_offset(field->graph_root.btf, et->name_off),
11431 node_off, btf_name_by_offset(reg->btf, t->name_off));
11434 meta->arg_btf = reg->btf;
11435 meta->arg_btf_id = reg->btf_id;
11437 if (node_off != field->graph_root.node_offset) {
11438 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11439 node_off, btf_field_type_name(node_field_type),
11440 field->graph_root.node_offset,
11441 btf_name_by_offset(field->graph_root.btf, et->name_off));
11448 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11449 struct bpf_reg_state *reg, u32 regno,
11450 struct bpf_kfunc_call_arg_meta *meta)
11452 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11453 BPF_LIST_HEAD, BPF_LIST_NODE,
11454 &meta->arg_list_head.field);
11457 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11458 struct bpf_reg_state *reg, u32 regno,
11459 struct bpf_kfunc_call_arg_meta *meta)
11461 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11462 BPF_RB_ROOT, BPF_RB_NODE,
11463 &meta->arg_rbtree_root.field);
11467 * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11468 * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11469 * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11470 * them can only be attached to some specific hook points.
11472 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11474 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11476 switch (prog_type) {
11477 case BPF_PROG_TYPE_LSM:
11479 case BPF_PROG_TYPE_TRACING:
11480 if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11484 return env->prog->aux->sleepable;
11488 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11491 const char *func_name = meta->func_name, *ref_tname;
11492 const struct btf *btf = meta->btf;
11493 const struct btf_param *args;
11494 struct btf_record *rec;
11498 args = (const struct btf_param *)(meta->func_proto + 1);
11499 nargs = btf_type_vlen(meta->func_proto);
11500 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11501 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11502 MAX_BPF_FUNC_REG_ARGS);
11506 /* Check that BTF function arguments match actual types that the
11509 for (i = 0; i < nargs; i++) {
11510 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
11511 const struct btf_type *t, *ref_t, *resolve_ret;
11512 enum bpf_arg_type arg_type = ARG_DONTCARE;
11513 u32 regno = i + 1, ref_id, type_size;
11514 bool is_ret_buf_sz = false;
11517 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11519 if (is_kfunc_arg_ignore(btf, &args[i]))
11522 if (btf_type_is_scalar(t)) {
11523 if (reg->type != SCALAR_VALUE) {
11524 verbose(env, "R%d is not a scalar\n", regno);
11528 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11529 if (meta->arg_constant.found) {
11530 verbose(env, "verifier internal error: only one constant argument permitted\n");
11533 if (!tnum_is_const(reg->var_off)) {
11534 verbose(env, "R%d must be a known constant\n", regno);
11537 ret = mark_chain_precision(env, regno);
11540 meta->arg_constant.found = true;
11541 meta->arg_constant.value = reg->var_off.value;
11542 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11543 meta->r0_rdonly = true;
11544 is_ret_buf_sz = true;
11545 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11546 is_ret_buf_sz = true;
11549 if (is_ret_buf_sz) {
11550 if (meta->r0_size) {
11551 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11555 if (!tnum_is_const(reg->var_off)) {
11556 verbose(env, "R%d is not a const\n", regno);
11560 meta->r0_size = reg->var_off.value;
11561 ret = mark_chain_precision(env, regno);
11568 if (!btf_type_is_ptr(t)) {
11569 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11573 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11574 (register_is_null(reg) || type_may_be_null(reg->type)) &&
11575 !is_kfunc_arg_nullable(meta->btf, &args[i])) {
11576 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11580 if (reg->ref_obj_id) {
11581 if (is_kfunc_release(meta) && meta->ref_obj_id) {
11582 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11583 regno, reg->ref_obj_id,
11587 meta->ref_obj_id = reg->ref_obj_id;
11588 if (is_kfunc_release(meta))
11589 meta->release_regno = regno;
11592 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11593 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11595 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11596 if (kf_arg_type < 0)
11597 return kf_arg_type;
11599 switch (kf_arg_type) {
11600 case KF_ARG_PTR_TO_NULL:
11602 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11603 case KF_ARG_PTR_TO_BTF_ID:
11604 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11607 if (!is_trusted_reg(reg)) {
11608 if (!is_kfunc_rcu(meta)) {
11609 verbose(env, "R%d must be referenced or trusted\n", regno);
11612 if (!is_rcu_reg(reg)) {
11613 verbose(env, "R%d must be a rcu pointer\n", regno);
11619 case KF_ARG_PTR_TO_CTX:
11620 /* Trusted arguments have the same offset checks as release arguments */
11621 arg_type |= OBJ_RELEASE;
11623 case KF_ARG_PTR_TO_DYNPTR:
11624 case KF_ARG_PTR_TO_ITER:
11625 case KF_ARG_PTR_TO_LIST_HEAD:
11626 case KF_ARG_PTR_TO_LIST_NODE:
11627 case KF_ARG_PTR_TO_RB_ROOT:
11628 case KF_ARG_PTR_TO_RB_NODE:
11629 case KF_ARG_PTR_TO_MEM:
11630 case KF_ARG_PTR_TO_MEM_SIZE:
11631 case KF_ARG_PTR_TO_CALLBACK:
11632 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11633 case KF_ARG_PTR_TO_CONST_STR:
11634 /* Trusted by default */
11641 if (is_kfunc_release(meta) && reg->ref_obj_id)
11642 arg_type |= OBJ_RELEASE;
11643 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11647 switch (kf_arg_type) {
11648 case KF_ARG_PTR_TO_CTX:
11649 if (reg->type != PTR_TO_CTX) {
11650 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11654 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11655 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11658 meta->ret_btf_id = ret;
11661 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11662 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
11663 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
11664 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
11667 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
11668 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
11669 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
11673 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11676 if (!reg->ref_obj_id) {
11677 verbose(env, "allocated object must be referenced\n");
11680 if (meta->btf == btf_vmlinux) {
11681 meta->arg_btf = reg->btf;
11682 meta->arg_btf_id = reg->btf_id;
11685 case KF_ARG_PTR_TO_DYNPTR:
11687 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11688 int clone_ref_obj_id = 0;
11690 if (reg->type != PTR_TO_STACK &&
11691 reg->type != CONST_PTR_TO_DYNPTR) {
11692 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11696 if (reg->type == CONST_PTR_TO_DYNPTR)
11697 dynptr_arg_type |= MEM_RDONLY;
11699 if (is_kfunc_arg_uninit(btf, &args[i]))
11700 dynptr_arg_type |= MEM_UNINIT;
11702 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11703 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11704 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11705 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11706 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11707 (dynptr_arg_type & MEM_UNINIT)) {
11708 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11710 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11711 verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11715 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11716 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11717 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11718 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11723 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11727 if (!(dynptr_arg_type & MEM_UNINIT)) {
11728 int id = dynptr_id(env, reg);
11731 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11734 meta->initialized_dynptr.id = id;
11735 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11736 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11741 case KF_ARG_PTR_TO_ITER:
11742 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
11743 if (!check_css_task_iter_allowlist(env)) {
11744 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
11748 ret = process_iter_arg(env, regno, insn_idx, meta);
11752 case KF_ARG_PTR_TO_LIST_HEAD:
11753 if (reg->type != PTR_TO_MAP_VALUE &&
11754 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11755 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11758 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11759 verbose(env, "allocated object must be referenced\n");
11762 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11766 case KF_ARG_PTR_TO_RB_ROOT:
11767 if (reg->type != PTR_TO_MAP_VALUE &&
11768 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11769 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11772 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11773 verbose(env, "allocated object must be referenced\n");
11776 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11780 case KF_ARG_PTR_TO_LIST_NODE:
11781 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11782 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11785 if (!reg->ref_obj_id) {
11786 verbose(env, "allocated object must be referenced\n");
11789 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11793 case KF_ARG_PTR_TO_RB_NODE:
11794 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11795 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11796 verbose(env, "rbtree_remove node input must be non-owning ref\n");
11799 if (in_rbtree_lock_required_cb(env)) {
11800 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11804 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11805 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11808 if (!reg->ref_obj_id) {
11809 verbose(env, "allocated object must be referenced\n");
11814 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11818 case KF_ARG_PTR_TO_BTF_ID:
11819 /* Only base_type is checked, further checks are done here */
11820 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11821 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11822 !reg2btf_ids[base_type(reg->type)]) {
11823 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11824 verbose(env, "expected %s or socket\n",
11825 reg_type_str(env, base_type(reg->type) |
11826 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11829 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11833 case KF_ARG_PTR_TO_MEM:
11834 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11835 if (IS_ERR(resolve_ret)) {
11836 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11837 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11840 ret = check_mem_reg(env, reg, regno, type_size);
11844 case KF_ARG_PTR_TO_MEM_SIZE:
11846 struct bpf_reg_state *buff_reg = ®s[regno];
11847 const struct btf_param *buff_arg = &args[i];
11848 struct bpf_reg_state *size_reg = ®s[regno + 1];
11849 const struct btf_param *size_arg = &args[i + 1];
11851 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11852 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11854 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11859 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11860 if (meta->arg_constant.found) {
11861 verbose(env, "verifier internal error: only one constant argument permitted\n");
11864 if (!tnum_is_const(size_reg->var_off)) {
11865 verbose(env, "R%d must be a known constant\n", regno + 1);
11868 meta->arg_constant.found = true;
11869 meta->arg_constant.value = size_reg->var_off.value;
11872 /* Skip next '__sz' or '__szk' argument */
11876 case KF_ARG_PTR_TO_CALLBACK:
11877 if (reg->type != PTR_TO_FUNC) {
11878 verbose(env, "arg%d expected pointer to func\n", i);
11881 meta->subprogno = reg->subprogno;
11883 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11884 if (!type_is_ptr_alloc_obj(reg->type)) {
11885 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11888 if (!type_is_non_owning_ref(reg->type))
11889 meta->arg_owning_ref = true;
11891 rec = reg_btf_record(reg);
11893 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11897 if (rec->refcount_off < 0) {
11898 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11902 meta->arg_btf = reg->btf;
11903 meta->arg_btf_id = reg->btf_id;
11905 case KF_ARG_PTR_TO_CONST_STR:
11906 if (reg->type != PTR_TO_MAP_VALUE) {
11907 verbose(env, "arg#%d doesn't point to a const string\n", i);
11910 ret = check_reg_const_str(env, reg, regno);
11917 if (is_kfunc_release(meta) && !meta->release_regno) {
11918 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11926 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11927 struct bpf_insn *insn,
11928 struct bpf_kfunc_call_arg_meta *meta,
11929 const char **kfunc_name)
11931 const struct btf_type *func, *func_proto;
11932 u32 func_id, *kfunc_flags;
11933 const char *func_name;
11934 struct btf *desc_btf;
11937 *kfunc_name = NULL;
11942 desc_btf = find_kfunc_desc_btf(env, insn->off);
11943 if (IS_ERR(desc_btf))
11944 return PTR_ERR(desc_btf);
11946 func_id = insn->imm;
11947 func = btf_type_by_id(desc_btf, func_id);
11948 func_name = btf_name_by_offset(desc_btf, func->name_off);
11950 *kfunc_name = func_name;
11951 func_proto = btf_type_by_id(desc_btf, func->type);
11953 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11954 if (!kfunc_flags) {
11958 memset(meta, 0, sizeof(*meta));
11959 meta->btf = desc_btf;
11960 meta->func_id = func_id;
11961 meta->kfunc_flags = *kfunc_flags;
11962 meta->func_proto = func_proto;
11963 meta->func_name = func_name;
11968 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
11970 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11973 const struct btf_type *t, *ptr_type;
11974 u32 i, nargs, ptr_type_id, release_ref_obj_id;
11975 struct bpf_reg_state *regs = cur_regs(env);
11976 const char *func_name, *ptr_type_name;
11977 bool sleepable, rcu_lock, rcu_unlock;
11978 struct bpf_kfunc_call_arg_meta meta;
11979 struct bpf_insn_aux_data *insn_aux;
11980 int err, insn_idx = *insn_idx_p;
11981 const struct btf_param *args;
11982 const struct btf_type *ret_t;
11983 struct btf *desc_btf;
11985 /* skip for now, but return error when we find this in fixup_kfunc_call */
11989 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11990 if (err == -EACCES && func_name)
11991 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11994 desc_btf = meta.btf;
11995 insn_aux = &env->insn_aux_data[insn_idx];
11997 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11999 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12000 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12004 sleepable = is_kfunc_sleepable(&meta);
12005 if (sleepable && !env->prog->aux->sleepable) {
12006 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12010 /* Check the arguments */
12011 err = check_kfunc_args(env, &meta, insn_idx);
12015 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12016 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12017 set_rbtree_add_callback_state);
12019 verbose(env, "kfunc %s#%d failed callback verification\n",
12020 func_name, meta.func_id);
12025 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
12026 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
12028 if (env->cur_state->active_rcu_lock) {
12029 struct bpf_func_state *state;
12030 struct bpf_reg_state *reg;
12031 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
12033 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
12034 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
12039 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
12041 } else if (rcu_unlock) {
12042 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
12043 if (reg->type & MEM_RCU) {
12044 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
12045 reg->type |= PTR_UNTRUSTED;
12048 env->cur_state->active_rcu_lock = false;
12049 } else if (sleepable) {
12050 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
12053 } else if (rcu_lock) {
12054 env->cur_state->active_rcu_lock = true;
12055 } else if (rcu_unlock) {
12056 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
12060 /* In case of release function, we get register number of refcounted
12061 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
12063 if (meta.release_regno) {
12064 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
12066 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12067 func_name, meta.func_id);
12072 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12073 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12074 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12075 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
12076 insn_aux->insert_off = regs[BPF_REG_2].off;
12077 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
12078 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
12080 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
12081 func_name, meta.func_id);
12085 err = release_reference(env, release_ref_obj_id);
12087 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12088 func_name, meta.func_id);
12093 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12094 if (!bpf_jit_supports_exceptions()) {
12095 verbose(env, "JIT does not support calling kfunc %s#%d\n",
12096 func_name, meta.func_id);
12099 env->seen_exception = true;
12101 /* In the case of the default callback, the cookie value passed
12102 * to bpf_throw becomes the return value of the program.
12104 if (!env->exception_callback_subprog) {
12105 err = check_return_code(env, BPF_REG_1, "R1");
12111 for (i = 0; i < CALLER_SAVED_REGS; i++)
12112 mark_reg_not_init(env, regs, caller_saved[i]);
12114 /* Check return type */
12115 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
12117 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
12118 /* Only exception is bpf_obj_new_impl */
12119 if (meta.btf != btf_vmlinux ||
12120 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
12121 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
12122 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
12123 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12128 if (btf_type_is_scalar(t)) {
12129 mark_reg_unknown(env, regs, BPF_REG_0);
12130 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12131 } else if (btf_type_is_ptr(t)) {
12132 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12134 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12135 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12136 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12137 struct btf_struct_meta *struct_meta;
12138 struct btf *ret_btf;
12141 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12144 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12145 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12149 ret_btf = env->prog->aux->btf;
12150 ret_btf_id = meta.arg_constant.value;
12152 /* This may be NULL due to user not supplying a BTF */
12154 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12158 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12159 if (!ret_t || !__btf_type_is_struct(ret_t)) {
12160 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12164 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12165 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
12166 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
12167 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
12171 if (!bpf_global_percpu_ma_set) {
12172 mutex_lock(&bpf_percpu_ma_lock);
12173 if (!bpf_global_percpu_ma_set) {
12174 /* Charge memory allocated with bpf_global_percpu_ma to
12175 * root memcg. The obj_cgroup for root memcg is NULL.
12177 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
12179 bpf_global_percpu_ma_set = true;
12181 mutex_unlock(&bpf_percpu_ma_lock);
12186 mutex_lock(&bpf_percpu_ma_lock);
12187 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
12188 mutex_unlock(&bpf_percpu_ma_lock);
12193 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12194 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12195 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12196 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12201 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12206 mark_reg_known_zero(env, regs, BPF_REG_0);
12207 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12208 regs[BPF_REG_0].btf = ret_btf;
12209 regs[BPF_REG_0].btf_id = ret_btf_id;
12210 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12211 regs[BPF_REG_0].type |= MEM_PERCPU;
12213 insn_aux->obj_new_size = ret_t->size;
12214 insn_aux->kptr_struct_meta = struct_meta;
12215 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12216 mark_reg_known_zero(env, regs, BPF_REG_0);
12217 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12218 regs[BPF_REG_0].btf = meta.arg_btf;
12219 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12221 insn_aux->kptr_struct_meta =
12222 btf_find_struct_meta(meta.arg_btf,
12224 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12225 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12226 struct btf_field *field = meta.arg_list_head.field;
12228 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12229 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12230 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12231 struct btf_field *field = meta.arg_rbtree_root.field;
12233 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12234 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12235 mark_reg_known_zero(env, regs, BPF_REG_0);
12236 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12237 regs[BPF_REG_0].btf = desc_btf;
12238 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12239 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12240 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12241 if (!ret_t || !btf_type_is_struct(ret_t)) {
12243 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12247 mark_reg_known_zero(env, regs, BPF_REG_0);
12248 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12249 regs[BPF_REG_0].btf = desc_btf;
12250 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12251 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12252 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12253 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12255 mark_reg_known_zero(env, regs, BPF_REG_0);
12257 if (!meta.arg_constant.found) {
12258 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12262 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12264 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12265 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12267 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12268 regs[BPF_REG_0].type |= MEM_RDONLY;
12270 /* this will set env->seen_direct_write to true */
12271 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12272 verbose(env, "the prog does not allow writes to packet data\n");
12277 if (!meta.initialized_dynptr.id) {
12278 verbose(env, "verifier internal error: no dynptr id\n");
12281 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12283 /* we don't need to set BPF_REG_0's ref obj id
12284 * because packet slices are not refcounted (see
12285 * dynptr_type_refcounted)
12288 verbose(env, "kernel function %s unhandled dynamic return type\n",
12292 } else if (!__btf_type_is_struct(ptr_type)) {
12293 if (!meta.r0_size) {
12296 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12298 meta.r0_rdonly = true;
12301 if (!meta.r0_size) {
12302 ptr_type_name = btf_name_by_offset(desc_btf,
12303 ptr_type->name_off);
12305 "kernel function %s returns pointer type %s %s is not supported\n",
12307 btf_type_str(ptr_type),
12312 mark_reg_known_zero(env, regs, BPF_REG_0);
12313 regs[BPF_REG_0].type = PTR_TO_MEM;
12314 regs[BPF_REG_0].mem_size = meta.r0_size;
12316 if (meta.r0_rdonly)
12317 regs[BPF_REG_0].type |= MEM_RDONLY;
12319 /* Ensures we don't access the memory after a release_reference() */
12320 if (meta.ref_obj_id)
12321 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12323 mark_reg_known_zero(env, regs, BPF_REG_0);
12324 regs[BPF_REG_0].btf = desc_btf;
12325 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12326 regs[BPF_REG_0].btf_id = ptr_type_id;
12329 if (is_kfunc_ret_null(&meta)) {
12330 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12331 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12332 regs[BPF_REG_0].id = ++env->id_gen;
12334 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12335 if (is_kfunc_acquire(&meta)) {
12336 int id = acquire_reference_state(env, insn_idx);
12340 if (is_kfunc_ret_null(&meta))
12341 regs[BPF_REG_0].id = id;
12342 regs[BPF_REG_0].ref_obj_id = id;
12343 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12344 ref_set_non_owning(env, ®s[BPF_REG_0]);
12347 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
12348 regs[BPF_REG_0].id = ++env->id_gen;
12349 } else if (btf_type_is_void(t)) {
12350 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12351 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12352 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12353 insn_aux->kptr_struct_meta =
12354 btf_find_struct_meta(meta.arg_btf,
12360 nargs = btf_type_vlen(meta.func_proto);
12361 args = (const struct btf_param *)(meta.func_proto + 1);
12362 for (i = 0; i < nargs; i++) {
12365 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12366 if (btf_type_is_ptr(t))
12367 mark_btf_func_reg_size(env, regno, sizeof(void *));
12369 /* scalar. ensured by btf_check_kfunc_arg_match() */
12370 mark_btf_func_reg_size(env, regno, t->size);
12373 if (is_iter_next_kfunc(&meta)) {
12374 err = process_iter_next_call(env, insn_idx, &meta);
12382 static bool signed_add_overflows(s64 a, s64 b)
12384 /* Do the add in u64, where overflow is well-defined */
12385 s64 res = (s64)((u64)a + (u64)b);
12392 static bool signed_add32_overflows(s32 a, s32 b)
12394 /* Do the add in u32, where overflow is well-defined */
12395 s32 res = (s32)((u32)a + (u32)b);
12402 static bool signed_sub_overflows(s64 a, s64 b)
12404 /* Do the sub in u64, where overflow is well-defined */
12405 s64 res = (s64)((u64)a - (u64)b);
12412 static bool signed_sub32_overflows(s32 a, s32 b)
12414 /* Do the sub in u32, where overflow is well-defined */
12415 s32 res = (s32)((u32)a - (u32)b);
12422 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12423 const struct bpf_reg_state *reg,
12424 enum bpf_reg_type type)
12426 bool known = tnum_is_const(reg->var_off);
12427 s64 val = reg->var_off.value;
12428 s64 smin = reg->smin_value;
12430 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12431 verbose(env, "math between %s pointer and %lld is not allowed\n",
12432 reg_type_str(env, type), val);
12436 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12437 verbose(env, "%s pointer offset %d is not allowed\n",
12438 reg_type_str(env, type), reg->off);
12442 if (smin == S64_MIN) {
12443 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12444 reg_type_str(env, type));
12448 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12449 verbose(env, "value %lld makes %s pointer be out of bounds\n",
12450 smin, reg_type_str(env, type));
12458 REASON_BOUNDS = -1,
12465 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12466 u32 *alu_limit, bool mask_to_left)
12468 u32 max = 0, ptr_limit = 0;
12470 switch (ptr_reg->type) {
12472 /* Offset 0 is out-of-bounds, but acceptable start for the
12473 * left direction, see BPF_REG_FP. Also, unknown scalar
12474 * offset where we would need to deal with min/max bounds is
12475 * currently prohibited for unprivileged.
12477 max = MAX_BPF_STACK + mask_to_left;
12478 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12480 case PTR_TO_MAP_VALUE:
12481 max = ptr_reg->map_ptr->value_size;
12482 ptr_limit = (mask_to_left ?
12483 ptr_reg->smin_value :
12484 ptr_reg->umax_value) + ptr_reg->off;
12487 return REASON_TYPE;
12490 if (ptr_limit >= max)
12491 return REASON_LIMIT;
12492 *alu_limit = ptr_limit;
12496 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12497 const struct bpf_insn *insn)
12499 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12502 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12503 u32 alu_state, u32 alu_limit)
12505 /* If we arrived here from different branches with different
12506 * state or limits to sanitize, then this won't work.
12508 if (aux->alu_state &&
12509 (aux->alu_state != alu_state ||
12510 aux->alu_limit != alu_limit))
12511 return REASON_PATHS;
12513 /* Corresponding fixup done in do_misc_fixups(). */
12514 aux->alu_state = alu_state;
12515 aux->alu_limit = alu_limit;
12519 static int sanitize_val_alu(struct bpf_verifier_env *env,
12520 struct bpf_insn *insn)
12522 struct bpf_insn_aux_data *aux = cur_aux(env);
12524 if (can_skip_alu_sanitation(env, insn))
12527 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12530 static bool sanitize_needed(u8 opcode)
12532 return opcode == BPF_ADD || opcode == BPF_SUB;
12535 struct bpf_sanitize_info {
12536 struct bpf_insn_aux_data aux;
12540 static struct bpf_verifier_state *
12541 sanitize_speculative_path(struct bpf_verifier_env *env,
12542 const struct bpf_insn *insn,
12543 u32 next_idx, u32 curr_idx)
12545 struct bpf_verifier_state *branch;
12546 struct bpf_reg_state *regs;
12548 branch = push_stack(env, next_idx, curr_idx, true);
12549 if (branch && insn) {
12550 regs = branch->frame[branch->curframe]->regs;
12551 if (BPF_SRC(insn->code) == BPF_K) {
12552 mark_reg_unknown(env, regs, insn->dst_reg);
12553 } else if (BPF_SRC(insn->code) == BPF_X) {
12554 mark_reg_unknown(env, regs, insn->dst_reg);
12555 mark_reg_unknown(env, regs, insn->src_reg);
12561 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12562 struct bpf_insn *insn,
12563 const struct bpf_reg_state *ptr_reg,
12564 const struct bpf_reg_state *off_reg,
12565 struct bpf_reg_state *dst_reg,
12566 struct bpf_sanitize_info *info,
12567 const bool commit_window)
12569 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12570 struct bpf_verifier_state *vstate = env->cur_state;
12571 bool off_is_imm = tnum_is_const(off_reg->var_off);
12572 bool off_is_neg = off_reg->smin_value < 0;
12573 bool ptr_is_dst_reg = ptr_reg == dst_reg;
12574 u8 opcode = BPF_OP(insn->code);
12575 u32 alu_state, alu_limit;
12576 struct bpf_reg_state tmp;
12580 if (can_skip_alu_sanitation(env, insn))
12583 /* We already marked aux for masking from non-speculative
12584 * paths, thus we got here in the first place. We only care
12585 * to explore bad access from here.
12587 if (vstate->speculative)
12590 if (!commit_window) {
12591 if (!tnum_is_const(off_reg->var_off) &&
12592 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12593 return REASON_BOUNDS;
12595 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
12596 (opcode == BPF_SUB && !off_is_neg);
12599 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12603 if (commit_window) {
12604 /* In commit phase we narrow the masking window based on
12605 * the observed pointer move after the simulated operation.
12607 alu_state = info->aux.alu_state;
12608 alu_limit = abs(info->aux.alu_limit - alu_limit);
12610 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12611 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12612 alu_state |= ptr_is_dst_reg ?
12613 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12615 /* Limit pruning on unknown scalars to enable deep search for
12616 * potential masking differences from other program paths.
12619 env->explore_alu_limits = true;
12622 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12626 /* If we're in commit phase, we're done here given we already
12627 * pushed the truncated dst_reg into the speculative verification
12630 * Also, when register is a known constant, we rewrite register-based
12631 * operation to immediate-based, and thus do not need masking (and as
12632 * a consequence, do not need to simulate the zero-truncation either).
12634 if (commit_window || off_is_imm)
12637 /* Simulate and find potential out-of-bounds access under
12638 * speculative execution from truncation as a result of
12639 * masking when off was not within expected range. If off
12640 * sits in dst, then we temporarily need to move ptr there
12641 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12642 * for cases where we use K-based arithmetic in one direction
12643 * and truncated reg-based in the other in order to explore
12646 if (!ptr_is_dst_reg) {
12648 copy_register_state(dst_reg, ptr_reg);
12650 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12652 if (!ptr_is_dst_reg && ret)
12654 return !ret ? REASON_STACK : 0;
12657 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12659 struct bpf_verifier_state *vstate = env->cur_state;
12661 /* If we simulate paths under speculation, we don't update the
12662 * insn as 'seen' such that when we verify unreachable paths in
12663 * the non-speculative domain, sanitize_dead_code() can still
12664 * rewrite/sanitize them.
12666 if (!vstate->speculative)
12667 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12670 static int sanitize_err(struct bpf_verifier_env *env,
12671 const struct bpf_insn *insn, int reason,
12672 const struct bpf_reg_state *off_reg,
12673 const struct bpf_reg_state *dst_reg)
12675 static const char *err = "pointer arithmetic with it prohibited for !root";
12676 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12677 u32 dst = insn->dst_reg, src = insn->src_reg;
12680 case REASON_BOUNDS:
12681 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12682 off_reg == dst_reg ? dst : src, err);
12685 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12686 off_reg == dst_reg ? src : dst, err);
12689 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12693 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12697 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12701 verbose(env, "verifier internal error: unknown reason (%d)\n",
12709 /* check that stack access falls within stack limits and that 'reg' doesn't
12710 * have a variable offset.
12712 * Variable offset is prohibited for unprivileged mode for simplicity since it
12713 * requires corresponding support in Spectre masking for stack ALU. See also
12714 * retrieve_ptr_limit().
12717 * 'off' includes 'reg->off'.
12719 static int check_stack_access_for_ptr_arithmetic(
12720 struct bpf_verifier_env *env,
12722 const struct bpf_reg_state *reg,
12725 if (!tnum_is_const(reg->var_off)) {
12728 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12729 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12730 regno, tn_buf, off);
12734 if (off >= 0 || off < -MAX_BPF_STACK) {
12735 verbose(env, "R%d stack pointer arithmetic goes out of range, "
12736 "prohibited for !root; off=%d\n", regno, off);
12743 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12744 const struct bpf_insn *insn,
12745 const struct bpf_reg_state *dst_reg)
12747 u32 dst = insn->dst_reg;
12749 /* For unprivileged we require that resulting offset must be in bounds
12750 * in order to be able to sanitize access later on.
12752 if (env->bypass_spec_v1)
12755 switch (dst_reg->type) {
12757 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12758 dst_reg->off + dst_reg->var_off.value))
12761 case PTR_TO_MAP_VALUE:
12762 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12763 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12764 "prohibited for !root\n", dst);
12775 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12776 * Caller should also handle BPF_MOV case separately.
12777 * If we return -EACCES, caller may want to try again treating pointer as a
12778 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
12780 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12781 struct bpf_insn *insn,
12782 const struct bpf_reg_state *ptr_reg,
12783 const struct bpf_reg_state *off_reg)
12785 struct bpf_verifier_state *vstate = env->cur_state;
12786 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12787 struct bpf_reg_state *regs = state->regs, *dst_reg;
12788 bool known = tnum_is_const(off_reg->var_off);
12789 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12790 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12791 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12792 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12793 struct bpf_sanitize_info info = {};
12794 u8 opcode = BPF_OP(insn->code);
12795 u32 dst = insn->dst_reg;
12798 dst_reg = ®s[dst];
12800 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12801 smin_val > smax_val || umin_val > umax_val) {
12802 /* Taint dst register if offset had invalid bounds derived from
12803 * e.g. dead branches.
12805 __mark_reg_unknown(env, dst_reg);
12809 if (BPF_CLASS(insn->code) != BPF_ALU64) {
12810 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12811 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12812 __mark_reg_unknown(env, dst_reg);
12817 "R%d 32-bit pointer arithmetic prohibited\n",
12822 if (ptr_reg->type & PTR_MAYBE_NULL) {
12823 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12824 dst, reg_type_str(env, ptr_reg->type));
12828 switch (base_type(ptr_reg->type)) {
12829 case PTR_TO_FLOW_KEYS:
12833 case CONST_PTR_TO_MAP:
12834 /* smin_val represents the known value */
12835 if (known && smin_val == 0 && opcode == BPF_ADD)
12838 case PTR_TO_PACKET_END:
12839 case PTR_TO_SOCKET:
12840 case PTR_TO_SOCK_COMMON:
12841 case PTR_TO_TCP_SOCK:
12842 case PTR_TO_XDP_SOCK:
12843 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12844 dst, reg_type_str(env, ptr_reg->type));
12850 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12851 * The id may be overwritten later if we create a new variable offset.
12853 dst_reg->type = ptr_reg->type;
12854 dst_reg->id = ptr_reg->id;
12856 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12857 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12860 /* pointer types do not carry 32-bit bounds at the moment. */
12861 __mark_reg32_unbounded(dst_reg);
12863 if (sanitize_needed(opcode)) {
12864 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12867 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12872 /* We can take a fixed offset as long as it doesn't overflow
12873 * the s32 'off' field
12875 if (known && (ptr_reg->off + smin_val ==
12876 (s64)(s32)(ptr_reg->off + smin_val))) {
12877 /* pointer += K. Accumulate it into fixed offset */
12878 dst_reg->smin_value = smin_ptr;
12879 dst_reg->smax_value = smax_ptr;
12880 dst_reg->umin_value = umin_ptr;
12881 dst_reg->umax_value = umax_ptr;
12882 dst_reg->var_off = ptr_reg->var_off;
12883 dst_reg->off = ptr_reg->off + smin_val;
12884 dst_reg->raw = ptr_reg->raw;
12887 /* A new variable offset is created. Note that off_reg->off
12888 * == 0, since it's a scalar.
12889 * dst_reg gets the pointer type and since some positive
12890 * integer value was added to the pointer, give it a new 'id'
12891 * if it's a PTR_TO_PACKET.
12892 * this creates a new 'base' pointer, off_reg (variable) gets
12893 * added into the variable offset, and we copy the fixed offset
12896 if (signed_add_overflows(smin_ptr, smin_val) ||
12897 signed_add_overflows(smax_ptr, smax_val)) {
12898 dst_reg->smin_value = S64_MIN;
12899 dst_reg->smax_value = S64_MAX;
12901 dst_reg->smin_value = smin_ptr + smin_val;
12902 dst_reg->smax_value = smax_ptr + smax_val;
12904 if (umin_ptr + umin_val < umin_ptr ||
12905 umax_ptr + umax_val < umax_ptr) {
12906 dst_reg->umin_value = 0;
12907 dst_reg->umax_value = U64_MAX;
12909 dst_reg->umin_value = umin_ptr + umin_val;
12910 dst_reg->umax_value = umax_ptr + umax_val;
12912 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12913 dst_reg->off = ptr_reg->off;
12914 dst_reg->raw = ptr_reg->raw;
12915 if (reg_is_pkt_pointer(ptr_reg)) {
12916 dst_reg->id = ++env->id_gen;
12917 /* something was added to pkt_ptr, set range to zero */
12918 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12922 if (dst_reg == off_reg) {
12923 /* scalar -= pointer. Creates an unknown scalar */
12924 verbose(env, "R%d tried to subtract pointer from scalar\n",
12928 /* We don't allow subtraction from FP, because (according to
12929 * test_verifier.c test "invalid fp arithmetic", JITs might not
12930 * be able to deal with it.
12932 if (ptr_reg->type == PTR_TO_STACK) {
12933 verbose(env, "R%d subtraction from stack pointer prohibited\n",
12937 if (known && (ptr_reg->off - smin_val ==
12938 (s64)(s32)(ptr_reg->off - smin_val))) {
12939 /* pointer -= K. Subtract it from fixed offset */
12940 dst_reg->smin_value = smin_ptr;
12941 dst_reg->smax_value = smax_ptr;
12942 dst_reg->umin_value = umin_ptr;
12943 dst_reg->umax_value = umax_ptr;
12944 dst_reg->var_off = ptr_reg->var_off;
12945 dst_reg->id = ptr_reg->id;
12946 dst_reg->off = ptr_reg->off - smin_val;
12947 dst_reg->raw = ptr_reg->raw;
12950 /* A new variable offset is created. If the subtrahend is known
12951 * nonnegative, then any reg->range we had before is still good.
12953 if (signed_sub_overflows(smin_ptr, smax_val) ||
12954 signed_sub_overflows(smax_ptr, smin_val)) {
12955 /* Overflow possible, we know nothing */
12956 dst_reg->smin_value = S64_MIN;
12957 dst_reg->smax_value = S64_MAX;
12959 dst_reg->smin_value = smin_ptr - smax_val;
12960 dst_reg->smax_value = smax_ptr - smin_val;
12962 if (umin_ptr < umax_val) {
12963 /* Overflow possible, we know nothing */
12964 dst_reg->umin_value = 0;
12965 dst_reg->umax_value = U64_MAX;
12967 /* Cannot overflow (as long as bounds are consistent) */
12968 dst_reg->umin_value = umin_ptr - umax_val;
12969 dst_reg->umax_value = umax_ptr - umin_val;
12971 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12972 dst_reg->off = ptr_reg->off;
12973 dst_reg->raw = ptr_reg->raw;
12974 if (reg_is_pkt_pointer(ptr_reg)) {
12975 dst_reg->id = ++env->id_gen;
12976 /* something was added to pkt_ptr, set range to zero */
12978 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12984 /* bitwise ops on pointers are troublesome, prohibit. */
12985 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12986 dst, bpf_alu_string[opcode >> 4]);
12989 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12990 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12991 dst, bpf_alu_string[opcode >> 4]);
12995 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12997 reg_bounds_sync(dst_reg);
12998 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
13000 if (sanitize_needed(opcode)) {
13001 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13004 return sanitize_err(env, insn, ret, off_reg, dst_reg);
13010 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13011 struct bpf_reg_state *src_reg)
13013 s32 smin_val = src_reg->s32_min_value;
13014 s32 smax_val = src_reg->s32_max_value;
13015 u32 umin_val = src_reg->u32_min_value;
13016 u32 umax_val = src_reg->u32_max_value;
13018 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
13019 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
13020 dst_reg->s32_min_value = S32_MIN;
13021 dst_reg->s32_max_value = S32_MAX;
13023 dst_reg->s32_min_value += smin_val;
13024 dst_reg->s32_max_value += smax_val;
13026 if (dst_reg->u32_min_value + umin_val < umin_val ||
13027 dst_reg->u32_max_value + umax_val < umax_val) {
13028 dst_reg->u32_min_value = 0;
13029 dst_reg->u32_max_value = U32_MAX;
13031 dst_reg->u32_min_value += umin_val;
13032 dst_reg->u32_max_value += umax_val;
13036 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13037 struct bpf_reg_state *src_reg)
13039 s64 smin_val = src_reg->smin_value;
13040 s64 smax_val = src_reg->smax_value;
13041 u64 umin_val = src_reg->umin_value;
13042 u64 umax_val = src_reg->umax_value;
13044 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
13045 signed_add_overflows(dst_reg->smax_value, smax_val)) {
13046 dst_reg->smin_value = S64_MIN;
13047 dst_reg->smax_value = S64_MAX;
13049 dst_reg->smin_value += smin_val;
13050 dst_reg->smax_value += smax_val;
13052 if (dst_reg->umin_value + umin_val < umin_val ||
13053 dst_reg->umax_value + umax_val < umax_val) {
13054 dst_reg->umin_value = 0;
13055 dst_reg->umax_value = U64_MAX;
13057 dst_reg->umin_value += umin_val;
13058 dst_reg->umax_value += umax_val;
13062 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13063 struct bpf_reg_state *src_reg)
13065 s32 smin_val = src_reg->s32_min_value;
13066 s32 smax_val = src_reg->s32_max_value;
13067 u32 umin_val = src_reg->u32_min_value;
13068 u32 umax_val = src_reg->u32_max_value;
13070 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
13071 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
13072 /* Overflow possible, we know nothing */
13073 dst_reg->s32_min_value = S32_MIN;
13074 dst_reg->s32_max_value = S32_MAX;
13076 dst_reg->s32_min_value -= smax_val;
13077 dst_reg->s32_max_value -= smin_val;
13079 if (dst_reg->u32_min_value < umax_val) {
13080 /* Overflow possible, we know nothing */
13081 dst_reg->u32_min_value = 0;
13082 dst_reg->u32_max_value = U32_MAX;
13084 /* Cannot overflow (as long as bounds are consistent) */
13085 dst_reg->u32_min_value -= umax_val;
13086 dst_reg->u32_max_value -= umin_val;
13090 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13091 struct bpf_reg_state *src_reg)
13093 s64 smin_val = src_reg->smin_value;
13094 s64 smax_val = src_reg->smax_value;
13095 u64 umin_val = src_reg->umin_value;
13096 u64 umax_val = src_reg->umax_value;
13098 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
13099 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
13100 /* Overflow possible, we know nothing */
13101 dst_reg->smin_value = S64_MIN;
13102 dst_reg->smax_value = S64_MAX;
13104 dst_reg->smin_value -= smax_val;
13105 dst_reg->smax_value -= smin_val;
13107 if (dst_reg->umin_value < umax_val) {
13108 /* Overflow possible, we know nothing */
13109 dst_reg->umin_value = 0;
13110 dst_reg->umax_value = U64_MAX;
13112 /* Cannot overflow (as long as bounds are consistent) */
13113 dst_reg->umin_value -= umax_val;
13114 dst_reg->umax_value -= umin_val;
13118 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13119 struct bpf_reg_state *src_reg)
13121 s32 smin_val = src_reg->s32_min_value;
13122 u32 umin_val = src_reg->u32_min_value;
13123 u32 umax_val = src_reg->u32_max_value;
13125 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13126 /* Ain't nobody got time to multiply that sign */
13127 __mark_reg32_unbounded(dst_reg);
13130 /* Both values are positive, so we can work with unsigned and
13131 * copy the result to signed (unless it exceeds S32_MAX).
13133 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13134 /* Potential overflow, we know nothing */
13135 __mark_reg32_unbounded(dst_reg);
13138 dst_reg->u32_min_value *= umin_val;
13139 dst_reg->u32_max_value *= umax_val;
13140 if (dst_reg->u32_max_value > S32_MAX) {
13141 /* Overflow possible, we know nothing */
13142 dst_reg->s32_min_value = S32_MIN;
13143 dst_reg->s32_max_value = S32_MAX;
13145 dst_reg->s32_min_value = dst_reg->u32_min_value;
13146 dst_reg->s32_max_value = dst_reg->u32_max_value;
13150 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13151 struct bpf_reg_state *src_reg)
13153 s64 smin_val = src_reg->smin_value;
13154 u64 umin_val = src_reg->umin_value;
13155 u64 umax_val = src_reg->umax_value;
13157 if (smin_val < 0 || dst_reg->smin_value < 0) {
13158 /* Ain't nobody got time to multiply that sign */
13159 __mark_reg64_unbounded(dst_reg);
13162 /* Both values are positive, so we can work with unsigned and
13163 * copy the result to signed (unless it exceeds S64_MAX).
13165 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13166 /* Potential overflow, we know nothing */
13167 __mark_reg64_unbounded(dst_reg);
13170 dst_reg->umin_value *= umin_val;
13171 dst_reg->umax_value *= umax_val;
13172 if (dst_reg->umax_value > S64_MAX) {
13173 /* Overflow possible, we know nothing */
13174 dst_reg->smin_value = S64_MIN;
13175 dst_reg->smax_value = S64_MAX;
13177 dst_reg->smin_value = dst_reg->umin_value;
13178 dst_reg->smax_value = dst_reg->umax_value;
13182 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13183 struct bpf_reg_state *src_reg)
13185 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13186 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13187 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13188 s32 smin_val = src_reg->s32_min_value;
13189 u32 umax_val = src_reg->u32_max_value;
13191 if (src_known && dst_known) {
13192 __mark_reg32_known(dst_reg, var32_off.value);
13196 /* We get our minimum from the var_off, since that's inherently
13197 * bitwise. Our maximum is the minimum of the operands' maxima.
13199 dst_reg->u32_min_value = var32_off.value;
13200 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13201 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13202 /* Lose signed bounds when ANDing negative numbers,
13203 * ain't nobody got time for that.
13205 dst_reg->s32_min_value = S32_MIN;
13206 dst_reg->s32_max_value = S32_MAX;
13208 /* ANDing two positives gives a positive, so safe to
13209 * cast result into s64.
13211 dst_reg->s32_min_value = dst_reg->u32_min_value;
13212 dst_reg->s32_max_value = dst_reg->u32_max_value;
13216 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13217 struct bpf_reg_state *src_reg)
13219 bool src_known = tnum_is_const(src_reg->var_off);
13220 bool dst_known = tnum_is_const(dst_reg->var_off);
13221 s64 smin_val = src_reg->smin_value;
13222 u64 umax_val = src_reg->umax_value;
13224 if (src_known && dst_known) {
13225 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13229 /* We get our minimum from the var_off, since that's inherently
13230 * bitwise. Our maximum is the minimum of the operands' maxima.
13232 dst_reg->umin_value = dst_reg->var_off.value;
13233 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13234 if (dst_reg->smin_value < 0 || smin_val < 0) {
13235 /* Lose signed bounds when ANDing negative numbers,
13236 * ain't nobody got time for that.
13238 dst_reg->smin_value = S64_MIN;
13239 dst_reg->smax_value = S64_MAX;
13241 /* ANDing two positives gives a positive, so safe to
13242 * cast result into s64.
13244 dst_reg->smin_value = dst_reg->umin_value;
13245 dst_reg->smax_value = dst_reg->umax_value;
13247 /* We may learn something more from the var_off */
13248 __update_reg_bounds(dst_reg);
13251 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13252 struct bpf_reg_state *src_reg)
13254 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13255 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13256 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13257 s32 smin_val = src_reg->s32_min_value;
13258 u32 umin_val = src_reg->u32_min_value;
13260 if (src_known && dst_known) {
13261 __mark_reg32_known(dst_reg, var32_off.value);
13265 /* We get our maximum from the var_off, and our minimum is the
13266 * maximum of the operands' minima
13268 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13269 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13270 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13271 /* Lose signed bounds when ORing negative numbers,
13272 * ain't nobody got time for that.
13274 dst_reg->s32_min_value = S32_MIN;
13275 dst_reg->s32_max_value = S32_MAX;
13277 /* ORing two positives gives a positive, so safe to
13278 * cast result into s64.
13280 dst_reg->s32_min_value = dst_reg->u32_min_value;
13281 dst_reg->s32_max_value = dst_reg->u32_max_value;
13285 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13286 struct bpf_reg_state *src_reg)
13288 bool src_known = tnum_is_const(src_reg->var_off);
13289 bool dst_known = tnum_is_const(dst_reg->var_off);
13290 s64 smin_val = src_reg->smin_value;
13291 u64 umin_val = src_reg->umin_value;
13293 if (src_known && dst_known) {
13294 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13298 /* We get our maximum from the var_off, and our minimum is the
13299 * maximum of the operands' minima
13301 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13302 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13303 if (dst_reg->smin_value < 0 || smin_val < 0) {
13304 /* Lose signed bounds when ORing negative numbers,
13305 * ain't nobody got time for that.
13307 dst_reg->smin_value = S64_MIN;
13308 dst_reg->smax_value = S64_MAX;
13310 /* ORing two positives gives a positive, so safe to
13311 * cast result into s64.
13313 dst_reg->smin_value = dst_reg->umin_value;
13314 dst_reg->smax_value = dst_reg->umax_value;
13316 /* We may learn something more from the var_off */
13317 __update_reg_bounds(dst_reg);
13320 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13321 struct bpf_reg_state *src_reg)
13323 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13324 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13325 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13326 s32 smin_val = src_reg->s32_min_value;
13328 if (src_known && dst_known) {
13329 __mark_reg32_known(dst_reg, var32_off.value);
13333 /* We get both minimum and maximum from the var32_off. */
13334 dst_reg->u32_min_value = var32_off.value;
13335 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13337 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13338 /* XORing two positive sign numbers gives a positive,
13339 * so safe to cast u32 result into s32.
13341 dst_reg->s32_min_value = dst_reg->u32_min_value;
13342 dst_reg->s32_max_value = dst_reg->u32_max_value;
13344 dst_reg->s32_min_value = S32_MIN;
13345 dst_reg->s32_max_value = S32_MAX;
13349 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13350 struct bpf_reg_state *src_reg)
13352 bool src_known = tnum_is_const(src_reg->var_off);
13353 bool dst_known = tnum_is_const(dst_reg->var_off);
13354 s64 smin_val = src_reg->smin_value;
13356 if (src_known && dst_known) {
13357 /* dst_reg->var_off.value has been updated earlier */
13358 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13362 /* We get both minimum and maximum from the var_off. */
13363 dst_reg->umin_value = dst_reg->var_off.value;
13364 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13366 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13367 /* XORing two positive sign numbers gives a positive,
13368 * so safe to cast u64 result into s64.
13370 dst_reg->smin_value = dst_reg->umin_value;
13371 dst_reg->smax_value = dst_reg->umax_value;
13373 dst_reg->smin_value = S64_MIN;
13374 dst_reg->smax_value = S64_MAX;
13377 __update_reg_bounds(dst_reg);
13380 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13381 u64 umin_val, u64 umax_val)
13383 /* We lose all sign bit information (except what we can pick
13386 dst_reg->s32_min_value = S32_MIN;
13387 dst_reg->s32_max_value = S32_MAX;
13388 /* If we might shift our top bit out, then we know nothing */
13389 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13390 dst_reg->u32_min_value = 0;
13391 dst_reg->u32_max_value = U32_MAX;
13393 dst_reg->u32_min_value <<= umin_val;
13394 dst_reg->u32_max_value <<= umax_val;
13398 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13399 struct bpf_reg_state *src_reg)
13401 u32 umax_val = src_reg->u32_max_value;
13402 u32 umin_val = src_reg->u32_min_value;
13403 /* u32 alu operation will zext upper bits */
13404 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13406 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13407 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13408 /* Not required but being careful mark reg64 bounds as unknown so
13409 * that we are forced to pick them up from tnum and zext later and
13410 * if some path skips this step we are still safe.
13412 __mark_reg64_unbounded(dst_reg);
13413 __update_reg32_bounds(dst_reg);
13416 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13417 u64 umin_val, u64 umax_val)
13419 /* Special case <<32 because it is a common compiler pattern to sign
13420 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13421 * positive we know this shift will also be positive so we can track
13422 * bounds correctly. Otherwise we lose all sign bit information except
13423 * what we can pick up from var_off. Perhaps we can generalize this
13424 * later to shifts of any length.
13426 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13427 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13429 dst_reg->smax_value = S64_MAX;
13431 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13432 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13434 dst_reg->smin_value = S64_MIN;
13436 /* If we might shift our top bit out, then we know nothing */
13437 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13438 dst_reg->umin_value = 0;
13439 dst_reg->umax_value = U64_MAX;
13441 dst_reg->umin_value <<= umin_val;
13442 dst_reg->umax_value <<= umax_val;
13446 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13447 struct bpf_reg_state *src_reg)
13449 u64 umax_val = src_reg->umax_value;
13450 u64 umin_val = src_reg->umin_value;
13452 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
13453 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13454 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13456 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13457 /* We may learn something more from the var_off */
13458 __update_reg_bounds(dst_reg);
13461 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13462 struct bpf_reg_state *src_reg)
13464 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13465 u32 umax_val = src_reg->u32_max_value;
13466 u32 umin_val = src_reg->u32_min_value;
13468 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13469 * be negative, then either:
13470 * 1) src_reg might be zero, so the sign bit of the result is
13471 * unknown, so we lose our signed bounds
13472 * 2) it's known negative, thus the unsigned bounds capture the
13474 * 3) the signed bounds cross zero, so they tell us nothing
13476 * If the value in dst_reg is known nonnegative, then again the
13477 * unsigned bounds capture the signed bounds.
13478 * Thus, in all cases it suffices to blow away our signed bounds
13479 * and rely on inferring new ones from the unsigned bounds and
13480 * var_off of the result.
13482 dst_reg->s32_min_value = S32_MIN;
13483 dst_reg->s32_max_value = S32_MAX;
13485 dst_reg->var_off = tnum_rshift(subreg, umin_val);
13486 dst_reg->u32_min_value >>= umax_val;
13487 dst_reg->u32_max_value >>= umin_val;
13489 __mark_reg64_unbounded(dst_reg);
13490 __update_reg32_bounds(dst_reg);
13493 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13494 struct bpf_reg_state *src_reg)
13496 u64 umax_val = src_reg->umax_value;
13497 u64 umin_val = src_reg->umin_value;
13499 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13500 * be negative, then either:
13501 * 1) src_reg might be zero, so the sign bit of the result is
13502 * unknown, so we lose our signed bounds
13503 * 2) it's known negative, thus the unsigned bounds capture the
13505 * 3) the signed bounds cross zero, so they tell us nothing
13507 * If the value in dst_reg is known nonnegative, then again the
13508 * unsigned bounds capture the signed bounds.
13509 * Thus, in all cases it suffices to blow away our signed bounds
13510 * and rely on inferring new ones from the unsigned bounds and
13511 * var_off of the result.
13513 dst_reg->smin_value = S64_MIN;
13514 dst_reg->smax_value = S64_MAX;
13515 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13516 dst_reg->umin_value >>= umax_val;
13517 dst_reg->umax_value >>= umin_val;
13519 /* Its not easy to operate on alu32 bounds here because it depends
13520 * on bits being shifted in. Take easy way out and mark unbounded
13521 * so we can recalculate later from tnum.
13523 __mark_reg32_unbounded(dst_reg);
13524 __update_reg_bounds(dst_reg);
13527 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13528 struct bpf_reg_state *src_reg)
13530 u64 umin_val = src_reg->u32_min_value;
13532 /* Upon reaching here, src_known is true and
13533 * umax_val is equal to umin_val.
13535 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13536 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13538 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13540 /* blow away the dst_reg umin_value/umax_value and rely on
13541 * dst_reg var_off to refine the result.
13543 dst_reg->u32_min_value = 0;
13544 dst_reg->u32_max_value = U32_MAX;
13546 __mark_reg64_unbounded(dst_reg);
13547 __update_reg32_bounds(dst_reg);
13550 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13551 struct bpf_reg_state *src_reg)
13553 u64 umin_val = src_reg->umin_value;
13555 /* Upon reaching here, src_known is true and umax_val is equal
13558 dst_reg->smin_value >>= umin_val;
13559 dst_reg->smax_value >>= umin_val;
13561 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13563 /* blow away the dst_reg umin_value/umax_value and rely on
13564 * dst_reg var_off to refine the result.
13566 dst_reg->umin_value = 0;
13567 dst_reg->umax_value = U64_MAX;
13569 /* Its not easy to operate on alu32 bounds here because it depends
13570 * on bits being shifted in from upper 32-bits. Take easy way out
13571 * and mark unbounded so we can recalculate later from tnum.
13573 __mark_reg32_unbounded(dst_reg);
13574 __update_reg_bounds(dst_reg);
13577 /* WARNING: This function does calculations on 64-bit values, but the actual
13578 * execution may occur on 32-bit values. Therefore, things like bitshifts
13579 * need extra checks in the 32-bit case.
13581 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13582 struct bpf_insn *insn,
13583 struct bpf_reg_state *dst_reg,
13584 struct bpf_reg_state src_reg)
13586 struct bpf_reg_state *regs = cur_regs(env);
13587 u8 opcode = BPF_OP(insn->code);
13589 s64 smin_val, smax_val;
13590 u64 umin_val, umax_val;
13591 s32 s32_min_val, s32_max_val;
13592 u32 u32_min_val, u32_max_val;
13593 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13594 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13597 smin_val = src_reg.smin_value;
13598 smax_val = src_reg.smax_value;
13599 umin_val = src_reg.umin_value;
13600 umax_val = src_reg.umax_value;
13602 s32_min_val = src_reg.s32_min_value;
13603 s32_max_val = src_reg.s32_max_value;
13604 u32_min_val = src_reg.u32_min_value;
13605 u32_max_val = src_reg.u32_max_value;
13608 src_known = tnum_subreg_is_const(src_reg.var_off);
13610 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13611 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13612 /* Taint dst register if offset had invalid bounds
13613 * derived from e.g. dead branches.
13615 __mark_reg_unknown(env, dst_reg);
13619 src_known = tnum_is_const(src_reg.var_off);
13621 (smin_val != smax_val || umin_val != umax_val)) ||
13622 smin_val > smax_val || umin_val > umax_val) {
13623 /* Taint dst register if offset had invalid bounds
13624 * derived from e.g. dead branches.
13626 __mark_reg_unknown(env, dst_reg);
13632 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13633 __mark_reg_unknown(env, dst_reg);
13637 if (sanitize_needed(opcode)) {
13638 ret = sanitize_val_alu(env, insn);
13640 return sanitize_err(env, insn, ret, NULL, NULL);
13643 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13644 * There are two classes of instructions: The first class we track both
13645 * alu32 and alu64 sign/unsigned bounds independently this provides the
13646 * greatest amount of precision when alu operations are mixed with jmp32
13647 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13648 * and BPF_OR. This is possible because these ops have fairly easy to
13649 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13650 * See alu32 verifier tests for examples. The second class of
13651 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13652 * with regards to tracking sign/unsigned bounds because the bits may
13653 * cross subreg boundaries in the alu64 case. When this happens we mark
13654 * the reg unbounded in the subreg bound space and use the resulting
13655 * tnum to calculate an approximation of the sign/unsigned bounds.
13659 scalar32_min_max_add(dst_reg, &src_reg);
13660 scalar_min_max_add(dst_reg, &src_reg);
13661 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13664 scalar32_min_max_sub(dst_reg, &src_reg);
13665 scalar_min_max_sub(dst_reg, &src_reg);
13666 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13669 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13670 scalar32_min_max_mul(dst_reg, &src_reg);
13671 scalar_min_max_mul(dst_reg, &src_reg);
13674 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13675 scalar32_min_max_and(dst_reg, &src_reg);
13676 scalar_min_max_and(dst_reg, &src_reg);
13679 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13680 scalar32_min_max_or(dst_reg, &src_reg);
13681 scalar_min_max_or(dst_reg, &src_reg);
13684 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13685 scalar32_min_max_xor(dst_reg, &src_reg);
13686 scalar_min_max_xor(dst_reg, &src_reg);
13689 if (umax_val >= insn_bitness) {
13690 /* Shifts greater than 31 or 63 are undefined.
13691 * This includes shifts by a negative number.
13693 mark_reg_unknown(env, regs, insn->dst_reg);
13697 scalar32_min_max_lsh(dst_reg, &src_reg);
13699 scalar_min_max_lsh(dst_reg, &src_reg);
13702 if (umax_val >= insn_bitness) {
13703 /* Shifts greater than 31 or 63 are undefined.
13704 * This includes shifts by a negative number.
13706 mark_reg_unknown(env, regs, insn->dst_reg);
13710 scalar32_min_max_rsh(dst_reg, &src_reg);
13712 scalar_min_max_rsh(dst_reg, &src_reg);
13715 if (umax_val >= insn_bitness) {
13716 /* Shifts greater than 31 or 63 are undefined.
13717 * This includes shifts by a negative number.
13719 mark_reg_unknown(env, regs, insn->dst_reg);
13723 scalar32_min_max_arsh(dst_reg, &src_reg);
13725 scalar_min_max_arsh(dst_reg, &src_reg);
13728 mark_reg_unknown(env, regs, insn->dst_reg);
13732 /* ALU32 ops are zero extended into 64bit register */
13734 zext_32_to_64(dst_reg);
13735 reg_bounds_sync(dst_reg);
13739 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13742 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13743 struct bpf_insn *insn)
13745 struct bpf_verifier_state *vstate = env->cur_state;
13746 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13747 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13748 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13749 u8 opcode = BPF_OP(insn->code);
13752 dst_reg = ®s[insn->dst_reg];
13754 if (dst_reg->type != SCALAR_VALUE)
13757 /* Make sure ID is cleared otherwise dst_reg min/max could be
13758 * incorrectly propagated into other registers by find_equal_scalars()
13761 if (BPF_SRC(insn->code) == BPF_X) {
13762 src_reg = ®s[insn->src_reg];
13763 if (src_reg->type != SCALAR_VALUE) {
13764 if (dst_reg->type != SCALAR_VALUE) {
13765 /* Combining two pointers by any ALU op yields
13766 * an arbitrary scalar. Disallow all math except
13767 * pointer subtraction
13769 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13770 mark_reg_unknown(env, regs, insn->dst_reg);
13773 verbose(env, "R%d pointer %s pointer prohibited\n",
13775 bpf_alu_string[opcode >> 4]);
13778 /* scalar += pointer
13779 * This is legal, but we have to reverse our
13780 * src/dest handling in computing the range
13782 err = mark_chain_precision(env, insn->dst_reg);
13785 return adjust_ptr_min_max_vals(env, insn,
13788 } else if (ptr_reg) {
13789 /* pointer += scalar */
13790 err = mark_chain_precision(env, insn->src_reg);
13793 return adjust_ptr_min_max_vals(env, insn,
13795 } else if (dst_reg->precise) {
13796 /* if dst_reg is precise, src_reg should be precise as well */
13797 err = mark_chain_precision(env, insn->src_reg);
13802 /* Pretend the src is a reg with a known value, since we only
13803 * need to be able to read from this state.
13805 off_reg.type = SCALAR_VALUE;
13806 __mark_reg_known(&off_reg, insn->imm);
13807 src_reg = &off_reg;
13808 if (ptr_reg) /* pointer += K */
13809 return adjust_ptr_min_max_vals(env, insn,
13813 /* Got here implies adding two SCALAR_VALUEs */
13814 if (WARN_ON_ONCE(ptr_reg)) {
13815 print_verifier_state(env, state, true);
13816 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13819 if (WARN_ON(!src_reg)) {
13820 print_verifier_state(env, state, true);
13821 verbose(env, "verifier internal error: no src_reg\n");
13824 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13827 /* check validity of 32-bit and 64-bit arithmetic operations */
13828 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13830 struct bpf_reg_state *regs = cur_regs(env);
13831 u8 opcode = BPF_OP(insn->code);
13834 if (opcode == BPF_END || opcode == BPF_NEG) {
13835 if (opcode == BPF_NEG) {
13836 if (BPF_SRC(insn->code) != BPF_K ||
13837 insn->src_reg != BPF_REG_0 ||
13838 insn->off != 0 || insn->imm != 0) {
13839 verbose(env, "BPF_NEG uses reserved fields\n");
13843 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13844 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13845 (BPF_CLASS(insn->code) == BPF_ALU64 &&
13846 BPF_SRC(insn->code) != BPF_TO_LE)) {
13847 verbose(env, "BPF_END uses reserved fields\n");
13852 /* check src operand */
13853 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13857 if (is_pointer_value(env, insn->dst_reg)) {
13858 verbose(env, "R%d pointer arithmetic prohibited\n",
13863 /* check dest operand */
13864 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13868 } else if (opcode == BPF_MOV) {
13870 if (BPF_SRC(insn->code) == BPF_X) {
13871 if (insn->imm != 0) {
13872 verbose(env, "BPF_MOV uses reserved fields\n");
13876 if (BPF_CLASS(insn->code) == BPF_ALU) {
13877 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13878 verbose(env, "BPF_MOV uses reserved fields\n");
13882 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13884 verbose(env, "BPF_MOV uses reserved fields\n");
13889 /* check src operand */
13890 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13894 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13895 verbose(env, "BPF_MOV uses reserved fields\n");
13900 /* check dest operand, mark as required later */
13901 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13905 if (BPF_SRC(insn->code) == BPF_X) {
13906 struct bpf_reg_state *src_reg = regs + insn->src_reg;
13907 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13908 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13909 !tnum_is_const(src_reg->var_off);
13911 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13912 if (insn->off == 0) {
13914 * copy register state to dest reg
13917 /* Assign src and dst registers the same ID
13918 * that will be used by find_equal_scalars()
13919 * to propagate min/max range.
13921 src_reg->id = ++env->id_gen;
13922 copy_register_state(dst_reg, src_reg);
13923 dst_reg->live |= REG_LIVE_WRITTEN;
13924 dst_reg->subreg_def = DEF_NOT_SUBREG;
13926 /* case: R1 = (s8, s16 s32)R2 */
13927 if (is_pointer_value(env, insn->src_reg)) {
13929 "R%d sign-extension part of pointer\n",
13932 } else if (src_reg->type == SCALAR_VALUE) {
13935 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13936 if (no_sext && need_id)
13937 src_reg->id = ++env->id_gen;
13938 copy_register_state(dst_reg, src_reg);
13941 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13942 dst_reg->live |= REG_LIVE_WRITTEN;
13943 dst_reg->subreg_def = DEF_NOT_SUBREG;
13945 mark_reg_unknown(env, regs, insn->dst_reg);
13949 /* R1 = (u32) R2 */
13950 if (is_pointer_value(env, insn->src_reg)) {
13952 "R%d partial copy of pointer\n",
13955 } else if (src_reg->type == SCALAR_VALUE) {
13956 if (insn->off == 0) {
13957 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13959 if (is_src_reg_u32 && need_id)
13960 src_reg->id = ++env->id_gen;
13961 copy_register_state(dst_reg, src_reg);
13962 /* Make sure ID is cleared if src_reg is not in u32
13963 * range otherwise dst_reg min/max could be incorrectly
13964 * propagated into src_reg by find_equal_scalars()
13966 if (!is_src_reg_u32)
13968 dst_reg->live |= REG_LIVE_WRITTEN;
13969 dst_reg->subreg_def = env->insn_idx + 1;
13971 /* case: W1 = (s8, s16)W2 */
13972 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13974 if (no_sext && need_id)
13975 src_reg->id = ++env->id_gen;
13976 copy_register_state(dst_reg, src_reg);
13979 dst_reg->live |= REG_LIVE_WRITTEN;
13980 dst_reg->subreg_def = env->insn_idx + 1;
13981 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13984 mark_reg_unknown(env, regs,
13987 zext_32_to_64(dst_reg);
13988 reg_bounds_sync(dst_reg);
13992 * remember the value we stored into this reg
13994 /* clear any state __mark_reg_known doesn't set */
13995 mark_reg_unknown(env, regs, insn->dst_reg);
13996 regs[insn->dst_reg].type = SCALAR_VALUE;
13997 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13998 __mark_reg_known(regs + insn->dst_reg,
14001 __mark_reg_known(regs + insn->dst_reg,
14006 } else if (opcode > BPF_END) {
14007 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
14010 } else { /* all other ALU ops: and, sub, xor, add, ... */
14012 if (BPF_SRC(insn->code) == BPF_X) {
14013 if (insn->imm != 0 || insn->off > 1 ||
14014 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14015 verbose(env, "BPF_ALU uses reserved fields\n");
14018 /* check src1 operand */
14019 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14023 if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
14024 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14025 verbose(env, "BPF_ALU uses reserved fields\n");
14030 /* check src2 operand */
14031 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14035 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
14036 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
14037 verbose(env, "div by zero\n");
14041 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
14042 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
14043 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
14045 if (insn->imm < 0 || insn->imm >= size) {
14046 verbose(env, "invalid shift %d\n", insn->imm);
14051 /* check dest operand */
14052 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14053 err = err ?: adjust_reg_min_max_vals(env, insn);
14058 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu");
14061 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
14062 struct bpf_reg_state *dst_reg,
14063 enum bpf_reg_type type,
14064 bool range_right_open)
14066 struct bpf_func_state *state;
14067 struct bpf_reg_state *reg;
14070 if (dst_reg->off < 0 ||
14071 (dst_reg->off == 0 && range_right_open))
14072 /* This doesn't give us any range */
14075 if (dst_reg->umax_value > MAX_PACKET_OFF ||
14076 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
14077 /* Risk of overflow. For instance, ptr + (1<<63) may be less
14078 * than pkt_end, but that's because it's also less than pkt.
14082 new_range = dst_reg->off;
14083 if (range_right_open)
14086 /* Examples for register markings:
14088 * pkt_data in dst register:
14092 * if (r2 > pkt_end) goto <handle exception>
14097 * if (r2 < pkt_end) goto <access okay>
14098 * <handle exception>
14101 * r2 == dst_reg, pkt_end == src_reg
14102 * r2=pkt(id=n,off=8,r=0)
14103 * r3=pkt(id=n,off=0,r=0)
14105 * pkt_data in src register:
14109 * if (pkt_end >= r2) goto <access okay>
14110 * <handle exception>
14114 * if (pkt_end <= r2) goto <handle exception>
14118 * pkt_end == dst_reg, r2 == src_reg
14119 * r2=pkt(id=n,off=8,r=0)
14120 * r3=pkt(id=n,off=0,r=0)
14122 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14123 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14124 * and [r3, r3 + 8-1) respectively is safe to access depending on
14128 /* If our ids match, then we must have the same max_value. And we
14129 * don't care about the other reg's fixed offset, since if it's too big
14130 * the range won't allow anything.
14131 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14133 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14134 if (reg->type == type && reg->id == dst_reg->id)
14135 /* keep the maximum range already checked */
14136 reg->range = max(reg->range, new_range);
14141 * <reg1> <op> <reg2>, currently assuming reg2 is a constant
14143 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14144 u8 opcode, bool is_jmp32)
14146 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
14147 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
14148 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
14149 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
14150 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
14151 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
14152 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
14153 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
14154 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
14155 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
14159 /* constants, umin/umax and smin/smax checks would be
14160 * redundant in this case because they all should match
14162 if (tnum_is_const(t1) && tnum_is_const(t2))
14163 return t1.value == t2.value;
14164 /* non-overlapping ranges */
14165 if (umin1 > umax2 || umax1 < umin2)
14167 if (smin1 > smax2 || smax1 < smin2)
14170 /* if 64-bit ranges are inconclusive, see if we can
14171 * utilize 32-bit subrange knowledge to eliminate
14172 * branches that can't be taken a priori
14174 if (reg1->u32_min_value > reg2->u32_max_value ||
14175 reg1->u32_max_value < reg2->u32_min_value)
14177 if (reg1->s32_min_value > reg2->s32_max_value ||
14178 reg1->s32_max_value < reg2->s32_min_value)
14183 /* constants, umin/umax and smin/smax checks would be
14184 * redundant in this case because they all should match
14186 if (tnum_is_const(t1) && tnum_is_const(t2))
14187 return t1.value != t2.value;
14188 /* non-overlapping ranges */
14189 if (umin1 > umax2 || umax1 < umin2)
14191 if (smin1 > smax2 || smax1 < smin2)
14194 /* if 64-bit ranges are inconclusive, see if we can
14195 * utilize 32-bit subrange knowledge to eliminate
14196 * branches that can't be taken a priori
14198 if (reg1->u32_min_value > reg2->u32_max_value ||
14199 reg1->u32_max_value < reg2->u32_min_value)
14201 if (reg1->s32_min_value > reg2->s32_max_value ||
14202 reg1->s32_max_value < reg2->s32_min_value)
14207 if (!is_reg_const(reg2, is_jmp32)) {
14211 if (!is_reg_const(reg2, is_jmp32))
14213 if ((~t1.mask & t1.value) & t2.value)
14215 if (!((t1.mask | t1.value) & t2.value))
14221 else if (umax1 <= umin2)
14227 else if (smax1 <= smin2)
14233 else if (umin1 >= umax2)
14239 else if (smin1 >= smax2)
14243 if (umin1 >= umax2)
14245 else if (umax1 < umin2)
14249 if (smin1 >= smax2)
14251 else if (smax1 < smin2)
14255 if (umax1 <= umin2)
14257 else if (umin1 > umax2)
14261 if (smax1 <= smin2)
14263 else if (smin1 > smax2)
14271 static int flip_opcode(u32 opcode)
14273 /* How can we transform "a <op> b" into "b <op> a"? */
14274 static const u8 opcode_flip[16] = {
14275 /* these stay the same */
14276 [BPF_JEQ >> 4] = BPF_JEQ,
14277 [BPF_JNE >> 4] = BPF_JNE,
14278 [BPF_JSET >> 4] = BPF_JSET,
14279 /* these swap "lesser" and "greater" (L and G in the opcodes) */
14280 [BPF_JGE >> 4] = BPF_JLE,
14281 [BPF_JGT >> 4] = BPF_JLT,
14282 [BPF_JLE >> 4] = BPF_JGE,
14283 [BPF_JLT >> 4] = BPF_JGT,
14284 [BPF_JSGE >> 4] = BPF_JSLE,
14285 [BPF_JSGT >> 4] = BPF_JSLT,
14286 [BPF_JSLE >> 4] = BPF_JSGE,
14287 [BPF_JSLT >> 4] = BPF_JSGT
14289 return opcode_flip[opcode >> 4];
14292 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14293 struct bpf_reg_state *src_reg,
14296 struct bpf_reg_state *pkt;
14298 if (src_reg->type == PTR_TO_PACKET_END) {
14300 } else if (dst_reg->type == PTR_TO_PACKET_END) {
14302 opcode = flip_opcode(opcode);
14307 if (pkt->range >= 0)
14312 /* pkt <= pkt_end */
14315 /* pkt > pkt_end */
14316 if (pkt->range == BEYOND_PKT_END)
14317 /* pkt has at last one extra byte beyond pkt_end */
14318 return opcode == BPF_JGT;
14321 /* pkt < pkt_end */
14324 /* pkt >= pkt_end */
14325 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14326 return opcode == BPF_JGE;
14332 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
14334 * 1 - branch will be taken and "goto target" will be executed
14335 * 0 - branch will not be taken and fall-through to next insn
14336 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
14339 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14340 u8 opcode, bool is_jmp32)
14342 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
14343 return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
14345 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
14348 /* arrange that reg2 is a scalar, and reg1 is a pointer */
14349 if (!is_reg_const(reg2, is_jmp32)) {
14350 opcode = flip_opcode(opcode);
14353 /* and ensure that reg2 is a constant */
14354 if (!is_reg_const(reg2, is_jmp32))
14357 if (!reg_not_null(reg1))
14360 /* If pointer is valid tests against zero will fail so we can
14361 * use this to direct branch taken.
14363 val = reg_const_value(reg2, is_jmp32);
14377 /* now deal with two scalars, but not necessarily constants */
14378 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
14381 /* Opcode that corresponds to a *false* branch condition.
14382 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
14384 static u8 rev_opcode(u8 opcode)
14387 case BPF_JEQ: return BPF_JNE;
14388 case BPF_JNE: return BPF_JEQ;
14389 /* JSET doesn't have it's reverse opcode in BPF, so add
14390 * BPF_X flag to denote the reverse of that operation
14392 case BPF_JSET: return BPF_JSET | BPF_X;
14393 case BPF_JSET | BPF_X: return BPF_JSET;
14394 case BPF_JGE: return BPF_JLT;
14395 case BPF_JGT: return BPF_JLE;
14396 case BPF_JLE: return BPF_JGT;
14397 case BPF_JLT: return BPF_JGE;
14398 case BPF_JSGE: return BPF_JSLT;
14399 case BPF_JSGT: return BPF_JSLE;
14400 case BPF_JSLE: return BPF_JSGT;
14401 case BPF_JSLT: return BPF_JSGE;
14406 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
14407 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14408 u8 opcode, bool is_jmp32)
14417 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14418 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14419 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14420 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14421 reg2->u32_min_value = reg1->u32_min_value;
14422 reg2->u32_max_value = reg1->u32_max_value;
14423 reg2->s32_min_value = reg1->s32_min_value;
14424 reg2->s32_max_value = reg1->s32_max_value;
14426 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
14427 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14428 reg2->var_off = tnum_with_subreg(reg2->var_off, t);
14430 reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
14431 reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14432 reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
14433 reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14434 reg2->umin_value = reg1->umin_value;
14435 reg2->umax_value = reg1->umax_value;
14436 reg2->smin_value = reg1->smin_value;
14437 reg2->smax_value = reg1->smax_value;
14439 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
14440 reg2->var_off = reg1->var_off;
14444 if (!is_reg_const(reg2, is_jmp32))
14446 if (!is_reg_const(reg2, is_jmp32))
14449 /* try to recompute the bound of reg1 if reg2 is a const and
14450 * is exactly the edge of reg1.
14452 val = reg_const_value(reg2, is_jmp32);
14454 /* u32_min_value is not equal to 0xffffffff at this point,
14455 * because otherwise u32_max_value is 0xffffffff as well,
14456 * in such a case both reg1 and reg2 would be constants,
14457 * jump would be predicted and reg_set_min_max() won't
14460 * Same reasoning works for all {u,s}{min,max}{32,64} cases
14463 if (reg1->u32_min_value == (u32)val)
14464 reg1->u32_min_value++;
14465 if (reg1->u32_max_value == (u32)val)
14466 reg1->u32_max_value--;
14467 if (reg1->s32_min_value == (s32)val)
14468 reg1->s32_min_value++;
14469 if (reg1->s32_max_value == (s32)val)
14470 reg1->s32_max_value--;
14472 if (reg1->umin_value == (u64)val)
14473 reg1->umin_value++;
14474 if (reg1->umax_value == (u64)val)
14475 reg1->umax_value--;
14476 if (reg1->smin_value == (s64)val)
14477 reg1->smin_value++;
14478 if (reg1->smax_value == (s64)val)
14479 reg1->smax_value--;
14483 if (!is_reg_const(reg2, is_jmp32))
14485 if (!is_reg_const(reg2, is_jmp32))
14487 val = reg_const_value(reg2, is_jmp32);
14488 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
14489 * requires single bit to learn something useful. E.g., if we
14490 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
14491 * are actually set? We can learn something definite only if
14492 * it's a single-bit value to begin with.
14494 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
14495 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
14496 * bit 1 is set, which we can readily use in adjustments.
14498 if (!is_power_of_2(val))
14501 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
14502 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14504 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
14507 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
14508 if (!is_reg_const(reg2, is_jmp32))
14510 if (!is_reg_const(reg2, is_jmp32))
14512 val = reg_const_value(reg2, is_jmp32);
14514 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
14515 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14517 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
14522 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14523 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14525 reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14526 reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
14531 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
14532 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
14534 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
14535 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
14540 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14541 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14543 reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14544 reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
14549 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
14550 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
14552 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
14553 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
14560 /* just reuse LE/LT logic above */
14561 opcode = flip_opcode(opcode);
14569 /* Adjusts the register min/max values in the case that the dst_reg and
14570 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
14571 * check, in which case we havea fake SCALAR_VALUE representing insn->imm).
14572 * Technically we can do similar adjustments for pointers to the same object,
14573 * but we don't support that right now.
14575 static int reg_set_min_max(struct bpf_verifier_env *env,
14576 struct bpf_reg_state *true_reg1,
14577 struct bpf_reg_state *true_reg2,
14578 struct bpf_reg_state *false_reg1,
14579 struct bpf_reg_state *false_reg2,
14580 u8 opcode, bool is_jmp32)
14584 /* If either register is a pointer, we can't learn anything about its
14585 * variable offset from the compare (unless they were a pointer into
14586 * the same object, but we don't bother with that).
14588 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
14591 /* fallthrough (FALSE) branch */
14592 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
14593 reg_bounds_sync(false_reg1);
14594 reg_bounds_sync(false_reg2);
14596 /* jump (TRUE) branch */
14597 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
14598 reg_bounds_sync(true_reg1);
14599 reg_bounds_sync(true_reg2);
14601 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
14602 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
14603 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
14604 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
14608 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14609 struct bpf_reg_state *reg, u32 id,
14612 if (type_may_be_null(reg->type) && reg->id == id &&
14613 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14614 /* Old offset (both fixed and variable parts) should have been
14615 * known-zero, because we don't allow pointer arithmetic on
14616 * pointers that might be NULL. If we see this happening, don't
14617 * convert the register.
14619 * But in some cases, some helpers that return local kptrs
14620 * advance offset for the returned pointer. In those cases, it
14621 * is fine to expect to see reg->off.
14623 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14625 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14626 WARN_ON_ONCE(reg->off))
14630 reg->type = SCALAR_VALUE;
14631 /* We don't need id and ref_obj_id from this point
14632 * onwards anymore, thus we should better reset it,
14633 * so that state pruning has chances to take effect.
14636 reg->ref_obj_id = 0;
14641 mark_ptr_not_null_reg(reg);
14643 if (!reg_may_point_to_spin_lock(reg)) {
14644 /* For not-NULL ptr, reg->ref_obj_id will be reset
14645 * in release_reference().
14647 * reg->id is still used by spin_lock ptr. Other
14648 * than spin_lock ptr type, reg->id can be reset.
14655 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14656 * be folded together at some point.
14658 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14661 struct bpf_func_state *state = vstate->frame[vstate->curframe];
14662 struct bpf_reg_state *regs = state->regs, *reg;
14663 u32 ref_obj_id = regs[regno].ref_obj_id;
14664 u32 id = regs[regno].id;
14666 if (ref_obj_id && ref_obj_id == id && is_null)
14667 /* regs[regno] is in the " == NULL" branch.
14668 * No one could have freed the reference state before
14669 * doing the NULL check.
14671 WARN_ON_ONCE(release_reference_state(state, id));
14673 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14674 mark_ptr_or_null_reg(state, reg, id, is_null);
14678 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14679 struct bpf_reg_state *dst_reg,
14680 struct bpf_reg_state *src_reg,
14681 struct bpf_verifier_state *this_branch,
14682 struct bpf_verifier_state *other_branch)
14684 if (BPF_SRC(insn->code) != BPF_X)
14687 /* Pointers are always 64-bit. */
14688 if (BPF_CLASS(insn->code) == BPF_JMP32)
14691 switch (BPF_OP(insn->code)) {
14693 if ((dst_reg->type == PTR_TO_PACKET &&
14694 src_reg->type == PTR_TO_PACKET_END) ||
14695 (dst_reg->type == PTR_TO_PACKET_META &&
14696 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14697 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14698 find_good_pkt_pointers(this_branch, dst_reg,
14699 dst_reg->type, false);
14700 mark_pkt_end(other_branch, insn->dst_reg, true);
14701 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14702 src_reg->type == PTR_TO_PACKET) ||
14703 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14704 src_reg->type == PTR_TO_PACKET_META)) {
14705 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
14706 find_good_pkt_pointers(other_branch, src_reg,
14707 src_reg->type, true);
14708 mark_pkt_end(this_branch, insn->src_reg, false);
14714 if ((dst_reg->type == PTR_TO_PACKET &&
14715 src_reg->type == PTR_TO_PACKET_END) ||
14716 (dst_reg->type == PTR_TO_PACKET_META &&
14717 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14718 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14719 find_good_pkt_pointers(other_branch, dst_reg,
14720 dst_reg->type, true);
14721 mark_pkt_end(this_branch, insn->dst_reg, false);
14722 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14723 src_reg->type == PTR_TO_PACKET) ||
14724 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14725 src_reg->type == PTR_TO_PACKET_META)) {
14726 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
14727 find_good_pkt_pointers(this_branch, src_reg,
14728 src_reg->type, false);
14729 mark_pkt_end(other_branch, insn->src_reg, true);
14735 if ((dst_reg->type == PTR_TO_PACKET &&
14736 src_reg->type == PTR_TO_PACKET_END) ||
14737 (dst_reg->type == PTR_TO_PACKET_META &&
14738 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14739 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14740 find_good_pkt_pointers(this_branch, dst_reg,
14741 dst_reg->type, true);
14742 mark_pkt_end(other_branch, insn->dst_reg, false);
14743 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14744 src_reg->type == PTR_TO_PACKET) ||
14745 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14746 src_reg->type == PTR_TO_PACKET_META)) {
14747 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14748 find_good_pkt_pointers(other_branch, src_reg,
14749 src_reg->type, false);
14750 mark_pkt_end(this_branch, insn->src_reg, true);
14756 if ((dst_reg->type == PTR_TO_PACKET &&
14757 src_reg->type == PTR_TO_PACKET_END) ||
14758 (dst_reg->type == PTR_TO_PACKET_META &&
14759 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14760 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14761 find_good_pkt_pointers(other_branch, dst_reg,
14762 dst_reg->type, false);
14763 mark_pkt_end(this_branch, insn->dst_reg, true);
14764 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14765 src_reg->type == PTR_TO_PACKET) ||
14766 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14767 src_reg->type == PTR_TO_PACKET_META)) {
14768 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14769 find_good_pkt_pointers(this_branch, src_reg,
14770 src_reg->type, true);
14771 mark_pkt_end(other_branch, insn->src_reg, false);
14783 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14784 struct bpf_reg_state *known_reg)
14786 struct bpf_func_state *state;
14787 struct bpf_reg_state *reg;
14789 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14790 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14791 copy_register_state(reg, known_reg);
14795 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14796 struct bpf_insn *insn, int *insn_idx)
14798 struct bpf_verifier_state *this_branch = env->cur_state;
14799 struct bpf_verifier_state *other_branch;
14800 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14801 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14802 struct bpf_reg_state *eq_branch_regs;
14803 struct bpf_reg_state fake_reg = {};
14804 u8 opcode = BPF_OP(insn->code);
14809 /* Only conditional jumps are expected to reach here. */
14810 if (opcode == BPF_JA || opcode > BPF_JSLE) {
14811 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14815 /* check src2 operand */
14816 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14820 dst_reg = ®s[insn->dst_reg];
14821 if (BPF_SRC(insn->code) == BPF_X) {
14822 if (insn->imm != 0) {
14823 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14827 /* check src1 operand */
14828 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14832 src_reg = ®s[insn->src_reg];
14833 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14834 is_pointer_value(env, insn->src_reg)) {
14835 verbose(env, "R%d pointer comparison prohibited\n",
14840 if (insn->src_reg != BPF_REG_0) {
14841 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14844 src_reg = &fake_reg;
14845 src_reg->type = SCALAR_VALUE;
14846 __mark_reg_known(src_reg, insn->imm);
14849 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14850 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
14852 /* If we get here with a dst_reg pointer type it is because
14853 * above is_branch_taken() special cased the 0 comparison.
14855 if (!__is_pointer_value(false, dst_reg))
14856 err = mark_chain_precision(env, insn->dst_reg);
14857 if (BPF_SRC(insn->code) == BPF_X && !err &&
14858 !__is_pointer_value(false, src_reg))
14859 err = mark_chain_precision(env, insn->src_reg);
14865 /* Only follow the goto, ignore fall-through. If needed, push
14866 * the fall-through branch for simulation under speculative
14869 if (!env->bypass_spec_v1 &&
14870 !sanitize_speculative_path(env, insn, *insn_idx + 1,
14873 if (env->log.level & BPF_LOG_LEVEL)
14874 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14875 *insn_idx += insn->off;
14877 } else if (pred == 0) {
14878 /* Only follow the fall-through branch, since that's where the
14879 * program will go. If needed, push the goto branch for
14880 * simulation under speculative execution.
14882 if (!env->bypass_spec_v1 &&
14883 !sanitize_speculative_path(env, insn,
14884 *insn_idx + insn->off + 1,
14887 if (env->log.level & BPF_LOG_LEVEL)
14888 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14892 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14896 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14898 if (BPF_SRC(insn->code) == BPF_X) {
14899 err = reg_set_min_max(env,
14900 &other_branch_regs[insn->dst_reg],
14901 &other_branch_regs[insn->src_reg],
14902 dst_reg, src_reg, opcode, is_jmp32);
14903 } else /* BPF_SRC(insn->code) == BPF_K */ {
14904 err = reg_set_min_max(env,
14905 &other_branch_regs[insn->dst_reg],
14906 src_reg /* fake one */,
14907 dst_reg, src_reg /* same fake one */,
14913 if (BPF_SRC(insn->code) == BPF_X &&
14914 src_reg->type == SCALAR_VALUE && src_reg->id &&
14915 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14916 find_equal_scalars(this_branch, src_reg);
14917 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14919 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14920 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14921 find_equal_scalars(this_branch, dst_reg);
14922 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14925 /* if one pointer register is compared to another pointer
14926 * register check if PTR_MAYBE_NULL could be lifted.
14927 * E.g. register A - maybe null
14928 * register B - not null
14929 * for JNE A, B, ... - A is not null in the false branch;
14930 * for JEQ A, B, ... - A is not null in the true branch.
14932 * Since PTR_TO_BTF_ID points to a kernel struct that does
14933 * not need to be null checked by the BPF program, i.e.,
14934 * could be null even without PTR_MAYBE_NULL marking, so
14935 * only propagate nullness when neither reg is that type.
14937 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14938 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14939 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14940 base_type(src_reg->type) != PTR_TO_BTF_ID &&
14941 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14942 eq_branch_regs = NULL;
14945 eq_branch_regs = other_branch_regs;
14948 eq_branch_regs = regs;
14954 if (eq_branch_regs) {
14955 if (type_may_be_null(src_reg->type))
14956 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14958 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14962 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14963 * NOTE: these optimizations below are related with pointer comparison
14964 * which will never be JMP32.
14966 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14967 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14968 type_may_be_null(dst_reg->type)) {
14969 /* Mark all identical registers in each branch as either
14970 * safe or unknown depending R == 0 or R != 0 conditional.
14972 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14973 opcode == BPF_JNE);
14974 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14975 opcode == BPF_JEQ);
14976 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
14977 this_branch, other_branch) &&
14978 is_pointer_value(env, insn->dst_reg)) {
14979 verbose(env, "R%d pointer comparison prohibited\n",
14983 if (env->log.level & BPF_LOG_LEVEL)
14984 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14988 /* verify BPF_LD_IMM64 instruction */
14989 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14991 struct bpf_insn_aux_data *aux = cur_aux(env);
14992 struct bpf_reg_state *regs = cur_regs(env);
14993 struct bpf_reg_state *dst_reg;
14994 struct bpf_map *map;
14997 if (BPF_SIZE(insn->code) != BPF_DW) {
14998 verbose(env, "invalid BPF_LD_IMM insn\n");
15001 if (insn->off != 0) {
15002 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
15006 err = check_reg_arg(env, insn->dst_reg, DST_OP);
15010 dst_reg = ®s[insn->dst_reg];
15011 if (insn->src_reg == 0) {
15012 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
15014 dst_reg->type = SCALAR_VALUE;
15015 __mark_reg_known(®s[insn->dst_reg], imm);
15019 /* All special src_reg cases are listed below. From this point onwards
15020 * we either succeed and assign a corresponding dst_reg->type after
15021 * zeroing the offset, or fail and reject the program.
15023 mark_reg_known_zero(env, regs, insn->dst_reg);
15025 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
15026 dst_reg->type = aux->btf_var.reg_type;
15027 switch (base_type(dst_reg->type)) {
15029 dst_reg->mem_size = aux->btf_var.mem_size;
15031 case PTR_TO_BTF_ID:
15032 dst_reg->btf = aux->btf_var.btf;
15033 dst_reg->btf_id = aux->btf_var.btf_id;
15036 verbose(env, "bpf verifier is misconfigured\n");
15042 if (insn->src_reg == BPF_PSEUDO_FUNC) {
15043 struct bpf_prog_aux *aux = env->prog->aux;
15044 u32 subprogno = find_subprog(env,
15045 env->insn_idx + insn->imm + 1);
15047 if (!aux->func_info) {
15048 verbose(env, "missing btf func_info\n");
15051 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
15052 verbose(env, "callback function not static\n");
15056 dst_reg->type = PTR_TO_FUNC;
15057 dst_reg->subprogno = subprogno;
15061 map = env->used_maps[aux->map_index];
15062 dst_reg->map_ptr = map;
15064 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15065 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15066 dst_reg->type = PTR_TO_MAP_VALUE;
15067 dst_reg->off = aux->map_off;
15068 WARN_ON_ONCE(map->max_entries != 1);
15069 /* We want reg->id to be same (0) as map_value is not distinct */
15070 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15071 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15072 dst_reg->type = CONST_PTR_TO_MAP;
15074 verbose(env, "bpf verifier is misconfigured\n");
15081 static bool may_access_skb(enum bpf_prog_type type)
15084 case BPF_PROG_TYPE_SOCKET_FILTER:
15085 case BPF_PROG_TYPE_SCHED_CLS:
15086 case BPF_PROG_TYPE_SCHED_ACT:
15093 /* verify safety of LD_ABS|LD_IND instructions:
15094 * - they can only appear in the programs where ctx == skb
15095 * - since they are wrappers of function calls, they scratch R1-R5 registers,
15096 * preserve R6-R9, and store return value into R0
15099 * ctx == skb == R6 == CTX
15102 * SRC == any register
15103 * IMM == 32-bit immediate
15106 * R0 - 8/16/32-bit skb data converted to cpu endianness
15108 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15110 struct bpf_reg_state *regs = cur_regs(env);
15111 static const int ctx_reg = BPF_REG_6;
15112 u8 mode = BPF_MODE(insn->code);
15115 if (!may_access_skb(resolve_prog_type(env->prog))) {
15116 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15120 if (!env->ops->gen_ld_abs) {
15121 verbose(env, "bpf verifier is misconfigured\n");
15125 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15126 BPF_SIZE(insn->code) == BPF_DW ||
15127 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15128 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
15132 /* check whether implicit source operand (register R6) is readable */
15133 err = check_reg_arg(env, ctx_reg, SRC_OP);
15137 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15138 * gen_ld_abs() may terminate the program at runtime, leading to
15141 err = check_reference_leak(env, false);
15143 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15147 if (env->cur_state->active_lock.ptr) {
15148 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15152 if (env->cur_state->active_rcu_lock) {
15153 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15157 if (regs[ctx_reg].type != PTR_TO_CTX) {
15159 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
15163 if (mode == BPF_IND) {
15164 /* check explicit source operand */
15165 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15170 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
15174 /* reset caller saved regs to unreadable */
15175 for (i = 0; i < CALLER_SAVED_REGS; i++) {
15176 mark_reg_not_init(env, regs, caller_saved[i]);
15177 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15180 /* mark destination R0 register as readable, since it contains
15181 * the value fetched from the packet.
15182 * Already marked as written above.
15184 mark_reg_unknown(env, regs, BPF_REG_0);
15185 /* ld_abs load up to 32-bit skb data. */
15186 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
15190 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
15192 const char *exit_ctx = "At program exit";
15193 struct tnum enforce_attach_type_range = tnum_unknown;
15194 const struct bpf_prog *prog = env->prog;
15195 struct bpf_reg_state *reg;
15196 struct bpf_retval_range range = retval_range(0, 1);
15197 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15199 struct bpf_func_state *frame = env->cur_state->frame[0];
15200 const bool is_subprog = frame->subprogno;
15202 /* LSM and struct_ops func-ptr's return type could be "void" */
15203 if (!is_subprog || frame->in_exception_callback_fn) {
15204 switch (prog_type) {
15205 case BPF_PROG_TYPE_LSM:
15206 if (prog->expected_attach_type == BPF_LSM_CGROUP)
15207 /* See below, can be 0 or 0-1 depending on hook. */
15210 case BPF_PROG_TYPE_STRUCT_OPS:
15211 if (!prog->aux->attach_func_proto->type)
15219 /* eBPF calling convention is such that R0 is used
15220 * to return the value from eBPF program.
15221 * Make sure that it's readable at this time
15222 * of bpf_exit, which means that program wrote
15223 * something into it earlier
15225 err = check_reg_arg(env, regno, SRC_OP);
15229 if (is_pointer_value(env, regno)) {
15230 verbose(env, "R%d leaks addr as return value\n", regno);
15234 reg = cur_regs(env) + regno;
15236 if (frame->in_async_callback_fn) {
15237 /* enforce return zero from async callbacks like timer */
15238 exit_ctx = "At async callback return";
15239 range = retval_range(0, 0);
15240 goto enforce_retval;
15243 if (is_subprog && !frame->in_exception_callback_fn) {
15244 if (reg->type != SCALAR_VALUE) {
15245 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15246 regno, reg_type_str(env, reg->type));
15252 switch (prog_type) {
15253 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15254 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15255 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15256 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15257 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15258 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15259 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15260 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15261 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15262 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15263 range = retval_range(1, 1);
15264 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15265 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15266 range = retval_range(0, 3);
15268 case BPF_PROG_TYPE_CGROUP_SKB:
15269 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15270 range = retval_range(0, 3);
15271 enforce_attach_type_range = tnum_range(2, 3);
15274 case BPF_PROG_TYPE_CGROUP_SOCK:
15275 case BPF_PROG_TYPE_SOCK_OPS:
15276 case BPF_PROG_TYPE_CGROUP_DEVICE:
15277 case BPF_PROG_TYPE_CGROUP_SYSCTL:
15278 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15280 case BPF_PROG_TYPE_RAW_TRACEPOINT:
15281 if (!env->prog->aux->attach_btf_id)
15283 range = retval_range(0, 0);
15285 case BPF_PROG_TYPE_TRACING:
15286 switch (env->prog->expected_attach_type) {
15287 case BPF_TRACE_FENTRY:
15288 case BPF_TRACE_FEXIT:
15289 range = retval_range(0, 0);
15291 case BPF_TRACE_RAW_TP:
15292 case BPF_MODIFY_RETURN:
15294 case BPF_TRACE_ITER:
15300 case BPF_PROG_TYPE_SK_LOOKUP:
15301 range = retval_range(SK_DROP, SK_PASS);
15304 case BPF_PROG_TYPE_LSM:
15305 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15306 /* Regular BPF_PROG_TYPE_LSM programs can return
15311 if (!env->prog->aux->attach_func_proto->type) {
15312 /* Make sure programs that attach to void
15313 * hooks don't try to modify return value.
15315 range = retval_range(1, 1);
15319 case BPF_PROG_TYPE_NETFILTER:
15320 range = retval_range(NF_DROP, NF_ACCEPT);
15322 case BPF_PROG_TYPE_EXT:
15323 /* freplace program can return anything as its return value
15324 * depends on the to-be-replaced kernel func or bpf program.
15331 if (reg->type != SCALAR_VALUE) {
15332 verbose(env, "%s the register R%d is not a known value (%s)\n",
15333 exit_ctx, regno, reg_type_str(env, reg->type));
15337 err = mark_chain_precision(env, regno);
15341 if (!retval_range_within(range, reg)) {
15342 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
15344 prog->expected_attach_type == BPF_LSM_CGROUP &&
15345 prog_type == BPF_PROG_TYPE_LSM &&
15346 !prog->aux->attach_func_proto->type)
15347 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15351 if (!tnum_is_unknown(enforce_attach_type_range) &&
15352 tnum_in(enforce_attach_type_range, reg->var_off))
15353 env->prog->enforce_expected_attach_type = 1;
15357 /* non-recursive DFS pseudo code
15358 * 1 procedure DFS-iterative(G,v):
15359 * 2 label v as discovered
15360 * 3 let S be a stack
15362 * 5 while S is not empty
15364 * 7 if t is what we're looking for:
15366 * 9 for all edges e in G.adjacentEdges(t) do
15367 * 10 if edge e is already labelled
15368 * 11 continue with the next edge
15369 * 12 w <- G.adjacentVertex(t,e)
15370 * 13 if vertex w is not discovered and not explored
15371 * 14 label e as tree-edge
15372 * 15 label w as discovered
15375 * 18 else if vertex w is discovered
15376 * 19 label e as back-edge
15378 * 21 // vertex w is explored
15379 * 22 label e as forward- or cross-edge
15380 * 23 label t as explored
15384 * 0x10 - discovered
15385 * 0x11 - discovered and fall-through edge labelled
15386 * 0x12 - discovered and fall-through and branch edges labelled
15397 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15399 env->insn_aux_data[idx].prune_point = true;
15402 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15404 return env->insn_aux_data[insn_idx].prune_point;
15407 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15409 env->insn_aux_data[idx].force_checkpoint = true;
15412 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15414 return env->insn_aux_data[insn_idx].force_checkpoint;
15417 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15419 env->insn_aux_data[idx].calls_callback = true;
15422 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15424 return env->insn_aux_data[insn_idx].calls_callback;
15428 DONE_EXPLORING = 0,
15429 KEEP_EXPLORING = 1,
15432 /* t, w, e - match pseudo-code above:
15433 * t - index of current instruction
15434 * w - next instruction
15437 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15439 int *insn_stack = env->cfg.insn_stack;
15440 int *insn_state = env->cfg.insn_state;
15442 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15443 return DONE_EXPLORING;
15445 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15446 return DONE_EXPLORING;
15448 if (w < 0 || w >= env->prog->len) {
15449 verbose_linfo(env, t, "%d: ", t);
15450 verbose(env, "jump out of range from insn %d to %d\n", t, w);
15455 /* mark branch target for state pruning */
15456 mark_prune_point(env, w);
15457 mark_jmp_point(env, w);
15460 if (insn_state[w] == 0) {
15462 insn_state[t] = DISCOVERED | e;
15463 insn_state[w] = DISCOVERED;
15464 if (env->cfg.cur_stack >= env->prog->len)
15466 insn_stack[env->cfg.cur_stack++] = w;
15467 return KEEP_EXPLORING;
15468 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15469 if (env->bpf_capable)
15470 return DONE_EXPLORING;
15471 verbose_linfo(env, t, "%d: ", t);
15472 verbose_linfo(env, w, "%d: ", w);
15473 verbose(env, "back-edge from insn %d to %d\n", t, w);
15475 } else if (insn_state[w] == EXPLORED) {
15476 /* forward- or cross-edge */
15477 insn_state[t] = DISCOVERED | e;
15479 verbose(env, "insn state internal bug\n");
15482 return DONE_EXPLORING;
15485 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15486 struct bpf_verifier_env *env,
15491 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15492 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15496 mark_prune_point(env, t + insn_sz);
15497 /* when we exit from subprog, we need to record non-linear history */
15498 mark_jmp_point(env, t + insn_sz);
15500 if (visit_callee) {
15501 mark_prune_point(env, t);
15502 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15507 /* Visits the instruction at index t and returns one of the following:
15508 * < 0 - an error occurred
15509 * DONE_EXPLORING - the instruction was fully explored
15510 * KEEP_EXPLORING - there is still work to be done before it is fully explored
15512 static int visit_insn(int t, struct bpf_verifier_env *env)
15514 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15515 int ret, off, insn_sz;
15517 if (bpf_pseudo_func(insn))
15518 return visit_func_call_insn(t, insns, env, true);
15520 /* All non-branch instructions have a single fall-through edge. */
15521 if (BPF_CLASS(insn->code) != BPF_JMP &&
15522 BPF_CLASS(insn->code) != BPF_JMP32) {
15523 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15524 return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15527 switch (BPF_OP(insn->code)) {
15529 return DONE_EXPLORING;
15532 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15533 /* Mark this call insn as a prune point to trigger
15534 * is_state_visited() check before call itself is
15535 * processed by __check_func_call(). Otherwise new
15536 * async state will be pushed for further exploration.
15538 mark_prune_point(env, t);
15539 /* For functions that invoke callbacks it is not known how many times
15540 * callback would be called. Verifier models callback calling functions
15541 * by repeatedly visiting callback bodies and returning to origin call
15543 * In order to stop such iteration verifier needs to identify when a
15544 * state identical some state from a previous iteration is reached.
15545 * Check below forces creation of checkpoint before callback calling
15546 * instruction to allow search for such identical states.
15548 if (is_sync_callback_calling_insn(insn)) {
15549 mark_calls_callback(env, t);
15550 mark_force_checkpoint(env, t);
15551 mark_prune_point(env, t);
15552 mark_jmp_point(env, t);
15554 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15555 struct bpf_kfunc_call_arg_meta meta;
15557 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15558 if (ret == 0 && is_iter_next_kfunc(&meta)) {
15559 mark_prune_point(env, t);
15560 /* Checking and saving state checkpoints at iter_next() call
15561 * is crucial for fast convergence of open-coded iterator loop
15562 * logic, so we need to force it. If we don't do that,
15563 * is_state_visited() might skip saving a checkpoint, causing
15564 * unnecessarily long sequence of not checkpointed
15565 * instructions and jumps, leading to exhaustion of jump
15566 * history buffer, and potentially other undesired outcomes.
15567 * It is expected that with correct open-coded iterators
15568 * convergence will happen quickly, so we don't run a risk of
15569 * exhausting memory.
15571 mark_force_checkpoint(env, t);
15574 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15577 if (BPF_SRC(insn->code) != BPF_K)
15580 if (BPF_CLASS(insn->code) == BPF_JMP)
15585 /* unconditional jump with single edge */
15586 ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15590 mark_prune_point(env, t + off + 1);
15591 mark_jmp_point(env, t + off + 1);
15596 /* conditional jump with two edges */
15597 mark_prune_point(env, t);
15599 ret = push_insn(t, t + 1, FALLTHROUGH, env);
15603 return push_insn(t, t + insn->off + 1, BRANCH, env);
15607 /* non-recursive depth-first-search to detect loops in BPF program
15608 * loop == back-edge in directed graph
15610 static int check_cfg(struct bpf_verifier_env *env)
15612 int insn_cnt = env->prog->len;
15613 int *insn_stack, *insn_state;
15614 int ex_insn_beg, i, ret = 0;
15615 bool ex_done = false;
15617 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15621 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15623 kvfree(insn_state);
15627 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15628 insn_stack[0] = 0; /* 0 is the first instruction */
15629 env->cfg.cur_stack = 1;
15632 while (env->cfg.cur_stack > 0) {
15633 int t = insn_stack[env->cfg.cur_stack - 1];
15635 ret = visit_insn(t, env);
15637 case DONE_EXPLORING:
15638 insn_state[t] = EXPLORED;
15639 env->cfg.cur_stack--;
15641 case KEEP_EXPLORING:
15645 verbose(env, "visit_insn internal bug\n");
15652 if (env->cfg.cur_stack < 0) {
15653 verbose(env, "pop stack internal bug\n");
15658 if (env->exception_callback_subprog && !ex_done) {
15659 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
15661 insn_state[ex_insn_beg] = DISCOVERED;
15662 insn_stack[0] = ex_insn_beg;
15663 env->cfg.cur_stack = 1;
15668 for (i = 0; i < insn_cnt; i++) {
15669 struct bpf_insn *insn = &env->prog->insnsi[i];
15671 if (insn_state[i] != EXPLORED) {
15672 verbose(env, "unreachable insn %d\n", i);
15676 if (bpf_is_ldimm64(insn)) {
15677 if (insn_state[i + 1] != 0) {
15678 verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15682 i++; /* skip second half of ldimm64 */
15685 ret = 0; /* cfg looks good */
15688 kvfree(insn_state);
15689 kvfree(insn_stack);
15690 env->cfg.insn_state = env->cfg.insn_stack = NULL;
15694 static int check_abnormal_return(struct bpf_verifier_env *env)
15698 for (i = 1; i < env->subprog_cnt; i++) {
15699 if (env->subprog_info[i].has_ld_abs) {
15700 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15703 if (env->subprog_info[i].has_tail_call) {
15704 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15711 /* The minimum supported BTF func info size */
15712 #define MIN_BPF_FUNCINFO_SIZE 8
15713 #define MAX_FUNCINFO_REC_SIZE 252
15715 static int check_btf_func_early(struct bpf_verifier_env *env,
15716 const union bpf_attr *attr,
15719 u32 krec_size = sizeof(struct bpf_func_info);
15720 const struct btf_type *type, *func_proto;
15721 u32 i, nfuncs, urec_size, min_size;
15722 struct bpf_func_info *krecord;
15723 struct bpf_prog *prog;
15724 const struct btf *btf;
15725 u32 prev_offset = 0;
15729 nfuncs = attr->func_info_cnt;
15731 if (check_abnormal_return(env))
15736 urec_size = attr->func_info_rec_size;
15737 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15738 urec_size > MAX_FUNCINFO_REC_SIZE ||
15739 urec_size % sizeof(u32)) {
15740 verbose(env, "invalid func info rec size %u\n", urec_size);
15745 btf = prog->aux->btf;
15747 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15748 min_size = min_t(u32, krec_size, urec_size);
15750 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15754 for (i = 0; i < nfuncs; i++) {
15755 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15757 if (ret == -E2BIG) {
15758 verbose(env, "nonzero tailing record in func info");
15759 /* set the size kernel expects so loader can zero
15760 * out the rest of the record.
15762 if (copy_to_bpfptr_offset(uattr,
15763 offsetof(union bpf_attr, func_info_rec_size),
15764 &min_size, sizeof(min_size)))
15770 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15775 /* check insn_off */
15778 if (krecord[i].insn_off) {
15780 "nonzero insn_off %u for the first func info record",
15781 krecord[i].insn_off);
15784 } else if (krecord[i].insn_off <= prev_offset) {
15786 "same or smaller insn offset (%u) than previous func info record (%u)",
15787 krecord[i].insn_off, prev_offset);
15791 /* check type_id */
15792 type = btf_type_by_id(btf, krecord[i].type_id);
15793 if (!type || !btf_type_is_func(type)) {
15794 verbose(env, "invalid type id %d in func info",
15795 krecord[i].type_id);
15799 func_proto = btf_type_by_id(btf, type->type);
15800 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15801 /* btf_func_check() already verified it during BTF load */
15804 prev_offset = krecord[i].insn_off;
15805 bpfptr_add(&urecord, urec_size);
15808 prog->aux->func_info = krecord;
15809 prog->aux->func_info_cnt = nfuncs;
15817 static int check_btf_func(struct bpf_verifier_env *env,
15818 const union bpf_attr *attr,
15821 const struct btf_type *type, *func_proto, *ret_type;
15822 u32 i, nfuncs, urec_size;
15823 struct bpf_func_info *krecord;
15824 struct bpf_func_info_aux *info_aux = NULL;
15825 struct bpf_prog *prog;
15826 const struct btf *btf;
15828 bool scalar_return;
15831 nfuncs = attr->func_info_cnt;
15833 if (check_abnormal_return(env))
15837 if (nfuncs != env->subprog_cnt) {
15838 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15842 urec_size = attr->func_info_rec_size;
15845 btf = prog->aux->btf;
15847 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15849 krecord = prog->aux->func_info;
15850 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15854 for (i = 0; i < nfuncs; i++) {
15855 /* check insn_off */
15858 if (env->subprog_info[i].start != krecord[i].insn_off) {
15859 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15863 /* Already checked type_id */
15864 type = btf_type_by_id(btf, krecord[i].type_id);
15865 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15866 /* Already checked func_proto */
15867 func_proto = btf_type_by_id(btf, type->type);
15869 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15871 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15872 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15873 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15876 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15877 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15881 bpfptr_add(&urecord, urec_size);
15884 prog->aux->func_info_aux = info_aux;
15892 static void adjust_btf_func(struct bpf_verifier_env *env)
15894 struct bpf_prog_aux *aux = env->prog->aux;
15897 if (!aux->func_info)
15900 /* func_info is not available for hidden subprogs */
15901 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
15902 aux->func_info[i].insn_off = env->subprog_info[i].start;
15905 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
15906 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
15908 static int check_btf_line(struct bpf_verifier_env *env,
15909 const union bpf_attr *attr,
15912 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15913 struct bpf_subprog_info *sub;
15914 struct bpf_line_info *linfo;
15915 struct bpf_prog *prog;
15916 const struct btf *btf;
15920 nr_linfo = attr->line_info_cnt;
15923 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15926 rec_size = attr->line_info_rec_size;
15927 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15928 rec_size > MAX_LINEINFO_REC_SIZE ||
15929 rec_size & (sizeof(u32) - 1))
15932 /* Need to zero it in case the userspace may
15933 * pass in a smaller bpf_line_info object.
15935 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15936 GFP_KERNEL | __GFP_NOWARN);
15941 btf = prog->aux->btf;
15944 sub = env->subprog_info;
15945 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15946 expected_size = sizeof(struct bpf_line_info);
15947 ncopy = min_t(u32, expected_size, rec_size);
15948 for (i = 0; i < nr_linfo; i++) {
15949 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15951 if (err == -E2BIG) {
15952 verbose(env, "nonzero tailing record in line_info");
15953 if (copy_to_bpfptr_offset(uattr,
15954 offsetof(union bpf_attr, line_info_rec_size),
15955 &expected_size, sizeof(expected_size)))
15961 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15967 * Check insn_off to ensure
15968 * 1) strictly increasing AND
15969 * 2) bounded by prog->len
15971 * The linfo[0].insn_off == 0 check logically falls into
15972 * the later "missing bpf_line_info for func..." case
15973 * because the first linfo[0].insn_off must be the
15974 * first sub also and the first sub must have
15975 * subprog_info[0].start == 0.
15977 if ((i && linfo[i].insn_off <= prev_offset) ||
15978 linfo[i].insn_off >= prog->len) {
15979 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15980 i, linfo[i].insn_off, prev_offset,
15986 if (!prog->insnsi[linfo[i].insn_off].code) {
15988 "Invalid insn code at line_info[%u].insn_off\n",
15994 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15995 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15996 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
16001 if (s != env->subprog_cnt) {
16002 if (linfo[i].insn_off == sub[s].start) {
16003 sub[s].linfo_idx = i;
16005 } else if (sub[s].start < linfo[i].insn_off) {
16006 verbose(env, "missing bpf_line_info for func#%u\n", s);
16012 prev_offset = linfo[i].insn_off;
16013 bpfptr_add(&ulinfo, rec_size);
16016 if (s != env->subprog_cnt) {
16017 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
16018 env->subprog_cnt - s, s);
16023 prog->aux->linfo = linfo;
16024 prog->aux->nr_linfo = nr_linfo;
16033 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
16034 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
16036 static int check_core_relo(struct bpf_verifier_env *env,
16037 const union bpf_attr *attr,
16040 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
16041 struct bpf_core_relo core_relo = {};
16042 struct bpf_prog *prog = env->prog;
16043 const struct btf *btf = prog->aux->btf;
16044 struct bpf_core_ctx ctx = {
16048 bpfptr_t u_core_relo;
16051 nr_core_relo = attr->core_relo_cnt;
16054 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
16057 rec_size = attr->core_relo_rec_size;
16058 if (rec_size < MIN_CORE_RELO_SIZE ||
16059 rec_size > MAX_CORE_RELO_SIZE ||
16060 rec_size % sizeof(u32))
16063 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
16064 expected_size = sizeof(struct bpf_core_relo);
16065 ncopy = min_t(u32, expected_size, rec_size);
16067 /* Unlike func_info and line_info, copy and apply each CO-RE
16068 * relocation record one at a time.
16070 for (i = 0; i < nr_core_relo; i++) {
16071 /* future proofing when sizeof(bpf_core_relo) changes */
16072 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
16074 if (err == -E2BIG) {
16075 verbose(env, "nonzero tailing record in core_relo");
16076 if (copy_to_bpfptr_offset(uattr,
16077 offsetof(union bpf_attr, core_relo_rec_size),
16078 &expected_size, sizeof(expected_size)))
16084 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16089 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16090 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16091 i, core_relo.insn_off, prog->len);
16096 err = bpf_core_apply(&ctx, &core_relo, i,
16097 &prog->insnsi[core_relo.insn_off / 8]);
16100 bpfptr_add(&u_core_relo, rec_size);
16105 static int check_btf_info_early(struct bpf_verifier_env *env,
16106 const union bpf_attr *attr,
16112 if (!attr->func_info_cnt && !attr->line_info_cnt) {
16113 if (check_abnormal_return(env))
16118 btf = btf_get_by_fd(attr->prog_btf_fd);
16120 return PTR_ERR(btf);
16121 if (btf_is_kernel(btf)) {
16125 env->prog->aux->btf = btf;
16127 err = check_btf_func_early(env, attr, uattr);
16133 static int check_btf_info(struct bpf_verifier_env *env,
16134 const union bpf_attr *attr,
16139 if (!attr->func_info_cnt && !attr->line_info_cnt) {
16140 if (check_abnormal_return(env))
16145 err = check_btf_func(env, attr, uattr);
16149 err = check_btf_line(env, attr, uattr);
16153 err = check_core_relo(env, attr, uattr);
16160 /* check %cur's range satisfies %old's */
16161 static bool range_within(struct bpf_reg_state *old,
16162 struct bpf_reg_state *cur)
16164 return old->umin_value <= cur->umin_value &&
16165 old->umax_value >= cur->umax_value &&
16166 old->smin_value <= cur->smin_value &&
16167 old->smax_value >= cur->smax_value &&
16168 old->u32_min_value <= cur->u32_min_value &&
16169 old->u32_max_value >= cur->u32_max_value &&
16170 old->s32_min_value <= cur->s32_min_value &&
16171 old->s32_max_value >= cur->s32_max_value;
16174 /* If in the old state two registers had the same id, then they need to have
16175 * the same id in the new state as well. But that id could be different from
16176 * the old state, so we need to track the mapping from old to new ids.
16177 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
16178 * regs with old id 5 must also have new id 9 for the new state to be safe. But
16179 * regs with a different old id could still have new id 9, we don't care about
16181 * So we look through our idmap to see if this old id has been seen before. If
16182 * so, we require the new id to match; otherwise, we add the id pair to the map.
16184 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16186 struct bpf_id_pair *map = idmap->map;
16189 /* either both IDs should be set or both should be zero */
16190 if (!!old_id != !!cur_id)
16193 if (old_id == 0) /* cur_id == 0 as well */
16196 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
16198 /* Reached an empty slot; haven't seen this id before */
16199 map[i].old = old_id;
16200 map[i].cur = cur_id;
16203 if (map[i].old == old_id)
16204 return map[i].cur == cur_id;
16205 if (map[i].cur == cur_id)
16208 /* We ran out of idmap slots, which should be impossible */
16213 /* Similar to check_ids(), but allocate a unique temporary ID
16214 * for 'old_id' or 'cur_id' of zero.
16215 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
16217 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16219 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
16220 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
16222 return check_ids(old_id, cur_id, idmap);
16225 static void clean_func_state(struct bpf_verifier_env *env,
16226 struct bpf_func_state *st)
16228 enum bpf_reg_liveness live;
16231 for (i = 0; i < BPF_REG_FP; i++) {
16232 live = st->regs[i].live;
16233 /* liveness must not touch this register anymore */
16234 st->regs[i].live |= REG_LIVE_DONE;
16235 if (!(live & REG_LIVE_READ))
16236 /* since the register is unused, clear its state
16237 * to make further comparison simpler
16239 __mark_reg_not_init(env, &st->regs[i]);
16242 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
16243 live = st->stack[i].spilled_ptr.live;
16244 /* liveness must not touch this stack slot anymore */
16245 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
16246 if (!(live & REG_LIVE_READ)) {
16247 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
16248 for (j = 0; j < BPF_REG_SIZE; j++)
16249 st->stack[i].slot_type[j] = STACK_INVALID;
16254 static void clean_verifier_state(struct bpf_verifier_env *env,
16255 struct bpf_verifier_state *st)
16259 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
16260 /* all regs in this state in all frames were already marked */
16263 for (i = 0; i <= st->curframe; i++)
16264 clean_func_state(env, st->frame[i]);
16267 /* the parentage chains form a tree.
16268 * the verifier states are added to state lists at given insn and
16269 * pushed into state stack for future exploration.
16270 * when the verifier reaches bpf_exit insn some of the verifer states
16271 * stored in the state lists have their final liveness state already,
16272 * but a lot of states will get revised from liveness point of view when
16273 * the verifier explores other branches.
16276 * 2: if r1 == 100 goto pc+1
16279 * when the verifier reaches exit insn the register r0 in the state list of
16280 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
16281 * of insn 2 and goes exploring further. At the insn 4 it will walk the
16282 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
16284 * Since the verifier pushes the branch states as it sees them while exploring
16285 * the program the condition of walking the branch instruction for the second
16286 * time means that all states below this branch were already explored and
16287 * their final liveness marks are already propagated.
16288 * Hence when the verifier completes the search of state list in is_state_visited()
16289 * we can call this clean_live_states() function to mark all liveness states
16290 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16291 * will not be used.
16292 * This function also clears the registers and stack for states that !READ
16293 * to simplify state merging.
16295 * Important note here that walking the same branch instruction in the callee
16296 * doesn't meant that the states are DONE. The verifier has to compare
16299 static void clean_live_states(struct bpf_verifier_env *env, int insn,
16300 struct bpf_verifier_state *cur)
16302 struct bpf_verifier_state_list *sl;
16304 sl = *explored_state(env, insn);
16306 if (sl->state.branches)
16308 if (sl->state.insn_idx != insn ||
16309 !same_callsites(&sl->state, cur))
16311 clean_verifier_state(env, &sl->state);
16317 static bool regs_exact(const struct bpf_reg_state *rold,
16318 const struct bpf_reg_state *rcur,
16319 struct bpf_idmap *idmap)
16321 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16322 check_ids(rold->id, rcur->id, idmap) &&
16323 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16326 /* Returns true if (rold safe implies rcur safe) */
16327 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
16328 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
16331 return regs_exact(rold, rcur, idmap);
16333 if (!(rold->live & REG_LIVE_READ))
16334 /* explored state didn't use this */
16336 if (rold->type == NOT_INIT)
16337 /* explored state can't have used this */
16339 if (rcur->type == NOT_INIT)
16342 /* Enforce that register types have to match exactly, including their
16343 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16346 * One can make a point that using a pointer register as unbounded
16347 * SCALAR would be technically acceptable, but this could lead to
16348 * pointer leaks because scalars are allowed to leak while pointers
16349 * are not. We could make this safe in special cases if root is
16350 * calling us, but it's probably not worth the hassle.
16352 * Also, register types that are *not* MAYBE_NULL could technically be
16353 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16354 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16355 * to the same map).
16356 * However, if the old MAYBE_NULL register then got NULL checked,
16357 * doing so could have affected others with the same id, and we can't
16358 * check for that because we lost the id when we converted to
16359 * a non-MAYBE_NULL variant.
16360 * So, as a general rule we don't allow mixing MAYBE_NULL and
16361 * non-MAYBE_NULL registers as well.
16363 if (rold->type != rcur->type)
16366 switch (base_type(rold->type)) {
16368 if (env->explore_alu_limits) {
16369 /* explore_alu_limits disables tnum_in() and range_within()
16370 * logic and requires everything to be strict
16372 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16373 check_scalar_ids(rold->id, rcur->id, idmap);
16375 if (!rold->precise)
16377 /* Why check_ids() for scalar registers?
16379 * Consider the following BPF code:
16380 * 1: r6 = ... unbound scalar, ID=a ...
16381 * 2: r7 = ... unbound scalar, ID=b ...
16382 * 3: if (r6 > r7) goto +1
16384 * 5: if (r6 > X) goto ...
16385 * 6: ... memory operation using r7 ...
16387 * First verification path is [1-6]:
16388 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16389 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16390 * r7 <= X, because r6 and r7 share same id.
16391 * Next verification path is [1-4, 6].
16393 * Instruction (6) would be reached in two states:
16394 * I. r6{.id=b}, r7{.id=b} via path 1-6;
16395 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16397 * Use check_ids() to distinguish these states.
16399 * Also verify that new value satisfies old value range knowledge.
16401 return range_within(rold, rcur) &&
16402 tnum_in(rold->var_off, rcur->var_off) &&
16403 check_scalar_ids(rold->id, rcur->id, idmap);
16404 case PTR_TO_MAP_KEY:
16405 case PTR_TO_MAP_VALUE:
16408 case PTR_TO_TP_BUFFER:
16409 /* If the new min/max/var_off satisfy the old ones and
16410 * everything else matches, we are OK.
16412 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16413 range_within(rold, rcur) &&
16414 tnum_in(rold->var_off, rcur->var_off) &&
16415 check_ids(rold->id, rcur->id, idmap) &&
16416 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16417 case PTR_TO_PACKET_META:
16418 case PTR_TO_PACKET:
16419 /* We must have at least as much range as the old ptr
16420 * did, so that any accesses which were safe before are
16421 * still safe. This is true even if old range < old off,
16422 * since someone could have accessed through (ptr - k), or
16423 * even done ptr -= k in a register, to get a safe access.
16425 if (rold->range > rcur->range)
16427 /* If the offsets don't match, we can't trust our alignment;
16428 * nor can we be sure that we won't fall out of range.
16430 if (rold->off != rcur->off)
16432 /* id relations must be preserved */
16433 if (!check_ids(rold->id, rcur->id, idmap))
16435 /* new val must satisfy old val knowledge */
16436 return range_within(rold, rcur) &&
16437 tnum_in(rold->var_off, rcur->var_off);
16439 /* two stack pointers are equal only if they're pointing to
16440 * the same stack frame, since fp-8 in foo != fp-8 in bar
16442 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16444 return regs_exact(rold, rcur, idmap);
16448 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16449 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16453 /* walk slots of the explored stack and ignore any additional
16454 * slots in the current stack, since explored(safe) state
16457 for (i = 0; i < old->allocated_stack; i++) {
16458 struct bpf_reg_state *old_reg, *cur_reg;
16460 spi = i / BPF_REG_SIZE;
16463 old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16464 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16467 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16468 i += BPF_REG_SIZE - 1;
16469 /* explored state didn't use this */
16473 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16476 if (env->allow_uninit_stack &&
16477 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16480 /* explored stack has more populated slots than current stack
16481 * and these slots were used
16483 if (i >= cur->allocated_stack)
16486 /* if old state was safe with misc data in the stack
16487 * it will be safe with zero-initialized stack.
16488 * The opposite is not true
16490 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16491 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16493 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16494 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16495 /* Ex: old explored (safe) state has STACK_SPILL in
16496 * this stack slot, but current has STACK_MISC ->
16497 * this verifier states are not equivalent,
16498 * return false to continue verification of this path
16501 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16503 /* Both old and cur are having same slot_type */
16504 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16506 /* when explored and current stack slot are both storing
16507 * spilled registers, check that stored pointers types
16508 * are the same as well.
16509 * Ex: explored safe path could have stored
16510 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16511 * but current path has stored:
16512 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16513 * such verifier states are not equivalent.
16514 * return false to continue verification of this path
16516 if (!regsafe(env, &old->stack[spi].spilled_ptr,
16517 &cur->stack[spi].spilled_ptr, idmap, exact))
16521 old_reg = &old->stack[spi].spilled_ptr;
16522 cur_reg = &cur->stack[spi].spilled_ptr;
16523 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16524 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16525 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16529 old_reg = &old->stack[spi].spilled_ptr;
16530 cur_reg = &cur->stack[spi].spilled_ptr;
16531 /* iter.depth is not compared between states as it
16532 * doesn't matter for correctness and would otherwise
16533 * prevent convergence; we maintain it only to prevent
16534 * infinite loop check triggering, see
16535 * iter_active_depths_differ()
16537 if (old_reg->iter.btf != cur_reg->iter.btf ||
16538 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16539 old_reg->iter.state != cur_reg->iter.state ||
16540 /* ignore {old_reg,cur_reg}->iter.depth, see above */
16541 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16546 case STACK_INVALID:
16548 /* Ensure that new unhandled slot types return false by default */
16556 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16557 struct bpf_idmap *idmap)
16561 if (old->acquired_refs != cur->acquired_refs)
16564 for (i = 0; i < old->acquired_refs; i++) {
16565 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16572 /* compare two verifier states
16574 * all states stored in state_list are known to be valid, since
16575 * verifier reached 'bpf_exit' instruction through them
16577 * this function is called when verifier exploring different branches of
16578 * execution popped from the state stack. If it sees an old state that has
16579 * more strict register state and more strict stack state then this execution
16580 * branch doesn't need to be explored further, since verifier already
16581 * concluded that more strict state leads to valid finish.
16583 * Therefore two states are equivalent if register state is more conservative
16584 * and explored stack state is more conservative than the current one.
16587 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16588 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16590 * In other words if current stack state (one being explored) has more
16591 * valid slots than old one that already passed validation, it means
16592 * the verifier can stop exploring and conclude that current state is valid too
16594 * Similarly with registers. If explored state has register type as invalid
16595 * whereas register type in current state is meaningful, it means that
16596 * the current state will reach 'bpf_exit' instruction safely
16598 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16599 struct bpf_func_state *cur, bool exact)
16603 for (i = 0; i < MAX_BPF_REG; i++)
16604 if (!regsafe(env, &old->regs[i], &cur->regs[i],
16605 &env->idmap_scratch, exact))
16608 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16611 if (!refsafe(old, cur, &env->idmap_scratch))
16617 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16619 env->idmap_scratch.tmp_id_gen = env->id_gen;
16620 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16623 static bool states_equal(struct bpf_verifier_env *env,
16624 struct bpf_verifier_state *old,
16625 struct bpf_verifier_state *cur,
16630 if (old->curframe != cur->curframe)
16633 reset_idmap_scratch(env);
16635 /* Verification state from speculative execution simulation
16636 * must never prune a non-speculative execution one.
16638 if (old->speculative && !cur->speculative)
16641 if (old->active_lock.ptr != cur->active_lock.ptr)
16644 /* Old and cur active_lock's have to be either both present
16647 if (!!old->active_lock.id != !!cur->active_lock.id)
16650 if (old->active_lock.id &&
16651 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16654 if (old->active_rcu_lock != cur->active_rcu_lock)
16657 /* for states to be equal callsites have to be the same
16658 * and all frame states need to be equivalent
16660 for (i = 0; i <= old->curframe; i++) {
16661 if (old->frame[i]->callsite != cur->frame[i]->callsite)
16663 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16669 /* Return 0 if no propagation happened. Return negative error code if error
16670 * happened. Otherwise, return the propagated bit.
16672 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16673 struct bpf_reg_state *reg,
16674 struct bpf_reg_state *parent_reg)
16676 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16677 u8 flag = reg->live & REG_LIVE_READ;
16680 /* When comes here, read flags of PARENT_REG or REG could be any of
16681 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16682 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16684 if (parent_flag == REG_LIVE_READ64 ||
16685 /* Or if there is no read flag from REG. */
16687 /* Or if the read flag from REG is the same as PARENT_REG. */
16688 parent_flag == flag)
16691 err = mark_reg_read(env, reg, parent_reg, flag);
16698 /* A write screens off any subsequent reads; but write marks come from the
16699 * straight-line code between a state and its parent. When we arrive at an
16700 * equivalent state (jump target or such) we didn't arrive by the straight-line
16701 * code, so read marks in the state must propagate to the parent regardless
16702 * of the state's write marks. That's what 'parent == state->parent' comparison
16703 * in mark_reg_read() is for.
16705 static int propagate_liveness(struct bpf_verifier_env *env,
16706 const struct bpf_verifier_state *vstate,
16707 struct bpf_verifier_state *vparent)
16709 struct bpf_reg_state *state_reg, *parent_reg;
16710 struct bpf_func_state *state, *parent;
16711 int i, frame, err = 0;
16713 if (vparent->curframe != vstate->curframe) {
16714 WARN(1, "propagate_live: parent frame %d current frame %d\n",
16715 vparent->curframe, vstate->curframe);
16718 /* Propagate read liveness of registers... */
16719 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16720 for (frame = 0; frame <= vstate->curframe; frame++) {
16721 parent = vparent->frame[frame];
16722 state = vstate->frame[frame];
16723 parent_reg = parent->regs;
16724 state_reg = state->regs;
16725 /* We don't need to worry about FP liveness, it's read-only */
16726 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16727 err = propagate_liveness_reg(env, &state_reg[i],
16731 if (err == REG_LIVE_READ64)
16732 mark_insn_zext(env, &parent_reg[i]);
16735 /* Propagate stack slots. */
16736 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16737 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16738 parent_reg = &parent->stack[i].spilled_ptr;
16739 state_reg = &state->stack[i].spilled_ptr;
16740 err = propagate_liveness_reg(env, state_reg,
16749 /* find precise scalars in the previous equivalent state and
16750 * propagate them into the current state
16752 static int propagate_precision(struct bpf_verifier_env *env,
16753 const struct bpf_verifier_state *old)
16755 struct bpf_reg_state *state_reg;
16756 struct bpf_func_state *state;
16757 int i, err = 0, fr;
16760 for (fr = old->curframe; fr >= 0; fr--) {
16761 state = old->frame[fr];
16762 state_reg = state->regs;
16764 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16765 if (state_reg->type != SCALAR_VALUE ||
16766 !state_reg->precise ||
16767 !(state_reg->live & REG_LIVE_READ))
16769 if (env->log.level & BPF_LOG_LEVEL2) {
16771 verbose(env, "frame %d: propagating r%d", fr, i);
16773 verbose(env, ",r%d", i);
16775 bt_set_frame_reg(&env->bt, fr, i);
16779 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16780 if (!is_spilled_reg(&state->stack[i]))
16782 state_reg = &state->stack[i].spilled_ptr;
16783 if (state_reg->type != SCALAR_VALUE ||
16784 !state_reg->precise ||
16785 !(state_reg->live & REG_LIVE_READ))
16787 if (env->log.level & BPF_LOG_LEVEL2) {
16789 verbose(env, "frame %d: propagating fp%d",
16790 fr, (-i - 1) * BPF_REG_SIZE);
16792 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16794 bt_set_frame_slot(&env->bt, fr, i);
16798 verbose(env, "\n");
16801 err = mark_chain_precision_batch(env);
16808 static bool states_maybe_looping(struct bpf_verifier_state *old,
16809 struct bpf_verifier_state *cur)
16811 struct bpf_func_state *fold, *fcur;
16812 int i, fr = cur->curframe;
16814 if (old->curframe != fr)
16817 fold = old->frame[fr];
16818 fcur = cur->frame[fr];
16819 for (i = 0; i < MAX_BPF_REG; i++)
16820 if (memcmp(&fold->regs[i], &fcur->regs[i],
16821 offsetof(struct bpf_reg_state, parent)))
16826 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16828 return env->insn_aux_data[insn_idx].is_iter_next;
16831 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16832 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16833 * states to match, which otherwise would look like an infinite loop. So while
16834 * iter_next() calls are taken care of, we still need to be careful and
16835 * prevent erroneous and too eager declaration of "ininite loop", when
16836 * iterators are involved.
16838 * Here's a situation in pseudo-BPF assembly form:
16840 * 0: again: ; set up iter_next() call args
16841 * 1: r1 = &it ; <CHECKPOINT HERE>
16842 * 2: call bpf_iter_num_next ; this is iter_next() call
16843 * 3: if r0 == 0 goto done
16844 * 4: ... something useful here ...
16845 * 5: goto again ; another iteration
16848 * 8: call bpf_iter_num_destroy ; clean up iter state
16851 * This is a typical loop. Let's assume that we have a prune point at 1:,
16852 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16853 * again`, assuming other heuristics don't get in a way).
16855 * When we first time come to 1:, let's say we have some state X. We proceed
16856 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16857 * Now we come back to validate that forked ACTIVE state. We proceed through
16858 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16859 * are converging. But the problem is that we don't know that yet, as this
16860 * convergence has to happen at iter_next() call site only. So if nothing is
16861 * done, at 1: verifier will use bounded loop logic and declare infinite
16862 * looping (and would be *technically* correct, if not for iterator's
16863 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16864 * don't want that. So what we do in process_iter_next_call() when we go on
16865 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16866 * a different iteration. So when we suspect an infinite loop, we additionally
16867 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16868 * pretend we are not looping and wait for next iter_next() call.
16870 * This only applies to ACTIVE state. In DRAINED state we don't expect to
16871 * loop, because that would actually mean infinite loop, as DRAINED state is
16872 * "sticky", and so we'll keep returning into the same instruction with the
16873 * same state (at least in one of possible code paths).
16875 * This approach allows to keep infinite loop heuristic even in the face of
16876 * active iterator. E.g., C snippet below is and will be detected as
16877 * inifintely looping:
16879 * struct bpf_iter_num it;
16882 * bpf_iter_num_new(&it, 0, 10);
16883 * while ((p = bpf_iter_num_next(&t))) {
16885 * while (x--) {} // <<-- infinite loop here
16889 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16891 struct bpf_reg_state *slot, *cur_slot;
16892 struct bpf_func_state *state;
16895 for (fr = old->curframe; fr >= 0; fr--) {
16896 state = old->frame[fr];
16897 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16898 if (state->stack[i].slot_type[0] != STACK_ITER)
16901 slot = &state->stack[i].spilled_ptr;
16902 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16905 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16906 if (cur_slot->iter.depth != slot->iter.depth)
16913 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16915 struct bpf_verifier_state_list *new_sl;
16916 struct bpf_verifier_state_list *sl, **pprev;
16917 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16918 int i, j, n, err, states_cnt = 0;
16919 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16920 bool add_new_state = force_new_state;
16923 /* bpf progs typically have pruning point every 4 instructions
16924 * http://vger.kernel.org/bpfconf2019.html#session-1
16925 * Do not add new state for future pruning if the verifier hasn't seen
16926 * at least 2 jumps and at least 8 instructions.
16927 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16928 * In tests that amounts to up to 50% reduction into total verifier
16929 * memory consumption and 20% verifier time speedup.
16931 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16932 env->insn_processed - env->prev_insn_processed >= 8)
16933 add_new_state = true;
16935 pprev = explored_state(env, insn_idx);
16938 clean_live_states(env, insn_idx, cur);
16942 if (sl->state.insn_idx != insn_idx)
16945 if (sl->state.branches) {
16946 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16948 if (frame->in_async_callback_fn &&
16949 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16950 /* Different async_entry_cnt means that the verifier is
16951 * processing another entry into async callback.
16952 * Seeing the same state is not an indication of infinite
16953 * loop or infinite recursion.
16954 * But finding the same state doesn't mean that it's safe
16955 * to stop processing the current state. The previous state
16956 * hasn't yet reached bpf_exit, since state.branches > 0.
16957 * Checking in_async_callback_fn alone is not enough either.
16958 * Since the verifier still needs to catch infinite loops
16959 * inside async callbacks.
16961 goto skip_inf_loop_check;
16963 /* BPF open-coded iterators loop detection is special.
16964 * states_maybe_looping() logic is too simplistic in detecting
16965 * states that *might* be equivalent, because it doesn't know
16966 * about ID remapping, so don't even perform it.
16967 * See process_iter_next_call() and iter_active_depths_differ()
16968 * for overview of the logic. When current and one of parent
16969 * states are detected as equivalent, it's a good thing: we prove
16970 * convergence and can stop simulating further iterations.
16971 * It's safe to assume that iterator loop will finish, taking into
16972 * account iter_next() contract of eventually returning
16973 * sticky NULL result.
16975 * Note, that states have to be compared exactly in this case because
16976 * read and precision marks might not be finalized inside the loop.
16977 * E.g. as in the program below:
16980 * 2. r6 = bpf_get_prandom_u32()
16981 * 3. while (bpf_iter_num_next(&fp[-8])) {
16982 * 4. if (r6 != 42) {
16984 * 6. r6 = bpf_get_prandom_u32()
16989 * 11. r8 = *(u64 *)(r0 + 0)
16990 * 12. r6 = bpf_get_prandom_u32()
16993 * Here verifier would first visit path 1-3, create a checkpoint at 3
16994 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16995 * not have read or precision mark for r7 yet, thus inexact states
16996 * comparison would discard current state with r7=-32
16997 * => unsafe memory access at 11 would not be caught.
16999 if (is_iter_next_insn(env, insn_idx)) {
17000 if (states_equal(env, &sl->state, cur, true)) {
17001 struct bpf_func_state *cur_frame;
17002 struct bpf_reg_state *iter_state, *iter_reg;
17005 cur_frame = cur->frame[cur->curframe];
17006 /* btf_check_iter_kfuncs() enforces that
17007 * iter state pointer is always the first arg
17009 iter_reg = &cur_frame->regs[BPF_REG_1];
17010 /* current state is valid due to states_equal(),
17011 * so we can assume valid iter and reg state,
17012 * no need for extra (re-)validations
17014 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
17015 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
17016 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
17017 update_loop_entry(cur, &sl->state);
17021 goto skip_inf_loop_check;
17023 if (calls_callback(env, insn_idx)) {
17024 if (states_equal(env, &sl->state, cur, true))
17026 goto skip_inf_loop_check;
17028 /* attempt to detect infinite loop to avoid unnecessary doomed work */
17029 if (states_maybe_looping(&sl->state, cur) &&
17030 states_equal(env, &sl->state, cur, false) &&
17031 !iter_active_depths_differ(&sl->state, cur) &&
17032 sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
17033 verbose_linfo(env, insn_idx, "; ");
17034 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
17035 verbose(env, "cur state:");
17036 print_verifier_state(env, cur->frame[cur->curframe], true);
17037 verbose(env, "old state:");
17038 print_verifier_state(env, sl->state.frame[cur->curframe], true);
17041 /* if the verifier is processing a loop, avoid adding new state
17042 * too often, since different loop iterations have distinct
17043 * states and may not help future pruning.
17044 * This threshold shouldn't be too low to make sure that
17045 * a loop with large bound will be rejected quickly.
17046 * The most abusive loop will be:
17048 * if r1 < 1000000 goto pc-2
17049 * 1M insn_procssed limit / 100 == 10k peak states.
17050 * This threshold shouldn't be too high either, since states
17051 * at the end of the loop are likely to be useful in pruning.
17053 skip_inf_loop_check:
17054 if (!force_new_state &&
17055 env->jmps_processed - env->prev_jmps_processed < 20 &&
17056 env->insn_processed - env->prev_insn_processed < 100)
17057 add_new_state = false;
17060 /* If sl->state is a part of a loop and this loop's entry is a part of
17061 * current verification path then states have to be compared exactly.
17062 * 'force_exact' is needed to catch the following case:
17064 * initial Here state 'succ' was processed first,
17065 * | it was eventually tracked to produce a
17066 * V state identical to 'hdr'.
17067 * .---------> hdr All branches from 'succ' had been explored
17068 * | | and thus 'succ' has its .branches == 0.
17070 * | .------... Suppose states 'cur' and 'succ' correspond
17071 * | | | to the same instruction + callsites.
17072 * | V V In such case it is necessary to check
17073 * | ... ... if 'succ' and 'cur' are states_equal().
17074 * | | | If 'succ' and 'cur' are a part of the
17075 * | V V same loop exact flag has to be set.
17076 * | succ <- cur To check if that is the case, verify
17077 * | | if loop entry of 'succ' is in current
17083 * Additional details are in the comment before get_loop_entry().
17085 loop_entry = get_loop_entry(&sl->state);
17086 force_exact = loop_entry && loop_entry->branches > 0;
17087 if (states_equal(env, &sl->state, cur, force_exact)) {
17089 update_loop_entry(cur, loop_entry);
17092 /* reached equivalent register/stack state,
17093 * prune the search.
17094 * Registers read by the continuation are read by us.
17095 * If we have any write marks in env->cur_state, they
17096 * will prevent corresponding reads in the continuation
17097 * from reaching our parent (an explored_state). Our
17098 * own state will get the read marks recorded, but
17099 * they'll be immediately forgotten as we're pruning
17100 * this state and will pop a new one.
17102 err = propagate_liveness(env, &sl->state, cur);
17104 /* if previous state reached the exit with precision and
17105 * current state is equivalent to it (except precsion marks)
17106 * the precision needs to be propagated back in
17107 * the current state.
17109 if (is_jmp_point(env, env->insn_idx))
17110 err = err ? : push_jmp_history(env, cur, 0);
17111 err = err ? : propagate_precision(env, &sl->state);
17117 /* when new state is not going to be added do not increase miss count.
17118 * Otherwise several loop iterations will remove the state
17119 * recorded earlier. The goal of these heuristics is to have
17120 * states from some iterations of the loop (some in the beginning
17121 * and some at the end) to help pruning.
17125 /* heuristic to determine whether this state is beneficial
17126 * to keep checking from state equivalence point of view.
17127 * Higher numbers increase max_states_per_insn and verification time,
17128 * but do not meaningfully decrease insn_processed.
17129 * 'n' controls how many times state could miss before eviction.
17130 * Use bigger 'n' for checkpoints because evicting checkpoint states
17131 * too early would hinder iterator convergence.
17133 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
17134 if (sl->miss_cnt > sl->hit_cnt * n + n) {
17135 /* the state is unlikely to be useful. Remove it to
17136 * speed up verification
17139 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
17140 !sl->state.used_as_loop_entry) {
17141 u32 br = sl->state.branches;
17144 "BUG live_done but branches_to_explore %d\n",
17146 free_verifier_state(&sl->state, false);
17148 env->peak_states--;
17150 /* cannot free this state, since parentage chain may
17151 * walk it later. Add it for free_list instead to
17152 * be freed at the end of verification
17154 sl->next = env->free_list;
17155 env->free_list = sl;
17165 if (env->max_states_per_insn < states_cnt)
17166 env->max_states_per_insn = states_cnt;
17168 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
17171 if (!add_new_state)
17174 /* There were no equivalent states, remember the current one.
17175 * Technically the current state is not proven to be safe yet,
17176 * but it will either reach outer most bpf_exit (which means it's safe)
17177 * or it will be rejected. When there are no loops the verifier won't be
17178 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
17179 * again on the way to bpf_exit.
17180 * When looping the sl->state.branches will be > 0 and this state
17181 * will not be considered for equivalence until branches == 0.
17183 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
17186 env->total_states++;
17187 env->peak_states++;
17188 env->prev_jmps_processed = env->jmps_processed;
17189 env->prev_insn_processed = env->insn_processed;
17191 /* forget precise markings we inherited, see __mark_chain_precision */
17192 if (env->bpf_capable)
17193 mark_all_scalars_imprecise(env, cur);
17195 /* add new state to the head of linked list */
17196 new = &new_sl->state;
17197 err = copy_verifier_state(new, cur);
17199 free_verifier_state(new, false);
17203 new->insn_idx = insn_idx;
17204 WARN_ONCE(new->branches != 1,
17205 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
17208 cur->first_insn_idx = insn_idx;
17209 cur->dfs_depth = new->dfs_depth + 1;
17210 clear_jmp_history(cur);
17211 new_sl->next = *explored_state(env, insn_idx);
17212 *explored_state(env, insn_idx) = new_sl;
17213 /* connect new state to parentage chain. Current frame needs all
17214 * registers connected. Only r6 - r9 of the callers are alive (pushed
17215 * to the stack implicitly by JITs) so in callers' frames connect just
17216 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
17217 * the state of the call instruction (with WRITTEN set), and r0 comes
17218 * from callee with its full parentage chain, anyway.
17220 /* clear write marks in current state: the writes we did are not writes
17221 * our child did, so they don't screen off its reads from us.
17222 * (There are no read marks in current state, because reads always mark
17223 * their parent and current state never has children yet. Only
17224 * explored_states can get read marks.)
17226 for (j = 0; j <= cur->curframe; j++) {
17227 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
17228 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
17229 for (i = 0; i < BPF_REG_FP; i++)
17230 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
17233 /* all stack frames are accessible from callee, clear them all */
17234 for (j = 0; j <= cur->curframe; j++) {
17235 struct bpf_func_state *frame = cur->frame[j];
17236 struct bpf_func_state *newframe = new->frame[j];
17238 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
17239 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
17240 frame->stack[i].spilled_ptr.parent =
17241 &newframe->stack[i].spilled_ptr;
17247 /* Return true if it's OK to have the same insn return a different type. */
17248 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17250 switch (base_type(type)) {
17252 case PTR_TO_SOCKET:
17253 case PTR_TO_SOCK_COMMON:
17254 case PTR_TO_TCP_SOCK:
17255 case PTR_TO_XDP_SOCK:
17256 case PTR_TO_BTF_ID:
17263 /* If an instruction was previously used with particular pointer types, then we
17264 * need to be careful to avoid cases such as the below, where it may be ok
17265 * for one branch accessing the pointer, but not ok for the other branch:
17270 * R1 = some_other_valid_ptr;
17273 * R2 = *(u32 *)(R1 + 0);
17275 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17277 return src != prev && (!reg_type_mismatch_ok(src) ||
17278 !reg_type_mismatch_ok(prev));
17281 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17282 bool allow_trust_missmatch)
17284 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17286 if (*prev_type == NOT_INIT) {
17287 /* Saw a valid insn
17288 * dst_reg = *(u32 *)(src_reg + off)
17289 * save type to validate intersecting paths
17292 } else if (reg_type_mismatch(type, *prev_type)) {
17293 /* Abuser program is trying to use the same insn
17294 * dst_reg = *(u32*) (src_reg + off)
17295 * with different pointer types:
17296 * src_reg == ctx in one branch and
17297 * src_reg == stack|map in some other branch.
17300 if (allow_trust_missmatch &&
17301 base_type(type) == PTR_TO_BTF_ID &&
17302 base_type(*prev_type) == PTR_TO_BTF_ID) {
17304 * Have to support a use case when one path through
17305 * the program yields TRUSTED pointer while another
17306 * is UNTRUSTED. Fallback to UNTRUSTED to generate
17307 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17309 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17311 verbose(env, "same insn cannot be used with different pointers\n");
17319 static int do_check(struct bpf_verifier_env *env)
17321 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17322 struct bpf_verifier_state *state = env->cur_state;
17323 struct bpf_insn *insns = env->prog->insnsi;
17324 struct bpf_reg_state *regs;
17325 int insn_cnt = env->prog->len;
17326 bool do_print_state = false;
17327 int prev_insn_idx = -1;
17330 bool exception_exit = false;
17331 struct bpf_insn *insn;
17335 /* reset current history entry on each new instruction */
17336 env->cur_hist_ent = NULL;
17338 env->prev_insn_idx = prev_insn_idx;
17339 if (env->insn_idx >= insn_cnt) {
17340 verbose(env, "invalid insn idx %d insn_cnt %d\n",
17341 env->insn_idx, insn_cnt);
17345 insn = &insns[env->insn_idx];
17346 class = BPF_CLASS(insn->code);
17348 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17350 "BPF program is too large. Processed %d insn\n",
17351 env->insn_processed);
17355 state->last_insn_idx = env->prev_insn_idx;
17357 if (is_prune_point(env, env->insn_idx)) {
17358 err = is_state_visited(env, env->insn_idx);
17362 /* found equivalent state, can prune the search */
17363 if (env->log.level & BPF_LOG_LEVEL) {
17364 if (do_print_state)
17365 verbose(env, "\nfrom %d to %d%s: safe\n",
17366 env->prev_insn_idx, env->insn_idx,
17367 env->cur_state->speculative ?
17368 " (speculative execution)" : "");
17370 verbose(env, "%d: safe\n", env->insn_idx);
17372 goto process_bpf_exit;
17376 if (is_jmp_point(env, env->insn_idx)) {
17377 err = push_jmp_history(env, state, 0);
17382 if (signal_pending(current))
17385 if (need_resched())
17388 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17389 verbose(env, "\nfrom %d to %d%s:",
17390 env->prev_insn_idx, env->insn_idx,
17391 env->cur_state->speculative ?
17392 " (speculative execution)" : "");
17393 print_verifier_state(env, state->frame[state->curframe], true);
17394 do_print_state = false;
17397 if (env->log.level & BPF_LOG_LEVEL) {
17398 const struct bpf_insn_cbs cbs = {
17399 .cb_call = disasm_kfunc_name,
17400 .cb_print = verbose,
17401 .private_data = env,
17404 if (verifier_state_scratched(env))
17405 print_insn_state(env, state->frame[state->curframe]);
17407 verbose_linfo(env, env->insn_idx, "; ");
17408 env->prev_log_pos = env->log.end_pos;
17409 verbose(env, "%d: ", env->insn_idx);
17410 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17411 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17412 env->prev_log_pos = env->log.end_pos;
17415 if (bpf_prog_is_offloaded(env->prog->aux)) {
17416 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17417 env->prev_insn_idx);
17422 regs = cur_regs(env);
17423 sanitize_mark_insn_seen(env);
17424 prev_insn_idx = env->insn_idx;
17426 if (class == BPF_ALU || class == BPF_ALU64) {
17427 err = check_alu_op(env, insn);
17431 } else if (class == BPF_LDX) {
17432 enum bpf_reg_type src_reg_type;
17434 /* check for reserved fields is already done */
17436 /* check src operand */
17437 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17441 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17445 src_reg_type = regs[insn->src_reg].type;
17447 /* check that memory (src_reg + off) is readable,
17448 * the state of dst_reg will be updated by this func
17450 err = check_mem_access(env, env->insn_idx, insn->src_reg,
17451 insn->off, BPF_SIZE(insn->code),
17452 BPF_READ, insn->dst_reg, false,
17453 BPF_MODE(insn->code) == BPF_MEMSX);
17454 err = err ?: save_aux_ptr_type(env, src_reg_type, true);
17455 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx");
17458 } else if (class == BPF_STX) {
17459 enum bpf_reg_type dst_reg_type;
17461 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17462 err = check_atomic(env, env->insn_idx, insn);
17469 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17470 verbose(env, "BPF_STX uses reserved fields\n");
17474 /* check src1 operand */
17475 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17478 /* check src2 operand */
17479 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17483 dst_reg_type = regs[insn->dst_reg].type;
17485 /* check that memory (dst_reg + off) is writeable */
17486 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17487 insn->off, BPF_SIZE(insn->code),
17488 BPF_WRITE, insn->src_reg, false, false);
17492 err = save_aux_ptr_type(env, dst_reg_type, false);
17495 } else if (class == BPF_ST) {
17496 enum bpf_reg_type dst_reg_type;
17498 if (BPF_MODE(insn->code) != BPF_MEM ||
17499 insn->src_reg != BPF_REG_0) {
17500 verbose(env, "BPF_ST uses reserved fields\n");
17503 /* check src operand */
17504 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17508 dst_reg_type = regs[insn->dst_reg].type;
17510 /* check that memory (dst_reg + off) is writeable */
17511 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17512 insn->off, BPF_SIZE(insn->code),
17513 BPF_WRITE, -1, false, false);
17517 err = save_aux_ptr_type(env, dst_reg_type, false);
17520 } else if (class == BPF_JMP || class == BPF_JMP32) {
17521 u8 opcode = BPF_OP(insn->code);
17523 env->jmps_processed++;
17524 if (opcode == BPF_CALL) {
17525 if (BPF_SRC(insn->code) != BPF_K ||
17526 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17527 && insn->off != 0) ||
17528 (insn->src_reg != BPF_REG_0 &&
17529 insn->src_reg != BPF_PSEUDO_CALL &&
17530 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17531 insn->dst_reg != BPF_REG_0 ||
17532 class == BPF_JMP32) {
17533 verbose(env, "BPF_CALL uses reserved fields\n");
17537 if (env->cur_state->active_lock.ptr) {
17538 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17539 (insn->src_reg == BPF_PSEUDO_CALL) ||
17540 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17541 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17542 verbose(env, "function calls are not allowed while holding a lock\n");
17546 if (insn->src_reg == BPF_PSEUDO_CALL) {
17547 err = check_func_call(env, insn, &env->insn_idx);
17548 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17549 err = check_kfunc_call(env, insn, &env->insn_idx);
17550 if (!err && is_bpf_throw_kfunc(insn)) {
17551 exception_exit = true;
17552 goto process_bpf_exit_full;
17555 err = check_helper_call(env, insn, &env->insn_idx);
17560 mark_reg_scratched(env, BPF_REG_0);
17561 } else if (opcode == BPF_JA) {
17562 if (BPF_SRC(insn->code) != BPF_K ||
17563 insn->src_reg != BPF_REG_0 ||
17564 insn->dst_reg != BPF_REG_0 ||
17565 (class == BPF_JMP && insn->imm != 0) ||
17566 (class == BPF_JMP32 && insn->off != 0)) {
17567 verbose(env, "BPF_JA uses reserved fields\n");
17571 if (class == BPF_JMP)
17572 env->insn_idx += insn->off + 1;
17574 env->insn_idx += insn->imm + 1;
17577 } else if (opcode == BPF_EXIT) {
17578 if (BPF_SRC(insn->code) != BPF_K ||
17580 insn->src_reg != BPF_REG_0 ||
17581 insn->dst_reg != BPF_REG_0 ||
17582 class == BPF_JMP32) {
17583 verbose(env, "BPF_EXIT uses reserved fields\n");
17586 process_bpf_exit_full:
17587 if (env->cur_state->active_lock.ptr &&
17588 !in_rbtree_lock_required_cb(env)) {
17589 verbose(env, "bpf_spin_unlock is missing\n");
17593 if (env->cur_state->active_rcu_lock &&
17594 !in_rbtree_lock_required_cb(env)) {
17595 verbose(env, "bpf_rcu_read_unlock is missing\n");
17599 /* We must do check_reference_leak here before
17600 * prepare_func_exit to handle the case when
17601 * state->curframe > 0, it may be a callback
17602 * function, for which reference_state must
17603 * match caller reference state when it exits.
17605 err = check_reference_leak(env, exception_exit);
17609 /* The side effect of the prepare_func_exit
17610 * which is being skipped is that it frees
17611 * bpf_func_state. Typically, process_bpf_exit
17612 * will only be hit with outermost exit.
17613 * copy_verifier_state in pop_stack will handle
17614 * freeing of any extra bpf_func_state left over
17615 * from not processing all nested function
17616 * exits. We also skip return code checks as
17617 * they are not needed for exceptional exits.
17619 if (exception_exit)
17620 goto process_bpf_exit;
17622 if (state->curframe) {
17623 /* exit from nested function */
17624 err = prepare_func_exit(env, &env->insn_idx);
17627 do_print_state = true;
17631 err = check_return_code(env, BPF_REG_0, "R0");
17635 mark_verifier_state_scratched(env);
17636 update_branch_counts(env, env->cur_state);
17637 err = pop_stack(env, &prev_insn_idx,
17638 &env->insn_idx, pop_log);
17640 if (err != -ENOENT)
17644 do_print_state = true;
17648 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17652 } else if (class == BPF_LD) {
17653 u8 mode = BPF_MODE(insn->code);
17655 if (mode == BPF_ABS || mode == BPF_IND) {
17656 err = check_ld_abs(env, insn);
17660 } else if (mode == BPF_IMM) {
17661 err = check_ld_imm(env, insn);
17666 sanitize_mark_insn_seen(env);
17668 verbose(env, "invalid BPF_LD mode\n");
17672 verbose(env, "unknown insn class %d\n", class);
17682 static int find_btf_percpu_datasec(struct btf *btf)
17684 const struct btf_type *t;
17689 * Both vmlinux and module each have their own ".data..percpu"
17690 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17691 * types to look at only module's own BTF types.
17693 n = btf_nr_types(btf);
17694 if (btf_is_module(btf))
17695 i = btf_nr_types(btf_vmlinux);
17699 for(; i < n; i++) {
17700 t = btf_type_by_id(btf, i);
17701 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17704 tname = btf_name_by_offset(btf, t->name_off);
17705 if (!strcmp(tname, ".data..percpu"))
17712 /* replace pseudo btf_id with kernel symbol address */
17713 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17714 struct bpf_insn *insn,
17715 struct bpf_insn_aux_data *aux)
17717 const struct btf_var_secinfo *vsi;
17718 const struct btf_type *datasec;
17719 struct btf_mod_pair *btf_mod;
17720 const struct btf_type *t;
17721 const char *sym_name;
17722 bool percpu = false;
17723 u32 type, id = insn->imm;
17727 int i, btf_fd, err;
17729 btf_fd = insn[1].imm;
17731 btf = btf_get_by_fd(btf_fd);
17733 verbose(env, "invalid module BTF object FD specified.\n");
17737 if (!btf_vmlinux) {
17738 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17745 t = btf_type_by_id(btf, id);
17747 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17752 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17753 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17758 sym_name = btf_name_by_offset(btf, t->name_off);
17759 addr = kallsyms_lookup_name(sym_name);
17761 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17766 insn[0].imm = (u32)addr;
17767 insn[1].imm = addr >> 32;
17769 if (btf_type_is_func(t)) {
17770 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17771 aux->btf_var.mem_size = 0;
17775 datasec_id = find_btf_percpu_datasec(btf);
17776 if (datasec_id > 0) {
17777 datasec = btf_type_by_id(btf, datasec_id);
17778 for_each_vsi(i, datasec, vsi) {
17779 if (vsi->type == id) {
17787 t = btf_type_skip_modifiers(btf, type, NULL);
17789 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17790 aux->btf_var.btf = btf;
17791 aux->btf_var.btf_id = type;
17792 } else if (!btf_type_is_struct(t)) {
17793 const struct btf_type *ret;
17797 /* resolve the type size of ksym. */
17798 ret = btf_resolve_size(btf, t, &tsize);
17800 tname = btf_name_by_offset(btf, t->name_off);
17801 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17802 tname, PTR_ERR(ret));
17806 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17807 aux->btf_var.mem_size = tsize;
17809 aux->btf_var.reg_type = PTR_TO_BTF_ID;
17810 aux->btf_var.btf = btf;
17811 aux->btf_var.btf_id = type;
17814 /* check whether we recorded this BTF (and maybe module) already */
17815 for (i = 0; i < env->used_btf_cnt; i++) {
17816 if (env->used_btfs[i].btf == btf) {
17822 if (env->used_btf_cnt >= MAX_USED_BTFS) {
17827 btf_mod = &env->used_btfs[env->used_btf_cnt];
17828 btf_mod->btf = btf;
17829 btf_mod->module = NULL;
17831 /* if we reference variables from kernel module, bump its refcount */
17832 if (btf_is_module(btf)) {
17833 btf_mod->module = btf_try_get_module(btf);
17834 if (!btf_mod->module) {
17840 env->used_btf_cnt++;
17848 static bool is_tracing_prog_type(enum bpf_prog_type type)
17851 case BPF_PROG_TYPE_KPROBE:
17852 case BPF_PROG_TYPE_TRACEPOINT:
17853 case BPF_PROG_TYPE_PERF_EVENT:
17854 case BPF_PROG_TYPE_RAW_TRACEPOINT:
17855 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17862 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17863 struct bpf_map *map,
17864 struct bpf_prog *prog)
17867 enum bpf_prog_type prog_type = resolve_prog_type(prog);
17869 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17870 btf_record_has_field(map->record, BPF_RB_ROOT)) {
17871 if (is_tracing_prog_type(prog_type)) {
17872 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17877 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17878 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17879 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17883 if (is_tracing_prog_type(prog_type)) {
17884 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17889 if (btf_record_has_field(map->record, BPF_TIMER)) {
17890 if (is_tracing_prog_type(prog_type)) {
17891 verbose(env, "tracing progs cannot use bpf_timer yet\n");
17896 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17897 !bpf_offload_prog_map_match(prog, map)) {
17898 verbose(env, "offload device mismatch between prog and map\n");
17902 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17903 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17907 if (prog->aux->sleepable)
17908 switch (map->map_type) {
17909 case BPF_MAP_TYPE_HASH:
17910 case BPF_MAP_TYPE_LRU_HASH:
17911 case BPF_MAP_TYPE_ARRAY:
17912 case BPF_MAP_TYPE_PERCPU_HASH:
17913 case BPF_MAP_TYPE_PERCPU_ARRAY:
17914 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17915 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17916 case BPF_MAP_TYPE_HASH_OF_MAPS:
17917 case BPF_MAP_TYPE_RINGBUF:
17918 case BPF_MAP_TYPE_USER_RINGBUF:
17919 case BPF_MAP_TYPE_INODE_STORAGE:
17920 case BPF_MAP_TYPE_SK_STORAGE:
17921 case BPF_MAP_TYPE_TASK_STORAGE:
17922 case BPF_MAP_TYPE_CGRP_STORAGE:
17926 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17933 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17935 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17936 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17939 /* find and rewrite pseudo imm in ld_imm64 instructions:
17941 * 1. if it accesses map FD, replace it with actual map pointer.
17942 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17944 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17946 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17948 struct bpf_insn *insn = env->prog->insnsi;
17949 int insn_cnt = env->prog->len;
17952 err = bpf_prog_calc_tag(env->prog);
17956 for (i = 0; i < insn_cnt; i++, insn++) {
17957 if (BPF_CLASS(insn->code) == BPF_LDX &&
17958 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17960 verbose(env, "BPF_LDX uses reserved fields\n");
17964 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17965 struct bpf_insn_aux_data *aux;
17966 struct bpf_map *map;
17971 if (i == insn_cnt - 1 || insn[1].code != 0 ||
17972 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17973 insn[1].off != 0) {
17974 verbose(env, "invalid bpf_ld_imm64 insn\n");
17978 if (insn[0].src_reg == 0)
17979 /* valid generic load 64-bit imm */
17982 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17983 aux = &env->insn_aux_data[i];
17984 err = check_pseudo_btf_id(env, insn, aux);
17990 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17991 aux = &env->insn_aux_data[i];
17992 aux->ptr_type = PTR_TO_FUNC;
17996 /* In final convert_pseudo_ld_imm64() step, this is
17997 * converted into regular 64-bit imm load insn.
17999 switch (insn[0].src_reg) {
18000 case BPF_PSEUDO_MAP_VALUE:
18001 case BPF_PSEUDO_MAP_IDX_VALUE:
18003 case BPF_PSEUDO_MAP_FD:
18004 case BPF_PSEUDO_MAP_IDX:
18005 if (insn[1].imm == 0)
18009 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
18013 switch (insn[0].src_reg) {
18014 case BPF_PSEUDO_MAP_IDX_VALUE:
18015 case BPF_PSEUDO_MAP_IDX:
18016 if (bpfptr_is_null(env->fd_array)) {
18017 verbose(env, "fd_idx without fd_array is invalid\n");
18020 if (copy_from_bpfptr_offset(&fd, env->fd_array,
18021 insn[0].imm * sizeof(fd),
18031 map = __bpf_map_get(f);
18033 verbose(env, "fd %d is not pointing to valid bpf_map\n",
18035 return PTR_ERR(map);
18038 err = check_map_prog_compatibility(env, map, env->prog);
18044 aux = &env->insn_aux_data[i];
18045 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
18046 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
18047 addr = (unsigned long)map;
18049 u32 off = insn[1].imm;
18051 if (off >= BPF_MAX_VAR_OFF) {
18052 verbose(env, "direct value offset of %u is not allowed\n", off);
18057 if (!map->ops->map_direct_value_addr) {
18058 verbose(env, "no direct value access support for this map type\n");
18063 err = map->ops->map_direct_value_addr(map, &addr, off);
18065 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
18066 map->value_size, off);
18071 aux->map_off = off;
18075 insn[0].imm = (u32)addr;
18076 insn[1].imm = addr >> 32;
18078 /* check whether we recorded this map already */
18079 for (j = 0; j < env->used_map_cnt; j++) {
18080 if (env->used_maps[j] == map) {
18081 aux->map_index = j;
18087 if (env->used_map_cnt >= MAX_USED_MAPS) {
18092 if (env->prog->aux->sleepable)
18093 atomic64_inc(&map->sleepable_refcnt);
18094 /* hold the map. If the program is rejected by verifier,
18095 * the map will be released by release_maps() or it
18096 * will be used by the valid program until it's unloaded
18097 * and all maps are released in bpf_free_used_maps()
18101 aux->map_index = env->used_map_cnt;
18102 env->used_maps[env->used_map_cnt++] = map;
18104 if (bpf_map_is_cgroup_storage(map) &&
18105 bpf_cgroup_storage_assign(env->prog->aux, map)) {
18106 verbose(env, "only one cgroup storage of each type is allowed\n");
18118 /* Basic sanity check before we invest more work here. */
18119 if (!bpf_opcode_in_insntable(insn->code)) {
18120 verbose(env, "unknown opcode %02x\n", insn->code);
18125 /* now all pseudo BPF_LD_IMM64 instructions load valid
18126 * 'struct bpf_map *' into a register instead of user map_fd.
18127 * These pointers will be used later by verifier to validate map access.
18132 /* drop refcnt of maps used by the rejected program */
18133 static void release_maps(struct bpf_verifier_env *env)
18135 __bpf_free_used_maps(env->prog->aux, env->used_maps,
18136 env->used_map_cnt);
18139 /* drop refcnt of maps used by the rejected program */
18140 static void release_btfs(struct bpf_verifier_env *env)
18142 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
18143 env->used_btf_cnt);
18146 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
18147 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
18149 struct bpf_insn *insn = env->prog->insnsi;
18150 int insn_cnt = env->prog->len;
18153 for (i = 0; i < insn_cnt; i++, insn++) {
18154 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18156 if (insn->src_reg == BPF_PSEUDO_FUNC)
18162 /* single env->prog->insni[off] instruction was replaced with the range
18163 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
18164 * [0, off) and [off, end) to new locations, so the patched range stays zero
18166 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
18167 struct bpf_insn_aux_data *new_data,
18168 struct bpf_prog *new_prog, u32 off, u32 cnt)
18170 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
18171 struct bpf_insn *insn = new_prog->insnsi;
18172 u32 old_seen = old_data[off].seen;
18176 /* aux info at OFF always needs adjustment, no matter fast path
18177 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
18178 * original insn at old prog.
18180 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
18184 prog_len = new_prog->len;
18186 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
18187 memcpy(new_data + off + cnt - 1, old_data + off,
18188 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
18189 for (i = off; i < off + cnt - 1; i++) {
18190 /* Expand insni[off]'s seen count to the patched range. */
18191 new_data[i].seen = old_seen;
18192 new_data[i].zext_dst = insn_has_def32(env, insn + i);
18194 env->insn_aux_data = new_data;
18198 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
18204 /* NOTE: fake 'exit' subprog should be updated as well. */
18205 for (i = 0; i <= env->subprog_cnt; i++) {
18206 if (env->subprog_info[i].start <= off)
18208 env->subprog_info[i].start += len - 1;
18212 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
18214 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
18215 int i, sz = prog->aux->size_poke_tab;
18216 struct bpf_jit_poke_descriptor *desc;
18218 for (i = 0; i < sz; i++) {
18220 if (desc->insn_idx <= off)
18222 desc->insn_idx += len - 1;
18226 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
18227 const struct bpf_insn *patch, u32 len)
18229 struct bpf_prog *new_prog;
18230 struct bpf_insn_aux_data *new_data = NULL;
18233 new_data = vzalloc(array_size(env->prog->len + len - 1,
18234 sizeof(struct bpf_insn_aux_data)));
18239 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
18240 if (IS_ERR(new_prog)) {
18241 if (PTR_ERR(new_prog) == -ERANGE)
18243 "insn %d cannot be patched due to 16-bit range\n",
18244 env->insn_aux_data[off].orig_idx);
18248 adjust_insn_aux_data(env, new_data, new_prog, off, len);
18249 adjust_subprog_starts(env, off, len);
18250 adjust_poke_descs(new_prog, off, len);
18254 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
18259 /* find first prog starting at or after off (first to remove) */
18260 for (i = 0; i < env->subprog_cnt; i++)
18261 if (env->subprog_info[i].start >= off)
18263 /* find first prog starting at or after off + cnt (first to stay) */
18264 for (j = i; j < env->subprog_cnt; j++)
18265 if (env->subprog_info[j].start >= off + cnt)
18267 /* if j doesn't start exactly at off + cnt, we are just removing
18268 * the front of previous prog
18270 if (env->subprog_info[j].start != off + cnt)
18274 struct bpf_prog_aux *aux = env->prog->aux;
18277 /* move fake 'exit' subprog as well */
18278 move = env->subprog_cnt + 1 - j;
18280 memmove(env->subprog_info + i,
18281 env->subprog_info + j,
18282 sizeof(*env->subprog_info) * move);
18283 env->subprog_cnt -= j - i;
18285 /* remove func_info */
18286 if (aux->func_info) {
18287 move = aux->func_info_cnt - j;
18289 memmove(aux->func_info + i,
18290 aux->func_info + j,
18291 sizeof(*aux->func_info) * move);
18292 aux->func_info_cnt -= j - i;
18293 /* func_info->insn_off is set after all code rewrites,
18294 * in adjust_btf_func() - no need to adjust
18298 /* convert i from "first prog to remove" to "first to adjust" */
18299 if (env->subprog_info[i].start == off)
18303 /* update fake 'exit' subprog as well */
18304 for (; i <= env->subprog_cnt; i++)
18305 env->subprog_info[i].start -= cnt;
18310 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18313 struct bpf_prog *prog = env->prog;
18314 u32 i, l_off, l_cnt, nr_linfo;
18315 struct bpf_line_info *linfo;
18317 nr_linfo = prog->aux->nr_linfo;
18321 linfo = prog->aux->linfo;
18323 /* find first line info to remove, count lines to be removed */
18324 for (i = 0; i < nr_linfo; i++)
18325 if (linfo[i].insn_off >= off)
18330 for (; i < nr_linfo; i++)
18331 if (linfo[i].insn_off < off + cnt)
18336 /* First live insn doesn't match first live linfo, it needs to "inherit"
18337 * last removed linfo. prog is already modified, so prog->len == off
18338 * means no live instructions after (tail of the program was removed).
18340 if (prog->len != off && l_cnt &&
18341 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18343 linfo[--i].insn_off = off + cnt;
18346 /* remove the line info which refer to the removed instructions */
18348 memmove(linfo + l_off, linfo + i,
18349 sizeof(*linfo) * (nr_linfo - i));
18351 prog->aux->nr_linfo -= l_cnt;
18352 nr_linfo = prog->aux->nr_linfo;
18355 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
18356 for (i = l_off; i < nr_linfo; i++)
18357 linfo[i].insn_off -= cnt;
18359 /* fix up all subprogs (incl. 'exit') which start >= off */
18360 for (i = 0; i <= env->subprog_cnt; i++)
18361 if (env->subprog_info[i].linfo_idx > l_off) {
18362 /* program may have started in the removed region but
18363 * may not be fully removed
18365 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18366 env->subprog_info[i].linfo_idx -= l_cnt;
18368 env->subprog_info[i].linfo_idx = l_off;
18374 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18376 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18377 unsigned int orig_prog_len = env->prog->len;
18380 if (bpf_prog_is_offloaded(env->prog->aux))
18381 bpf_prog_offload_remove_insns(env, off, cnt);
18383 err = bpf_remove_insns(env->prog, off, cnt);
18387 err = adjust_subprog_starts_after_remove(env, off, cnt);
18391 err = bpf_adj_linfo_after_remove(env, off, cnt);
18395 memmove(aux_data + off, aux_data + off + cnt,
18396 sizeof(*aux_data) * (orig_prog_len - off - cnt));
18401 /* The verifier does more data flow analysis than llvm and will not
18402 * explore branches that are dead at run time. Malicious programs can
18403 * have dead code too. Therefore replace all dead at-run-time code
18406 * Just nops are not optimal, e.g. if they would sit at the end of the
18407 * program and through another bug we would manage to jump there, then
18408 * we'd execute beyond program memory otherwise. Returning exception
18409 * code also wouldn't work since we can have subprogs where the dead
18410 * code could be located.
18412 static void sanitize_dead_code(struct bpf_verifier_env *env)
18414 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18415 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18416 struct bpf_insn *insn = env->prog->insnsi;
18417 const int insn_cnt = env->prog->len;
18420 for (i = 0; i < insn_cnt; i++) {
18421 if (aux_data[i].seen)
18423 memcpy(insn + i, &trap, sizeof(trap));
18424 aux_data[i].zext_dst = false;
18428 static bool insn_is_cond_jump(u8 code)
18433 if (BPF_CLASS(code) == BPF_JMP32)
18434 return op != BPF_JA;
18436 if (BPF_CLASS(code) != BPF_JMP)
18439 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18442 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18444 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18445 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18446 struct bpf_insn *insn = env->prog->insnsi;
18447 const int insn_cnt = env->prog->len;
18450 for (i = 0; i < insn_cnt; i++, insn++) {
18451 if (!insn_is_cond_jump(insn->code))
18454 if (!aux_data[i + 1].seen)
18455 ja.off = insn->off;
18456 else if (!aux_data[i + 1 + insn->off].seen)
18461 if (bpf_prog_is_offloaded(env->prog->aux))
18462 bpf_prog_offload_replace_insn(env, i, &ja);
18464 memcpy(insn, &ja, sizeof(ja));
18468 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18470 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18471 int insn_cnt = env->prog->len;
18474 for (i = 0; i < insn_cnt; i++) {
18478 while (i + j < insn_cnt && !aux_data[i + j].seen)
18483 err = verifier_remove_insns(env, i, j);
18486 insn_cnt = env->prog->len;
18492 static int opt_remove_nops(struct bpf_verifier_env *env)
18494 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18495 struct bpf_insn *insn = env->prog->insnsi;
18496 int insn_cnt = env->prog->len;
18499 for (i = 0; i < insn_cnt; i++) {
18500 if (memcmp(&insn[i], &ja, sizeof(ja)))
18503 err = verifier_remove_insns(env, i, 1);
18513 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18514 const union bpf_attr *attr)
18516 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18517 struct bpf_insn_aux_data *aux = env->insn_aux_data;
18518 int i, patch_len, delta = 0, len = env->prog->len;
18519 struct bpf_insn *insns = env->prog->insnsi;
18520 struct bpf_prog *new_prog;
18523 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18524 zext_patch[1] = BPF_ZEXT_REG(0);
18525 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18526 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18527 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18528 for (i = 0; i < len; i++) {
18529 int adj_idx = i + delta;
18530 struct bpf_insn insn;
18533 insn = insns[adj_idx];
18534 load_reg = insn_def_regno(&insn);
18535 if (!aux[adj_idx].zext_dst) {
18543 class = BPF_CLASS(code);
18544 if (load_reg == -1)
18547 /* NOTE: arg "reg" (the fourth one) is only used for
18548 * BPF_STX + SRC_OP, so it is safe to pass NULL
18551 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18552 if (class == BPF_LD &&
18553 BPF_MODE(code) == BPF_IMM)
18558 /* ctx load could be transformed into wider load. */
18559 if (class == BPF_LDX &&
18560 aux[adj_idx].ptr_type == PTR_TO_CTX)
18563 imm_rnd = get_random_u32();
18564 rnd_hi32_patch[0] = insn;
18565 rnd_hi32_patch[1].imm = imm_rnd;
18566 rnd_hi32_patch[3].dst_reg = load_reg;
18567 patch = rnd_hi32_patch;
18569 goto apply_patch_buffer;
18572 /* Add in an zero-extend instruction if a) the JIT has requested
18573 * it or b) it's a CMPXCHG.
18575 * The latter is because: BPF_CMPXCHG always loads a value into
18576 * R0, therefore always zero-extends. However some archs'
18577 * equivalent instruction only does this load when the
18578 * comparison is successful. This detail of CMPXCHG is
18579 * orthogonal to the general zero-extension behaviour of the
18580 * CPU, so it's treated independently of bpf_jit_needs_zext.
18582 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18585 /* Zero-extension is done by the caller. */
18586 if (bpf_pseudo_kfunc_call(&insn))
18589 if (WARN_ON(load_reg == -1)) {
18590 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18594 zext_patch[0] = insn;
18595 zext_patch[1].dst_reg = load_reg;
18596 zext_patch[1].src_reg = load_reg;
18597 patch = zext_patch;
18599 apply_patch_buffer:
18600 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18603 env->prog = new_prog;
18604 insns = new_prog->insnsi;
18605 aux = env->insn_aux_data;
18606 delta += patch_len - 1;
18612 /* convert load instructions that access fields of a context type into a
18613 * sequence of instructions that access fields of the underlying structure:
18614 * struct __sk_buff -> struct sk_buff
18615 * struct bpf_sock_ops -> struct sock
18617 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18619 const struct bpf_verifier_ops *ops = env->ops;
18620 int i, cnt, size, ctx_field_size, delta = 0;
18621 const int insn_cnt = env->prog->len;
18622 struct bpf_insn insn_buf[16], *insn;
18623 u32 target_size, size_default, off;
18624 struct bpf_prog *new_prog;
18625 enum bpf_access_type type;
18626 bool is_narrower_load;
18628 if (ops->gen_prologue || env->seen_direct_write) {
18629 if (!ops->gen_prologue) {
18630 verbose(env, "bpf verifier is misconfigured\n");
18633 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18635 if (cnt >= ARRAY_SIZE(insn_buf)) {
18636 verbose(env, "bpf verifier is misconfigured\n");
18639 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18643 env->prog = new_prog;
18648 if (bpf_prog_is_offloaded(env->prog->aux))
18651 insn = env->prog->insnsi + delta;
18653 for (i = 0; i < insn_cnt; i++, insn++) {
18654 bpf_convert_ctx_access_t convert_ctx_access;
18657 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18658 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18659 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18660 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18661 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18662 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18663 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18665 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18666 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18667 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18668 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18669 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18670 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18671 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18672 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18678 if (type == BPF_WRITE &&
18679 env->insn_aux_data[i + delta].sanitize_stack_spill) {
18680 struct bpf_insn patch[] = {
18685 cnt = ARRAY_SIZE(patch);
18686 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18691 env->prog = new_prog;
18692 insn = new_prog->insnsi + i + delta;
18696 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18698 if (!ops->convert_ctx_access)
18700 convert_ctx_access = ops->convert_ctx_access;
18702 case PTR_TO_SOCKET:
18703 case PTR_TO_SOCK_COMMON:
18704 convert_ctx_access = bpf_sock_convert_ctx_access;
18706 case PTR_TO_TCP_SOCK:
18707 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18709 case PTR_TO_XDP_SOCK:
18710 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18712 case PTR_TO_BTF_ID:
18713 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18714 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18715 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18716 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18717 * any faults for loads into such types. BPF_WRITE is disallowed
18720 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18721 if (type == BPF_READ) {
18722 if (BPF_MODE(insn->code) == BPF_MEM)
18723 insn->code = BPF_LDX | BPF_PROBE_MEM |
18724 BPF_SIZE((insn)->code);
18726 insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18727 BPF_SIZE((insn)->code);
18728 env->prog->aux->num_exentries++;
18735 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18736 size = BPF_LDST_BYTES(insn);
18737 mode = BPF_MODE(insn->code);
18739 /* If the read access is a narrower load of the field,
18740 * convert to a 4/8-byte load, to minimum program type specific
18741 * convert_ctx_access changes. If conversion is successful,
18742 * we will apply proper mask to the result.
18744 is_narrower_load = size < ctx_field_size;
18745 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18747 if (is_narrower_load) {
18750 if (type == BPF_WRITE) {
18751 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18756 if (ctx_field_size == 4)
18758 else if (ctx_field_size == 8)
18759 size_code = BPF_DW;
18761 insn->off = off & ~(size_default - 1);
18762 insn->code = BPF_LDX | BPF_MEM | size_code;
18766 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18768 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18769 (ctx_field_size && !target_size)) {
18770 verbose(env, "bpf verifier is misconfigured\n");
18774 if (is_narrower_load && size < target_size) {
18775 u8 shift = bpf_ctx_narrow_access_offset(
18776 off, size, size_default) * 8;
18777 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18778 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18781 if (ctx_field_size <= 4) {
18783 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18786 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18787 (1 << size * 8) - 1);
18790 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18793 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18794 (1ULL << size * 8) - 1);
18797 if (mode == BPF_MEMSX)
18798 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18799 insn->dst_reg, insn->dst_reg,
18802 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18808 /* keep walking new program and skip insns we just inserted */
18809 env->prog = new_prog;
18810 insn = new_prog->insnsi + i + delta;
18816 static int jit_subprogs(struct bpf_verifier_env *env)
18818 struct bpf_prog *prog = env->prog, **func, *tmp;
18819 int i, j, subprog_start, subprog_end = 0, len, subprog;
18820 struct bpf_map *map_ptr;
18821 struct bpf_insn *insn;
18822 void *old_bpf_func;
18823 int err, num_exentries;
18825 if (env->subprog_cnt <= 1)
18828 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18829 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18832 /* Upon error here we cannot fall back to interpreter but
18833 * need a hard reject of the program. Thus -EFAULT is
18834 * propagated in any case.
18836 subprog = find_subprog(env, i + insn->imm + 1);
18838 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18839 i + insn->imm + 1);
18842 /* temporarily remember subprog id inside insn instead of
18843 * aux_data, since next loop will split up all insns into funcs
18845 insn->off = subprog;
18846 /* remember original imm in case JIT fails and fallback
18847 * to interpreter will be needed
18849 env->insn_aux_data[i].call_imm = insn->imm;
18850 /* point imm to __bpf_call_base+1 from JITs point of view */
18852 if (bpf_pseudo_func(insn))
18853 /* jit (e.g. x86_64) may emit fewer instructions
18854 * if it learns a u32 imm is the same as a u64 imm.
18855 * Force a non zero here.
18860 err = bpf_prog_alloc_jited_linfo(prog);
18862 goto out_undo_insn;
18865 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18867 goto out_undo_insn;
18869 for (i = 0; i < env->subprog_cnt; i++) {
18870 subprog_start = subprog_end;
18871 subprog_end = env->subprog_info[i + 1].start;
18873 len = subprog_end - subprog_start;
18874 /* bpf_prog_run() doesn't call subprogs directly,
18875 * hence main prog stats include the runtime of subprogs.
18876 * subprogs don't have IDs and not reachable via prog_get_next_id
18877 * func[i]->stats will never be accessed and stays NULL
18879 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18882 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18883 len * sizeof(struct bpf_insn));
18884 func[i]->type = prog->type;
18885 func[i]->len = len;
18886 if (bpf_prog_calc_tag(func[i]))
18888 func[i]->is_func = 1;
18889 func[i]->aux->func_idx = i;
18890 /* Below members will be freed only at prog->aux */
18891 func[i]->aux->btf = prog->aux->btf;
18892 func[i]->aux->func_info = prog->aux->func_info;
18893 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18894 func[i]->aux->poke_tab = prog->aux->poke_tab;
18895 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18897 for (j = 0; j < prog->aux->size_poke_tab; j++) {
18898 struct bpf_jit_poke_descriptor *poke;
18900 poke = &prog->aux->poke_tab[j];
18901 if (poke->insn_idx < subprog_end &&
18902 poke->insn_idx >= subprog_start)
18903 poke->aux = func[i]->aux;
18906 func[i]->aux->name[0] = 'F';
18907 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18908 func[i]->jit_requested = 1;
18909 func[i]->blinding_requested = prog->blinding_requested;
18910 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18911 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18912 func[i]->aux->linfo = prog->aux->linfo;
18913 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18914 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18915 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18917 insn = func[i]->insnsi;
18918 for (j = 0; j < func[i]->len; j++, insn++) {
18919 if (BPF_CLASS(insn->code) == BPF_LDX &&
18920 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18921 BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18924 func[i]->aux->num_exentries = num_exentries;
18925 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18926 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
18928 func[i]->aux->exception_boundary = env->seen_exception;
18929 func[i] = bpf_int_jit_compile(func[i]);
18930 if (!func[i]->jited) {
18937 /* at this point all bpf functions were successfully JITed
18938 * now populate all bpf_calls with correct addresses and
18939 * run last pass of JIT
18941 for (i = 0; i < env->subprog_cnt; i++) {
18942 insn = func[i]->insnsi;
18943 for (j = 0; j < func[i]->len; j++, insn++) {
18944 if (bpf_pseudo_func(insn)) {
18945 subprog = insn->off;
18946 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18947 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18950 if (!bpf_pseudo_call(insn))
18952 subprog = insn->off;
18953 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18956 /* we use the aux data to keep a list of the start addresses
18957 * of the JITed images for each function in the program
18959 * for some architectures, such as powerpc64, the imm field
18960 * might not be large enough to hold the offset of the start
18961 * address of the callee's JITed image from __bpf_call_base
18963 * in such cases, we can lookup the start address of a callee
18964 * by using its subprog id, available from the off field of
18965 * the call instruction, as an index for this list
18967 func[i]->aux->func = func;
18968 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
18969 func[i]->aux->real_func_cnt = env->subprog_cnt;
18971 for (i = 0; i < env->subprog_cnt; i++) {
18972 old_bpf_func = func[i]->bpf_func;
18973 tmp = bpf_int_jit_compile(func[i]);
18974 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18975 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18982 /* finally lock prog and jit images for all functions and
18983 * populate kallsysm. Begin at the first subprogram, since
18984 * bpf_prog_load will add the kallsyms for the main program.
18986 for (i = 1; i < env->subprog_cnt; i++) {
18987 bpf_prog_lock_ro(func[i]);
18988 bpf_prog_kallsyms_add(func[i]);
18991 /* Last step: make now unused interpreter insns from main
18992 * prog consistent for later dump requests, so they can
18993 * later look the same as if they were interpreted only.
18995 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18996 if (bpf_pseudo_func(insn)) {
18997 insn[0].imm = env->insn_aux_data[i].call_imm;
18998 insn[1].imm = insn->off;
19002 if (!bpf_pseudo_call(insn))
19004 insn->off = env->insn_aux_data[i].call_imm;
19005 subprog = find_subprog(env, i + insn->off + 1);
19006 insn->imm = subprog;
19010 prog->bpf_func = func[0]->bpf_func;
19011 prog->jited_len = func[0]->jited_len;
19012 prog->aux->extable = func[0]->aux->extable;
19013 prog->aux->num_exentries = func[0]->aux->num_exentries;
19014 prog->aux->func = func;
19015 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19016 prog->aux->real_func_cnt = env->subprog_cnt;
19017 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
19018 prog->aux->exception_boundary = func[0]->aux->exception_boundary;
19019 bpf_prog_jit_attempt_done(prog);
19022 /* We failed JIT'ing, so at this point we need to unregister poke
19023 * descriptors from subprogs, so that kernel is not attempting to
19024 * patch it anymore as we're freeing the subprog JIT memory.
19026 for (i = 0; i < prog->aux->size_poke_tab; i++) {
19027 map_ptr = prog->aux->poke_tab[i].tail_call.map;
19028 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
19030 /* At this point we're guaranteed that poke descriptors are not
19031 * live anymore. We can just unlink its descriptor table as it's
19032 * released with the main prog.
19034 for (i = 0; i < env->subprog_cnt; i++) {
19037 func[i]->aux->poke_tab = NULL;
19038 bpf_jit_free(func[i]);
19042 /* cleanup main prog to be interpreted */
19043 prog->jit_requested = 0;
19044 prog->blinding_requested = 0;
19045 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19046 if (!bpf_pseudo_call(insn))
19049 insn->imm = env->insn_aux_data[i].call_imm;
19051 bpf_prog_jit_attempt_done(prog);
19055 static int fixup_call_args(struct bpf_verifier_env *env)
19057 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19058 struct bpf_prog *prog = env->prog;
19059 struct bpf_insn *insn = prog->insnsi;
19060 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
19065 if (env->prog->jit_requested &&
19066 !bpf_prog_is_offloaded(env->prog->aux)) {
19067 err = jit_subprogs(env);
19070 if (err == -EFAULT)
19073 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19074 if (has_kfunc_call) {
19075 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
19078 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
19079 /* When JIT fails the progs with bpf2bpf calls and tail_calls
19080 * have to be rejected, since interpreter doesn't support them yet.
19082 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
19085 for (i = 0; i < prog->len; i++, insn++) {
19086 if (bpf_pseudo_func(insn)) {
19087 /* When JIT fails the progs with callback calls
19088 * have to be rejected, since interpreter doesn't support them yet.
19090 verbose(env, "callbacks are not allowed in non-JITed programs\n");
19094 if (!bpf_pseudo_call(insn))
19096 depth = get_callee_stack_depth(env, insn, i);
19099 bpf_patch_call_args(insn, depth);
19106 /* replace a generic kfunc with a specialized version if necessary */
19107 static void specialize_kfunc(struct bpf_verifier_env *env,
19108 u32 func_id, u16 offset, unsigned long *addr)
19110 struct bpf_prog *prog = env->prog;
19111 bool seen_direct_write;
19115 if (bpf_dev_bound_kfunc_id(func_id)) {
19116 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19118 *addr = (unsigned long)xdp_kfunc;
19121 /* fallback to default kfunc when not supported by netdev */
19127 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19128 seen_direct_write = env->seen_direct_write;
19129 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19132 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19134 /* restore env->seen_direct_write to its original value, since
19135 * may_access_direct_pkt_data mutates it
19137 env->seen_direct_write = seen_direct_write;
19141 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19142 u16 struct_meta_reg,
19143 u16 node_offset_reg,
19144 struct bpf_insn *insn,
19145 struct bpf_insn *insn_buf,
19148 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19149 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19151 insn_buf[0] = addr[0];
19152 insn_buf[1] = addr[1];
19153 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19154 insn_buf[3] = *insn;
19158 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19159 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
19161 const struct bpf_kfunc_desc *desc;
19164 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19170 /* insn->imm has the btf func_id. Replace it with an offset relative to
19171 * __bpf_call_base, unless the JIT needs to call functions that are
19172 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
19174 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
19176 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
19181 if (!bpf_jit_supports_far_kfunc_call())
19182 insn->imm = BPF_CALL_IMM(desc->addr);
19185 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
19186 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
19187 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19188 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19189 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
19191 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
19192 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19197 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19198 insn_buf[1] = addr[0];
19199 insn_buf[2] = addr[1];
19200 insn_buf[3] = *insn;
19202 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
19203 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
19204 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
19205 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19206 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19208 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
19209 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19214 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
19215 !kptr_struct_meta) {
19216 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19221 insn_buf[0] = addr[0];
19222 insn_buf[1] = addr[1];
19223 insn_buf[2] = *insn;
19225 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
19226 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
19227 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19228 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19229 int struct_meta_reg = BPF_REG_3;
19230 int node_offset_reg = BPF_REG_4;
19232 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
19233 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19234 struct_meta_reg = BPF_REG_4;
19235 node_offset_reg = BPF_REG_5;
19238 if (!kptr_struct_meta) {
19239 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19244 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19245 node_offset_reg, insn, insn_buf, cnt);
19246 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19247 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19248 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19254 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
19255 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
19257 struct bpf_subprog_info *info = env->subprog_info;
19258 int cnt = env->subprog_cnt;
19259 struct bpf_prog *prog;
19261 /* We only reserve one slot for hidden subprogs in subprog_info. */
19262 if (env->hidden_subprog_cnt) {
19263 verbose(env, "verifier internal error: only one hidden subprog supported\n");
19266 /* We're not patching any existing instruction, just appending the new
19267 * ones for the hidden subprog. Hence all of the adjustment operations
19268 * in bpf_patch_insn_data are no-ops.
19270 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
19274 info[cnt + 1].start = info[cnt].start;
19275 info[cnt].start = prog->len - len + 1;
19276 env->subprog_cnt++;
19277 env->hidden_subprog_cnt++;
19281 /* Do various post-verification rewrites in a single program pass.
19282 * These rewrites simplify JIT and interpreter implementations.
19284 static int do_misc_fixups(struct bpf_verifier_env *env)
19286 struct bpf_prog *prog = env->prog;
19287 enum bpf_attach_type eatype = prog->expected_attach_type;
19288 enum bpf_prog_type prog_type = resolve_prog_type(prog);
19289 struct bpf_insn *insn = prog->insnsi;
19290 const struct bpf_func_proto *fn;
19291 const int insn_cnt = prog->len;
19292 const struct bpf_map_ops *ops;
19293 struct bpf_insn_aux_data *aux;
19294 struct bpf_insn insn_buf[16];
19295 struct bpf_prog *new_prog;
19296 struct bpf_map *map_ptr;
19297 int i, ret, cnt, delta = 0;
19299 if (env->seen_exception && !env->exception_callback_subprog) {
19300 struct bpf_insn patch[] = {
19301 env->prog->insnsi[insn_cnt - 1],
19302 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
19306 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
19310 insn = prog->insnsi;
19312 env->exception_callback_subprog = env->subprog_cnt - 1;
19313 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */
19314 mark_subprog_exc_cb(env, env->exception_callback_subprog);
19317 for (i = 0; i < insn_cnt; i++, insn++) {
19318 /* Make divide-by-zero exceptions impossible. */
19319 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
19320 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
19321 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
19322 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
19323 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
19324 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
19325 struct bpf_insn *patchlet;
19326 struct bpf_insn chk_and_div[] = {
19327 /* [R,W]x div 0 -> 0 */
19328 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19329 BPF_JNE | BPF_K, insn->src_reg,
19331 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
19332 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19335 struct bpf_insn chk_and_mod[] = {
19336 /* [R,W]x mod 0 -> [R,W]x */
19337 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19338 BPF_JEQ | BPF_K, insn->src_reg,
19339 0, 1 + (is64 ? 0 : 1), 0),
19341 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19342 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
19345 patchlet = isdiv ? chk_and_div : chk_and_mod;
19346 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
19347 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
19349 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
19354 env->prog = prog = new_prog;
19355 insn = new_prog->insnsi + i + delta;
19359 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
19360 if (BPF_CLASS(insn->code) == BPF_LD &&
19361 (BPF_MODE(insn->code) == BPF_ABS ||
19362 BPF_MODE(insn->code) == BPF_IND)) {
19363 cnt = env->ops->gen_ld_abs(insn, insn_buf);
19364 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19365 verbose(env, "bpf verifier is misconfigured\n");
19369 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19374 env->prog = prog = new_prog;
19375 insn = new_prog->insnsi + i + delta;
19379 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
19380 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
19381 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
19382 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
19383 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
19384 struct bpf_insn *patch = &insn_buf[0];
19385 bool issrc, isneg, isimm;
19388 aux = &env->insn_aux_data[i + delta];
19389 if (!aux->alu_state ||
19390 aux->alu_state == BPF_ALU_NON_POINTER)
19393 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
19394 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
19395 BPF_ALU_SANITIZE_SRC;
19396 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
19398 off_reg = issrc ? insn->src_reg : insn->dst_reg;
19400 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19403 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19404 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19405 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
19406 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
19407 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
19408 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
19409 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
19412 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
19413 insn->src_reg = BPF_REG_AX;
19415 insn->code = insn->code == code_add ?
19416 code_sub : code_add;
19418 if (issrc && isneg && !isimm)
19419 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19420 cnt = patch - insn_buf;
19422 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19427 env->prog = prog = new_prog;
19428 insn = new_prog->insnsi + i + delta;
19432 if (insn->code != (BPF_JMP | BPF_CALL))
19434 if (insn->src_reg == BPF_PSEUDO_CALL)
19436 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19437 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19443 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19448 env->prog = prog = new_prog;
19449 insn = new_prog->insnsi + i + delta;
19453 if (insn->imm == BPF_FUNC_get_route_realm)
19454 prog->dst_needed = 1;
19455 if (insn->imm == BPF_FUNC_get_prandom_u32)
19456 bpf_user_rnd_init_once();
19457 if (insn->imm == BPF_FUNC_override_return)
19458 prog->kprobe_override = 1;
19459 if (insn->imm == BPF_FUNC_tail_call) {
19460 /* If we tail call into other programs, we
19461 * cannot make any assumptions since they can
19462 * be replaced dynamically during runtime in
19463 * the program array.
19465 prog->cb_access = 1;
19466 if (!allow_tail_call_in_subprogs(env))
19467 prog->aux->stack_depth = MAX_BPF_STACK;
19468 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19470 /* mark bpf_tail_call as different opcode to avoid
19471 * conditional branch in the interpreter for every normal
19472 * call and to prevent accidental JITing by JIT compiler
19473 * that doesn't support bpf_tail_call yet
19476 insn->code = BPF_JMP | BPF_TAIL_CALL;
19478 aux = &env->insn_aux_data[i + delta];
19479 if (env->bpf_capable && !prog->blinding_requested &&
19480 prog->jit_requested &&
19481 !bpf_map_key_poisoned(aux) &&
19482 !bpf_map_ptr_poisoned(aux) &&
19483 !bpf_map_ptr_unpriv(aux)) {
19484 struct bpf_jit_poke_descriptor desc = {
19485 .reason = BPF_POKE_REASON_TAIL_CALL,
19486 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19487 .tail_call.key = bpf_map_key_immediate(aux),
19488 .insn_idx = i + delta,
19491 ret = bpf_jit_add_poke_descriptor(prog, &desc);
19493 verbose(env, "adding tail call poke descriptor failed\n");
19497 insn->imm = ret + 1;
19501 if (!bpf_map_ptr_unpriv(aux))
19504 /* instead of changing every JIT dealing with tail_call
19505 * emit two extra insns:
19506 * if (index >= max_entries) goto out;
19507 * index &= array->index_mask;
19508 * to avoid out-of-bounds cpu speculation
19510 if (bpf_map_ptr_poisoned(aux)) {
19511 verbose(env, "tail_call abusing map_ptr\n");
19515 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19516 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19517 map_ptr->max_entries, 2);
19518 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19519 container_of(map_ptr,
19522 insn_buf[2] = *insn;
19524 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19529 env->prog = prog = new_prog;
19530 insn = new_prog->insnsi + i + delta;
19534 if (insn->imm == BPF_FUNC_timer_set_callback) {
19535 /* The verifier will process callback_fn as many times as necessary
19536 * with different maps and the register states prepared by
19537 * set_timer_callback_state will be accurate.
19539 * The following use case is valid:
19540 * map1 is shared by prog1, prog2, prog3.
19541 * prog1 calls bpf_timer_init for some map1 elements
19542 * prog2 calls bpf_timer_set_callback for some map1 elements.
19543 * Those that were not bpf_timer_init-ed will return -EINVAL.
19544 * prog3 calls bpf_timer_start for some map1 elements.
19545 * Those that were not both bpf_timer_init-ed and
19546 * bpf_timer_set_callback-ed will return -EINVAL.
19548 struct bpf_insn ld_addrs[2] = {
19549 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19552 insn_buf[0] = ld_addrs[0];
19553 insn_buf[1] = ld_addrs[1];
19554 insn_buf[2] = *insn;
19557 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19562 env->prog = prog = new_prog;
19563 insn = new_prog->insnsi + i + delta;
19564 goto patch_call_imm;
19567 if (is_storage_get_function(insn->imm)) {
19568 if (!env->prog->aux->sleepable ||
19569 env->insn_aux_data[i + delta].storage_get_func_atomic)
19570 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19572 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19573 insn_buf[1] = *insn;
19576 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19581 env->prog = prog = new_prog;
19582 insn = new_prog->insnsi + i + delta;
19583 goto patch_call_imm;
19586 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
19587 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
19588 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
19589 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
19591 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
19592 insn_buf[1] = *insn;
19595 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19600 env->prog = prog = new_prog;
19601 insn = new_prog->insnsi + i + delta;
19602 goto patch_call_imm;
19605 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19606 * and other inlining handlers are currently limited to 64 bit
19609 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19610 (insn->imm == BPF_FUNC_map_lookup_elem ||
19611 insn->imm == BPF_FUNC_map_update_elem ||
19612 insn->imm == BPF_FUNC_map_delete_elem ||
19613 insn->imm == BPF_FUNC_map_push_elem ||
19614 insn->imm == BPF_FUNC_map_pop_elem ||
19615 insn->imm == BPF_FUNC_map_peek_elem ||
19616 insn->imm == BPF_FUNC_redirect_map ||
19617 insn->imm == BPF_FUNC_for_each_map_elem ||
19618 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19619 aux = &env->insn_aux_data[i + delta];
19620 if (bpf_map_ptr_poisoned(aux))
19621 goto patch_call_imm;
19623 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19624 ops = map_ptr->ops;
19625 if (insn->imm == BPF_FUNC_map_lookup_elem &&
19626 ops->map_gen_lookup) {
19627 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19628 if (cnt == -EOPNOTSUPP)
19629 goto patch_map_ops_generic;
19630 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19631 verbose(env, "bpf verifier is misconfigured\n");
19635 new_prog = bpf_patch_insn_data(env, i + delta,
19641 env->prog = prog = new_prog;
19642 insn = new_prog->insnsi + i + delta;
19646 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19647 (void *(*)(struct bpf_map *map, void *key))NULL));
19648 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19649 (long (*)(struct bpf_map *map, void *key))NULL));
19650 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19651 (long (*)(struct bpf_map *map, void *key, void *value,
19653 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19654 (long (*)(struct bpf_map *map, void *value,
19656 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19657 (long (*)(struct bpf_map *map, void *value))NULL));
19658 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19659 (long (*)(struct bpf_map *map, void *value))NULL));
19660 BUILD_BUG_ON(!__same_type(ops->map_redirect,
19661 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19662 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19663 (long (*)(struct bpf_map *map,
19664 bpf_callback_t callback_fn,
19665 void *callback_ctx,
19667 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19668 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19670 patch_map_ops_generic:
19671 switch (insn->imm) {
19672 case BPF_FUNC_map_lookup_elem:
19673 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19675 case BPF_FUNC_map_update_elem:
19676 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19678 case BPF_FUNC_map_delete_elem:
19679 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19681 case BPF_FUNC_map_push_elem:
19682 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19684 case BPF_FUNC_map_pop_elem:
19685 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19687 case BPF_FUNC_map_peek_elem:
19688 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19690 case BPF_FUNC_redirect_map:
19691 insn->imm = BPF_CALL_IMM(ops->map_redirect);
19693 case BPF_FUNC_for_each_map_elem:
19694 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19696 case BPF_FUNC_map_lookup_percpu_elem:
19697 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19701 goto patch_call_imm;
19704 /* Implement bpf_jiffies64 inline. */
19705 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19706 insn->imm == BPF_FUNC_jiffies64) {
19707 struct bpf_insn ld_jiffies_addr[2] = {
19708 BPF_LD_IMM64(BPF_REG_0,
19709 (unsigned long)&jiffies),
19712 insn_buf[0] = ld_jiffies_addr[0];
19713 insn_buf[1] = ld_jiffies_addr[1];
19714 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19718 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19724 env->prog = prog = new_prog;
19725 insn = new_prog->insnsi + i + delta;
19729 /* Implement bpf_get_func_arg inline. */
19730 if (prog_type == BPF_PROG_TYPE_TRACING &&
19731 insn->imm == BPF_FUNC_get_func_arg) {
19732 /* Load nr_args from ctx - 8 */
19733 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19734 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19735 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19736 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19737 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19738 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19739 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19740 insn_buf[7] = BPF_JMP_A(1);
19741 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19744 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19749 env->prog = prog = new_prog;
19750 insn = new_prog->insnsi + i + delta;
19754 /* Implement bpf_get_func_ret inline. */
19755 if (prog_type == BPF_PROG_TYPE_TRACING &&
19756 insn->imm == BPF_FUNC_get_func_ret) {
19757 if (eatype == BPF_TRACE_FEXIT ||
19758 eatype == BPF_MODIFY_RETURN) {
19759 /* Load nr_args from ctx - 8 */
19760 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19761 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19762 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19763 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19764 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19765 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19768 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19772 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19777 env->prog = prog = new_prog;
19778 insn = new_prog->insnsi + i + delta;
19782 /* Implement get_func_arg_cnt inline. */
19783 if (prog_type == BPF_PROG_TYPE_TRACING &&
19784 insn->imm == BPF_FUNC_get_func_arg_cnt) {
19785 /* Load nr_args from ctx - 8 */
19786 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19788 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19792 env->prog = prog = new_prog;
19793 insn = new_prog->insnsi + i + delta;
19797 /* Implement bpf_get_func_ip inline. */
19798 if (prog_type == BPF_PROG_TYPE_TRACING &&
19799 insn->imm == BPF_FUNC_get_func_ip) {
19800 /* Load IP address from ctx - 16 */
19801 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19803 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19807 env->prog = prog = new_prog;
19808 insn = new_prog->insnsi + i + delta;
19813 fn = env->ops->get_func_proto(insn->imm, env->prog);
19814 /* all functions that have prototype and verifier allowed
19815 * programs to call them, must be real in-kernel functions
19819 "kernel subsystem misconfigured func %s#%d\n",
19820 func_id_name(insn->imm), insn->imm);
19823 insn->imm = fn->func - __bpf_call_base;
19826 /* Since poke tab is now finalized, publish aux to tracker. */
19827 for (i = 0; i < prog->aux->size_poke_tab; i++) {
19828 map_ptr = prog->aux->poke_tab[i].tail_call.map;
19829 if (!map_ptr->ops->map_poke_track ||
19830 !map_ptr->ops->map_poke_untrack ||
19831 !map_ptr->ops->map_poke_run) {
19832 verbose(env, "bpf verifier is misconfigured\n");
19836 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19838 verbose(env, "tracking tail call prog failed\n");
19843 sort_kfunc_descs_by_imm_off(env->prog);
19848 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19851 u32 callback_subprogno,
19854 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19855 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19856 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19857 int reg_loop_max = BPF_REG_6;
19858 int reg_loop_cnt = BPF_REG_7;
19859 int reg_loop_ctx = BPF_REG_8;
19861 struct bpf_prog *new_prog;
19862 u32 callback_start;
19863 u32 call_insn_offset;
19864 s32 callback_offset;
19866 /* This represents an inlined version of bpf_iter.c:bpf_loop,
19867 * be careful to modify this code in sync.
19869 struct bpf_insn insn_buf[] = {
19870 /* Return error and jump to the end of the patch if
19871 * expected number of iterations is too big.
19873 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19874 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19875 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19876 /* spill R6, R7, R8 to use these as loop vars */
19877 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19878 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19879 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19880 /* initialize loop vars */
19881 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19882 BPF_MOV32_IMM(reg_loop_cnt, 0),
19883 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19885 * if reg_loop_cnt >= reg_loop_max skip the loop body
19887 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19889 * correct callback offset would be set after patching
19891 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19892 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19894 /* increment loop counter */
19895 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19896 /* jump to loop header if callback returned 0 */
19897 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19898 /* return value of bpf_loop,
19899 * set R0 to the number of iterations
19901 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19902 /* restore original values of R6, R7, R8 */
19903 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19904 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19905 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19908 *cnt = ARRAY_SIZE(insn_buf);
19909 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19913 /* callback start is known only after patching */
19914 callback_start = env->subprog_info[callback_subprogno].start;
19915 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19916 call_insn_offset = position + 12;
19917 callback_offset = callback_start - call_insn_offset - 1;
19918 new_prog->insnsi[call_insn_offset].imm = callback_offset;
19923 static bool is_bpf_loop_call(struct bpf_insn *insn)
19925 return insn->code == (BPF_JMP | BPF_CALL) &&
19926 insn->src_reg == 0 &&
19927 insn->imm == BPF_FUNC_loop;
19930 /* For all sub-programs in the program (including main) check
19931 * insn_aux_data to see if there are bpf_loop calls that require
19932 * inlining. If such calls are found the calls are replaced with a
19933 * sequence of instructions produced by `inline_bpf_loop` function and
19934 * subprog stack_depth is increased by the size of 3 registers.
19935 * This stack space is used to spill values of the R6, R7, R8. These
19936 * registers are used to store the loop bound, counter and context
19939 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19941 struct bpf_subprog_info *subprogs = env->subprog_info;
19942 int i, cur_subprog = 0, cnt, delta = 0;
19943 struct bpf_insn *insn = env->prog->insnsi;
19944 int insn_cnt = env->prog->len;
19945 u16 stack_depth = subprogs[cur_subprog].stack_depth;
19946 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19947 u16 stack_depth_extra = 0;
19949 for (i = 0; i < insn_cnt; i++, insn++) {
19950 struct bpf_loop_inline_state *inline_state =
19951 &env->insn_aux_data[i + delta].loop_inline_state;
19953 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19954 struct bpf_prog *new_prog;
19956 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19957 new_prog = inline_bpf_loop(env,
19959 -(stack_depth + stack_depth_extra),
19960 inline_state->callback_subprogno,
19966 env->prog = new_prog;
19967 insn = new_prog->insnsi + i + delta;
19970 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19971 subprogs[cur_subprog].stack_depth += stack_depth_extra;
19973 stack_depth = subprogs[cur_subprog].stack_depth;
19974 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19975 stack_depth_extra = 0;
19979 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19984 static void free_states(struct bpf_verifier_env *env)
19986 struct bpf_verifier_state_list *sl, *sln;
19989 sl = env->free_list;
19992 free_verifier_state(&sl->state, false);
19996 env->free_list = NULL;
19998 if (!env->explored_states)
20001 for (i = 0; i < state_htab_size(env); i++) {
20002 sl = env->explored_states[i];
20006 free_verifier_state(&sl->state, false);
20010 env->explored_states[i] = NULL;
20014 static int do_check_common(struct bpf_verifier_env *env, int subprog)
20016 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20017 struct bpf_subprog_info *sub = subprog_info(env, subprog);
20018 struct bpf_verifier_state *state;
20019 struct bpf_reg_state *regs;
20022 env->prev_linfo = NULL;
20025 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
20028 state->curframe = 0;
20029 state->speculative = false;
20030 state->branches = 1;
20031 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
20032 if (!state->frame[0]) {
20036 env->cur_state = state;
20037 init_func_state(env, state->frame[0],
20038 BPF_MAIN_FUNC /* callsite */,
20041 state->first_insn_idx = env->subprog_info[subprog].start;
20042 state->last_insn_idx = -1;
20045 regs = state->frame[state->curframe]->regs;
20046 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
20047 const char *sub_name = subprog_name(env, subprog);
20048 struct bpf_subprog_arg_info *arg;
20049 struct bpf_reg_state *reg;
20051 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
20052 ret = btf_prepare_func_args(env, subprog);
20056 if (subprog_is_exc_cb(env, subprog)) {
20057 state->frame[0]->in_exception_callback_fn = true;
20058 /* We have already ensured that the callback returns an integer, just
20059 * like all global subprogs. We need to determine it only has a single
20062 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
20063 verbose(env, "exception cb only supports single integer argument\n");
20068 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
20069 arg = &sub->args[i - BPF_REG_1];
20072 if (arg->arg_type == ARG_PTR_TO_CTX) {
20073 reg->type = PTR_TO_CTX;
20074 mark_reg_known_zero(env, regs, i);
20075 } else if (arg->arg_type == ARG_ANYTHING) {
20076 reg->type = SCALAR_VALUE;
20077 mark_reg_unknown(env, regs, i);
20078 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
20079 /* assume unspecial LOCAL dynptr type */
20080 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
20081 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
20082 reg->type = PTR_TO_MEM;
20083 if (arg->arg_type & PTR_MAYBE_NULL)
20084 reg->type |= PTR_MAYBE_NULL;
20085 mark_reg_known_zero(env, regs, i);
20086 reg->mem_size = arg->mem_size;
20087 reg->id = ++env->id_gen;
20089 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
20090 i - BPF_REG_1, arg->arg_type);
20096 /* if main BPF program has associated BTF info, validate that
20097 * it's matching expected signature, and otherwise mark BTF
20098 * info for main program as unreliable
20100 if (env->prog->aux->func_info_aux) {
20101 ret = btf_prepare_func_args(env, 0);
20102 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
20103 env->prog->aux->func_info_aux[0].unreliable = true;
20106 /* 1st arg to a function */
20107 regs[BPF_REG_1].type = PTR_TO_CTX;
20108 mark_reg_known_zero(env, regs, BPF_REG_1);
20111 ret = do_check(env);
20113 /* check for NULL is necessary, since cur_state can be freed inside
20114 * do_check() under memory pressure.
20116 if (env->cur_state) {
20117 free_verifier_state(env->cur_state, true);
20118 env->cur_state = NULL;
20120 while (!pop_stack(env, NULL, NULL, false));
20121 if (!ret && pop_log)
20122 bpf_vlog_reset(&env->log, 0);
20127 /* Lazily verify all global functions based on their BTF, if they are called
20128 * from main BPF program or any of subprograms transitively.
20129 * BPF global subprogs called from dead code are not validated.
20130 * All callable global functions must pass verification.
20131 * Otherwise the whole program is rejected.
20142 * foo() will be verified first for R1=any_scalar_value. During verification it
20143 * will be assumed that bar() already verified successfully and call to bar()
20144 * from foo() will be checked for type match only. Later bar() will be verified
20145 * independently to check that it's safe for R1=any_scalar_value.
20147 static int do_check_subprogs(struct bpf_verifier_env *env)
20149 struct bpf_prog_aux *aux = env->prog->aux;
20150 struct bpf_func_info_aux *sub_aux;
20151 int i, ret, new_cnt;
20153 if (!aux->func_info)
20156 /* exception callback is presumed to be always called */
20157 if (env->exception_callback_subprog)
20158 subprog_aux(env, env->exception_callback_subprog)->called = true;
20162 for (i = 1; i < env->subprog_cnt; i++) {
20163 if (!subprog_is_global(env, i))
20166 sub_aux = subprog_aux(env, i);
20167 if (!sub_aux->called || sub_aux->verified)
20170 env->insn_idx = env->subprog_info[i].start;
20171 WARN_ON_ONCE(env->insn_idx == 0);
20172 ret = do_check_common(env, i);
20175 } else if (env->log.level & BPF_LOG_LEVEL) {
20176 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
20177 i, subprog_name(env, i));
20180 /* We verified new global subprog, it might have called some
20181 * more global subprogs that we haven't verified yet, so we
20182 * need to do another pass over subprogs to verify those.
20184 sub_aux->verified = true;
20188 /* We can't loop forever as we verify at least one global subprog on
20197 static int do_check_main(struct bpf_verifier_env *env)
20202 ret = do_check_common(env, 0);
20204 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20209 static void print_verification_stats(struct bpf_verifier_env *env)
20213 if (env->log.level & BPF_LOG_STATS) {
20214 verbose(env, "verification time %lld usec\n",
20215 div_u64(env->verification_time, 1000));
20216 verbose(env, "stack depth ");
20217 for (i = 0; i < env->subprog_cnt; i++) {
20218 u32 depth = env->subprog_info[i].stack_depth;
20220 verbose(env, "%d", depth);
20221 if (i + 1 < env->subprog_cnt)
20224 verbose(env, "\n");
20226 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
20227 "total_states %d peak_states %d mark_read %d\n",
20228 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
20229 env->max_states_per_insn, env->total_states,
20230 env->peak_states, env->longest_mark_read_walk);
20233 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
20235 const struct btf_type *t, *func_proto;
20236 const struct bpf_struct_ops *st_ops;
20237 const struct btf_member *member;
20238 struct bpf_prog *prog = env->prog;
20239 u32 btf_id, member_idx;
20242 if (!prog->gpl_compatible) {
20243 verbose(env, "struct ops programs must have a GPL compatible license\n");
20247 btf_id = prog->aux->attach_btf_id;
20248 st_ops = bpf_struct_ops_find(btf_id);
20250 verbose(env, "attach_btf_id %u is not a supported struct\n",
20256 member_idx = prog->expected_attach_type;
20257 if (member_idx >= btf_type_vlen(t)) {
20258 verbose(env, "attach to invalid member idx %u of struct %s\n",
20259 member_idx, st_ops->name);
20263 member = &btf_type_member(t)[member_idx];
20264 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
20265 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
20268 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
20269 mname, member_idx, st_ops->name);
20273 if (st_ops->check_member) {
20274 int err = st_ops->check_member(t, member, prog);
20277 verbose(env, "attach to unsupported member %s of struct %s\n",
20278 mname, st_ops->name);
20283 prog->aux->attach_func_proto = func_proto;
20284 prog->aux->attach_func_name = mname;
20285 env->ops = st_ops->verifier_ops;
20289 #define SECURITY_PREFIX "security_"
20291 static int check_attach_modify_return(unsigned long addr, const char *func_name)
20293 if (within_error_injection_list(addr) ||
20294 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
20300 /* list of non-sleepable functions that are otherwise on
20301 * ALLOW_ERROR_INJECTION list
20303 BTF_SET_START(btf_non_sleepable_error_inject)
20304 /* Three functions below can be called from sleepable and non-sleepable context.
20305 * Assume non-sleepable from bpf safety point of view.
20307 BTF_ID(func, __filemap_add_folio)
20308 BTF_ID(func, should_fail_alloc_page)
20309 BTF_ID(func, should_failslab)
20310 BTF_SET_END(btf_non_sleepable_error_inject)
20312 static int check_non_sleepable_error_inject(u32 btf_id)
20314 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
20317 int bpf_check_attach_target(struct bpf_verifier_log *log,
20318 const struct bpf_prog *prog,
20319 const struct bpf_prog *tgt_prog,
20321 struct bpf_attach_target_info *tgt_info)
20323 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
20324 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
20325 const char prefix[] = "btf_trace_";
20326 int ret = 0, subprog = -1, i;
20327 const struct btf_type *t;
20328 bool conservative = true;
20332 struct module *mod = NULL;
20335 bpf_log(log, "Tracing programs must provide btf_id\n");
20338 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
20341 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
20344 t = btf_type_by_id(btf, btf_id);
20346 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
20349 tname = btf_name_by_offset(btf, t->name_off);
20351 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
20355 struct bpf_prog_aux *aux = tgt_prog->aux;
20357 if (bpf_prog_is_dev_bound(prog->aux) &&
20358 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
20359 bpf_log(log, "Target program bound device mismatch");
20363 for (i = 0; i < aux->func_info_cnt; i++)
20364 if (aux->func_info[i].type_id == btf_id) {
20368 if (subprog == -1) {
20369 bpf_log(log, "Subprog %s doesn't exist\n", tname);
20372 if (aux->func && aux->func[subprog]->aux->exception_cb) {
20374 "%s programs cannot attach to exception callback\n",
20375 prog_extension ? "Extension" : "FENTRY/FEXIT");
20378 conservative = aux->func_info_aux[subprog].unreliable;
20379 if (prog_extension) {
20380 if (conservative) {
20382 "Cannot replace static functions\n");
20385 if (!prog->jit_requested) {
20387 "Extension programs should be JITed\n");
20391 if (!tgt_prog->jited) {
20392 bpf_log(log, "Can attach to only JITed progs\n");
20395 if (prog_tracing) {
20396 if (aux->attach_tracing_prog) {
20398 * Target program is an fentry/fexit which is already attached
20399 * to another tracing program. More levels of nesting
20400 * attachment are not allowed.
20402 bpf_log(log, "Cannot nest tracing program attach more than once\n");
20405 } else if (tgt_prog->type == prog->type) {
20407 * To avoid potential call chain cycles, prevent attaching of a
20408 * program extension to another extension. It's ok to attach
20409 * fentry/fexit to extension program.
20411 bpf_log(log, "Cannot recursively attach\n");
20414 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
20416 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
20417 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
20418 /* Program extensions can extend all program types
20419 * except fentry/fexit. The reason is the following.
20420 * The fentry/fexit programs are used for performance
20421 * analysis, stats and can be attached to any program
20422 * type. When extension program is replacing XDP function
20423 * it is necessary to allow performance analysis of all
20424 * functions. Both original XDP program and its program
20425 * extension. Hence attaching fentry/fexit to
20426 * BPF_PROG_TYPE_EXT is allowed. If extending of
20427 * fentry/fexit was allowed it would be possible to create
20428 * long call chain fentry->extension->fentry->extension
20429 * beyond reasonable stack size. Hence extending fentry
20432 bpf_log(log, "Cannot extend fentry/fexit\n");
20436 if (prog_extension) {
20437 bpf_log(log, "Cannot replace kernel functions\n");
20442 switch (prog->expected_attach_type) {
20443 case BPF_TRACE_RAW_TP:
20446 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
20449 if (!btf_type_is_typedef(t)) {
20450 bpf_log(log, "attach_btf_id %u is not a typedef\n",
20454 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
20455 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
20459 tname += sizeof(prefix) - 1;
20460 t = btf_type_by_id(btf, t->type);
20461 if (!btf_type_is_ptr(t))
20462 /* should never happen in valid vmlinux build */
20464 t = btf_type_by_id(btf, t->type);
20465 if (!btf_type_is_func_proto(t))
20466 /* should never happen in valid vmlinux build */
20470 case BPF_TRACE_ITER:
20471 if (!btf_type_is_func(t)) {
20472 bpf_log(log, "attach_btf_id %u is not a function\n",
20476 t = btf_type_by_id(btf, t->type);
20477 if (!btf_type_is_func_proto(t))
20479 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20484 if (!prog_extension)
20487 case BPF_MODIFY_RETURN:
20489 case BPF_LSM_CGROUP:
20490 case BPF_TRACE_FENTRY:
20491 case BPF_TRACE_FEXIT:
20492 if (!btf_type_is_func(t)) {
20493 bpf_log(log, "attach_btf_id %u is not a function\n",
20497 if (prog_extension &&
20498 btf_check_type_match(log, prog, btf, t))
20500 t = btf_type_by_id(btf, t->type);
20501 if (!btf_type_is_func_proto(t))
20504 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
20505 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
20506 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
20509 if (tgt_prog && conservative)
20512 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20518 addr = (long) tgt_prog->bpf_func;
20520 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20522 if (btf_is_module(btf)) {
20523 mod = btf_try_get_module(btf);
20525 addr = find_kallsyms_symbol_value(mod, tname);
20529 addr = kallsyms_lookup_name(tname);
20534 "The address of function %s cannot be found\n",
20540 if (prog->aux->sleepable) {
20542 switch (prog->type) {
20543 case BPF_PROG_TYPE_TRACING:
20545 /* fentry/fexit/fmod_ret progs can be sleepable if they are
20546 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20548 if (!check_non_sleepable_error_inject(btf_id) &&
20549 within_error_injection_list(addr))
20551 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
20552 * in the fmodret id set with the KF_SLEEPABLE flag.
20555 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20558 if (flags && (*flags & KF_SLEEPABLE))
20562 case BPF_PROG_TYPE_LSM:
20563 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
20564 * Only some of them are sleepable.
20566 if (bpf_lsm_is_sleepable_hook(btf_id))
20574 bpf_log(log, "%s is not sleepable\n", tname);
20577 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20580 bpf_log(log, "can't modify return codes of BPF programs\n");
20584 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20585 !check_attach_modify_return(addr, tname))
20589 bpf_log(log, "%s() is not modifiable\n", tname);
20596 tgt_info->tgt_addr = addr;
20597 tgt_info->tgt_name = tname;
20598 tgt_info->tgt_type = t;
20599 tgt_info->tgt_mod = mod;
20603 BTF_SET_START(btf_id_deny)
20606 BTF_ID(func, migrate_disable)
20607 BTF_ID(func, migrate_enable)
20609 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20610 BTF_ID(func, rcu_read_unlock_strict)
20612 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20613 BTF_ID(func, preempt_count_add)
20614 BTF_ID(func, preempt_count_sub)
20616 #ifdef CONFIG_PREEMPT_RCU
20617 BTF_ID(func, __rcu_read_lock)
20618 BTF_ID(func, __rcu_read_unlock)
20620 BTF_SET_END(btf_id_deny)
20622 static bool can_be_sleepable(struct bpf_prog *prog)
20624 if (prog->type == BPF_PROG_TYPE_TRACING) {
20625 switch (prog->expected_attach_type) {
20626 case BPF_TRACE_FENTRY:
20627 case BPF_TRACE_FEXIT:
20628 case BPF_MODIFY_RETURN:
20629 case BPF_TRACE_ITER:
20635 return prog->type == BPF_PROG_TYPE_LSM ||
20636 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20637 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20640 static int check_attach_btf_id(struct bpf_verifier_env *env)
20642 struct bpf_prog *prog = env->prog;
20643 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20644 struct bpf_attach_target_info tgt_info = {};
20645 u32 btf_id = prog->aux->attach_btf_id;
20646 struct bpf_trampoline *tr;
20650 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20651 if (prog->aux->sleepable)
20652 /* attach_btf_id checked to be zero already */
20654 verbose(env, "Syscall programs can only be sleepable\n");
20658 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20659 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20663 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20664 return check_struct_ops_btf_id(env);
20666 if (prog->type != BPF_PROG_TYPE_TRACING &&
20667 prog->type != BPF_PROG_TYPE_LSM &&
20668 prog->type != BPF_PROG_TYPE_EXT)
20671 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20675 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20676 /* to make freplace equivalent to their targets, they need to
20677 * inherit env->ops and expected_attach_type for the rest of the
20680 env->ops = bpf_verifier_ops[tgt_prog->type];
20681 prog->expected_attach_type = tgt_prog->expected_attach_type;
20684 /* store info about the attachment target that will be used later */
20685 prog->aux->attach_func_proto = tgt_info.tgt_type;
20686 prog->aux->attach_func_name = tgt_info.tgt_name;
20687 prog->aux->mod = tgt_info.tgt_mod;
20690 prog->aux->saved_dst_prog_type = tgt_prog->type;
20691 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20694 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20695 prog->aux->attach_btf_trace = true;
20697 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20698 if (!bpf_iter_prog_supported(prog))
20703 if (prog->type == BPF_PROG_TYPE_LSM) {
20704 ret = bpf_lsm_verify_prog(&env->log, prog);
20707 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
20708 btf_id_set_contains(&btf_id_deny, btf_id)) {
20712 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20713 tr = bpf_trampoline_get(key, &tgt_info);
20717 if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20718 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20720 prog->aux->dst_trampoline = tr;
20724 struct btf *bpf_get_btf_vmlinux(void)
20726 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20727 mutex_lock(&bpf_verifier_lock);
20729 btf_vmlinux = btf_parse_vmlinux();
20730 mutex_unlock(&bpf_verifier_lock);
20732 return btf_vmlinux;
20735 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20737 u64 start_time = ktime_get_ns();
20738 struct bpf_verifier_env *env;
20739 int i, len, ret = -EINVAL, err;
20743 /* no program is valid */
20744 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20747 /* 'struct bpf_verifier_env' can be global, but since it's not small,
20748 * allocate/free it every time bpf_check() is called
20750 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20756 len = (*prog)->len;
20757 env->insn_aux_data =
20758 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20760 if (!env->insn_aux_data)
20762 for (i = 0; i < len; i++)
20763 env->insn_aux_data[i].orig_idx = i;
20765 env->ops = bpf_verifier_ops[env->prog->type];
20766 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20767 is_priv = bpf_capable();
20769 bpf_get_btf_vmlinux();
20771 /* grab the mutex to protect few globals used by verifier */
20773 mutex_lock(&bpf_verifier_lock);
20775 /* user could have requested verbose verifier output
20776 * and supplied buffer to store the verification trace
20778 ret = bpf_vlog_init(&env->log, attr->log_level,
20779 (char __user *) (unsigned long) attr->log_buf,
20784 mark_verifier_state_clean(env);
20786 if (IS_ERR(btf_vmlinux)) {
20787 /* Either gcc or pahole or kernel are broken. */
20788 verbose(env, "in-kernel BTF is malformed\n");
20789 ret = PTR_ERR(btf_vmlinux);
20790 goto skip_full_check;
20793 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20794 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20795 env->strict_alignment = true;
20796 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20797 env->strict_alignment = false;
20799 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20800 env->allow_uninit_stack = bpf_allow_uninit_stack();
20801 env->bypass_spec_v1 = bpf_bypass_spec_v1();
20802 env->bypass_spec_v4 = bpf_bypass_spec_v4();
20803 env->bpf_capable = bpf_capable();
20806 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20807 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
20809 env->explored_states = kvcalloc(state_htab_size(env),
20810 sizeof(struct bpf_verifier_state_list *),
20813 if (!env->explored_states)
20814 goto skip_full_check;
20816 ret = check_btf_info_early(env, attr, uattr);
20818 goto skip_full_check;
20820 ret = add_subprog_and_kfunc(env);
20822 goto skip_full_check;
20824 ret = check_subprogs(env);
20826 goto skip_full_check;
20828 ret = check_btf_info(env, attr, uattr);
20830 goto skip_full_check;
20832 ret = check_attach_btf_id(env);
20834 goto skip_full_check;
20836 ret = resolve_pseudo_ldimm64(env);
20838 goto skip_full_check;
20840 if (bpf_prog_is_offloaded(env->prog->aux)) {
20841 ret = bpf_prog_offload_verifier_prep(env->prog);
20843 goto skip_full_check;
20846 ret = check_cfg(env);
20848 goto skip_full_check;
20850 ret = do_check_main(env);
20851 ret = ret ?: do_check_subprogs(env);
20853 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20854 ret = bpf_prog_offload_finalize(env);
20857 kvfree(env->explored_states);
20860 ret = check_max_stack_depth(env);
20862 /* instruction rewrites happen after this point */
20864 ret = optimize_bpf_loop(env);
20868 opt_hard_wire_dead_code_branches(env);
20870 ret = opt_remove_dead_code(env);
20872 ret = opt_remove_nops(env);
20875 sanitize_dead_code(env);
20879 /* program is valid, convert *(u32*)(ctx + off) accesses */
20880 ret = convert_ctx_accesses(env);
20883 ret = do_misc_fixups(env);
20885 /* do 32-bit optimization after insn patching has done so those patched
20886 * insns could be handled correctly.
20888 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20889 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20890 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20895 ret = fixup_call_args(env);
20897 env->verification_time = ktime_get_ns() - start_time;
20898 print_verification_stats(env);
20899 env->prog->aux->verified_insns = env->insn_processed;
20901 /* preserve original error even if log finalization is successful */
20902 err = bpf_vlog_finalize(&env->log, &log_true_size);
20906 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20907 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20908 &log_true_size, sizeof(log_true_size))) {
20910 goto err_release_maps;
20914 goto err_release_maps;
20916 if (env->used_map_cnt) {
20917 /* if program passed verifier, update used_maps in bpf_prog_info */
20918 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20919 sizeof(env->used_maps[0]),
20922 if (!env->prog->aux->used_maps) {
20924 goto err_release_maps;
20927 memcpy(env->prog->aux->used_maps, env->used_maps,
20928 sizeof(env->used_maps[0]) * env->used_map_cnt);
20929 env->prog->aux->used_map_cnt = env->used_map_cnt;
20931 if (env->used_btf_cnt) {
20932 /* if program passed verifier, update used_btfs in bpf_prog_aux */
20933 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20934 sizeof(env->used_btfs[0]),
20936 if (!env->prog->aux->used_btfs) {
20938 goto err_release_maps;
20941 memcpy(env->prog->aux->used_btfs, env->used_btfs,
20942 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20943 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20945 if (env->used_map_cnt || env->used_btf_cnt) {
20946 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
20947 * bpf_ld_imm64 instructions
20949 convert_pseudo_ld_imm64(env);
20952 adjust_btf_func(env);
20955 if (!env->prog->aux->used_maps)
20956 /* if we didn't copy map pointers into bpf_prog_info, release
20957 * them now. Otherwise free_used_maps() will release them.
20960 if (!env->prog->aux->used_btfs)
20963 /* extension progs temporarily inherit the attach_type of their targets
20964 for verification purposes, so set it back to zero before returning
20966 if (env->prog->type == BPF_PROG_TYPE_EXT)
20967 env->prog->expected_attach_type = 0;
20972 mutex_unlock(&bpf_verifier_lock);
20973 vfree(env->insn_aux_data);