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_async_callback_calling_insn(struct bpf_insn *insn)
533 return bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm);
536 static bool is_may_goto_insn(struct bpf_insn *insn)
538 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
541 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
543 return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
546 static bool is_storage_get_function(enum bpf_func_id func_id)
548 return func_id == BPF_FUNC_sk_storage_get ||
549 func_id == BPF_FUNC_inode_storage_get ||
550 func_id == BPF_FUNC_task_storage_get ||
551 func_id == BPF_FUNC_cgrp_storage_get;
554 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
555 const struct bpf_map *map)
557 int ref_obj_uses = 0;
559 if (is_ptr_cast_function(func_id))
561 if (is_acquire_function(func_id, map))
563 if (is_dynptr_ref_function(func_id))
566 return ref_obj_uses > 1;
569 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
571 return BPF_CLASS(insn->code) == BPF_STX &&
572 BPF_MODE(insn->code) == BPF_ATOMIC &&
573 insn->imm == BPF_CMPXCHG;
576 static int __get_spi(s32 off)
578 return (-off - 1) / BPF_REG_SIZE;
581 static struct bpf_func_state *func(struct bpf_verifier_env *env,
582 const struct bpf_reg_state *reg)
584 struct bpf_verifier_state *cur = env->cur_state;
586 return cur->frame[reg->frameno];
589 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
591 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
593 /* We need to check that slots between [spi - nr_slots + 1, spi] are
594 * within [0, allocated_stack).
596 * Please note that the spi grows downwards. For example, a dynptr
597 * takes the size of two stack slots; the first slot will be at
598 * spi and the second slot will be at spi - 1.
600 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
603 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
604 const char *obj_kind, int nr_slots)
608 if (!tnum_is_const(reg->var_off)) {
609 verbose(env, "%s has to be at a constant offset\n", obj_kind);
613 off = reg->off + reg->var_off.value;
614 if (off % BPF_REG_SIZE) {
615 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
619 spi = __get_spi(off);
620 if (spi + 1 < nr_slots) {
621 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
625 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
630 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
632 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
635 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
637 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
640 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
642 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
643 case DYNPTR_TYPE_LOCAL:
644 return BPF_DYNPTR_TYPE_LOCAL;
645 case DYNPTR_TYPE_RINGBUF:
646 return BPF_DYNPTR_TYPE_RINGBUF;
647 case DYNPTR_TYPE_SKB:
648 return BPF_DYNPTR_TYPE_SKB;
649 case DYNPTR_TYPE_XDP:
650 return BPF_DYNPTR_TYPE_XDP;
652 return BPF_DYNPTR_TYPE_INVALID;
656 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
659 case BPF_DYNPTR_TYPE_LOCAL:
660 return DYNPTR_TYPE_LOCAL;
661 case BPF_DYNPTR_TYPE_RINGBUF:
662 return DYNPTR_TYPE_RINGBUF;
663 case BPF_DYNPTR_TYPE_SKB:
664 return DYNPTR_TYPE_SKB;
665 case BPF_DYNPTR_TYPE_XDP:
666 return DYNPTR_TYPE_XDP;
672 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
674 return type == BPF_DYNPTR_TYPE_RINGBUF;
677 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
678 enum bpf_dynptr_type type,
679 bool first_slot, int dynptr_id);
681 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
682 struct bpf_reg_state *reg);
684 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
685 struct bpf_reg_state *sreg1,
686 struct bpf_reg_state *sreg2,
687 enum bpf_dynptr_type type)
689 int id = ++env->id_gen;
691 __mark_dynptr_reg(sreg1, type, true, id);
692 __mark_dynptr_reg(sreg2, type, false, id);
695 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
696 struct bpf_reg_state *reg,
697 enum bpf_dynptr_type type)
699 __mark_dynptr_reg(reg, type, true, ++env->id_gen);
702 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
703 struct bpf_func_state *state, int spi);
705 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
706 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
708 struct bpf_func_state *state = func(env, reg);
709 enum bpf_dynptr_type type;
712 spi = dynptr_get_spi(env, reg);
716 /* We cannot assume both spi and spi - 1 belong to the same dynptr,
717 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
718 * to ensure that for the following example:
721 * So marking spi = 2 should lead to destruction of both d1 and d2. In
722 * case they do belong to same dynptr, second call won't see slot_type
723 * as STACK_DYNPTR and will simply skip destruction.
725 err = destroy_if_dynptr_stack_slot(env, state, spi);
728 err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
732 for (i = 0; i < BPF_REG_SIZE; i++) {
733 state->stack[spi].slot_type[i] = STACK_DYNPTR;
734 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
737 type = arg_to_dynptr_type(arg_type);
738 if (type == BPF_DYNPTR_TYPE_INVALID)
741 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
742 &state->stack[spi - 1].spilled_ptr, type);
744 if (dynptr_type_refcounted(type)) {
745 /* The id is used to track proper releasing */
748 if (clone_ref_obj_id)
749 id = clone_ref_obj_id;
751 id = acquire_reference_state(env, insn_idx);
756 state->stack[spi].spilled_ptr.ref_obj_id = id;
757 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
760 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
761 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
766 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
770 for (i = 0; i < BPF_REG_SIZE; i++) {
771 state->stack[spi].slot_type[i] = STACK_INVALID;
772 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
775 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
776 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
778 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
780 * While we don't allow reading STACK_INVALID, it is still possible to
781 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
782 * helpers or insns can do partial read of that part without failing,
783 * but check_stack_range_initialized, check_stack_read_var_off, and
784 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
785 * the slot conservatively. Hence we need to prevent those liveness
788 * This was not a problem before because STACK_INVALID is only set by
789 * default (where the default reg state has its reg->parent as NULL), or
790 * in clean_live_states after REG_LIVE_DONE (at which point
791 * mark_reg_read won't walk reg->parent chain), but not randomly during
792 * verifier state exploration (like we did above). Hence, for our case
793 * parentage chain will still be live (i.e. reg->parent may be
794 * non-NULL), while earlier reg->parent was NULL, so we need
795 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
796 * done later on reads or by mark_dynptr_read as well to unnecessary
797 * mark registers in verifier state.
799 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
800 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
803 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
805 struct bpf_func_state *state = func(env, reg);
806 int spi, ref_obj_id, i;
808 spi = dynptr_get_spi(env, reg);
812 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
813 invalidate_dynptr(env, state, spi);
817 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
819 /* If the dynptr has a ref_obj_id, then we need to invalidate
822 * 1) Any dynptrs with a matching ref_obj_id (clones)
823 * 2) Any slices derived from this dynptr.
826 /* Invalidate any slices associated with this dynptr */
827 WARN_ON_ONCE(release_reference(env, ref_obj_id));
829 /* Invalidate any dynptr clones */
830 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
831 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
834 /* it should always be the case that if the ref obj id
835 * matches then the stack slot also belongs to a
838 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
839 verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
842 if (state->stack[i].spilled_ptr.dynptr.first_slot)
843 invalidate_dynptr(env, state, i);
849 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
850 struct bpf_reg_state *reg);
852 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
854 if (!env->allow_ptr_leaks)
855 __mark_reg_not_init(env, reg);
857 __mark_reg_unknown(env, reg);
860 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
861 struct bpf_func_state *state, int spi)
863 struct bpf_func_state *fstate;
864 struct bpf_reg_state *dreg;
867 /* We always ensure that STACK_DYNPTR is never set partially,
868 * hence just checking for slot_type[0] is enough. This is
869 * different for STACK_SPILL, where it may be only set for
870 * 1 byte, so code has to use is_spilled_reg.
872 if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
875 /* Reposition spi to first slot */
876 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
879 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
880 verbose(env, "cannot overwrite referenced dynptr\n");
884 mark_stack_slot_scratched(env, spi);
885 mark_stack_slot_scratched(env, spi - 1);
887 /* Writing partially to one dynptr stack slot destroys both. */
888 for (i = 0; i < BPF_REG_SIZE; i++) {
889 state->stack[spi].slot_type[i] = STACK_INVALID;
890 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
893 dynptr_id = state->stack[spi].spilled_ptr.id;
894 /* Invalidate any slices associated with this dynptr */
895 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
896 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
897 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
899 if (dreg->dynptr_id == dynptr_id)
900 mark_reg_invalid(env, dreg);
903 /* Do not release reference state, we are destroying dynptr on stack,
904 * not using some helper to release it. Just reset register.
906 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
907 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
909 /* Same reason as unmark_stack_slots_dynptr above */
910 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
911 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
916 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
920 if (reg->type == CONST_PTR_TO_DYNPTR)
923 spi = dynptr_get_spi(env, reg);
925 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
926 * error because this just means the stack state hasn't been updated yet.
927 * We will do check_mem_access to check and update stack bounds later.
929 if (spi < 0 && spi != -ERANGE)
932 /* We don't need to check if the stack slots are marked by previous
933 * dynptr initializations because we allow overwriting existing unreferenced
934 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
935 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
936 * touching are completely destructed before we reinitialize them for a new
937 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
938 * instead of delaying it until the end where the user will get "Unreleased
944 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
946 struct bpf_func_state *state = func(env, reg);
949 /* This already represents first slot of initialized bpf_dynptr.
951 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
952 * check_func_arg_reg_off's logic, so we don't need to check its
953 * offset and alignment.
955 if (reg->type == CONST_PTR_TO_DYNPTR)
958 spi = dynptr_get_spi(env, reg);
961 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
964 for (i = 0; i < BPF_REG_SIZE; i++) {
965 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
966 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
973 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
974 enum bpf_arg_type arg_type)
976 struct bpf_func_state *state = func(env, reg);
977 enum bpf_dynptr_type dynptr_type;
980 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
981 if (arg_type == ARG_PTR_TO_DYNPTR)
984 dynptr_type = arg_to_dynptr_type(arg_type);
985 if (reg->type == CONST_PTR_TO_DYNPTR) {
986 return reg->dynptr.type == dynptr_type;
988 spi = dynptr_get_spi(env, reg);
991 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
995 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
997 static bool in_rcu_cs(struct bpf_verifier_env *env);
999 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1001 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1002 struct bpf_kfunc_call_arg_meta *meta,
1003 struct bpf_reg_state *reg, int insn_idx,
1004 struct btf *btf, u32 btf_id, int nr_slots)
1006 struct bpf_func_state *state = func(env, reg);
1009 spi = iter_get_spi(env, reg, nr_slots);
1013 id = acquire_reference_state(env, insn_idx);
1017 for (i = 0; i < nr_slots; i++) {
1018 struct bpf_stack_state *slot = &state->stack[spi - i];
1019 struct bpf_reg_state *st = &slot->spilled_ptr;
1021 __mark_reg_known_zero(st);
1022 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1023 if (is_kfunc_rcu_protected(meta)) {
1025 st->type |= MEM_RCU;
1027 st->type |= PTR_UNTRUSTED;
1029 st->live |= REG_LIVE_WRITTEN;
1030 st->ref_obj_id = i == 0 ? id : 0;
1032 st->iter.btf_id = btf_id;
1033 st->iter.state = BPF_ITER_STATE_ACTIVE;
1036 for (j = 0; j < BPF_REG_SIZE; j++)
1037 slot->slot_type[j] = STACK_ITER;
1039 mark_stack_slot_scratched(env, spi - i);
1045 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1046 struct bpf_reg_state *reg, int nr_slots)
1048 struct bpf_func_state *state = func(env, reg);
1051 spi = iter_get_spi(env, reg, nr_slots);
1055 for (i = 0; i < nr_slots; i++) {
1056 struct bpf_stack_state *slot = &state->stack[spi - i];
1057 struct bpf_reg_state *st = &slot->spilled_ptr;
1060 WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1062 __mark_reg_not_init(env, st);
1064 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1065 st->live |= REG_LIVE_WRITTEN;
1067 for (j = 0; j < BPF_REG_SIZE; j++)
1068 slot->slot_type[j] = STACK_INVALID;
1070 mark_stack_slot_scratched(env, spi - i);
1076 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1077 struct bpf_reg_state *reg, int nr_slots)
1079 struct bpf_func_state *state = func(env, reg);
1082 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1083 * will do check_mem_access to check and update stack bounds later, so
1084 * return true for that case.
1086 spi = iter_get_spi(env, reg, nr_slots);
1092 for (i = 0; i < nr_slots; i++) {
1093 struct bpf_stack_state *slot = &state->stack[spi - i];
1095 for (j = 0; j < BPF_REG_SIZE; j++)
1096 if (slot->slot_type[j] == STACK_ITER)
1103 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1104 struct btf *btf, u32 btf_id, int nr_slots)
1106 struct bpf_func_state *state = func(env, reg);
1109 spi = iter_get_spi(env, reg, nr_slots);
1113 for (i = 0; i < nr_slots; i++) {
1114 struct bpf_stack_state *slot = &state->stack[spi - i];
1115 struct bpf_reg_state *st = &slot->spilled_ptr;
1117 if (st->type & PTR_UNTRUSTED)
1119 /* only main (first) slot has ref_obj_id set */
1120 if (i == 0 && !st->ref_obj_id)
1122 if (i != 0 && st->ref_obj_id)
1124 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1127 for (j = 0; j < BPF_REG_SIZE; j++)
1128 if (slot->slot_type[j] != STACK_ITER)
1135 /* Check if given stack slot is "special":
1136 * - spilled register state (STACK_SPILL);
1137 * - dynptr state (STACK_DYNPTR);
1138 * - iter state (STACK_ITER).
1140 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1142 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1154 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1159 /* The reg state of a pointer or a bounded scalar was saved when
1160 * it was spilled to the stack.
1162 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1164 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1167 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1169 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1170 stack->spilled_ptr.type == SCALAR_VALUE;
1173 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1175 return stack->slot_type[0] == STACK_SPILL &&
1176 stack->spilled_ptr.type == SCALAR_VALUE;
1179 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1180 * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1181 * more precise STACK_ZERO.
1182 * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take
1183 * env->allow_ptr_leaks into account and force STACK_MISC, if necessary.
1185 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1187 if (*stype == STACK_ZERO)
1189 if (env->allow_ptr_leaks && *stype == STACK_INVALID)
1191 *stype = STACK_MISC;
1194 static void scrub_spilled_slot(u8 *stype)
1196 if (*stype != STACK_INVALID)
1197 *stype = STACK_MISC;
1200 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1201 * small to hold src. This is different from krealloc since we don't want to preserve
1202 * the contents of dst.
1204 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1207 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1213 if (ZERO_OR_NULL_PTR(src))
1216 if (unlikely(check_mul_overflow(n, size, &bytes)))
1219 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1220 dst = krealloc(orig, alloc_bytes, flags);
1226 memcpy(dst, src, bytes);
1228 return dst ? dst : ZERO_SIZE_PTR;
1231 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1232 * small to hold new_n items. new items are zeroed out if the array grows.
1234 * Contrary to krealloc_array, does not free arr if new_n is zero.
1236 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1241 if (!new_n || old_n == new_n)
1244 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1245 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1253 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1256 return arr ? arr : ZERO_SIZE_PTR;
1259 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1261 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1262 sizeof(struct bpf_reference_state), GFP_KERNEL);
1266 dst->acquired_refs = src->acquired_refs;
1270 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1272 size_t n = src->allocated_stack / BPF_REG_SIZE;
1274 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1279 dst->allocated_stack = src->allocated_stack;
1283 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1285 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1286 sizeof(struct bpf_reference_state));
1290 state->acquired_refs = n;
1294 /* Possibly update state->allocated_stack to be at least size bytes. Also
1295 * possibly update the function's high-water mark in its bpf_subprog_info.
1297 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1299 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1301 /* The stack size is always a multiple of BPF_REG_SIZE. */
1302 size = round_up(size, BPF_REG_SIZE);
1303 n = size / BPF_REG_SIZE;
1308 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1312 state->allocated_stack = size;
1314 /* update known max for given subprogram */
1315 if (env->subprog_info[state->subprogno].stack_depth < size)
1316 env->subprog_info[state->subprogno].stack_depth = size;
1321 /* Acquire a pointer id from the env and update the state->refs to include
1322 * this new pointer reference.
1323 * On success, returns a valid pointer id to associate with the register
1324 * On failure, returns a negative errno.
1326 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1328 struct bpf_func_state *state = cur_func(env);
1329 int new_ofs = state->acquired_refs;
1332 err = resize_reference_state(state, state->acquired_refs + 1);
1336 state->refs[new_ofs].id = id;
1337 state->refs[new_ofs].insn_idx = insn_idx;
1338 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1343 /* release function corresponding to acquire_reference_state(). Idempotent. */
1344 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1348 last_idx = state->acquired_refs - 1;
1349 for (i = 0; i < state->acquired_refs; i++) {
1350 if (state->refs[i].id == ptr_id) {
1351 /* Cannot release caller references in callbacks */
1352 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1354 if (last_idx && i != last_idx)
1355 memcpy(&state->refs[i], &state->refs[last_idx],
1356 sizeof(*state->refs));
1357 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1358 state->acquired_refs--;
1365 static void free_func_state(struct bpf_func_state *state)
1370 kfree(state->stack);
1374 static void clear_jmp_history(struct bpf_verifier_state *state)
1376 kfree(state->jmp_history);
1377 state->jmp_history = NULL;
1378 state->jmp_history_cnt = 0;
1381 static void free_verifier_state(struct bpf_verifier_state *state,
1386 for (i = 0; i <= state->curframe; i++) {
1387 free_func_state(state->frame[i]);
1388 state->frame[i] = NULL;
1390 clear_jmp_history(state);
1395 /* copy verifier state from src to dst growing dst stack space
1396 * when necessary to accommodate larger src stack
1398 static int copy_func_state(struct bpf_func_state *dst,
1399 const struct bpf_func_state *src)
1403 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1404 err = copy_reference_state(dst, src);
1407 return copy_stack_state(dst, src);
1410 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1411 const struct bpf_verifier_state *src)
1413 struct bpf_func_state *dst;
1416 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1417 src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1419 if (!dst_state->jmp_history)
1421 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1423 /* if dst has more stack frames then src frame, free them, this is also
1424 * necessary in case of exceptional exits using bpf_throw.
1426 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1427 free_func_state(dst_state->frame[i]);
1428 dst_state->frame[i] = NULL;
1430 dst_state->speculative = src->speculative;
1431 dst_state->active_rcu_lock = src->active_rcu_lock;
1432 dst_state->curframe = src->curframe;
1433 dst_state->active_lock.ptr = src->active_lock.ptr;
1434 dst_state->active_lock.id = src->active_lock.id;
1435 dst_state->branches = src->branches;
1436 dst_state->parent = src->parent;
1437 dst_state->first_insn_idx = src->first_insn_idx;
1438 dst_state->last_insn_idx = src->last_insn_idx;
1439 dst_state->dfs_depth = src->dfs_depth;
1440 dst_state->callback_unroll_depth = src->callback_unroll_depth;
1441 dst_state->used_as_loop_entry = src->used_as_loop_entry;
1442 dst_state->may_goto_depth = src->may_goto_depth;
1443 for (i = 0; i <= src->curframe; i++) {
1444 dst = dst_state->frame[i];
1446 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1449 dst_state->frame[i] = dst;
1451 err = copy_func_state(dst, src->frame[i]);
1458 static u32 state_htab_size(struct bpf_verifier_env *env)
1460 return env->prog->len;
1463 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1465 struct bpf_verifier_state *cur = env->cur_state;
1466 struct bpf_func_state *state = cur->frame[cur->curframe];
1468 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1471 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1475 if (a->curframe != b->curframe)
1478 for (fr = a->curframe; fr >= 0; fr--)
1479 if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1485 /* Open coded iterators allow back-edges in the state graph in order to
1486 * check unbounded loops that iterators.
1488 * In is_state_visited() it is necessary to know if explored states are
1489 * part of some loops in order to decide whether non-exact states
1490 * comparison could be used:
1491 * - non-exact states comparison establishes sub-state relation and uses
1492 * read and precision marks to do so, these marks are propagated from
1493 * children states and thus are not guaranteed to be final in a loop;
1494 * - exact states comparison just checks if current and explored states
1495 * are identical (and thus form a back-edge).
1497 * Paper "A New Algorithm for Identifying Loops in Decompilation"
1498 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1499 * algorithm for loop structure detection and gives an overview of
1500 * relevant terminology. It also has helpful illustrations.
1502 * [1] https://api.semanticscholar.org/CorpusID:15784067
1504 * We use a similar algorithm but because loop nested structure is
1505 * irrelevant for verifier ours is significantly simpler and resembles
1506 * strongly connected components algorithm from Sedgewick's textbook.
1508 * Define topmost loop entry as a first node of the loop traversed in a
1509 * depth first search starting from initial state. The goal of the loop
1510 * tracking algorithm is to associate topmost loop entries with states
1511 * derived from these entries.
1513 * For each step in the DFS states traversal algorithm needs to identify
1514 * the following situations:
1516 * initial initial initial
1519 * ... ... .---------> hdr
1522 * cur .-> succ | .------...
1525 * succ '-- cur | ... ...
1535 * (A) successor state of cur (B) successor state of cur or it's entry
1536 * not yet traversed are in current DFS path, thus cur and succ
1537 * are members of the same outermost loop
1545 * .------... .------...
1548 * .-> hdr ... ... ...
1551 * | succ <- cur succ <- cur
1558 * (C) successor state of cur is a part of some loop but this loop
1559 * does not include cur or successor state is not in a loop at all.
1561 * Algorithm could be described as the following python code:
1563 * traversed = set() # Set of traversed nodes
1564 * entries = {} # Mapping from node to loop entry
1565 * depths = {} # Depth level assigned to graph node
1566 * path = set() # Current DFS path
1568 * # Find outermost loop entry known for n
1569 * def get_loop_entry(n):
1570 * h = entries.get(n, None)
1571 * while h in entries and entries[h] != h:
1575 * # Update n's loop entry if h's outermost entry comes
1576 * # before n's outermost entry in current DFS path.
1577 * def update_loop_entry(n, h):
1578 * n1 = get_loop_entry(n) or n
1579 * h1 = get_loop_entry(h) or h
1580 * if h1 in path and depths[h1] <= depths[n1]:
1583 * def dfs(n, depth):
1587 * for succ in G.successors(n):
1588 * if succ not in traversed:
1589 * # Case A: explore succ and update cur's loop entry
1590 * # only if succ's entry is in current DFS path.
1591 * dfs(succ, depth + 1)
1592 * h = get_loop_entry(succ)
1593 * update_loop_entry(n, h)
1595 * # Case B or C depending on `h1 in path` check in update_loop_entry().
1596 * update_loop_entry(n, succ)
1599 * To adapt this algorithm for use with verifier:
1600 * - use st->branch == 0 as a signal that DFS of succ had been finished
1601 * and cur's loop entry has to be updated (case A), handle this in
1602 * update_branch_counts();
1603 * - use st->branch > 0 as a signal that st is in the current DFS path;
1604 * - handle cases B and C in is_state_visited();
1605 * - update topmost loop entry for intermediate states in get_loop_entry().
1607 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1609 struct bpf_verifier_state *topmost = st->loop_entry, *old;
1611 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1612 topmost = topmost->loop_entry;
1613 /* Update loop entries for intermediate states to avoid this
1614 * traversal in future get_loop_entry() calls.
1616 while (st && st->loop_entry != topmost) {
1617 old = st->loop_entry;
1618 st->loop_entry = topmost;
1624 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1626 struct bpf_verifier_state *cur1, *hdr1;
1628 cur1 = get_loop_entry(cur) ?: cur;
1629 hdr1 = get_loop_entry(hdr) ?: hdr;
1630 /* The head1->branches check decides between cases B and C in
1631 * comment for get_loop_entry(). If hdr1->branches == 0 then
1632 * head's topmost loop entry is not in current DFS path,
1633 * hence 'cur' and 'hdr' are not in the same loop and there is
1634 * no need to update cur->loop_entry.
1636 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1637 cur->loop_entry = hdr;
1638 hdr->used_as_loop_entry = true;
1642 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1645 u32 br = --st->branches;
1647 /* br == 0 signals that DFS exploration for 'st' is finished,
1648 * thus it is necessary to update parent's loop entry if it
1649 * turned out that st is a part of some loop.
1650 * This is a part of 'case A' in get_loop_entry() comment.
1652 if (br == 0 && st->parent && st->loop_entry)
1653 update_loop_entry(st->parent, st->loop_entry);
1655 /* WARN_ON(br > 1) technically makes sense here,
1656 * but see comment in push_stack(), hence:
1658 WARN_ONCE((int)br < 0,
1659 "BUG update_branch_counts:branches_to_explore=%d\n",
1667 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1668 int *insn_idx, bool pop_log)
1670 struct bpf_verifier_state *cur = env->cur_state;
1671 struct bpf_verifier_stack_elem *elem, *head = env->head;
1674 if (env->head == NULL)
1678 err = copy_verifier_state(cur, &head->st);
1683 bpf_vlog_reset(&env->log, head->log_pos);
1685 *insn_idx = head->insn_idx;
1687 *prev_insn_idx = head->prev_insn_idx;
1689 free_verifier_state(&head->st, false);
1696 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1697 int insn_idx, int prev_insn_idx,
1700 struct bpf_verifier_state *cur = env->cur_state;
1701 struct bpf_verifier_stack_elem *elem;
1704 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1708 elem->insn_idx = insn_idx;
1709 elem->prev_insn_idx = prev_insn_idx;
1710 elem->next = env->head;
1711 elem->log_pos = env->log.end_pos;
1714 err = copy_verifier_state(&elem->st, cur);
1717 elem->st.speculative |= speculative;
1718 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1719 verbose(env, "The sequence of %d jumps is too complex.\n",
1723 if (elem->st.parent) {
1724 ++elem->st.parent->branches;
1725 /* WARN_ON(branches > 2) technically makes sense here,
1727 * 1. speculative states will bump 'branches' for non-branch
1729 * 2. is_state_visited() heuristics may decide not to create
1730 * a new state for a sequence of branches and all such current
1731 * and cloned states will be pointing to a single parent state
1732 * which might have large 'branches' count.
1737 free_verifier_state(env->cur_state, true);
1738 env->cur_state = NULL;
1739 /* pop all elements and return */
1740 while (!pop_stack(env, NULL, NULL, false));
1744 #define CALLER_SAVED_REGS 6
1745 static const int caller_saved[CALLER_SAVED_REGS] = {
1746 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1749 /* This helper doesn't clear reg->id */
1750 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1752 reg->var_off = tnum_const(imm);
1753 reg->smin_value = (s64)imm;
1754 reg->smax_value = (s64)imm;
1755 reg->umin_value = imm;
1756 reg->umax_value = 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 unknown part of a register (variable offset or scalar value) as
1765 * known to have the value @imm.
1767 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1769 /* Clear off and union(map_ptr, range) */
1770 memset(((u8 *)reg) + sizeof(reg->type), 0,
1771 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1773 reg->ref_obj_id = 0;
1774 ___mark_reg_known(reg, imm);
1777 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1779 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1780 reg->s32_min_value = (s32)imm;
1781 reg->s32_max_value = (s32)imm;
1782 reg->u32_min_value = (u32)imm;
1783 reg->u32_max_value = (u32)imm;
1786 /* Mark the 'variable offset' part of a register as zero. This should be
1787 * used only on registers holding a pointer type.
1789 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1791 __mark_reg_known(reg, 0);
1794 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1796 __mark_reg_known(reg, 0);
1797 reg->type = SCALAR_VALUE;
1798 /* all scalars are assumed imprecise initially (unless unprivileged,
1799 * in which case everything is forced to be precise)
1801 reg->precise = !env->bpf_capable;
1804 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1805 struct bpf_reg_state *regs, u32 regno)
1807 if (WARN_ON(regno >= MAX_BPF_REG)) {
1808 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1809 /* Something bad happened, let's kill all regs */
1810 for (regno = 0; regno < MAX_BPF_REG; regno++)
1811 __mark_reg_not_init(env, regs + regno);
1814 __mark_reg_known_zero(regs + regno);
1817 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1818 bool first_slot, int dynptr_id)
1820 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1821 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1822 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1824 __mark_reg_known_zero(reg);
1825 reg->type = CONST_PTR_TO_DYNPTR;
1826 /* Give each dynptr a unique id to uniquely associate slices to it. */
1827 reg->id = dynptr_id;
1828 reg->dynptr.type = type;
1829 reg->dynptr.first_slot = first_slot;
1832 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1834 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1835 const struct bpf_map *map = reg->map_ptr;
1837 if (map->inner_map_meta) {
1838 reg->type = CONST_PTR_TO_MAP;
1839 reg->map_ptr = map->inner_map_meta;
1840 /* transfer reg's id which is unique for every map_lookup_elem
1841 * as UID of the inner map.
1843 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1844 reg->map_uid = reg->id;
1845 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1846 reg->type = PTR_TO_XDP_SOCK;
1847 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1848 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1849 reg->type = PTR_TO_SOCKET;
1851 reg->type = PTR_TO_MAP_VALUE;
1856 reg->type &= ~PTR_MAYBE_NULL;
1859 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1860 struct btf_field_graph_root *ds_head)
1862 __mark_reg_known_zero(®s[regno]);
1863 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1864 regs[regno].btf = ds_head->btf;
1865 regs[regno].btf_id = ds_head->value_btf_id;
1866 regs[regno].off = ds_head->node_offset;
1869 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1871 return type_is_pkt_pointer(reg->type);
1874 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1876 return reg_is_pkt_pointer(reg) ||
1877 reg->type == PTR_TO_PACKET_END;
1880 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1882 return base_type(reg->type) == PTR_TO_MEM &&
1883 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1886 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1887 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1888 enum bpf_reg_type which)
1890 /* The register can already have a range from prior markings.
1891 * This is fine as long as it hasn't been advanced from its
1894 return reg->type == which &&
1897 tnum_equals_const(reg->var_off, 0);
1900 /* Reset the min/max bounds of a register */
1901 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1903 reg->smin_value = S64_MIN;
1904 reg->smax_value = S64_MAX;
1905 reg->umin_value = 0;
1906 reg->umax_value = U64_MAX;
1908 reg->s32_min_value = S32_MIN;
1909 reg->s32_max_value = S32_MAX;
1910 reg->u32_min_value = 0;
1911 reg->u32_max_value = U32_MAX;
1914 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1916 reg->smin_value = S64_MIN;
1917 reg->smax_value = S64_MAX;
1918 reg->umin_value = 0;
1919 reg->umax_value = U64_MAX;
1922 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1924 reg->s32_min_value = S32_MIN;
1925 reg->s32_max_value = S32_MAX;
1926 reg->u32_min_value = 0;
1927 reg->u32_max_value = U32_MAX;
1930 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1932 struct tnum var32_off = tnum_subreg(reg->var_off);
1934 /* min signed is max(sign bit) | min(other bits) */
1935 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1936 var32_off.value | (var32_off.mask & S32_MIN));
1937 /* max signed is min(sign bit) | max(other bits) */
1938 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1939 var32_off.value | (var32_off.mask & S32_MAX));
1940 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1941 reg->u32_max_value = min(reg->u32_max_value,
1942 (u32)(var32_off.value | var32_off.mask));
1945 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1947 /* min signed is max(sign bit) | min(other bits) */
1948 reg->smin_value = max_t(s64, reg->smin_value,
1949 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1950 /* max signed is min(sign bit) | max(other bits) */
1951 reg->smax_value = min_t(s64, reg->smax_value,
1952 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1953 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1954 reg->umax_value = min(reg->umax_value,
1955 reg->var_off.value | reg->var_off.mask);
1958 static void __update_reg_bounds(struct bpf_reg_state *reg)
1960 __update_reg32_bounds(reg);
1961 __update_reg64_bounds(reg);
1964 /* Uses signed min/max values to inform unsigned, and vice-versa */
1965 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1967 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32
1968 * bits to improve our u32/s32 boundaries.
1970 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
1971 * u64) is pretty trivial, it's obvious that in u32 we'll also have
1972 * [10, 20] range. But this property holds for any 64-bit range as
1973 * long as upper 32 bits in that entire range of values stay the same.
1975 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
1976 * in decimal) has the same upper 32 bits throughout all the values in
1977 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
1980 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
1981 * following the rules outlined below about u64/s64 correspondence
1982 * (which equally applies to u32 vs s32 correspondence). In general it
1983 * depends on actual hexadecimal values of 32-bit range. They can form
1984 * only valid u32, or only valid s32 ranges in some cases.
1986 * So we use all these insights to derive bounds for subregisters here.
1988 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
1989 /* u64 to u32 casting preserves validity of low 32 bits as
1990 * a range, if upper 32 bits are the same
1992 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
1993 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
1995 if ((s32)reg->umin_value <= (s32)reg->umax_value) {
1996 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
1997 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2000 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2001 /* low 32 bits should form a proper u32 range */
2002 if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2003 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2004 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2006 /* low 32 bits should form a proper s32 range */
2007 if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2008 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2009 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2012 /* Special case where upper bits form a small sequence of two
2013 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2014 * 0x00000000 is also valid), while lower bits form a proper s32 range
2015 * going from negative numbers to positive numbers. E.g., let's say we
2016 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2017 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2018 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2019 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2020 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2021 * upper 32 bits. As a random example, s64 range
2022 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2023 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2025 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2026 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2027 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2028 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2030 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2031 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2032 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2033 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2035 /* if u32 range forms a valid s32 range (due to matching sign bit),
2036 * try to learn from that
2038 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2039 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2040 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2042 /* If we cannot cross the sign boundary, then signed and unsigned bounds
2043 * are the same, so combine. This works even in the negative case, e.g.
2044 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2046 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2047 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2048 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2052 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2054 /* If u64 range forms a valid s64 range (due to matching sign bit),
2055 * try to learn from that. Let's do a bit of ASCII art to see when
2056 * this is happening. Let's take u64 range first:
2058 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
2059 * |-------------------------------|--------------------------------|
2061 * Valid u64 range is formed when umin and umax are anywhere in the
2062 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2063 * straightforward. Let's see how s64 range maps onto the same range
2064 * of values, annotated below the line for comparison:
2066 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
2067 * |-------------------------------|--------------------------------|
2068 * 0 S64_MAX S64_MIN -1
2070 * So s64 values basically start in the middle and they are logically
2071 * contiguous to the right of it, wrapping around from -1 to 0, and
2072 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2073 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2074 * more visually as mapped to sign-agnostic range of hex values.
2077 * _______________________________________________________________
2079 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
2080 * |-------------------------------|--------------------------------|
2081 * 0 S64_MAX S64_MIN -1
2083 * >------------------------------ ------------------------------->
2084 * s64 continues... s64 end s64 start s64 "midpoint"
2086 * What this means is that, in general, we can't always derive
2087 * something new about u64 from any random s64 range, and vice versa.
2089 * But we can do that in two particular cases. One is when entire
2090 * u64/s64 range is *entirely* contained within left half of the above
2091 * diagram or when it is *entirely* contained in the right half. I.e.:
2093 * |-------------------------------|--------------------------------|
2097 * [A, B] and [C, D] are contained entirely in their respective halves
2098 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2099 * will be non-negative both as u64 and s64 (and in fact it will be
2100 * identical ranges no matter the signedness). [C, D] treated as s64
2101 * will be a range of negative values, while in u64 it will be
2102 * non-negative range of values larger than 0x8000000000000000.
2104 * Now, any other range here can't be represented in both u64 and s64
2105 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2106 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2107 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2108 * for example. Similarly, valid s64 range [D, A] (going from negative
2109 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2110 * ranges as u64. Currently reg_state can't represent two segments per
2111 * numeric domain, so in such situations we can only derive maximal
2112 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2114 * So we use these facts to derive umin/umax from smin/smax and vice
2115 * versa only if they stay within the same "half". This is equivalent
2116 * to checking sign bit: lower half will have sign bit as zero, upper
2117 * half have sign bit 1. Below in code we simplify this by just
2118 * casting umin/umax as smin/smax and checking if they form valid
2119 * range, and vice versa. Those are equivalent checks.
2121 if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2122 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2123 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2125 /* If we cannot cross the sign boundary, then signed and unsigned bounds
2126 * are the same, so combine. This works even in the negative case, e.g.
2127 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2129 if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2130 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2131 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2135 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2137 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2138 * values on both sides of 64-bit range in hope to have tigher range.
2139 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2140 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2141 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2142 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2143 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2144 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2145 * We just need to make sure that derived bounds we are intersecting
2146 * with are well-formed ranges in respecitve s64 or u64 domain, just
2147 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2149 __u64 new_umin, new_umax;
2150 __s64 new_smin, new_smax;
2152 /* u32 -> u64 tightening, it's always well-formed */
2153 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2154 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2155 reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2156 reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2157 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2158 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2159 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2160 reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2161 reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2163 /* if s32 can be treated as valid u32 range, we can use it as well */
2164 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2165 /* s32 -> u64 tightening */
2166 new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2167 new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2168 reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2169 reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2170 /* s32 -> s64 tightening */
2171 new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2172 new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2173 reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2174 reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2178 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2180 __reg32_deduce_bounds(reg);
2181 __reg64_deduce_bounds(reg);
2182 __reg_deduce_mixed_bounds(reg);
2185 /* Attempts to improve var_off based on unsigned min/max information */
2186 static void __reg_bound_offset(struct bpf_reg_state *reg)
2188 struct tnum var64_off = tnum_intersect(reg->var_off,
2189 tnum_range(reg->umin_value,
2191 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2192 tnum_range(reg->u32_min_value,
2193 reg->u32_max_value));
2195 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2198 static void reg_bounds_sync(struct bpf_reg_state *reg)
2200 /* We might have learned new bounds from the var_off. */
2201 __update_reg_bounds(reg);
2202 /* We might have learned something about the sign bit. */
2203 __reg_deduce_bounds(reg);
2204 __reg_deduce_bounds(reg);
2205 /* We might have learned some bits from the bounds. */
2206 __reg_bound_offset(reg);
2207 /* Intersecting with the old var_off might have improved our bounds
2208 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2209 * then new var_off is (0; 0x7f...fc) which improves our umax.
2211 __update_reg_bounds(reg);
2214 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2215 struct bpf_reg_state *reg, const char *ctx)
2219 if (reg->umin_value > reg->umax_value ||
2220 reg->smin_value > reg->smax_value ||
2221 reg->u32_min_value > reg->u32_max_value ||
2222 reg->s32_min_value > reg->s32_max_value) {
2223 msg = "range bounds violation";
2227 if (tnum_is_const(reg->var_off)) {
2228 u64 uval = reg->var_off.value;
2229 s64 sval = (s64)uval;
2231 if (reg->umin_value != uval || reg->umax_value != uval ||
2232 reg->smin_value != sval || reg->smax_value != sval) {
2233 msg = "const tnum out of sync with range bounds";
2238 if (tnum_subreg_is_const(reg->var_off)) {
2239 u32 uval32 = tnum_subreg(reg->var_off).value;
2240 s32 sval32 = (s32)uval32;
2242 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2243 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2244 msg = "const subreg tnum out of sync with range bounds";
2251 verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2252 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2253 ctx, msg, reg->umin_value, reg->umax_value,
2254 reg->smin_value, reg->smax_value,
2255 reg->u32_min_value, reg->u32_max_value,
2256 reg->s32_min_value, reg->s32_max_value,
2257 reg->var_off.value, reg->var_off.mask);
2258 if (env->test_reg_invariants)
2260 __mark_reg_unbounded(reg);
2264 static bool __reg32_bound_s64(s32 a)
2266 return a >= 0 && a <= S32_MAX;
2269 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2271 reg->umin_value = reg->u32_min_value;
2272 reg->umax_value = reg->u32_max_value;
2274 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2275 * be positive otherwise set to worse case bounds and refine later
2278 if (__reg32_bound_s64(reg->s32_min_value) &&
2279 __reg32_bound_s64(reg->s32_max_value)) {
2280 reg->smin_value = reg->s32_min_value;
2281 reg->smax_value = reg->s32_max_value;
2283 reg->smin_value = 0;
2284 reg->smax_value = U32_MAX;
2288 /* Mark a register as having a completely unknown (scalar) value. */
2289 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2292 * Clear type, off, and union(map_ptr, range) and
2293 * padding between 'type' and union
2295 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2296 reg->type = SCALAR_VALUE;
2298 reg->ref_obj_id = 0;
2299 reg->var_off = tnum_unknown;
2301 reg->precise = false;
2302 __mark_reg_unbounded(reg);
2305 /* Mark a register as having a completely unknown (scalar) value,
2306 * initialize .precise as true when not bpf capable.
2308 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2309 struct bpf_reg_state *reg)
2311 __mark_reg_unknown_imprecise(reg);
2312 reg->precise = !env->bpf_capable;
2315 static void mark_reg_unknown(struct bpf_verifier_env *env,
2316 struct bpf_reg_state *regs, u32 regno)
2318 if (WARN_ON(regno >= MAX_BPF_REG)) {
2319 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2320 /* Something bad happened, let's kill all regs except FP */
2321 for (regno = 0; regno < BPF_REG_FP; regno++)
2322 __mark_reg_not_init(env, regs + regno);
2325 __mark_reg_unknown(env, regs + regno);
2328 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2329 struct bpf_reg_state *reg)
2331 __mark_reg_unknown(env, reg);
2332 reg->type = NOT_INIT;
2335 static void mark_reg_not_init(struct bpf_verifier_env *env,
2336 struct bpf_reg_state *regs, u32 regno)
2338 if (WARN_ON(regno >= MAX_BPF_REG)) {
2339 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2340 /* Something bad happened, let's kill all regs except FP */
2341 for (regno = 0; regno < BPF_REG_FP; regno++)
2342 __mark_reg_not_init(env, regs + regno);
2345 __mark_reg_not_init(env, regs + regno);
2348 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2349 struct bpf_reg_state *regs, u32 regno,
2350 enum bpf_reg_type reg_type,
2351 struct btf *btf, u32 btf_id,
2352 enum bpf_type_flag flag)
2354 if (reg_type == SCALAR_VALUE) {
2355 mark_reg_unknown(env, regs, regno);
2358 mark_reg_known_zero(env, regs, regno);
2359 regs[regno].type = PTR_TO_BTF_ID | flag;
2360 regs[regno].btf = btf;
2361 regs[regno].btf_id = btf_id;
2364 #define DEF_NOT_SUBREG (0)
2365 static void init_reg_state(struct bpf_verifier_env *env,
2366 struct bpf_func_state *state)
2368 struct bpf_reg_state *regs = state->regs;
2371 for (i = 0; i < MAX_BPF_REG; i++) {
2372 mark_reg_not_init(env, regs, i);
2373 regs[i].live = REG_LIVE_NONE;
2374 regs[i].parent = NULL;
2375 regs[i].subreg_def = DEF_NOT_SUBREG;
2379 regs[BPF_REG_FP].type = PTR_TO_STACK;
2380 mark_reg_known_zero(env, regs, BPF_REG_FP);
2381 regs[BPF_REG_FP].frameno = state->frameno;
2384 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2386 return (struct bpf_retval_range){ minval, maxval };
2389 #define BPF_MAIN_FUNC (-1)
2390 static void init_func_state(struct bpf_verifier_env *env,
2391 struct bpf_func_state *state,
2392 int callsite, int frameno, int subprogno)
2394 state->callsite = callsite;
2395 state->frameno = frameno;
2396 state->subprogno = subprogno;
2397 state->callback_ret_range = retval_range(0, 0);
2398 init_reg_state(env, state);
2399 mark_verifier_state_scratched(env);
2402 /* Similar to push_stack(), but for async callbacks */
2403 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2404 int insn_idx, int prev_insn_idx,
2407 struct bpf_verifier_stack_elem *elem;
2408 struct bpf_func_state *frame;
2410 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2414 elem->insn_idx = insn_idx;
2415 elem->prev_insn_idx = prev_insn_idx;
2416 elem->next = env->head;
2417 elem->log_pos = env->log.end_pos;
2420 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2422 "The sequence of %d jumps is too complex for async cb.\n",
2426 /* Unlike push_stack() do not copy_verifier_state().
2427 * The caller state doesn't matter.
2428 * This is async callback. It starts in a fresh stack.
2429 * Initialize it similar to do_check_common().
2431 elem->st.branches = 1;
2432 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2435 init_func_state(env, frame,
2436 BPF_MAIN_FUNC /* callsite */,
2437 0 /* frameno within this callchain */,
2438 subprog /* subprog number within this prog */);
2439 elem->st.frame[0] = frame;
2442 free_verifier_state(env->cur_state, true);
2443 env->cur_state = NULL;
2444 /* pop all elements and return */
2445 while (!pop_stack(env, NULL, NULL, false));
2451 SRC_OP, /* register is used as source operand */
2452 DST_OP, /* register is used as destination operand */
2453 DST_OP_NO_MARK /* same as above, check only, don't mark */
2456 static int cmp_subprogs(const void *a, const void *b)
2458 return ((struct bpf_subprog_info *)a)->start -
2459 ((struct bpf_subprog_info *)b)->start;
2462 static int find_subprog(struct bpf_verifier_env *env, int off)
2464 struct bpf_subprog_info *p;
2466 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2467 sizeof(env->subprog_info[0]), cmp_subprogs);
2470 return p - env->subprog_info;
2474 static int add_subprog(struct bpf_verifier_env *env, int off)
2476 int insn_cnt = env->prog->len;
2479 if (off >= insn_cnt || off < 0) {
2480 verbose(env, "call to invalid destination\n");
2483 ret = find_subprog(env, off);
2486 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2487 verbose(env, "too many subprograms\n");
2490 /* determine subprog starts. The end is one before the next starts */
2491 env->subprog_info[env->subprog_cnt++].start = off;
2492 sort(env->subprog_info, env->subprog_cnt,
2493 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2494 return env->subprog_cnt - 1;
2497 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2499 struct bpf_prog_aux *aux = env->prog->aux;
2500 struct btf *btf = aux->btf;
2501 const struct btf_type *t;
2502 u32 main_btf_id, id;
2506 /* Non-zero func_info_cnt implies valid btf */
2507 if (!aux->func_info_cnt)
2509 main_btf_id = aux->func_info[0].type_id;
2511 t = btf_type_by_id(btf, main_btf_id);
2513 verbose(env, "invalid btf id for main subprog in func_info\n");
2517 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2519 ret = PTR_ERR(name);
2520 /* If there is no tag present, there is no exception callback */
2523 else if (ret == -EEXIST)
2524 verbose(env, "multiple exception callback tags for main subprog\n");
2528 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2530 verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2534 t = btf_type_by_id(btf, id);
2535 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2536 verbose(env, "exception callback '%s' must have global linkage\n", name);
2540 for (i = 0; i < aux->func_info_cnt; i++) {
2541 if (aux->func_info[i].type_id != id)
2543 ret = aux->func_info[i].insn_off;
2544 /* Further func_info and subprog checks will also happen
2545 * later, so assume this is the right insn_off for now.
2548 verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2553 verbose(env, "exception callback type id not found in func_info\n");
2559 #define MAX_KFUNC_DESCS 256
2560 #define MAX_KFUNC_BTFS 256
2562 struct bpf_kfunc_desc {
2563 struct btf_func_model func_model;
2570 struct bpf_kfunc_btf {
2572 struct module *module;
2576 struct bpf_kfunc_desc_tab {
2577 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2578 * verification. JITs do lookups by bpf_insn, where func_id may not be
2579 * available, therefore at the end of verification do_misc_fixups()
2580 * sorts this by imm and offset.
2582 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2586 struct bpf_kfunc_btf_tab {
2587 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2591 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2593 const struct bpf_kfunc_desc *d0 = a;
2594 const struct bpf_kfunc_desc *d1 = b;
2596 /* func_id is not greater than BTF_MAX_TYPE */
2597 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2600 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2602 const struct bpf_kfunc_btf *d0 = a;
2603 const struct bpf_kfunc_btf *d1 = b;
2605 return d0->offset - d1->offset;
2608 static const struct bpf_kfunc_desc *
2609 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2611 struct bpf_kfunc_desc desc = {
2615 struct bpf_kfunc_desc_tab *tab;
2617 tab = prog->aux->kfunc_tab;
2618 return bsearch(&desc, tab->descs, tab->nr_descs,
2619 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2622 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2623 u16 btf_fd_idx, u8 **func_addr)
2625 const struct bpf_kfunc_desc *desc;
2627 desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2631 *func_addr = (u8 *)desc->addr;
2635 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2638 struct bpf_kfunc_btf kf_btf = { .offset = offset };
2639 struct bpf_kfunc_btf_tab *tab;
2640 struct bpf_kfunc_btf *b;
2645 tab = env->prog->aux->kfunc_btf_tab;
2646 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2647 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2649 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2650 verbose(env, "too many different module BTFs\n");
2651 return ERR_PTR(-E2BIG);
2654 if (bpfptr_is_null(env->fd_array)) {
2655 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2656 return ERR_PTR(-EPROTO);
2659 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2660 offset * sizeof(btf_fd),
2662 return ERR_PTR(-EFAULT);
2664 btf = btf_get_by_fd(btf_fd);
2666 verbose(env, "invalid module BTF fd specified\n");
2670 if (!btf_is_module(btf)) {
2671 verbose(env, "BTF fd for kfunc is not a module BTF\n");
2673 return ERR_PTR(-EINVAL);
2676 mod = btf_try_get_module(btf);
2679 return ERR_PTR(-ENXIO);
2682 b = &tab->descs[tab->nr_descs++];
2687 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2688 kfunc_btf_cmp_by_off, NULL);
2693 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2698 while (tab->nr_descs--) {
2699 module_put(tab->descs[tab->nr_descs].module);
2700 btf_put(tab->descs[tab->nr_descs].btf);
2705 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2709 /* In the future, this can be allowed to increase limit
2710 * of fd index into fd_array, interpreted as u16.
2712 verbose(env, "negative offset disallowed for kernel module function call\n");
2713 return ERR_PTR(-EINVAL);
2716 return __find_kfunc_desc_btf(env, offset);
2718 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2721 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2723 const struct btf_type *func, *func_proto;
2724 struct bpf_kfunc_btf_tab *btf_tab;
2725 struct bpf_kfunc_desc_tab *tab;
2726 struct bpf_prog_aux *prog_aux;
2727 struct bpf_kfunc_desc *desc;
2728 const char *func_name;
2729 struct btf *desc_btf;
2730 unsigned long call_imm;
2734 prog_aux = env->prog->aux;
2735 tab = prog_aux->kfunc_tab;
2736 btf_tab = prog_aux->kfunc_btf_tab;
2739 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2743 if (!env->prog->jit_requested) {
2744 verbose(env, "JIT is required for calling kernel function\n");
2748 if (!bpf_jit_supports_kfunc_call()) {
2749 verbose(env, "JIT does not support calling kernel function\n");
2753 if (!env->prog->gpl_compatible) {
2754 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2758 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2761 prog_aux->kfunc_tab = tab;
2764 /* func_id == 0 is always invalid, but instead of returning an error, be
2765 * conservative and wait until the code elimination pass before returning
2766 * error, so that invalid calls that get pruned out can be in BPF programs
2767 * loaded from userspace. It is also required that offset be untouched
2770 if (!func_id && !offset)
2773 if (!btf_tab && offset) {
2774 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2777 prog_aux->kfunc_btf_tab = btf_tab;
2780 desc_btf = find_kfunc_desc_btf(env, offset);
2781 if (IS_ERR(desc_btf)) {
2782 verbose(env, "failed to find BTF for kernel function\n");
2783 return PTR_ERR(desc_btf);
2786 if (find_kfunc_desc(env->prog, func_id, offset))
2789 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2790 verbose(env, "too many different kernel function calls\n");
2794 func = btf_type_by_id(desc_btf, func_id);
2795 if (!func || !btf_type_is_func(func)) {
2796 verbose(env, "kernel btf_id %u is not a function\n",
2800 func_proto = btf_type_by_id(desc_btf, func->type);
2801 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2802 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2807 func_name = btf_name_by_offset(desc_btf, func->name_off);
2808 addr = kallsyms_lookup_name(func_name);
2810 verbose(env, "cannot find address for kernel function %s\n",
2814 specialize_kfunc(env, func_id, offset, &addr);
2816 if (bpf_jit_supports_far_kfunc_call()) {
2819 call_imm = BPF_CALL_IMM(addr);
2820 /* Check whether the relative offset overflows desc->imm */
2821 if ((unsigned long)(s32)call_imm != call_imm) {
2822 verbose(env, "address of kernel function %s is out of range\n",
2828 if (bpf_dev_bound_kfunc_id(func_id)) {
2829 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2834 desc = &tab->descs[tab->nr_descs++];
2835 desc->func_id = func_id;
2836 desc->imm = call_imm;
2837 desc->offset = offset;
2839 err = btf_distill_func_proto(&env->log, desc_btf,
2840 func_proto, func_name,
2843 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2844 kfunc_desc_cmp_by_id_off, NULL);
2848 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2850 const struct bpf_kfunc_desc *d0 = a;
2851 const struct bpf_kfunc_desc *d1 = b;
2853 if (d0->imm != d1->imm)
2854 return d0->imm < d1->imm ? -1 : 1;
2855 if (d0->offset != d1->offset)
2856 return d0->offset < d1->offset ? -1 : 1;
2860 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2862 struct bpf_kfunc_desc_tab *tab;
2864 tab = prog->aux->kfunc_tab;
2868 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2869 kfunc_desc_cmp_by_imm_off, NULL);
2872 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2874 return !!prog->aux->kfunc_tab;
2877 const struct btf_func_model *
2878 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2879 const struct bpf_insn *insn)
2881 const struct bpf_kfunc_desc desc = {
2883 .offset = insn->off,
2885 const struct bpf_kfunc_desc *res;
2886 struct bpf_kfunc_desc_tab *tab;
2888 tab = prog->aux->kfunc_tab;
2889 res = bsearch(&desc, tab->descs, tab->nr_descs,
2890 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2892 return res ? &res->func_model : NULL;
2895 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2897 struct bpf_subprog_info *subprog = env->subprog_info;
2898 int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2899 struct bpf_insn *insn = env->prog->insnsi;
2901 /* Add entry function. */
2902 ret = add_subprog(env, 0);
2906 for (i = 0; i < insn_cnt; i++, insn++) {
2907 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2908 !bpf_pseudo_kfunc_call(insn))
2911 if (!env->bpf_capable) {
2912 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2916 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2917 ret = add_subprog(env, i + insn->imm + 1);
2919 ret = add_kfunc_call(env, insn->imm, insn->off);
2925 ret = bpf_find_exception_callback_insn_off(env);
2930 /* If ex_cb_insn > 0, this means that the main program has a subprog
2931 * marked using BTF decl tag to serve as the exception callback.
2934 ret = add_subprog(env, ex_cb_insn);
2937 for (i = 1; i < env->subprog_cnt; i++) {
2938 if (env->subprog_info[i].start != ex_cb_insn)
2940 env->exception_callback_subprog = i;
2941 mark_subprog_exc_cb(env, i);
2946 /* Add a fake 'exit' subprog which could simplify subprog iteration
2947 * logic. 'subprog_cnt' should not be increased.
2949 subprog[env->subprog_cnt].start = insn_cnt;
2951 if (env->log.level & BPF_LOG_LEVEL2)
2952 for (i = 0; i < env->subprog_cnt; i++)
2953 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2958 static int check_subprogs(struct bpf_verifier_env *env)
2960 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2961 struct bpf_subprog_info *subprog = env->subprog_info;
2962 struct bpf_insn *insn = env->prog->insnsi;
2963 int insn_cnt = env->prog->len;
2965 /* now check that all jumps are within the same subprog */
2966 subprog_start = subprog[cur_subprog].start;
2967 subprog_end = subprog[cur_subprog + 1].start;
2968 for (i = 0; i < insn_cnt; i++) {
2969 u8 code = insn[i].code;
2971 if (code == (BPF_JMP | BPF_CALL) &&
2972 insn[i].src_reg == 0 &&
2973 insn[i].imm == BPF_FUNC_tail_call)
2974 subprog[cur_subprog].has_tail_call = true;
2975 if (BPF_CLASS(code) == BPF_LD &&
2976 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2977 subprog[cur_subprog].has_ld_abs = true;
2978 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2980 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2982 if (code == (BPF_JMP32 | BPF_JA))
2983 off = i + insn[i].imm + 1;
2985 off = i + insn[i].off + 1;
2986 if (off < subprog_start || off >= subprog_end) {
2987 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2991 if (i == subprog_end - 1) {
2992 /* to avoid fall-through from one subprog into another
2993 * the last insn of the subprog should be either exit
2994 * or unconditional jump back or bpf_throw call
2996 if (code != (BPF_JMP | BPF_EXIT) &&
2997 code != (BPF_JMP32 | BPF_JA) &&
2998 code != (BPF_JMP | BPF_JA)) {
2999 verbose(env, "last insn is not an exit or jmp\n");
3002 subprog_start = subprog_end;
3004 if (cur_subprog < env->subprog_cnt)
3005 subprog_end = subprog[cur_subprog + 1].start;
3011 /* Parentage chain of this register (or stack slot) should take care of all
3012 * issues like callee-saved registers, stack slot allocation time, etc.
3014 static int mark_reg_read(struct bpf_verifier_env *env,
3015 const struct bpf_reg_state *state,
3016 struct bpf_reg_state *parent, u8 flag)
3018 bool writes = parent == state->parent; /* Observe write marks */
3022 /* if read wasn't screened by an earlier write ... */
3023 if (writes && state->live & REG_LIVE_WRITTEN)
3025 if (parent->live & REG_LIVE_DONE) {
3026 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3027 reg_type_str(env, parent->type),
3028 parent->var_off.value, parent->off);
3031 /* The first condition is more likely to be true than the
3032 * second, checked it first.
3034 if ((parent->live & REG_LIVE_READ) == flag ||
3035 parent->live & REG_LIVE_READ64)
3036 /* The parentage chain never changes and
3037 * this parent was already marked as LIVE_READ.
3038 * There is no need to keep walking the chain again and
3039 * keep re-marking all parents as LIVE_READ.
3040 * This case happens when the same register is read
3041 * multiple times without writes into it in-between.
3042 * Also, if parent has the stronger REG_LIVE_READ64 set,
3043 * then no need to set the weak REG_LIVE_READ32.
3046 /* ... then we depend on parent's value */
3047 parent->live |= flag;
3048 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3049 if (flag == REG_LIVE_READ64)
3050 parent->live &= ~REG_LIVE_READ32;
3052 parent = state->parent;
3057 if (env->longest_mark_read_walk < cnt)
3058 env->longest_mark_read_walk = cnt;
3062 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3064 struct bpf_func_state *state = func(env, reg);
3067 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
3068 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3071 if (reg->type == CONST_PTR_TO_DYNPTR)
3073 spi = dynptr_get_spi(env, reg);
3076 /* Caller ensures dynptr is valid and initialized, which means spi is in
3077 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3080 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3081 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3084 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3085 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3088 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3089 int spi, int nr_slots)
3091 struct bpf_func_state *state = func(env, reg);
3094 for (i = 0; i < nr_slots; i++) {
3095 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3097 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3101 mark_stack_slot_scratched(env, spi - i);
3107 /* This function is supposed to be used by the following 32-bit optimization
3108 * code only. It returns TRUE if the source or destination register operates
3109 * on 64-bit, otherwise return FALSE.
3111 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3112 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3117 class = BPF_CLASS(code);
3119 if (class == BPF_JMP) {
3120 /* BPF_EXIT for "main" will reach here. Return TRUE
3125 if (op == BPF_CALL) {
3126 /* BPF to BPF call will reach here because of marking
3127 * caller saved clobber with DST_OP_NO_MARK for which we
3128 * don't care the register def because they are anyway
3129 * marked as NOT_INIT already.
3131 if (insn->src_reg == BPF_PSEUDO_CALL)
3133 /* Helper call will reach here because of arg type
3134 * check, conservatively return TRUE.
3143 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3146 if (class == BPF_ALU64 || class == BPF_JMP ||
3147 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3150 if (class == BPF_ALU || class == BPF_JMP32)
3153 if (class == BPF_LDX) {
3155 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3156 /* LDX source must be ptr. */
3160 if (class == BPF_STX) {
3161 /* BPF_STX (including atomic variants) has multiple source
3162 * operands, one of which is a ptr. Check whether the caller is
3165 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3167 return BPF_SIZE(code) == BPF_DW;
3170 if (class == BPF_LD) {
3171 u8 mode = BPF_MODE(code);
3174 if (mode == BPF_IMM)
3177 /* Both LD_IND and LD_ABS return 32-bit data. */
3181 /* Implicit ctx ptr. */
3182 if (regno == BPF_REG_6)
3185 /* Explicit source could be any width. */
3189 if (class == BPF_ST)
3190 /* The only source register for BPF_ST is a ptr. */
3193 /* Conservatively return true at default. */
3197 /* Return the regno defined by the insn, or -1. */
3198 static int insn_def_regno(const struct bpf_insn *insn)
3200 switch (BPF_CLASS(insn->code)) {
3206 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3207 (insn->imm & BPF_FETCH)) {
3208 if (insn->imm == BPF_CMPXCHG)
3211 return insn->src_reg;
3216 return insn->dst_reg;
3220 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3221 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3223 int dst_reg = insn_def_regno(insn);
3228 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3231 static void mark_insn_zext(struct bpf_verifier_env *env,
3232 struct bpf_reg_state *reg)
3234 s32 def_idx = reg->subreg_def;
3236 if (def_idx == DEF_NOT_SUBREG)
3239 env->insn_aux_data[def_idx - 1].zext_dst = true;
3240 /* The dst will be zero extended, so won't be sub-register anymore. */
3241 reg->subreg_def = DEF_NOT_SUBREG;
3244 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3245 enum reg_arg_type t)
3247 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3248 struct bpf_reg_state *reg;
3251 if (regno >= MAX_BPF_REG) {
3252 verbose(env, "R%d is invalid\n", regno);
3256 mark_reg_scratched(env, regno);
3259 rw64 = is_reg64(env, insn, regno, reg, t);
3261 /* check whether register used as source operand can be read */
3262 if (reg->type == NOT_INIT) {
3263 verbose(env, "R%d !read_ok\n", regno);
3266 /* We don't need to worry about FP liveness because it's read-only */
3267 if (regno == BPF_REG_FP)
3271 mark_insn_zext(env, reg);
3273 return mark_reg_read(env, reg, reg->parent,
3274 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3276 /* check whether register used as dest operand can be written to */
3277 if (regno == BPF_REG_FP) {
3278 verbose(env, "frame pointer is read only\n");
3281 reg->live |= REG_LIVE_WRITTEN;
3282 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3284 mark_reg_unknown(env, regs, regno);
3289 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3290 enum reg_arg_type t)
3292 struct bpf_verifier_state *vstate = env->cur_state;
3293 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3295 return __check_reg_arg(env, state->regs, regno, t);
3298 static int insn_stack_access_flags(int frameno, int spi)
3300 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3303 static int insn_stack_access_spi(int insn_flags)
3305 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3308 static int insn_stack_access_frameno(int insn_flags)
3310 return insn_flags & INSN_F_FRAMENO_MASK;
3313 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3315 env->insn_aux_data[idx].jmp_point = true;
3318 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3320 return env->insn_aux_data[insn_idx].jmp_point;
3323 /* for any branch, call, exit record the history of jmps in the given state */
3324 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3327 u32 cnt = cur->jmp_history_cnt;
3328 struct bpf_jmp_history_entry *p;
3331 /* combine instruction flags if we already recorded this instruction */
3332 if (env->cur_hist_ent) {
3333 /* atomic instructions push insn_flags twice, for READ and
3334 * WRITE sides, but they should agree on stack slot
3336 WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
3337 (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3338 "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
3339 env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3340 env->cur_hist_ent->flags |= insn_flags;
3345 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3346 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3349 cur->jmp_history = p;
3351 p = &cur->jmp_history[cnt - 1];
3352 p->idx = env->insn_idx;
3353 p->prev_idx = env->prev_insn_idx;
3354 p->flags = insn_flags;
3355 cur->jmp_history_cnt = cnt;
3356 env->cur_hist_ent = p;
3361 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3362 u32 hist_end, int insn_idx)
3364 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3365 return &st->jmp_history[hist_end - 1];
3369 /* Backtrack one insn at a time. If idx is not at the top of recorded
3370 * history then previous instruction came from straight line execution.
3371 * Return -ENOENT if we exhausted all instructions within given state.
3373 * It's legal to have a bit of a looping with the same starting and ending
3374 * insn index within the same state, e.g.: 3->4->5->3, so just because current
3375 * instruction index is the same as state's first_idx doesn't mean we are
3376 * done. If there is still some jump history left, we should keep going. We
3377 * need to take into account that we might have a jump history between given
3378 * state's parent and itself, due to checkpointing. In this case, we'll have
3379 * history entry recording a jump from last instruction of parent state and
3380 * first instruction of given state.
3382 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3387 if (i == st->first_insn_idx) {
3390 if (cnt == 1 && st->jmp_history[0].idx == i)
3394 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3395 i = st->jmp_history[cnt - 1].prev_idx;
3403 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3405 const struct btf_type *func;
3406 struct btf *desc_btf;
3408 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3411 desc_btf = find_kfunc_desc_btf(data, insn->off);
3412 if (IS_ERR(desc_btf))
3415 func = btf_type_by_id(desc_btf, insn->imm);
3416 return btf_name_by_offset(desc_btf, func->name_off);
3419 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3424 static inline void bt_reset(struct backtrack_state *bt)
3426 struct bpf_verifier_env *env = bt->env;
3428 memset(bt, 0, sizeof(*bt));
3432 static inline u32 bt_empty(struct backtrack_state *bt)
3437 for (i = 0; i <= bt->frame; i++)
3438 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3443 static inline int bt_subprog_enter(struct backtrack_state *bt)
3445 if (bt->frame == MAX_CALL_FRAMES - 1) {
3446 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3447 WARN_ONCE(1, "verifier backtracking bug");
3454 static inline int bt_subprog_exit(struct backtrack_state *bt)
3456 if (bt->frame == 0) {
3457 verbose(bt->env, "BUG subprog exit from frame 0\n");
3458 WARN_ONCE(1, "verifier backtracking bug");
3465 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3467 bt->reg_masks[frame] |= 1 << reg;
3470 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3472 bt->reg_masks[frame] &= ~(1 << reg);
3475 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3477 bt_set_frame_reg(bt, bt->frame, reg);
3480 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3482 bt_clear_frame_reg(bt, bt->frame, reg);
3485 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3487 bt->stack_masks[frame] |= 1ull << slot;
3490 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3492 bt->stack_masks[frame] &= ~(1ull << slot);
3495 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3497 return bt->reg_masks[frame];
3500 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3502 return bt->reg_masks[bt->frame];
3505 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3507 return bt->stack_masks[frame];
3510 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3512 return bt->stack_masks[bt->frame];
3515 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3517 return bt->reg_masks[bt->frame] & (1 << reg);
3520 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
3522 return bt->stack_masks[frame] & (1ull << slot);
3525 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3526 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3528 DECLARE_BITMAP(mask, 64);
3534 bitmap_from_u64(mask, reg_mask);
3535 for_each_set_bit(i, mask, 32) {
3536 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3544 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3545 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3547 DECLARE_BITMAP(mask, 64);
3553 bitmap_from_u64(mask, stack_mask);
3554 for_each_set_bit(i, mask, 64) {
3555 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3564 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3566 /* For given verifier state backtrack_insn() is called from the last insn to
3567 * the first insn. Its purpose is to compute a bitmask of registers and
3568 * stack slots that needs precision in the parent verifier state.
3570 * @idx is an index of the instruction we are currently processing;
3571 * @subseq_idx is an index of the subsequent instruction that:
3572 * - *would be* executed next, if jump history is viewed in forward order;
3573 * - *was* processed previously during backtracking.
3575 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3576 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
3578 const struct bpf_insn_cbs cbs = {
3579 .cb_call = disasm_kfunc_name,
3580 .cb_print = verbose,
3581 .private_data = env,
3583 struct bpf_insn *insn = env->prog->insnsi + idx;
3584 u8 class = BPF_CLASS(insn->code);
3585 u8 opcode = BPF_OP(insn->code);
3586 u8 mode = BPF_MODE(insn->code);
3587 u32 dreg = insn->dst_reg;
3588 u32 sreg = insn->src_reg;
3591 if (insn->code == 0)
3593 if (env->log.level & BPF_LOG_LEVEL2) {
3594 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3595 verbose(env, "mark_precise: frame%d: regs=%s ",
3596 bt->frame, env->tmp_str_buf);
3597 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3598 verbose(env, "stack=%s before ", env->tmp_str_buf);
3599 verbose(env, "%d: ", idx);
3600 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3603 if (class == BPF_ALU || class == BPF_ALU64) {
3604 if (!bt_is_reg_set(bt, dreg))
3606 if (opcode == BPF_END || opcode == BPF_NEG) {
3607 /* sreg is reserved and unused
3608 * dreg still need precision before this insn
3611 } else if (opcode == BPF_MOV) {
3612 if (BPF_SRC(insn->code) == BPF_X) {
3613 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3614 * dreg needs precision after this insn
3615 * sreg needs precision before this insn
3617 bt_clear_reg(bt, dreg);
3618 bt_set_reg(bt, sreg);
3621 * dreg needs precision after this insn.
3622 * Corresponding register is already marked
3623 * as precise=true in this verifier state.
3624 * No further markings in parent are necessary
3626 bt_clear_reg(bt, dreg);
3629 if (BPF_SRC(insn->code) == BPF_X) {
3631 * both dreg and sreg need precision
3634 bt_set_reg(bt, sreg);
3636 * dreg still needs precision before this insn
3639 } else if (class == BPF_LDX) {
3640 if (!bt_is_reg_set(bt, dreg))
3642 bt_clear_reg(bt, dreg);
3644 /* scalars can only be spilled into stack w/o losing precision.
3645 * Load from any other memory can be zero extended.
3646 * The desire to keep that precision is already indicated
3647 * by 'precise' mark in corresponding register of this state.
3648 * No further tracking necessary.
3650 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3652 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3653 * that [fp - off] slot contains scalar that needs to be
3654 * tracked with precision
3656 spi = insn_stack_access_spi(hist->flags);
3657 fr = insn_stack_access_frameno(hist->flags);
3658 bt_set_frame_slot(bt, fr, spi);
3659 } else if (class == BPF_STX || class == BPF_ST) {
3660 if (bt_is_reg_set(bt, dreg))
3661 /* stx & st shouldn't be using _scalar_ dst_reg
3662 * to access memory. It means backtracking
3663 * encountered a case of pointer subtraction.
3666 /* scalars can only be spilled into stack */
3667 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3669 spi = insn_stack_access_spi(hist->flags);
3670 fr = insn_stack_access_frameno(hist->flags);
3671 if (!bt_is_frame_slot_set(bt, fr, spi))
3673 bt_clear_frame_slot(bt, fr, spi);
3674 if (class == BPF_STX)
3675 bt_set_reg(bt, sreg);
3676 } else if (class == BPF_JMP || class == BPF_JMP32) {
3677 if (bpf_pseudo_call(insn)) {
3678 int subprog_insn_idx, subprog;
3680 subprog_insn_idx = idx + insn->imm + 1;
3681 subprog = find_subprog(env, subprog_insn_idx);
3685 if (subprog_is_global(env, subprog)) {
3686 /* check that jump history doesn't have any
3687 * extra instructions from subprog; the next
3688 * instruction after call to global subprog
3689 * should be literally next instruction in
3692 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3693 /* r1-r5 are invalidated after subprog call,
3694 * so for global func call it shouldn't be set
3697 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3698 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3699 WARN_ONCE(1, "verifier backtracking bug");
3702 /* global subprog always sets R0 */
3703 bt_clear_reg(bt, BPF_REG_0);
3706 /* static subprog call instruction, which
3707 * means that we are exiting current subprog,
3708 * so only r1-r5 could be still requested as
3709 * precise, r0 and r6-r10 or any stack slot in
3710 * the current frame should be zero by now
3712 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3713 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3714 WARN_ONCE(1, "verifier backtracking bug");
3717 /* we are now tracking register spills correctly,
3718 * so any instance of leftover slots is a bug
3720 if (bt_stack_mask(bt) != 0) {
3721 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3722 WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
3725 /* propagate r1-r5 to the caller */
3726 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3727 if (bt_is_reg_set(bt, i)) {
3728 bt_clear_reg(bt, i);
3729 bt_set_frame_reg(bt, bt->frame - 1, i);
3732 if (bt_subprog_exit(bt))
3736 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3737 /* exit from callback subprog to callback-calling helper or
3738 * kfunc call. Use idx/subseq_idx check to discern it from
3739 * straight line code backtracking.
3740 * Unlike the subprog call handling above, we shouldn't
3741 * propagate precision of r1-r5 (if any requested), as they are
3742 * not actually arguments passed directly to callback subprogs
3744 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3745 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3746 WARN_ONCE(1, "verifier backtracking bug");
3749 if (bt_stack_mask(bt) != 0) {
3750 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3751 WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
3754 /* clear r1-r5 in callback subprog's mask */
3755 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3756 bt_clear_reg(bt, i);
3757 if (bt_subprog_exit(bt))
3760 } else if (opcode == BPF_CALL) {
3761 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3762 * catch this error later. Make backtracking conservative
3765 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3767 /* regular helper call sets R0 */
3768 bt_clear_reg(bt, BPF_REG_0);
3769 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3770 /* if backtracing was looking for registers R1-R5
3771 * they should have been found already.
3773 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3774 WARN_ONCE(1, "verifier backtracking bug");
3777 } else if (opcode == BPF_EXIT) {
3780 /* Backtracking to a nested function call, 'idx' is a part of
3781 * the inner frame 'subseq_idx' is a part of the outer frame.
3782 * In case of a regular function call, instructions giving
3783 * precision to registers R1-R5 should have been found already.
3784 * In case of a callback, it is ok to have R1-R5 marked for
3785 * backtracking, as these registers are set by the function
3786 * invoking callback.
3788 if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3789 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3790 bt_clear_reg(bt, i);
3791 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3792 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3793 WARN_ONCE(1, "verifier backtracking bug");
3797 /* BPF_EXIT in subprog or callback always returns
3798 * right after the call instruction, so by checking
3799 * whether the instruction at subseq_idx-1 is subprog
3800 * call or not we can distinguish actual exit from
3801 * *subprog* from exit from *callback*. In the former
3802 * case, we need to propagate r0 precision, if
3803 * necessary. In the former we never do that.
3805 r0_precise = subseq_idx - 1 >= 0 &&
3806 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3807 bt_is_reg_set(bt, BPF_REG_0);
3809 bt_clear_reg(bt, BPF_REG_0);
3810 if (bt_subprog_enter(bt))
3814 bt_set_reg(bt, BPF_REG_0);
3815 /* r6-r9 and stack slots will stay set in caller frame
3816 * bitmasks until we return back from callee(s)
3819 } else if (BPF_SRC(insn->code) == BPF_X) {
3820 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3823 * Both dreg and sreg need precision before
3824 * this insn. If only sreg was marked precise
3825 * before it would be equally necessary to
3826 * propagate it to dreg.
3828 bt_set_reg(bt, dreg);
3829 bt_set_reg(bt, sreg);
3830 /* else dreg <cond> K
3831 * Only dreg still needs precision before
3832 * this insn, so for the K-based conditional
3833 * there is nothing new to be marked.
3836 } else if (class == BPF_LD) {
3837 if (!bt_is_reg_set(bt, dreg))
3839 bt_clear_reg(bt, dreg);
3840 /* It's ld_imm64 or ld_abs or ld_ind.
3841 * For ld_imm64 no further tracking of precision
3842 * into parent is necessary
3844 if (mode == BPF_IND || mode == BPF_ABS)
3845 /* to be analyzed */
3851 /* the scalar precision tracking algorithm:
3852 * . at the start all registers have precise=false.
3853 * . scalar ranges are tracked as normal through alu and jmp insns.
3854 * . once precise value of the scalar register is used in:
3855 * . ptr + scalar alu
3856 * . if (scalar cond K|scalar)
3857 * . helper_call(.., scalar, ...) where ARG_CONST is expected
3858 * backtrack through the verifier states and mark all registers and
3859 * stack slots with spilled constants that these scalar regisers
3860 * should be precise.
3861 * . during state pruning two registers (or spilled stack slots)
3862 * are equivalent if both are not precise.
3864 * Note the verifier cannot simply walk register parentage chain,
3865 * since many different registers and stack slots could have been
3866 * used to compute single precise scalar.
3868 * The approach of starting with precise=true for all registers and then
3869 * backtrack to mark a register as not precise when the verifier detects
3870 * that program doesn't care about specific value (e.g., when helper
3871 * takes register as ARG_ANYTHING parameter) is not safe.
3873 * It's ok to walk single parentage chain of the verifier states.
3874 * It's possible that this backtracking will go all the way till 1st insn.
3875 * All other branches will be explored for needing precision later.
3877 * The backtracking needs to deal with cases like:
3878 * 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)
3881 * if r5 > 0x79f goto pc+7
3882 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3885 * call bpf_perf_event_output#25
3886 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3890 * call foo // uses callee's r6 inside to compute r0
3894 * to track above reg_mask/stack_mask needs to be independent for each frame.
3896 * Also if parent's curframe > frame where backtracking started,
3897 * the verifier need to mark registers in both frames, otherwise callees
3898 * may incorrectly prune callers. This is similar to
3899 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3901 * For now backtracking falls back into conservative marking.
3903 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3904 struct bpf_verifier_state *st)
3906 struct bpf_func_state *func;
3907 struct bpf_reg_state *reg;
3910 if (env->log.level & BPF_LOG_LEVEL2) {
3911 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3915 /* big hammer: mark all scalars precise in this path.
3916 * pop_stack may still get !precise scalars.
3917 * We also skip current state and go straight to first parent state,
3918 * because precision markings in current non-checkpointed state are
3919 * not needed. See why in the comment in __mark_chain_precision below.
3921 for (st = st->parent; st; st = st->parent) {
3922 for (i = 0; i <= st->curframe; i++) {
3923 func = st->frame[i];
3924 for (j = 0; j < BPF_REG_FP; j++) {
3925 reg = &func->regs[j];
3926 if (reg->type != SCALAR_VALUE || reg->precise)
3928 reg->precise = true;
3929 if (env->log.level & BPF_LOG_LEVEL2) {
3930 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3934 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3935 if (!is_spilled_reg(&func->stack[j]))
3937 reg = &func->stack[j].spilled_ptr;
3938 if (reg->type != SCALAR_VALUE || reg->precise)
3940 reg->precise = true;
3941 if (env->log.level & BPF_LOG_LEVEL2) {
3942 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3950 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3952 struct bpf_func_state *func;
3953 struct bpf_reg_state *reg;
3956 for (i = 0; i <= st->curframe; i++) {
3957 func = st->frame[i];
3958 for (j = 0; j < BPF_REG_FP; j++) {
3959 reg = &func->regs[j];
3960 if (reg->type != SCALAR_VALUE)
3962 reg->precise = false;
3964 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3965 if (!is_spilled_reg(&func->stack[j]))
3967 reg = &func->stack[j].spilled_ptr;
3968 if (reg->type != SCALAR_VALUE)
3970 reg->precise = false;
3975 static bool idset_contains(struct bpf_idset *s, u32 id)
3979 for (i = 0; i < s->count; ++i)
3980 if (s->ids[i] == id)
3986 static int idset_push(struct bpf_idset *s, u32 id)
3988 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3990 s->ids[s->count++] = id;
3994 static void idset_reset(struct bpf_idset *s)
3999 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4000 * Mark all registers with these IDs as precise.
4002 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4004 struct bpf_idset *precise_ids = &env->idset_scratch;
4005 struct backtrack_state *bt = &env->bt;
4006 struct bpf_func_state *func;
4007 struct bpf_reg_state *reg;
4008 DECLARE_BITMAP(mask, 64);
4011 idset_reset(precise_ids);
4013 for (fr = bt->frame; fr >= 0; fr--) {
4014 func = st->frame[fr];
4016 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4017 for_each_set_bit(i, mask, 32) {
4018 reg = &func->regs[i];
4019 if (!reg->id || reg->type != SCALAR_VALUE)
4021 if (idset_push(precise_ids, reg->id))
4025 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4026 for_each_set_bit(i, mask, 64) {
4027 if (i >= func->allocated_stack / BPF_REG_SIZE)
4029 if (!is_spilled_scalar_reg(&func->stack[i]))
4031 reg = &func->stack[i].spilled_ptr;
4034 if (idset_push(precise_ids, reg->id))
4039 for (fr = 0; fr <= st->curframe; ++fr) {
4040 func = st->frame[fr];
4042 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4043 reg = &func->regs[i];
4046 if (!idset_contains(precise_ids, reg->id))
4048 bt_set_frame_reg(bt, fr, i);
4050 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4051 if (!is_spilled_scalar_reg(&func->stack[i]))
4053 reg = &func->stack[i].spilled_ptr;
4056 if (!idset_contains(precise_ids, reg->id))
4058 bt_set_frame_slot(bt, fr, i);
4066 * __mark_chain_precision() backtracks BPF program instruction sequence and
4067 * chain of verifier states making sure that register *regno* (if regno >= 0)
4068 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4069 * SCALARS, as well as any other registers and slots that contribute to
4070 * a tracked state of given registers/stack slots, depending on specific BPF
4071 * assembly instructions (see backtrack_insns() for exact instruction handling
4072 * logic). This backtracking relies on recorded jmp_history and is able to
4073 * traverse entire chain of parent states. This process ends only when all the
4074 * necessary registers/slots and their transitive dependencies are marked as
4077 * One important and subtle aspect is that precise marks *do not matter* in
4078 * the currently verified state (current state). It is important to understand
4079 * why this is the case.
4081 * First, note that current state is the state that is not yet "checkpointed",
4082 * i.e., it is not yet put into env->explored_states, and it has no children
4083 * states as well. It's ephemeral, and can end up either a) being discarded if
4084 * compatible explored state is found at some point or BPF_EXIT instruction is
4085 * reached or b) checkpointed and put into env->explored_states, branching out
4086 * into one or more children states.
4088 * In the former case, precise markings in current state are completely
4089 * ignored by state comparison code (see regsafe() for details). Only
4090 * checkpointed ("old") state precise markings are important, and if old
4091 * state's register/slot is precise, regsafe() assumes current state's
4092 * register/slot as precise and checks value ranges exactly and precisely. If
4093 * states turn out to be compatible, current state's necessary precise
4094 * markings and any required parent states' precise markings are enforced
4095 * after the fact with propagate_precision() logic, after the fact. But it's
4096 * important to realize that in this case, even after marking current state
4097 * registers/slots as precise, we immediately discard current state. So what
4098 * actually matters is any of the precise markings propagated into current
4099 * state's parent states, which are always checkpointed (due to b) case above).
4100 * As such, for scenario a) it doesn't matter if current state has precise
4101 * markings set or not.
4103 * Now, for the scenario b), checkpointing and forking into child(ren)
4104 * state(s). Note that before current state gets to checkpointing step, any
4105 * processed instruction always assumes precise SCALAR register/slot
4106 * knowledge: if precise value or range is useful to prune jump branch, BPF
4107 * verifier takes this opportunity enthusiastically. Similarly, when
4108 * register's value is used to calculate offset or memory address, exact
4109 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4110 * what we mentioned above about state comparison ignoring precise markings
4111 * during state comparison, BPF verifier ignores and also assumes precise
4112 * markings *at will* during instruction verification process. But as verifier
4113 * assumes precision, it also propagates any precision dependencies across
4114 * parent states, which are not yet finalized, so can be further restricted
4115 * based on new knowledge gained from restrictions enforced by their children
4116 * states. This is so that once those parent states are finalized, i.e., when
4117 * they have no more active children state, state comparison logic in
4118 * is_state_visited() would enforce strict and precise SCALAR ranges, if
4119 * required for correctness.
4121 * To build a bit more intuition, note also that once a state is checkpointed,
4122 * the path we took to get to that state is not important. This is crucial
4123 * property for state pruning. When state is checkpointed and finalized at
4124 * some instruction index, it can be correctly and safely used to "short
4125 * circuit" any *compatible* state that reaches exactly the same instruction
4126 * index. I.e., if we jumped to that instruction from a completely different
4127 * code path than original finalized state was derived from, it doesn't
4128 * matter, current state can be discarded because from that instruction
4129 * forward having a compatible state will ensure we will safely reach the
4130 * exit. States describe preconditions for further exploration, but completely
4131 * forget the history of how we got here.
4133 * This also means that even if we needed precise SCALAR range to get to
4134 * finalized state, but from that point forward *that same* SCALAR register is
4135 * never used in a precise context (i.e., it's precise value is not needed for
4136 * correctness), it's correct and safe to mark such register as "imprecise"
4137 * (i.e., precise marking set to false). This is what we rely on when we do
4138 * not set precise marking in current state. If no child state requires
4139 * precision for any given SCALAR register, it's safe to dictate that it can
4140 * be imprecise. If any child state does require this register to be precise,
4141 * we'll mark it precise later retroactively during precise markings
4142 * propagation from child state to parent states.
4144 * Skipping precise marking setting in current state is a mild version of
4145 * relying on the above observation. But we can utilize this property even
4146 * more aggressively by proactively forgetting any precise marking in the
4147 * current state (which we inherited from the parent state), right before we
4148 * checkpoint it and branch off into new child state. This is done by
4149 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4150 * finalized states which help in short circuiting more future states.
4152 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4154 struct backtrack_state *bt = &env->bt;
4155 struct bpf_verifier_state *st = env->cur_state;
4156 int first_idx = st->first_insn_idx;
4157 int last_idx = env->insn_idx;
4158 int subseq_idx = -1;
4159 struct bpf_func_state *func;
4160 struct bpf_reg_state *reg;
4161 bool skip_first = true;
4164 if (!env->bpf_capable)
4167 /* set frame number from which we are starting to backtrack */
4168 bt_init(bt, env->cur_state->curframe);
4170 /* Do sanity checks against current state of register and/or stack
4171 * slot, but don't set precise flag in current state, as precision
4172 * tracking in the current state is unnecessary.
4174 func = st->frame[bt->frame];
4176 reg = &func->regs[regno];
4177 if (reg->type != SCALAR_VALUE) {
4178 WARN_ONCE(1, "backtracing misuse");
4181 bt_set_reg(bt, regno);
4188 DECLARE_BITMAP(mask, 64);
4189 u32 history = st->jmp_history_cnt;
4190 struct bpf_jmp_history_entry *hist;
4192 if (env->log.level & BPF_LOG_LEVEL2) {
4193 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4194 bt->frame, last_idx, first_idx, subseq_idx);
4197 /* If some register with scalar ID is marked as precise,
4198 * make sure that all registers sharing this ID are also precise.
4199 * This is needed to estimate effect of find_equal_scalars().
4200 * Do this at the last instruction of each state,
4201 * bpf_reg_state::id fields are valid for these instructions.
4203 * Allows to track precision in situation like below:
4205 * r2 = unknown value
4209 * r1 = r2 // r1 and r2 now share the same ID
4211 * --- state #1 {r1.id = A, r2.id = A} ---
4213 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4215 * --- state #2 {r1.id = A, r2.id = A} ---
4217 * r3 += r1 // need to mark both r1 and r2
4219 if (mark_precise_scalar_ids(env, st))
4223 /* we are at the entry into subprog, which
4224 * is expected for global funcs, but only if
4225 * requested precise registers are R1-R5
4226 * (which are global func's input arguments)
4228 if (st->curframe == 0 &&
4229 st->frame[0]->subprogno > 0 &&
4230 st->frame[0]->callsite == BPF_MAIN_FUNC &&
4231 bt_stack_mask(bt) == 0 &&
4232 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4233 bitmap_from_u64(mask, bt_reg_mask(bt));
4234 for_each_set_bit(i, mask, 32) {
4235 reg = &st->frame[0]->regs[i];
4236 bt_clear_reg(bt, i);
4237 if (reg->type == SCALAR_VALUE)
4238 reg->precise = true;
4243 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4244 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4245 WARN_ONCE(1, "verifier backtracking bug");
4249 for (i = last_idx;;) {
4254 hist = get_jmp_hist_entry(st, history, i);
4255 err = backtrack_insn(env, i, subseq_idx, hist, bt);
4257 if (err == -ENOTSUPP) {
4258 mark_all_scalars_precise(env, env->cur_state);
4265 /* Found assignment(s) into tracked register in this state.
4266 * Since this state is already marked, just return.
4267 * Nothing to be tracked further in the parent state.
4271 i = get_prev_insn_idx(st, i, &history);
4274 if (i >= env->prog->len) {
4275 /* This can happen if backtracking reached insn 0
4276 * and there are still reg_mask or stack_mask
4278 * It means the backtracking missed the spot where
4279 * particular register was initialized with a constant.
4281 verbose(env, "BUG backtracking idx %d\n", i);
4282 WARN_ONCE(1, "verifier backtracking bug");
4290 for (fr = bt->frame; fr >= 0; fr--) {
4291 func = st->frame[fr];
4292 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4293 for_each_set_bit(i, mask, 32) {
4294 reg = &func->regs[i];
4295 if (reg->type != SCALAR_VALUE) {
4296 bt_clear_frame_reg(bt, fr, i);
4300 bt_clear_frame_reg(bt, fr, i);
4302 reg->precise = true;
4305 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4306 for_each_set_bit(i, mask, 64) {
4307 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4308 verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
4309 i, func->allocated_stack / BPF_REG_SIZE);
4310 WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
4314 if (!is_spilled_scalar_reg(&func->stack[i])) {
4315 bt_clear_frame_slot(bt, fr, i);
4318 reg = &func->stack[i].spilled_ptr;
4320 bt_clear_frame_slot(bt, fr, i);
4322 reg->precise = true;
4324 if (env->log.level & BPF_LOG_LEVEL2) {
4325 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4326 bt_frame_reg_mask(bt, fr));
4327 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4328 fr, env->tmp_str_buf);
4329 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4330 bt_frame_stack_mask(bt, fr));
4331 verbose(env, "stack=%s: ", env->tmp_str_buf);
4332 print_verifier_state(env, func, true);
4339 subseq_idx = first_idx;
4340 last_idx = st->last_insn_idx;
4341 first_idx = st->first_insn_idx;
4344 /* if we still have requested precise regs or slots, we missed
4345 * something (e.g., stack access through non-r10 register), so
4346 * fallback to marking all precise
4348 if (!bt_empty(bt)) {
4349 mark_all_scalars_precise(env, env->cur_state);
4356 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4358 return __mark_chain_precision(env, regno);
4361 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4362 * desired reg and stack masks across all relevant frames
4364 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4366 return __mark_chain_precision(env, -1);
4369 static bool is_spillable_regtype(enum bpf_reg_type type)
4371 switch (base_type(type)) {
4372 case PTR_TO_MAP_VALUE:
4376 case PTR_TO_PACKET_META:
4377 case PTR_TO_PACKET_END:
4378 case PTR_TO_FLOW_KEYS:
4379 case CONST_PTR_TO_MAP:
4381 case PTR_TO_SOCK_COMMON:
4382 case PTR_TO_TCP_SOCK:
4383 case PTR_TO_XDP_SOCK:
4388 case PTR_TO_MAP_KEY:
4396 /* Does this register contain a constant zero? */
4397 static bool register_is_null(struct bpf_reg_state *reg)
4399 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4402 /* check if register is a constant scalar value */
4403 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4405 return reg->type == SCALAR_VALUE &&
4406 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4409 /* assuming is_reg_const() is true, return constant value of a register */
4410 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4412 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4415 static bool __is_pointer_value(bool allow_ptr_leaks,
4416 const struct bpf_reg_state *reg)
4418 if (allow_ptr_leaks)
4421 return reg->type != SCALAR_VALUE;
4424 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4425 struct bpf_reg_state *src_reg)
4427 if (src_reg->type == SCALAR_VALUE && !src_reg->id &&
4428 !tnum_is_const(src_reg->var_off))
4429 /* Ensure that src_reg has a valid ID that will be copied to
4430 * dst_reg and then will be used by find_equal_scalars() to
4431 * propagate min/max range.
4433 src_reg->id = ++env->id_gen;
4436 /* Copy src state preserving dst->parent and dst->live fields */
4437 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4439 struct bpf_reg_state *parent = dst->parent;
4440 enum bpf_reg_liveness live = dst->live;
4443 dst->parent = parent;
4447 static void save_register_state(struct bpf_verifier_env *env,
4448 struct bpf_func_state *state,
4449 int spi, struct bpf_reg_state *reg,
4454 copy_register_state(&state->stack[spi].spilled_ptr, reg);
4455 if (size == BPF_REG_SIZE)
4456 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4458 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4459 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4461 /* size < 8 bytes spill */
4463 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4466 static bool is_bpf_st_mem(struct bpf_insn *insn)
4468 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4471 static int get_reg_width(struct bpf_reg_state *reg)
4473 return fls64(reg->umax_value);
4476 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4477 * stack boundary and alignment are checked in check_mem_access()
4479 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4480 /* stack frame we're writing to */
4481 struct bpf_func_state *state,
4482 int off, int size, int value_regno,
4485 struct bpf_func_state *cur; /* state of the current function */
4486 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4487 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4488 struct bpf_reg_state *reg = NULL;
4489 int insn_flags = insn_stack_access_flags(state->frameno, spi);
4491 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4492 * so it's aligned access and [off, off + size) are within stack limits
4494 if (!env->allow_ptr_leaks &&
4495 is_spilled_reg(&state->stack[spi]) &&
4496 size != BPF_REG_SIZE) {
4497 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4501 cur = env->cur_state->frame[env->cur_state->curframe];
4502 if (value_regno >= 0)
4503 reg = &cur->regs[value_regno];
4504 if (!env->bypass_spec_v4) {
4505 bool sanitize = reg && is_spillable_regtype(reg->type);
4507 for (i = 0; i < size; i++) {
4508 u8 type = state->stack[spi].slot_type[i];
4510 if (type != STACK_MISC && type != STACK_ZERO) {
4517 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4520 err = destroy_if_dynptr_stack_slot(env, state, spi);
4524 mark_stack_slot_scratched(env, spi);
4525 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
4526 bool reg_value_fits;
4528 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
4529 /* Make sure that reg had an ID to build a relation on spill. */
4531 assign_scalar_id_before_mov(env, reg);
4532 save_register_state(env, state, spi, reg, size);
4533 /* Break the relation on a narrowing spill. */
4534 if (!reg_value_fits)
4535 state->stack[spi].spilled_ptr.id = 0;
4536 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4538 struct bpf_reg_state fake_reg = {};
4540 __mark_reg_known(&fake_reg, insn->imm);
4541 fake_reg.type = SCALAR_VALUE;
4542 save_register_state(env, state, spi, &fake_reg, size);
4543 } else if (reg && is_spillable_regtype(reg->type)) {
4544 /* register containing pointer is being spilled into stack */
4545 if (size != BPF_REG_SIZE) {
4546 verbose_linfo(env, insn_idx, "; ");
4547 verbose(env, "invalid size of register spill\n");
4550 if (state != cur && reg->type == PTR_TO_STACK) {
4551 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4554 save_register_state(env, state, spi, reg, size);
4556 u8 type = STACK_MISC;
4558 /* regular write of data into stack destroys any spilled ptr */
4559 state->stack[spi].spilled_ptr.type = NOT_INIT;
4560 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4561 if (is_stack_slot_special(&state->stack[spi]))
4562 for (i = 0; i < BPF_REG_SIZE; i++)
4563 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4565 /* only mark the slot as written if all 8 bytes were written
4566 * otherwise read propagation may incorrectly stop too soon
4567 * when stack slots are partially written.
4568 * This heuristic means that read propagation will be
4569 * conservative, since it will add reg_live_read marks
4570 * to stack slots all the way to first state when programs
4571 * writes+reads less than 8 bytes
4573 if (size == BPF_REG_SIZE)
4574 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4576 /* when we zero initialize stack slots mark them as such */
4577 if ((reg && register_is_null(reg)) ||
4578 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4579 /* STACK_ZERO case happened because register spill
4580 * wasn't properly aligned at the stack slot boundary,
4581 * so it's not a register spill anymore; force
4582 * originating register to be precise to make
4583 * STACK_ZERO correct for subsequent states
4585 err = mark_chain_precision(env, value_regno);
4591 /* Mark slots affected by this stack write. */
4592 for (i = 0; i < size; i++)
4593 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
4594 insn_flags = 0; /* not a register spill */
4598 return push_jmp_history(env, env->cur_state, insn_flags);
4602 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4603 * known to contain a variable offset.
4604 * This function checks whether the write is permitted and conservatively
4605 * tracks the effects of the write, considering that each stack slot in the
4606 * dynamic range is potentially written to.
4608 * 'off' includes 'regno->off'.
4609 * 'value_regno' can be -1, meaning that an unknown value is being written to
4612 * Spilled pointers in range are not marked as written because we don't know
4613 * what's going to be actually written. This means that read propagation for
4614 * future reads cannot be terminated by this write.
4616 * For privileged programs, uninitialized stack slots are considered
4617 * initialized by this write (even though we don't know exactly what offsets
4618 * are going to be written to). The idea is that we don't want the verifier to
4619 * reject future reads that access slots written to through variable offsets.
4621 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4622 /* func where register points to */
4623 struct bpf_func_state *state,
4624 int ptr_regno, int off, int size,
4625 int value_regno, int insn_idx)
4627 struct bpf_func_state *cur; /* state of the current function */
4628 int min_off, max_off;
4630 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4631 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4632 bool writing_zero = false;
4633 /* set if the fact that we're writing a zero is used to let any
4634 * stack slots remain STACK_ZERO
4636 bool zero_used = false;
4638 cur = env->cur_state->frame[env->cur_state->curframe];
4639 ptr_reg = &cur->regs[ptr_regno];
4640 min_off = ptr_reg->smin_value + off;
4641 max_off = ptr_reg->smax_value + off + size;
4642 if (value_regno >= 0)
4643 value_reg = &cur->regs[value_regno];
4644 if ((value_reg && register_is_null(value_reg)) ||
4645 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4646 writing_zero = true;
4648 for (i = min_off; i < max_off; i++) {
4652 err = destroy_if_dynptr_stack_slot(env, state, spi);
4657 /* Variable offset writes destroy any spilled pointers in range. */
4658 for (i = min_off; i < max_off; i++) {
4659 u8 new_type, *stype;
4663 spi = slot / BPF_REG_SIZE;
4664 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4665 mark_stack_slot_scratched(env, spi);
4667 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4668 /* Reject the write if range we may write to has not
4669 * been initialized beforehand. If we didn't reject
4670 * here, the ptr status would be erased below (even
4671 * though not all slots are actually overwritten),
4672 * possibly opening the door to leaks.
4674 * We do however catch STACK_INVALID case below, and
4675 * only allow reading possibly uninitialized memory
4676 * later for CAP_PERFMON, as the write may not happen to
4679 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4684 /* If writing_zero and the spi slot contains a spill of value 0,
4685 * maintain the spill type.
4687 if (writing_zero && *stype == STACK_SPILL &&
4688 is_spilled_scalar_reg(&state->stack[spi])) {
4689 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
4691 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
4697 /* Erase all other spilled pointers. */
4698 state->stack[spi].spilled_ptr.type = NOT_INIT;
4700 /* Update the slot type. */
4701 new_type = STACK_MISC;
4702 if (writing_zero && *stype == STACK_ZERO) {
4703 new_type = STACK_ZERO;
4706 /* If the slot is STACK_INVALID, we check whether it's OK to
4707 * pretend that it will be initialized by this write. The slot
4708 * might not actually be written to, and so if we mark it as
4709 * initialized future reads might leak uninitialized memory.
4710 * For privileged programs, we will accept such reads to slots
4711 * that may or may not be written because, if we're reject
4712 * them, the error would be too confusing.
4714 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4715 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4722 /* backtracking doesn't work for STACK_ZERO yet. */
4723 err = mark_chain_precision(env, value_regno);
4730 /* When register 'dst_regno' is assigned some values from stack[min_off,
4731 * max_off), we set the register's type according to the types of the
4732 * respective stack slots. If all the stack values are known to be zeros, then
4733 * so is the destination reg. Otherwise, the register is considered to be
4734 * SCALAR. This function does not deal with register filling; the caller must
4735 * ensure that all spilled registers in the stack range have been marked as
4738 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4739 /* func where src register points to */
4740 struct bpf_func_state *ptr_state,
4741 int min_off, int max_off, int dst_regno)
4743 struct bpf_verifier_state *vstate = env->cur_state;
4744 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4749 for (i = min_off; i < max_off; i++) {
4751 spi = slot / BPF_REG_SIZE;
4752 mark_stack_slot_scratched(env, spi);
4753 stype = ptr_state->stack[spi].slot_type;
4754 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4758 if (zeros == max_off - min_off) {
4759 /* Any access_size read into register is zero extended,
4760 * so the whole register == const_zero.
4762 __mark_reg_const_zero(env, &state->regs[dst_regno]);
4764 /* have read misc data from the stack */
4765 mark_reg_unknown(env, state->regs, dst_regno);
4767 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4770 /* Read the stack at 'off' and put the results into the register indicated by
4771 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4774 * 'dst_regno' can be -1, meaning that the read value is not going to a
4777 * The access is assumed to be within the current stack bounds.
4779 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4780 /* func where src register points to */
4781 struct bpf_func_state *reg_state,
4782 int off, int size, int dst_regno)
4784 struct bpf_verifier_state *vstate = env->cur_state;
4785 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4786 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4787 struct bpf_reg_state *reg;
4789 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
4791 stype = reg_state->stack[spi].slot_type;
4792 reg = ®_state->stack[spi].spilled_ptr;
4794 mark_stack_slot_scratched(env, spi);
4796 if (is_spilled_reg(®_state->stack[spi])) {
4799 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4802 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4803 if (reg->type != SCALAR_VALUE) {
4804 verbose_linfo(env, env->insn_idx, "; ");
4805 verbose(env, "invalid size of register fill\n");
4809 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4813 if (size <= spill_size &&
4814 bpf_stack_narrow_access_ok(off, size, spill_size)) {
4815 /* The earlier check_reg_arg() has decided the
4816 * subreg_def for this insn. Save it first.
4818 s32 subreg_def = state->regs[dst_regno].subreg_def;
4820 copy_register_state(&state->regs[dst_regno], reg);
4821 state->regs[dst_regno].subreg_def = subreg_def;
4823 /* Break the relation on a narrowing fill.
4824 * coerce_reg_to_size will adjust the boundaries.
4826 if (get_reg_width(reg) > size * BITS_PER_BYTE)
4827 state->regs[dst_regno].id = 0;
4829 int spill_cnt = 0, zero_cnt = 0;
4831 for (i = 0; i < size; i++) {
4832 type = stype[(slot - i) % BPF_REG_SIZE];
4833 if (type == STACK_SPILL) {
4837 if (type == STACK_MISC)
4839 if (type == STACK_ZERO) {
4843 if (type == STACK_INVALID && env->allow_uninit_stack)
4845 verbose(env, "invalid read from stack off %d+%d size %d\n",
4850 if (spill_cnt == size &&
4851 tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
4852 __mark_reg_const_zero(env, &state->regs[dst_regno]);
4853 /* this IS register fill, so keep insn_flags */
4854 } else if (zero_cnt == size) {
4855 /* similarly to mark_reg_stack_read(), preserve zeroes */
4856 __mark_reg_const_zero(env, &state->regs[dst_regno]);
4857 insn_flags = 0; /* not restoring original register state */
4859 mark_reg_unknown(env, state->regs, dst_regno);
4860 insn_flags = 0; /* not restoring original register state */
4863 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4864 } else if (dst_regno >= 0) {
4865 /* restore register state from stack */
4866 copy_register_state(&state->regs[dst_regno], reg);
4867 /* mark reg as written since spilled pointer state likely
4868 * has its liveness marks cleared by is_state_visited()
4869 * which resets stack/reg liveness for state transitions
4871 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4872 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4873 /* If dst_regno==-1, the caller is asking us whether
4874 * it is acceptable to use this value as a SCALAR_VALUE
4876 * We must not allow unprivileged callers to do that
4877 * with spilled pointers.
4879 verbose(env, "leaking pointer from stack off %d\n",
4883 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4885 for (i = 0; i < size; i++) {
4886 type = stype[(slot - i) % BPF_REG_SIZE];
4887 if (type == STACK_MISC)
4889 if (type == STACK_ZERO)
4891 if (type == STACK_INVALID && env->allow_uninit_stack)
4893 verbose(env, "invalid read from stack off %d+%d size %d\n",
4897 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4899 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4900 insn_flags = 0; /* we are not restoring spilled register */
4903 return push_jmp_history(env, env->cur_state, insn_flags);
4907 enum bpf_access_src {
4908 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
4909 ACCESS_HELPER = 2, /* the access is performed by a helper */
4912 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4913 int regno, int off, int access_size,
4914 bool zero_size_allowed,
4915 enum bpf_access_src type,
4916 struct bpf_call_arg_meta *meta);
4918 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4920 return cur_regs(env) + regno;
4923 /* Read the stack at 'ptr_regno + off' and put the result into the register
4925 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4926 * but not its variable offset.
4927 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4929 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4930 * filling registers (i.e. reads of spilled register cannot be detected when
4931 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4932 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4933 * offset; for a fixed offset check_stack_read_fixed_off should be used
4936 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4937 int ptr_regno, int off, int size, int dst_regno)
4939 /* The state of the source register. */
4940 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4941 struct bpf_func_state *ptr_state = func(env, reg);
4943 int min_off, max_off;
4945 /* Note that we pass a NULL meta, so raw access will not be permitted.
4947 err = check_stack_range_initialized(env, ptr_regno, off, size,
4948 false, ACCESS_DIRECT, NULL);
4952 min_off = reg->smin_value + off;
4953 max_off = reg->smax_value + off;
4954 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4958 /* check_stack_read dispatches to check_stack_read_fixed_off or
4959 * check_stack_read_var_off.
4961 * The caller must ensure that the offset falls within the allocated stack
4964 * 'dst_regno' is a register which will receive the value from the stack. It
4965 * can be -1, meaning that the read value is not going to a register.
4967 static int check_stack_read(struct bpf_verifier_env *env,
4968 int ptr_regno, int off, int size,
4971 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4972 struct bpf_func_state *state = func(env, reg);
4974 /* Some accesses are only permitted with a static offset. */
4975 bool var_off = !tnum_is_const(reg->var_off);
4977 /* The offset is required to be static when reads don't go to a
4978 * register, in order to not leak pointers (see
4979 * check_stack_read_fixed_off).
4981 if (dst_regno < 0 && var_off) {
4984 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4985 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4989 /* Variable offset is prohibited for unprivileged mode for simplicity
4990 * since it requires corresponding support in Spectre masking for stack
4991 * ALU. See also retrieve_ptr_limit(). The check in
4992 * check_stack_access_for_ptr_arithmetic() called by
4993 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4994 * with variable offsets, therefore no check is required here. Further,
4995 * just checking it here would be insufficient as speculative stack
4996 * writes could still lead to unsafe speculative behaviour.
4999 off += reg->var_off.value;
5000 err = check_stack_read_fixed_off(env, state, off, size,
5003 /* Variable offset stack reads need more conservative handling
5004 * than fixed offset ones. Note that dst_regno >= 0 on this
5007 err = check_stack_read_var_off(env, ptr_regno, off, size,
5014 /* check_stack_write dispatches to check_stack_write_fixed_off or
5015 * check_stack_write_var_off.
5017 * 'ptr_regno' is the register used as a pointer into the stack.
5018 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5019 * 'value_regno' is the register whose value we're writing to the stack. It can
5020 * be -1, meaning that we're not writing from a register.
5022 * The caller must ensure that the offset falls within the maximum stack size.
5024 static int check_stack_write(struct bpf_verifier_env *env,
5025 int ptr_regno, int off, int size,
5026 int value_regno, int insn_idx)
5028 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5029 struct bpf_func_state *state = func(env, reg);
5032 if (tnum_is_const(reg->var_off)) {
5033 off += reg->var_off.value;
5034 err = check_stack_write_fixed_off(env, state, off, size,
5035 value_regno, insn_idx);
5037 /* Variable offset stack reads need more conservative handling
5038 * than fixed offset ones.
5040 err = check_stack_write_var_off(env, state,
5041 ptr_regno, off, size,
5042 value_regno, insn_idx);
5047 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5048 int off, int size, enum bpf_access_type type)
5050 struct bpf_reg_state *regs = cur_regs(env);
5051 struct bpf_map *map = regs[regno].map_ptr;
5052 u32 cap = bpf_map_flags_to_cap(map);
5054 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5055 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5056 map->value_size, off, size);
5060 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5061 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5062 map->value_size, off, size);
5069 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5070 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5071 int off, int size, u32 mem_size,
5072 bool zero_size_allowed)
5074 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5075 struct bpf_reg_state *reg;
5077 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5080 reg = &cur_regs(env)[regno];
5081 switch (reg->type) {
5082 case PTR_TO_MAP_KEY:
5083 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5084 mem_size, off, size);
5086 case PTR_TO_MAP_VALUE:
5087 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5088 mem_size, off, size);
5091 case PTR_TO_PACKET_META:
5092 case PTR_TO_PACKET_END:
5093 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5094 off, size, regno, reg->id, off, mem_size);
5098 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5099 mem_size, off, size);
5105 /* check read/write into a memory region with possible variable offset */
5106 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5107 int off, int size, u32 mem_size,
5108 bool zero_size_allowed)
5110 struct bpf_verifier_state *vstate = env->cur_state;
5111 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5112 struct bpf_reg_state *reg = &state->regs[regno];
5115 /* We may have adjusted the register pointing to memory region, so we
5116 * need to try adding each of min_value and max_value to off
5117 * to make sure our theoretical access will be safe.
5119 * The minimum value is only important with signed
5120 * comparisons where we can't assume the floor of a
5121 * value is 0. If we are using signed variables for our
5122 * index'es we need to make sure that whatever we use
5123 * will have a set floor within our range.
5125 if (reg->smin_value < 0 &&
5126 (reg->smin_value == S64_MIN ||
5127 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5128 reg->smin_value + off < 0)) {
5129 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5133 err = __check_mem_access(env, regno, reg->smin_value + off, size,
5134 mem_size, zero_size_allowed);
5136 verbose(env, "R%d min value is outside of the allowed memory range\n",
5141 /* If we haven't set a max value then we need to bail since we can't be
5142 * sure we won't do bad things.
5143 * If reg->umax_value + off could overflow, treat that as unbounded too.
5145 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5146 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5150 err = __check_mem_access(env, regno, reg->umax_value + off, size,
5151 mem_size, zero_size_allowed);
5153 verbose(env, "R%d max value is outside of the allowed memory range\n",
5161 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5162 const struct bpf_reg_state *reg, int regno,
5165 /* Access to this pointer-typed register or passing it to a helper
5166 * is only allowed in its original, unmodified form.
5170 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5171 reg_type_str(env, reg->type), regno, reg->off);
5175 if (!fixed_off_ok && reg->off) {
5176 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5177 reg_type_str(env, reg->type), regno, reg->off);
5181 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5184 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5185 verbose(env, "variable %s access var_off=%s disallowed\n",
5186 reg_type_str(env, reg->type), tn_buf);
5193 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5194 const struct bpf_reg_state *reg, int regno)
5196 return __check_ptr_off_reg(env, reg, regno, false);
5199 static int map_kptr_match_type(struct bpf_verifier_env *env,
5200 struct btf_field *kptr_field,
5201 struct bpf_reg_state *reg, u32 regno)
5203 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5205 const char *reg_name = "";
5207 if (btf_is_kernel(reg->btf)) {
5208 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5210 /* Only unreferenced case accepts untrusted pointers */
5211 if (kptr_field->type == BPF_KPTR_UNREF)
5212 perm_flags |= PTR_UNTRUSTED;
5214 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5215 if (kptr_field->type == BPF_KPTR_PERCPU)
5216 perm_flags |= MEM_PERCPU;
5219 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5222 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5223 reg_name = btf_type_name(reg->btf, reg->btf_id);
5225 /* For ref_ptr case, release function check should ensure we get one
5226 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5227 * normal store of unreferenced kptr, we must ensure var_off is zero.
5228 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5229 * reg->off and reg->ref_obj_id are not needed here.
5231 if (__check_ptr_off_reg(env, reg, regno, true))
5234 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5235 * we also need to take into account the reg->off.
5237 * We want to support cases like:
5245 * v = func(); // PTR_TO_BTF_ID
5246 * val->foo = v; // reg->off is zero, btf and btf_id match type
5247 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5248 * // first member type of struct after comparison fails
5249 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5252 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5253 * is zero. We must also ensure that btf_struct_ids_match does not walk
5254 * the struct to match type against first member of struct, i.e. reject
5255 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5256 * strict mode to true for type match.
5258 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5259 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5260 kptr_field->type != BPF_KPTR_UNREF))
5264 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5265 reg_type_str(env, reg->type), reg_name);
5266 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5267 if (kptr_field->type == BPF_KPTR_UNREF)
5268 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5275 static bool in_sleepable(struct bpf_verifier_env *env)
5277 return env->prog->sleepable;
5280 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5281 * can dereference RCU protected pointers and result is PTR_TRUSTED.
5283 static bool in_rcu_cs(struct bpf_verifier_env *env)
5285 return env->cur_state->active_rcu_lock ||
5286 env->cur_state->active_lock.ptr ||
5290 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5291 BTF_SET_START(rcu_protected_types)
5292 BTF_ID(struct, prog_test_ref_kfunc)
5293 #ifdef CONFIG_CGROUPS
5294 BTF_ID(struct, cgroup)
5296 #ifdef CONFIG_BPF_JIT
5297 BTF_ID(struct, bpf_cpumask)
5299 BTF_ID(struct, task_struct)
5300 BTF_SET_END(rcu_protected_types)
5302 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5304 if (!btf_is_kernel(btf))
5306 return btf_id_set_contains(&rcu_protected_types, btf_id);
5309 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5311 struct btf_struct_meta *meta;
5313 if (btf_is_kernel(kptr_field->kptr.btf))
5316 meta = btf_find_struct_meta(kptr_field->kptr.btf,
5317 kptr_field->kptr.btf_id);
5319 return meta ? meta->record : NULL;
5322 static bool rcu_safe_kptr(const struct btf_field *field)
5324 const struct btf_field_kptr *kptr = &field->kptr;
5326 return field->type == BPF_KPTR_PERCPU ||
5327 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5330 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5332 struct btf_record *rec;
5335 ret = PTR_MAYBE_NULL;
5336 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5338 if (kptr_field->type == BPF_KPTR_PERCPU)
5340 else if (!btf_is_kernel(kptr_field->kptr.btf))
5343 rec = kptr_pointee_btf_record(kptr_field);
5344 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5347 ret |= PTR_UNTRUSTED;
5353 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5354 int value_regno, int insn_idx,
5355 struct btf_field *kptr_field)
5357 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5358 int class = BPF_CLASS(insn->code);
5359 struct bpf_reg_state *val_reg;
5361 /* Things we already checked for in check_map_access and caller:
5362 * - Reject cases where variable offset may touch kptr
5363 * - size of access (must be BPF_DW)
5364 * - tnum_is_const(reg->var_off)
5365 * - kptr_field->offset == off + reg->var_off.value
5367 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5368 if (BPF_MODE(insn->code) != BPF_MEM) {
5369 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5373 /* We only allow loading referenced kptr, since it will be marked as
5374 * untrusted, similar to unreferenced kptr.
5376 if (class != BPF_LDX &&
5377 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5378 verbose(env, "store to referenced kptr disallowed\n");
5382 if (class == BPF_LDX) {
5383 val_reg = reg_state(env, value_regno);
5384 /* We can simply mark the value_regno receiving the pointer
5385 * value from map as PTR_TO_BTF_ID, with the correct type.
5387 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5388 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5389 /* For mark_ptr_or_null_reg */
5390 val_reg->id = ++env->id_gen;
5391 } else if (class == BPF_STX) {
5392 val_reg = reg_state(env, value_regno);
5393 if (!register_is_null(val_reg) &&
5394 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5396 } else if (class == BPF_ST) {
5398 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5399 kptr_field->offset);
5403 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5409 /* check read/write into a map element with possible variable offset */
5410 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5411 int off, int size, bool zero_size_allowed,
5412 enum bpf_access_src src)
5414 struct bpf_verifier_state *vstate = env->cur_state;
5415 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5416 struct bpf_reg_state *reg = &state->regs[regno];
5417 struct bpf_map *map = reg->map_ptr;
5418 struct btf_record *rec;
5421 err = check_mem_region_access(env, regno, off, size, map->value_size,
5426 if (IS_ERR_OR_NULL(map->record))
5429 for (i = 0; i < rec->cnt; i++) {
5430 struct btf_field *field = &rec->fields[i];
5431 u32 p = field->offset;
5433 /* If any part of a field can be touched by load/store, reject
5434 * this program. To check that [x1, x2) overlaps with [y1, y2),
5435 * it is sufficient to check x1 < y2 && y1 < x2.
5437 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5438 p < reg->umax_value + off + size) {
5439 switch (field->type) {
5440 case BPF_KPTR_UNREF:
5442 case BPF_KPTR_PERCPU:
5443 if (src != ACCESS_DIRECT) {
5444 verbose(env, "kptr cannot be accessed indirectly by helper\n");
5447 if (!tnum_is_const(reg->var_off)) {
5448 verbose(env, "kptr access cannot have variable offset\n");
5451 if (p != off + reg->var_off.value) {
5452 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5453 p, off + reg->var_off.value);
5456 if (size != bpf_size_to_bytes(BPF_DW)) {
5457 verbose(env, "kptr access size must be BPF_DW\n");
5462 verbose(env, "%s cannot be accessed directly by load/store\n",
5463 btf_field_type_name(field->type));
5471 #define MAX_PACKET_OFF 0xffff
5473 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5474 const struct bpf_call_arg_meta *meta,
5475 enum bpf_access_type t)
5477 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5479 switch (prog_type) {
5480 /* Program types only with direct read access go here! */
5481 case BPF_PROG_TYPE_LWT_IN:
5482 case BPF_PROG_TYPE_LWT_OUT:
5483 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5484 case BPF_PROG_TYPE_SK_REUSEPORT:
5485 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5486 case BPF_PROG_TYPE_CGROUP_SKB:
5491 /* Program types with direct read + write access go here! */
5492 case BPF_PROG_TYPE_SCHED_CLS:
5493 case BPF_PROG_TYPE_SCHED_ACT:
5494 case BPF_PROG_TYPE_XDP:
5495 case BPF_PROG_TYPE_LWT_XMIT:
5496 case BPF_PROG_TYPE_SK_SKB:
5497 case BPF_PROG_TYPE_SK_MSG:
5499 return meta->pkt_access;
5501 env->seen_direct_write = true;
5504 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5506 env->seen_direct_write = true;
5515 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5516 int size, bool zero_size_allowed)
5518 struct bpf_reg_state *regs = cur_regs(env);
5519 struct bpf_reg_state *reg = ®s[regno];
5522 /* We may have added a variable offset to the packet pointer; but any
5523 * reg->range we have comes after that. We are only checking the fixed
5527 /* We don't allow negative numbers, because we aren't tracking enough
5528 * detail to prove they're safe.
5530 if (reg->smin_value < 0) {
5531 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5536 err = reg->range < 0 ? -EINVAL :
5537 __check_mem_access(env, regno, off, size, reg->range,
5540 verbose(env, "R%d offset is outside of the packet\n", regno);
5544 /* __check_mem_access has made sure "off + size - 1" is within u16.
5545 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5546 * otherwise find_good_pkt_pointers would have refused to set range info
5547 * that __check_mem_access would have rejected this pkt access.
5548 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5550 env->prog->aux->max_pkt_offset =
5551 max_t(u32, env->prog->aux->max_pkt_offset,
5552 off + reg->umax_value + size - 1);
5557 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
5558 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5559 enum bpf_access_type t, enum bpf_reg_type *reg_type,
5560 struct btf **btf, u32 *btf_id)
5562 struct bpf_insn_access_aux info = {
5563 .reg_type = *reg_type,
5567 if (env->ops->is_valid_access &&
5568 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5569 /* A non zero info.ctx_field_size indicates that this field is a
5570 * candidate for later verifier transformation to load the whole
5571 * field and then apply a mask when accessed with a narrower
5572 * access than actual ctx access size. A zero info.ctx_field_size
5573 * will only allow for whole field access and rejects any other
5574 * type of narrower access.
5576 *reg_type = info.reg_type;
5578 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5580 *btf_id = info.btf_id;
5582 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5584 /* remember the offset of last byte accessed in ctx */
5585 if (env->prog->aux->max_ctx_offset < off + size)
5586 env->prog->aux->max_ctx_offset = off + size;
5590 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5594 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5597 if (size < 0 || off < 0 ||
5598 (u64)off + size > sizeof(struct bpf_flow_keys)) {
5599 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5606 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5607 u32 regno, int off, int size,
5608 enum bpf_access_type t)
5610 struct bpf_reg_state *regs = cur_regs(env);
5611 struct bpf_reg_state *reg = ®s[regno];
5612 struct bpf_insn_access_aux info = {};
5615 if (reg->smin_value < 0) {
5616 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5621 switch (reg->type) {
5622 case PTR_TO_SOCK_COMMON:
5623 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5626 valid = bpf_sock_is_valid_access(off, size, t, &info);
5628 case PTR_TO_TCP_SOCK:
5629 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5631 case PTR_TO_XDP_SOCK:
5632 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5640 env->insn_aux_data[insn_idx].ctx_field_size =
5641 info.ctx_field_size;
5645 verbose(env, "R%d invalid %s access off=%d size=%d\n",
5646 regno, reg_type_str(env, reg->type), off, size);
5651 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5653 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5656 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5658 const struct bpf_reg_state *reg = reg_state(env, regno);
5660 return reg->type == PTR_TO_CTX;
5663 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5665 const struct bpf_reg_state *reg = reg_state(env, regno);
5667 return type_is_sk_pointer(reg->type);
5670 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5672 const struct bpf_reg_state *reg = reg_state(env, regno);
5674 return type_is_pkt_pointer(reg->type);
5677 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5679 const struct bpf_reg_state *reg = reg_state(env, regno);
5681 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5682 return reg->type == PTR_TO_FLOW_KEYS;
5685 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
5687 const struct bpf_reg_state *reg = reg_state(env, regno);
5689 return reg->type == PTR_TO_ARENA;
5692 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5694 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5695 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5696 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5698 [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5701 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5703 /* A referenced register is always trusted. */
5704 if (reg->ref_obj_id)
5707 /* Types listed in the reg2btf_ids are always trusted */
5708 if (reg2btf_ids[base_type(reg->type)])
5711 /* If a register is not referenced, it is trusted if it has the
5712 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5713 * other type modifiers may be safe, but we elect to take an opt-in
5714 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5717 * Eventually, we should make PTR_TRUSTED the single source of truth
5718 * for whether a register is trusted.
5720 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5721 !bpf_type_has_unsafe_modifiers(reg->type);
5724 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5726 return reg->type & MEM_RCU;
5729 static void clear_trusted_flags(enum bpf_type_flag *flag)
5731 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5734 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5735 const struct bpf_reg_state *reg,
5736 int off, int size, bool strict)
5738 struct tnum reg_off;
5741 /* Byte size accesses are always allowed. */
5742 if (!strict || size == 1)
5745 /* For platforms that do not have a Kconfig enabling
5746 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5747 * NET_IP_ALIGN is universally set to '2'. And on platforms
5748 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5749 * to this code only in strict mode where we want to emulate
5750 * the NET_IP_ALIGN==2 checking. Therefore use an
5751 * unconditional IP align value of '2'.
5755 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5756 if (!tnum_is_aligned(reg_off, size)) {
5759 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5761 "misaligned packet access off %d+%s+%d+%d size %d\n",
5762 ip_align, tn_buf, reg->off, off, size);
5769 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5770 const struct bpf_reg_state *reg,
5771 const char *pointer_desc,
5772 int off, int size, bool strict)
5774 struct tnum reg_off;
5776 /* Byte size accesses are always allowed. */
5777 if (!strict || size == 1)
5780 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5781 if (!tnum_is_aligned(reg_off, size)) {
5784 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5785 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5786 pointer_desc, tn_buf, reg->off, off, size);
5793 static int check_ptr_alignment(struct bpf_verifier_env *env,
5794 const struct bpf_reg_state *reg, int off,
5795 int size, bool strict_alignment_once)
5797 bool strict = env->strict_alignment || strict_alignment_once;
5798 const char *pointer_desc = "";
5800 switch (reg->type) {
5802 case PTR_TO_PACKET_META:
5803 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5804 * right in front, treat it the very same way.
5806 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5807 case PTR_TO_FLOW_KEYS:
5808 pointer_desc = "flow keys ";
5810 case PTR_TO_MAP_KEY:
5811 pointer_desc = "key ";
5813 case PTR_TO_MAP_VALUE:
5814 pointer_desc = "value ";
5817 pointer_desc = "context ";
5820 pointer_desc = "stack ";
5821 /* The stack spill tracking logic in check_stack_write_fixed_off()
5822 * and check_stack_read_fixed_off() relies on stack accesses being
5828 pointer_desc = "sock ";
5830 case PTR_TO_SOCK_COMMON:
5831 pointer_desc = "sock_common ";
5833 case PTR_TO_TCP_SOCK:
5834 pointer_desc = "tcp_sock ";
5836 case PTR_TO_XDP_SOCK:
5837 pointer_desc = "xdp_sock ";
5844 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5848 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
5850 if (env->prog->jit_requested)
5851 return round_up(stack_depth, 16);
5853 /* round up to 32-bytes, since this is granularity
5854 * of interpreter stack size
5856 return round_up(max_t(u32, stack_depth, 1), 32);
5859 /* starting from main bpf function walk all instructions of the function
5860 * and recursively walk all callees that given function can call.
5861 * Ignore jump and exit insns.
5862 * Since recursion is prevented by check_cfg() this algorithm
5863 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5865 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5867 struct bpf_subprog_info *subprog = env->subprog_info;
5868 struct bpf_insn *insn = env->prog->insnsi;
5869 int depth = 0, frame = 0, i, subprog_end;
5870 bool tail_call_reachable = false;
5871 int ret_insn[MAX_CALL_FRAMES];
5872 int ret_prog[MAX_CALL_FRAMES];
5875 i = subprog[idx].start;
5877 /* protect against potential stack overflow that might happen when
5878 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5879 * depth for such case down to 256 so that the worst case scenario
5880 * would result in 8k stack size (32 which is tailcall limit * 256 =
5883 * To get the idea what might happen, see an example:
5884 * func1 -> sub rsp, 128
5885 * subfunc1 -> sub rsp, 256
5886 * tailcall1 -> add rsp, 256
5887 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5888 * subfunc2 -> sub rsp, 64
5889 * subfunc22 -> sub rsp, 128
5890 * tailcall2 -> add rsp, 128
5891 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5893 * tailcall will unwind the current stack frame but it will not get rid
5894 * of caller's stack as shown on the example above.
5896 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5898 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5902 depth += round_up_stack_depth(env, subprog[idx].stack_depth);
5903 if (depth > MAX_BPF_STACK) {
5904 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5909 subprog_end = subprog[idx + 1].start;
5910 for (; i < subprog_end; i++) {
5911 int next_insn, sidx;
5913 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5916 if (!is_bpf_throw_kfunc(insn + i))
5918 if (subprog[idx].is_cb)
5920 for (int c = 0; c < frame && !err; c++) {
5921 if (subprog[ret_prog[c]].is_cb) {
5929 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5934 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5936 /* remember insn and function to return to */
5937 ret_insn[frame] = i + 1;
5938 ret_prog[frame] = idx;
5940 /* find the callee */
5941 next_insn = i + insn[i].imm + 1;
5942 sidx = find_subprog(env, next_insn);
5944 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5948 if (subprog[sidx].is_async_cb) {
5949 if (subprog[sidx].has_tail_call) {
5950 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5953 /* async callbacks don't increase bpf prog stack size unless called directly */
5954 if (!bpf_pseudo_call(insn + i))
5956 if (subprog[sidx].is_exception_cb) {
5957 verbose(env, "insn %d cannot call exception cb directly\n", i);
5964 if (subprog[idx].has_tail_call)
5965 tail_call_reachable = true;
5968 if (frame >= MAX_CALL_FRAMES) {
5969 verbose(env, "the call stack of %d frames is too deep !\n",
5975 /* if tail call got detected across bpf2bpf calls then mark each of the
5976 * currently present subprog frames as tail call reachable subprogs;
5977 * this info will be utilized by JIT so that we will be preserving the
5978 * tail call counter throughout bpf2bpf calls combined with tailcalls
5980 if (tail_call_reachable)
5981 for (j = 0; j < frame; j++) {
5982 if (subprog[ret_prog[j]].is_exception_cb) {
5983 verbose(env, "cannot tail call within exception cb\n");
5986 subprog[ret_prog[j]].tail_call_reachable = true;
5988 if (subprog[0].tail_call_reachable)
5989 env->prog->aux->tail_call_reachable = true;
5991 /* end of for() loop means the last insn of the 'subprog'
5992 * was reached. Doesn't matter whether it was JA or EXIT
5996 depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
5998 i = ret_insn[frame];
5999 idx = ret_prog[frame];
6003 static int check_max_stack_depth(struct bpf_verifier_env *env)
6005 struct bpf_subprog_info *si = env->subprog_info;
6008 for (int i = 0; i < env->subprog_cnt; i++) {
6009 if (!i || si[i].is_async_cb) {
6010 ret = check_max_stack_depth_subprog(env, i);
6019 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6020 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6021 const struct bpf_insn *insn, int idx)
6023 int start = idx + insn->imm + 1, subprog;
6025 subprog = find_subprog(env, start);
6027 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6031 return env->subprog_info[subprog].stack_depth;
6035 static int __check_buffer_access(struct bpf_verifier_env *env,
6036 const char *buf_info,
6037 const struct bpf_reg_state *reg,
6038 int regno, int off, int size)
6042 "R%d invalid %s buffer access: off=%d, size=%d\n",
6043 regno, buf_info, off, size);
6046 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6049 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6051 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6052 regno, off, tn_buf);
6059 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6060 const struct bpf_reg_state *reg,
6061 int regno, int off, int size)
6065 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6069 if (off + size > env->prog->aux->max_tp_access)
6070 env->prog->aux->max_tp_access = off + size;
6075 static int check_buffer_access(struct bpf_verifier_env *env,
6076 const struct bpf_reg_state *reg,
6077 int regno, int off, int size,
6078 bool zero_size_allowed,
6081 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6084 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6088 if (off + size > *max_access)
6089 *max_access = off + size;
6094 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6095 static void zext_32_to_64(struct bpf_reg_state *reg)
6097 reg->var_off = tnum_subreg(reg->var_off);
6098 __reg_assign_32_into_64(reg);
6101 /* truncate register to smaller size (in bytes)
6102 * must be called with size < BPF_REG_SIZE
6104 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6108 /* clear high bits in bit representation */
6109 reg->var_off = tnum_cast(reg->var_off, size);
6111 /* fix arithmetic bounds */
6112 mask = ((u64)1 << (size * 8)) - 1;
6113 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6114 reg->umin_value &= mask;
6115 reg->umax_value &= mask;
6117 reg->umin_value = 0;
6118 reg->umax_value = mask;
6120 reg->smin_value = reg->umin_value;
6121 reg->smax_value = reg->umax_value;
6123 /* If size is smaller than 32bit register the 32bit register
6124 * values are also truncated so we push 64-bit bounds into
6125 * 32-bit bounds. Above were truncated < 32-bits already.
6128 __mark_reg32_unbounded(reg);
6130 reg_bounds_sync(reg);
6133 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6136 reg->smin_value = reg->s32_min_value = S8_MIN;
6137 reg->smax_value = reg->s32_max_value = S8_MAX;
6138 } else if (size == 2) {
6139 reg->smin_value = reg->s32_min_value = S16_MIN;
6140 reg->smax_value = reg->s32_max_value = S16_MAX;
6143 reg->smin_value = reg->s32_min_value = S32_MIN;
6144 reg->smax_value = reg->s32_max_value = S32_MAX;
6146 reg->umin_value = reg->u32_min_value = 0;
6147 reg->umax_value = U64_MAX;
6148 reg->u32_max_value = U32_MAX;
6149 reg->var_off = tnum_unknown;
6152 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6154 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6155 u64 top_smax_value, top_smin_value;
6156 u64 num_bits = size * 8;
6158 if (tnum_is_const(reg->var_off)) {
6159 u64_cval = reg->var_off.value;
6161 reg->var_off = tnum_const((s8)u64_cval);
6163 reg->var_off = tnum_const((s16)u64_cval);
6166 reg->var_off = tnum_const((s32)u64_cval);
6168 u64_cval = reg->var_off.value;
6169 reg->smax_value = reg->smin_value = u64_cval;
6170 reg->umax_value = reg->umin_value = u64_cval;
6171 reg->s32_max_value = reg->s32_min_value = u64_cval;
6172 reg->u32_max_value = reg->u32_min_value = u64_cval;
6176 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6177 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6179 if (top_smax_value != top_smin_value)
6182 /* find the s64_min and s64_min after sign extension */
6184 init_s64_max = (s8)reg->smax_value;
6185 init_s64_min = (s8)reg->smin_value;
6186 } else if (size == 2) {
6187 init_s64_max = (s16)reg->smax_value;
6188 init_s64_min = (s16)reg->smin_value;
6190 init_s64_max = (s32)reg->smax_value;
6191 init_s64_min = (s32)reg->smin_value;
6194 s64_max = max(init_s64_max, init_s64_min);
6195 s64_min = min(init_s64_max, init_s64_min);
6197 /* both of s64_max/s64_min positive or negative */
6198 if ((s64_max >= 0) == (s64_min >= 0)) {
6199 reg->smin_value = reg->s32_min_value = s64_min;
6200 reg->smax_value = reg->s32_max_value = s64_max;
6201 reg->umin_value = reg->u32_min_value = s64_min;
6202 reg->umax_value = reg->u32_max_value = s64_max;
6203 reg->var_off = tnum_range(s64_min, s64_max);
6208 set_sext64_default_val(reg, size);
6211 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6214 reg->s32_min_value = S8_MIN;
6215 reg->s32_max_value = S8_MAX;
6218 reg->s32_min_value = S16_MIN;
6219 reg->s32_max_value = S16_MAX;
6221 reg->u32_min_value = 0;
6222 reg->u32_max_value = U32_MAX;
6225 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6227 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6228 u32 top_smax_value, top_smin_value;
6229 u32 num_bits = size * 8;
6231 if (tnum_is_const(reg->var_off)) {
6232 u32_val = reg->var_off.value;
6234 reg->var_off = tnum_const((s8)u32_val);
6236 reg->var_off = tnum_const((s16)u32_val);
6238 u32_val = reg->var_off.value;
6239 reg->s32_min_value = reg->s32_max_value = u32_val;
6240 reg->u32_min_value = reg->u32_max_value = u32_val;
6244 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6245 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6247 if (top_smax_value != top_smin_value)
6250 /* find the s32_min and s32_min after sign extension */
6252 init_s32_max = (s8)reg->s32_max_value;
6253 init_s32_min = (s8)reg->s32_min_value;
6256 init_s32_max = (s16)reg->s32_max_value;
6257 init_s32_min = (s16)reg->s32_min_value;
6259 s32_max = max(init_s32_max, init_s32_min);
6260 s32_min = min(init_s32_max, init_s32_min);
6262 if ((s32_min >= 0) == (s32_max >= 0)) {
6263 reg->s32_min_value = s32_min;
6264 reg->s32_max_value = s32_max;
6265 reg->u32_min_value = (u32)s32_min;
6266 reg->u32_max_value = (u32)s32_max;
6271 set_sext32_default_val(reg, size);
6274 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6276 /* A map is considered read-only if the following condition are true:
6278 * 1) BPF program side cannot change any of the map content. The
6279 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6280 * and was set at map creation time.
6281 * 2) The map value(s) have been initialized from user space by a
6282 * loader and then "frozen", such that no new map update/delete
6283 * operations from syscall side are possible for the rest of
6284 * the map's lifetime from that point onwards.
6285 * 3) Any parallel/pending map update/delete operations from syscall
6286 * side have been completed. Only after that point, it's safe to
6287 * assume that map value(s) are immutable.
6289 return (map->map_flags & BPF_F_RDONLY_PROG) &&
6290 READ_ONCE(map->frozen) &&
6291 !bpf_map_write_active(map);
6294 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6301 err = map->ops->map_direct_value_addr(map, &addr, off);
6304 ptr = (void *)(long)addr + off;
6308 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6311 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6314 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6325 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
6326 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
6327 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
6330 * Allow list few fields as RCU trusted or full trusted.
6331 * This logic doesn't allow mix tagging and will be removed once GCC supports
6335 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6336 BTF_TYPE_SAFE_RCU(struct task_struct) {
6337 const cpumask_t *cpus_ptr;
6338 struct css_set __rcu *cgroups;
6339 struct task_struct __rcu *real_parent;
6340 struct task_struct *group_leader;
6343 BTF_TYPE_SAFE_RCU(struct cgroup) {
6344 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6345 struct kernfs_node *kn;
6348 BTF_TYPE_SAFE_RCU(struct css_set) {
6349 struct cgroup *dfl_cgrp;
6352 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6353 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6354 struct file __rcu *exe_file;
6357 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6358 * because bpf prog accessible sockets are SOCK_RCU_FREE.
6360 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6364 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6368 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6369 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6370 struct seq_file *seq;
6373 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6374 struct bpf_iter_meta *meta;
6375 struct task_struct *task;
6378 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6382 BTF_TYPE_SAFE_TRUSTED(struct file) {
6383 struct inode *f_inode;
6386 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6387 /* no negative dentry-s in places where bpf can see it */
6388 struct inode *d_inode;
6391 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6395 static bool type_is_rcu(struct bpf_verifier_env *env,
6396 struct bpf_reg_state *reg,
6397 const char *field_name, u32 btf_id)
6399 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6400 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6401 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6403 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6406 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6407 struct bpf_reg_state *reg,
6408 const char *field_name, u32 btf_id)
6410 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6411 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6412 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6414 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6417 static bool type_is_trusted(struct bpf_verifier_env *env,
6418 struct bpf_reg_state *reg,
6419 const char *field_name, u32 btf_id)
6421 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6422 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6423 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6424 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6425 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6426 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6428 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6431 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6432 struct bpf_reg_state *regs,
6433 int regno, int off, int size,
6434 enum bpf_access_type atype,
6437 struct bpf_reg_state *reg = regs + regno;
6438 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6439 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6440 const char *field_name = NULL;
6441 enum bpf_type_flag flag = 0;
6445 if (!env->allow_ptr_leaks) {
6447 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6451 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6453 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6459 "R%d is ptr_%s invalid negative access: off=%d\n",
6463 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6466 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6468 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6469 regno, tname, off, tn_buf);
6473 if (reg->type & MEM_USER) {
6475 "R%d is ptr_%s access user memory: off=%d\n",
6480 if (reg->type & MEM_PERCPU) {
6482 "R%d is ptr_%s access percpu memory: off=%d\n",
6487 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6488 if (!btf_is_kernel(reg->btf)) {
6489 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6492 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6494 /* Writes are permitted with default btf_struct_access for
6495 * program allocated objects (which always have ref_obj_id > 0),
6496 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6498 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6499 verbose(env, "only read is supported\n");
6503 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6504 !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6505 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6509 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6515 if (ret != PTR_TO_BTF_ID) {
6518 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6519 /* If this is an untrusted pointer, all pointers formed by walking it
6520 * also inherit the untrusted flag.
6522 flag = PTR_UNTRUSTED;
6524 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6525 /* By default any pointer obtained from walking a trusted pointer is no
6526 * longer trusted, unless the field being accessed has explicitly been
6527 * marked as inheriting its parent's state of trust (either full or RCU).
6529 * 'cgroups' pointer is untrusted if task->cgroups dereference
6530 * happened in a sleepable program outside of bpf_rcu_read_lock()
6531 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6532 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6534 * A regular RCU-protected pointer with __rcu tag can also be deemed
6535 * trusted if we are in an RCU CS. Such pointer can be NULL.
6537 if (type_is_trusted(env, reg, field_name, btf_id)) {
6538 flag |= PTR_TRUSTED;
6539 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6540 if (type_is_rcu(env, reg, field_name, btf_id)) {
6541 /* ignore __rcu tag and mark it MEM_RCU */
6543 } else if (flag & MEM_RCU ||
6544 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6545 /* __rcu tagged pointers can be NULL */
6546 flag |= MEM_RCU | PTR_MAYBE_NULL;
6548 /* We always trust them */
6549 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6550 flag & PTR_UNTRUSTED)
6551 flag &= ~PTR_UNTRUSTED;
6552 } else if (flag & (MEM_PERCPU | MEM_USER)) {
6555 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6556 clear_trusted_flags(&flag);
6560 * If not in RCU CS or MEM_RCU pointer can be NULL then
6561 * aggressively mark as untrusted otherwise such
6562 * pointers will be plain PTR_TO_BTF_ID without flags
6563 * and will be allowed to be passed into helpers for
6566 flag = PTR_UNTRUSTED;
6569 /* Old compat. Deprecated */
6570 clear_trusted_flags(&flag);
6573 if (atype == BPF_READ && value_regno >= 0)
6574 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6579 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6580 struct bpf_reg_state *regs,
6581 int regno, int off, int size,
6582 enum bpf_access_type atype,
6585 struct bpf_reg_state *reg = regs + regno;
6586 struct bpf_map *map = reg->map_ptr;
6587 struct bpf_reg_state map_reg;
6588 enum bpf_type_flag flag = 0;
6589 const struct btf_type *t;
6595 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6599 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6600 verbose(env, "map_ptr access not supported for map type %d\n",
6605 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6606 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6608 if (!env->allow_ptr_leaks) {
6610 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6616 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6621 if (atype != BPF_READ) {
6622 verbose(env, "only read from %s is supported\n", tname);
6626 /* Simulate access to a PTR_TO_BTF_ID */
6627 memset(&map_reg, 0, sizeof(map_reg));
6628 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6629 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6633 if (value_regno >= 0)
6634 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6639 /* Check that the stack access at the given offset is within bounds. The
6640 * maximum valid offset is -1.
6642 * The minimum valid offset is -MAX_BPF_STACK for writes, and
6643 * -state->allocated_stack for reads.
6645 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6647 struct bpf_func_state *state,
6648 enum bpf_access_type t)
6652 if (t == BPF_WRITE || env->allow_uninit_stack)
6653 min_valid_off = -MAX_BPF_STACK;
6655 min_valid_off = -state->allocated_stack;
6657 if (off < min_valid_off || off > -1)
6662 /* Check that the stack access at 'regno + off' falls within the maximum stack
6665 * 'off' includes `regno->offset`, but not its dynamic part (if any).
6667 static int check_stack_access_within_bounds(
6668 struct bpf_verifier_env *env,
6669 int regno, int off, int access_size,
6670 enum bpf_access_src src, enum bpf_access_type type)
6672 struct bpf_reg_state *regs = cur_regs(env);
6673 struct bpf_reg_state *reg = regs + regno;
6674 struct bpf_func_state *state = func(env, reg);
6675 s64 min_off, max_off;
6679 if (src == ACCESS_HELPER)
6680 /* We don't know if helpers are reading or writing (or both). */
6681 err_extra = " indirect access to";
6682 else if (type == BPF_READ)
6683 err_extra = " read from";
6685 err_extra = " write to";
6687 if (tnum_is_const(reg->var_off)) {
6688 min_off = (s64)reg->var_off.value + off;
6689 max_off = min_off + access_size;
6691 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6692 reg->smin_value <= -BPF_MAX_VAR_OFF) {
6693 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6697 min_off = reg->smin_value + off;
6698 max_off = reg->smax_value + off + access_size;
6701 err = check_stack_slot_within_bounds(env, min_off, state, type);
6702 if (!err && max_off > 0)
6703 err = -EINVAL; /* out of stack access into non-negative offsets */
6704 if (!err && access_size < 0)
6705 /* access_size should not be negative (or overflow an int); others checks
6706 * along the way should have prevented such an access.
6708 err = -EFAULT; /* invalid negative access size; integer overflow? */
6711 if (tnum_is_const(reg->var_off)) {
6712 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6713 err_extra, regno, off, access_size);
6717 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6718 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
6719 err_extra, regno, tn_buf, off, access_size);
6724 /* Note that there is no stack access with offset zero, so the needed stack
6725 * size is -min_off, not -min_off+1.
6727 return grow_stack_state(env, state, -min_off /* size */);
6730 /* check whether memory at (regno + off) is accessible for t = (read | write)
6731 * if t==write, value_regno is a register which value is stored into memory
6732 * if t==read, value_regno is a register which will receive the value from memory
6733 * if t==write && value_regno==-1, some unknown value is stored into memory
6734 * if t==read && value_regno==-1, don't care what we read from memory
6736 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6737 int off, int bpf_size, enum bpf_access_type t,
6738 int value_regno, bool strict_alignment_once, bool is_ldsx)
6740 struct bpf_reg_state *regs = cur_regs(env);
6741 struct bpf_reg_state *reg = regs + regno;
6744 size = bpf_size_to_bytes(bpf_size);
6748 /* alignment checks will add in reg->off themselves */
6749 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6753 /* for access checks, reg->off is just part of off */
6756 if (reg->type == PTR_TO_MAP_KEY) {
6757 if (t == BPF_WRITE) {
6758 verbose(env, "write to change key R%d not allowed\n", regno);
6762 err = check_mem_region_access(env, regno, off, size,
6763 reg->map_ptr->key_size, false);
6766 if (value_regno >= 0)
6767 mark_reg_unknown(env, regs, value_regno);
6768 } else if (reg->type == PTR_TO_MAP_VALUE) {
6769 struct btf_field *kptr_field = NULL;
6771 if (t == BPF_WRITE && value_regno >= 0 &&
6772 is_pointer_value(env, value_regno)) {
6773 verbose(env, "R%d leaks addr into map\n", value_regno);
6776 err = check_map_access_type(env, regno, off, size, t);
6779 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6782 if (tnum_is_const(reg->var_off))
6783 kptr_field = btf_record_find(reg->map_ptr->record,
6784 off + reg->var_off.value, BPF_KPTR);
6786 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6787 } else if (t == BPF_READ && value_regno >= 0) {
6788 struct bpf_map *map = reg->map_ptr;
6790 /* if map is read-only, track its contents as scalars */
6791 if (tnum_is_const(reg->var_off) &&
6792 bpf_map_is_rdonly(map) &&
6793 map->ops->map_direct_value_addr) {
6794 int map_off = off + reg->var_off.value;
6797 err = bpf_map_direct_read(map, map_off, size,
6802 regs[value_regno].type = SCALAR_VALUE;
6803 __mark_reg_known(®s[value_regno], val);
6805 mark_reg_unknown(env, regs, value_regno);
6808 } else if (base_type(reg->type) == PTR_TO_MEM) {
6809 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6811 if (type_may_be_null(reg->type)) {
6812 verbose(env, "R%d invalid mem access '%s'\n", regno,
6813 reg_type_str(env, reg->type));
6817 if (t == BPF_WRITE && rdonly_mem) {
6818 verbose(env, "R%d cannot write into %s\n",
6819 regno, reg_type_str(env, reg->type));
6823 if (t == BPF_WRITE && value_regno >= 0 &&
6824 is_pointer_value(env, value_regno)) {
6825 verbose(env, "R%d leaks addr into mem\n", value_regno);
6829 err = check_mem_region_access(env, regno, off, size,
6830 reg->mem_size, false);
6831 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6832 mark_reg_unknown(env, regs, value_regno);
6833 } else if (reg->type == PTR_TO_CTX) {
6834 enum bpf_reg_type reg_type = SCALAR_VALUE;
6835 struct btf *btf = NULL;
6838 if (t == BPF_WRITE && value_regno >= 0 &&
6839 is_pointer_value(env, value_regno)) {
6840 verbose(env, "R%d leaks addr into ctx\n", value_regno);
6844 err = check_ptr_off_reg(env, reg, regno);
6848 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
6851 verbose_linfo(env, insn_idx, "; ");
6852 if (!err && t == BPF_READ && value_regno >= 0) {
6853 /* ctx access returns either a scalar, or a
6854 * PTR_TO_PACKET[_META,_END]. In the latter
6855 * case, we know the offset is zero.
6857 if (reg_type == SCALAR_VALUE) {
6858 mark_reg_unknown(env, regs, value_regno);
6860 mark_reg_known_zero(env, regs,
6862 if (type_may_be_null(reg_type))
6863 regs[value_regno].id = ++env->id_gen;
6864 /* A load of ctx field could have different
6865 * actual load size with the one encoded in the
6866 * insn. When the dst is PTR, it is for sure not
6869 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6870 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6871 regs[value_regno].btf = btf;
6872 regs[value_regno].btf_id = btf_id;
6875 regs[value_regno].type = reg_type;
6878 } else if (reg->type == PTR_TO_STACK) {
6879 /* Basic bounds checks. */
6880 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6885 err = check_stack_read(env, regno, off, size,
6888 err = check_stack_write(env, regno, off, size,
6889 value_regno, insn_idx);
6890 } else if (reg_is_pkt_pointer(reg)) {
6891 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6892 verbose(env, "cannot write into packet\n");
6895 if (t == BPF_WRITE && value_regno >= 0 &&
6896 is_pointer_value(env, value_regno)) {
6897 verbose(env, "R%d leaks addr into packet\n",
6901 err = check_packet_access(env, regno, off, size, false);
6902 if (!err && t == BPF_READ && value_regno >= 0)
6903 mark_reg_unknown(env, regs, value_regno);
6904 } else if (reg->type == PTR_TO_FLOW_KEYS) {
6905 if (t == BPF_WRITE && value_regno >= 0 &&
6906 is_pointer_value(env, value_regno)) {
6907 verbose(env, "R%d leaks addr into flow keys\n",
6912 err = check_flow_keys_access(env, off, size);
6913 if (!err && t == BPF_READ && value_regno >= 0)
6914 mark_reg_unknown(env, regs, value_regno);
6915 } else if (type_is_sk_pointer(reg->type)) {
6916 if (t == BPF_WRITE) {
6917 verbose(env, "R%d cannot write into %s\n",
6918 regno, reg_type_str(env, reg->type));
6921 err = check_sock_access(env, insn_idx, regno, off, size, t);
6922 if (!err && value_regno >= 0)
6923 mark_reg_unknown(env, regs, value_regno);
6924 } else if (reg->type == PTR_TO_TP_BUFFER) {
6925 err = check_tp_buffer_access(env, reg, regno, off, size);
6926 if (!err && t == BPF_READ && value_regno >= 0)
6927 mark_reg_unknown(env, regs, value_regno);
6928 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6929 !type_may_be_null(reg->type)) {
6930 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6932 } else if (reg->type == CONST_PTR_TO_MAP) {
6933 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6935 } else if (base_type(reg->type) == PTR_TO_BUF) {
6936 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6940 if (t == BPF_WRITE) {
6941 verbose(env, "R%d cannot write into %s\n",
6942 regno, reg_type_str(env, reg->type));
6945 max_access = &env->prog->aux->max_rdonly_access;
6947 max_access = &env->prog->aux->max_rdwr_access;
6950 err = check_buffer_access(env, reg, regno, off, size, false,
6953 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6954 mark_reg_unknown(env, regs, value_regno);
6955 } else if (reg->type == PTR_TO_ARENA) {
6956 if (t == BPF_READ && value_regno >= 0)
6957 mark_reg_unknown(env, regs, value_regno);
6959 verbose(env, "R%d invalid mem access '%s'\n", regno,
6960 reg_type_str(env, reg->type));
6964 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6965 regs[value_regno].type == SCALAR_VALUE) {
6967 /* b/h/w load zero-extends, mark upper bits as known 0 */
6968 coerce_reg_to_size(®s[value_regno], size);
6970 coerce_reg_to_size_sx(®s[value_regno], size);
6975 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6980 switch (insn->imm) {
6982 case BPF_ADD | BPF_FETCH:
6984 case BPF_AND | BPF_FETCH:
6986 case BPF_OR | BPF_FETCH:
6988 case BPF_XOR | BPF_FETCH:
6993 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6997 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6998 verbose(env, "invalid atomic operand size\n");
7002 /* check src1 operand */
7003 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7007 /* check src2 operand */
7008 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7012 if (insn->imm == BPF_CMPXCHG) {
7013 /* Check comparison of R0 with memory location */
7014 const u32 aux_reg = BPF_REG_0;
7016 err = check_reg_arg(env, aux_reg, SRC_OP);
7020 if (is_pointer_value(env, aux_reg)) {
7021 verbose(env, "R%d leaks addr into mem\n", aux_reg);
7026 if (is_pointer_value(env, insn->src_reg)) {
7027 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7031 if (is_ctx_reg(env, insn->dst_reg) ||
7032 is_pkt_reg(env, insn->dst_reg) ||
7033 is_flow_key_reg(env, insn->dst_reg) ||
7034 is_sk_reg(env, insn->dst_reg) ||
7035 is_arena_reg(env, insn->dst_reg)) {
7036 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7038 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7042 if (insn->imm & BPF_FETCH) {
7043 if (insn->imm == BPF_CMPXCHG)
7044 load_reg = BPF_REG_0;
7046 load_reg = insn->src_reg;
7048 /* check and record load of old value */
7049 err = check_reg_arg(env, load_reg, DST_OP);
7053 /* This instruction accesses a memory location but doesn't
7054 * actually load it into a register.
7059 /* Check whether we can read the memory, with second call for fetch
7060 * case to simulate the register fill.
7062 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7063 BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7064 if (!err && load_reg >= 0)
7065 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7066 BPF_SIZE(insn->code), BPF_READ, load_reg,
7071 /* Check whether we can write into the same memory. */
7072 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7073 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7079 /* When register 'regno' is used to read the stack (either directly or through
7080 * a helper function) make sure that it's within stack boundary and, depending
7081 * on the access type and privileges, that all elements of the stack are
7084 * 'off' includes 'regno->off', but not its dynamic part (if any).
7086 * All registers that have been spilled on the stack in the slots within the
7087 * read offsets are marked as read.
7089 static int check_stack_range_initialized(
7090 struct bpf_verifier_env *env, int regno, int off,
7091 int access_size, bool zero_size_allowed,
7092 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7094 struct bpf_reg_state *reg = reg_state(env, regno);
7095 struct bpf_func_state *state = func(env, reg);
7096 int err, min_off, max_off, i, j, slot, spi;
7097 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7098 enum bpf_access_type bounds_check_type;
7099 /* Some accesses can write anything into the stack, others are
7102 bool clobber = false;
7104 if (access_size == 0 && !zero_size_allowed) {
7105 verbose(env, "invalid zero-sized read\n");
7109 if (type == ACCESS_HELPER) {
7110 /* The bounds checks for writes are more permissive than for
7111 * reads. However, if raw_mode is not set, we'll do extra
7114 bounds_check_type = BPF_WRITE;
7117 bounds_check_type = BPF_READ;
7119 err = check_stack_access_within_bounds(env, regno, off, access_size,
7120 type, bounds_check_type);
7125 if (tnum_is_const(reg->var_off)) {
7126 min_off = max_off = reg->var_off.value + off;
7128 /* Variable offset is prohibited for unprivileged mode for
7129 * simplicity since it requires corresponding support in
7130 * Spectre masking for stack ALU.
7131 * See also retrieve_ptr_limit().
7133 if (!env->bypass_spec_v1) {
7136 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7137 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7138 regno, err_extra, tn_buf);
7141 /* Only initialized buffer on stack is allowed to be accessed
7142 * with variable offset. With uninitialized buffer it's hard to
7143 * guarantee that whole memory is marked as initialized on
7144 * helper return since specific bounds are unknown what may
7145 * cause uninitialized stack leaking.
7147 if (meta && meta->raw_mode)
7150 min_off = reg->smin_value + off;
7151 max_off = reg->smax_value + off;
7154 if (meta && meta->raw_mode) {
7155 /* Ensure we won't be overwriting dynptrs when simulating byte
7156 * by byte access in check_helper_call using meta.access_size.
7157 * This would be a problem if we have a helper in the future
7160 * helper(uninit_mem, len, dynptr)
7162 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7163 * may end up writing to dynptr itself when touching memory from
7164 * arg 1. This can be relaxed on a case by case basis for known
7165 * safe cases, but reject due to the possibilitiy of aliasing by
7168 for (i = min_off; i < max_off + access_size; i++) {
7169 int stack_off = -i - 1;
7172 /* raw_mode may write past allocated_stack */
7173 if (state->allocated_stack <= stack_off)
7175 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7176 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7180 meta->access_size = access_size;
7181 meta->regno = regno;
7185 for (i = min_off; i < max_off + access_size; i++) {
7189 spi = slot / BPF_REG_SIZE;
7190 if (state->allocated_stack <= slot) {
7191 verbose(env, "verifier bug: allocated_stack too small");
7195 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7196 if (*stype == STACK_MISC)
7198 if ((*stype == STACK_ZERO) ||
7199 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7201 /* helper can write anything into the stack */
7202 *stype = STACK_MISC;
7207 if (is_spilled_reg(&state->stack[spi]) &&
7208 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7209 env->allow_ptr_leaks)) {
7211 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7212 for (j = 0; j < BPF_REG_SIZE; j++)
7213 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7218 if (tnum_is_const(reg->var_off)) {
7219 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7220 err_extra, regno, min_off, i - min_off, access_size);
7224 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7225 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7226 err_extra, regno, tn_buf, i - min_off, access_size);
7230 /* reading any byte out of 8-byte 'spill_slot' will cause
7231 * the whole slot to be marked as 'read'
7233 mark_reg_read(env, &state->stack[spi].spilled_ptr,
7234 state->stack[spi].spilled_ptr.parent,
7236 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7237 * be sure that whether stack slot is written to or not. Hence,
7238 * we must still conservatively propagate reads upwards even if
7239 * helper may write to the entire memory range.
7245 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7246 int access_size, bool zero_size_allowed,
7247 struct bpf_call_arg_meta *meta)
7249 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7252 switch (base_type(reg->type)) {
7254 case PTR_TO_PACKET_META:
7255 return check_packet_access(env, regno, reg->off, access_size,
7257 case PTR_TO_MAP_KEY:
7258 if (meta && meta->raw_mode) {
7259 verbose(env, "R%d cannot write into %s\n", regno,
7260 reg_type_str(env, reg->type));
7263 return check_mem_region_access(env, regno, reg->off, access_size,
7264 reg->map_ptr->key_size, false);
7265 case PTR_TO_MAP_VALUE:
7266 if (check_map_access_type(env, regno, reg->off, access_size,
7267 meta && meta->raw_mode ? BPF_WRITE :
7270 return check_map_access(env, regno, reg->off, access_size,
7271 zero_size_allowed, ACCESS_HELPER);
7273 if (type_is_rdonly_mem(reg->type)) {
7274 if (meta && meta->raw_mode) {
7275 verbose(env, "R%d cannot write into %s\n", regno,
7276 reg_type_str(env, reg->type));
7280 return check_mem_region_access(env, regno, reg->off,
7281 access_size, reg->mem_size,
7284 if (type_is_rdonly_mem(reg->type)) {
7285 if (meta && meta->raw_mode) {
7286 verbose(env, "R%d cannot write into %s\n", regno,
7287 reg_type_str(env, reg->type));
7291 max_access = &env->prog->aux->max_rdonly_access;
7293 max_access = &env->prog->aux->max_rdwr_access;
7295 return check_buffer_access(env, reg, regno, reg->off,
7296 access_size, zero_size_allowed,
7299 return check_stack_range_initialized(
7301 regno, reg->off, access_size,
7302 zero_size_allowed, ACCESS_HELPER, meta);
7304 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7305 access_size, BPF_READ, -1);
7307 /* in case the function doesn't know how to access the context,
7308 * (because we are in a program of type SYSCALL for example), we
7309 * can not statically check its size.
7310 * Dynamically check it now.
7312 if (!env->ops->convert_ctx_access) {
7313 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7314 int offset = access_size - 1;
7316 /* Allow zero-byte read from PTR_TO_CTX */
7317 if (access_size == 0)
7318 return zero_size_allowed ? 0 : -EACCES;
7320 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7321 atype, -1, false, false);
7325 default: /* scalar_value or invalid ptr */
7326 /* Allow zero-byte read from NULL, regardless of pointer type */
7327 if (zero_size_allowed && access_size == 0 &&
7328 register_is_null(reg))
7331 verbose(env, "R%d type=%s ", regno,
7332 reg_type_str(env, reg->type));
7333 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7338 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7341 * @regno is the register containing the access size. regno-1 is the register
7342 * containing the pointer.
7344 static int check_mem_size_reg(struct bpf_verifier_env *env,
7345 struct bpf_reg_state *reg, u32 regno,
7346 bool zero_size_allowed,
7347 struct bpf_call_arg_meta *meta)
7351 /* This is used to refine r0 return value bounds for helpers
7352 * that enforce this value as an upper bound on return values.
7353 * See do_refine_retval_range() for helpers that can refine
7354 * the return value. C type of helper is u32 so we pull register
7355 * bound from umax_value however, if negative verifier errors
7356 * out. Only upper bounds can be learned because retval is an
7357 * int type and negative retvals are allowed.
7359 meta->msize_max_value = reg->umax_value;
7361 /* The register is SCALAR_VALUE; the access check
7362 * happens using its boundaries.
7364 if (!tnum_is_const(reg->var_off))
7365 /* For unprivileged variable accesses, disable raw
7366 * mode so that the program is required to
7367 * initialize all the memory that the helper could
7368 * just partially fill up.
7372 if (reg->smin_value < 0) {
7373 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7378 if (reg->umin_value == 0 && !zero_size_allowed) {
7379 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7380 regno, reg->umin_value, reg->umax_value);
7384 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7385 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7389 err = check_helper_mem_access(env, regno - 1,
7391 zero_size_allowed, meta);
7393 err = mark_chain_precision(env, regno);
7397 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7398 u32 regno, u32 mem_size)
7400 bool may_be_null = type_may_be_null(reg->type);
7401 struct bpf_reg_state saved_reg;
7402 struct bpf_call_arg_meta meta;
7405 if (register_is_null(reg))
7408 memset(&meta, 0, sizeof(meta));
7409 /* Assuming that the register contains a value check if the memory
7410 * access is safe. Temporarily save and restore the register's state as
7411 * the conversion shouldn't be visible to a caller.
7415 mark_ptr_not_null_reg(reg);
7418 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7419 /* Check access for BPF_WRITE */
7420 meta.raw_mode = true;
7421 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7429 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7432 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7433 bool may_be_null = type_may_be_null(mem_reg->type);
7434 struct bpf_reg_state saved_reg;
7435 struct bpf_call_arg_meta meta;
7438 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7440 memset(&meta, 0, sizeof(meta));
7443 saved_reg = *mem_reg;
7444 mark_ptr_not_null_reg(mem_reg);
7447 err = check_mem_size_reg(env, reg, regno, true, &meta);
7448 /* Check access for BPF_WRITE */
7449 meta.raw_mode = true;
7450 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7453 *mem_reg = saved_reg;
7457 /* Implementation details:
7458 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7459 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7460 * Two bpf_map_lookups (even with the same key) will have different reg->id.
7461 * Two separate bpf_obj_new will also have different reg->id.
7462 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7463 * clears reg->id after value_or_null->value transition, since the verifier only
7464 * cares about the range of access to valid map value pointer and doesn't care
7465 * about actual address of the map element.
7466 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7467 * reg->id > 0 after value_or_null->value transition. By doing so
7468 * two bpf_map_lookups will be considered two different pointers that
7469 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7470 * returned from bpf_obj_new.
7471 * The verifier allows taking only one bpf_spin_lock at a time to avoid
7473 * Since only one bpf_spin_lock is allowed the checks are simpler than
7474 * reg_is_refcounted() logic. The verifier needs to remember only
7475 * one spin_lock instead of array of acquired_refs.
7476 * cur_state->active_lock remembers which map value element or allocated
7477 * object got locked and clears it after bpf_spin_unlock.
7479 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7482 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7483 struct bpf_verifier_state *cur = env->cur_state;
7484 bool is_const = tnum_is_const(reg->var_off);
7485 u64 val = reg->var_off.value;
7486 struct bpf_map *map = NULL;
7487 struct btf *btf = NULL;
7488 struct btf_record *rec;
7492 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7496 if (reg->type == PTR_TO_MAP_VALUE) {
7500 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7508 rec = reg_btf_record(reg);
7509 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7510 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7511 map ? map->name : "kptr");
7514 if (rec->spin_lock_off != val + reg->off) {
7515 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7516 val + reg->off, rec->spin_lock_off);
7520 if (cur->active_lock.ptr) {
7522 "Locking two bpf_spin_locks are not allowed\n");
7526 cur->active_lock.ptr = map;
7528 cur->active_lock.ptr = btf;
7529 cur->active_lock.id = reg->id;
7538 if (!cur->active_lock.ptr) {
7539 verbose(env, "bpf_spin_unlock without taking a lock\n");
7542 if (cur->active_lock.ptr != ptr ||
7543 cur->active_lock.id != reg->id) {
7544 verbose(env, "bpf_spin_unlock of different lock\n");
7548 invalidate_non_owning_refs(env);
7550 cur->active_lock.ptr = NULL;
7551 cur->active_lock.id = 0;
7556 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7557 struct bpf_call_arg_meta *meta)
7559 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7560 bool is_const = tnum_is_const(reg->var_off);
7561 struct bpf_map *map = reg->map_ptr;
7562 u64 val = reg->var_off.value;
7566 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7571 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7575 if (!btf_record_has_field(map->record, BPF_TIMER)) {
7576 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7579 if (map->record->timer_off != val + reg->off) {
7580 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7581 val + reg->off, map->record->timer_off);
7584 if (meta->map_ptr) {
7585 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7588 meta->map_uid = reg->map_uid;
7589 meta->map_ptr = map;
7593 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7594 struct bpf_call_arg_meta *meta)
7596 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7597 struct bpf_map *map_ptr = reg->map_ptr;
7598 struct btf_field *kptr_field;
7601 if (!tnum_is_const(reg->var_off)) {
7603 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7607 if (!map_ptr->btf) {
7608 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7612 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7613 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7617 meta->map_ptr = map_ptr;
7618 kptr_off = reg->off + reg->var_off.value;
7619 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7621 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7624 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7625 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7628 meta->kptr_field = kptr_field;
7632 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7633 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7635 * In both cases we deal with the first 8 bytes, but need to mark the next 8
7636 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7637 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7639 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7640 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7641 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7642 * mutate the view of the dynptr and also possibly destroy it. In the latter
7643 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7644 * memory that dynptr points to.
7646 * The verifier will keep track both levels of mutation (bpf_dynptr's in
7647 * reg->type and the memory's in reg->dynptr.type), but there is no support for
7648 * readonly dynptr view yet, hence only the first case is tracked and checked.
7650 * This is consistent with how C applies the const modifier to a struct object,
7651 * where the pointer itself inside bpf_dynptr becomes const but not what it
7654 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7655 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7657 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7658 enum bpf_arg_type arg_type, int clone_ref_obj_id)
7660 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7663 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7664 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7666 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7667 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7671 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
7672 * constructing a mutable bpf_dynptr object.
7674 * Currently, this is only possible with PTR_TO_STACK
7675 * pointing to a region of at least 16 bytes which doesn't
7676 * contain an existing bpf_dynptr.
7678 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7679 * mutated or destroyed. However, the memory it points to
7682 * None - Points to a initialized dynptr that can be mutated and
7683 * destroyed, including mutation of the memory it points
7686 if (arg_type & MEM_UNINIT) {
7689 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7690 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7694 /* we write BPF_DW bits (8 bytes) at a time */
7695 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7696 err = check_mem_access(env, insn_idx, regno,
7697 i, BPF_DW, BPF_WRITE, -1, false, false);
7702 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7703 } else /* MEM_RDONLY and None case from above */ {
7704 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7705 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7706 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7710 if (!is_dynptr_reg_valid_init(env, reg)) {
7712 "Expected an initialized dynptr as arg #%d\n",
7717 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7718 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7720 "Expected a dynptr of type %s as arg #%d\n",
7721 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7725 err = mark_dynptr_read(env, reg);
7730 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7732 struct bpf_func_state *state = func(env, reg);
7734 return state->stack[spi].spilled_ptr.ref_obj_id;
7737 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7739 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7742 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7744 return meta->kfunc_flags & KF_ITER_NEW;
7747 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7749 return meta->kfunc_flags & KF_ITER_NEXT;
7752 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7754 return meta->kfunc_flags & KF_ITER_DESTROY;
7757 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7759 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7760 * kfunc is iter state pointer
7762 return arg == 0 && is_iter_kfunc(meta);
7765 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7766 struct bpf_kfunc_call_arg_meta *meta)
7768 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7769 const struct btf_type *t;
7770 const struct btf_param *arg;
7771 int spi, err, i, nr_slots;
7774 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7775 arg = &btf_params(meta->func_proto)[0];
7776 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
7777 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
7778 nr_slots = t->size / BPF_REG_SIZE;
7780 if (is_iter_new_kfunc(meta)) {
7781 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7782 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7783 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7784 iter_type_str(meta->btf, btf_id), regno);
7788 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7789 err = check_mem_access(env, insn_idx, regno,
7790 i, BPF_DW, BPF_WRITE, -1, false, false);
7795 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7799 /* iter_next() or iter_destroy() expect initialized iter state*/
7800 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7805 verbose(env, "expected an initialized iter_%s as arg #%d\n",
7806 iter_type_str(meta->btf, btf_id), regno);
7809 verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7815 spi = iter_get_spi(env, reg, nr_slots);
7819 err = mark_iter_read(env, reg, spi, nr_slots);
7823 /* remember meta->iter info for process_iter_next_call() */
7824 meta->iter.spi = spi;
7825 meta->iter.frameno = reg->frameno;
7826 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7828 if (is_iter_destroy_kfunc(meta)) {
7829 err = unmark_stack_slots_iter(env, reg, nr_slots);
7838 /* Look for a previous loop entry at insn_idx: nearest parent state
7839 * stopped at insn_idx with callsites matching those in cur->frame.
7841 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7842 struct bpf_verifier_state *cur,
7845 struct bpf_verifier_state_list *sl;
7846 struct bpf_verifier_state *st;
7848 /* Explored states are pushed in stack order, most recent states come first */
7849 sl = *explored_state(env, insn_idx);
7850 for (; sl; sl = sl->next) {
7851 /* If st->branches != 0 state is a part of current DFS verification path,
7852 * hence cur & st for a loop.
7855 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7856 st->dfs_depth < cur->dfs_depth)
7863 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7864 static bool regs_exact(const struct bpf_reg_state *rold,
7865 const struct bpf_reg_state *rcur,
7866 struct bpf_idmap *idmap);
7868 static void maybe_widen_reg(struct bpf_verifier_env *env,
7869 struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7870 struct bpf_idmap *idmap)
7872 if (rold->type != SCALAR_VALUE)
7874 if (rold->type != rcur->type)
7876 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7878 __mark_reg_unknown(env, rcur);
7881 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7882 struct bpf_verifier_state *old,
7883 struct bpf_verifier_state *cur)
7885 struct bpf_func_state *fold, *fcur;
7888 reset_idmap_scratch(env);
7889 for (fr = old->curframe; fr >= 0; fr--) {
7890 fold = old->frame[fr];
7891 fcur = cur->frame[fr];
7893 for (i = 0; i < MAX_BPF_REG; i++)
7894 maybe_widen_reg(env,
7897 &env->idmap_scratch);
7899 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7900 if (!is_spilled_reg(&fold->stack[i]) ||
7901 !is_spilled_reg(&fcur->stack[i]))
7904 maybe_widen_reg(env,
7905 &fold->stack[i].spilled_ptr,
7906 &fcur->stack[i].spilled_ptr,
7907 &env->idmap_scratch);
7913 /* process_iter_next_call() is called when verifier gets to iterator's next
7914 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7915 * to it as just "iter_next()" in comments below.
7917 * BPF verifier relies on a crucial contract for any iter_next()
7918 * implementation: it should *eventually* return NULL, and once that happens
7919 * it should keep returning NULL. That is, once iterator exhausts elements to
7920 * iterate, it should never reset or spuriously return new elements.
7922 * With the assumption of such contract, process_iter_next_call() simulates
7923 * a fork in the verifier state to validate loop logic correctness and safety
7924 * without having to simulate infinite amount of iterations.
7926 * In current state, we first assume that iter_next() returned NULL and
7927 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7928 * conditions we should not form an infinite loop and should eventually reach
7931 * Besides that, we also fork current state and enqueue it for later
7932 * verification. In a forked state we keep iterator state as ACTIVE
7933 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7934 * also bump iteration depth to prevent erroneous infinite loop detection
7935 * later on (see iter_active_depths_differ() comment for details). In this
7936 * state we assume that we'll eventually loop back to another iter_next()
7937 * calls (it could be in exactly same location or in some other instruction,
7938 * it doesn't matter, we don't make any unnecessary assumptions about this,
7939 * everything revolves around iterator state in a stack slot, not which
7940 * instruction is calling iter_next()). When that happens, we either will come
7941 * to iter_next() with equivalent state and can conclude that next iteration
7942 * will proceed in exactly the same way as we just verified, so it's safe to
7943 * assume that loop converges. If not, we'll go on another iteration
7944 * simulation with a different input state, until all possible starting states
7945 * are validated or we reach maximum number of instructions limit.
7947 * This way, we will either exhaustively discover all possible input states
7948 * that iterator loop can start with and eventually will converge, or we'll
7949 * effectively regress into bounded loop simulation logic and either reach
7950 * maximum number of instructions if loop is not provably convergent, or there
7951 * is some statically known limit on number of iterations (e.g., if there is
7952 * an explicit `if n > 100 then break;` statement somewhere in the loop).
7954 * Iteration convergence logic in is_state_visited() relies on exact
7955 * states comparison, which ignores read and precision marks.
7956 * This is necessary because read and precision marks are not finalized
7957 * while in the loop. Exact comparison might preclude convergence for
7958 * simple programs like below:
7961 * while(iter_next(&it))
7964 * At each iteration step i++ would produce a new distinct state and
7965 * eventually instruction processing limit would be reached.
7967 * To avoid such behavior speculatively forget (widen) range for
7968 * imprecise scalar registers, if those registers were not precise at the
7969 * end of the previous iteration and do not match exactly.
7971 * This is a conservative heuristic that allows to verify wide range of programs,
7972 * however it precludes verification of programs that conjure an
7973 * imprecise value on the first loop iteration and use it as precise on a second.
7974 * For example, the following safe program would fail to verify:
7976 * struct bpf_num_iter it;
7979 * bpf_iter_num_new(&it, 0, 10);
7980 * while (bpf_iter_num_next(&it)) {
7983 * i = 7; // Because i changed verifier would forget
7984 * // it's range on second loop entry.
7986 * arr[i] = 42; // This would fail to verify.
7989 * bpf_iter_num_destroy(&it);
7991 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7992 struct bpf_kfunc_call_arg_meta *meta)
7994 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7995 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7996 struct bpf_reg_state *cur_iter, *queued_iter;
7997 int iter_frameno = meta->iter.frameno;
7998 int iter_spi = meta->iter.spi;
8000 BTF_TYPE_EMIT(struct bpf_iter);
8002 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8004 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8005 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8006 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
8007 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8011 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
8012 /* Because iter_next() call is a checkpoint is_state_visitied()
8013 * should guarantee parent state with same call sites and insn_idx.
8015 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8016 !same_callsites(cur_st->parent, cur_st)) {
8017 verbose(env, "bug: bad parent state for iter next call");
8020 /* Note cur_st->parent in the call below, it is necessary to skip
8021 * checkpoint created for cur_st by is_state_visited()
8022 * right at this instruction.
8024 prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8025 /* branch out active iter state */
8026 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8030 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8031 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8032 queued_iter->iter.depth++;
8034 widen_imprecise_scalars(env, prev_st, queued_st);
8036 queued_fr = queued_st->frame[queued_st->curframe];
8037 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8040 /* switch to DRAINED state, but keep the depth unchanged */
8041 /* mark current iter state as drained and assume returned NULL */
8042 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8043 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8048 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8050 return type == ARG_CONST_SIZE ||
8051 type == ARG_CONST_SIZE_OR_ZERO;
8054 static bool arg_type_is_release(enum bpf_arg_type type)
8056 return type & OBJ_RELEASE;
8059 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8061 return base_type(type) == ARG_PTR_TO_DYNPTR;
8064 static int int_ptr_type_to_size(enum bpf_arg_type type)
8066 if (type == ARG_PTR_TO_INT)
8068 else if (type == ARG_PTR_TO_LONG)
8074 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8075 const struct bpf_call_arg_meta *meta,
8076 enum bpf_arg_type *arg_type)
8078 if (!meta->map_ptr) {
8079 /* kernel subsystem misconfigured verifier */
8080 verbose(env, "invalid map_ptr to access map->type\n");
8084 switch (meta->map_ptr->map_type) {
8085 case BPF_MAP_TYPE_SOCKMAP:
8086 case BPF_MAP_TYPE_SOCKHASH:
8087 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8088 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8090 verbose(env, "invalid arg_type for sockmap/sockhash\n");
8094 case BPF_MAP_TYPE_BLOOM_FILTER:
8095 if (meta->func_id == BPF_FUNC_map_peek_elem)
8096 *arg_type = ARG_PTR_TO_MAP_VALUE;
8104 struct bpf_reg_types {
8105 const enum bpf_reg_type types[10];
8109 static const struct bpf_reg_types sock_types = {
8119 static const struct bpf_reg_types btf_id_sock_common_types = {
8126 PTR_TO_BTF_ID | PTR_TRUSTED,
8128 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8132 static const struct bpf_reg_types mem_types = {
8140 PTR_TO_MEM | MEM_RINGBUF,
8142 PTR_TO_BTF_ID | PTR_TRUSTED,
8146 static const struct bpf_reg_types int_ptr_types = {
8156 static const struct bpf_reg_types spin_lock_types = {
8159 PTR_TO_BTF_ID | MEM_ALLOC,
8163 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8164 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8165 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8166 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8167 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8168 static const struct bpf_reg_types btf_ptr_types = {
8171 PTR_TO_BTF_ID | PTR_TRUSTED,
8172 PTR_TO_BTF_ID | MEM_RCU,
8175 static const struct bpf_reg_types percpu_btf_ptr_types = {
8177 PTR_TO_BTF_ID | MEM_PERCPU,
8178 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8179 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8182 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8183 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8184 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8185 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8186 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8187 static const struct bpf_reg_types dynptr_types = {
8190 CONST_PTR_TO_DYNPTR,
8194 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8195 [ARG_PTR_TO_MAP_KEY] = &mem_types,
8196 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
8197 [ARG_CONST_SIZE] = &scalar_types,
8198 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
8199 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
8200 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
8201 [ARG_PTR_TO_CTX] = &context_types,
8202 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
8204 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
8206 [ARG_PTR_TO_SOCKET] = &fullsock_types,
8207 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
8208 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
8209 [ARG_PTR_TO_MEM] = &mem_types,
8210 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
8211 [ARG_PTR_TO_INT] = &int_ptr_types,
8212 [ARG_PTR_TO_LONG] = &int_ptr_types,
8213 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
8214 [ARG_PTR_TO_FUNC] = &func_ptr_types,
8215 [ARG_PTR_TO_STACK] = &stack_ptr_types,
8216 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
8217 [ARG_PTR_TO_TIMER] = &timer_types,
8218 [ARG_PTR_TO_KPTR] = &kptr_types,
8219 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
8222 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8223 enum bpf_arg_type arg_type,
8224 const u32 *arg_btf_id,
8225 struct bpf_call_arg_meta *meta)
8227 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8228 enum bpf_reg_type expected, type = reg->type;
8229 const struct bpf_reg_types *compatible;
8232 compatible = compatible_reg_types[base_type(arg_type)];
8234 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8238 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8239 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8241 * Same for MAYBE_NULL:
8243 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8244 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8246 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8248 * Therefore we fold these flags depending on the arg_type before comparison.
8250 if (arg_type & MEM_RDONLY)
8251 type &= ~MEM_RDONLY;
8252 if (arg_type & PTR_MAYBE_NULL)
8253 type &= ~PTR_MAYBE_NULL;
8254 if (base_type(arg_type) == ARG_PTR_TO_MEM)
8255 type &= ~DYNPTR_TYPE_FLAG_MASK;
8257 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) {
8259 type &= ~MEM_PERCPU;
8262 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8263 expected = compatible->types[i];
8264 if (expected == NOT_INIT)
8267 if (type == expected)
8271 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8272 for (j = 0; j + 1 < i; j++)
8273 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8274 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8278 if (base_type(reg->type) != PTR_TO_BTF_ID)
8281 if (compatible == &mem_types) {
8282 if (!(arg_type & MEM_RDONLY)) {
8284 "%s() may write into memory pointed by R%d type=%s\n",
8285 func_id_name(meta->func_id),
8286 regno, reg_type_str(env, reg->type));
8292 switch ((int)reg->type) {
8294 case PTR_TO_BTF_ID | PTR_TRUSTED:
8295 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
8296 case PTR_TO_BTF_ID | MEM_RCU:
8297 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8298 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8300 /* For bpf_sk_release, it needs to match against first member
8301 * 'struct sock_common', hence make an exception for it. This
8302 * allows bpf_sk_release to work for multiple socket types.
8304 bool strict_type_match = arg_type_is_release(arg_type) &&
8305 meta->func_id != BPF_FUNC_sk_release;
8307 if (type_may_be_null(reg->type) &&
8308 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8309 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8314 if (!compatible->btf_id) {
8315 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8318 arg_btf_id = compatible->btf_id;
8321 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8322 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8325 if (arg_btf_id == BPF_PTR_POISON) {
8326 verbose(env, "verifier internal error:");
8327 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8332 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8333 btf_vmlinux, *arg_btf_id,
8334 strict_type_match)) {
8335 verbose(env, "R%d is of type %s but %s is expected\n",
8336 regno, btf_type_name(reg->btf, reg->btf_id),
8337 btf_type_name(btf_vmlinux, *arg_btf_id));
8343 case PTR_TO_BTF_ID | MEM_ALLOC:
8344 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8345 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8346 meta->func_id != BPF_FUNC_kptr_xchg) {
8347 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8350 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8351 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8355 case PTR_TO_BTF_ID | MEM_PERCPU:
8356 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8357 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8358 /* Handled by helper specific checks */
8361 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8367 static struct btf_field *
8368 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8370 struct btf_field *field;
8371 struct btf_record *rec;
8373 rec = reg_btf_record(reg);
8377 field = btf_record_find(rec, off, fields);
8384 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8385 const struct bpf_reg_state *reg, int regno,
8386 enum bpf_arg_type arg_type)
8388 u32 type = reg->type;
8390 /* When referenced register is passed to release function, its fixed
8393 * We will check arg_type_is_release reg has ref_obj_id when storing
8394 * meta->release_regno.
8396 if (arg_type_is_release(arg_type)) {
8397 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8398 * may not directly point to the object being released, but to
8399 * dynptr pointing to such object, which might be at some offset
8400 * on the stack. In that case, we simply to fallback to the
8403 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8406 /* Doing check_ptr_off_reg check for the offset will catch this
8407 * because fixed_off_ok is false, but checking here allows us
8408 * to give the user a better error message.
8411 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8415 return __check_ptr_off_reg(env, reg, regno, false);
8419 /* Pointer types where both fixed and variable offset is explicitly allowed: */
8422 case PTR_TO_PACKET_META:
8423 case PTR_TO_MAP_KEY:
8424 case PTR_TO_MAP_VALUE:
8426 case PTR_TO_MEM | MEM_RDONLY:
8427 case PTR_TO_MEM | MEM_RINGBUF:
8429 case PTR_TO_BUF | MEM_RDONLY:
8433 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8437 case PTR_TO_BTF_ID | MEM_ALLOC:
8438 case PTR_TO_BTF_ID | PTR_TRUSTED:
8439 case PTR_TO_BTF_ID | MEM_RCU:
8440 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8441 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8442 /* When referenced PTR_TO_BTF_ID is passed to release function,
8443 * its fixed offset must be 0. In the other cases, fixed offset
8444 * can be non-zero. This was already checked above. So pass
8445 * fixed_off_ok as true to allow fixed offset for all other
8446 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8447 * still need to do checks instead of returning.
8449 return __check_ptr_off_reg(env, reg, regno, true);
8451 return __check_ptr_off_reg(env, reg, regno, false);
8455 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8456 const struct bpf_func_proto *fn,
8457 struct bpf_reg_state *regs)
8459 struct bpf_reg_state *state = NULL;
8462 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8463 if (arg_type_is_dynptr(fn->arg_type[i])) {
8465 verbose(env, "verifier internal error: multiple dynptr args\n");
8468 state = ®s[BPF_REG_1 + i];
8472 verbose(env, "verifier internal error: no dynptr arg found\n");
8477 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8479 struct bpf_func_state *state = func(env, reg);
8482 if (reg->type == CONST_PTR_TO_DYNPTR)
8484 spi = dynptr_get_spi(env, reg);
8487 return state->stack[spi].spilled_ptr.id;
8490 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8492 struct bpf_func_state *state = func(env, reg);
8495 if (reg->type == CONST_PTR_TO_DYNPTR)
8496 return reg->ref_obj_id;
8497 spi = dynptr_get_spi(env, reg);
8500 return state->stack[spi].spilled_ptr.ref_obj_id;
8503 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8504 struct bpf_reg_state *reg)
8506 struct bpf_func_state *state = func(env, reg);
8509 if (reg->type == CONST_PTR_TO_DYNPTR)
8510 return reg->dynptr.type;
8512 spi = __get_spi(reg->off);
8514 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8515 return BPF_DYNPTR_TYPE_INVALID;
8518 return state->stack[spi].spilled_ptr.dynptr.type;
8521 static int check_reg_const_str(struct bpf_verifier_env *env,
8522 struct bpf_reg_state *reg, u32 regno)
8524 struct bpf_map *map = reg->map_ptr;
8530 if (reg->type != PTR_TO_MAP_VALUE)
8533 if (!bpf_map_is_rdonly(map)) {
8534 verbose(env, "R%d does not point to a readonly map'\n", regno);
8538 if (!tnum_is_const(reg->var_off)) {
8539 verbose(env, "R%d is not a constant address'\n", regno);
8543 if (!map->ops->map_direct_value_addr) {
8544 verbose(env, "no direct value access support for this map type\n");
8548 err = check_map_access(env, regno, reg->off,
8549 map->value_size - reg->off, false,
8554 map_off = reg->off + reg->var_off.value;
8555 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8557 verbose(env, "direct value access on string failed\n");
8561 str_ptr = (char *)(long)(map_addr);
8562 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8563 verbose(env, "string is not zero-terminated\n");
8569 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8570 struct bpf_call_arg_meta *meta,
8571 const struct bpf_func_proto *fn,
8574 u32 regno = BPF_REG_1 + arg;
8575 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8576 enum bpf_arg_type arg_type = fn->arg_type[arg];
8577 enum bpf_reg_type type = reg->type;
8578 u32 *arg_btf_id = NULL;
8581 if (arg_type == ARG_DONTCARE)
8584 err = check_reg_arg(env, regno, SRC_OP);
8588 if (arg_type == ARG_ANYTHING) {
8589 if (is_pointer_value(env, regno)) {
8590 verbose(env, "R%d leaks addr into helper function\n",
8597 if (type_is_pkt_pointer(type) &&
8598 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8599 verbose(env, "helper access to the packet is not allowed\n");
8603 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8604 err = resolve_map_arg_type(env, meta, &arg_type);
8609 if (register_is_null(reg) && type_may_be_null(arg_type))
8610 /* A NULL register has a SCALAR_VALUE type, so skip
8613 goto skip_type_check;
8615 /* arg_btf_id and arg_size are in a union. */
8616 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8617 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8618 arg_btf_id = fn->arg_btf_id[arg];
8620 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8624 err = check_func_arg_reg_off(env, reg, regno, arg_type);
8629 if (arg_type_is_release(arg_type)) {
8630 if (arg_type_is_dynptr(arg_type)) {
8631 struct bpf_func_state *state = func(env, reg);
8634 /* Only dynptr created on stack can be released, thus
8635 * the get_spi and stack state checks for spilled_ptr
8636 * should only be done before process_dynptr_func for
8639 if (reg->type == PTR_TO_STACK) {
8640 spi = dynptr_get_spi(env, reg);
8641 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8642 verbose(env, "arg %d is an unacquired reference\n", regno);
8646 verbose(env, "cannot release unowned const bpf_dynptr\n");
8649 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8650 verbose(env, "R%d must be referenced when passed to release function\n",
8654 if (meta->release_regno) {
8655 verbose(env, "verifier internal error: more than one release argument\n");
8658 meta->release_regno = regno;
8661 if (reg->ref_obj_id) {
8662 if (meta->ref_obj_id) {
8663 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8664 regno, reg->ref_obj_id,
8668 meta->ref_obj_id = reg->ref_obj_id;
8671 switch (base_type(arg_type)) {
8672 case ARG_CONST_MAP_PTR:
8673 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8674 if (meta->map_ptr) {
8675 /* Use map_uid (which is unique id of inner map) to reject:
8676 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8677 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8678 * if (inner_map1 && inner_map2) {
8679 * timer = bpf_map_lookup_elem(inner_map1);
8681 * // mismatch would have been allowed
8682 * bpf_timer_init(timer, inner_map2);
8685 * Comparing map_ptr is enough to distinguish normal and outer maps.
8687 if (meta->map_ptr != reg->map_ptr ||
8688 meta->map_uid != reg->map_uid) {
8690 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8691 meta->map_uid, reg->map_uid);
8695 meta->map_ptr = reg->map_ptr;
8696 meta->map_uid = reg->map_uid;
8698 case ARG_PTR_TO_MAP_KEY:
8699 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8700 * check that [key, key + map->key_size) are within
8701 * stack limits and initialized
8703 if (!meta->map_ptr) {
8704 /* in function declaration map_ptr must come before
8705 * map_key, so that it's verified and known before
8706 * we have to check map_key here. Otherwise it means
8707 * that kernel subsystem misconfigured verifier
8709 verbose(env, "invalid map_ptr to access map->key\n");
8712 err = check_helper_mem_access(env, regno,
8713 meta->map_ptr->key_size, false,
8716 case ARG_PTR_TO_MAP_VALUE:
8717 if (type_may_be_null(arg_type) && register_is_null(reg))
8720 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8721 * check [value, value + map->value_size) validity
8723 if (!meta->map_ptr) {
8724 /* kernel subsystem misconfigured verifier */
8725 verbose(env, "invalid map_ptr to access map->value\n");
8728 meta->raw_mode = arg_type & MEM_UNINIT;
8729 err = check_helper_mem_access(env, regno,
8730 meta->map_ptr->value_size, false,
8733 case ARG_PTR_TO_PERCPU_BTF_ID:
8735 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8738 meta->ret_btf = reg->btf;
8739 meta->ret_btf_id = reg->btf_id;
8741 case ARG_PTR_TO_SPIN_LOCK:
8742 if (in_rbtree_lock_required_cb(env)) {
8743 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8746 if (meta->func_id == BPF_FUNC_spin_lock) {
8747 err = process_spin_lock(env, regno, true);
8750 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8751 err = process_spin_lock(env, regno, false);
8755 verbose(env, "verifier internal error\n");
8759 case ARG_PTR_TO_TIMER:
8760 err = process_timer_func(env, regno, meta);
8764 case ARG_PTR_TO_FUNC:
8765 meta->subprogno = reg->subprogno;
8767 case ARG_PTR_TO_MEM:
8768 /* The access to this pointer is only checked when we hit the
8769 * next is_mem_size argument below.
8771 meta->raw_mode = arg_type & MEM_UNINIT;
8772 if (arg_type & MEM_FIXED_SIZE) {
8773 err = check_helper_mem_access(env, regno,
8774 fn->arg_size[arg], false,
8778 case ARG_CONST_SIZE:
8779 err = check_mem_size_reg(env, reg, regno, false, meta);
8781 case ARG_CONST_SIZE_OR_ZERO:
8782 err = check_mem_size_reg(env, reg, regno, true, meta);
8784 case ARG_PTR_TO_DYNPTR:
8785 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8789 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8790 if (!tnum_is_const(reg->var_off)) {
8791 verbose(env, "R%d is not a known constant'\n",
8795 meta->mem_size = reg->var_off.value;
8796 err = mark_chain_precision(env, regno);
8800 case ARG_PTR_TO_INT:
8801 case ARG_PTR_TO_LONG:
8803 int size = int_ptr_type_to_size(arg_type);
8805 err = check_helper_mem_access(env, regno, size, false, meta);
8808 err = check_ptr_alignment(env, reg, 0, size, true);
8811 case ARG_PTR_TO_CONST_STR:
8813 err = check_reg_const_str(env, reg, regno);
8818 case ARG_PTR_TO_KPTR:
8819 err = process_kptr_func(env, regno, meta);
8828 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8830 enum bpf_attach_type eatype = env->prog->expected_attach_type;
8831 enum bpf_prog_type type = resolve_prog_type(env->prog);
8833 if (func_id != BPF_FUNC_map_update_elem)
8836 /* It's not possible to get access to a locked struct sock in these
8837 * contexts, so updating is safe.
8840 case BPF_PROG_TYPE_TRACING:
8841 if (eatype == BPF_TRACE_ITER)
8844 case BPF_PROG_TYPE_SOCKET_FILTER:
8845 case BPF_PROG_TYPE_SCHED_CLS:
8846 case BPF_PROG_TYPE_SCHED_ACT:
8847 case BPF_PROG_TYPE_XDP:
8848 case BPF_PROG_TYPE_SK_REUSEPORT:
8849 case BPF_PROG_TYPE_FLOW_DISSECTOR:
8850 case BPF_PROG_TYPE_SK_LOOKUP:
8856 verbose(env, "cannot update sockmap in this context\n");
8860 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8862 return env->prog->jit_requested &&
8863 bpf_jit_supports_subprog_tailcalls();
8866 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8867 struct bpf_map *map, int func_id)
8872 /* We need a two way check, first is from map perspective ... */
8873 switch (map->map_type) {
8874 case BPF_MAP_TYPE_PROG_ARRAY:
8875 if (func_id != BPF_FUNC_tail_call)
8878 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8879 if (func_id != BPF_FUNC_perf_event_read &&
8880 func_id != BPF_FUNC_perf_event_output &&
8881 func_id != BPF_FUNC_skb_output &&
8882 func_id != BPF_FUNC_perf_event_read_value &&
8883 func_id != BPF_FUNC_xdp_output)
8886 case BPF_MAP_TYPE_RINGBUF:
8887 if (func_id != BPF_FUNC_ringbuf_output &&
8888 func_id != BPF_FUNC_ringbuf_reserve &&
8889 func_id != BPF_FUNC_ringbuf_query &&
8890 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8891 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8892 func_id != BPF_FUNC_ringbuf_discard_dynptr)
8895 case BPF_MAP_TYPE_USER_RINGBUF:
8896 if (func_id != BPF_FUNC_user_ringbuf_drain)
8899 case BPF_MAP_TYPE_STACK_TRACE:
8900 if (func_id != BPF_FUNC_get_stackid)
8903 case BPF_MAP_TYPE_CGROUP_ARRAY:
8904 if (func_id != BPF_FUNC_skb_under_cgroup &&
8905 func_id != BPF_FUNC_current_task_under_cgroup)
8908 case BPF_MAP_TYPE_CGROUP_STORAGE:
8909 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8910 if (func_id != BPF_FUNC_get_local_storage)
8913 case BPF_MAP_TYPE_DEVMAP:
8914 case BPF_MAP_TYPE_DEVMAP_HASH:
8915 if (func_id != BPF_FUNC_redirect_map &&
8916 func_id != BPF_FUNC_map_lookup_elem)
8919 /* Restrict bpf side of cpumap and xskmap, open when use-cases
8922 case BPF_MAP_TYPE_CPUMAP:
8923 if (func_id != BPF_FUNC_redirect_map)
8926 case BPF_MAP_TYPE_XSKMAP:
8927 if (func_id != BPF_FUNC_redirect_map &&
8928 func_id != BPF_FUNC_map_lookup_elem)
8931 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8932 case BPF_MAP_TYPE_HASH_OF_MAPS:
8933 if (func_id != BPF_FUNC_map_lookup_elem)
8936 case BPF_MAP_TYPE_SOCKMAP:
8937 if (func_id != BPF_FUNC_sk_redirect_map &&
8938 func_id != BPF_FUNC_sock_map_update &&
8939 func_id != BPF_FUNC_map_delete_elem &&
8940 func_id != BPF_FUNC_msg_redirect_map &&
8941 func_id != BPF_FUNC_sk_select_reuseport &&
8942 func_id != BPF_FUNC_map_lookup_elem &&
8943 !may_update_sockmap(env, func_id))
8946 case BPF_MAP_TYPE_SOCKHASH:
8947 if (func_id != BPF_FUNC_sk_redirect_hash &&
8948 func_id != BPF_FUNC_sock_hash_update &&
8949 func_id != BPF_FUNC_map_delete_elem &&
8950 func_id != BPF_FUNC_msg_redirect_hash &&
8951 func_id != BPF_FUNC_sk_select_reuseport &&
8952 func_id != BPF_FUNC_map_lookup_elem &&
8953 !may_update_sockmap(env, func_id))
8956 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8957 if (func_id != BPF_FUNC_sk_select_reuseport)
8960 case BPF_MAP_TYPE_QUEUE:
8961 case BPF_MAP_TYPE_STACK:
8962 if (func_id != BPF_FUNC_map_peek_elem &&
8963 func_id != BPF_FUNC_map_pop_elem &&
8964 func_id != BPF_FUNC_map_push_elem)
8967 case BPF_MAP_TYPE_SK_STORAGE:
8968 if (func_id != BPF_FUNC_sk_storage_get &&
8969 func_id != BPF_FUNC_sk_storage_delete &&
8970 func_id != BPF_FUNC_kptr_xchg)
8973 case BPF_MAP_TYPE_INODE_STORAGE:
8974 if (func_id != BPF_FUNC_inode_storage_get &&
8975 func_id != BPF_FUNC_inode_storage_delete &&
8976 func_id != BPF_FUNC_kptr_xchg)
8979 case BPF_MAP_TYPE_TASK_STORAGE:
8980 if (func_id != BPF_FUNC_task_storage_get &&
8981 func_id != BPF_FUNC_task_storage_delete &&
8982 func_id != BPF_FUNC_kptr_xchg)
8985 case BPF_MAP_TYPE_CGRP_STORAGE:
8986 if (func_id != BPF_FUNC_cgrp_storage_get &&
8987 func_id != BPF_FUNC_cgrp_storage_delete &&
8988 func_id != BPF_FUNC_kptr_xchg)
8991 case BPF_MAP_TYPE_BLOOM_FILTER:
8992 if (func_id != BPF_FUNC_map_peek_elem &&
8993 func_id != BPF_FUNC_map_push_elem)
9000 /* ... and second from the function itself. */
9002 case BPF_FUNC_tail_call:
9003 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
9005 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
9006 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
9010 case BPF_FUNC_perf_event_read:
9011 case BPF_FUNC_perf_event_output:
9012 case BPF_FUNC_perf_event_read_value:
9013 case BPF_FUNC_skb_output:
9014 case BPF_FUNC_xdp_output:
9015 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
9018 case BPF_FUNC_ringbuf_output:
9019 case BPF_FUNC_ringbuf_reserve:
9020 case BPF_FUNC_ringbuf_query:
9021 case BPF_FUNC_ringbuf_reserve_dynptr:
9022 case BPF_FUNC_ringbuf_submit_dynptr:
9023 case BPF_FUNC_ringbuf_discard_dynptr:
9024 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
9027 case BPF_FUNC_user_ringbuf_drain:
9028 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
9031 case BPF_FUNC_get_stackid:
9032 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
9035 case BPF_FUNC_current_task_under_cgroup:
9036 case BPF_FUNC_skb_under_cgroup:
9037 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
9040 case BPF_FUNC_redirect_map:
9041 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
9042 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9043 map->map_type != BPF_MAP_TYPE_CPUMAP &&
9044 map->map_type != BPF_MAP_TYPE_XSKMAP)
9047 case BPF_FUNC_sk_redirect_map:
9048 case BPF_FUNC_msg_redirect_map:
9049 case BPF_FUNC_sock_map_update:
9050 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9053 case BPF_FUNC_sk_redirect_hash:
9054 case BPF_FUNC_msg_redirect_hash:
9055 case BPF_FUNC_sock_hash_update:
9056 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
9059 case BPF_FUNC_get_local_storage:
9060 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9061 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9064 case BPF_FUNC_sk_select_reuseport:
9065 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9066 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9067 map->map_type != BPF_MAP_TYPE_SOCKHASH)
9070 case BPF_FUNC_map_pop_elem:
9071 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9072 map->map_type != BPF_MAP_TYPE_STACK)
9075 case BPF_FUNC_map_peek_elem:
9076 case BPF_FUNC_map_push_elem:
9077 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9078 map->map_type != BPF_MAP_TYPE_STACK &&
9079 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9082 case BPF_FUNC_map_lookup_percpu_elem:
9083 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9084 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9085 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9088 case BPF_FUNC_sk_storage_get:
9089 case BPF_FUNC_sk_storage_delete:
9090 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9093 case BPF_FUNC_inode_storage_get:
9094 case BPF_FUNC_inode_storage_delete:
9095 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9098 case BPF_FUNC_task_storage_get:
9099 case BPF_FUNC_task_storage_delete:
9100 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9103 case BPF_FUNC_cgrp_storage_get:
9104 case BPF_FUNC_cgrp_storage_delete:
9105 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9114 verbose(env, "cannot pass map_type %d into func %s#%d\n",
9115 map->map_type, func_id_name(func_id), func_id);
9119 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9123 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9125 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9127 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9129 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9131 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9134 /* We only support one arg being in raw mode at the moment,
9135 * which is sufficient for the helper functions we have
9141 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9143 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9144 bool has_size = fn->arg_size[arg] != 0;
9145 bool is_next_size = false;
9147 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9148 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9150 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9151 return is_next_size;
9153 return has_size == is_next_size || is_next_size == is_fixed;
9156 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9158 /* bpf_xxx(..., buf, len) call will access 'len'
9159 * bytes from memory 'buf'. Both arg types need
9160 * to be paired, so make sure there's no buggy
9161 * helper function specification.
9163 if (arg_type_is_mem_size(fn->arg1_type) ||
9164 check_args_pair_invalid(fn, 0) ||
9165 check_args_pair_invalid(fn, 1) ||
9166 check_args_pair_invalid(fn, 2) ||
9167 check_args_pair_invalid(fn, 3) ||
9168 check_args_pair_invalid(fn, 4))
9174 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9178 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9179 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9180 return !!fn->arg_btf_id[i];
9181 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9182 return fn->arg_btf_id[i] == BPF_PTR_POISON;
9183 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9184 /* arg_btf_id and arg_size are in a union. */
9185 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9186 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9193 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9195 return check_raw_mode_ok(fn) &&
9196 check_arg_pair_ok(fn) &&
9197 check_btf_id_ok(fn) ? 0 : -EINVAL;
9200 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9201 * are now invalid, so turn them into unknown SCALAR_VALUE.
9203 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9204 * since these slices point to packet data.
9206 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9208 struct bpf_func_state *state;
9209 struct bpf_reg_state *reg;
9211 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9212 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9213 mark_reg_invalid(env, reg);
9219 BEYOND_PKT_END = -2,
9222 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9224 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9225 struct bpf_reg_state *reg = &state->regs[regn];
9227 if (reg->type != PTR_TO_PACKET)
9228 /* PTR_TO_PACKET_META is not supported yet */
9231 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9232 * How far beyond pkt_end it goes is unknown.
9233 * if (!range_open) it's the case of pkt >= pkt_end
9234 * if (range_open) it's the case of pkt > pkt_end
9235 * hence this pointer is at least 1 byte bigger than pkt_end
9238 reg->range = BEYOND_PKT_END;
9240 reg->range = AT_PKT_END;
9243 /* The pointer with the specified id has released its reference to kernel
9244 * resources. Identify all copies of the same pointer and clear the reference.
9246 static int release_reference(struct bpf_verifier_env *env,
9249 struct bpf_func_state *state;
9250 struct bpf_reg_state *reg;
9253 err = release_reference_state(cur_func(env), ref_obj_id);
9257 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9258 if (reg->ref_obj_id == ref_obj_id)
9259 mark_reg_invalid(env, reg);
9265 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9267 struct bpf_func_state *unused;
9268 struct bpf_reg_state *reg;
9270 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9271 if (type_is_non_owning_ref(reg->type))
9272 mark_reg_invalid(env, reg);
9276 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9277 struct bpf_reg_state *regs)
9281 /* after the call registers r0 - r5 were scratched */
9282 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9283 mark_reg_not_init(env, regs, caller_saved[i]);
9284 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9288 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9289 struct bpf_func_state *caller,
9290 struct bpf_func_state *callee,
9293 static int set_callee_state(struct bpf_verifier_env *env,
9294 struct bpf_func_state *caller,
9295 struct bpf_func_state *callee, int insn_idx);
9297 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9298 set_callee_state_fn set_callee_state_cb,
9299 struct bpf_verifier_state *state)
9301 struct bpf_func_state *caller, *callee;
9304 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9305 verbose(env, "the call stack of %d frames is too deep\n",
9306 state->curframe + 2);
9310 if (state->frame[state->curframe + 1]) {
9311 verbose(env, "verifier bug. Frame %d already allocated\n",
9312 state->curframe + 1);
9316 caller = state->frame[state->curframe];
9317 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9320 state->frame[state->curframe + 1] = callee;
9322 /* callee cannot access r0, r6 - r9 for reading and has to write
9323 * into its own stack before reading from it.
9324 * callee can read/write into caller's stack
9326 init_func_state(env, callee,
9327 /* remember the callsite, it will be used by bpf_exit */
9329 state->curframe + 1 /* frameno within this callchain */,
9330 subprog /* subprog number within this prog */);
9331 /* Transfer references to the callee */
9332 err = copy_reference_state(callee, caller);
9333 err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9337 /* only increment it after check_reg_arg() finished */
9343 free_func_state(callee);
9344 state->frame[state->curframe + 1] = NULL;
9348 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9349 const struct btf *btf,
9350 struct bpf_reg_state *regs)
9352 struct bpf_subprog_info *sub = subprog_info(env, subprog);
9353 struct bpf_verifier_log *log = &env->log;
9357 ret = btf_prepare_func_args(env, subprog);
9361 /* check that BTF function arguments match actual types that the
9364 for (i = 0; i < sub->arg_cnt; i++) {
9366 struct bpf_reg_state *reg = ®s[regno];
9367 struct bpf_subprog_arg_info *arg = &sub->args[i];
9369 if (arg->arg_type == ARG_ANYTHING) {
9370 if (reg->type != SCALAR_VALUE) {
9371 bpf_log(log, "R%d is not a scalar\n", regno);
9374 } else if (arg->arg_type == ARG_PTR_TO_CTX) {
9375 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9378 /* If function expects ctx type in BTF check that caller
9379 * is passing PTR_TO_CTX.
9381 if (reg->type != PTR_TO_CTX) {
9382 bpf_log(log, "arg#%d expects pointer to ctx\n", i);
9385 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9386 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9389 if (check_mem_reg(env, reg, regno, arg->mem_size))
9391 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
9392 bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
9395 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
9397 * Can pass any value and the kernel won't crash, but
9398 * only PTR_TO_ARENA or SCALAR make sense. Everything
9399 * else is a bug in the bpf program. Point it out to
9400 * the user at the verification time instead of
9401 * run-time debug nightmare.
9403 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
9404 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
9407 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
9408 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
9411 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
9412 struct bpf_call_arg_meta meta;
9415 if (register_is_null(reg) && type_may_be_null(arg->arg_type))
9418 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
9419 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
9420 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
9424 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
9433 /* Compare BTF of a function call with given bpf_reg_state.
9435 * EFAULT - there is a verifier bug. Abort verification.
9436 * EINVAL - there is a type mismatch or BTF is not available.
9437 * 0 - BTF matches with what bpf_reg_state expects.
9438 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9440 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9441 struct bpf_reg_state *regs)
9443 struct bpf_prog *prog = env->prog;
9444 struct btf *btf = prog->aux->btf;
9448 if (!prog->aux->func_info)
9451 btf_id = prog->aux->func_info[subprog].type_id;
9455 if (prog->aux->func_info_aux[subprog].unreliable)
9458 err = btf_check_func_arg_match(env, subprog, btf, regs);
9459 /* Compiler optimizations can remove arguments from static functions
9460 * or mismatched type can be passed into a global function.
9461 * In such cases mark the function as unreliable from BTF point of view.
9464 prog->aux->func_info_aux[subprog].unreliable = true;
9468 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9469 int insn_idx, int subprog,
9470 set_callee_state_fn set_callee_state_cb)
9472 struct bpf_verifier_state *state = env->cur_state, *callback_state;
9473 struct bpf_func_state *caller, *callee;
9476 caller = state->frame[state->curframe];
9477 err = btf_check_subprog_call(env, subprog, caller->regs);
9481 /* set_callee_state is used for direct subprog calls, but we are
9482 * interested in validating only BPF helpers that can call subprogs as
9485 env->subprog_info[subprog].is_cb = true;
9486 if (bpf_pseudo_kfunc_call(insn) &&
9487 !is_sync_callback_calling_kfunc(insn->imm)) {
9488 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9489 func_id_name(insn->imm), insn->imm);
9491 } else if (!bpf_pseudo_kfunc_call(insn) &&
9492 !is_callback_calling_function(insn->imm)) { /* helper */
9493 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9494 func_id_name(insn->imm), insn->imm);
9498 if (is_async_callback_calling_insn(insn)) {
9499 struct bpf_verifier_state *async_cb;
9501 /* there is no real recursion here. timer callbacks are async */
9502 env->subprog_info[subprog].is_async_cb = true;
9503 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9507 callee = async_cb->frame[0];
9508 callee->async_entry_cnt = caller->async_entry_cnt + 1;
9510 /* Convert bpf_timer_set_callback() args into timer callback args */
9511 err = set_callee_state_cb(env, caller, callee, insn_idx);
9518 /* for callback functions enqueue entry to callback and
9519 * proceed with next instruction within current frame.
9521 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9522 if (!callback_state)
9525 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9530 callback_state->callback_unroll_depth++;
9531 callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9532 caller->callback_depth = 0;
9536 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9539 struct bpf_verifier_state *state = env->cur_state;
9540 struct bpf_func_state *caller;
9541 int err, subprog, target_insn;
9543 target_insn = *insn_idx + insn->imm + 1;
9544 subprog = find_subprog(env, target_insn);
9546 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9550 caller = state->frame[state->curframe];
9551 err = btf_check_subprog_call(env, subprog, caller->regs);
9554 if (subprog_is_global(env, subprog)) {
9555 const char *sub_name = subprog_name(env, subprog);
9557 /* Only global subprogs cannot be called with a lock held. */
9558 if (env->cur_state->active_lock.ptr) {
9559 verbose(env, "global function calls are not allowed while holding a lock,\n"
9560 "use static function instead\n");
9565 verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9570 verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9572 /* mark global subprog for verifying after main prog */
9573 subprog_aux(env, subprog)->called = true;
9574 clear_caller_saved_regs(env, caller->regs);
9576 /* All global functions return a 64-bit SCALAR_VALUE */
9577 mark_reg_unknown(env, caller->regs, BPF_REG_0);
9578 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9580 /* continue with next insn after call */
9584 /* for regular function entry setup new frame and continue
9587 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9591 clear_caller_saved_regs(env, caller->regs);
9593 /* and go analyze first insn of the callee */
9594 *insn_idx = env->subprog_info[subprog].start - 1;
9596 if (env->log.level & BPF_LOG_LEVEL) {
9597 verbose(env, "caller:\n");
9598 print_verifier_state(env, caller, true);
9599 verbose(env, "callee:\n");
9600 print_verifier_state(env, state->frame[state->curframe], true);
9606 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9607 struct bpf_func_state *caller,
9608 struct bpf_func_state *callee)
9610 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9611 * void *callback_ctx, u64 flags);
9612 * callback_fn(struct bpf_map *map, void *key, void *value,
9613 * void *callback_ctx);
9615 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9617 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9618 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9619 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9621 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9622 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9623 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9625 /* pointer to stack or null */
9626 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9629 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9633 static int set_callee_state(struct bpf_verifier_env *env,
9634 struct bpf_func_state *caller,
9635 struct bpf_func_state *callee, int insn_idx)
9639 /* copy r1 - r5 args that callee can access. The copy includes parent
9640 * pointers, which connects us up to the liveness chain
9642 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9643 callee->regs[i] = caller->regs[i];
9647 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9648 struct bpf_func_state *caller,
9649 struct bpf_func_state *callee,
9652 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9653 struct bpf_map *map;
9656 if (bpf_map_ptr_poisoned(insn_aux)) {
9657 verbose(env, "tail_call abusing map_ptr\n");
9661 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9662 if (!map->ops->map_set_for_each_callback_args ||
9663 !map->ops->map_for_each_callback) {
9664 verbose(env, "callback function not allowed for map\n");
9668 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9672 callee->in_callback_fn = true;
9673 callee->callback_ret_range = retval_range(0, 1);
9677 static int set_loop_callback_state(struct bpf_verifier_env *env,
9678 struct bpf_func_state *caller,
9679 struct bpf_func_state *callee,
9682 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9684 * callback_fn(u32 index, void *callback_ctx);
9686 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9687 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9690 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9691 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9692 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9694 callee->in_callback_fn = true;
9695 callee->callback_ret_range = retval_range(0, 1);
9699 static int set_timer_callback_state(struct bpf_verifier_env *env,
9700 struct bpf_func_state *caller,
9701 struct bpf_func_state *callee,
9704 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9706 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9707 * callback_fn(struct bpf_map *map, void *key, void *value);
9709 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9710 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9711 callee->regs[BPF_REG_1].map_ptr = map_ptr;
9713 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9714 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9715 callee->regs[BPF_REG_2].map_ptr = map_ptr;
9717 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9718 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9719 callee->regs[BPF_REG_3].map_ptr = map_ptr;
9722 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9723 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9724 callee->in_async_callback_fn = true;
9725 callee->callback_ret_range = retval_range(0, 1);
9729 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9730 struct bpf_func_state *caller,
9731 struct bpf_func_state *callee,
9734 /* bpf_find_vma(struct task_struct *task, u64 addr,
9735 * void *callback_fn, void *callback_ctx, u64 flags)
9736 * (callback_fn)(struct task_struct *task,
9737 * struct vm_area_struct *vma, void *callback_ctx);
9739 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9741 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9742 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9743 callee->regs[BPF_REG_2].btf = btf_vmlinux;
9744 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
9746 /* pointer to stack or null */
9747 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9750 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9751 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9752 callee->in_callback_fn = true;
9753 callee->callback_ret_range = retval_range(0, 1);
9757 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9758 struct bpf_func_state *caller,
9759 struct bpf_func_state *callee,
9762 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9763 * callback_ctx, u64 flags);
9764 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9766 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9767 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9768 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9771 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9772 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9773 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9775 callee->in_callback_fn = true;
9776 callee->callback_ret_range = retval_range(0, 1);
9780 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9781 struct bpf_func_state *caller,
9782 struct bpf_func_state *callee,
9785 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9786 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9788 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9789 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9790 * by this point, so look at 'root'
9792 struct btf_field *field;
9794 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9796 if (!field || !field->graph_root.value_btf_id)
9799 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9800 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9801 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9802 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9804 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9805 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9806 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9807 callee->in_callback_fn = true;
9808 callee->callback_ret_range = retval_range(0, 1);
9812 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9814 /* Are we currently verifying the callback for a rbtree helper that must
9815 * be called with lock held? If so, no need to complain about unreleased
9818 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9820 struct bpf_verifier_state *state = env->cur_state;
9821 struct bpf_insn *insn = env->prog->insnsi;
9822 struct bpf_func_state *callee;
9825 if (!state->curframe)
9828 callee = state->frame[state->curframe];
9830 if (!callee->in_callback_fn)
9833 kfunc_btf_id = insn[callee->callsite].imm;
9834 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9837 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
9839 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
9842 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9844 struct bpf_verifier_state *state = env->cur_state, *prev_st;
9845 struct bpf_func_state *caller, *callee;
9846 struct bpf_reg_state *r0;
9847 bool in_callback_fn;
9850 callee = state->frame[state->curframe];
9851 r0 = &callee->regs[BPF_REG_0];
9852 if (r0->type == PTR_TO_STACK) {
9853 /* technically it's ok to return caller's stack pointer
9854 * (or caller's caller's pointer) back to the caller,
9855 * since these pointers are valid. Only current stack
9856 * pointer will be invalid as soon as function exits,
9857 * but let's be conservative
9859 verbose(env, "cannot return stack pointer to the caller\n");
9863 caller = state->frame[state->curframe - 1];
9864 if (callee->in_callback_fn) {
9865 if (r0->type != SCALAR_VALUE) {
9866 verbose(env, "R0 not a scalar value\n");
9870 /* we are going to rely on register's precise value */
9871 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9872 err = err ?: mark_chain_precision(env, BPF_REG_0);
9876 /* enforce R0 return value range */
9877 if (!retval_range_within(callee->callback_ret_range, r0)) {
9878 verbose_invalid_scalar(env, r0, callee->callback_ret_range,
9879 "At callback return", "R0");
9882 if (!calls_callback(env, callee->callsite)) {
9883 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9884 *insn_idx, callee->callsite);
9888 /* return to the caller whatever r0 had in the callee */
9889 caller->regs[BPF_REG_0] = *r0;
9892 /* callback_fn frame should have released its own additions to parent's
9893 * reference state at this point, or check_reference_leak would
9894 * complain, hence it must be the same as the caller. There is no need
9897 if (!callee->in_callback_fn) {
9898 /* Transfer references to the caller */
9899 err = copy_reference_state(caller, callee);
9904 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9905 * there function call logic would reschedule callback visit. If iteration
9906 * converges is_state_visited() would prune that visit eventually.
9908 in_callback_fn = callee->in_callback_fn;
9910 *insn_idx = callee->callsite;
9912 *insn_idx = callee->callsite + 1;
9914 if (env->log.level & BPF_LOG_LEVEL) {
9915 verbose(env, "returning from callee:\n");
9916 print_verifier_state(env, callee, true);
9917 verbose(env, "to caller at %d:\n", *insn_idx);
9918 print_verifier_state(env, caller, true);
9920 /* clear everything in the callee. In case of exceptional exits using
9921 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
9922 free_func_state(callee);
9923 state->frame[state->curframe--] = NULL;
9925 /* for callbacks widen imprecise scalars to make programs like below verify:
9927 * struct ctx { int i; }
9928 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9930 * struct ctx = { .i = 0; }
9931 * bpf_loop(100, cb, &ctx, 0);
9933 * This is similar to what is done in process_iter_next_call() for open
9936 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9938 err = widen_imprecise_scalars(env, prev_st, state);
9945 static int do_refine_retval_range(struct bpf_verifier_env *env,
9946 struct bpf_reg_state *regs, int ret_type,
9948 struct bpf_call_arg_meta *meta)
9950 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
9952 if (ret_type != RET_INTEGER)
9956 case BPF_FUNC_get_stack:
9957 case BPF_FUNC_get_task_stack:
9958 case BPF_FUNC_probe_read_str:
9959 case BPF_FUNC_probe_read_kernel_str:
9960 case BPF_FUNC_probe_read_user_str:
9961 ret_reg->smax_value = meta->msize_max_value;
9962 ret_reg->s32_max_value = meta->msize_max_value;
9963 ret_reg->smin_value = -MAX_ERRNO;
9964 ret_reg->s32_min_value = -MAX_ERRNO;
9965 reg_bounds_sync(ret_reg);
9967 case BPF_FUNC_get_smp_processor_id:
9968 ret_reg->umax_value = nr_cpu_ids - 1;
9969 ret_reg->u32_max_value = nr_cpu_ids - 1;
9970 ret_reg->smax_value = nr_cpu_ids - 1;
9971 ret_reg->s32_max_value = nr_cpu_ids - 1;
9972 ret_reg->umin_value = 0;
9973 ret_reg->u32_min_value = 0;
9974 ret_reg->smin_value = 0;
9975 ret_reg->s32_min_value = 0;
9976 reg_bounds_sync(ret_reg);
9980 return reg_bounds_sanity_check(env, ret_reg, "retval");
9984 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9985 int func_id, int insn_idx)
9987 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9988 struct bpf_map *map = meta->map_ptr;
9990 if (func_id != BPF_FUNC_tail_call &&
9991 func_id != BPF_FUNC_map_lookup_elem &&
9992 func_id != BPF_FUNC_map_update_elem &&
9993 func_id != BPF_FUNC_map_delete_elem &&
9994 func_id != BPF_FUNC_map_push_elem &&
9995 func_id != BPF_FUNC_map_pop_elem &&
9996 func_id != BPF_FUNC_map_peek_elem &&
9997 func_id != BPF_FUNC_for_each_map_elem &&
9998 func_id != BPF_FUNC_redirect_map &&
9999 func_id != BPF_FUNC_map_lookup_percpu_elem)
10003 verbose(env, "kernel subsystem misconfigured verifier\n");
10007 /* In case of read-only, some additional restrictions
10008 * need to be applied in order to prevent altering the
10009 * state of the map from program side.
10011 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
10012 (func_id == BPF_FUNC_map_delete_elem ||
10013 func_id == BPF_FUNC_map_update_elem ||
10014 func_id == BPF_FUNC_map_push_elem ||
10015 func_id == BPF_FUNC_map_pop_elem)) {
10016 verbose(env, "write into map forbidden\n");
10020 if (!BPF_MAP_PTR(aux->map_ptr_state))
10021 bpf_map_ptr_store(aux, meta->map_ptr,
10022 !meta->map_ptr->bypass_spec_v1);
10023 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
10024 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
10025 !meta->map_ptr->bypass_spec_v1);
10030 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10031 int func_id, int insn_idx)
10033 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10034 struct bpf_reg_state *regs = cur_regs(env), *reg;
10035 struct bpf_map *map = meta->map_ptr;
10039 if (func_id != BPF_FUNC_tail_call)
10041 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
10042 verbose(env, "kernel subsystem misconfigured verifier\n");
10046 reg = ®s[BPF_REG_3];
10047 val = reg->var_off.value;
10048 max = map->max_entries;
10050 if (!(is_reg_const(reg, false) && val < max)) {
10051 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10055 err = mark_chain_precision(env, BPF_REG_3);
10058 if (bpf_map_key_unseen(aux))
10059 bpf_map_key_store(aux, val);
10060 else if (!bpf_map_key_poisoned(aux) &&
10061 bpf_map_key_immediate(aux) != val)
10062 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10066 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
10068 struct bpf_func_state *state = cur_func(env);
10069 bool refs_lingering = false;
10072 if (!exception_exit && state->frameno && !state->in_callback_fn)
10075 for (i = 0; i < state->acquired_refs; i++) {
10076 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
10078 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
10079 state->refs[i].id, state->refs[i].insn_idx);
10080 refs_lingering = true;
10082 return refs_lingering ? -EINVAL : 0;
10085 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10086 struct bpf_reg_state *regs)
10088 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
10089 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
10090 struct bpf_map *fmt_map = fmt_reg->map_ptr;
10091 struct bpf_bprintf_data data = {};
10092 int err, fmt_map_off, num_args;
10096 /* data must be an array of u64 */
10097 if (data_len_reg->var_off.value % 8)
10099 num_args = data_len_reg->var_off.value / 8;
10101 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10102 * and map_direct_value_addr is set.
10104 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
10105 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10108 verbose(env, "verifier bug\n");
10111 fmt = (char *)(long)fmt_addr + fmt_map_off;
10113 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10114 * can focus on validating the format specifiers.
10116 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10118 verbose(env, "Invalid format string\n");
10123 static int check_get_func_ip(struct bpf_verifier_env *env)
10125 enum bpf_prog_type type = resolve_prog_type(env->prog);
10126 int func_id = BPF_FUNC_get_func_ip;
10128 if (type == BPF_PROG_TYPE_TRACING) {
10129 if (!bpf_prog_has_trampoline(env->prog)) {
10130 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10131 func_id_name(func_id), func_id);
10135 } else if (type == BPF_PROG_TYPE_KPROBE) {
10139 verbose(env, "func %s#%d not supported for program type %d\n",
10140 func_id_name(func_id), func_id, type);
10144 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10146 return &env->insn_aux_data[env->insn_idx];
10149 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10151 struct bpf_reg_state *regs = cur_regs(env);
10152 struct bpf_reg_state *reg = ®s[BPF_REG_4];
10153 bool reg_is_null = register_is_null(reg);
10156 mark_chain_precision(env, BPF_REG_4);
10158 return reg_is_null;
10161 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10163 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10165 if (!state->initialized) {
10166 state->initialized = 1;
10167 state->fit_for_inline = loop_flag_is_zero(env);
10168 state->callback_subprogno = subprogno;
10172 if (!state->fit_for_inline)
10175 state->fit_for_inline = (loop_flag_is_zero(env) &&
10176 state->callback_subprogno == subprogno);
10179 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10182 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10183 bool returns_cpu_specific_alloc_ptr = false;
10184 const struct bpf_func_proto *fn = NULL;
10185 enum bpf_return_type ret_type;
10186 enum bpf_type_flag ret_flag;
10187 struct bpf_reg_state *regs;
10188 struct bpf_call_arg_meta meta;
10189 int insn_idx = *insn_idx_p;
10191 int i, err, func_id;
10193 /* find function prototype */
10194 func_id = insn->imm;
10195 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
10196 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
10201 if (env->ops->get_func_proto)
10202 fn = env->ops->get_func_proto(func_id, env->prog);
10204 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
10209 /* eBPF programs must be GPL compatible to use GPL-ed functions */
10210 if (!env->prog->gpl_compatible && fn->gpl_only) {
10211 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10215 if (fn->allowed && !fn->allowed(env->prog)) {
10216 verbose(env, "helper call is not allowed in probe\n");
10220 if (!in_sleepable(env) && fn->might_sleep) {
10221 verbose(env, "helper call might sleep in a non-sleepable prog\n");
10225 /* With LD_ABS/IND some JITs save/restore skb from r1. */
10226 changes_data = bpf_helper_changes_pkt_data(fn->func);
10227 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10228 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10229 func_id_name(func_id), func_id);
10233 memset(&meta, 0, sizeof(meta));
10234 meta.pkt_access = fn->pkt_access;
10236 err = check_func_proto(fn, func_id);
10238 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10239 func_id_name(func_id), func_id);
10243 if (env->cur_state->active_rcu_lock) {
10244 if (fn->might_sleep) {
10245 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10246 func_id_name(func_id), func_id);
10250 if (in_sleepable(env) && is_storage_get_function(func_id))
10251 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10254 meta.func_id = func_id;
10256 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10257 err = check_func_arg(env, i, &meta, fn, insn_idx);
10262 err = record_func_map(env, &meta, func_id, insn_idx);
10266 err = record_func_key(env, &meta, func_id, insn_idx);
10270 /* Mark slots with STACK_MISC in case of raw mode, stack offset
10271 * is inferred from register state.
10273 for (i = 0; i < meta.access_size; i++) {
10274 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10275 BPF_WRITE, -1, false, false);
10280 regs = cur_regs(env);
10282 if (meta.release_regno) {
10284 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10285 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10286 * is safe to do directly.
10288 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10289 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10290 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10293 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
10294 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10295 u32 ref_obj_id = meta.ref_obj_id;
10296 bool in_rcu = in_rcu_cs(env);
10297 struct bpf_func_state *state;
10298 struct bpf_reg_state *reg;
10300 err = release_reference_state(cur_func(env), ref_obj_id);
10302 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10303 if (reg->ref_obj_id == ref_obj_id) {
10304 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10305 reg->ref_obj_id = 0;
10306 reg->type &= ~MEM_ALLOC;
10307 reg->type |= MEM_RCU;
10309 mark_reg_invalid(env, reg);
10314 } else if (meta.ref_obj_id) {
10315 err = release_reference(env, meta.ref_obj_id);
10316 } else if (register_is_null(®s[meta.release_regno])) {
10317 /* meta.ref_obj_id can only be 0 if register that is meant to be
10318 * released is NULL, which must be > R0.
10323 verbose(env, "func %s#%d reference has not been acquired before\n",
10324 func_id_name(func_id), func_id);
10330 case BPF_FUNC_tail_call:
10331 err = check_reference_leak(env, false);
10333 verbose(env, "tail_call would lead to reference leak\n");
10337 case BPF_FUNC_get_local_storage:
10338 /* check that flags argument in get_local_storage(map, flags) is 0,
10339 * this is required because get_local_storage() can't return an error.
10341 if (!register_is_null(®s[BPF_REG_2])) {
10342 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10346 case BPF_FUNC_for_each_map_elem:
10347 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10348 set_map_elem_callback_state);
10350 case BPF_FUNC_timer_set_callback:
10351 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10352 set_timer_callback_state);
10354 case BPF_FUNC_find_vma:
10355 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10356 set_find_vma_callback_state);
10358 case BPF_FUNC_snprintf:
10359 err = check_bpf_snprintf_call(env, regs);
10361 case BPF_FUNC_loop:
10362 update_loop_inline_state(env, meta.subprogno);
10363 /* Verifier relies on R1 value to determine if bpf_loop() iteration
10364 * is finished, thus mark it precise.
10366 err = mark_chain_precision(env, BPF_REG_1);
10369 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10370 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10371 set_loop_callback_state);
10373 cur_func(env)->callback_depth = 0;
10374 if (env->log.level & BPF_LOG_LEVEL2)
10375 verbose(env, "frame%d bpf_loop iteration limit reached\n",
10376 env->cur_state->curframe);
10379 case BPF_FUNC_dynptr_from_mem:
10380 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10381 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10382 reg_type_str(env, regs[BPF_REG_1].type));
10386 case BPF_FUNC_set_retval:
10387 if (prog_type == BPF_PROG_TYPE_LSM &&
10388 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10389 if (!env->prog->aux->attach_func_proto->type) {
10390 /* Make sure programs that attach to void
10391 * hooks don't try to modify return value.
10393 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10398 case BPF_FUNC_dynptr_data:
10400 struct bpf_reg_state *reg;
10401 int id, ref_obj_id;
10403 reg = get_dynptr_arg_reg(env, fn, regs);
10408 if (meta.dynptr_id) {
10409 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10412 if (meta.ref_obj_id) {
10413 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10417 id = dynptr_id(env, reg);
10419 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10423 ref_obj_id = dynptr_ref_obj_id(env, reg);
10424 if (ref_obj_id < 0) {
10425 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10429 meta.dynptr_id = id;
10430 meta.ref_obj_id = ref_obj_id;
10434 case BPF_FUNC_dynptr_write:
10436 enum bpf_dynptr_type dynptr_type;
10437 struct bpf_reg_state *reg;
10439 reg = get_dynptr_arg_reg(env, fn, regs);
10443 dynptr_type = dynptr_get_type(env, reg);
10444 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10447 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10448 /* this will trigger clear_all_pkt_pointers(), which will
10449 * invalidate all dynptr slices associated with the skb
10451 changes_data = true;
10455 case BPF_FUNC_per_cpu_ptr:
10456 case BPF_FUNC_this_cpu_ptr:
10458 struct bpf_reg_state *reg = ®s[BPF_REG_1];
10459 const struct btf_type *type;
10461 if (reg->type & MEM_RCU) {
10462 type = btf_type_by_id(reg->btf, reg->btf_id);
10463 if (!type || !btf_type_is_struct(type)) {
10464 verbose(env, "Helper has invalid btf/btf_id in R1\n");
10467 returns_cpu_specific_alloc_ptr = true;
10468 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10472 case BPF_FUNC_user_ringbuf_drain:
10473 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10474 set_user_ringbuf_callback_state);
10481 /* reset caller saved regs */
10482 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10483 mark_reg_not_init(env, regs, caller_saved[i]);
10484 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10487 /* helper call returns 64-bit value. */
10488 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10490 /* update return register (already marked as written above) */
10491 ret_type = fn->ret_type;
10492 ret_flag = type_flag(ret_type);
10494 switch (base_type(ret_type)) {
10496 /* sets type to SCALAR_VALUE */
10497 mark_reg_unknown(env, regs, BPF_REG_0);
10500 regs[BPF_REG_0].type = NOT_INIT;
10502 case RET_PTR_TO_MAP_VALUE:
10503 /* There is no offset yet applied, variable or fixed */
10504 mark_reg_known_zero(env, regs, BPF_REG_0);
10505 /* remember map_ptr, so that check_map_access()
10506 * can check 'value_size' boundary of memory access
10507 * to map element returned from bpf_map_lookup_elem()
10509 if (meta.map_ptr == NULL) {
10511 "kernel subsystem misconfigured verifier\n");
10514 regs[BPF_REG_0].map_ptr = meta.map_ptr;
10515 regs[BPF_REG_0].map_uid = meta.map_uid;
10516 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10517 if (!type_may_be_null(ret_type) &&
10518 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10519 regs[BPF_REG_0].id = ++env->id_gen;
10522 case RET_PTR_TO_SOCKET:
10523 mark_reg_known_zero(env, regs, BPF_REG_0);
10524 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10526 case RET_PTR_TO_SOCK_COMMON:
10527 mark_reg_known_zero(env, regs, BPF_REG_0);
10528 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10530 case RET_PTR_TO_TCP_SOCK:
10531 mark_reg_known_zero(env, regs, BPF_REG_0);
10532 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10534 case RET_PTR_TO_MEM:
10535 mark_reg_known_zero(env, regs, BPF_REG_0);
10536 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10537 regs[BPF_REG_0].mem_size = meta.mem_size;
10539 case RET_PTR_TO_MEM_OR_BTF_ID:
10541 const struct btf_type *t;
10543 mark_reg_known_zero(env, regs, BPF_REG_0);
10544 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10545 if (!btf_type_is_struct(t)) {
10547 const struct btf_type *ret;
10550 /* resolve the type size of ksym. */
10551 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10553 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10554 verbose(env, "unable to resolve the size of type '%s': %ld\n",
10555 tname, PTR_ERR(ret));
10558 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10559 regs[BPF_REG_0].mem_size = tsize;
10561 if (returns_cpu_specific_alloc_ptr) {
10562 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10564 /* MEM_RDONLY may be carried from ret_flag, but it
10565 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10566 * it will confuse the check of PTR_TO_BTF_ID in
10567 * check_mem_access().
10569 ret_flag &= ~MEM_RDONLY;
10570 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10573 regs[BPF_REG_0].btf = meta.ret_btf;
10574 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10578 case RET_PTR_TO_BTF_ID:
10580 struct btf *ret_btf;
10583 mark_reg_known_zero(env, regs, BPF_REG_0);
10584 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10585 if (func_id == BPF_FUNC_kptr_xchg) {
10586 ret_btf = meta.kptr_field->kptr.btf;
10587 ret_btf_id = meta.kptr_field->kptr.btf_id;
10588 if (!btf_is_kernel(ret_btf)) {
10589 regs[BPF_REG_0].type |= MEM_ALLOC;
10590 if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10591 regs[BPF_REG_0].type |= MEM_PERCPU;
10594 if (fn->ret_btf_id == BPF_PTR_POISON) {
10595 verbose(env, "verifier internal error:");
10596 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10597 func_id_name(func_id));
10600 ret_btf = btf_vmlinux;
10601 ret_btf_id = *fn->ret_btf_id;
10603 if (ret_btf_id == 0) {
10604 verbose(env, "invalid return type %u of func %s#%d\n",
10605 base_type(ret_type), func_id_name(func_id),
10609 regs[BPF_REG_0].btf = ret_btf;
10610 regs[BPF_REG_0].btf_id = ret_btf_id;
10614 verbose(env, "unknown return type %u of func %s#%d\n",
10615 base_type(ret_type), func_id_name(func_id), func_id);
10619 if (type_may_be_null(regs[BPF_REG_0].type))
10620 regs[BPF_REG_0].id = ++env->id_gen;
10622 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10623 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10624 func_id_name(func_id), func_id);
10628 if (is_dynptr_ref_function(func_id))
10629 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10631 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10632 /* For release_reference() */
10633 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10634 } else if (is_acquire_function(func_id, meta.map_ptr)) {
10635 int id = acquire_reference_state(env, insn_idx);
10639 /* For mark_ptr_or_null_reg() */
10640 regs[BPF_REG_0].id = id;
10641 /* For release_reference() */
10642 regs[BPF_REG_0].ref_obj_id = id;
10645 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
10649 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10653 if ((func_id == BPF_FUNC_get_stack ||
10654 func_id == BPF_FUNC_get_task_stack) &&
10655 !env->prog->has_callchain_buf) {
10656 const char *err_str;
10658 #ifdef CONFIG_PERF_EVENTS
10659 err = get_callchain_buffers(sysctl_perf_event_max_stack);
10660 err_str = "cannot get callchain buffer for func %s#%d\n";
10663 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10666 verbose(env, err_str, func_id_name(func_id), func_id);
10670 env->prog->has_callchain_buf = true;
10673 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10674 env->prog->call_get_stack = true;
10676 if (func_id == BPF_FUNC_get_func_ip) {
10677 if (check_get_func_ip(env))
10679 env->prog->call_get_func_ip = true;
10683 clear_all_pkt_pointers(env);
10687 /* mark_btf_func_reg_size() is used when the reg size is determined by
10688 * the BTF func_proto's return value size and argument.
10690 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10693 struct bpf_reg_state *reg = &cur_regs(env)[regno];
10695 if (regno == BPF_REG_0) {
10696 /* Function return value */
10697 reg->live |= REG_LIVE_WRITTEN;
10698 reg->subreg_def = reg_size == sizeof(u64) ?
10699 DEF_NOT_SUBREG : env->insn_idx + 1;
10701 /* Function argument */
10702 if (reg_size == sizeof(u64)) {
10703 mark_insn_zext(env, reg);
10704 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10706 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10711 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10713 return meta->kfunc_flags & KF_ACQUIRE;
10716 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10718 return meta->kfunc_flags & KF_RELEASE;
10721 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10723 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10726 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10728 return meta->kfunc_flags & KF_SLEEPABLE;
10731 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10733 return meta->kfunc_flags & KF_DESTRUCTIVE;
10736 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10738 return meta->kfunc_flags & KF_RCU;
10741 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10743 return meta->kfunc_flags & KF_RCU_PROTECTED;
10746 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10747 const struct btf_param *arg,
10748 const struct bpf_reg_state *reg)
10750 const struct btf_type *t;
10752 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10753 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10756 return btf_param_match_suffix(btf, arg, "__sz");
10759 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10760 const struct btf_param *arg,
10761 const struct bpf_reg_state *reg)
10763 const struct btf_type *t;
10765 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10766 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10769 return btf_param_match_suffix(btf, arg, "__szk");
10772 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10774 return btf_param_match_suffix(btf, arg, "__opt");
10777 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10779 return btf_param_match_suffix(btf, arg, "__k");
10782 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10784 return btf_param_match_suffix(btf, arg, "__ign");
10787 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
10789 return btf_param_match_suffix(btf, arg, "__map");
10792 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10794 return btf_param_match_suffix(btf, arg, "__alloc");
10797 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10799 return btf_param_match_suffix(btf, arg, "__uninit");
10802 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10804 return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
10807 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10809 return btf_param_match_suffix(btf, arg, "__nullable");
10812 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
10814 return btf_param_match_suffix(btf, arg, "__str");
10817 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10818 const struct btf_param *arg,
10821 int len, target_len = strlen(name);
10822 const char *param_name;
10824 param_name = btf_name_by_offset(btf, arg->name_off);
10825 if (str_is_empty(param_name))
10827 len = strlen(param_name);
10828 if (len != target_len)
10830 if (strcmp(param_name, name))
10838 KF_ARG_LIST_HEAD_ID,
10839 KF_ARG_LIST_NODE_ID,
10844 BTF_ID_LIST(kf_arg_btf_ids)
10845 BTF_ID(struct, bpf_dynptr_kern)
10846 BTF_ID(struct, bpf_list_head)
10847 BTF_ID(struct, bpf_list_node)
10848 BTF_ID(struct, bpf_rb_root)
10849 BTF_ID(struct, bpf_rb_node)
10851 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10852 const struct btf_param *arg, int type)
10854 const struct btf_type *t;
10857 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10860 if (!btf_type_is_ptr(t))
10862 t = btf_type_skip_modifiers(btf, t->type, &res_id);
10865 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10868 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10870 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10873 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10875 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10878 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10880 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10883 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10885 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10888 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10890 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10893 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10894 const struct btf_param *arg)
10896 const struct btf_type *t;
10898 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10905 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10906 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10907 const struct btf *btf,
10908 const struct btf_type *t, int rec)
10910 const struct btf_type *member_type;
10911 const struct btf_member *member;
10914 if (!btf_type_is_struct(t))
10917 for_each_member(i, t, member) {
10918 const struct btf_array *array;
10920 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10921 if (btf_type_is_struct(member_type)) {
10923 verbose(env, "max struct nesting depth exceeded\n");
10926 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10930 if (btf_type_is_array(member_type)) {
10931 array = btf_array(member_type);
10932 if (!array->nelems)
10934 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10935 if (!btf_type_is_scalar(member_type))
10939 if (!btf_type_is_scalar(member_type))
10945 enum kfunc_ptr_arg_type {
10947 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
10948 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10949 KF_ARG_PTR_TO_DYNPTR,
10950 KF_ARG_PTR_TO_ITER,
10951 KF_ARG_PTR_TO_LIST_HEAD,
10952 KF_ARG_PTR_TO_LIST_NODE,
10953 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
10955 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
10956 KF_ARG_PTR_TO_CALLBACK,
10957 KF_ARG_PTR_TO_RB_ROOT,
10958 KF_ARG_PTR_TO_RB_NODE,
10959 KF_ARG_PTR_TO_NULL,
10960 KF_ARG_PTR_TO_CONST_STR,
10964 enum special_kfunc_type {
10965 KF_bpf_obj_new_impl,
10966 KF_bpf_obj_drop_impl,
10967 KF_bpf_refcount_acquire_impl,
10968 KF_bpf_list_push_front_impl,
10969 KF_bpf_list_push_back_impl,
10970 KF_bpf_list_pop_front,
10971 KF_bpf_list_pop_back,
10972 KF_bpf_cast_to_kern_ctx,
10973 KF_bpf_rdonly_cast,
10974 KF_bpf_rcu_read_lock,
10975 KF_bpf_rcu_read_unlock,
10976 KF_bpf_rbtree_remove,
10977 KF_bpf_rbtree_add_impl,
10978 KF_bpf_rbtree_first,
10979 KF_bpf_dynptr_from_skb,
10980 KF_bpf_dynptr_from_xdp,
10981 KF_bpf_dynptr_slice,
10982 KF_bpf_dynptr_slice_rdwr,
10983 KF_bpf_dynptr_clone,
10984 KF_bpf_percpu_obj_new_impl,
10985 KF_bpf_percpu_obj_drop_impl,
10987 KF_bpf_iter_css_task_new,
10990 BTF_SET_START(special_kfunc_set)
10991 BTF_ID(func, bpf_obj_new_impl)
10992 BTF_ID(func, bpf_obj_drop_impl)
10993 BTF_ID(func, bpf_refcount_acquire_impl)
10994 BTF_ID(func, bpf_list_push_front_impl)
10995 BTF_ID(func, bpf_list_push_back_impl)
10996 BTF_ID(func, bpf_list_pop_front)
10997 BTF_ID(func, bpf_list_pop_back)
10998 BTF_ID(func, bpf_cast_to_kern_ctx)
10999 BTF_ID(func, bpf_rdonly_cast)
11000 BTF_ID(func, bpf_rbtree_remove)
11001 BTF_ID(func, bpf_rbtree_add_impl)
11002 BTF_ID(func, bpf_rbtree_first)
11003 BTF_ID(func, bpf_dynptr_from_skb)
11004 BTF_ID(func, bpf_dynptr_from_xdp)
11005 BTF_ID(func, bpf_dynptr_slice)
11006 BTF_ID(func, bpf_dynptr_slice_rdwr)
11007 BTF_ID(func, bpf_dynptr_clone)
11008 BTF_ID(func, bpf_percpu_obj_new_impl)
11009 BTF_ID(func, bpf_percpu_obj_drop_impl)
11010 BTF_ID(func, bpf_throw)
11011 #ifdef CONFIG_CGROUPS
11012 BTF_ID(func, bpf_iter_css_task_new)
11014 BTF_SET_END(special_kfunc_set)
11016 BTF_ID_LIST(special_kfunc_list)
11017 BTF_ID(func, bpf_obj_new_impl)
11018 BTF_ID(func, bpf_obj_drop_impl)
11019 BTF_ID(func, bpf_refcount_acquire_impl)
11020 BTF_ID(func, bpf_list_push_front_impl)
11021 BTF_ID(func, bpf_list_push_back_impl)
11022 BTF_ID(func, bpf_list_pop_front)
11023 BTF_ID(func, bpf_list_pop_back)
11024 BTF_ID(func, bpf_cast_to_kern_ctx)
11025 BTF_ID(func, bpf_rdonly_cast)
11026 BTF_ID(func, bpf_rcu_read_lock)
11027 BTF_ID(func, bpf_rcu_read_unlock)
11028 BTF_ID(func, bpf_rbtree_remove)
11029 BTF_ID(func, bpf_rbtree_add_impl)
11030 BTF_ID(func, bpf_rbtree_first)
11031 BTF_ID(func, bpf_dynptr_from_skb)
11032 BTF_ID(func, bpf_dynptr_from_xdp)
11033 BTF_ID(func, bpf_dynptr_slice)
11034 BTF_ID(func, bpf_dynptr_slice_rdwr)
11035 BTF_ID(func, bpf_dynptr_clone)
11036 BTF_ID(func, bpf_percpu_obj_new_impl)
11037 BTF_ID(func, bpf_percpu_obj_drop_impl)
11038 BTF_ID(func, bpf_throw)
11039 #ifdef CONFIG_CGROUPS
11040 BTF_ID(func, bpf_iter_css_task_new)
11045 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
11047 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
11048 meta->arg_owning_ref) {
11052 return meta->kfunc_flags & KF_RET_NULL;
11055 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
11057 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
11060 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
11062 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11065 static enum kfunc_ptr_arg_type
11066 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
11067 struct bpf_kfunc_call_arg_meta *meta,
11068 const struct btf_type *t, const struct btf_type *ref_t,
11069 const char *ref_tname, const struct btf_param *args,
11070 int argno, int nargs)
11072 u32 regno = argno + 1;
11073 struct bpf_reg_state *regs = cur_regs(env);
11074 struct bpf_reg_state *reg = ®s[regno];
11075 bool arg_mem_size = false;
11077 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
11078 return KF_ARG_PTR_TO_CTX;
11080 /* In this function, we verify the kfunc's BTF as per the argument type,
11081 * leaving the rest of the verification with respect to the register
11082 * type to our caller. When a set of conditions hold in the BTF type of
11083 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11085 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
11086 return KF_ARG_PTR_TO_CTX;
11088 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
11089 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11091 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
11092 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11094 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
11095 return KF_ARG_PTR_TO_DYNPTR;
11097 if (is_kfunc_arg_iter(meta, argno))
11098 return KF_ARG_PTR_TO_ITER;
11100 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
11101 return KF_ARG_PTR_TO_LIST_HEAD;
11103 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
11104 return KF_ARG_PTR_TO_LIST_NODE;
11106 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
11107 return KF_ARG_PTR_TO_RB_ROOT;
11109 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
11110 return KF_ARG_PTR_TO_RB_NODE;
11112 if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
11113 return KF_ARG_PTR_TO_CONST_STR;
11115 if (is_kfunc_arg_map(meta->btf, &args[argno]))
11116 return KF_ARG_PTR_TO_MAP;
11118 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11119 if (!btf_type_is_struct(ref_t)) {
11120 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11121 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11124 return KF_ARG_PTR_TO_BTF_ID;
11127 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11128 return KF_ARG_PTR_TO_CALLBACK;
11130 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11131 return KF_ARG_PTR_TO_NULL;
11133 if (argno + 1 < nargs &&
11134 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
11135 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
11136 arg_mem_size = true;
11138 /* This is the catch all argument type of register types supported by
11139 * check_helper_mem_access. However, we only allow when argument type is
11140 * pointer to scalar, or struct composed (recursively) of scalars. When
11141 * arg_mem_size is true, the pointer can be void *.
11143 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11144 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11145 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11146 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11149 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11152 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11153 struct bpf_reg_state *reg,
11154 const struct btf_type *ref_t,
11155 const char *ref_tname, u32 ref_id,
11156 struct bpf_kfunc_call_arg_meta *meta,
11159 const struct btf_type *reg_ref_t;
11160 bool strict_type_match = false;
11161 const struct btf *reg_btf;
11162 const char *reg_ref_tname;
11165 if (base_type(reg->type) == PTR_TO_BTF_ID) {
11166 reg_btf = reg->btf;
11167 reg_ref_id = reg->btf_id;
11169 reg_btf = btf_vmlinux;
11170 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11173 /* Enforce strict type matching for calls to kfuncs that are acquiring
11174 * or releasing a reference, or are no-cast aliases. We do _not_
11175 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11176 * as we want to enable BPF programs to pass types that are bitwise
11177 * equivalent without forcing them to explicitly cast with something
11178 * like bpf_cast_to_kern_ctx().
11180 * For example, say we had a type like the following:
11182 * struct bpf_cpumask {
11183 * cpumask_t cpumask;
11184 * refcount_t usage;
11187 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11188 * to a struct cpumask, so it would be safe to pass a struct
11189 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11191 * The philosophy here is similar to how we allow scalars of different
11192 * types to be passed to kfuncs as long as the size is the same. The
11193 * only difference here is that we're simply allowing
11194 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11197 if (is_kfunc_acquire(meta) ||
11198 (is_kfunc_release(meta) && reg->ref_obj_id) ||
11199 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11200 strict_type_match = true;
11202 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
11204 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
11205 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11206 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
11207 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11208 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11209 btf_type_str(reg_ref_t), reg_ref_tname);
11215 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11217 struct bpf_verifier_state *state = env->cur_state;
11218 struct btf_record *rec = reg_btf_record(reg);
11220 if (!state->active_lock.ptr) {
11221 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11225 if (type_flag(reg->type) & NON_OWN_REF) {
11226 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11230 reg->type |= NON_OWN_REF;
11231 if (rec->refcount_off >= 0)
11232 reg->type |= MEM_RCU;
11237 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11239 struct bpf_func_state *state, *unused;
11240 struct bpf_reg_state *reg;
11243 state = cur_func(env);
11246 verbose(env, "verifier internal error: ref_obj_id is zero for "
11247 "owning -> non-owning conversion\n");
11251 for (i = 0; i < state->acquired_refs; i++) {
11252 if (state->refs[i].id != ref_obj_id)
11255 /* Clear ref_obj_id here so release_reference doesn't clobber
11258 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11259 if (reg->ref_obj_id == ref_obj_id) {
11260 reg->ref_obj_id = 0;
11261 ref_set_non_owning(env, reg);
11267 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11271 /* Implementation details:
11273 * Each register points to some region of memory, which we define as an
11274 * allocation. Each allocation may embed a bpf_spin_lock which protects any
11275 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11276 * allocation. The lock and the data it protects are colocated in the same
11279 * Hence, everytime a register holds a pointer value pointing to such
11280 * allocation, the verifier preserves a unique reg->id for it.
11282 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11283 * bpf_spin_lock is called.
11285 * To enable this, lock state in the verifier captures two values:
11286 * active_lock.ptr = Register's type specific pointer
11287 * active_lock.id = A unique ID for each register pointer value
11289 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11290 * supported register types.
11292 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11293 * allocated objects is the reg->btf pointer.
11295 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11296 * can establish the provenance of the map value statically for each distinct
11297 * lookup into such maps. They always contain a single map value hence unique
11298 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11300 * So, in case of global variables, they use array maps with max_entries = 1,
11301 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11302 * into the same map value as max_entries is 1, as described above).
11304 * In case of inner map lookups, the inner map pointer has same map_ptr as the
11305 * outer map pointer (in verifier context), but each lookup into an inner map
11306 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11307 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11308 * will get different reg->id assigned to each lookup, hence different
11311 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11312 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11313 * returned from bpf_obj_new. Each allocation receives a new reg->id.
11315 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11320 switch ((int)reg->type) {
11321 case PTR_TO_MAP_VALUE:
11322 ptr = reg->map_ptr;
11324 case PTR_TO_BTF_ID | MEM_ALLOC:
11328 verbose(env, "verifier internal error: unknown reg type for lock check\n");
11333 if (!env->cur_state->active_lock.ptr)
11335 if (env->cur_state->active_lock.ptr != ptr ||
11336 env->cur_state->active_lock.id != id) {
11337 verbose(env, "held lock and object are not in the same allocation\n");
11343 static bool is_bpf_list_api_kfunc(u32 btf_id)
11345 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11346 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11347 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11348 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11351 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11353 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11354 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11355 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11358 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11360 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11361 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11364 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11366 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11369 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11371 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11372 insn->imm == special_kfunc_list[KF_bpf_throw];
11375 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11377 return is_bpf_rbtree_api_kfunc(btf_id);
11380 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11381 enum btf_field_type head_field_type,
11386 switch (head_field_type) {
11387 case BPF_LIST_HEAD:
11388 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11391 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11394 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11395 btf_field_type_name(head_field_type));
11400 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11401 btf_field_type_name(head_field_type));
11405 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11406 enum btf_field_type node_field_type,
11411 switch (node_field_type) {
11412 case BPF_LIST_NODE:
11413 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11414 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11417 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11418 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11421 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11422 btf_field_type_name(node_field_type));
11427 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11428 btf_field_type_name(node_field_type));
11433 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11434 struct bpf_reg_state *reg, u32 regno,
11435 struct bpf_kfunc_call_arg_meta *meta,
11436 enum btf_field_type head_field_type,
11437 struct btf_field **head_field)
11439 const char *head_type_name;
11440 struct btf_field *field;
11441 struct btf_record *rec;
11444 if (meta->btf != btf_vmlinux) {
11445 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11449 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11452 head_type_name = btf_field_type_name(head_field_type);
11453 if (!tnum_is_const(reg->var_off)) {
11455 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11456 regno, head_type_name);
11460 rec = reg_btf_record(reg);
11461 head_off = reg->off + reg->var_off.value;
11462 field = btf_record_find(rec, head_off, head_field_type);
11464 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11468 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11469 if (check_reg_allocation_locked(env, reg)) {
11470 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11471 rec->spin_lock_off, head_type_name);
11476 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11479 *head_field = field;
11483 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11484 struct bpf_reg_state *reg, u32 regno,
11485 struct bpf_kfunc_call_arg_meta *meta)
11487 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11488 &meta->arg_list_head.field);
11491 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11492 struct bpf_reg_state *reg, u32 regno,
11493 struct bpf_kfunc_call_arg_meta *meta)
11495 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11496 &meta->arg_rbtree_root.field);
11500 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11501 struct bpf_reg_state *reg, u32 regno,
11502 struct bpf_kfunc_call_arg_meta *meta,
11503 enum btf_field_type head_field_type,
11504 enum btf_field_type node_field_type,
11505 struct btf_field **node_field)
11507 const char *node_type_name;
11508 const struct btf_type *et, *t;
11509 struct btf_field *field;
11512 if (meta->btf != btf_vmlinux) {
11513 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11517 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11520 node_type_name = btf_field_type_name(node_field_type);
11521 if (!tnum_is_const(reg->var_off)) {
11523 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11524 regno, node_type_name);
11528 node_off = reg->off + reg->var_off.value;
11529 field = reg_find_field_offset(reg, node_off, node_field_type);
11530 if (!field || field->offset != node_off) {
11531 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11535 field = *node_field;
11537 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11538 t = btf_type_by_id(reg->btf, reg->btf_id);
11539 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11540 field->graph_root.value_btf_id, true)) {
11541 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11542 "in struct %s, but arg is at offset=%d in struct %s\n",
11543 btf_field_type_name(head_field_type),
11544 btf_field_type_name(node_field_type),
11545 field->graph_root.node_offset,
11546 btf_name_by_offset(field->graph_root.btf, et->name_off),
11547 node_off, btf_name_by_offset(reg->btf, t->name_off));
11550 meta->arg_btf = reg->btf;
11551 meta->arg_btf_id = reg->btf_id;
11553 if (node_off != field->graph_root.node_offset) {
11554 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11555 node_off, btf_field_type_name(node_field_type),
11556 field->graph_root.node_offset,
11557 btf_name_by_offset(field->graph_root.btf, et->name_off));
11564 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11565 struct bpf_reg_state *reg, u32 regno,
11566 struct bpf_kfunc_call_arg_meta *meta)
11568 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11569 BPF_LIST_HEAD, BPF_LIST_NODE,
11570 &meta->arg_list_head.field);
11573 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11574 struct bpf_reg_state *reg, u32 regno,
11575 struct bpf_kfunc_call_arg_meta *meta)
11577 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11578 BPF_RB_ROOT, BPF_RB_NODE,
11579 &meta->arg_rbtree_root.field);
11583 * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11584 * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11585 * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11586 * them can only be attached to some specific hook points.
11588 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11590 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11592 switch (prog_type) {
11593 case BPF_PROG_TYPE_LSM:
11595 case BPF_PROG_TYPE_TRACING:
11596 if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11600 return in_sleepable(env);
11604 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11607 const char *func_name = meta->func_name, *ref_tname;
11608 const struct btf *btf = meta->btf;
11609 const struct btf_param *args;
11610 struct btf_record *rec;
11614 args = (const struct btf_param *)(meta->func_proto + 1);
11615 nargs = btf_type_vlen(meta->func_proto);
11616 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11617 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11618 MAX_BPF_FUNC_REG_ARGS);
11622 /* Check that BTF function arguments match actual types that the
11625 for (i = 0; i < nargs; i++) {
11626 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
11627 const struct btf_type *t, *ref_t, *resolve_ret;
11628 enum bpf_arg_type arg_type = ARG_DONTCARE;
11629 u32 regno = i + 1, ref_id, type_size;
11630 bool is_ret_buf_sz = false;
11633 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11635 if (is_kfunc_arg_ignore(btf, &args[i]))
11638 if (btf_type_is_scalar(t)) {
11639 if (reg->type != SCALAR_VALUE) {
11640 verbose(env, "R%d is not a scalar\n", regno);
11644 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11645 if (meta->arg_constant.found) {
11646 verbose(env, "verifier internal error: only one constant argument permitted\n");
11649 if (!tnum_is_const(reg->var_off)) {
11650 verbose(env, "R%d must be a known constant\n", regno);
11653 ret = mark_chain_precision(env, regno);
11656 meta->arg_constant.found = true;
11657 meta->arg_constant.value = reg->var_off.value;
11658 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11659 meta->r0_rdonly = true;
11660 is_ret_buf_sz = true;
11661 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11662 is_ret_buf_sz = true;
11665 if (is_ret_buf_sz) {
11666 if (meta->r0_size) {
11667 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11671 if (!tnum_is_const(reg->var_off)) {
11672 verbose(env, "R%d is not a const\n", regno);
11676 meta->r0_size = reg->var_off.value;
11677 ret = mark_chain_precision(env, regno);
11684 if (!btf_type_is_ptr(t)) {
11685 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11689 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11690 (register_is_null(reg) || type_may_be_null(reg->type)) &&
11691 !is_kfunc_arg_nullable(meta->btf, &args[i])) {
11692 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11696 if (reg->ref_obj_id) {
11697 if (is_kfunc_release(meta) && meta->ref_obj_id) {
11698 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11699 regno, reg->ref_obj_id,
11703 meta->ref_obj_id = reg->ref_obj_id;
11704 if (is_kfunc_release(meta))
11705 meta->release_regno = regno;
11708 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11709 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11711 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11712 if (kf_arg_type < 0)
11713 return kf_arg_type;
11715 switch (kf_arg_type) {
11716 case KF_ARG_PTR_TO_NULL:
11718 case KF_ARG_PTR_TO_MAP:
11719 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11720 case KF_ARG_PTR_TO_BTF_ID:
11721 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11724 if (!is_trusted_reg(reg)) {
11725 if (!is_kfunc_rcu(meta)) {
11726 verbose(env, "R%d must be referenced or trusted\n", regno);
11729 if (!is_rcu_reg(reg)) {
11730 verbose(env, "R%d must be a rcu pointer\n", regno);
11736 case KF_ARG_PTR_TO_CTX:
11737 /* Trusted arguments have the same offset checks as release arguments */
11738 arg_type |= OBJ_RELEASE;
11740 case KF_ARG_PTR_TO_DYNPTR:
11741 case KF_ARG_PTR_TO_ITER:
11742 case KF_ARG_PTR_TO_LIST_HEAD:
11743 case KF_ARG_PTR_TO_LIST_NODE:
11744 case KF_ARG_PTR_TO_RB_ROOT:
11745 case KF_ARG_PTR_TO_RB_NODE:
11746 case KF_ARG_PTR_TO_MEM:
11747 case KF_ARG_PTR_TO_MEM_SIZE:
11748 case KF_ARG_PTR_TO_CALLBACK:
11749 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11750 case KF_ARG_PTR_TO_CONST_STR:
11751 /* Trusted by default */
11758 if (is_kfunc_release(meta) && reg->ref_obj_id)
11759 arg_type |= OBJ_RELEASE;
11760 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11764 switch (kf_arg_type) {
11765 case KF_ARG_PTR_TO_CTX:
11766 if (reg->type != PTR_TO_CTX) {
11767 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11771 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11772 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11775 meta->ret_btf_id = ret;
11778 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11779 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
11780 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
11781 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
11784 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
11785 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
11786 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
11790 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11793 if (!reg->ref_obj_id) {
11794 verbose(env, "allocated object must be referenced\n");
11797 if (meta->btf == btf_vmlinux) {
11798 meta->arg_btf = reg->btf;
11799 meta->arg_btf_id = reg->btf_id;
11802 case KF_ARG_PTR_TO_DYNPTR:
11804 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11805 int clone_ref_obj_id = 0;
11807 if (reg->type != PTR_TO_STACK &&
11808 reg->type != CONST_PTR_TO_DYNPTR) {
11809 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11813 if (reg->type == CONST_PTR_TO_DYNPTR)
11814 dynptr_arg_type |= MEM_RDONLY;
11816 if (is_kfunc_arg_uninit(btf, &args[i]))
11817 dynptr_arg_type |= MEM_UNINIT;
11819 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11820 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11821 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11822 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11823 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11824 (dynptr_arg_type & MEM_UNINIT)) {
11825 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11827 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11828 verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11832 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11833 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11834 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11835 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11840 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11844 if (!(dynptr_arg_type & MEM_UNINIT)) {
11845 int id = dynptr_id(env, reg);
11848 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11851 meta->initialized_dynptr.id = id;
11852 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11853 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11858 case KF_ARG_PTR_TO_ITER:
11859 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
11860 if (!check_css_task_iter_allowlist(env)) {
11861 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
11865 ret = process_iter_arg(env, regno, insn_idx, meta);
11869 case KF_ARG_PTR_TO_LIST_HEAD:
11870 if (reg->type != PTR_TO_MAP_VALUE &&
11871 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11872 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11875 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11876 verbose(env, "allocated object must be referenced\n");
11879 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11883 case KF_ARG_PTR_TO_RB_ROOT:
11884 if (reg->type != PTR_TO_MAP_VALUE &&
11885 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11886 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11889 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11890 verbose(env, "allocated object must be referenced\n");
11893 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11897 case KF_ARG_PTR_TO_LIST_NODE:
11898 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11899 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11902 if (!reg->ref_obj_id) {
11903 verbose(env, "allocated object must be referenced\n");
11906 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11910 case KF_ARG_PTR_TO_RB_NODE:
11911 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11912 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11913 verbose(env, "rbtree_remove node input must be non-owning ref\n");
11916 if (in_rbtree_lock_required_cb(env)) {
11917 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11921 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11922 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11925 if (!reg->ref_obj_id) {
11926 verbose(env, "allocated object must be referenced\n");
11931 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11935 case KF_ARG_PTR_TO_MAP:
11936 /* If argument has '__map' suffix expect 'struct bpf_map *' */
11937 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
11938 ref_t = btf_type_by_id(btf_vmlinux, ref_id);
11939 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11941 case KF_ARG_PTR_TO_BTF_ID:
11942 /* Only base_type is checked, further checks are done here */
11943 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11944 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11945 !reg2btf_ids[base_type(reg->type)]) {
11946 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11947 verbose(env, "expected %s or socket\n",
11948 reg_type_str(env, base_type(reg->type) |
11949 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11952 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11956 case KF_ARG_PTR_TO_MEM:
11957 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11958 if (IS_ERR(resolve_ret)) {
11959 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11960 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11963 ret = check_mem_reg(env, reg, regno, type_size);
11967 case KF_ARG_PTR_TO_MEM_SIZE:
11969 struct bpf_reg_state *buff_reg = ®s[regno];
11970 const struct btf_param *buff_arg = &args[i];
11971 struct bpf_reg_state *size_reg = ®s[regno + 1];
11972 const struct btf_param *size_arg = &args[i + 1];
11974 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11975 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11977 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11982 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11983 if (meta->arg_constant.found) {
11984 verbose(env, "verifier internal error: only one constant argument permitted\n");
11987 if (!tnum_is_const(size_reg->var_off)) {
11988 verbose(env, "R%d must be a known constant\n", regno + 1);
11991 meta->arg_constant.found = true;
11992 meta->arg_constant.value = size_reg->var_off.value;
11995 /* Skip next '__sz' or '__szk' argument */
11999 case KF_ARG_PTR_TO_CALLBACK:
12000 if (reg->type != PTR_TO_FUNC) {
12001 verbose(env, "arg%d expected pointer to func\n", i);
12004 meta->subprogno = reg->subprogno;
12006 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12007 if (!type_is_ptr_alloc_obj(reg->type)) {
12008 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
12011 if (!type_is_non_owning_ref(reg->type))
12012 meta->arg_owning_ref = true;
12014 rec = reg_btf_record(reg);
12016 verbose(env, "verifier internal error: Couldn't find btf_record\n");
12020 if (rec->refcount_off < 0) {
12021 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
12025 meta->arg_btf = reg->btf;
12026 meta->arg_btf_id = reg->btf_id;
12028 case KF_ARG_PTR_TO_CONST_STR:
12029 if (reg->type != PTR_TO_MAP_VALUE) {
12030 verbose(env, "arg#%d doesn't point to a const string\n", i);
12033 ret = check_reg_const_str(env, reg, regno);
12040 if (is_kfunc_release(meta) && !meta->release_regno) {
12041 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
12049 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
12050 struct bpf_insn *insn,
12051 struct bpf_kfunc_call_arg_meta *meta,
12052 const char **kfunc_name)
12054 const struct btf_type *func, *func_proto;
12055 u32 func_id, *kfunc_flags;
12056 const char *func_name;
12057 struct btf *desc_btf;
12060 *kfunc_name = NULL;
12065 desc_btf = find_kfunc_desc_btf(env, insn->off);
12066 if (IS_ERR(desc_btf))
12067 return PTR_ERR(desc_btf);
12069 func_id = insn->imm;
12070 func = btf_type_by_id(desc_btf, func_id);
12071 func_name = btf_name_by_offset(desc_btf, func->name_off);
12073 *kfunc_name = func_name;
12074 func_proto = btf_type_by_id(desc_btf, func->type);
12076 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
12077 if (!kfunc_flags) {
12081 memset(meta, 0, sizeof(*meta));
12082 meta->btf = desc_btf;
12083 meta->func_id = func_id;
12084 meta->kfunc_flags = *kfunc_flags;
12085 meta->func_proto = func_proto;
12086 meta->func_name = func_name;
12091 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
12093 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12096 const struct btf_type *t, *ptr_type;
12097 u32 i, nargs, ptr_type_id, release_ref_obj_id;
12098 struct bpf_reg_state *regs = cur_regs(env);
12099 const char *func_name, *ptr_type_name;
12100 bool sleepable, rcu_lock, rcu_unlock;
12101 struct bpf_kfunc_call_arg_meta meta;
12102 struct bpf_insn_aux_data *insn_aux;
12103 int err, insn_idx = *insn_idx_p;
12104 const struct btf_param *args;
12105 const struct btf_type *ret_t;
12106 struct btf *desc_btf;
12108 /* skip for now, but return error when we find this in fixup_kfunc_call */
12112 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
12113 if (err == -EACCES && func_name)
12114 verbose(env, "calling kernel function %s is not allowed\n", func_name);
12117 desc_btf = meta.btf;
12118 insn_aux = &env->insn_aux_data[insn_idx];
12120 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
12122 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12123 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12127 sleepable = is_kfunc_sleepable(&meta);
12128 if (sleepable && !in_sleepable(env)) {
12129 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12133 /* Check the arguments */
12134 err = check_kfunc_args(env, &meta, insn_idx);
12138 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12139 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12140 set_rbtree_add_callback_state);
12142 verbose(env, "kfunc %s#%d failed callback verification\n",
12143 func_name, meta.func_id);
12148 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
12149 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
12151 if (env->cur_state->active_rcu_lock) {
12152 struct bpf_func_state *state;
12153 struct bpf_reg_state *reg;
12154 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
12156 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
12157 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
12162 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
12164 } else if (rcu_unlock) {
12165 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
12166 if (reg->type & MEM_RCU) {
12167 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
12168 reg->type |= PTR_UNTRUSTED;
12171 env->cur_state->active_rcu_lock = false;
12172 } else if (sleepable) {
12173 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
12176 } else if (rcu_lock) {
12177 env->cur_state->active_rcu_lock = true;
12178 } else if (rcu_unlock) {
12179 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
12183 /* In case of release function, we get register number of refcounted
12184 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
12186 if (meta.release_regno) {
12187 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
12189 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12190 func_name, meta.func_id);
12195 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12196 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12197 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12198 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
12199 insn_aux->insert_off = regs[BPF_REG_2].off;
12200 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
12201 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
12203 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
12204 func_name, meta.func_id);
12208 err = release_reference(env, release_ref_obj_id);
12210 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12211 func_name, meta.func_id);
12216 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12217 if (!bpf_jit_supports_exceptions()) {
12218 verbose(env, "JIT does not support calling kfunc %s#%d\n",
12219 func_name, meta.func_id);
12222 env->seen_exception = true;
12224 /* In the case of the default callback, the cookie value passed
12225 * to bpf_throw becomes the return value of the program.
12227 if (!env->exception_callback_subprog) {
12228 err = check_return_code(env, BPF_REG_1, "R1");
12234 for (i = 0; i < CALLER_SAVED_REGS; i++)
12235 mark_reg_not_init(env, regs, caller_saved[i]);
12237 /* Check return type */
12238 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
12240 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
12241 /* Only exception is bpf_obj_new_impl */
12242 if (meta.btf != btf_vmlinux ||
12243 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
12244 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
12245 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
12246 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12251 if (btf_type_is_scalar(t)) {
12252 mark_reg_unknown(env, regs, BPF_REG_0);
12253 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12254 } else if (btf_type_is_ptr(t)) {
12255 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12257 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12258 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12259 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12260 struct btf_struct_meta *struct_meta;
12261 struct btf *ret_btf;
12264 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12267 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12268 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12272 ret_btf = env->prog->aux->btf;
12273 ret_btf_id = meta.arg_constant.value;
12275 /* This may be NULL due to user not supplying a BTF */
12277 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12281 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12282 if (!ret_t || !__btf_type_is_struct(ret_t)) {
12283 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12287 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12288 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
12289 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
12290 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
12294 if (!bpf_global_percpu_ma_set) {
12295 mutex_lock(&bpf_percpu_ma_lock);
12296 if (!bpf_global_percpu_ma_set) {
12297 /* Charge memory allocated with bpf_global_percpu_ma to
12298 * root memcg. The obj_cgroup for root memcg is NULL.
12300 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
12302 bpf_global_percpu_ma_set = true;
12304 mutex_unlock(&bpf_percpu_ma_lock);
12309 mutex_lock(&bpf_percpu_ma_lock);
12310 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
12311 mutex_unlock(&bpf_percpu_ma_lock);
12316 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12317 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12318 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12319 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12324 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12329 mark_reg_known_zero(env, regs, BPF_REG_0);
12330 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12331 regs[BPF_REG_0].btf = ret_btf;
12332 regs[BPF_REG_0].btf_id = ret_btf_id;
12333 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12334 regs[BPF_REG_0].type |= MEM_PERCPU;
12336 insn_aux->obj_new_size = ret_t->size;
12337 insn_aux->kptr_struct_meta = struct_meta;
12338 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12339 mark_reg_known_zero(env, regs, BPF_REG_0);
12340 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12341 regs[BPF_REG_0].btf = meta.arg_btf;
12342 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12344 insn_aux->kptr_struct_meta =
12345 btf_find_struct_meta(meta.arg_btf,
12347 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12348 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12349 struct btf_field *field = meta.arg_list_head.field;
12351 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12352 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12353 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12354 struct btf_field *field = meta.arg_rbtree_root.field;
12356 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12357 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12358 mark_reg_known_zero(env, regs, BPF_REG_0);
12359 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12360 regs[BPF_REG_0].btf = desc_btf;
12361 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12362 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12363 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12364 if (!ret_t || !btf_type_is_struct(ret_t)) {
12366 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12370 mark_reg_known_zero(env, regs, BPF_REG_0);
12371 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12372 regs[BPF_REG_0].btf = desc_btf;
12373 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12374 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12375 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12376 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12378 mark_reg_known_zero(env, regs, BPF_REG_0);
12380 if (!meta.arg_constant.found) {
12381 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12385 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12387 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12388 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12390 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12391 regs[BPF_REG_0].type |= MEM_RDONLY;
12393 /* this will set env->seen_direct_write to true */
12394 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12395 verbose(env, "the prog does not allow writes to packet data\n");
12400 if (!meta.initialized_dynptr.id) {
12401 verbose(env, "verifier internal error: no dynptr id\n");
12404 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12406 /* we don't need to set BPF_REG_0's ref obj id
12407 * because packet slices are not refcounted (see
12408 * dynptr_type_refcounted)
12411 verbose(env, "kernel function %s unhandled dynamic return type\n",
12415 } else if (btf_type_is_void(ptr_type)) {
12416 /* kfunc returning 'void *' is equivalent to returning scalar */
12417 mark_reg_unknown(env, regs, BPF_REG_0);
12418 } else if (!__btf_type_is_struct(ptr_type)) {
12419 if (!meta.r0_size) {
12422 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12424 meta.r0_rdonly = true;
12427 if (!meta.r0_size) {
12428 ptr_type_name = btf_name_by_offset(desc_btf,
12429 ptr_type->name_off);
12431 "kernel function %s returns pointer type %s %s is not supported\n",
12433 btf_type_str(ptr_type),
12438 mark_reg_known_zero(env, regs, BPF_REG_0);
12439 regs[BPF_REG_0].type = PTR_TO_MEM;
12440 regs[BPF_REG_0].mem_size = meta.r0_size;
12442 if (meta.r0_rdonly)
12443 regs[BPF_REG_0].type |= MEM_RDONLY;
12445 /* Ensures we don't access the memory after a release_reference() */
12446 if (meta.ref_obj_id)
12447 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12449 mark_reg_known_zero(env, regs, BPF_REG_0);
12450 regs[BPF_REG_0].btf = desc_btf;
12451 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12452 regs[BPF_REG_0].btf_id = ptr_type_id;
12455 if (is_kfunc_ret_null(&meta)) {
12456 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12457 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12458 regs[BPF_REG_0].id = ++env->id_gen;
12460 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12461 if (is_kfunc_acquire(&meta)) {
12462 int id = acquire_reference_state(env, insn_idx);
12466 if (is_kfunc_ret_null(&meta))
12467 regs[BPF_REG_0].id = id;
12468 regs[BPF_REG_0].ref_obj_id = id;
12469 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12470 ref_set_non_owning(env, ®s[BPF_REG_0]);
12473 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
12474 regs[BPF_REG_0].id = ++env->id_gen;
12475 } else if (btf_type_is_void(t)) {
12476 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12477 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12478 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12479 insn_aux->kptr_struct_meta =
12480 btf_find_struct_meta(meta.arg_btf,
12486 nargs = btf_type_vlen(meta.func_proto);
12487 args = (const struct btf_param *)(meta.func_proto + 1);
12488 for (i = 0; i < nargs; i++) {
12491 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12492 if (btf_type_is_ptr(t))
12493 mark_btf_func_reg_size(env, regno, sizeof(void *));
12495 /* scalar. ensured by btf_check_kfunc_arg_match() */
12496 mark_btf_func_reg_size(env, regno, t->size);
12499 if (is_iter_next_kfunc(&meta)) {
12500 err = process_iter_next_call(env, insn_idx, &meta);
12508 static bool signed_add_overflows(s64 a, s64 b)
12510 /* Do the add in u64, where overflow is well-defined */
12511 s64 res = (s64)((u64)a + (u64)b);
12518 static bool signed_add32_overflows(s32 a, s32 b)
12520 /* Do the add in u32, where overflow is well-defined */
12521 s32 res = (s32)((u32)a + (u32)b);
12528 static bool signed_sub_overflows(s64 a, s64 b)
12530 /* Do the sub in u64, where overflow is well-defined */
12531 s64 res = (s64)((u64)a - (u64)b);
12538 static bool signed_sub32_overflows(s32 a, s32 b)
12540 /* Do the sub in u32, where overflow is well-defined */
12541 s32 res = (s32)((u32)a - (u32)b);
12548 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12549 const struct bpf_reg_state *reg,
12550 enum bpf_reg_type type)
12552 bool known = tnum_is_const(reg->var_off);
12553 s64 val = reg->var_off.value;
12554 s64 smin = reg->smin_value;
12556 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12557 verbose(env, "math between %s pointer and %lld is not allowed\n",
12558 reg_type_str(env, type), val);
12562 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12563 verbose(env, "%s pointer offset %d is not allowed\n",
12564 reg_type_str(env, type), reg->off);
12568 if (smin == S64_MIN) {
12569 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12570 reg_type_str(env, type));
12574 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12575 verbose(env, "value %lld makes %s pointer be out of bounds\n",
12576 smin, reg_type_str(env, type));
12584 REASON_BOUNDS = -1,
12591 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12592 u32 *alu_limit, bool mask_to_left)
12594 u32 max = 0, ptr_limit = 0;
12596 switch (ptr_reg->type) {
12598 /* Offset 0 is out-of-bounds, but acceptable start for the
12599 * left direction, see BPF_REG_FP. Also, unknown scalar
12600 * offset where we would need to deal with min/max bounds is
12601 * currently prohibited for unprivileged.
12603 max = MAX_BPF_STACK + mask_to_left;
12604 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12606 case PTR_TO_MAP_VALUE:
12607 max = ptr_reg->map_ptr->value_size;
12608 ptr_limit = (mask_to_left ?
12609 ptr_reg->smin_value :
12610 ptr_reg->umax_value) + ptr_reg->off;
12613 return REASON_TYPE;
12616 if (ptr_limit >= max)
12617 return REASON_LIMIT;
12618 *alu_limit = ptr_limit;
12622 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12623 const struct bpf_insn *insn)
12625 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12628 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12629 u32 alu_state, u32 alu_limit)
12631 /* If we arrived here from different branches with different
12632 * state or limits to sanitize, then this won't work.
12634 if (aux->alu_state &&
12635 (aux->alu_state != alu_state ||
12636 aux->alu_limit != alu_limit))
12637 return REASON_PATHS;
12639 /* Corresponding fixup done in do_misc_fixups(). */
12640 aux->alu_state = alu_state;
12641 aux->alu_limit = alu_limit;
12645 static int sanitize_val_alu(struct bpf_verifier_env *env,
12646 struct bpf_insn *insn)
12648 struct bpf_insn_aux_data *aux = cur_aux(env);
12650 if (can_skip_alu_sanitation(env, insn))
12653 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12656 static bool sanitize_needed(u8 opcode)
12658 return opcode == BPF_ADD || opcode == BPF_SUB;
12661 struct bpf_sanitize_info {
12662 struct bpf_insn_aux_data aux;
12666 static struct bpf_verifier_state *
12667 sanitize_speculative_path(struct bpf_verifier_env *env,
12668 const struct bpf_insn *insn,
12669 u32 next_idx, u32 curr_idx)
12671 struct bpf_verifier_state *branch;
12672 struct bpf_reg_state *regs;
12674 branch = push_stack(env, next_idx, curr_idx, true);
12675 if (branch && insn) {
12676 regs = branch->frame[branch->curframe]->regs;
12677 if (BPF_SRC(insn->code) == BPF_K) {
12678 mark_reg_unknown(env, regs, insn->dst_reg);
12679 } else if (BPF_SRC(insn->code) == BPF_X) {
12680 mark_reg_unknown(env, regs, insn->dst_reg);
12681 mark_reg_unknown(env, regs, insn->src_reg);
12687 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12688 struct bpf_insn *insn,
12689 const struct bpf_reg_state *ptr_reg,
12690 const struct bpf_reg_state *off_reg,
12691 struct bpf_reg_state *dst_reg,
12692 struct bpf_sanitize_info *info,
12693 const bool commit_window)
12695 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12696 struct bpf_verifier_state *vstate = env->cur_state;
12697 bool off_is_imm = tnum_is_const(off_reg->var_off);
12698 bool off_is_neg = off_reg->smin_value < 0;
12699 bool ptr_is_dst_reg = ptr_reg == dst_reg;
12700 u8 opcode = BPF_OP(insn->code);
12701 u32 alu_state, alu_limit;
12702 struct bpf_reg_state tmp;
12706 if (can_skip_alu_sanitation(env, insn))
12709 /* We already marked aux for masking from non-speculative
12710 * paths, thus we got here in the first place. We only care
12711 * to explore bad access from here.
12713 if (vstate->speculative)
12716 if (!commit_window) {
12717 if (!tnum_is_const(off_reg->var_off) &&
12718 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12719 return REASON_BOUNDS;
12721 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
12722 (opcode == BPF_SUB && !off_is_neg);
12725 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12729 if (commit_window) {
12730 /* In commit phase we narrow the masking window based on
12731 * the observed pointer move after the simulated operation.
12733 alu_state = info->aux.alu_state;
12734 alu_limit = abs(info->aux.alu_limit - alu_limit);
12736 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12737 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12738 alu_state |= ptr_is_dst_reg ?
12739 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12741 /* Limit pruning on unknown scalars to enable deep search for
12742 * potential masking differences from other program paths.
12745 env->explore_alu_limits = true;
12748 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12752 /* If we're in commit phase, we're done here given we already
12753 * pushed the truncated dst_reg into the speculative verification
12756 * Also, when register is a known constant, we rewrite register-based
12757 * operation to immediate-based, and thus do not need masking (and as
12758 * a consequence, do not need to simulate the zero-truncation either).
12760 if (commit_window || off_is_imm)
12763 /* Simulate and find potential out-of-bounds access under
12764 * speculative execution from truncation as a result of
12765 * masking when off was not within expected range. If off
12766 * sits in dst, then we temporarily need to move ptr there
12767 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12768 * for cases where we use K-based arithmetic in one direction
12769 * and truncated reg-based in the other in order to explore
12772 if (!ptr_is_dst_reg) {
12774 copy_register_state(dst_reg, ptr_reg);
12776 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12778 if (!ptr_is_dst_reg && ret)
12780 return !ret ? REASON_STACK : 0;
12783 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12785 struct bpf_verifier_state *vstate = env->cur_state;
12787 /* If we simulate paths under speculation, we don't update the
12788 * insn as 'seen' such that when we verify unreachable paths in
12789 * the non-speculative domain, sanitize_dead_code() can still
12790 * rewrite/sanitize them.
12792 if (!vstate->speculative)
12793 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12796 static int sanitize_err(struct bpf_verifier_env *env,
12797 const struct bpf_insn *insn, int reason,
12798 const struct bpf_reg_state *off_reg,
12799 const struct bpf_reg_state *dst_reg)
12801 static const char *err = "pointer arithmetic with it prohibited for !root";
12802 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12803 u32 dst = insn->dst_reg, src = insn->src_reg;
12806 case REASON_BOUNDS:
12807 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12808 off_reg == dst_reg ? dst : src, err);
12811 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12812 off_reg == dst_reg ? src : dst, err);
12815 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12819 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12823 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12827 verbose(env, "verifier internal error: unknown reason (%d)\n",
12835 /* check that stack access falls within stack limits and that 'reg' doesn't
12836 * have a variable offset.
12838 * Variable offset is prohibited for unprivileged mode for simplicity since it
12839 * requires corresponding support in Spectre masking for stack ALU. See also
12840 * retrieve_ptr_limit().
12843 * 'off' includes 'reg->off'.
12845 static int check_stack_access_for_ptr_arithmetic(
12846 struct bpf_verifier_env *env,
12848 const struct bpf_reg_state *reg,
12851 if (!tnum_is_const(reg->var_off)) {
12854 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12855 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12856 regno, tn_buf, off);
12860 if (off >= 0 || off < -MAX_BPF_STACK) {
12861 verbose(env, "R%d stack pointer arithmetic goes out of range, "
12862 "prohibited for !root; off=%d\n", regno, off);
12869 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12870 const struct bpf_insn *insn,
12871 const struct bpf_reg_state *dst_reg)
12873 u32 dst = insn->dst_reg;
12875 /* For unprivileged we require that resulting offset must be in bounds
12876 * in order to be able to sanitize access later on.
12878 if (env->bypass_spec_v1)
12881 switch (dst_reg->type) {
12883 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12884 dst_reg->off + dst_reg->var_off.value))
12887 case PTR_TO_MAP_VALUE:
12888 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12889 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12890 "prohibited for !root\n", dst);
12901 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12902 * Caller should also handle BPF_MOV case separately.
12903 * If we return -EACCES, caller may want to try again treating pointer as a
12904 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
12906 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12907 struct bpf_insn *insn,
12908 const struct bpf_reg_state *ptr_reg,
12909 const struct bpf_reg_state *off_reg)
12911 struct bpf_verifier_state *vstate = env->cur_state;
12912 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12913 struct bpf_reg_state *regs = state->regs, *dst_reg;
12914 bool known = tnum_is_const(off_reg->var_off);
12915 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12916 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12917 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12918 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12919 struct bpf_sanitize_info info = {};
12920 u8 opcode = BPF_OP(insn->code);
12921 u32 dst = insn->dst_reg;
12924 dst_reg = ®s[dst];
12926 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12927 smin_val > smax_val || umin_val > umax_val) {
12928 /* Taint dst register if offset had invalid bounds derived from
12929 * e.g. dead branches.
12931 __mark_reg_unknown(env, dst_reg);
12935 if (BPF_CLASS(insn->code) != BPF_ALU64) {
12936 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12937 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12938 __mark_reg_unknown(env, dst_reg);
12943 "R%d 32-bit pointer arithmetic prohibited\n",
12948 if (ptr_reg->type & PTR_MAYBE_NULL) {
12949 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12950 dst, reg_type_str(env, ptr_reg->type));
12954 switch (base_type(ptr_reg->type)) {
12956 case PTR_TO_MAP_VALUE:
12957 case PTR_TO_MAP_KEY:
12959 case PTR_TO_PACKET_META:
12960 case PTR_TO_PACKET:
12961 case PTR_TO_TP_BUFFER:
12962 case PTR_TO_BTF_ID:
12966 case CONST_PTR_TO_DYNPTR:
12968 case PTR_TO_FLOW_KEYS:
12972 case CONST_PTR_TO_MAP:
12973 /* smin_val represents the known value */
12974 if (known && smin_val == 0 && opcode == BPF_ADD)
12978 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12979 dst, reg_type_str(env, ptr_reg->type));
12983 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12984 * The id may be overwritten later if we create a new variable offset.
12986 dst_reg->type = ptr_reg->type;
12987 dst_reg->id = ptr_reg->id;
12989 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12990 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12993 /* pointer types do not carry 32-bit bounds at the moment. */
12994 __mark_reg32_unbounded(dst_reg);
12996 if (sanitize_needed(opcode)) {
12997 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
13000 return sanitize_err(env, insn, ret, off_reg, dst_reg);
13005 /* We can take a fixed offset as long as it doesn't overflow
13006 * the s32 'off' field
13008 if (known && (ptr_reg->off + smin_val ==
13009 (s64)(s32)(ptr_reg->off + smin_val))) {
13010 /* pointer += K. Accumulate it into fixed offset */
13011 dst_reg->smin_value = smin_ptr;
13012 dst_reg->smax_value = smax_ptr;
13013 dst_reg->umin_value = umin_ptr;
13014 dst_reg->umax_value = umax_ptr;
13015 dst_reg->var_off = ptr_reg->var_off;
13016 dst_reg->off = ptr_reg->off + smin_val;
13017 dst_reg->raw = ptr_reg->raw;
13020 /* A new variable offset is created. Note that off_reg->off
13021 * == 0, since it's a scalar.
13022 * dst_reg gets the pointer type and since some positive
13023 * integer value was added to the pointer, give it a new 'id'
13024 * if it's a PTR_TO_PACKET.
13025 * this creates a new 'base' pointer, off_reg (variable) gets
13026 * added into the variable offset, and we copy the fixed offset
13029 if (signed_add_overflows(smin_ptr, smin_val) ||
13030 signed_add_overflows(smax_ptr, smax_val)) {
13031 dst_reg->smin_value = S64_MIN;
13032 dst_reg->smax_value = S64_MAX;
13034 dst_reg->smin_value = smin_ptr + smin_val;
13035 dst_reg->smax_value = smax_ptr + smax_val;
13037 if (umin_ptr + umin_val < umin_ptr ||
13038 umax_ptr + umax_val < umax_ptr) {
13039 dst_reg->umin_value = 0;
13040 dst_reg->umax_value = U64_MAX;
13042 dst_reg->umin_value = umin_ptr + umin_val;
13043 dst_reg->umax_value = umax_ptr + umax_val;
13045 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
13046 dst_reg->off = ptr_reg->off;
13047 dst_reg->raw = ptr_reg->raw;
13048 if (reg_is_pkt_pointer(ptr_reg)) {
13049 dst_reg->id = ++env->id_gen;
13050 /* something was added to pkt_ptr, set range to zero */
13051 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13055 if (dst_reg == off_reg) {
13056 /* scalar -= pointer. Creates an unknown scalar */
13057 verbose(env, "R%d tried to subtract pointer from scalar\n",
13061 /* We don't allow subtraction from FP, because (according to
13062 * test_verifier.c test "invalid fp arithmetic", JITs might not
13063 * be able to deal with it.
13065 if (ptr_reg->type == PTR_TO_STACK) {
13066 verbose(env, "R%d subtraction from stack pointer prohibited\n",
13070 if (known && (ptr_reg->off - smin_val ==
13071 (s64)(s32)(ptr_reg->off - smin_val))) {
13072 /* pointer -= K. Subtract it from fixed offset */
13073 dst_reg->smin_value = smin_ptr;
13074 dst_reg->smax_value = smax_ptr;
13075 dst_reg->umin_value = umin_ptr;
13076 dst_reg->umax_value = umax_ptr;
13077 dst_reg->var_off = ptr_reg->var_off;
13078 dst_reg->id = ptr_reg->id;
13079 dst_reg->off = ptr_reg->off - smin_val;
13080 dst_reg->raw = ptr_reg->raw;
13083 /* A new variable offset is created. If the subtrahend is known
13084 * nonnegative, then any reg->range we had before is still good.
13086 if (signed_sub_overflows(smin_ptr, smax_val) ||
13087 signed_sub_overflows(smax_ptr, smin_val)) {
13088 /* Overflow possible, we know nothing */
13089 dst_reg->smin_value = S64_MIN;
13090 dst_reg->smax_value = S64_MAX;
13092 dst_reg->smin_value = smin_ptr - smax_val;
13093 dst_reg->smax_value = smax_ptr - smin_val;
13095 if (umin_ptr < umax_val) {
13096 /* Overflow possible, we know nothing */
13097 dst_reg->umin_value = 0;
13098 dst_reg->umax_value = U64_MAX;
13100 /* Cannot overflow (as long as bounds are consistent) */
13101 dst_reg->umin_value = umin_ptr - umax_val;
13102 dst_reg->umax_value = umax_ptr - umin_val;
13104 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
13105 dst_reg->off = ptr_reg->off;
13106 dst_reg->raw = ptr_reg->raw;
13107 if (reg_is_pkt_pointer(ptr_reg)) {
13108 dst_reg->id = ++env->id_gen;
13109 /* something was added to pkt_ptr, set range to zero */
13111 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13117 /* bitwise ops on pointers are troublesome, prohibit. */
13118 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
13119 dst, bpf_alu_string[opcode >> 4]);
13122 /* other operators (e.g. MUL,LSH) produce non-pointer results */
13123 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
13124 dst, bpf_alu_string[opcode >> 4]);
13128 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
13130 reg_bounds_sync(dst_reg);
13131 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
13133 if (sanitize_needed(opcode)) {
13134 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13137 return sanitize_err(env, insn, ret, off_reg, dst_reg);
13143 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13144 struct bpf_reg_state *src_reg)
13146 s32 smin_val = src_reg->s32_min_value;
13147 s32 smax_val = src_reg->s32_max_value;
13148 u32 umin_val = src_reg->u32_min_value;
13149 u32 umax_val = src_reg->u32_max_value;
13151 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
13152 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
13153 dst_reg->s32_min_value = S32_MIN;
13154 dst_reg->s32_max_value = S32_MAX;
13156 dst_reg->s32_min_value += smin_val;
13157 dst_reg->s32_max_value += smax_val;
13159 if (dst_reg->u32_min_value + umin_val < umin_val ||
13160 dst_reg->u32_max_value + umax_val < umax_val) {
13161 dst_reg->u32_min_value = 0;
13162 dst_reg->u32_max_value = U32_MAX;
13164 dst_reg->u32_min_value += umin_val;
13165 dst_reg->u32_max_value += umax_val;
13169 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13170 struct bpf_reg_state *src_reg)
13172 s64 smin_val = src_reg->smin_value;
13173 s64 smax_val = src_reg->smax_value;
13174 u64 umin_val = src_reg->umin_value;
13175 u64 umax_val = src_reg->umax_value;
13177 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
13178 signed_add_overflows(dst_reg->smax_value, smax_val)) {
13179 dst_reg->smin_value = S64_MIN;
13180 dst_reg->smax_value = S64_MAX;
13182 dst_reg->smin_value += smin_val;
13183 dst_reg->smax_value += smax_val;
13185 if (dst_reg->umin_value + umin_val < umin_val ||
13186 dst_reg->umax_value + umax_val < umax_val) {
13187 dst_reg->umin_value = 0;
13188 dst_reg->umax_value = U64_MAX;
13190 dst_reg->umin_value += umin_val;
13191 dst_reg->umax_value += umax_val;
13195 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13196 struct bpf_reg_state *src_reg)
13198 s32 smin_val = src_reg->s32_min_value;
13199 s32 smax_val = src_reg->s32_max_value;
13200 u32 umin_val = src_reg->u32_min_value;
13201 u32 umax_val = src_reg->u32_max_value;
13203 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
13204 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
13205 /* Overflow possible, we know nothing */
13206 dst_reg->s32_min_value = S32_MIN;
13207 dst_reg->s32_max_value = S32_MAX;
13209 dst_reg->s32_min_value -= smax_val;
13210 dst_reg->s32_max_value -= smin_val;
13212 if (dst_reg->u32_min_value < umax_val) {
13213 /* Overflow possible, we know nothing */
13214 dst_reg->u32_min_value = 0;
13215 dst_reg->u32_max_value = U32_MAX;
13217 /* Cannot overflow (as long as bounds are consistent) */
13218 dst_reg->u32_min_value -= umax_val;
13219 dst_reg->u32_max_value -= umin_val;
13223 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13224 struct bpf_reg_state *src_reg)
13226 s64 smin_val = src_reg->smin_value;
13227 s64 smax_val = src_reg->smax_value;
13228 u64 umin_val = src_reg->umin_value;
13229 u64 umax_val = src_reg->umax_value;
13231 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
13232 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
13233 /* Overflow possible, we know nothing */
13234 dst_reg->smin_value = S64_MIN;
13235 dst_reg->smax_value = S64_MAX;
13237 dst_reg->smin_value -= smax_val;
13238 dst_reg->smax_value -= smin_val;
13240 if (dst_reg->umin_value < umax_val) {
13241 /* Overflow possible, we know nothing */
13242 dst_reg->umin_value = 0;
13243 dst_reg->umax_value = U64_MAX;
13245 /* Cannot overflow (as long as bounds are consistent) */
13246 dst_reg->umin_value -= umax_val;
13247 dst_reg->umax_value -= umin_val;
13251 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13252 struct bpf_reg_state *src_reg)
13254 s32 smin_val = src_reg->s32_min_value;
13255 u32 umin_val = src_reg->u32_min_value;
13256 u32 umax_val = src_reg->u32_max_value;
13258 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13259 /* Ain't nobody got time to multiply that sign */
13260 __mark_reg32_unbounded(dst_reg);
13263 /* Both values are positive, so we can work with unsigned and
13264 * copy the result to signed (unless it exceeds S32_MAX).
13266 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13267 /* Potential overflow, we know nothing */
13268 __mark_reg32_unbounded(dst_reg);
13271 dst_reg->u32_min_value *= umin_val;
13272 dst_reg->u32_max_value *= umax_val;
13273 if (dst_reg->u32_max_value > S32_MAX) {
13274 /* Overflow possible, we know nothing */
13275 dst_reg->s32_min_value = S32_MIN;
13276 dst_reg->s32_max_value = S32_MAX;
13278 dst_reg->s32_min_value = dst_reg->u32_min_value;
13279 dst_reg->s32_max_value = dst_reg->u32_max_value;
13283 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13284 struct bpf_reg_state *src_reg)
13286 s64 smin_val = src_reg->smin_value;
13287 u64 umin_val = src_reg->umin_value;
13288 u64 umax_val = src_reg->umax_value;
13290 if (smin_val < 0 || dst_reg->smin_value < 0) {
13291 /* Ain't nobody got time to multiply that sign */
13292 __mark_reg64_unbounded(dst_reg);
13295 /* Both values are positive, so we can work with unsigned and
13296 * copy the result to signed (unless it exceeds S64_MAX).
13298 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13299 /* Potential overflow, we know nothing */
13300 __mark_reg64_unbounded(dst_reg);
13303 dst_reg->umin_value *= umin_val;
13304 dst_reg->umax_value *= umax_val;
13305 if (dst_reg->umax_value > S64_MAX) {
13306 /* Overflow possible, we know nothing */
13307 dst_reg->smin_value = S64_MIN;
13308 dst_reg->smax_value = S64_MAX;
13310 dst_reg->smin_value = dst_reg->umin_value;
13311 dst_reg->smax_value = dst_reg->umax_value;
13315 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13316 struct bpf_reg_state *src_reg)
13318 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13319 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13320 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13321 s32 smin_val = src_reg->s32_min_value;
13322 u32 umax_val = src_reg->u32_max_value;
13324 if (src_known && dst_known) {
13325 __mark_reg32_known(dst_reg, var32_off.value);
13329 /* We get our minimum from the var_off, since that's inherently
13330 * bitwise. Our maximum is the minimum of the operands' maxima.
13332 dst_reg->u32_min_value = var32_off.value;
13333 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13334 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13335 /* Lose signed bounds when ANDing negative numbers,
13336 * ain't nobody got time for that.
13338 dst_reg->s32_min_value = S32_MIN;
13339 dst_reg->s32_max_value = S32_MAX;
13341 /* ANDing two positives gives a positive, so safe to
13342 * cast result into s64.
13344 dst_reg->s32_min_value = dst_reg->u32_min_value;
13345 dst_reg->s32_max_value = dst_reg->u32_max_value;
13349 static void scalar_min_max_and(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;
13355 u64 umax_val = src_reg->umax_value;
13357 if (src_known && dst_known) {
13358 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13362 /* We get our minimum from the var_off, since that's inherently
13363 * bitwise. Our maximum is the minimum of the operands' maxima.
13365 dst_reg->umin_value = dst_reg->var_off.value;
13366 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13367 if (dst_reg->smin_value < 0 || smin_val < 0) {
13368 /* Lose signed bounds when ANDing negative numbers,
13369 * ain't nobody got time for that.
13371 dst_reg->smin_value = S64_MIN;
13372 dst_reg->smax_value = S64_MAX;
13374 /* ANDing two positives gives a positive, so safe to
13375 * cast result into s64.
13377 dst_reg->smin_value = dst_reg->umin_value;
13378 dst_reg->smax_value = dst_reg->umax_value;
13380 /* We may learn something more from the var_off */
13381 __update_reg_bounds(dst_reg);
13384 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13385 struct bpf_reg_state *src_reg)
13387 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13388 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13389 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13390 s32 smin_val = src_reg->s32_min_value;
13391 u32 umin_val = src_reg->u32_min_value;
13393 if (src_known && dst_known) {
13394 __mark_reg32_known(dst_reg, var32_off.value);
13398 /* We get our maximum from the var_off, and our minimum is the
13399 * maximum of the operands' minima
13401 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13402 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13403 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13404 /* Lose signed bounds when ORing negative numbers,
13405 * ain't nobody got time for that.
13407 dst_reg->s32_min_value = S32_MIN;
13408 dst_reg->s32_max_value = S32_MAX;
13410 /* ORing two positives gives a positive, so safe to
13411 * cast result into s64.
13413 dst_reg->s32_min_value = dst_reg->u32_min_value;
13414 dst_reg->s32_max_value = dst_reg->u32_max_value;
13418 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13419 struct bpf_reg_state *src_reg)
13421 bool src_known = tnum_is_const(src_reg->var_off);
13422 bool dst_known = tnum_is_const(dst_reg->var_off);
13423 s64 smin_val = src_reg->smin_value;
13424 u64 umin_val = src_reg->umin_value;
13426 if (src_known && dst_known) {
13427 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13431 /* We get our maximum from the var_off, and our minimum is the
13432 * maximum of the operands' minima
13434 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13435 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13436 if (dst_reg->smin_value < 0 || smin_val < 0) {
13437 /* Lose signed bounds when ORing negative numbers,
13438 * ain't nobody got time for that.
13440 dst_reg->smin_value = S64_MIN;
13441 dst_reg->smax_value = S64_MAX;
13443 /* ORing two positives gives a positive, so safe to
13444 * cast result into s64.
13446 dst_reg->smin_value = dst_reg->umin_value;
13447 dst_reg->smax_value = dst_reg->umax_value;
13449 /* We may learn something more from the var_off */
13450 __update_reg_bounds(dst_reg);
13453 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13454 struct bpf_reg_state *src_reg)
13456 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13457 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13458 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13459 s32 smin_val = src_reg->s32_min_value;
13461 if (src_known && dst_known) {
13462 __mark_reg32_known(dst_reg, var32_off.value);
13466 /* We get both minimum and maximum from the var32_off. */
13467 dst_reg->u32_min_value = var32_off.value;
13468 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13470 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13471 /* XORing two positive sign numbers gives a positive,
13472 * so safe to cast u32 result into s32.
13474 dst_reg->s32_min_value = dst_reg->u32_min_value;
13475 dst_reg->s32_max_value = dst_reg->u32_max_value;
13477 dst_reg->s32_min_value = S32_MIN;
13478 dst_reg->s32_max_value = S32_MAX;
13482 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13483 struct bpf_reg_state *src_reg)
13485 bool src_known = tnum_is_const(src_reg->var_off);
13486 bool dst_known = tnum_is_const(dst_reg->var_off);
13487 s64 smin_val = src_reg->smin_value;
13489 if (src_known && dst_known) {
13490 /* dst_reg->var_off.value has been updated earlier */
13491 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13495 /* We get both minimum and maximum from the var_off. */
13496 dst_reg->umin_value = dst_reg->var_off.value;
13497 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13499 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13500 /* XORing two positive sign numbers gives a positive,
13501 * so safe to cast u64 result into s64.
13503 dst_reg->smin_value = dst_reg->umin_value;
13504 dst_reg->smax_value = dst_reg->umax_value;
13506 dst_reg->smin_value = S64_MIN;
13507 dst_reg->smax_value = S64_MAX;
13510 __update_reg_bounds(dst_reg);
13513 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13514 u64 umin_val, u64 umax_val)
13516 /* We lose all sign bit information (except what we can pick
13519 dst_reg->s32_min_value = S32_MIN;
13520 dst_reg->s32_max_value = S32_MAX;
13521 /* If we might shift our top bit out, then we know nothing */
13522 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13523 dst_reg->u32_min_value = 0;
13524 dst_reg->u32_max_value = U32_MAX;
13526 dst_reg->u32_min_value <<= umin_val;
13527 dst_reg->u32_max_value <<= umax_val;
13531 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13532 struct bpf_reg_state *src_reg)
13534 u32 umax_val = src_reg->u32_max_value;
13535 u32 umin_val = src_reg->u32_min_value;
13536 /* u32 alu operation will zext upper bits */
13537 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13539 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13540 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13541 /* Not required but being careful mark reg64 bounds as unknown so
13542 * that we are forced to pick them up from tnum and zext later and
13543 * if some path skips this step we are still safe.
13545 __mark_reg64_unbounded(dst_reg);
13546 __update_reg32_bounds(dst_reg);
13549 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13550 u64 umin_val, u64 umax_val)
13552 /* Special case <<32 because it is a common compiler pattern to sign
13553 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13554 * positive we know this shift will also be positive so we can track
13555 * bounds correctly. Otherwise we lose all sign bit information except
13556 * what we can pick up from var_off. Perhaps we can generalize this
13557 * later to shifts of any length.
13559 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13560 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13562 dst_reg->smax_value = S64_MAX;
13564 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13565 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13567 dst_reg->smin_value = S64_MIN;
13569 /* If we might shift our top bit out, then we know nothing */
13570 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13571 dst_reg->umin_value = 0;
13572 dst_reg->umax_value = U64_MAX;
13574 dst_reg->umin_value <<= umin_val;
13575 dst_reg->umax_value <<= umax_val;
13579 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13580 struct bpf_reg_state *src_reg)
13582 u64 umax_val = src_reg->umax_value;
13583 u64 umin_val = src_reg->umin_value;
13585 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
13586 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13587 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13589 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13590 /* We may learn something more from the var_off */
13591 __update_reg_bounds(dst_reg);
13594 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13595 struct bpf_reg_state *src_reg)
13597 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13598 u32 umax_val = src_reg->u32_max_value;
13599 u32 umin_val = src_reg->u32_min_value;
13601 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13602 * be negative, then either:
13603 * 1) src_reg might be zero, so the sign bit of the result is
13604 * unknown, so we lose our signed bounds
13605 * 2) it's known negative, thus the unsigned bounds capture the
13607 * 3) the signed bounds cross zero, so they tell us nothing
13609 * If the value in dst_reg is known nonnegative, then again the
13610 * unsigned bounds capture the signed bounds.
13611 * Thus, in all cases it suffices to blow away our signed bounds
13612 * and rely on inferring new ones from the unsigned bounds and
13613 * var_off of the result.
13615 dst_reg->s32_min_value = S32_MIN;
13616 dst_reg->s32_max_value = S32_MAX;
13618 dst_reg->var_off = tnum_rshift(subreg, umin_val);
13619 dst_reg->u32_min_value >>= umax_val;
13620 dst_reg->u32_max_value >>= umin_val;
13622 __mark_reg64_unbounded(dst_reg);
13623 __update_reg32_bounds(dst_reg);
13626 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13627 struct bpf_reg_state *src_reg)
13629 u64 umax_val = src_reg->umax_value;
13630 u64 umin_val = src_reg->umin_value;
13632 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13633 * be negative, then either:
13634 * 1) src_reg might be zero, so the sign bit of the result is
13635 * unknown, so we lose our signed bounds
13636 * 2) it's known negative, thus the unsigned bounds capture the
13638 * 3) the signed bounds cross zero, so they tell us nothing
13640 * If the value in dst_reg is known nonnegative, then again the
13641 * unsigned bounds capture the signed bounds.
13642 * Thus, in all cases it suffices to blow away our signed bounds
13643 * and rely on inferring new ones from the unsigned bounds and
13644 * var_off of the result.
13646 dst_reg->smin_value = S64_MIN;
13647 dst_reg->smax_value = S64_MAX;
13648 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13649 dst_reg->umin_value >>= umax_val;
13650 dst_reg->umax_value >>= umin_val;
13652 /* Its not easy to operate on alu32 bounds here because it depends
13653 * on bits being shifted in. Take easy way out and mark unbounded
13654 * so we can recalculate later from tnum.
13656 __mark_reg32_unbounded(dst_reg);
13657 __update_reg_bounds(dst_reg);
13660 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13661 struct bpf_reg_state *src_reg)
13663 u64 umin_val = src_reg->u32_min_value;
13665 /* Upon reaching here, src_known is true and
13666 * umax_val is equal to umin_val.
13668 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13669 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13671 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13673 /* blow away the dst_reg umin_value/umax_value and rely on
13674 * dst_reg var_off to refine the result.
13676 dst_reg->u32_min_value = 0;
13677 dst_reg->u32_max_value = U32_MAX;
13679 __mark_reg64_unbounded(dst_reg);
13680 __update_reg32_bounds(dst_reg);
13683 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13684 struct bpf_reg_state *src_reg)
13686 u64 umin_val = src_reg->umin_value;
13688 /* Upon reaching here, src_known is true and umax_val is equal
13691 dst_reg->smin_value >>= umin_val;
13692 dst_reg->smax_value >>= umin_val;
13694 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13696 /* blow away the dst_reg umin_value/umax_value and rely on
13697 * dst_reg var_off to refine the result.
13699 dst_reg->umin_value = 0;
13700 dst_reg->umax_value = U64_MAX;
13702 /* Its not easy to operate on alu32 bounds here because it depends
13703 * on bits being shifted in from upper 32-bits. Take easy way out
13704 * and mark unbounded so we can recalculate later from tnum.
13706 __mark_reg32_unbounded(dst_reg);
13707 __update_reg_bounds(dst_reg);
13710 /* WARNING: This function does calculations on 64-bit values, but the actual
13711 * execution may occur on 32-bit values. Therefore, things like bitshifts
13712 * need extra checks in the 32-bit case.
13714 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13715 struct bpf_insn *insn,
13716 struct bpf_reg_state *dst_reg,
13717 struct bpf_reg_state src_reg)
13719 struct bpf_reg_state *regs = cur_regs(env);
13720 u8 opcode = BPF_OP(insn->code);
13722 s64 smin_val, smax_val;
13723 u64 umin_val, umax_val;
13724 s32 s32_min_val, s32_max_val;
13725 u32 u32_min_val, u32_max_val;
13726 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13727 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13730 smin_val = src_reg.smin_value;
13731 smax_val = src_reg.smax_value;
13732 umin_val = src_reg.umin_value;
13733 umax_val = src_reg.umax_value;
13735 s32_min_val = src_reg.s32_min_value;
13736 s32_max_val = src_reg.s32_max_value;
13737 u32_min_val = src_reg.u32_min_value;
13738 u32_max_val = src_reg.u32_max_value;
13741 src_known = tnum_subreg_is_const(src_reg.var_off);
13743 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13744 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13745 /* Taint dst register if offset had invalid bounds
13746 * derived from e.g. dead branches.
13748 __mark_reg_unknown(env, dst_reg);
13752 src_known = tnum_is_const(src_reg.var_off);
13754 (smin_val != smax_val || umin_val != umax_val)) ||
13755 smin_val > smax_val || umin_val > umax_val) {
13756 /* Taint dst register if offset had invalid bounds
13757 * derived from e.g. dead branches.
13759 __mark_reg_unknown(env, dst_reg);
13765 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13766 __mark_reg_unknown(env, dst_reg);
13770 if (sanitize_needed(opcode)) {
13771 ret = sanitize_val_alu(env, insn);
13773 return sanitize_err(env, insn, ret, NULL, NULL);
13776 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13777 * There are two classes of instructions: The first class we track both
13778 * alu32 and alu64 sign/unsigned bounds independently this provides the
13779 * greatest amount of precision when alu operations are mixed with jmp32
13780 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13781 * and BPF_OR. This is possible because these ops have fairly easy to
13782 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13783 * See alu32 verifier tests for examples. The second class of
13784 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13785 * with regards to tracking sign/unsigned bounds because the bits may
13786 * cross subreg boundaries in the alu64 case. When this happens we mark
13787 * the reg unbounded in the subreg bound space and use the resulting
13788 * tnum to calculate an approximation of the sign/unsigned bounds.
13792 scalar32_min_max_add(dst_reg, &src_reg);
13793 scalar_min_max_add(dst_reg, &src_reg);
13794 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13797 scalar32_min_max_sub(dst_reg, &src_reg);
13798 scalar_min_max_sub(dst_reg, &src_reg);
13799 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13802 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13803 scalar32_min_max_mul(dst_reg, &src_reg);
13804 scalar_min_max_mul(dst_reg, &src_reg);
13807 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13808 scalar32_min_max_and(dst_reg, &src_reg);
13809 scalar_min_max_and(dst_reg, &src_reg);
13812 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13813 scalar32_min_max_or(dst_reg, &src_reg);
13814 scalar_min_max_or(dst_reg, &src_reg);
13817 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13818 scalar32_min_max_xor(dst_reg, &src_reg);
13819 scalar_min_max_xor(dst_reg, &src_reg);
13822 if (umax_val >= insn_bitness) {
13823 /* Shifts greater than 31 or 63 are undefined.
13824 * This includes shifts by a negative number.
13826 mark_reg_unknown(env, regs, insn->dst_reg);
13830 scalar32_min_max_lsh(dst_reg, &src_reg);
13832 scalar_min_max_lsh(dst_reg, &src_reg);
13835 if (umax_val >= insn_bitness) {
13836 /* Shifts greater than 31 or 63 are undefined.
13837 * This includes shifts by a negative number.
13839 mark_reg_unknown(env, regs, insn->dst_reg);
13843 scalar32_min_max_rsh(dst_reg, &src_reg);
13845 scalar_min_max_rsh(dst_reg, &src_reg);
13848 if (umax_val >= insn_bitness) {
13849 /* Shifts greater than 31 or 63 are undefined.
13850 * This includes shifts by a negative number.
13852 mark_reg_unknown(env, regs, insn->dst_reg);
13856 scalar32_min_max_arsh(dst_reg, &src_reg);
13858 scalar_min_max_arsh(dst_reg, &src_reg);
13861 mark_reg_unknown(env, regs, insn->dst_reg);
13865 /* ALU32 ops are zero extended into 64bit register */
13867 zext_32_to_64(dst_reg);
13868 reg_bounds_sync(dst_reg);
13872 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13875 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13876 struct bpf_insn *insn)
13878 struct bpf_verifier_state *vstate = env->cur_state;
13879 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13880 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13881 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13882 u8 opcode = BPF_OP(insn->code);
13885 dst_reg = ®s[insn->dst_reg];
13888 if (dst_reg->type == PTR_TO_ARENA) {
13889 struct bpf_insn_aux_data *aux = cur_aux(env);
13891 if (BPF_CLASS(insn->code) == BPF_ALU64)
13893 * 32-bit operations zero upper bits automatically.
13894 * 64-bit operations need to be converted to 32.
13896 aux->needs_zext = true;
13898 /* Any arithmetic operations are allowed on arena pointers */
13902 if (dst_reg->type != SCALAR_VALUE)
13905 /* Make sure ID is cleared otherwise dst_reg min/max could be
13906 * incorrectly propagated into other registers by find_equal_scalars()
13909 if (BPF_SRC(insn->code) == BPF_X) {
13910 src_reg = ®s[insn->src_reg];
13911 if (src_reg->type != SCALAR_VALUE) {
13912 if (dst_reg->type != SCALAR_VALUE) {
13913 /* Combining two pointers by any ALU op yields
13914 * an arbitrary scalar. Disallow all math except
13915 * pointer subtraction
13917 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13918 mark_reg_unknown(env, regs, insn->dst_reg);
13921 verbose(env, "R%d pointer %s pointer prohibited\n",
13923 bpf_alu_string[opcode >> 4]);
13926 /* scalar += pointer
13927 * This is legal, but we have to reverse our
13928 * src/dest handling in computing the range
13930 err = mark_chain_precision(env, insn->dst_reg);
13933 return adjust_ptr_min_max_vals(env, insn,
13936 } else if (ptr_reg) {
13937 /* pointer += scalar */
13938 err = mark_chain_precision(env, insn->src_reg);
13941 return adjust_ptr_min_max_vals(env, insn,
13943 } else if (dst_reg->precise) {
13944 /* if dst_reg is precise, src_reg should be precise as well */
13945 err = mark_chain_precision(env, insn->src_reg);
13950 /* Pretend the src is a reg with a known value, since we only
13951 * need to be able to read from this state.
13953 off_reg.type = SCALAR_VALUE;
13954 __mark_reg_known(&off_reg, insn->imm);
13955 src_reg = &off_reg;
13956 if (ptr_reg) /* pointer += K */
13957 return adjust_ptr_min_max_vals(env, insn,
13961 /* Got here implies adding two SCALAR_VALUEs */
13962 if (WARN_ON_ONCE(ptr_reg)) {
13963 print_verifier_state(env, state, true);
13964 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13967 if (WARN_ON(!src_reg)) {
13968 print_verifier_state(env, state, true);
13969 verbose(env, "verifier internal error: no src_reg\n");
13972 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13975 /* check validity of 32-bit and 64-bit arithmetic operations */
13976 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13978 struct bpf_reg_state *regs = cur_regs(env);
13979 u8 opcode = BPF_OP(insn->code);
13982 if (opcode == BPF_END || opcode == BPF_NEG) {
13983 if (opcode == BPF_NEG) {
13984 if (BPF_SRC(insn->code) != BPF_K ||
13985 insn->src_reg != BPF_REG_0 ||
13986 insn->off != 0 || insn->imm != 0) {
13987 verbose(env, "BPF_NEG uses reserved fields\n");
13991 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13992 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13993 (BPF_CLASS(insn->code) == BPF_ALU64 &&
13994 BPF_SRC(insn->code) != BPF_TO_LE)) {
13995 verbose(env, "BPF_END uses reserved fields\n");
14000 /* check src operand */
14001 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14005 if (is_pointer_value(env, insn->dst_reg)) {
14006 verbose(env, "R%d pointer arithmetic prohibited\n",
14011 /* check dest operand */
14012 err = check_reg_arg(env, insn->dst_reg, DST_OP);
14016 } else if (opcode == BPF_MOV) {
14018 if (BPF_SRC(insn->code) == BPF_X) {
14019 if (BPF_CLASS(insn->code) == BPF_ALU) {
14020 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
14022 verbose(env, "BPF_MOV uses reserved fields\n");
14025 } else if (insn->off == BPF_ADDR_SPACE_CAST) {
14026 if (insn->imm != 1 && insn->imm != 1u << 16) {
14027 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
14030 if (!env->prog->aux->arena) {
14031 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
14035 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
14036 insn->off != 32) || insn->imm) {
14037 verbose(env, "BPF_MOV uses reserved fields\n");
14042 /* check src operand */
14043 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14047 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
14048 verbose(env, "BPF_MOV uses reserved fields\n");
14053 /* check dest operand, mark as required later */
14054 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14058 if (BPF_SRC(insn->code) == BPF_X) {
14059 struct bpf_reg_state *src_reg = regs + insn->src_reg;
14060 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
14062 if (BPF_CLASS(insn->code) == BPF_ALU64) {
14064 /* off == BPF_ADDR_SPACE_CAST */
14065 mark_reg_unknown(env, regs, insn->dst_reg);
14066 if (insn->imm == 1) { /* cast from as(1) to as(0) */
14067 dst_reg->type = PTR_TO_ARENA;
14068 /* PTR_TO_ARENA is 32-bit */
14069 dst_reg->subreg_def = env->insn_idx + 1;
14071 } else if (insn->off == 0) {
14073 * copy register state to dest reg
14075 assign_scalar_id_before_mov(env, src_reg);
14076 copy_register_state(dst_reg, src_reg);
14077 dst_reg->live |= REG_LIVE_WRITTEN;
14078 dst_reg->subreg_def = DEF_NOT_SUBREG;
14080 /* case: R1 = (s8, s16 s32)R2 */
14081 if (is_pointer_value(env, insn->src_reg)) {
14083 "R%d sign-extension part of pointer\n",
14086 } else if (src_reg->type == SCALAR_VALUE) {
14089 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14091 assign_scalar_id_before_mov(env, src_reg);
14092 copy_register_state(dst_reg, src_reg);
14095 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
14096 dst_reg->live |= REG_LIVE_WRITTEN;
14097 dst_reg->subreg_def = DEF_NOT_SUBREG;
14099 mark_reg_unknown(env, regs, insn->dst_reg);
14103 /* R1 = (u32) R2 */
14104 if (is_pointer_value(env, insn->src_reg)) {
14106 "R%d partial copy of pointer\n",
14109 } else if (src_reg->type == SCALAR_VALUE) {
14110 if (insn->off == 0) {
14111 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
14113 if (is_src_reg_u32)
14114 assign_scalar_id_before_mov(env, src_reg);
14115 copy_register_state(dst_reg, src_reg);
14116 /* Make sure ID is cleared if src_reg is not in u32
14117 * range otherwise dst_reg min/max could be incorrectly
14118 * propagated into src_reg by find_equal_scalars()
14120 if (!is_src_reg_u32)
14122 dst_reg->live |= REG_LIVE_WRITTEN;
14123 dst_reg->subreg_def = env->insn_idx + 1;
14125 /* case: W1 = (s8, s16)W2 */
14126 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14129 assign_scalar_id_before_mov(env, src_reg);
14130 copy_register_state(dst_reg, src_reg);
14133 dst_reg->live |= REG_LIVE_WRITTEN;
14134 dst_reg->subreg_def = env->insn_idx + 1;
14135 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
14138 mark_reg_unknown(env, regs,
14141 zext_32_to_64(dst_reg);
14142 reg_bounds_sync(dst_reg);
14146 * remember the value we stored into this reg
14148 /* clear any state __mark_reg_known doesn't set */
14149 mark_reg_unknown(env, regs, insn->dst_reg);
14150 regs[insn->dst_reg].type = SCALAR_VALUE;
14151 if (BPF_CLASS(insn->code) == BPF_ALU64) {
14152 __mark_reg_known(regs + insn->dst_reg,
14155 __mark_reg_known(regs + insn->dst_reg,
14160 } else if (opcode > BPF_END) {
14161 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
14164 } else { /* all other ALU ops: and, sub, xor, add, ... */
14166 if (BPF_SRC(insn->code) == BPF_X) {
14167 if (insn->imm != 0 || insn->off > 1 ||
14168 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14169 verbose(env, "BPF_ALU uses reserved fields\n");
14172 /* check src1 operand */
14173 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14177 if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
14178 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14179 verbose(env, "BPF_ALU uses reserved fields\n");
14184 /* check src2 operand */
14185 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14189 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
14190 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
14191 verbose(env, "div by zero\n");
14195 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
14196 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
14197 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
14199 if (insn->imm < 0 || insn->imm >= size) {
14200 verbose(env, "invalid shift %d\n", insn->imm);
14205 /* check dest operand */
14206 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14207 err = err ?: adjust_reg_min_max_vals(env, insn);
14212 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu");
14215 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
14216 struct bpf_reg_state *dst_reg,
14217 enum bpf_reg_type type,
14218 bool range_right_open)
14220 struct bpf_func_state *state;
14221 struct bpf_reg_state *reg;
14224 if (dst_reg->off < 0 ||
14225 (dst_reg->off == 0 && range_right_open))
14226 /* This doesn't give us any range */
14229 if (dst_reg->umax_value > MAX_PACKET_OFF ||
14230 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
14231 /* Risk of overflow. For instance, ptr + (1<<63) may be less
14232 * than pkt_end, but that's because it's also less than pkt.
14236 new_range = dst_reg->off;
14237 if (range_right_open)
14240 /* Examples for register markings:
14242 * pkt_data in dst register:
14246 * if (r2 > pkt_end) goto <handle exception>
14251 * if (r2 < pkt_end) goto <access okay>
14252 * <handle exception>
14255 * r2 == dst_reg, pkt_end == src_reg
14256 * r2=pkt(id=n,off=8,r=0)
14257 * r3=pkt(id=n,off=0,r=0)
14259 * pkt_data in src register:
14263 * if (pkt_end >= r2) goto <access okay>
14264 * <handle exception>
14268 * if (pkt_end <= r2) goto <handle exception>
14272 * pkt_end == dst_reg, r2 == src_reg
14273 * r2=pkt(id=n,off=8,r=0)
14274 * r3=pkt(id=n,off=0,r=0)
14276 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14277 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14278 * and [r3, r3 + 8-1) respectively is safe to access depending on
14282 /* If our ids match, then we must have the same max_value. And we
14283 * don't care about the other reg's fixed offset, since if it's too big
14284 * the range won't allow anything.
14285 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14287 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14288 if (reg->type == type && reg->id == dst_reg->id)
14289 /* keep the maximum range already checked */
14290 reg->range = max(reg->range, new_range);
14295 * <reg1> <op> <reg2>, currently assuming reg2 is a constant
14297 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14298 u8 opcode, bool is_jmp32)
14300 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
14301 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
14302 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
14303 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
14304 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
14305 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
14306 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
14307 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
14308 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
14309 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
14313 /* constants, umin/umax and smin/smax checks would be
14314 * redundant in this case because they all should match
14316 if (tnum_is_const(t1) && tnum_is_const(t2))
14317 return t1.value == t2.value;
14318 /* non-overlapping ranges */
14319 if (umin1 > umax2 || umax1 < umin2)
14321 if (smin1 > smax2 || smax1 < smin2)
14324 /* if 64-bit ranges are inconclusive, see if we can
14325 * utilize 32-bit subrange knowledge to eliminate
14326 * branches that can't be taken a priori
14328 if (reg1->u32_min_value > reg2->u32_max_value ||
14329 reg1->u32_max_value < reg2->u32_min_value)
14331 if (reg1->s32_min_value > reg2->s32_max_value ||
14332 reg1->s32_max_value < reg2->s32_min_value)
14337 /* constants, umin/umax and smin/smax checks would be
14338 * redundant in this case because they all should match
14340 if (tnum_is_const(t1) && tnum_is_const(t2))
14341 return t1.value != t2.value;
14342 /* non-overlapping ranges */
14343 if (umin1 > umax2 || umax1 < umin2)
14345 if (smin1 > smax2 || smax1 < smin2)
14348 /* if 64-bit ranges are inconclusive, see if we can
14349 * utilize 32-bit subrange knowledge to eliminate
14350 * branches that can't be taken a priori
14352 if (reg1->u32_min_value > reg2->u32_max_value ||
14353 reg1->u32_max_value < reg2->u32_min_value)
14355 if (reg1->s32_min_value > reg2->s32_max_value ||
14356 reg1->s32_max_value < reg2->s32_min_value)
14361 if (!is_reg_const(reg2, is_jmp32)) {
14365 if (!is_reg_const(reg2, is_jmp32))
14367 if ((~t1.mask & t1.value) & t2.value)
14369 if (!((t1.mask | t1.value) & t2.value))
14375 else if (umax1 <= umin2)
14381 else if (smax1 <= smin2)
14387 else if (umin1 >= umax2)
14393 else if (smin1 >= smax2)
14397 if (umin1 >= umax2)
14399 else if (umax1 < umin2)
14403 if (smin1 >= smax2)
14405 else if (smax1 < smin2)
14409 if (umax1 <= umin2)
14411 else if (umin1 > umax2)
14415 if (smax1 <= smin2)
14417 else if (smin1 > smax2)
14425 static int flip_opcode(u32 opcode)
14427 /* How can we transform "a <op> b" into "b <op> a"? */
14428 static const u8 opcode_flip[16] = {
14429 /* these stay the same */
14430 [BPF_JEQ >> 4] = BPF_JEQ,
14431 [BPF_JNE >> 4] = BPF_JNE,
14432 [BPF_JSET >> 4] = BPF_JSET,
14433 /* these swap "lesser" and "greater" (L and G in the opcodes) */
14434 [BPF_JGE >> 4] = BPF_JLE,
14435 [BPF_JGT >> 4] = BPF_JLT,
14436 [BPF_JLE >> 4] = BPF_JGE,
14437 [BPF_JLT >> 4] = BPF_JGT,
14438 [BPF_JSGE >> 4] = BPF_JSLE,
14439 [BPF_JSGT >> 4] = BPF_JSLT,
14440 [BPF_JSLE >> 4] = BPF_JSGE,
14441 [BPF_JSLT >> 4] = BPF_JSGT
14443 return opcode_flip[opcode >> 4];
14446 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14447 struct bpf_reg_state *src_reg,
14450 struct bpf_reg_state *pkt;
14452 if (src_reg->type == PTR_TO_PACKET_END) {
14454 } else if (dst_reg->type == PTR_TO_PACKET_END) {
14456 opcode = flip_opcode(opcode);
14461 if (pkt->range >= 0)
14466 /* pkt <= pkt_end */
14469 /* pkt > pkt_end */
14470 if (pkt->range == BEYOND_PKT_END)
14471 /* pkt has at last one extra byte beyond pkt_end */
14472 return opcode == BPF_JGT;
14475 /* pkt < pkt_end */
14478 /* pkt >= pkt_end */
14479 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14480 return opcode == BPF_JGE;
14486 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
14488 * 1 - branch will be taken and "goto target" will be executed
14489 * 0 - branch will not be taken and fall-through to next insn
14490 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
14493 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14494 u8 opcode, bool is_jmp32)
14496 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
14497 return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
14499 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
14502 /* arrange that reg2 is a scalar, and reg1 is a pointer */
14503 if (!is_reg_const(reg2, is_jmp32)) {
14504 opcode = flip_opcode(opcode);
14507 /* and ensure that reg2 is a constant */
14508 if (!is_reg_const(reg2, is_jmp32))
14511 if (!reg_not_null(reg1))
14514 /* If pointer is valid tests against zero will fail so we can
14515 * use this to direct branch taken.
14517 val = reg_const_value(reg2, is_jmp32);
14531 /* now deal with two scalars, but not necessarily constants */
14532 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
14535 /* Opcode that corresponds to a *false* branch condition.
14536 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
14538 static u8 rev_opcode(u8 opcode)
14541 case BPF_JEQ: return BPF_JNE;
14542 case BPF_JNE: return BPF_JEQ;
14543 /* JSET doesn't have it's reverse opcode in BPF, so add
14544 * BPF_X flag to denote the reverse of that operation
14546 case BPF_JSET: return BPF_JSET | BPF_X;
14547 case BPF_JSET | BPF_X: return BPF_JSET;
14548 case BPF_JGE: return BPF_JLT;
14549 case BPF_JGT: return BPF_JLE;
14550 case BPF_JLE: return BPF_JGT;
14551 case BPF_JLT: return BPF_JGE;
14552 case BPF_JSGE: return BPF_JSLT;
14553 case BPF_JSGT: return BPF_JSLE;
14554 case BPF_JSLE: return BPF_JSGT;
14555 case BPF_JSLT: return BPF_JSGE;
14560 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
14561 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14562 u8 opcode, bool is_jmp32)
14571 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14572 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14573 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14574 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14575 reg2->u32_min_value = reg1->u32_min_value;
14576 reg2->u32_max_value = reg1->u32_max_value;
14577 reg2->s32_min_value = reg1->s32_min_value;
14578 reg2->s32_max_value = reg1->s32_max_value;
14580 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
14581 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14582 reg2->var_off = tnum_with_subreg(reg2->var_off, t);
14584 reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
14585 reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14586 reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
14587 reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14588 reg2->umin_value = reg1->umin_value;
14589 reg2->umax_value = reg1->umax_value;
14590 reg2->smin_value = reg1->smin_value;
14591 reg2->smax_value = reg1->smax_value;
14593 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
14594 reg2->var_off = reg1->var_off;
14598 if (!is_reg_const(reg2, is_jmp32))
14600 if (!is_reg_const(reg2, is_jmp32))
14603 /* try to recompute the bound of reg1 if reg2 is a const and
14604 * is exactly the edge of reg1.
14606 val = reg_const_value(reg2, is_jmp32);
14608 /* u32_min_value is not equal to 0xffffffff at this point,
14609 * because otherwise u32_max_value is 0xffffffff as well,
14610 * in such a case both reg1 and reg2 would be constants,
14611 * jump would be predicted and reg_set_min_max() won't
14614 * Same reasoning works for all {u,s}{min,max}{32,64} cases
14617 if (reg1->u32_min_value == (u32)val)
14618 reg1->u32_min_value++;
14619 if (reg1->u32_max_value == (u32)val)
14620 reg1->u32_max_value--;
14621 if (reg1->s32_min_value == (s32)val)
14622 reg1->s32_min_value++;
14623 if (reg1->s32_max_value == (s32)val)
14624 reg1->s32_max_value--;
14626 if (reg1->umin_value == (u64)val)
14627 reg1->umin_value++;
14628 if (reg1->umax_value == (u64)val)
14629 reg1->umax_value--;
14630 if (reg1->smin_value == (s64)val)
14631 reg1->smin_value++;
14632 if (reg1->smax_value == (s64)val)
14633 reg1->smax_value--;
14637 if (!is_reg_const(reg2, is_jmp32))
14639 if (!is_reg_const(reg2, is_jmp32))
14641 val = reg_const_value(reg2, is_jmp32);
14642 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
14643 * requires single bit to learn something useful. E.g., if we
14644 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
14645 * are actually set? We can learn something definite only if
14646 * it's a single-bit value to begin with.
14648 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
14649 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
14650 * bit 1 is set, which we can readily use in adjustments.
14652 if (!is_power_of_2(val))
14655 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
14656 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14658 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
14661 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
14662 if (!is_reg_const(reg2, is_jmp32))
14664 if (!is_reg_const(reg2, is_jmp32))
14666 val = reg_const_value(reg2, is_jmp32);
14668 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
14669 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14671 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
14676 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14677 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14679 reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14680 reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
14685 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
14686 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
14688 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
14689 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
14694 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14695 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14697 reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14698 reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
14703 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
14704 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
14706 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
14707 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
14714 /* just reuse LE/LT logic above */
14715 opcode = flip_opcode(opcode);
14723 /* Adjusts the register min/max values in the case that the dst_reg and
14724 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
14725 * check, in which case we havea fake SCALAR_VALUE representing insn->imm).
14726 * Technically we can do similar adjustments for pointers to the same object,
14727 * but we don't support that right now.
14729 static int reg_set_min_max(struct bpf_verifier_env *env,
14730 struct bpf_reg_state *true_reg1,
14731 struct bpf_reg_state *true_reg2,
14732 struct bpf_reg_state *false_reg1,
14733 struct bpf_reg_state *false_reg2,
14734 u8 opcode, bool is_jmp32)
14738 /* If either register is a pointer, we can't learn anything about its
14739 * variable offset from the compare (unless they were a pointer into
14740 * the same object, but we don't bother with that).
14742 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
14745 /* fallthrough (FALSE) branch */
14746 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
14747 reg_bounds_sync(false_reg1);
14748 reg_bounds_sync(false_reg2);
14750 /* jump (TRUE) branch */
14751 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
14752 reg_bounds_sync(true_reg1);
14753 reg_bounds_sync(true_reg2);
14755 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
14756 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
14757 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
14758 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
14762 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14763 struct bpf_reg_state *reg, u32 id,
14766 if (type_may_be_null(reg->type) && reg->id == id &&
14767 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14768 /* Old offset (both fixed and variable parts) should have been
14769 * known-zero, because we don't allow pointer arithmetic on
14770 * pointers that might be NULL. If we see this happening, don't
14771 * convert the register.
14773 * But in some cases, some helpers that return local kptrs
14774 * advance offset for the returned pointer. In those cases, it
14775 * is fine to expect to see reg->off.
14777 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14779 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14780 WARN_ON_ONCE(reg->off))
14784 reg->type = SCALAR_VALUE;
14785 /* We don't need id and ref_obj_id from this point
14786 * onwards anymore, thus we should better reset it,
14787 * so that state pruning has chances to take effect.
14790 reg->ref_obj_id = 0;
14795 mark_ptr_not_null_reg(reg);
14797 if (!reg_may_point_to_spin_lock(reg)) {
14798 /* For not-NULL ptr, reg->ref_obj_id will be reset
14799 * in release_reference().
14801 * reg->id is still used by spin_lock ptr. Other
14802 * than spin_lock ptr type, reg->id can be reset.
14809 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14810 * be folded together at some point.
14812 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14815 struct bpf_func_state *state = vstate->frame[vstate->curframe];
14816 struct bpf_reg_state *regs = state->regs, *reg;
14817 u32 ref_obj_id = regs[regno].ref_obj_id;
14818 u32 id = regs[regno].id;
14820 if (ref_obj_id && ref_obj_id == id && is_null)
14821 /* regs[regno] is in the " == NULL" branch.
14822 * No one could have freed the reference state before
14823 * doing the NULL check.
14825 WARN_ON_ONCE(release_reference_state(state, id));
14827 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14828 mark_ptr_or_null_reg(state, reg, id, is_null);
14832 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14833 struct bpf_reg_state *dst_reg,
14834 struct bpf_reg_state *src_reg,
14835 struct bpf_verifier_state *this_branch,
14836 struct bpf_verifier_state *other_branch)
14838 if (BPF_SRC(insn->code) != BPF_X)
14841 /* Pointers are always 64-bit. */
14842 if (BPF_CLASS(insn->code) == BPF_JMP32)
14845 switch (BPF_OP(insn->code)) {
14847 if ((dst_reg->type == PTR_TO_PACKET &&
14848 src_reg->type == PTR_TO_PACKET_END) ||
14849 (dst_reg->type == PTR_TO_PACKET_META &&
14850 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14851 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14852 find_good_pkt_pointers(this_branch, dst_reg,
14853 dst_reg->type, false);
14854 mark_pkt_end(other_branch, insn->dst_reg, true);
14855 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14856 src_reg->type == PTR_TO_PACKET) ||
14857 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14858 src_reg->type == PTR_TO_PACKET_META)) {
14859 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
14860 find_good_pkt_pointers(other_branch, src_reg,
14861 src_reg->type, true);
14862 mark_pkt_end(this_branch, insn->src_reg, false);
14868 if ((dst_reg->type == PTR_TO_PACKET &&
14869 src_reg->type == PTR_TO_PACKET_END) ||
14870 (dst_reg->type == PTR_TO_PACKET_META &&
14871 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14872 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14873 find_good_pkt_pointers(other_branch, dst_reg,
14874 dst_reg->type, true);
14875 mark_pkt_end(this_branch, insn->dst_reg, false);
14876 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14877 src_reg->type == PTR_TO_PACKET) ||
14878 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14879 src_reg->type == PTR_TO_PACKET_META)) {
14880 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
14881 find_good_pkt_pointers(this_branch, src_reg,
14882 src_reg->type, false);
14883 mark_pkt_end(other_branch, insn->src_reg, true);
14889 if ((dst_reg->type == PTR_TO_PACKET &&
14890 src_reg->type == PTR_TO_PACKET_END) ||
14891 (dst_reg->type == PTR_TO_PACKET_META &&
14892 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14893 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14894 find_good_pkt_pointers(this_branch, dst_reg,
14895 dst_reg->type, true);
14896 mark_pkt_end(other_branch, insn->dst_reg, false);
14897 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14898 src_reg->type == PTR_TO_PACKET) ||
14899 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14900 src_reg->type == PTR_TO_PACKET_META)) {
14901 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14902 find_good_pkt_pointers(other_branch, src_reg,
14903 src_reg->type, false);
14904 mark_pkt_end(this_branch, insn->src_reg, true);
14910 if ((dst_reg->type == PTR_TO_PACKET &&
14911 src_reg->type == PTR_TO_PACKET_END) ||
14912 (dst_reg->type == PTR_TO_PACKET_META &&
14913 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14914 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14915 find_good_pkt_pointers(other_branch, dst_reg,
14916 dst_reg->type, false);
14917 mark_pkt_end(this_branch, insn->dst_reg, true);
14918 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14919 src_reg->type == PTR_TO_PACKET) ||
14920 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14921 src_reg->type == PTR_TO_PACKET_META)) {
14922 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14923 find_good_pkt_pointers(this_branch, src_reg,
14924 src_reg->type, true);
14925 mark_pkt_end(other_branch, insn->src_reg, false);
14937 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14938 struct bpf_reg_state *known_reg)
14940 struct bpf_func_state *state;
14941 struct bpf_reg_state *reg;
14943 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14944 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14945 copy_register_state(reg, known_reg);
14949 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14950 struct bpf_insn *insn, int *insn_idx)
14952 struct bpf_verifier_state *this_branch = env->cur_state;
14953 struct bpf_verifier_state *other_branch;
14954 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14955 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14956 struct bpf_reg_state *eq_branch_regs;
14957 struct bpf_reg_state fake_reg = {};
14958 u8 opcode = BPF_OP(insn->code);
14963 /* Only conditional jumps are expected to reach here. */
14964 if (opcode == BPF_JA || opcode > BPF_JCOND) {
14965 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14969 if (opcode == BPF_JCOND) {
14970 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
14971 int idx = *insn_idx;
14973 if (insn->code != (BPF_JMP | BPF_JCOND) ||
14974 insn->src_reg != BPF_MAY_GOTO ||
14975 insn->dst_reg || insn->imm || insn->off == 0) {
14976 verbose(env, "invalid may_goto off %d imm %d\n",
14977 insn->off, insn->imm);
14980 prev_st = find_prev_entry(env, cur_st->parent, idx);
14982 /* branch out 'fallthrough' insn as a new state to explore */
14983 queued_st = push_stack(env, idx + 1, idx, false);
14987 queued_st->may_goto_depth++;
14989 widen_imprecise_scalars(env, prev_st, queued_st);
14990 *insn_idx += insn->off;
14994 /* check src2 operand */
14995 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14999 dst_reg = ®s[insn->dst_reg];
15000 if (BPF_SRC(insn->code) == BPF_X) {
15001 if (insn->imm != 0) {
15002 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15006 /* check src1 operand */
15007 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15011 src_reg = ®s[insn->src_reg];
15012 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
15013 is_pointer_value(env, insn->src_reg)) {
15014 verbose(env, "R%d pointer comparison prohibited\n",
15019 if (insn->src_reg != BPF_REG_0) {
15020 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15023 src_reg = &fake_reg;
15024 src_reg->type = SCALAR_VALUE;
15025 __mark_reg_known(src_reg, insn->imm);
15028 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
15029 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
15031 /* If we get here with a dst_reg pointer type it is because
15032 * above is_branch_taken() special cased the 0 comparison.
15034 if (!__is_pointer_value(false, dst_reg))
15035 err = mark_chain_precision(env, insn->dst_reg);
15036 if (BPF_SRC(insn->code) == BPF_X && !err &&
15037 !__is_pointer_value(false, src_reg))
15038 err = mark_chain_precision(env, insn->src_reg);
15044 /* Only follow the goto, ignore fall-through. If needed, push
15045 * the fall-through branch for simulation under speculative
15048 if (!env->bypass_spec_v1 &&
15049 !sanitize_speculative_path(env, insn, *insn_idx + 1,
15052 if (env->log.level & BPF_LOG_LEVEL)
15053 print_insn_state(env, this_branch->frame[this_branch->curframe]);
15054 *insn_idx += insn->off;
15056 } else if (pred == 0) {
15057 /* Only follow the fall-through branch, since that's where the
15058 * program will go. If needed, push the goto branch for
15059 * simulation under speculative execution.
15061 if (!env->bypass_spec_v1 &&
15062 !sanitize_speculative_path(env, insn,
15063 *insn_idx + insn->off + 1,
15066 if (env->log.level & BPF_LOG_LEVEL)
15067 print_insn_state(env, this_branch->frame[this_branch->curframe]);
15071 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
15075 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
15077 if (BPF_SRC(insn->code) == BPF_X) {
15078 err = reg_set_min_max(env,
15079 &other_branch_regs[insn->dst_reg],
15080 &other_branch_regs[insn->src_reg],
15081 dst_reg, src_reg, opcode, is_jmp32);
15082 } else /* BPF_SRC(insn->code) == BPF_K */ {
15083 err = reg_set_min_max(env,
15084 &other_branch_regs[insn->dst_reg],
15085 src_reg /* fake one */,
15086 dst_reg, src_reg /* same fake one */,
15092 if (BPF_SRC(insn->code) == BPF_X &&
15093 src_reg->type == SCALAR_VALUE && src_reg->id &&
15094 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
15095 find_equal_scalars(this_branch, src_reg);
15096 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
15098 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
15099 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
15100 find_equal_scalars(this_branch, dst_reg);
15101 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
15104 /* if one pointer register is compared to another pointer
15105 * register check if PTR_MAYBE_NULL could be lifted.
15106 * E.g. register A - maybe null
15107 * register B - not null
15108 * for JNE A, B, ... - A is not null in the false branch;
15109 * for JEQ A, B, ... - A is not null in the true branch.
15111 * Since PTR_TO_BTF_ID points to a kernel struct that does
15112 * not need to be null checked by the BPF program, i.e.,
15113 * could be null even without PTR_MAYBE_NULL marking, so
15114 * only propagate nullness when neither reg is that type.
15116 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
15117 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
15118 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
15119 base_type(src_reg->type) != PTR_TO_BTF_ID &&
15120 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
15121 eq_branch_regs = NULL;
15124 eq_branch_regs = other_branch_regs;
15127 eq_branch_regs = regs;
15133 if (eq_branch_regs) {
15134 if (type_may_be_null(src_reg->type))
15135 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
15137 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
15141 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
15142 * NOTE: these optimizations below are related with pointer comparison
15143 * which will never be JMP32.
15145 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
15146 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
15147 type_may_be_null(dst_reg->type)) {
15148 /* Mark all identical registers in each branch as either
15149 * safe or unknown depending R == 0 or R != 0 conditional.
15151 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
15152 opcode == BPF_JNE);
15153 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
15154 opcode == BPF_JEQ);
15155 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
15156 this_branch, other_branch) &&
15157 is_pointer_value(env, insn->dst_reg)) {
15158 verbose(env, "R%d pointer comparison prohibited\n",
15162 if (env->log.level & BPF_LOG_LEVEL)
15163 print_insn_state(env, this_branch->frame[this_branch->curframe]);
15167 /* verify BPF_LD_IMM64 instruction */
15168 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
15170 struct bpf_insn_aux_data *aux = cur_aux(env);
15171 struct bpf_reg_state *regs = cur_regs(env);
15172 struct bpf_reg_state *dst_reg;
15173 struct bpf_map *map;
15176 if (BPF_SIZE(insn->code) != BPF_DW) {
15177 verbose(env, "invalid BPF_LD_IMM insn\n");
15180 if (insn->off != 0) {
15181 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
15185 err = check_reg_arg(env, insn->dst_reg, DST_OP);
15189 dst_reg = ®s[insn->dst_reg];
15190 if (insn->src_reg == 0) {
15191 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
15193 dst_reg->type = SCALAR_VALUE;
15194 __mark_reg_known(®s[insn->dst_reg], imm);
15198 /* All special src_reg cases are listed below. From this point onwards
15199 * we either succeed and assign a corresponding dst_reg->type after
15200 * zeroing the offset, or fail and reject the program.
15202 mark_reg_known_zero(env, regs, insn->dst_reg);
15204 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
15205 dst_reg->type = aux->btf_var.reg_type;
15206 switch (base_type(dst_reg->type)) {
15208 dst_reg->mem_size = aux->btf_var.mem_size;
15210 case PTR_TO_BTF_ID:
15211 dst_reg->btf = aux->btf_var.btf;
15212 dst_reg->btf_id = aux->btf_var.btf_id;
15215 verbose(env, "bpf verifier is misconfigured\n");
15221 if (insn->src_reg == BPF_PSEUDO_FUNC) {
15222 struct bpf_prog_aux *aux = env->prog->aux;
15223 u32 subprogno = find_subprog(env,
15224 env->insn_idx + insn->imm + 1);
15226 if (!aux->func_info) {
15227 verbose(env, "missing btf func_info\n");
15230 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
15231 verbose(env, "callback function not static\n");
15235 dst_reg->type = PTR_TO_FUNC;
15236 dst_reg->subprogno = subprogno;
15240 map = env->used_maps[aux->map_index];
15241 dst_reg->map_ptr = map;
15243 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15244 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15245 if (map->map_type == BPF_MAP_TYPE_ARENA) {
15246 __mark_reg_unknown(env, dst_reg);
15249 dst_reg->type = PTR_TO_MAP_VALUE;
15250 dst_reg->off = aux->map_off;
15251 WARN_ON_ONCE(map->max_entries != 1);
15252 /* We want reg->id to be same (0) as map_value is not distinct */
15253 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15254 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15255 dst_reg->type = CONST_PTR_TO_MAP;
15257 verbose(env, "bpf verifier is misconfigured\n");
15264 static bool may_access_skb(enum bpf_prog_type type)
15267 case BPF_PROG_TYPE_SOCKET_FILTER:
15268 case BPF_PROG_TYPE_SCHED_CLS:
15269 case BPF_PROG_TYPE_SCHED_ACT:
15276 /* verify safety of LD_ABS|LD_IND instructions:
15277 * - they can only appear in the programs where ctx == skb
15278 * - since they are wrappers of function calls, they scratch R1-R5 registers,
15279 * preserve R6-R9, and store return value into R0
15282 * ctx == skb == R6 == CTX
15285 * SRC == any register
15286 * IMM == 32-bit immediate
15289 * R0 - 8/16/32-bit skb data converted to cpu endianness
15291 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15293 struct bpf_reg_state *regs = cur_regs(env);
15294 static const int ctx_reg = BPF_REG_6;
15295 u8 mode = BPF_MODE(insn->code);
15298 if (!may_access_skb(resolve_prog_type(env->prog))) {
15299 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15303 if (!env->ops->gen_ld_abs) {
15304 verbose(env, "bpf verifier is misconfigured\n");
15308 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15309 BPF_SIZE(insn->code) == BPF_DW ||
15310 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15311 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
15315 /* check whether implicit source operand (register R6) is readable */
15316 err = check_reg_arg(env, ctx_reg, SRC_OP);
15320 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15321 * gen_ld_abs() may terminate the program at runtime, leading to
15324 err = check_reference_leak(env, false);
15326 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15330 if (env->cur_state->active_lock.ptr) {
15331 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15335 if (env->cur_state->active_rcu_lock) {
15336 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15340 if (regs[ctx_reg].type != PTR_TO_CTX) {
15342 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
15346 if (mode == BPF_IND) {
15347 /* check explicit source operand */
15348 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15353 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
15357 /* reset caller saved regs to unreadable */
15358 for (i = 0; i < CALLER_SAVED_REGS; i++) {
15359 mark_reg_not_init(env, regs, caller_saved[i]);
15360 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15363 /* mark destination R0 register as readable, since it contains
15364 * the value fetched from the packet.
15365 * Already marked as written above.
15367 mark_reg_unknown(env, regs, BPF_REG_0);
15368 /* ld_abs load up to 32-bit skb data. */
15369 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
15373 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
15375 const char *exit_ctx = "At program exit";
15376 struct tnum enforce_attach_type_range = tnum_unknown;
15377 const struct bpf_prog *prog = env->prog;
15378 struct bpf_reg_state *reg;
15379 struct bpf_retval_range range = retval_range(0, 1);
15380 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15382 struct bpf_func_state *frame = env->cur_state->frame[0];
15383 const bool is_subprog = frame->subprogno;
15385 /* LSM and struct_ops func-ptr's return type could be "void" */
15386 if (!is_subprog || frame->in_exception_callback_fn) {
15387 switch (prog_type) {
15388 case BPF_PROG_TYPE_LSM:
15389 if (prog->expected_attach_type == BPF_LSM_CGROUP)
15390 /* See below, can be 0 or 0-1 depending on hook. */
15393 case BPF_PROG_TYPE_STRUCT_OPS:
15394 if (!prog->aux->attach_func_proto->type)
15402 /* eBPF calling convention is such that R0 is used
15403 * to return the value from eBPF program.
15404 * Make sure that it's readable at this time
15405 * of bpf_exit, which means that program wrote
15406 * something into it earlier
15408 err = check_reg_arg(env, regno, SRC_OP);
15412 if (is_pointer_value(env, regno)) {
15413 verbose(env, "R%d leaks addr as return value\n", regno);
15417 reg = cur_regs(env) + regno;
15419 if (frame->in_async_callback_fn) {
15420 /* enforce return zero from async callbacks like timer */
15421 exit_ctx = "At async callback return";
15422 range = retval_range(0, 0);
15423 goto enforce_retval;
15426 if (is_subprog && !frame->in_exception_callback_fn) {
15427 if (reg->type != SCALAR_VALUE) {
15428 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15429 regno, reg_type_str(env, reg->type));
15435 switch (prog_type) {
15436 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15437 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15438 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15439 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15440 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15441 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15442 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15443 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15444 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15445 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15446 range = retval_range(1, 1);
15447 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15448 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15449 range = retval_range(0, 3);
15451 case BPF_PROG_TYPE_CGROUP_SKB:
15452 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15453 range = retval_range(0, 3);
15454 enforce_attach_type_range = tnum_range(2, 3);
15457 case BPF_PROG_TYPE_CGROUP_SOCK:
15458 case BPF_PROG_TYPE_SOCK_OPS:
15459 case BPF_PROG_TYPE_CGROUP_DEVICE:
15460 case BPF_PROG_TYPE_CGROUP_SYSCTL:
15461 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15463 case BPF_PROG_TYPE_RAW_TRACEPOINT:
15464 if (!env->prog->aux->attach_btf_id)
15466 range = retval_range(0, 0);
15468 case BPF_PROG_TYPE_TRACING:
15469 switch (env->prog->expected_attach_type) {
15470 case BPF_TRACE_FENTRY:
15471 case BPF_TRACE_FEXIT:
15472 range = retval_range(0, 0);
15474 case BPF_TRACE_RAW_TP:
15475 case BPF_MODIFY_RETURN:
15477 case BPF_TRACE_ITER:
15483 case BPF_PROG_TYPE_SK_LOOKUP:
15484 range = retval_range(SK_DROP, SK_PASS);
15487 case BPF_PROG_TYPE_LSM:
15488 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15489 /* Regular BPF_PROG_TYPE_LSM programs can return
15494 if (!env->prog->aux->attach_func_proto->type) {
15495 /* Make sure programs that attach to void
15496 * hooks don't try to modify return value.
15498 range = retval_range(1, 1);
15502 case BPF_PROG_TYPE_NETFILTER:
15503 range = retval_range(NF_DROP, NF_ACCEPT);
15505 case BPF_PROG_TYPE_EXT:
15506 /* freplace program can return anything as its return value
15507 * depends on the to-be-replaced kernel func or bpf program.
15514 if (reg->type != SCALAR_VALUE) {
15515 verbose(env, "%s the register R%d is not a known value (%s)\n",
15516 exit_ctx, regno, reg_type_str(env, reg->type));
15520 err = mark_chain_precision(env, regno);
15524 if (!retval_range_within(range, reg)) {
15525 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
15527 prog->expected_attach_type == BPF_LSM_CGROUP &&
15528 prog_type == BPF_PROG_TYPE_LSM &&
15529 !prog->aux->attach_func_proto->type)
15530 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15534 if (!tnum_is_unknown(enforce_attach_type_range) &&
15535 tnum_in(enforce_attach_type_range, reg->var_off))
15536 env->prog->enforce_expected_attach_type = 1;
15540 /* non-recursive DFS pseudo code
15541 * 1 procedure DFS-iterative(G,v):
15542 * 2 label v as discovered
15543 * 3 let S be a stack
15545 * 5 while S is not empty
15547 * 7 if t is what we're looking for:
15549 * 9 for all edges e in G.adjacentEdges(t) do
15550 * 10 if edge e is already labelled
15551 * 11 continue with the next edge
15552 * 12 w <- G.adjacentVertex(t,e)
15553 * 13 if vertex w is not discovered and not explored
15554 * 14 label e as tree-edge
15555 * 15 label w as discovered
15558 * 18 else if vertex w is discovered
15559 * 19 label e as back-edge
15561 * 21 // vertex w is explored
15562 * 22 label e as forward- or cross-edge
15563 * 23 label t as explored
15567 * 0x10 - discovered
15568 * 0x11 - discovered and fall-through edge labelled
15569 * 0x12 - discovered and fall-through and branch edges labelled
15580 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15582 env->insn_aux_data[idx].prune_point = true;
15585 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15587 return env->insn_aux_data[insn_idx].prune_point;
15590 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15592 env->insn_aux_data[idx].force_checkpoint = true;
15595 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15597 return env->insn_aux_data[insn_idx].force_checkpoint;
15600 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15602 env->insn_aux_data[idx].calls_callback = true;
15605 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15607 return env->insn_aux_data[insn_idx].calls_callback;
15611 DONE_EXPLORING = 0,
15612 KEEP_EXPLORING = 1,
15615 /* t, w, e - match pseudo-code above:
15616 * t - index of current instruction
15617 * w - next instruction
15620 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15622 int *insn_stack = env->cfg.insn_stack;
15623 int *insn_state = env->cfg.insn_state;
15625 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15626 return DONE_EXPLORING;
15628 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15629 return DONE_EXPLORING;
15631 if (w < 0 || w >= env->prog->len) {
15632 verbose_linfo(env, t, "%d: ", t);
15633 verbose(env, "jump out of range from insn %d to %d\n", t, w);
15638 /* mark branch target for state pruning */
15639 mark_prune_point(env, w);
15640 mark_jmp_point(env, w);
15643 if (insn_state[w] == 0) {
15645 insn_state[t] = DISCOVERED | e;
15646 insn_state[w] = DISCOVERED;
15647 if (env->cfg.cur_stack >= env->prog->len)
15649 insn_stack[env->cfg.cur_stack++] = w;
15650 return KEEP_EXPLORING;
15651 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15652 if (env->bpf_capable)
15653 return DONE_EXPLORING;
15654 verbose_linfo(env, t, "%d: ", t);
15655 verbose_linfo(env, w, "%d: ", w);
15656 verbose(env, "back-edge from insn %d to %d\n", t, w);
15658 } else if (insn_state[w] == EXPLORED) {
15659 /* forward- or cross-edge */
15660 insn_state[t] = DISCOVERED | e;
15662 verbose(env, "insn state internal bug\n");
15665 return DONE_EXPLORING;
15668 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15669 struct bpf_verifier_env *env,
15674 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15675 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15679 mark_prune_point(env, t + insn_sz);
15680 /* when we exit from subprog, we need to record non-linear history */
15681 mark_jmp_point(env, t + insn_sz);
15683 if (visit_callee) {
15684 mark_prune_point(env, t);
15685 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15690 /* Visits the instruction at index t and returns one of the following:
15691 * < 0 - an error occurred
15692 * DONE_EXPLORING - the instruction was fully explored
15693 * KEEP_EXPLORING - there is still work to be done before it is fully explored
15695 static int visit_insn(int t, struct bpf_verifier_env *env)
15697 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15698 int ret, off, insn_sz;
15700 if (bpf_pseudo_func(insn))
15701 return visit_func_call_insn(t, insns, env, true);
15703 /* All non-branch instructions have a single fall-through edge. */
15704 if (BPF_CLASS(insn->code) != BPF_JMP &&
15705 BPF_CLASS(insn->code) != BPF_JMP32) {
15706 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15707 return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15710 switch (BPF_OP(insn->code)) {
15712 return DONE_EXPLORING;
15715 if (is_async_callback_calling_insn(insn))
15716 /* Mark this call insn as a prune point to trigger
15717 * is_state_visited() check before call itself is
15718 * processed by __check_func_call(). Otherwise new
15719 * async state will be pushed for further exploration.
15721 mark_prune_point(env, t);
15722 /* For functions that invoke callbacks it is not known how many times
15723 * callback would be called. Verifier models callback calling functions
15724 * by repeatedly visiting callback bodies and returning to origin call
15726 * In order to stop such iteration verifier needs to identify when a
15727 * state identical some state from a previous iteration is reached.
15728 * Check below forces creation of checkpoint before callback calling
15729 * instruction to allow search for such identical states.
15731 if (is_sync_callback_calling_insn(insn)) {
15732 mark_calls_callback(env, t);
15733 mark_force_checkpoint(env, t);
15734 mark_prune_point(env, t);
15735 mark_jmp_point(env, t);
15737 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15738 struct bpf_kfunc_call_arg_meta meta;
15740 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15741 if (ret == 0 && is_iter_next_kfunc(&meta)) {
15742 mark_prune_point(env, t);
15743 /* Checking and saving state checkpoints at iter_next() call
15744 * is crucial for fast convergence of open-coded iterator loop
15745 * logic, so we need to force it. If we don't do that,
15746 * is_state_visited() might skip saving a checkpoint, causing
15747 * unnecessarily long sequence of not checkpointed
15748 * instructions and jumps, leading to exhaustion of jump
15749 * history buffer, and potentially other undesired outcomes.
15750 * It is expected that with correct open-coded iterators
15751 * convergence will happen quickly, so we don't run a risk of
15752 * exhausting memory.
15754 mark_force_checkpoint(env, t);
15757 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15760 if (BPF_SRC(insn->code) != BPF_K)
15763 if (BPF_CLASS(insn->code) == BPF_JMP)
15768 /* unconditional jump with single edge */
15769 ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15773 mark_prune_point(env, t + off + 1);
15774 mark_jmp_point(env, t + off + 1);
15779 /* conditional jump with two edges */
15780 mark_prune_point(env, t);
15781 if (is_may_goto_insn(insn))
15782 mark_force_checkpoint(env, t);
15784 ret = push_insn(t, t + 1, FALLTHROUGH, env);
15788 return push_insn(t, t + insn->off + 1, BRANCH, env);
15792 /* non-recursive depth-first-search to detect loops in BPF program
15793 * loop == back-edge in directed graph
15795 static int check_cfg(struct bpf_verifier_env *env)
15797 int insn_cnt = env->prog->len;
15798 int *insn_stack, *insn_state;
15799 int ex_insn_beg, i, ret = 0;
15800 bool ex_done = false;
15802 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15806 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15808 kvfree(insn_state);
15812 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15813 insn_stack[0] = 0; /* 0 is the first instruction */
15814 env->cfg.cur_stack = 1;
15817 while (env->cfg.cur_stack > 0) {
15818 int t = insn_stack[env->cfg.cur_stack - 1];
15820 ret = visit_insn(t, env);
15822 case DONE_EXPLORING:
15823 insn_state[t] = EXPLORED;
15824 env->cfg.cur_stack--;
15826 case KEEP_EXPLORING:
15830 verbose(env, "visit_insn internal bug\n");
15837 if (env->cfg.cur_stack < 0) {
15838 verbose(env, "pop stack internal bug\n");
15843 if (env->exception_callback_subprog && !ex_done) {
15844 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
15846 insn_state[ex_insn_beg] = DISCOVERED;
15847 insn_stack[0] = ex_insn_beg;
15848 env->cfg.cur_stack = 1;
15853 for (i = 0; i < insn_cnt; i++) {
15854 struct bpf_insn *insn = &env->prog->insnsi[i];
15856 if (insn_state[i] != EXPLORED) {
15857 verbose(env, "unreachable insn %d\n", i);
15861 if (bpf_is_ldimm64(insn)) {
15862 if (insn_state[i + 1] != 0) {
15863 verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15867 i++; /* skip second half of ldimm64 */
15870 ret = 0; /* cfg looks good */
15873 kvfree(insn_state);
15874 kvfree(insn_stack);
15875 env->cfg.insn_state = env->cfg.insn_stack = NULL;
15879 static int check_abnormal_return(struct bpf_verifier_env *env)
15883 for (i = 1; i < env->subprog_cnt; i++) {
15884 if (env->subprog_info[i].has_ld_abs) {
15885 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15888 if (env->subprog_info[i].has_tail_call) {
15889 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15896 /* The minimum supported BTF func info size */
15897 #define MIN_BPF_FUNCINFO_SIZE 8
15898 #define MAX_FUNCINFO_REC_SIZE 252
15900 static int check_btf_func_early(struct bpf_verifier_env *env,
15901 const union bpf_attr *attr,
15904 u32 krec_size = sizeof(struct bpf_func_info);
15905 const struct btf_type *type, *func_proto;
15906 u32 i, nfuncs, urec_size, min_size;
15907 struct bpf_func_info *krecord;
15908 struct bpf_prog *prog;
15909 const struct btf *btf;
15910 u32 prev_offset = 0;
15914 nfuncs = attr->func_info_cnt;
15916 if (check_abnormal_return(env))
15921 urec_size = attr->func_info_rec_size;
15922 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15923 urec_size > MAX_FUNCINFO_REC_SIZE ||
15924 urec_size % sizeof(u32)) {
15925 verbose(env, "invalid func info rec size %u\n", urec_size);
15930 btf = prog->aux->btf;
15932 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15933 min_size = min_t(u32, krec_size, urec_size);
15935 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15939 for (i = 0; i < nfuncs; i++) {
15940 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15942 if (ret == -E2BIG) {
15943 verbose(env, "nonzero tailing record in func info");
15944 /* set the size kernel expects so loader can zero
15945 * out the rest of the record.
15947 if (copy_to_bpfptr_offset(uattr,
15948 offsetof(union bpf_attr, func_info_rec_size),
15949 &min_size, sizeof(min_size)))
15955 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15960 /* check insn_off */
15963 if (krecord[i].insn_off) {
15965 "nonzero insn_off %u for the first func info record",
15966 krecord[i].insn_off);
15969 } else if (krecord[i].insn_off <= prev_offset) {
15971 "same or smaller insn offset (%u) than previous func info record (%u)",
15972 krecord[i].insn_off, prev_offset);
15976 /* check type_id */
15977 type = btf_type_by_id(btf, krecord[i].type_id);
15978 if (!type || !btf_type_is_func(type)) {
15979 verbose(env, "invalid type id %d in func info",
15980 krecord[i].type_id);
15984 func_proto = btf_type_by_id(btf, type->type);
15985 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15986 /* btf_func_check() already verified it during BTF load */
15989 prev_offset = krecord[i].insn_off;
15990 bpfptr_add(&urecord, urec_size);
15993 prog->aux->func_info = krecord;
15994 prog->aux->func_info_cnt = nfuncs;
16002 static int check_btf_func(struct bpf_verifier_env *env,
16003 const union bpf_attr *attr,
16006 const struct btf_type *type, *func_proto, *ret_type;
16007 u32 i, nfuncs, urec_size;
16008 struct bpf_func_info *krecord;
16009 struct bpf_func_info_aux *info_aux = NULL;
16010 struct bpf_prog *prog;
16011 const struct btf *btf;
16013 bool scalar_return;
16016 nfuncs = attr->func_info_cnt;
16018 if (check_abnormal_return(env))
16022 if (nfuncs != env->subprog_cnt) {
16023 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
16027 urec_size = attr->func_info_rec_size;
16030 btf = prog->aux->btf;
16032 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
16034 krecord = prog->aux->func_info;
16035 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
16039 for (i = 0; i < nfuncs; i++) {
16040 /* check insn_off */
16043 if (env->subprog_info[i].start != krecord[i].insn_off) {
16044 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
16048 /* Already checked type_id */
16049 type = btf_type_by_id(btf, krecord[i].type_id);
16050 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
16051 /* Already checked func_proto */
16052 func_proto = btf_type_by_id(btf, type->type);
16054 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
16056 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
16057 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
16058 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
16061 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
16062 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
16066 bpfptr_add(&urecord, urec_size);
16069 prog->aux->func_info_aux = info_aux;
16077 static void adjust_btf_func(struct bpf_verifier_env *env)
16079 struct bpf_prog_aux *aux = env->prog->aux;
16082 if (!aux->func_info)
16085 /* func_info is not available for hidden subprogs */
16086 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
16087 aux->func_info[i].insn_off = env->subprog_info[i].start;
16090 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
16091 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
16093 static int check_btf_line(struct bpf_verifier_env *env,
16094 const union bpf_attr *attr,
16097 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
16098 struct bpf_subprog_info *sub;
16099 struct bpf_line_info *linfo;
16100 struct bpf_prog *prog;
16101 const struct btf *btf;
16105 nr_linfo = attr->line_info_cnt;
16108 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
16111 rec_size = attr->line_info_rec_size;
16112 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
16113 rec_size > MAX_LINEINFO_REC_SIZE ||
16114 rec_size & (sizeof(u32) - 1))
16117 /* Need to zero it in case the userspace may
16118 * pass in a smaller bpf_line_info object.
16120 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
16121 GFP_KERNEL | __GFP_NOWARN);
16126 btf = prog->aux->btf;
16129 sub = env->subprog_info;
16130 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
16131 expected_size = sizeof(struct bpf_line_info);
16132 ncopy = min_t(u32, expected_size, rec_size);
16133 for (i = 0; i < nr_linfo; i++) {
16134 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
16136 if (err == -E2BIG) {
16137 verbose(env, "nonzero tailing record in line_info");
16138 if (copy_to_bpfptr_offset(uattr,
16139 offsetof(union bpf_attr, line_info_rec_size),
16140 &expected_size, sizeof(expected_size)))
16146 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
16152 * Check insn_off to ensure
16153 * 1) strictly increasing AND
16154 * 2) bounded by prog->len
16156 * The linfo[0].insn_off == 0 check logically falls into
16157 * the later "missing bpf_line_info for func..." case
16158 * because the first linfo[0].insn_off must be the
16159 * first sub also and the first sub must have
16160 * subprog_info[0].start == 0.
16162 if ((i && linfo[i].insn_off <= prev_offset) ||
16163 linfo[i].insn_off >= prog->len) {
16164 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
16165 i, linfo[i].insn_off, prev_offset,
16171 if (!prog->insnsi[linfo[i].insn_off].code) {
16173 "Invalid insn code at line_info[%u].insn_off\n",
16179 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
16180 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
16181 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
16186 if (s != env->subprog_cnt) {
16187 if (linfo[i].insn_off == sub[s].start) {
16188 sub[s].linfo_idx = i;
16190 } else if (sub[s].start < linfo[i].insn_off) {
16191 verbose(env, "missing bpf_line_info for func#%u\n", s);
16197 prev_offset = linfo[i].insn_off;
16198 bpfptr_add(&ulinfo, rec_size);
16201 if (s != env->subprog_cnt) {
16202 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
16203 env->subprog_cnt - s, s);
16208 prog->aux->linfo = linfo;
16209 prog->aux->nr_linfo = nr_linfo;
16218 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
16219 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
16221 static int check_core_relo(struct bpf_verifier_env *env,
16222 const union bpf_attr *attr,
16225 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
16226 struct bpf_core_relo core_relo = {};
16227 struct bpf_prog *prog = env->prog;
16228 const struct btf *btf = prog->aux->btf;
16229 struct bpf_core_ctx ctx = {
16233 bpfptr_t u_core_relo;
16236 nr_core_relo = attr->core_relo_cnt;
16239 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
16242 rec_size = attr->core_relo_rec_size;
16243 if (rec_size < MIN_CORE_RELO_SIZE ||
16244 rec_size > MAX_CORE_RELO_SIZE ||
16245 rec_size % sizeof(u32))
16248 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
16249 expected_size = sizeof(struct bpf_core_relo);
16250 ncopy = min_t(u32, expected_size, rec_size);
16252 /* Unlike func_info and line_info, copy and apply each CO-RE
16253 * relocation record one at a time.
16255 for (i = 0; i < nr_core_relo; i++) {
16256 /* future proofing when sizeof(bpf_core_relo) changes */
16257 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
16259 if (err == -E2BIG) {
16260 verbose(env, "nonzero tailing record in core_relo");
16261 if (copy_to_bpfptr_offset(uattr,
16262 offsetof(union bpf_attr, core_relo_rec_size),
16263 &expected_size, sizeof(expected_size)))
16269 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16274 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16275 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16276 i, core_relo.insn_off, prog->len);
16281 err = bpf_core_apply(&ctx, &core_relo, i,
16282 &prog->insnsi[core_relo.insn_off / 8]);
16285 bpfptr_add(&u_core_relo, rec_size);
16290 static int check_btf_info_early(struct bpf_verifier_env *env,
16291 const union bpf_attr *attr,
16297 if (!attr->func_info_cnt && !attr->line_info_cnt) {
16298 if (check_abnormal_return(env))
16303 btf = btf_get_by_fd(attr->prog_btf_fd);
16305 return PTR_ERR(btf);
16306 if (btf_is_kernel(btf)) {
16310 env->prog->aux->btf = btf;
16312 err = check_btf_func_early(env, attr, uattr);
16318 static int check_btf_info(struct bpf_verifier_env *env,
16319 const union bpf_attr *attr,
16324 if (!attr->func_info_cnt && !attr->line_info_cnt) {
16325 if (check_abnormal_return(env))
16330 err = check_btf_func(env, attr, uattr);
16334 err = check_btf_line(env, attr, uattr);
16338 err = check_core_relo(env, attr, uattr);
16345 /* check %cur's range satisfies %old's */
16346 static bool range_within(const struct bpf_reg_state *old,
16347 const struct bpf_reg_state *cur)
16349 return old->umin_value <= cur->umin_value &&
16350 old->umax_value >= cur->umax_value &&
16351 old->smin_value <= cur->smin_value &&
16352 old->smax_value >= cur->smax_value &&
16353 old->u32_min_value <= cur->u32_min_value &&
16354 old->u32_max_value >= cur->u32_max_value &&
16355 old->s32_min_value <= cur->s32_min_value &&
16356 old->s32_max_value >= cur->s32_max_value;
16359 /* If in the old state two registers had the same id, then they need to have
16360 * the same id in the new state as well. But that id could be different from
16361 * the old state, so we need to track the mapping from old to new ids.
16362 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
16363 * regs with old id 5 must also have new id 9 for the new state to be safe. But
16364 * regs with a different old id could still have new id 9, we don't care about
16366 * So we look through our idmap to see if this old id has been seen before. If
16367 * so, we require the new id to match; otherwise, we add the id pair to the map.
16369 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16371 struct bpf_id_pair *map = idmap->map;
16374 /* either both IDs should be set or both should be zero */
16375 if (!!old_id != !!cur_id)
16378 if (old_id == 0) /* cur_id == 0 as well */
16381 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
16383 /* Reached an empty slot; haven't seen this id before */
16384 map[i].old = old_id;
16385 map[i].cur = cur_id;
16388 if (map[i].old == old_id)
16389 return map[i].cur == cur_id;
16390 if (map[i].cur == cur_id)
16393 /* We ran out of idmap slots, which should be impossible */
16398 /* Similar to check_ids(), but allocate a unique temporary ID
16399 * for 'old_id' or 'cur_id' of zero.
16400 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
16402 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16404 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
16405 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
16407 return check_ids(old_id, cur_id, idmap);
16410 static void clean_func_state(struct bpf_verifier_env *env,
16411 struct bpf_func_state *st)
16413 enum bpf_reg_liveness live;
16416 for (i = 0; i < BPF_REG_FP; i++) {
16417 live = st->regs[i].live;
16418 /* liveness must not touch this register anymore */
16419 st->regs[i].live |= REG_LIVE_DONE;
16420 if (!(live & REG_LIVE_READ))
16421 /* since the register is unused, clear its state
16422 * to make further comparison simpler
16424 __mark_reg_not_init(env, &st->regs[i]);
16427 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
16428 live = st->stack[i].spilled_ptr.live;
16429 /* liveness must not touch this stack slot anymore */
16430 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
16431 if (!(live & REG_LIVE_READ)) {
16432 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
16433 for (j = 0; j < BPF_REG_SIZE; j++)
16434 st->stack[i].slot_type[j] = STACK_INVALID;
16439 static void clean_verifier_state(struct bpf_verifier_env *env,
16440 struct bpf_verifier_state *st)
16444 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
16445 /* all regs in this state in all frames were already marked */
16448 for (i = 0; i <= st->curframe; i++)
16449 clean_func_state(env, st->frame[i]);
16452 /* the parentage chains form a tree.
16453 * the verifier states are added to state lists at given insn and
16454 * pushed into state stack for future exploration.
16455 * when the verifier reaches bpf_exit insn some of the verifer states
16456 * stored in the state lists have their final liveness state already,
16457 * but a lot of states will get revised from liveness point of view when
16458 * the verifier explores other branches.
16461 * 2: if r1 == 100 goto pc+1
16464 * when the verifier reaches exit insn the register r0 in the state list of
16465 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
16466 * of insn 2 and goes exploring further. At the insn 4 it will walk the
16467 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
16469 * Since the verifier pushes the branch states as it sees them while exploring
16470 * the program the condition of walking the branch instruction for the second
16471 * time means that all states below this branch were already explored and
16472 * their final liveness marks are already propagated.
16473 * Hence when the verifier completes the search of state list in is_state_visited()
16474 * we can call this clean_live_states() function to mark all liveness states
16475 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16476 * will not be used.
16477 * This function also clears the registers and stack for states that !READ
16478 * to simplify state merging.
16480 * Important note here that walking the same branch instruction in the callee
16481 * doesn't meant that the states are DONE. The verifier has to compare
16484 static void clean_live_states(struct bpf_verifier_env *env, int insn,
16485 struct bpf_verifier_state *cur)
16487 struct bpf_verifier_state_list *sl;
16489 sl = *explored_state(env, insn);
16491 if (sl->state.branches)
16493 if (sl->state.insn_idx != insn ||
16494 !same_callsites(&sl->state, cur))
16496 clean_verifier_state(env, &sl->state);
16502 static bool regs_exact(const struct bpf_reg_state *rold,
16503 const struct bpf_reg_state *rcur,
16504 struct bpf_idmap *idmap)
16506 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16507 check_ids(rold->id, rcur->id, idmap) &&
16508 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16517 /* Returns true if (rold safe implies rcur safe) */
16518 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
16519 struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
16520 enum exact_level exact)
16522 if (exact == EXACT)
16523 return regs_exact(rold, rcur, idmap);
16525 if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT)
16526 /* explored state didn't use this */
16528 if (rold->type == NOT_INIT) {
16529 if (exact == NOT_EXACT || rcur->type == NOT_INIT)
16530 /* explored state can't have used this */
16534 /* Enforce that register types have to match exactly, including their
16535 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16538 * One can make a point that using a pointer register as unbounded
16539 * SCALAR would be technically acceptable, but this could lead to
16540 * pointer leaks because scalars are allowed to leak while pointers
16541 * are not. We could make this safe in special cases if root is
16542 * calling us, but it's probably not worth the hassle.
16544 * Also, register types that are *not* MAYBE_NULL could technically be
16545 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16546 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16547 * to the same map).
16548 * However, if the old MAYBE_NULL register then got NULL checked,
16549 * doing so could have affected others with the same id, and we can't
16550 * check for that because we lost the id when we converted to
16551 * a non-MAYBE_NULL variant.
16552 * So, as a general rule we don't allow mixing MAYBE_NULL and
16553 * non-MAYBE_NULL registers as well.
16555 if (rold->type != rcur->type)
16558 switch (base_type(rold->type)) {
16560 if (env->explore_alu_limits) {
16561 /* explore_alu_limits disables tnum_in() and range_within()
16562 * logic and requires everything to be strict
16564 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16565 check_scalar_ids(rold->id, rcur->id, idmap);
16567 if (!rold->precise && exact == NOT_EXACT)
16569 /* Why check_ids() for scalar registers?
16571 * Consider the following BPF code:
16572 * 1: r6 = ... unbound scalar, ID=a ...
16573 * 2: r7 = ... unbound scalar, ID=b ...
16574 * 3: if (r6 > r7) goto +1
16576 * 5: if (r6 > X) goto ...
16577 * 6: ... memory operation using r7 ...
16579 * First verification path is [1-6]:
16580 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16581 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16582 * r7 <= X, because r6 and r7 share same id.
16583 * Next verification path is [1-4, 6].
16585 * Instruction (6) would be reached in two states:
16586 * I. r6{.id=b}, r7{.id=b} via path 1-6;
16587 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16589 * Use check_ids() to distinguish these states.
16591 * Also verify that new value satisfies old value range knowledge.
16593 return range_within(rold, rcur) &&
16594 tnum_in(rold->var_off, rcur->var_off) &&
16595 check_scalar_ids(rold->id, rcur->id, idmap);
16596 case PTR_TO_MAP_KEY:
16597 case PTR_TO_MAP_VALUE:
16600 case PTR_TO_TP_BUFFER:
16601 /* If the new min/max/var_off satisfy the old ones and
16602 * everything else matches, we are OK.
16604 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16605 range_within(rold, rcur) &&
16606 tnum_in(rold->var_off, rcur->var_off) &&
16607 check_ids(rold->id, rcur->id, idmap) &&
16608 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16609 case PTR_TO_PACKET_META:
16610 case PTR_TO_PACKET:
16611 /* We must have at least as much range as the old ptr
16612 * did, so that any accesses which were safe before are
16613 * still safe. This is true even if old range < old off,
16614 * since someone could have accessed through (ptr - k), or
16615 * even done ptr -= k in a register, to get a safe access.
16617 if (rold->range > rcur->range)
16619 /* If the offsets don't match, we can't trust our alignment;
16620 * nor can we be sure that we won't fall out of range.
16622 if (rold->off != rcur->off)
16624 /* id relations must be preserved */
16625 if (!check_ids(rold->id, rcur->id, idmap))
16627 /* new val must satisfy old val knowledge */
16628 return range_within(rold, rcur) &&
16629 tnum_in(rold->var_off, rcur->var_off);
16631 /* two stack pointers are equal only if they're pointing to
16632 * the same stack frame, since fp-8 in foo != fp-8 in bar
16634 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16638 return regs_exact(rold, rcur, idmap);
16642 static struct bpf_reg_state unbound_reg;
16644 static __init int unbound_reg_init(void)
16646 __mark_reg_unknown_imprecise(&unbound_reg);
16647 unbound_reg.live |= REG_LIVE_READ;
16650 late_initcall(unbound_reg_init);
16652 static bool is_stack_all_misc(struct bpf_verifier_env *env,
16653 struct bpf_stack_state *stack)
16657 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
16658 if ((stack->slot_type[i] == STACK_MISC) ||
16659 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
16667 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
16668 struct bpf_stack_state *stack)
16670 if (is_spilled_scalar_reg64(stack))
16671 return &stack->spilled_ptr;
16673 if (is_stack_all_misc(env, stack))
16674 return &unbound_reg;
16679 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16680 struct bpf_func_state *cur, struct bpf_idmap *idmap,
16681 enum exact_level exact)
16685 /* walk slots of the explored stack and ignore any additional
16686 * slots in the current stack, since explored(safe) state
16689 for (i = 0; i < old->allocated_stack; i++) {
16690 struct bpf_reg_state *old_reg, *cur_reg;
16692 spi = i / BPF_REG_SIZE;
16694 if (exact != NOT_EXACT &&
16695 old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16696 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16699 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)
16700 && exact == NOT_EXACT) {
16701 i += BPF_REG_SIZE - 1;
16702 /* explored state didn't use this */
16706 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16709 if (env->allow_uninit_stack &&
16710 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16713 /* explored stack has more populated slots than current stack
16714 * and these slots were used
16716 if (i >= cur->allocated_stack)
16719 /* 64-bit scalar spill vs all slots MISC and vice versa.
16720 * Load from all slots MISC produces unbound scalar.
16721 * Construct a fake register for such stack and call
16722 * regsafe() to ensure scalar ids are compared.
16724 old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
16725 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
16726 if (old_reg && cur_reg) {
16727 if (!regsafe(env, old_reg, cur_reg, idmap, exact))
16729 i += BPF_REG_SIZE - 1;
16733 /* if old state was safe with misc data in the stack
16734 * it will be safe with zero-initialized stack.
16735 * The opposite is not true
16737 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16738 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16740 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16741 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16742 /* Ex: old explored (safe) state has STACK_SPILL in
16743 * this stack slot, but current has STACK_MISC ->
16744 * this verifier states are not equivalent,
16745 * return false to continue verification of this path
16748 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16750 /* Both old and cur are having same slot_type */
16751 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16753 /* when explored and current stack slot are both storing
16754 * spilled registers, check that stored pointers types
16755 * are the same as well.
16756 * Ex: explored safe path could have stored
16757 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16758 * but current path has stored:
16759 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16760 * such verifier states are not equivalent.
16761 * return false to continue verification of this path
16763 if (!regsafe(env, &old->stack[spi].spilled_ptr,
16764 &cur->stack[spi].spilled_ptr, idmap, exact))
16768 old_reg = &old->stack[spi].spilled_ptr;
16769 cur_reg = &cur->stack[spi].spilled_ptr;
16770 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16771 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16772 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16776 old_reg = &old->stack[spi].spilled_ptr;
16777 cur_reg = &cur->stack[spi].spilled_ptr;
16778 /* iter.depth is not compared between states as it
16779 * doesn't matter for correctness and would otherwise
16780 * prevent convergence; we maintain it only to prevent
16781 * infinite loop check triggering, see
16782 * iter_active_depths_differ()
16784 if (old_reg->iter.btf != cur_reg->iter.btf ||
16785 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16786 old_reg->iter.state != cur_reg->iter.state ||
16787 /* ignore {old_reg,cur_reg}->iter.depth, see above */
16788 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16793 case STACK_INVALID:
16795 /* Ensure that new unhandled slot types return false by default */
16803 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16804 struct bpf_idmap *idmap)
16808 if (old->acquired_refs != cur->acquired_refs)
16811 for (i = 0; i < old->acquired_refs; i++) {
16812 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16819 /* compare two verifier states
16821 * all states stored in state_list are known to be valid, since
16822 * verifier reached 'bpf_exit' instruction through them
16824 * this function is called when verifier exploring different branches of
16825 * execution popped from the state stack. If it sees an old state that has
16826 * more strict register state and more strict stack state then this execution
16827 * branch doesn't need to be explored further, since verifier already
16828 * concluded that more strict state leads to valid finish.
16830 * Therefore two states are equivalent if register state is more conservative
16831 * and explored stack state is more conservative than the current one.
16834 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16835 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16837 * In other words if current stack state (one being explored) has more
16838 * valid slots than old one that already passed validation, it means
16839 * the verifier can stop exploring and conclude that current state is valid too
16841 * Similarly with registers. If explored state has register type as invalid
16842 * whereas register type in current state is meaningful, it means that
16843 * the current state will reach 'bpf_exit' instruction safely
16845 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16846 struct bpf_func_state *cur, enum exact_level exact)
16850 if (old->callback_depth > cur->callback_depth)
16853 for (i = 0; i < MAX_BPF_REG; i++)
16854 if (!regsafe(env, &old->regs[i], &cur->regs[i],
16855 &env->idmap_scratch, exact))
16858 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16861 if (!refsafe(old, cur, &env->idmap_scratch))
16867 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16869 env->idmap_scratch.tmp_id_gen = env->id_gen;
16870 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16873 static bool states_equal(struct bpf_verifier_env *env,
16874 struct bpf_verifier_state *old,
16875 struct bpf_verifier_state *cur,
16876 enum exact_level exact)
16880 if (old->curframe != cur->curframe)
16883 reset_idmap_scratch(env);
16885 /* Verification state from speculative execution simulation
16886 * must never prune a non-speculative execution one.
16888 if (old->speculative && !cur->speculative)
16891 if (old->active_lock.ptr != cur->active_lock.ptr)
16894 /* Old and cur active_lock's have to be either both present
16897 if (!!old->active_lock.id != !!cur->active_lock.id)
16900 if (old->active_lock.id &&
16901 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16904 if (old->active_rcu_lock != cur->active_rcu_lock)
16907 /* for states to be equal callsites have to be the same
16908 * and all frame states need to be equivalent
16910 for (i = 0; i <= old->curframe; i++) {
16911 if (old->frame[i]->callsite != cur->frame[i]->callsite)
16913 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16919 /* Return 0 if no propagation happened. Return negative error code if error
16920 * happened. Otherwise, return the propagated bit.
16922 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16923 struct bpf_reg_state *reg,
16924 struct bpf_reg_state *parent_reg)
16926 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16927 u8 flag = reg->live & REG_LIVE_READ;
16930 /* When comes here, read flags of PARENT_REG or REG could be any of
16931 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16932 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16934 if (parent_flag == REG_LIVE_READ64 ||
16935 /* Or if there is no read flag from REG. */
16937 /* Or if the read flag from REG is the same as PARENT_REG. */
16938 parent_flag == flag)
16941 err = mark_reg_read(env, reg, parent_reg, flag);
16948 /* A write screens off any subsequent reads; but write marks come from the
16949 * straight-line code between a state and its parent. When we arrive at an
16950 * equivalent state (jump target or such) we didn't arrive by the straight-line
16951 * code, so read marks in the state must propagate to the parent regardless
16952 * of the state's write marks. That's what 'parent == state->parent' comparison
16953 * in mark_reg_read() is for.
16955 static int propagate_liveness(struct bpf_verifier_env *env,
16956 const struct bpf_verifier_state *vstate,
16957 struct bpf_verifier_state *vparent)
16959 struct bpf_reg_state *state_reg, *parent_reg;
16960 struct bpf_func_state *state, *parent;
16961 int i, frame, err = 0;
16963 if (vparent->curframe != vstate->curframe) {
16964 WARN(1, "propagate_live: parent frame %d current frame %d\n",
16965 vparent->curframe, vstate->curframe);
16968 /* Propagate read liveness of registers... */
16969 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16970 for (frame = 0; frame <= vstate->curframe; frame++) {
16971 parent = vparent->frame[frame];
16972 state = vstate->frame[frame];
16973 parent_reg = parent->regs;
16974 state_reg = state->regs;
16975 /* We don't need to worry about FP liveness, it's read-only */
16976 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16977 err = propagate_liveness_reg(env, &state_reg[i],
16981 if (err == REG_LIVE_READ64)
16982 mark_insn_zext(env, &parent_reg[i]);
16985 /* Propagate stack slots. */
16986 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16987 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16988 parent_reg = &parent->stack[i].spilled_ptr;
16989 state_reg = &state->stack[i].spilled_ptr;
16990 err = propagate_liveness_reg(env, state_reg,
16999 /* find precise scalars in the previous equivalent state and
17000 * propagate them into the current state
17002 static int propagate_precision(struct bpf_verifier_env *env,
17003 const struct bpf_verifier_state *old)
17005 struct bpf_reg_state *state_reg;
17006 struct bpf_func_state *state;
17007 int i, err = 0, fr;
17010 for (fr = old->curframe; fr >= 0; fr--) {
17011 state = old->frame[fr];
17012 state_reg = state->regs;
17014 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
17015 if (state_reg->type != SCALAR_VALUE ||
17016 !state_reg->precise ||
17017 !(state_reg->live & REG_LIVE_READ))
17019 if (env->log.level & BPF_LOG_LEVEL2) {
17021 verbose(env, "frame %d: propagating r%d", fr, i);
17023 verbose(env, ",r%d", i);
17025 bt_set_frame_reg(&env->bt, fr, i);
17029 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17030 if (!is_spilled_reg(&state->stack[i]))
17032 state_reg = &state->stack[i].spilled_ptr;
17033 if (state_reg->type != SCALAR_VALUE ||
17034 !state_reg->precise ||
17035 !(state_reg->live & REG_LIVE_READ))
17037 if (env->log.level & BPF_LOG_LEVEL2) {
17039 verbose(env, "frame %d: propagating fp%d",
17040 fr, (-i - 1) * BPF_REG_SIZE);
17042 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
17044 bt_set_frame_slot(&env->bt, fr, i);
17048 verbose(env, "\n");
17051 err = mark_chain_precision_batch(env);
17058 static bool states_maybe_looping(struct bpf_verifier_state *old,
17059 struct bpf_verifier_state *cur)
17061 struct bpf_func_state *fold, *fcur;
17062 int i, fr = cur->curframe;
17064 if (old->curframe != fr)
17067 fold = old->frame[fr];
17068 fcur = cur->frame[fr];
17069 for (i = 0; i < MAX_BPF_REG; i++)
17070 if (memcmp(&fold->regs[i], &fcur->regs[i],
17071 offsetof(struct bpf_reg_state, parent)))
17076 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
17078 return env->insn_aux_data[insn_idx].is_iter_next;
17081 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
17082 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
17083 * states to match, which otherwise would look like an infinite loop. So while
17084 * iter_next() calls are taken care of, we still need to be careful and
17085 * prevent erroneous and too eager declaration of "ininite loop", when
17086 * iterators are involved.
17088 * Here's a situation in pseudo-BPF assembly form:
17090 * 0: again: ; set up iter_next() call args
17091 * 1: r1 = &it ; <CHECKPOINT HERE>
17092 * 2: call bpf_iter_num_next ; this is iter_next() call
17093 * 3: if r0 == 0 goto done
17094 * 4: ... something useful here ...
17095 * 5: goto again ; another iteration
17098 * 8: call bpf_iter_num_destroy ; clean up iter state
17101 * This is a typical loop. Let's assume that we have a prune point at 1:,
17102 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
17103 * again`, assuming other heuristics don't get in a way).
17105 * When we first time come to 1:, let's say we have some state X. We proceed
17106 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
17107 * Now we come back to validate that forked ACTIVE state. We proceed through
17108 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
17109 * are converging. But the problem is that we don't know that yet, as this
17110 * convergence has to happen at iter_next() call site only. So if nothing is
17111 * done, at 1: verifier will use bounded loop logic and declare infinite
17112 * looping (and would be *technically* correct, if not for iterator's
17113 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
17114 * don't want that. So what we do in process_iter_next_call() when we go on
17115 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
17116 * a different iteration. So when we suspect an infinite loop, we additionally
17117 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
17118 * pretend we are not looping and wait for next iter_next() call.
17120 * This only applies to ACTIVE state. In DRAINED state we don't expect to
17121 * loop, because that would actually mean infinite loop, as DRAINED state is
17122 * "sticky", and so we'll keep returning into the same instruction with the
17123 * same state (at least in one of possible code paths).
17125 * This approach allows to keep infinite loop heuristic even in the face of
17126 * active iterator. E.g., C snippet below is and will be detected as
17127 * inifintely looping:
17129 * struct bpf_iter_num it;
17132 * bpf_iter_num_new(&it, 0, 10);
17133 * while ((p = bpf_iter_num_next(&t))) {
17135 * while (x--) {} // <<-- infinite loop here
17139 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
17141 struct bpf_reg_state *slot, *cur_slot;
17142 struct bpf_func_state *state;
17145 for (fr = old->curframe; fr >= 0; fr--) {
17146 state = old->frame[fr];
17147 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17148 if (state->stack[i].slot_type[0] != STACK_ITER)
17151 slot = &state->stack[i].spilled_ptr;
17152 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
17155 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
17156 if (cur_slot->iter.depth != slot->iter.depth)
17163 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
17165 struct bpf_verifier_state_list *new_sl;
17166 struct bpf_verifier_state_list *sl, **pprev;
17167 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
17168 int i, j, n, err, states_cnt = 0;
17169 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
17170 bool add_new_state = force_new_state;
17173 /* bpf progs typically have pruning point every 4 instructions
17174 * http://vger.kernel.org/bpfconf2019.html#session-1
17175 * Do not add new state for future pruning if the verifier hasn't seen
17176 * at least 2 jumps and at least 8 instructions.
17177 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
17178 * In tests that amounts to up to 50% reduction into total verifier
17179 * memory consumption and 20% verifier time speedup.
17181 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
17182 env->insn_processed - env->prev_insn_processed >= 8)
17183 add_new_state = true;
17185 pprev = explored_state(env, insn_idx);
17188 clean_live_states(env, insn_idx, cur);
17192 if (sl->state.insn_idx != insn_idx)
17195 if (sl->state.branches) {
17196 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
17198 if (frame->in_async_callback_fn &&
17199 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
17200 /* Different async_entry_cnt means that the verifier is
17201 * processing another entry into async callback.
17202 * Seeing the same state is not an indication of infinite
17203 * loop or infinite recursion.
17204 * But finding the same state doesn't mean that it's safe
17205 * to stop processing the current state. The previous state
17206 * hasn't yet reached bpf_exit, since state.branches > 0.
17207 * Checking in_async_callback_fn alone is not enough either.
17208 * Since the verifier still needs to catch infinite loops
17209 * inside async callbacks.
17211 goto skip_inf_loop_check;
17213 /* BPF open-coded iterators loop detection is special.
17214 * states_maybe_looping() logic is too simplistic in detecting
17215 * states that *might* be equivalent, because it doesn't know
17216 * about ID remapping, so don't even perform it.
17217 * See process_iter_next_call() and iter_active_depths_differ()
17218 * for overview of the logic. When current and one of parent
17219 * states are detected as equivalent, it's a good thing: we prove
17220 * convergence and can stop simulating further iterations.
17221 * It's safe to assume that iterator loop will finish, taking into
17222 * account iter_next() contract of eventually returning
17223 * sticky NULL result.
17225 * Note, that states have to be compared exactly in this case because
17226 * read and precision marks might not be finalized inside the loop.
17227 * E.g. as in the program below:
17230 * 2. r6 = bpf_get_prandom_u32()
17231 * 3. while (bpf_iter_num_next(&fp[-8])) {
17232 * 4. if (r6 != 42) {
17234 * 6. r6 = bpf_get_prandom_u32()
17239 * 11. r8 = *(u64 *)(r0 + 0)
17240 * 12. r6 = bpf_get_prandom_u32()
17243 * Here verifier would first visit path 1-3, create a checkpoint at 3
17244 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
17245 * not have read or precision mark for r7 yet, thus inexact states
17246 * comparison would discard current state with r7=-32
17247 * => unsafe memory access at 11 would not be caught.
17249 if (is_iter_next_insn(env, insn_idx)) {
17250 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
17251 struct bpf_func_state *cur_frame;
17252 struct bpf_reg_state *iter_state, *iter_reg;
17255 cur_frame = cur->frame[cur->curframe];
17256 /* btf_check_iter_kfuncs() enforces that
17257 * iter state pointer is always the first arg
17259 iter_reg = &cur_frame->regs[BPF_REG_1];
17260 /* current state is valid due to states_equal(),
17261 * so we can assume valid iter and reg state,
17262 * no need for extra (re-)validations
17264 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
17265 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
17266 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
17267 update_loop_entry(cur, &sl->state);
17271 goto skip_inf_loop_check;
17273 if (is_may_goto_insn_at(env, insn_idx)) {
17274 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
17275 update_loop_entry(cur, &sl->state);
17278 goto skip_inf_loop_check;
17280 if (calls_callback(env, insn_idx)) {
17281 if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
17283 goto skip_inf_loop_check;
17285 /* attempt to detect infinite loop to avoid unnecessary doomed work */
17286 if (states_maybe_looping(&sl->state, cur) &&
17287 states_equal(env, &sl->state, cur, EXACT) &&
17288 !iter_active_depths_differ(&sl->state, cur) &&
17289 sl->state.may_goto_depth == cur->may_goto_depth &&
17290 sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
17291 verbose_linfo(env, insn_idx, "; ");
17292 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
17293 verbose(env, "cur state:");
17294 print_verifier_state(env, cur->frame[cur->curframe], true);
17295 verbose(env, "old state:");
17296 print_verifier_state(env, sl->state.frame[cur->curframe], true);
17299 /* if the verifier is processing a loop, avoid adding new state
17300 * too often, since different loop iterations have distinct
17301 * states and may not help future pruning.
17302 * This threshold shouldn't be too low to make sure that
17303 * a loop with large bound will be rejected quickly.
17304 * The most abusive loop will be:
17306 * if r1 < 1000000 goto pc-2
17307 * 1M insn_procssed limit / 100 == 10k peak states.
17308 * This threshold shouldn't be too high either, since states
17309 * at the end of the loop are likely to be useful in pruning.
17311 skip_inf_loop_check:
17312 if (!force_new_state &&
17313 env->jmps_processed - env->prev_jmps_processed < 20 &&
17314 env->insn_processed - env->prev_insn_processed < 100)
17315 add_new_state = false;
17318 /* If sl->state is a part of a loop and this loop's entry is a part of
17319 * current verification path then states have to be compared exactly.
17320 * 'force_exact' is needed to catch the following case:
17322 * initial Here state 'succ' was processed first,
17323 * | it was eventually tracked to produce a
17324 * V state identical to 'hdr'.
17325 * .---------> hdr All branches from 'succ' had been explored
17326 * | | and thus 'succ' has its .branches == 0.
17328 * | .------... Suppose states 'cur' and 'succ' correspond
17329 * | | | to the same instruction + callsites.
17330 * | V V In such case it is necessary to check
17331 * | ... ... if 'succ' and 'cur' are states_equal().
17332 * | | | If 'succ' and 'cur' are a part of the
17333 * | V V same loop exact flag has to be set.
17334 * | succ <- cur To check if that is the case, verify
17335 * | | if loop entry of 'succ' is in current
17341 * Additional details are in the comment before get_loop_entry().
17343 loop_entry = get_loop_entry(&sl->state);
17344 force_exact = loop_entry && loop_entry->branches > 0;
17345 if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) {
17347 update_loop_entry(cur, loop_entry);
17350 /* reached equivalent register/stack state,
17351 * prune the search.
17352 * Registers read by the continuation are read by us.
17353 * If we have any write marks in env->cur_state, they
17354 * will prevent corresponding reads in the continuation
17355 * from reaching our parent (an explored_state). Our
17356 * own state will get the read marks recorded, but
17357 * they'll be immediately forgotten as we're pruning
17358 * this state and will pop a new one.
17360 err = propagate_liveness(env, &sl->state, cur);
17362 /* if previous state reached the exit with precision and
17363 * current state is equivalent to it (except precsion marks)
17364 * the precision needs to be propagated back in
17365 * the current state.
17367 if (is_jmp_point(env, env->insn_idx))
17368 err = err ? : push_jmp_history(env, cur, 0);
17369 err = err ? : propagate_precision(env, &sl->state);
17375 /* when new state is not going to be added do not increase miss count.
17376 * Otherwise several loop iterations will remove the state
17377 * recorded earlier. The goal of these heuristics is to have
17378 * states from some iterations of the loop (some in the beginning
17379 * and some at the end) to help pruning.
17383 /* heuristic to determine whether this state is beneficial
17384 * to keep checking from state equivalence point of view.
17385 * Higher numbers increase max_states_per_insn and verification time,
17386 * but do not meaningfully decrease insn_processed.
17387 * 'n' controls how many times state could miss before eviction.
17388 * Use bigger 'n' for checkpoints because evicting checkpoint states
17389 * too early would hinder iterator convergence.
17391 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
17392 if (sl->miss_cnt > sl->hit_cnt * n + n) {
17393 /* the state is unlikely to be useful. Remove it to
17394 * speed up verification
17397 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
17398 !sl->state.used_as_loop_entry) {
17399 u32 br = sl->state.branches;
17402 "BUG live_done but branches_to_explore %d\n",
17404 free_verifier_state(&sl->state, false);
17406 env->peak_states--;
17408 /* cannot free this state, since parentage chain may
17409 * walk it later. Add it for free_list instead to
17410 * be freed at the end of verification
17412 sl->next = env->free_list;
17413 env->free_list = sl;
17423 if (env->max_states_per_insn < states_cnt)
17424 env->max_states_per_insn = states_cnt;
17426 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
17429 if (!add_new_state)
17432 /* There were no equivalent states, remember the current one.
17433 * Technically the current state is not proven to be safe yet,
17434 * but it will either reach outer most bpf_exit (which means it's safe)
17435 * or it will be rejected. When there are no loops the verifier won't be
17436 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
17437 * again on the way to bpf_exit.
17438 * When looping the sl->state.branches will be > 0 and this state
17439 * will not be considered for equivalence until branches == 0.
17441 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
17444 env->total_states++;
17445 env->peak_states++;
17446 env->prev_jmps_processed = env->jmps_processed;
17447 env->prev_insn_processed = env->insn_processed;
17449 /* forget precise markings we inherited, see __mark_chain_precision */
17450 if (env->bpf_capable)
17451 mark_all_scalars_imprecise(env, cur);
17453 /* add new state to the head of linked list */
17454 new = &new_sl->state;
17455 err = copy_verifier_state(new, cur);
17457 free_verifier_state(new, false);
17461 new->insn_idx = insn_idx;
17462 WARN_ONCE(new->branches != 1,
17463 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
17466 cur->first_insn_idx = insn_idx;
17467 cur->dfs_depth = new->dfs_depth + 1;
17468 clear_jmp_history(cur);
17469 new_sl->next = *explored_state(env, insn_idx);
17470 *explored_state(env, insn_idx) = new_sl;
17471 /* connect new state to parentage chain. Current frame needs all
17472 * registers connected. Only r6 - r9 of the callers are alive (pushed
17473 * to the stack implicitly by JITs) so in callers' frames connect just
17474 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
17475 * the state of the call instruction (with WRITTEN set), and r0 comes
17476 * from callee with its full parentage chain, anyway.
17478 /* clear write marks in current state: the writes we did are not writes
17479 * our child did, so they don't screen off its reads from us.
17480 * (There are no read marks in current state, because reads always mark
17481 * their parent and current state never has children yet. Only
17482 * explored_states can get read marks.)
17484 for (j = 0; j <= cur->curframe; j++) {
17485 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
17486 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
17487 for (i = 0; i < BPF_REG_FP; i++)
17488 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
17491 /* all stack frames are accessible from callee, clear them all */
17492 for (j = 0; j <= cur->curframe; j++) {
17493 struct bpf_func_state *frame = cur->frame[j];
17494 struct bpf_func_state *newframe = new->frame[j];
17496 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
17497 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
17498 frame->stack[i].spilled_ptr.parent =
17499 &newframe->stack[i].spilled_ptr;
17505 /* Return true if it's OK to have the same insn return a different type. */
17506 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17508 switch (base_type(type)) {
17510 case PTR_TO_SOCKET:
17511 case PTR_TO_SOCK_COMMON:
17512 case PTR_TO_TCP_SOCK:
17513 case PTR_TO_XDP_SOCK:
17514 case PTR_TO_BTF_ID:
17522 /* If an instruction was previously used with particular pointer types, then we
17523 * need to be careful to avoid cases such as the below, where it may be ok
17524 * for one branch accessing the pointer, but not ok for the other branch:
17529 * R1 = some_other_valid_ptr;
17532 * R2 = *(u32 *)(R1 + 0);
17534 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17536 return src != prev && (!reg_type_mismatch_ok(src) ||
17537 !reg_type_mismatch_ok(prev));
17540 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17541 bool allow_trust_missmatch)
17543 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17545 if (*prev_type == NOT_INIT) {
17546 /* Saw a valid insn
17547 * dst_reg = *(u32 *)(src_reg + off)
17548 * save type to validate intersecting paths
17551 } else if (reg_type_mismatch(type, *prev_type)) {
17552 /* Abuser program is trying to use the same insn
17553 * dst_reg = *(u32*) (src_reg + off)
17554 * with different pointer types:
17555 * src_reg == ctx in one branch and
17556 * src_reg == stack|map in some other branch.
17559 if (allow_trust_missmatch &&
17560 base_type(type) == PTR_TO_BTF_ID &&
17561 base_type(*prev_type) == PTR_TO_BTF_ID) {
17563 * Have to support a use case when one path through
17564 * the program yields TRUSTED pointer while another
17565 * is UNTRUSTED. Fallback to UNTRUSTED to generate
17566 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17568 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17570 verbose(env, "same insn cannot be used with different pointers\n");
17578 static int do_check(struct bpf_verifier_env *env)
17580 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17581 struct bpf_verifier_state *state = env->cur_state;
17582 struct bpf_insn *insns = env->prog->insnsi;
17583 struct bpf_reg_state *regs;
17584 int insn_cnt = env->prog->len;
17585 bool do_print_state = false;
17586 int prev_insn_idx = -1;
17589 bool exception_exit = false;
17590 struct bpf_insn *insn;
17594 /* reset current history entry on each new instruction */
17595 env->cur_hist_ent = NULL;
17597 env->prev_insn_idx = prev_insn_idx;
17598 if (env->insn_idx >= insn_cnt) {
17599 verbose(env, "invalid insn idx %d insn_cnt %d\n",
17600 env->insn_idx, insn_cnt);
17604 insn = &insns[env->insn_idx];
17605 class = BPF_CLASS(insn->code);
17607 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17609 "BPF program is too large. Processed %d insn\n",
17610 env->insn_processed);
17614 state->last_insn_idx = env->prev_insn_idx;
17616 if (is_prune_point(env, env->insn_idx)) {
17617 err = is_state_visited(env, env->insn_idx);
17621 /* found equivalent state, can prune the search */
17622 if (env->log.level & BPF_LOG_LEVEL) {
17623 if (do_print_state)
17624 verbose(env, "\nfrom %d to %d%s: safe\n",
17625 env->prev_insn_idx, env->insn_idx,
17626 env->cur_state->speculative ?
17627 " (speculative execution)" : "");
17629 verbose(env, "%d: safe\n", env->insn_idx);
17631 goto process_bpf_exit;
17635 if (is_jmp_point(env, env->insn_idx)) {
17636 err = push_jmp_history(env, state, 0);
17641 if (signal_pending(current))
17644 if (need_resched())
17647 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17648 verbose(env, "\nfrom %d to %d%s:",
17649 env->prev_insn_idx, env->insn_idx,
17650 env->cur_state->speculative ?
17651 " (speculative execution)" : "");
17652 print_verifier_state(env, state->frame[state->curframe], true);
17653 do_print_state = false;
17656 if (env->log.level & BPF_LOG_LEVEL) {
17657 const struct bpf_insn_cbs cbs = {
17658 .cb_call = disasm_kfunc_name,
17659 .cb_print = verbose,
17660 .private_data = env,
17663 if (verifier_state_scratched(env))
17664 print_insn_state(env, state->frame[state->curframe]);
17666 verbose_linfo(env, env->insn_idx, "; ");
17667 env->prev_log_pos = env->log.end_pos;
17668 verbose(env, "%d: ", env->insn_idx);
17669 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17670 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17671 env->prev_log_pos = env->log.end_pos;
17674 if (bpf_prog_is_offloaded(env->prog->aux)) {
17675 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17676 env->prev_insn_idx);
17681 regs = cur_regs(env);
17682 sanitize_mark_insn_seen(env);
17683 prev_insn_idx = env->insn_idx;
17685 if (class == BPF_ALU || class == BPF_ALU64) {
17686 err = check_alu_op(env, insn);
17690 } else if (class == BPF_LDX) {
17691 enum bpf_reg_type src_reg_type;
17693 /* check for reserved fields is already done */
17695 /* check src operand */
17696 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17700 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17704 src_reg_type = regs[insn->src_reg].type;
17706 /* check that memory (src_reg + off) is readable,
17707 * the state of dst_reg will be updated by this func
17709 err = check_mem_access(env, env->insn_idx, insn->src_reg,
17710 insn->off, BPF_SIZE(insn->code),
17711 BPF_READ, insn->dst_reg, false,
17712 BPF_MODE(insn->code) == BPF_MEMSX);
17713 err = err ?: save_aux_ptr_type(env, src_reg_type, true);
17714 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx");
17717 } else if (class == BPF_STX) {
17718 enum bpf_reg_type dst_reg_type;
17720 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17721 err = check_atomic(env, env->insn_idx, insn);
17728 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17729 verbose(env, "BPF_STX uses reserved fields\n");
17733 /* check src1 operand */
17734 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17737 /* check src2 operand */
17738 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17742 dst_reg_type = regs[insn->dst_reg].type;
17744 /* check that memory (dst_reg + off) is writeable */
17745 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17746 insn->off, BPF_SIZE(insn->code),
17747 BPF_WRITE, insn->src_reg, false, false);
17751 err = save_aux_ptr_type(env, dst_reg_type, false);
17754 } else if (class == BPF_ST) {
17755 enum bpf_reg_type dst_reg_type;
17757 if (BPF_MODE(insn->code) != BPF_MEM ||
17758 insn->src_reg != BPF_REG_0) {
17759 verbose(env, "BPF_ST uses reserved fields\n");
17762 /* check src operand */
17763 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17767 dst_reg_type = regs[insn->dst_reg].type;
17769 /* check that memory (dst_reg + off) is writeable */
17770 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17771 insn->off, BPF_SIZE(insn->code),
17772 BPF_WRITE, -1, false, false);
17776 err = save_aux_ptr_type(env, dst_reg_type, false);
17779 } else if (class == BPF_JMP || class == BPF_JMP32) {
17780 u8 opcode = BPF_OP(insn->code);
17782 env->jmps_processed++;
17783 if (opcode == BPF_CALL) {
17784 if (BPF_SRC(insn->code) != BPF_K ||
17785 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17786 && insn->off != 0) ||
17787 (insn->src_reg != BPF_REG_0 &&
17788 insn->src_reg != BPF_PSEUDO_CALL &&
17789 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17790 insn->dst_reg != BPF_REG_0 ||
17791 class == BPF_JMP32) {
17792 verbose(env, "BPF_CALL uses reserved fields\n");
17796 if (env->cur_state->active_lock.ptr) {
17797 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17798 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17799 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17800 verbose(env, "function calls are not allowed while holding a lock\n");
17804 if (insn->src_reg == BPF_PSEUDO_CALL) {
17805 err = check_func_call(env, insn, &env->insn_idx);
17806 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17807 err = check_kfunc_call(env, insn, &env->insn_idx);
17808 if (!err && is_bpf_throw_kfunc(insn)) {
17809 exception_exit = true;
17810 goto process_bpf_exit_full;
17813 err = check_helper_call(env, insn, &env->insn_idx);
17818 mark_reg_scratched(env, BPF_REG_0);
17819 } else if (opcode == BPF_JA) {
17820 if (BPF_SRC(insn->code) != BPF_K ||
17821 insn->src_reg != BPF_REG_0 ||
17822 insn->dst_reg != BPF_REG_0 ||
17823 (class == BPF_JMP && insn->imm != 0) ||
17824 (class == BPF_JMP32 && insn->off != 0)) {
17825 verbose(env, "BPF_JA uses reserved fields\n");
17829 if (class == BPF_JMP)
17830 env->insn_idx += insn->off + 1;
17832 env->insn_idx += insn->imm + 1;
17835 } else if (opcode == BPF_EXIT) {
17836 if (BPF_SRC(insn->code) != BPF_K ||
17838 insn->src_reg != BPF_REG_0 ||
17839 insn->dst_reg != BPF_REG_0 ||
17840 class == BPF_JMP32) {
17841 verbose(env, "BPF_EXIT uses reserved fields\n");
17844 process_bpf_exit_full:
17845 if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) {
17846 verbose(env, "bpf_spin_unlock is missing\n");
17850 if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) {
17851 verbose(env, "bpf_rcu_read_unlock is missing\n");
17855 /* We must do check_reference_leak here before
17856 * prepare_func_exit to handle the case when
17857 * state->curframe > 0, it may be a callback
17858 * function, for which reference_state must
17859 * match caller reference state when it exits.
17861 err = check_reference_leak(env, exception_exit);
17865 /* The side effect of the prepare_func_exit
17866 * which is being skipped is that it frees
17867 * bpf_func_state. Typically, process_bpf_exit
17868 * will only be hit with outermost exit.
17869 * copy_verifier_state in pop_stack will handle
17870 * freeing of any extra bpf_func_state left over
17871 * from not processing all nested function
17872 * exits. We also skip return code checks as
17873 * they are not needed for exceptional exits.
17875 if (exception_exit)
17876 goto process_bpf_exit;
17878 if (state->curframe) {
17879 /* exit from nested function */
17880 err = prepare_func_exit(env, &env->insn_idx);
17883 do_print_state = true;
17887 err = check_return_code(env, BPF_REG_0, "R0");
17891 mark_verifier_state_scratched(env);
17892 update_branch_counts(env, env->cur_state);
17893 err = pop_stack(env, &prev_insn_idx,
17894 &env->insn_idx, pop_log);
17896 if (err != -ENOENT)
17900 do_print_state = true;
17904 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17908 } else if (class == BPF_LD) {
17909 u8 mode = BPF_MODE(insn->code);
17911 if (mode == BPF_ABS || mode == BPF_IND) {
17912 err = check_ld_abs(env, insn);
17916 } else if (mode == BPF_IMM) {
17917 err = check_ld_imm(env, insn);
17922 sanitize_mark_insn_seen(env);
17924 verbose(env, "invalid BPF_LD mode\n");
17928 verbose(env, "unknown insn class %d\n", class);
17938 static int find_btf_percpu_datasec(struct btf *btf)
17940 const struct btf_type *t;
17945 * Both vmlinux and module each have their own ".data..percpu"
17946 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17947 * types to look at only module's own BTF types.
17949 n = btf_nr_types(btf);
17950 if (btf_is_module(btf))
17951 i = btf_nr_types(btf_vmlinux);
17955 for(; i < n; i++) {
17956 t = btf_type_by_id(btf, i);
17957 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17960 tname = btf_name_by_offset(btf, t->name_off);
17961 if (!strcmp(tname, ".data..percpu"))
17968 /* replace pseudo btf_id with kernel symbol address */
17969 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17970 struct bpf_insn *insn,
17971 struct bpf_insn_aux_data *aux)
17973 const struct btf_var_secinfo *vsi;
17974 const struct btf_type *datasec;
17975 struct btf_mod_pair *btf_mod;
17976 const struct btf_type *t;
17977 const char *sym_name;
17978 bool percpu = false;
17979 u32 type, id = insn->imm;
17983 int i, btf_fd, err;
17985 btf_fd = insn[1].imm;
17987 btf = btf_get_by_fd(btf_fd);
17989 verbose(env, "invalid module BTF object FD specified.\n");
17993 if (!btf_vmlinux) {
17994 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
18001 t = btf_type_by_id(btf, id);
18003 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
18008 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
18009 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
18014 sym_name = btf_name_by_offset(btf, t->name_off);
18015 addr = kallsyms_lookup_name(sym_name);
18017 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
18022 insn[0].imm = (u32)addr;
18023 insn[1].imm = addr >> 32;
18025 if (btf_type_is_func(t)) {
18026 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18027 aux->btf_var.mem_size = 0;
18031 datasec_id = find_btf_percpu_datasec(btf);
18032 if (datasec_id > 0) {
18033 datasec = btf_type_by_id(btf, datasec_id);
18034 for_each_vsi(i, datasec, vsi) {
18035 if (vsi->type == id) {
18043 t = btf_type_skip_modifiers(btf, type, NULL);
18045 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
18046 aux->btf_var.btf = btf;
18047 aux->btf_var.btf_id = type;
18048 } else if (!btf_type_is_struct(t)) {
18049 const struct btf_type *ret;
18053 /* resolve the type size of ksym. */
18054 ret = btf_resolve_size(btf, t, &tsize);
18056 tname = btf_name_by_offset(btf, t->name_off);
18057 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
18058 tname, PTR_ERR(ret));
18062 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18063 aux->btf_var.mem_size = tsize;
18065 aux->btf_var.reg_type = PTR_TO_BTF_ID;
18066 aux->btf_var.btf = btf;
18067 aux->btf_var.btf_id = type;
18070 /* check whether we recorded this BTF (and maybe module) already */
18071 for (i = 0; i < env->used_btf_cnt; i++) {
18072 if (env->used_btfs[i].btf == btf) {
18078 if (env->used_btf_cnt >= MAX_USED_BTFS) {
18083 btf_mod = &env->used_btfs[env->used_btf_cnt];
18084 btf_mod->btf = btf;
18085 btf_mod->module = NULL;
18087 /* if we reference variables from kernel module, bump its refcount */
18088 if (btf_is_module(btf)) {
18089 btf_mod->module = btf_try_get_module(btf);
18090 if (!btf_mod->module) {
18096 env->used_btf_cnt++;
18104 static bool is_tracing_prog_type(enum bpf_prog_type type)
18107 case BPF_PROG_TYPE_KPROBE:
18108 case BPF_PROG_TYPE_TRACEPOINT:
18109 case BPF_PROG_TYPE_PERF_EVENT:
18110 case BPF_PROG_TYPE_RAW_TRACEPOINT:
18111 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
18118 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
18119 struct bpf_map *map,
18120 struct bpf_prog *prog)
18123 enum bpf_prog_type prog_type = resolve_prog_type(prog);
18125 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
18126 btf_record_has_field(map->record, BPF_RB_ROOT)) {
18127 if (is_tracing_prog_type(prog_type)) {
18128 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
18133 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
18134 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
18135 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
18139 if (is_tracing_prog_type(prog_type)) {
18140 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
18145 if (btf_record_has_field(map->record, BPF_TIMER)) {
18146 if (is_tracing_prog_type(prog_type)) {
18147 verbose(env, "tracing progs cannot use bpf_timer yet\n");
18152 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
18153 !bpf_offload_prog_map_match(prog, map)) {
18154 verbose(env, "offload device mismatch between prog and map\n");
18158 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
18159 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
18163 if (prog->sleepable)
18164 switch (map->map_type) {
18165 case BPF_MAP_TYPE_HASH:
18166 case BPF_MAP_TYPE_LRU_HASH:
18167 case BPF_MAP_TYPE_ARRAY:
18168 case BPF_MAP_TYPE_PERCPU_HASH:
18169 case BPF_MAP_TYPE_PERCPU_ARRAY:
18170 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
18171 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
18172 case BPF_MAP_TYPE_HASH_OF_MAPS:
18173 case BPF_MAP_TYPE_RINGBUF:
18174 case BPF_MAP_TYPE_USER_RINGBUF:
18175 case BPF_MAP_TYPE_INODE_STORAGE:
18176 case BPF_MAP_TYPE_SK_STORAGE:
18177 case BPF_MAP_TYPE_TASK_STORAGE:
18178 case BPF_MAP_TYPE_CGRP_STORAGE:
18179 case BPF_MAP_TYPE_QUEUE:
18180 case BPF_MAP_TYPE_STACK:
18181 case BPF_MAP_TYPE_ARENA:
18185 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
18192 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
18194 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
18195 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
18198 /* find and rewrite pseudo imm in ld_imm64 instructions:
18200 * 1. if it accesses map FD, replace it with actual map pointer.
18201 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
18203 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
18205 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
18207 struct bpf_insn *insn = env->prog->insnsi;
18208 int insn_cnt = env->prog->len;
18211 err = bpf_prog_calc_tag(env->prog);
18215 for (i = 0; i < insn_cnt; i++, insn++) {
18216 if (BPF_CLASS(insn->code) == BPF_LDX &&
18217 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
18219 verbose(env, "BPF_LDX uses reserved fields\n");
18223 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
18224 struct bpf_insn_aux_data *aux;
18225 struct bpf_map *map;
18230 if (i == insn_cnt - 1 || insn[1].code != 0 ||
18231 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
18232 insn[1].off != 0) {
18233 verbose(env, "invalid bpf_ld_imm64 insn\n");
18237 if (insn[0].src_reg == 0)
18238 /* valid generic load 64-bit imm */
18241 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
18242 aux = &env->insn_aux_data[i];
18243 err = check_pseudo_btf_id(env, insn, aux);
18249 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
18250 aux = &env->insn_aux_data[i];
18251 aux->ptr_type = PTR_TO_FUNC;
18255 /* In final convert_pseudo_ld_imm64() step, this is
18256 * converted into regular 64-bit imm load insn.
18258 switch (insn[0].src_reg) {
18259 case BPF_PSEUDO_MAP_VALUE:
18260 case BPF_PSEUDO_MAP_IDX_VALUE:
18262 case BPF_PSEUDO_MAP_FD:
18263 case BPF_PSEUDO_MAP_IDX:
18264 if (insn[1].imm == 0)
18268 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
18272 switch (insn[0].src_reg) {
18273 case BPF_PSEUDO_MAP_IDX_VALUE:
18274 case BPF_PSEUDO_MAP_IDX:
18275 if (bpfptr_is_null(env->fd_array)) {
18276 verbose(env, "fd_idx without fd_array is invalid\n");
18279 if (copy_from_bpfptr_offset(&fd, env->fd_array,
18280 insn[0].imm * sizeof(fd),
18290 map = __bpf_map_get(f);
18292 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
18293 return PTR_ERR(map);
18296 err = check_map_prog_compatibility(env, map, env->prog);
18302 aux = &env->insn_aux_data[i];
18303 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
18304 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
18305 addr = (unsigned long)map;
18307 u32 off = insn[1].imm;
18309 if (off >= BPF_MAX_VAR_OFF) {
18310 verbose(env, "direct value offset of %u is not allowed\n", off);
18315 if (!map->ops->map_direct_value_addr) {
18316 verbose(env, "no direct value access support for this map type\n");
18321 err = map->ops->map_direct_value_addr(map, &addr, off);
18323 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
18324 map->value_size, off);
18329 aux->map_off = off;
18333 insn[0].imm = (u32)addr;
18334 insn[1].imm = addr >> 32;
18336 /* check whether we recorded this map already */
18337 for (j = 0; j < env->used_map_cnt; j++) {
18338 if (env->used_maps[j] == map) {
18339 aux->map_index = j;
18345 if (env->used_map_cnt >= MAX_USED_MAPS) {
18350 if (env->prog->sleepable)
18351 atomic64_inc(&map->sleepable_refcnt);
18352 /* hold the map. If the program is rejected by verifier,
18353 * the map will be released by release_maps() or it
18354 * will be used by the valid program until it's unloaded
18355 * and all maps are released in bpf_free_used_maps()
18359 aux->map_index = env->used_map_cnt;
18360 env->used_maps[env->used_map_cnt++] = map;
18362 if (bpf_map_is_cgroup_storage(map) &&
18363 bpf_cgroup_storage_assign(env->prog->aux, map)) {
18364 verbose(env, "only one cgroup storage of each type is allowed\n");
18368 if (map->map_type == BPF_MAP_TYPE_ARENA) {
18369 if (env->prog->aux->arena) {
18370 verbose(env, "Only one arena per program\n");
18374 if (!env->allow_ptr_leaks || !env->bpf_capable) {
18375 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
18379 if (!env->prog->jit_requested) {
18380 verbose(env, "JIT is required to use arena\n");
18382 return -EOPNOTSUPP;
18384 if (!bpf_jit_supports_arena()) {
18385 verbose(env, "JIT doesn't support arena\n");
18387 return -EOPNOTSUPP;
18389 env->prog->aux->arena = (void *)map;
18390 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
18391 verbose(env, "arena's user address must be set via map_extra or mmap()\n");
18404 /* Basic sanity check before we invest more work here. */
18405 if (!bpf_opcode_in_insntable(insn->code)) {
18406 verbose(env, "unknown opcode %02x\n", insn->code);
18411 /* now all pseudo BPF_LD_IMM64 instructions load valid
18412 * 'struct bpf_map *' into a register instead of user map_fd.
18413 * These pointers will be used later by verifier to validate map access.
18418 /* drop refcnt of maps used by the rejected program */
18419 static void release_maps(struct bpf_verifier_env *env)
18421 __bpf_free_used_maps(env->prog->aux, env->used_maps,
18422 env->used_map_cnt);
18425 /* drop refcnt of maps used by the rejected program */
18426 static void release_btfs(struct bpf_verifier_env *env)
18428 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
18429 env->used_btf_cnt);
18432 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
18433 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
18435 struct bpf_insn *insn = env->prog->insnsi;
18436 int insn_cnt = env->prog->len;
18439 for (i = 0; i < insn_cnt; i++, insn++) {
18440 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18442 if (insn->src_reg == BPF_PSEUDO_FUNC)
18448 /* single env->prog->insni[off] instruction was replaced with the range
18449 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
18450 * [0, off) and [off, end) to new locations, so the patched range stays zero
18452 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
18453 struct bpf_insn_aux_data *new_data,
18454 struct bpf_prog *new_prog, u32 off, u32 cnt)
18456 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
18457 struct bpf_insn *insn = new_prog->insnsi;
18458 u32 old_seen = old_data[off].seen;
18462 /* aux info at OFF always needs adjustment, no matter fast path
18463 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
18464 * original insn at old prog.
18466 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
18470 prog_len = new_prog->len;
18472 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
18473 memcpy(new_data + off + cnt - 1, old_data + off,
18474 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
18475 for (i = off; i < off + cnt - 1; i++) {
18476 /* Expand insni[off]'s seen count to the patched range. */
18477 new_data[i].seen = old_seen;
18478 new_data[i].zext_dst = insn_has_def32(env, insn + i);
18480 env->insn_aux_data = new_data;
18484 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
18490 /* NOTE: fake 'exit' subprog should be updated as well. */
18491 for (i = 0; i <= env->subprog_cnt; i++) {
18492 if (env->subprog_info[i].start <= off)
18494 env->subprog_info[i].start += len - 1;
18498 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
18500 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
18501 int i, sz = prog->aux->size_poke_tab;
18502 struct bpf_jit_poke_descriptor *desc;
18504 for (i = 0; i < sz; i++) {
18506 if (desc->insn_idx <= off)
18508 desc->insn_idx += len - 1;
18512 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
18513 const struct bpf_insn *patch, u32 len)
18515 struct bpf_prog *new_prog;
18516 struct bpf_insn_aux_data *new_data = NULL;
18519 new_data = vzalloc(array_size(env->prog->len + len - 1,
18520 sizeof(struct bpf_insn_aux_data)));
18525 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
18526 if (IS_ERR(new_prog)) {
18527 if (PTR_ERR(new_prog) == -ERANGE)
18529 "insn %d cannot be patched due to 16-bit range\n",
18530 env->insn_aux_data[off].orig_idx);
18534 adjust_insn_aux_data(env, new_data, new_prog, off, len);
18535 adjust_subprog_starts(env, off, len);
18536 adjust_poke_descs(new_prog, off, len);
18540 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
18545 /* find first prog starting at or after off (first to remove) */
18546 for (i = 0; i < env->subprog_cnt; i++)
18547 if (env->subprog_info[i].start >= off)
18549 /* find first prog starting at or after off + cnt (first to stay) */
18550 for (j = i; j < env->subprog_cnt; j++)
18551 if (env->subprog_info[j].start >= off + cnt)
18553 /* if j doesn't start exactly at off + cnt, we are just removing
18554 * the front of previous prog
18556 if (env->subprog_info[j].start != off + cnt)
18560 struct bpf_prog_aux *aux = env->prog->aux;
18563 /* move fake 'exit' subprog as well */
18564 move = env->subprog_cnt + 1 - j;
18566 memmove(env->subprog_info + i,
18567 env->subprog_info + j,
18568 sizeof(*env->subprog_info) * move);
18569 env->subprog_cnt -= j - i;
18571 /* remove func_info */
18572 if (aux->func_info) {
18573 move = aux->func_info_cnt - j;
18575 memmove(aux->func_info + i,
18576 aux->func_info + j,
18577 sizeof(*aux->func_info) * move);
18578 aux->func_info_cnt -= j - i;
18579 /* func_info->insn_off is set after all code rewrites,
18580 * in adjust_btf_func() - no need to adjust
18584 /* convert i from "first prog to remove" to "first to adjust" */
18585 if (env->subprog_info[i].start == off)
18589 /* update fake 'exit' subprog as well */
18590 for (; i <= env->subprog_cnt; i++)
18591 env->subprog_info[i].start -= cnt;
18596 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18599 struct bpf_prog *prog = env->prog;
18600 u32 i, l_off, l_cnt, nr_linfo;
18601 struct bpf_line_info *linfo;
18603 nr_linfo = prog->aux->nr_linfo;
18607 linfo = prog->aux->linfo;
18609 /* find first line info to remove, count lines to be removed */
18610 for (i = 0; i < nr_linfo; i++)
18611 if (linfo[i].insn_off >= off)
18616 for (; i < nr_linfo; i++)
18617 if (linfo[i].insn_off < off + cnt)
18622 /* First live insn doesn't match first live linfo, it needs to "inherit"
18623 * last removed linfo. prog is already modified, so prog->len == off
18624 * means no live instructions after (tail of the program was removed).
18626 if (prog->len != off && l_cnt &&
18627 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18629 linfo[--i].insn_off = off + cnt;
18632 /* remove the line info which refer to the removed instructions */
18634 memmove(linfo + l_off, linfo + i,
18635 sizeof(*linfo) * (nr_linfo - i));
18637 prog->aux->nr_linfo -= l_cnt;
18638 nr_linfo = prog->aux->nr_linfo;
18641 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
18642 for (i = l_off; i < nr_linfo; i++)
18643 linfo[i].insn_off -= cnt;
18645 /* fix up all subprogs (incl. 'exit') which start >= off */
18646 for (i = 0; i <= env->subprog_cnt; i++)
18647 if (env->subprog_info[i].linfo_idx > l_off) {
18648 /* program may have started in the removed region but
18649 * may not be fully removed
18651 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18652 env->subprog_info[i].linfo_idx -= l_cnt;
18654 env->subprog_info[i].linfo_idx = l_off;
18660 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18662 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18663 unsigned int orig_prog_len = env->prog->len;
18666 if (bpf_prog_is_offloaded(env->prog->aux))
18667 bpf_prog_offload_remove_insns(env, off, cnt);
18669 err = bpf_remove_insns(env->prog, off, cnt);
18673 err = adjust_subprog_starts_after_remove(env, off, cnt);
18677 err = bpf_adj_linfo_after_remove(env, off, cnt);
18681 memmove(aux_data + off, aux_data + off + cnt,
18682 sizeof(*aux_data) * (orig_prog_len - off - cnt));
18687 /* The verifier does more data flow analysis than llvm and will not
18688 * explore branches that are dead at run time. Malicious programs can
18689 * have dead code too. Therefore replace all dead at-run-time code
18692 * Just nops are not optimal, e.g. if they would sit at the end of the
18693 * program and through another bug we would manage to jump there, then
18694 * we'd execute beyond program memory otherwise. Returning exception
18695 * code also wouldn't work since we can have subprogs where the dead
18696 * code could be located.
18698 static void sanitize_dead_code(struct bpf_verifier_env *env)
18700 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18701 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18702 struct bpf_insn *insn = env->prog->insnsi;
18703 const int insn_cnt = env->prog->len;
18706 for (i = 0; i < insn_cnt; i++) {
18707 if (aux_data[i].seen)
18709 memcpy(insn + i, &trap, sizeof(trap));
18710 aux_data[i].zext_dst = false;
18714 static bool insn_is_cond_jump(u8 code)
18719 if (BPF_CLASS(code) == BPF_JMP32)
18720 return op != BPF_JA;
18722 if (BPF_CLASS(code) != BPF_JMP)
18725 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18728 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18730 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18731 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18732 struct bpf_insn *insn = env->prog->insnsi;
18733 const int insn_cnt = env->prog->len;
18736 for (i = 0; i < insn_cnt; i++, insn++) {
18737 if (!insn_is_cond_jump(insn->code))
18740 if (!aux_data[i + 1].seen)
18741 ja.off = insn->off;
18742 else if (!aux_data[i + 1 + insn->off].seen)
18747 if (bpf_prog_is_offloaded(env->prog->aux))
18748 bpf_prog_offload_replace_insn(env, i, &ja);
18750 memcpy(insn, &ja, sizeof(ja));
18754 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18756 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18757 int insn_cnt = env->prog->len;
18760 for (i = 0; i < insn_cnt; i++) {
18764 while (i + j < insn_cnt && !aux_data[i + j].seen)
18769 err = verifier_remove_insns(env, i, j);
18772 insn_cnt = env->prog->len;
18778 static int opt_remove_nops(struct bpf_verifier_env *env)
18780 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18781 struct bpf_insn *insn = env->prog->insnsi;
18782 int insn_cnt = env->prog->len;
18785 for (i = 0; i < insn_cnt; i++) {
18786 if (memcmp(&insn[i], &ja, sizeof(ja)))
18789 err = verifier_remove_insns(env, i, 1);
18799 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18800 const union bpf_attr *attr)
18802 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18803 struct bpf_insn_aux_data *aux = env->insn_aux_data;
18804 int i, patch_len, delta = 0, len = env->prog->len;
18805 struct bpf_insn *insns = env->prog->insnsi;
18806 struct bpf_prog *new_prog;
18809 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18810 zext_patch[1] = BPF_ZEXT_REG(0);
18811 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18812 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18813 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18814 for (i = 0; i < len; i++) {
18815 int adj_idx = i + delta;
18816 struct bpf_insn insn;
18819 insn = insns[adj_idx];
18820 load_reg = insn_def_regno(&insn);
18821 if (!aux[adj_idx].zext_dst) {
18829 class = BPF_CLASS(code);
18830 if (load_reg == -1)
18833 /* NOTE: arg "reg" (the fourth one) is only used for
18834 * BPF_STX + SRC_OP, so it is safe to pass NULL
18837 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18838 if (class == BPF_LD &&
18839 BPF_MODE(code) == BPF_IMM)
18844 /* ctx load could be transformed into wider load. */
18845 if (class == BPF_LDX &&
18846 aux[adj_idx].ptr_type == PTR_TO_CTX)
18849 imm_rnd = get_random_u32();
18850 rnd_hi32_patch[0] = insn;
18851 rnd_hi32_patch[1].imm = imm_rnd;
18852 rnd_hi32_patch[3].dst_reg = load_reg;
18853 patch = rnd_hi32_patch;
18855 goto apply_patch_buffer;
18858 /* Add in an zero-extend instruction if a) the JIT has requested
18859 * it or b) it's a CMPXCHG.
18861 * The latter is because: BPF_CMPXCHG always loads a value into
18862 * R0, therefore always zero-extends. However some archs'
18863 * equivalent instruction only does this load when the
18864 * comparison is successful. This detail of CMPXCHG is
18865 * orthogonal to the general zero-extension behaviour of the
18866 * CPU, so it's treated independently of bpf_jit_needs_zext.
18868 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18871 /* Zero-extension is done by the caller. */
18872 if (bpf_pseudo_kfunc_call(&insn))
18875 if (WARN_ON(load_reg == -1)) {
18876 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18880 zext_patch[0] = insn;
18881 zext_patch[1].dst_reg = load_reg;
18882 zext_patch[1].src_reg = load_reg;
18883 patch = zext_patch;
18885 apply_patch_buffer:
18886 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18889 env->prog = new_prog;
18890 insns = new_prog->insnsi;
18891 aux = env->insn_aux_data;
18892 delta += patch_len - 1;
18898 /* convert load instructions that access fields of a context type into a
18899 * sequence of instructions that access fields of the underlying structure:
18900 * struct __sk_buff -> struct sk_buff
18901 * struct bpf_sock_ops -> struct sock
18903 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18905 const struct bpf_verifier_ops *ops = env->ops;
18906 int i, cnt, size, ctx_field_size, delta = 0;
18907 const int insn_cnt = env->prog->len;
18908 struct bpf_insn insn_buf[16], *insn;
18909 u32 target_size, size_default, off;
18910 struct bpf_prog *new_prog;
18911 enum bpf_access_type type;
18912 bool is_narrower_load;
18914 if (ops->gen_prologue || env->seen_direct_write) {
18915 if (!ops->gen_prologue) {
18916 verbose(env, "bpf verifier is misconfigured\n");
18919 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18921 if (cnt >= ARRAY_SIZE(insn_buf)) {
18922 verbose(env, "bpf verifier is misconfigured\n");
18925 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18929 env->prog = new_prog;
18934 if (bpf_prog_is_offloaded(env->prog->aux))
18937 insn = env->prog->insnsi + delta;
18939 for (i = 0; i < insn_cnt; i++, insn++) {
18940 bpf_convert_ctx_access_t convert_ctx_access;
18943 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18944 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18945 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18946 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18947 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18948 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18949 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18951 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18952 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18953 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18954 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18955 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18956 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18957 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18958 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18964 if (type == BPF_WRITE &&
18965 env->insn_aux_data[i + delta].sanitize_stack_spill) {
18966 struct bpf_insn patch[] = {
18971 cnt = ARRAY_SIZE(patch);
18972 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18977 env->prog = new_prog;
18978 insn = new_prog->insnsi + i + delta;
18982 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18984 if (!ops->convert_ctx_access)
18986 convert_ctx_access = ops->convert_ctx_access;
18988 case PTR_TO_SOCKET:
18989 case PTR_TO_SOCK_COMMON:
18990 convert_ctx_access = bpf_sock_convert_ctx_access;
18992 case PTR_TO_TCP_SOCK:
18993 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18995 case PTR_TO_XDP_SOCK:
18996 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18998 case PTR_TO_BTF_ID:
18999 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
19000 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
19001 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
19002 * be said once it is marked PTR_UNTRUSTED, hence we must handle
19003 * any faults for loads into such types. BPF_WRITE is disallowed
19006 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
19007 if (type == BPF_READ) {
19008 if (BPF_MODE(insn->code) == BPF_MEM)
19009 insn->code = BPF_LDX | BPF_PROBE_MEM |
19010 BPF_SIZE((insn)->code);
19012 insn->code = BPF_LDX | BPF_PROBE_MEMSX |
19013 BPF_SIZE((insn)->code);
19014 env->prog->aux->num_exentries++;
19018 if (BPF_MODE(insn->code) == BPF_MEMSX) {
19019 verbose(env, "sign extending loads from arena are not supported yet\n");
19020 return -EOPNOTSUPP;
19022 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
19023 env->prog->aux->num_exentries++;
19029 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
19030 size = BPF_LDST_BYTES(insn);
19031 mode = BPF_MODE(insn->code);
19033 /* If the read access is a narrower load of the field,
19034 * convert to a 4/8-byte load, to minimum program type specific
19035 * convert_ctx_access changes. If conversion is successful,
19036 * we will apply proper mask to the result.
19038 is_narrower_load = size < ctx_field_size;
19039 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
19041 if (is_narrower_load) {
19044 if (type == BPF_WRITE) {
19045 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
19050 if (ctx_field_size == 4)
19052 else if (ctx_field_size == 8)
19053 size_code = BPF_DW;
19055 insn->off = off & ~(size_default - 1);
19056 insn->code = BPF_LDX | BPF_MEM | size_code;
19060 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
19062 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
19063 (ctx_field_size && !target_size)) {
19064 verbose(env, "bpf verifier is misconfigured\n");
19068 if (is_narrower_load && size < target_size) {
19069 u8 shift = bpf_ctx_narrow_access_offset(
19070 off, size, size_default) * 8;
19071 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
19072 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
19075 if (ctx_field_size <= 4) {
19077 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
19080 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
19081 (1 << size * 8) - 1);
19084 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
19087 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
19088 (1ULL << size * 8) - 1);
19091 if (mode == BPF_MEMSX)
19092 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
19093 insn->dst_reg, insn->dst_reg,
19096 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19102 /* keep walking new program and skip insns we just inserted */
19103 env->prog = new_prog;
19104 insn = new_prog->insnsi + i + delta;
19110 static int jit_subprogs(struct bpf_verifier_env *env)
19112 struct bpf_prog *prog = env->prog, **func, *tmp;
19113 int i, j, subprog_start, subprog_end = 0, len, subprog;
19114 struct bpf_map *map_ptr;
19115 struct bpf_insn *insn;
19116 void *old_bpf_func;
19117 int err, num_exentries;
19119 if (env->subprog_cnt <= 1)
19122 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19123 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
19126 /* Upon error here we cannot fall back to interpreter but
19127 * need a hard reject of the program. Thus -EFAULT is
19128 * propagated in any case.
19130 subprog = find_subprog(env, i + insn->imm + 1);
19132 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
19133 i + insn->imm + 1);
19136 /* temporarily remember subprog id inside insn instead of
19137 * aux_data, since next loop will split up all insns into funcs
19139 insn->off = subprog;
19140 /* remember original imm in case JIT fails and fallback
19141 * to interpreter will be needed
19143 env->insn_aux_data[i].call_imm = insn->imm;
19144 /* point imm to __bpf_call_base+1 from JITs point of view */
19146 if (bpf_pseudo_func(insn))
19147 /* jit (e.g. x86_64) may emit fewer instructions
19148 * if it learns a u32 imm is the same as a u64 imm.
19149 * Force a non zero here.
19154 err = bpf_prog_alloc_jited_linfo(prog);
19156 goto out_undo_insn;
19159 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
19161 goto out_undo_insn;
19163 for (i = 0; i < env->subprog_cnt; i++) {
19164 subprog_start = subprog_end;
19165 subprog_end = env->subprog_info[i + 1].start;
19167 len = subprog_end - subprog_start;
19168 /* bpf_prog_run() doesn't call subprogs directly,
19169 * hence main prog stats include the runtime of subprogs.
19170 * subprogs don't have IDs and not reachable via prog_get_next_id
19171 * func[i]->stats will never be accessed and stays NULL
19173 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
19176 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
19177 len * sizeof(struct bpf_insn));
19178 func[i]->type = prog->type;
19179 func[i]->len = len;
19180 if (bpf_prog_calc_tag(func[i]))
19182 func[i]->is_func = 1;
19183 func[i]->aux->func_idx = i;
19184 /* Below members will be freed only at prog->aux */
19185 func[i]->aux->btf = prog->aux->btf;
19186 func[i]->aux->func_info = prog->aux->func_info;
19187 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
19188 func[i]->aux->poke_tab = prog->aux->poke_tab;
19189 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
19191 for (j = 0; j < prog->aux->size_poke_tab; j++) {
19192 struct bpf_jit_poke_descriptor *poke;
19194 poke = &prog->aux->poke_tab[j];
19195 if (poke->insn_idx < subprog_end &&
19196 poke->insn_idx >= subprog_start)
19197 poke->aux = func[i]->aux;
19200 func[i]->aux->name[0] = 'F';
19201 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
19202 func[i]->jit_requested = 1;
19203 func[i]->blinding_requested = prog->blinding_requested;
19204 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
19205 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
19206 func[i]->aux->linfo = prog->aux->linfo;
19207 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
19208 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
19209 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
19210 func[i]->aux->arena = prog->aux->arena;
19212 insn = func[i]->insnsi;
19213 for (j = 0; j < func[i]->len; j++, insn++) {
19214 if (BPF_CLASS(insn->code) == BPF_LDX &&
19215 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
19216 BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
19217 BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
19219 if ((BPF_CLASS(insn->code) == BPF_STX ||
19220 BPF_CLASS(insn->code) == BPF_ST) &&
19221 BPF_MODE(insn->code) == BPF_PROBE_MEM32)
19224 func[i]->aux->num_exentries = num_exentries;
19225 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
19226 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
19228 func[i]->aux->exception_boundary = env->seen_exception;
19229 func[i] = bpf_int_jit_compile(func[i]);
19230 if (!func[i]->jited) {
19237 /* at this point all bpf functions were successfully JITed
19238 * now populate all bpf_calls with correct addresses and
19239 * run last pass of JIT
19241 for (i = 0; i < env->subprog_cnt; i++) {
19242 insn = func[i]->insnsi;
19243 for (j = 0; j < func[i]->len; j++, insn++) {
19244 if (bpf_pseudo_func(insn)) {
19245 subprog = insn->off;
19246 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
19247 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
19250 if (!bpf_pseudo_call(insn))
19252 subprog = insn->off;
19253 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
19256 /* we use the aux data to keep a list of the start addresses
19257 * of the JITed images for each function in the program
19259 * for some architectures, such as powerpc64, the imm field
19260 * might not be large enough to hold the offset of the start
19261 * address of the callee's JITed image from __bpf_call_base
19263 * in such cases, we can lookup the start address of a callee
19264 * by using its subprog id, available from the off field of
19265 * the call instruction, as an index for this list
19267 func[i]->aux->func = func;
19268 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19269 func[i]->aux->real_func_cnt = env->subprog_cnt;
19271 for (i = 0; i < env->subprog_cnt; i++) {
19272 old_bpf_func = func[i]->bpf_func;
19273 tmp = bpf_int_jit_compile(func[i]);
19274 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
19275 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
19282 /* finally lock prog and jit images for all functions and
19283 * populate kallsysm. Begin at the first subprogram, since
19284 * bpf_prog_load will add the kallsyms for the main program.
19286 for (i = 1; i < env->subprog_cnt; i++) {
19287 bpf_prog_lock_ro(func[i]);
19288 bpf_prog_kallsyms_add(func[i]);
19291 /* Last step: make now unused interpreter insns from main
19292 * prog consistent for later dump requests, so they can
19293 * later look the same as if they were interpreted only.
19295 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19296 if (bpf_pseudo_func(insn)) {
19297 insn[0].imm = env->insn_aux_data[i].call_imm;
19298 insn[1].imm = insn->off;
19302 if (!bpf_pseudo_call(insn))
19304 insn->off = env->insn_aux_data[i].call_imm;
19305 subprog = find_subprog(env, i + insn->off + 1);
19306 insn->imm = subprog;
19310 prog->bpf_func = func[0]->bpf_func;
19311 prog->jited_len = func[0]->jited_len;
19312 prog->aux->extable = func[0]->aux->extable;
19313 prog->aux->num_exentries = func[0]->aux->num_exentries;
19314 prog->aux->func = func;
19315 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19316 prog->aux->real_func_cnt = env->subprog_cnt;
19317 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
19318 prog->aux->exception_boundary = func[0]->aux->exception_boundary;
19319 bpf_prog_jit_attempt_done(prog);
19322 /* We failed JIT'ing, so at this point we need to unregister poke
19323 * descriptors from subprogs, so that kernel is not attempting to
19324 * patch it anymore as we're freeing the subprog JIT memory.
19326 for (i = 0; i < prog->aux->size_poke_tab; i++) {
19327 map_ptr = prog->aux->poke_tab[i].tail_call.map;
19328 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
19330 /* At this point we're guaranteed that poke descriptors are not
19331 * live anymore. We can just unlink its descriptor table as it's
19332 * released with the main prog.
19334 for (i = 0; i < env->subprog_cnt; i++) {
19337 func[i]->aux->poke_tab = NULL;
19338 bpf_jit_free(func[i]);
19342 /* cleanup main prog to be interpreted */
19343 prog->jit_requested = 0;
19344 prog->blinding_requested = 0;
19345 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19346 if (!bpf_pseudo_call(insn))
19349 insn->imm = env->insn_aux_data[i].call_imm;
19351 bpf_prog_jit_attempt_done(prog);
19355 static int fixup_call_args(struct bpf_verifier_env *env)
19357 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19358 struct bpf_prog *prog = env->prog;
19359 struct bpf_insn *insn = prog->insnsi;
19360 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
19365 if (env->prog->jit_requested &&
19366 !bpf_prog_is_offloaded(env->prog->aux)) {
19367 err = jit_subprogs(env);
19370 if (err == -EFAULT)
19373 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19374 if (has_kfunc_call) {
19375 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
19378 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
19379 /* When JIT fails the progs with bpf2bpf calls and tail_calls
19380 * have to be rejected, since interpreter doesn't support them yet.
19382 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
19385 for (i = 0; i < prog->len; i++, insn++) {
19386 if (bpf_pseudo_func(insn)) {
19387 /* When JIT fails the progs with callback calls
19388 * have to be rejected, since interpreter doesn't support them yet.
19390 verbose(env, "callbacks are not allowed in non-JITed programs\n");
19394 if (!bpf_pseudo_call(insn))
19396 depth = get_callee_stack_depth(env, insn, i);
19399 bpf_patch_call_args(insn, depth);
19406 /* replace a generic kfunc with a specialized version if necessary */
19407 static void specialize_kfunc(struct bpf_verifier_env *env,
19408 u32 func_id, u16 offset, unsigned long *addr)
19410 struct bpf_prog *prog = env->prog;
19411 bool seen_direct_write;
19415 if (bpf_dev_bound_kfunc_id(func_id)) {
19416 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19418 *addr = (unsigned long)xdp_kfunc;
19421 /* fallback to default kfunc when not supported by netdev */
19427 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19428 seen_direct_write = env->seen_direct_write;
19429 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19432 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19434 /* restore env->seen_direct_write to its original value, since
19435 * may_access_direct_pkt_data mutates it
19437 env->seen_direct_write = seen_direct_write;
19441 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19442 u16 struct_meta_reg,
19443 u16 node_offset_reg,
19444 struct bpf_insn *insn,
19445 struct bpf_insn *insn_buf,
19448 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19449 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19451 insn_buf[0] = addr[0];
19452 insn_buf[1] = addr[1];
19453 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19454 insn_buf[3] = *insn;
19458 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19459 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
19461 const struct bpf_kfunc_desc *desc;
19464 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19470 /* insn->imm has the btf func_id. Replace it with an offset relative to
19471 * __bpf_call_base, unless the JIT needs to call functions that are
19472 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
19474 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
19476 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
19481 if (!bpf_jit_supports_far_kfunc_call())
19482 insn->imm = BPF_CALL_IMM(desc->addr);
19485 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
19486 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
19487 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19488 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19489 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
19491 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
19492 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19497 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19498 insn_buf[1] = addr[0];
19499 insn_buf[2] = addr[1];
19500 insn_buf[3] = *insn;
19502 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
19503 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
19504 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
19505 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19506 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19508 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
19509 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19514 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
19515 !kptr_struct_meta) {
19516 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19521 insn_buf[0] = addr[0];
19522 insn_buf[1] = addr[1];
19523 insn_buf[2] = *insn;
19525 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
19526 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
19527 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19528 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19529 int struct_meta_reg = BPF_REG_3;
19530 int node_offset_reg = BPF_REG_4;
19532 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
19533 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19534 struct_meta_reg = BPF_REG_4;
19535 node_offset_reg = BPF_REG_5;
19538 if (!kptr_struct_meta) {
19539 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19544 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19545 node_offset_reg, insn, insn_buf, cnt);
19546 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19547 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19548 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19554 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
19555 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
19557 struct bpf_subprog_info *info = env->subprog_info;
19558 int cnt = env->subprog_cnt;
19559 struct bpf_prog *prog;
19561 /* We only reserve one slot for hidden subprogs in subprog_info. */
19562 if (env->hidden_subprog_cnt) {
19563 verbose(env, "verifier internal error: only one hidden subprog supported\n");
19566 /* We're not patching any existing instruction, just appending the new
19567 * ones for the hidden subprog. Hence all of the adjustment operations
19568 * in bpf_patch_insn_data are no-ops.
19570 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
19574 info[cnt + 1].start = info[cnt].start;
19575 info[cnt].start = prog->len - len + 1;
19576 env->subprog_cnt++;
19577 env->hidden_subprog_cnt++;
19581 /* Do various post-verification rewrites in a single program pass.
19582 * These rewrites simplify JIT and interpreter implementations.
19584 static int do_misc_fixups(struct bpf_verifier_env *env)
19586 struct bpf_prog *prog = env->prog;
19587 enum bpf_attach_type eatype = prog->expected_attach_type;
19588 enum bpf_prog_type prog_type = resolve_prog_type(prog);
19589 struct bpf_insn *insn = prog->insnsi;
19590 const struct bpf_func_proto *fn;
19591 const int insn_cnt = prog->len;
19592 const struct bpf_map_ops *ops;
19593 struct bpf_insn_aux_data *aux;
19594 struct bpf_insn insn_buf[16];
19595 struct bpf_prog *new_prog;
19596 struct bpf_map *map_ptr;
19597 int i, ret, cnt, delta = 0, cur_subprog = 0;
19598 struct bpf_subprog_info *subprogs = env->subprog_info;
19599 u16 stack_depth = subprogs[cur_subprog].stack_depth;
19600 u16 stack_depth_extra = 0;
19602 if (env->seen_exception && !env->exception_callback_subprog) {
19603 struct bpf_insn patch[] = {
19604 env->prog->insnsi[insn_cnt - 1],
19605 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
19609 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
19613 insn = prog->insnsi;
19615 env->exception_callback_subprog = env->subprog_cnt - 1;
19616 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */
19617 mark_subprog_exc_cb(env, env->exception_callback_subprog);
19620 for (i = 0; i < insn_cnt;) {
19621 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
19622 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
19623 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
19624 /* convert to 32-bit mov that clears upper 32-bit */
19625 insn->code = BPF_ALU | BPF_MOV | BPF_X;
19626 /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
19629 } /* cast from as(0) to as(1) should be handled by JIT */
19633 if (env->insn_aux_data[i + delta].needs_zext)
19634 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
19635 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
19637 /* Make divide-by-zero exceptions impossible. */
19638 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
19639 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
19640 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
19641 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
19642 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
19643 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
19644 struct bpf_insn *patchlet;
19645 struct bpf_insn chk_and_div[] = {
19646 /* [R,W]x div 0 -> 0 */
19647 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19648 BPF_JNE | BPF_K, insn->src_reg,
19650 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
19651 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19654 struct bpf_insn chk_and_mod[] = {
19655 /* [R,W]x mod 0 -> [R,W]x */
19656 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19657 BPF_JEQ | BPF_K, insn->src_reg,
19658 0, 1 + (is64 ? 0 : 1), 0),
19660 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19661 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
19664 patchlet = isdiv ? chk_and_div : chk_and_mod;
19665 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
19666 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
19668 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
19673 env->prog = prog = new_prog;
19674 insn = new_prog->insnsi + i + delta;
19678 /* Make it impossible to de-reference a userspace address */
19679 if (BPF_CLASS(insn->code) == BPF_LDX &&
19680 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
19681 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
19682 struct bpf_insn *patch = &insn_buf[0];
19683 u64 uaddress_limit = bpf_arch_uaddress_limit();
19685 if (!uaddress_limit)
19688 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
19690 *patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
19691 *patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
19692 *patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
19694 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
19695 *patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
19697 cnt = patch - insn_buf;
19698 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19703 env->prog = prog = new_prog;
19704 insn = new_prog->insnsi + i + delta;
19708 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
19709 if (BPF_CLASS(insn->code) == BPF_LD &&
19710 (BPF_MODE(insn->code) == BPF_ABS ||
19711 BPF_MODE(insn->code) == BPF_IND)) {
19712 cnt = env->ops->gen_ld_abs(insn, insn_buf);
19713 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19714 verbose(env, "bpf verifier is misconfigured\n");
19718 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19723 env->prog = prog = new_prog;
19724 insn = new_prog->insnsi + i + delta;
19728 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
19729 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
19730 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
19731 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
19732 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
19733 struct bpf_insn *patch = &insn_buf[0];
19734 bool issrc, isneg, isimm;
19737 aux = &env->insn_aux_data[i + delta];
19738 if (!aux->alu_state ||
19739 aux->alu_state == BPF_ALU_NON_POINTER)
19742 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
19743 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
19744 BPF_ALU_SANITIZE_SRC;
19745 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
19747 off_reg = issrc ? insn->src_reg : insn->dst_reg;
19749 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19752 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19753 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19754 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
19755 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
19756 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
19757 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
19758 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
19761 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
19762 insn->src_reg = BPF_REG_AX;
19764 insn->code = insn->code == code_add ?
19765 code_sub : code_add;
19767 if (issrc && isneg && !isimm)
19768 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19769 cnt = patch - insn_buf;
19771 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19776 env->prog = prog = new_prog;
19777 insn = new_prog->insnsi + i + delta;
19781 if (is_may_goto_insn(insn)) {
19782 int stack_off = -stack_depth - 8;
19784 stack_depth_extra = 8;
19785 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
19786 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
19787 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
19788 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
19791 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19796 env->prog = prog = new_prog;
19797 insn = new_prog->insnsi + i + delta;
19801 if (insn->code != (BPF_JMP | BPF_CALL))
19803 if (insn->src_reg == BPF_PSEUDO_CALL)
19805 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19806 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19812 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19817 env->prog = prog = new_prog;
19818 insn = new_prog->insnsi + i + delta;
19822 if (insn->imm == BPF_FUNC_get_route_realm)
19823 prog->dst_needed = 1;
19824 if (insn->imm == BPF_FUNC_get_prandom_u32)
19825 bpf_user_rnd_init_once();
19826 if (insn->imm == BPF_FUNC_override_return)
19827 prog->kprobe_override = 1;
19828 if (insn->imm == BPF_FUNC_tail_call) {
19829 /* If we tail call into other programs, we
19830 * cannot make any assumptions since they can
19831 * be replaced dynamically during runtime in
19832 * the program array.
19834 prog->cb_access = 1;
19835 if (!allow_tail_call_in_subprogs(env))
19836 prog->aux->stack_depth = MAX_BPF_STACK;
19837 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19839 /* mark bpf_tail_call as different opcode to avoid
19840 * conditional branch in the interpreter for every normal
19841 * call and to prevent accidental JITing by JIT compiler
19842 * that doesn't support bpf_tail_call yet
19845 insn->code = BPF_JMP | BPF_TAIL_CALL;
19847 aux = &env->insn_aux_data[i + delta];
19848 if (env->bpf_capable && !prog->blinding_requested &&
19849 prog->jit_requested &&
19850 !bpf_map_key_poisoned(aux) &&
19851 !bpf_map_ptr_poisoned(aux) &&
19852 !bpf_map_ptr_unpriv(aux)) {
19853 struct bpf_jit_poke_descriptor desc = {
19854 .reason = BPF_POKE_REASON_TAIL_CALL,
19855 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19856 .tail_call.key = bpf_map_key_immediate(aux),
19857 .insn_idx = i + delta,
19860 ret = bpf_jit_add_poke_descriptor(prog, &desc);
19862 verbose(env, "adding tail call poke descriptor failed\n");
19866 insn->imm = ret + 1;
19870 if (!bpf_map_ptr_unpriv(aux))
19873 /* instead of changing every JIT dealing with tail_call
19874 * emit two extra insns:
19875 * if (index >= max_entries) goto out;
19876 * index &= array->index_mask;
19877 * to avoid out-of-bounds cpu speculation
19879 if (bpf_map_ptr_poisoned(aux)) {
19880 verbose(env, "tail_call abusing map_ptr\n");
19884 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19885 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19886 map_ptr->max_entries, 2);
19887 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19888 container_of(map_ptr,
19891 insn_buf[2] = *insn;
19893 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19898 env->prog = prog = new_prog;
19899 insn = new_prog->insnsi + i + delta;
19903 if (insn->imm == BPF_FUNC_timer_set_callback) {
19904 /* The verifier will process callback_fn as many times as necessary
19905 * with different maps and the register states prepared by
19906 * set_timer_callback_state will be accurate.
19908 * The following use case is valid:
19909 * map1 is shared by prog1, prog2, prog3.
19910 * prog1 calls bpf_timer_init for some map1 elements
19911 * prog2 calls bpf_timer_set_callback for some map1 elements.
19912 * Those that were not bpf_timer_init-ed will return -EINVAL.
19913 * prog3 calls bpf_timer_start for some map1 elements.
19914 * Those that were not both bpf_timer_init-ed and
19915 * bpf_timer_set_callback-ed will return -EINVAL.
19917 struct bpf_insn ld_addrs[2] = {
19918 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19921 insn_buf[0] = ld_addrs[0];
19922 insn_buf[1] = ld_addrs[1];
19923 insn_buf[2] = *insn;
19926 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19931 env->prog = prog = new_prog;
19932 insn = new_prog->insnsi + i + delta;
19933 goto patch_call_imm;
19936 if (is_storage_get_function(insn->imm)) {
19937 if (!in_sleepable(env) ||
19938 env->insn_aux_data[i + delta].storage_get_func_atomic)
19939 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19941 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19942 insn_buf[1] = *insn;
19945 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19950 env->prog = prog = new_prog;
19951 insn = new_prog->insnsi + i + delta;
19952 goto patch_call_imm;
19955 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
19956 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
19957 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
19958 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
19960 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
19961 insn_buf[1] = *insn;
19964 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19969 env->prog = prog = new_prog;
19970 insn = new_prog->insnsi + i + delta;
19971 goto patch_call_imm;
19974 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19975 * and other inlining handlers are currently limited to 64 bit
19978 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19979 (insn->imm == BPF_FUNC_map_lookup_elem ||
19980 insn->imm == BPF_FUNC_map_update_elem ||
19981 insn->imm == BPF_FUNC_map_delete_elem ||
19982 insn->imm == BPF_FUNC_map_push_elem ||
19983 insn->imm == BPF_FUNC_map_pop_elem ||
19984 insn->imm == BPF_FUNC_map_peek_elem ||
19985 insn->imm == BPF_FUNC_redirect_map ||
19986 insn->imm == BPF_FUNC_for_each_map_elem ||
19987 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19988 aux = &env->insn_aux_data[i + delta];
19989 if (bpf_map_ptr_poisoned(aux))
19990 goto patch_call_imm;
19992 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19993 ops = map_ptr->ops;
19994 if (insn->imm == BPF_FUNC_map_lookup_elem &&
19995 ops->map_gen_lookup) {
19996 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19997 if (cnt == -EOPNOTSUPP)
19998 goto patch_map_ops_generic;
19999 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
20000 verbose(env, "bpf verifier is misconfigured\n");
20004 new_prog = bpf_patch_insn_data(env, i + delta,
20010 env->prog = prog = new_prog;
20011 insn = new_prog->insnsi + i + delta;
20015 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
20016 (void *(*)(struct bpf_map *map, void *key))NULL));
20017 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
20018 (long (*)(struct bpf_map *map, void *key))NULL));
20019 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
20020 (long (*)(struct bpf_map *map, void *key, void *value,
20022 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
20023 (long (*)(struct bpf_map *map, void *value,
20025 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
20026 (long (*)(struct bpf_map *map, void *value))NULL));
20027 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
20028 (long (*)(struct bpf_map *map, void *value))NULL));
20029 BUILD_BUG_ON(!__same_type(ops->map_redirect,
20030 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
20031 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
20032 (long (*)(struct bpf_map *map,
20033 bpf_callback_t callback_fn,
20034 void *callback_ctx,
20036 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
20037 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
20039 patch_map_ops_generic:
20040 switch (insn->imm) {
20041 case BPF_FUNC_map_lookup_elem:
20042 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
20044 case BPF_FUNC_map_update_elem:
20045 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
20047 case BPF_FUNC_map_delete_elem:
20048 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
20050 case BPF_FUNC_map_push_elem:
20051 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
20053 case BPF_FUNC_map_pop_elem:
20054 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
20056 case BPF_FUNC_map_peek_elem:
20057 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
20059 case BPF_FUNC_redirect_map:
20060 insn->imm = BPF_CALL_IMM(ops->map_redirect);
20062 case BPF_FUNC_for_each_map_elem:
20063 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
20065 case BPF_FUNC_map_lookup_percpu_elem:
20066 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
20070 goto patch_call_imm;
20073 /* Implement bpf_jiffies64 inline. */
20074 if (prog->jit_requested && BITS_PER_LONG == 64 &&
20075 insn->imm == BPF_FUNC_jiffies64) {
20076 struct bpf_insn ld_jiffies_addr[2] = {
20077 BPF_LD_IMM64(BPF_REG_0,
20078 (unsigned long)&jiffies),
20081 insn_buf[0] = ld_jiffies_addr[0];
20082 insn_buf[1] = ld_jiffies_addr[1];
20083 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
20087 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
20093 env->prog = prog = new_prog;
20094 insn = new_prog->insnsi + i + delta;
20098 /* Implement bpf_get_func_arg inline. */
20099 if (prog_type == BPF_PROG_TYPE_TRACING &&
20100 insn->imm == BPF_FUNC_get_func_arg) {
20101 /* Load nr_args from ctx - 8 */
20102 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20103 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
20104 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
20105 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
20106 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
20107 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
20108 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
20109 insn_buf[7] = BPF_JMP_A(1);
20110 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
20113 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20118 env->prog = prog = new_prog;
20119 insn = new_prog->insnsi + i + delta;
20123 /* Implement bpf_get_func_ret inline. */
20124 if (prog_type == BPF_PROG_TYPE_TRACING &&
20125 insn->imm == BPF_FUNC_get_func_ret) {
20126 if (eatype == BPF_TRACE_FEXIT ||
20127 eatype == BPF_MODIFY_RETURN) {
20128 /* Load nr_args from ctx - 8 */
20129 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20130 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
20131 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
20132 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
20133 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
20134 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
20137 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
20141 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20146 env->prog = prog = new_prog;
20147 insn = new_prog->insnsi + i + delta;
20151 /* Implement get_func_arg_cnt inline. */
20152 if (prog_type == BPF_PROG_TYPE_TRACING &&
20153 insn->imm == BPF_FUNC_get_func_arg_cnt) {
20154 /* Load nr_args from ctx - 8 */
20155 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20157 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
20161 env->prog = prog = new_prog;
20162 insn = new_prog->insnsi + i + delta;
20166 /* Implement bpf_get_func_ip inline. */
20167 if (prog_type == BPF_PROG_TYPE_TRACING &&
20168 insn->imm == BPF_FUNC_get_func_ip) {
20169 /* Load IP address from ctx - 16 */
20170 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
20172 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
20176 env->prog = prog = new_prog;
20177 insn = new_prog->insnsi + i + delta;
20181 /* Implement bpf_kptr_xchg inline */
20182 if (prog->jit_requested && BITS_PER_LONG == 64 &&
20183 insn->imm == BPF_FUNC_kptr_xchg &&
20184 bpf_jit_supports_ptr_xchg()) {
20185 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
20186 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
20189 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20194 env->prog = prog = new_prog;
20195 insn = new_prog->insnsi + i + delta;
20199 fn = env->ops->get_func_proto(insn->imm, env->prog);
20200 /* all functions that have prototype and verifier allowed
20201 * programs to call them, must be real in-kernel functions
20205 "kernel subsystem misconfigured func %s#%d\n",
20206 func_id_name(insn->imm), insn->imm);
20209 insn->imm = fn->func - __bpf_call_base;
20211 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
20212 subprogs[cur_subprog].stack_depth += stack_depth_extra;
20213 subprogs[cur_subprog].stack_extra = stack_depth_extra;
20215 stack_depth = subprogs[cur_subprog].stack_depth;
20216 stack_depth_extra = 0;
20222 env->prog->aux->stack_depth = subprogs[0].stack_depth;
20223 for (i = 0; i < env->subprog_cnt; i++) {
20224 int subprog_start = subprogs[i].start;
20225 int stack_slots = subprogs[i].stack_extra / 8;
20229 if (stack_slots > 1) {
20230 verbose(env, "verifier bug: stack_slots supports may_goto only\n");
20234 /* Add ST insn to subprog prologue to init extra stack */
20235 insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP,
20236 -subprogs[i].stack_depth, BPF_MAX_LOOPS);
20237 /* Copy first actual insn to preserve it */
20238 insn_buf[1] = env->prog->insnsi[subprog_start];
20240 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2);
20243 env->prog = prog = new_prog;
20246 /* Since poke tab is now finalized, publish aux to tracker. */
20247 for (i = 0; i < prog->aux->size_poke_tab; i++) {
20248 map_ptr = prog->aux->poke_tab[i].tail_call.map;
20249 if (!map_ptr->ops->map_poke_track ||
20250 !map_ptr->ops->map_poke_untrack ||
20251 !map_ptr->ops->map_poke_run) {
20252 verbose(env, "bpf verifier is misconfigured\n");
20256 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
20258 verbose(env, "tracking tail call prog failed\n");
20263 sort_kfunc_descs_by_imm_off(env->prog);
20268 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
20271 u32 callback_subprogno,
20274 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
20275 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
20276 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
20277 int reg_loop_max = BPF_REG_6;
20278 int reg_loop_cnt = BPF_REG_7;
20279 int reg_loop_ctx = BPF_REG_8;
20281 struct bpf_prog *new_prog;
20282 u32 callback_start;
20283 u32 call_insn_offset;
20284 s32 callback_offset;
20286 /* This represents an inlined version of bpf_iter.c:bpf_loop,
20287 * be careful to modify this code in sync.
20289 struct bpf_insn insn_buf[] = {
20290 /* Return error and jump to the end of the patch if
20291 * expected number of iterations is too big.
20293 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
20294 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
20295 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
20296 /* spill R6, R7, R8 to use these as loop vars */
20297 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
20298 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
20299 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
20300 /* initialize loop vars */
20301 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
20302 BPF_MOV32_IMM(reg_loop_cnt, 0),
20303 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
20305 * if reg_loop_cnt >= reg_loop_max skip the loop body
20307 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
20309 * correct callback offset would be set after patching
20311 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
20312 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
20314 /* increment loop counter */
20315 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
20316 /* jump to loop header if callback returned 0 */
20317 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
20318 /* return value of bpf_loop,
20319 * set R0 to the number of iterations
20321 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
20322 /* restore original values of R6, R7, R8 */
20323 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
20324 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
20325 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
20328 *cnt = ARRAY_SIZE(insn_buf);
20329 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
20333 /* callback start is known only after patching */
20334 callback_start = env->subprog_info[callback_subprogno].start;
20335 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
20336 call_insn_offset = position + 12;
20337 callback_offset = callback_start - call_insn_offset - 1;
20338 new_prog->insnsi[call_insn_offset].imm = callback_offset;
20343 static bool is_bpf_loop_call(struct bpf_insn *insn)
20345 return insn->code == (BPF_JMP | BPF_CALL) &&
20346 insn->src_reg == 0 &&
20347 insn->imm == BPF_FUNC_loop;
20350 /* For all sub-programs in the program (including main) check
20351 * insn_aux_data to see if there are bpf_loop calls that require
20352 * inlining. If such calls are found the calls are replaced with a
20353 * sequence of instructions produced by `inline_bpf_loop` function and
20354 * subprog stack_depth is increased by the size of 3 registers.
20355 * This stack space is used to spill values of the R6, R7, R8. These
20356 * registers are used to store the loop bound, counter and context
20359 static int optimize_bpf_loop(struct bpf_verifier_env *env)
20361 struct bpf_subprog_info *subprogs = env->subprog_info;
20362 int i, cur_subprog = 0, cnt, delta = 0;
20363 struct bpf_insn *insn = env->prog->insnsi;
20364 int insn_cnt = env->prog->len;
20365 u16 stack_depth = subprogs[cur_subprog].stack_depth;
20366 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20367 u16 stack_depth_extra = 0;
20369 for (i = 0; i < insn_cnt; i++, insn++) {
20370 struct bpf_loop_inline_state *inline_state =
20371 &env->insn_aux_data[i + delta].loop_inline_state;
20373 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
20374 struct bpf_prog *new_prog;
20376 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
20377 new_prog = inline_bpf_loop(env,
20379 -(stack_depth + stack_depth_extra),
20380 inline_state->callback_subprogno,
20386 env->prog = new_prog;
20387 insn = new_prog->insnsi + i + delta;
20390 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
20391 subprogs[cur_subprog].stack_depth += stack_depth_extra;
20393 stack_depth = subprogs[cur_subprog].stack_depth;
20394 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20395 stack_depth_extra = 0;
20399 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20404 static void free_states(struct bpf_verifier_env *env)
20406 struct bpf_verifier_state_list *sl, *sln;
20409 sl = env->free_list;
20412 free_verifier_state(&sl->state, false);
20416 env->free_list = NULL;
20418 if (!env->explored_states)
20421 for (i = 0; i < state_htab_size(env); i++) {
20422 sl = env->explored_states[i];
20426 free_verifier_state(&sl->state, false);
20430 env->explored_states[i] = NULL;
20434 static int do_check_common(struct bpf_verifier_env *env, int subprog)
20436 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20437 struct bpf_subprog_info *sub = subprog_info(env, subprog);
20438 struct bpf_verifier_state *state;
20439 struct bpf_reg_state *regs;
20442 env->prev_linfo = NULL;
20445 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
20448 state->curframe = 0;
20449 state->speculative = false;
20450 state->branches = 1;
20451 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
20452 if (!state->frame[0]) {
20456 env->cur_state = state;
20457 init_func_state(env, state->frame[0],
20458 BPF_MAIN_FUNC /* callsite */,
20461 state->first_insn_idx = env->subprog_info[subprog].start;
20462 state->last_insn_idx = -1;
20464 regs = state->frame[state->curframe]->regs;
20465 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
20466 const char *sub_name = subprog_name(env, subprog);
20467 struct bpf_subprog_arg_info *arg;
20468 struct bpf_reg_state *reg;
20470 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
20471 ret = btf_prepare_func_args(env, subprog);
20475 if (subprog_is_exc_cb(env, subprog)) {
20476 state->frame[0]->in_exception_callback_fn = true;
20477 /* We have already ensured that the callback returns an integer, just
20478 * like all global subprogs. We need to determine it only has a single
20481 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
20482 verbose(env, "exception cb only supports single integer argument\n");
20487 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
20488 arg = &sub->args[i - BPF_REG_1];
20491 if (arg->arg_type == ARG_PTR_TO_CTX) {
20492 reg->type = PTR_TO_CTX;
20493 mark_reg_known_zero(env, regs, i);
20494 } else if (arg->arg_type == ARG_ANYTHING) {
20495 reg->type = SCALAR_VALUE;
20496 mark_reg_unknown(env, regs, i);
20497 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
20498 /* assume unspecial LOCAL dynptr type */
20499 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
20500 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
20501 reg->type = PTR_TO_MEM;
20502 if (arg->arg_type & PTR_MAYBE_NULL)
20503 reg->type |= PTR_MAYBE_NULL;
20504 mark_reg_known_zero(env, regs, i);
20505 reg->mem_size = arg->mem_size;
20506 reg->id = ++env->id_gen;
20507 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
20508 reg->type = PTR_TO_BTF_ID;
20509 if (arg->arg_type & PTR_MAYBE_NULL)
20510 reg->type |= PTR_MAYBE_NULL;
20511 if (arg->arg_type & PTR_UNTRUSTED)
20512 reg->type |= PTR_UNTRUSTED;
20513 if (arg->arg_type & PTR_TRUSTED)
20514 reg->type |= PTR_TRUSTED;
20515 mark_reg_known_zero(env, regs, i);
20516 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
20517 reg->btf_id = arg->btf_id;
20518 reg->id = ++env->id_gen;
20519 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
20520 /* caller can pass either PTR_TO_ARENA or SCALAR */
20521 mark_reg_unknown(env, regs, i);
20523 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
20524 i - BPF_REG_1, arg->arg_type);
20530 /* if main BPF program has associated BTF info, validate that
20531 * it's matching expected signature, and otherwise mark BTF
20532 * info for main program as unreliable
20534 if (env->prog->aux->func_info_aux) {
20535 ret = btf_prepare_func_args(env, 0);
20536 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
20537 env->prog->aux->func_info_aux[0].unreliable = true;
20540 /* 1st arg to a function */
20541 regs[BPF_REG_1].type = PTR_TO_CTX;
20542 mark_reg_known_zero(env, regs, BPF_REG_1);
20545 ret = do_check(env);
20547 /* check for NULL is necessary, since cur_state can be freed inside
20548 * do_check() under memory pressure.
20550 if (env->cur_state) {
20551 free_verifier_state(env->cur_state, true);
20552 env->cur_state = NULL;
20554 while (!pop_stack(env, NULL, NULL, false));
20555 if (!ret && pop_log)
20556 bpf_vlog_reset(&env->log, 0);
20561 /* Lazily verify all global functions based on their BTF, if they are called
20562 * from main BPF program or any of subprograms transitively.
20563 * BPF global subprogs called from dead code are not validated.
20564 * All callable global functions must pass verification.
20565 * Otherwise the whole program is rejected.
20576 * foo() will be verified first for R1=any_scalar_value. During verification it
20577 * will be assumed that bar() already verified successfully and call to bar()
20578 * from foo() will be checked for type match only. Later bar() will be verified
20579 * independently to check that it's safe for R1=any_scalar_value.
20581 static int do_check_subprogs(struct bpf_verifier_env *env)
20583 struct bpf_prog_aux *aux = env->prog->aux;
20584 struct bpf_func_info_aux *sub_aux;
20585 int i, ret, new_cnt;
20587 if (!aux->func_info)
20590 /* exception callback is presumed to be always called */
20591 if (env->exception_callback_subprog)
20592 subprog_aux(env, env->exception_callback_subprog)->called = true;
20596 for (i = 1; i < env->subprog_cnt; i++) {
20597 if (!subprog_is_global(env, i))
20600 sub_aux = subprog_aux(env, i);
20601 if (!sub_aux->called || sub_aux->verified)
20604 env->insn_idx = env->subprog_info[i].start;
20605 WARN_ON_ONCE(env->insn_idx == 0);
20606 ret = do_check_common(env, i);
20609 } else if (env->log.level & BPF_LOG_LEVEL) {
20610 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
20611 i, subprog_name(env, i));
20614 /* We verified new global subprog, it might have called some
20615 * more global subprogs that we haven't verified yet, so we
20616 * need to do another pass over subprogs to verify those.
20618 sub_aux->verified = true;
20622 /* We can't loop forever as we verify at least one global subprog on
20631 static int do_check_main(struct bpf_verifier_env *env)
20636 ret = do_check_common(env, 0);
20638 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20643 static void print_verification_stats(struct bpf_verifier_env *env)
20647 if (env->log.level & BPF_LOG_STATS) {
20648 verbose(env, "verification time %lld usec\n",
20649 div_u64(env->verification_time, 1000));
20650 verbose(env, "stack depth ");
20651 for (i = 0; i < env->subprog_cnt; i++) {
20652 u32 depth = env->subprog_info[i].stack_depth;
20654 verbose(env, "%d", depth);
20655 if (i + 1 < env->subprog_cnt)
20658 verbose(env, "\n");
20660 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
20661 "total_states %d peak_states %d mark_read %d\n",
20662 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
20663 env->max_states_per_insn, env->total_states,
20664 env->peak_states, env->longest_mark_read_walk);
20667 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
20669 const struct btf_type *t, *func_proto;
20670 const struct bpf_struct_ops_desc *st_ops_desc;
20671 const struct bpf_struct_ops *st_ops;
20672 const struct btf_member *member;
20673 struct bpf_prog *prog = env->prog;
20674 u32 btf_id, member_idx;
20678 if (!prog->gpl_compatible) {
20679 verbose(env, "struct ops programs must have a GPL compatible license\n");
20683 if (!prog->aux->attach_btf_id)
20686 btf = prog->aux->attach_btf;
20687 if (btf_is_module(btf)) {
20688 /* Make sure st_ops is valid through the lifetime of env */
20689 env->attach_btf_mod = btf_try_get_module(btf);
20690 if (!env->attach_btf_mod) {
20691 verbose(env, "struct_ops module %s is not found\n",
20692 btf_get_name(btf));
20697 btf_id = prog->aux->attach_btf_id;
20698 st_ops_desc = bpf_struct_ops_find(btf, btf_id);
20699 if (!st_ops_desc) {
20700 verbose(env, "attach_btf_id %u is not a supported struct\n",
20704 st_ops = st_ops_desc->st_ops;
20706 t = st_ops_desc->type;
20707 member_idx = prog->expected_attach_type;
20708 if (member_idx >= btf_type_vlen(t)) {
20709 verbose(env, "attach to invalid member idx %u of struct %s\n",
20710 member_idx, st_ops->name);
20714 member = &btf_type_member(t)[member_idx];
20715 mname = btf_name_by_offset(btf, member->name_off);
20716 func_proto = btf_type_resolve_func_ptr(btf, member->type,
20719 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
20720 mname, member_idx, st_ops->name);
20724 if (st_ops->check_member) {
20725 int err = st_ops->check_member(t, member, prog);
20728 verbose(env, "attach to unsupported member %s of struct %s\n",
20729 mname, st_ops->name);
20734 /* btf_ctx_access() used this to provide argument type info */
20735 prog->aux->ctx_arg_info =
20736 st_ops_desc->arg_info[member_idx].info;
20737 prog->aux->ctx_arg_info_size =
20738 st_ops_desc->arg_info[member_idx].cnt;
20740 prog->aux->attach_func_proto = func_proto;
20741 prog->aux->attach_func_name = mname;
20742 env->ops = st_ops->verifier_ops;
20746 #define SECURITY_PREFIX "security_"
20748 static int check_attach_modify_return(unsigned long addr, const char *func_name)
20750 if (within_error_injection_list(addr) ||
20751 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
20757 /* list of non-sleepable functions that are otherwise on
20758 * ALLOW_ERROR_INJECTION list
20760 BTF_SET_START(btf_non_sleepable_error_inject)
20761 /* Three functions below can be called from sleepable and non-sleepable context.
20762 * Assume non-sleepable from bpf safety point of view.
20764 BTF_ID(func, __filemap_add_folio)
20765 BTF_ID(func, should_fail_alloc_page)
20766 BTF_ID(func, should_failslab)
20767 BTF_SET_END(btf_non_sleepable_error_inject)
20769 static int check_non_sleepable_error_inject(u32 btf_id)
20771 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
20774 int bpf_check_attach_target(struct bpf_verifier_log *log,
20775 const struct bpf_prog *prog,
20776 const struct bpf_prog *tgt_prog,
20778 struct bpf_attach_target_info *tgt_info)
20780 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
20781 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
20782 const char prefix[] = "btf_trace_";
20783 int ret = 0, subprog = -1, i;
20784 const struct btf_type *t;
20785 bool conservative = true;
20789 struct module *mod = NULL;
20792 bpf_log(log, "Tracing programs must provide btf_id\n");
20795 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
20798 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
20801 t = btf_type_by_id(btf, btf_id);
20803 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
20806 tname = btf_name_by_offset(btf, t->name_off);
20808 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
20812 struct bpf_prog_aux *aux = tgt_prog->aux;
20814 if (bpf_prog_is_dev_bound(prog->aux) &&
20815 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
20816 bpf_log(log, "Target program bound device mismatch");
20820 for (i = 0; i < aux->func_info_cnt; i++)
20821 if (aux->func_info[i].type_id == btf_id) {
20825 if (subprog == -1) {
20826 bpf_log(log, "Subprog %s doesn't exist\n", tname);
20829 if (aux->func && aux->func[subprog]->aux->exception_cb) {
20831 "%s programs cannot attach to exception callback\n",
20832 prog_extension ? "Extension" : "FENTRY/FEXIT");
20835 conservative = aux->func_info_aux[subprog].unreliable;
20836 if (prog_extension) {
20837 if (conservative) {
20839 "Cannot replace static functions\n");
20842 if (!prog->jit_requested) {
20844 "Extension programs should be JITed\n");
20848 if (!tgt_prog->jited) {
20849 bpf_log(log, "Can attach to only JITed progs\n");
20852 if (prog_tracing) {
20853 if (aux->attach_tracing_prog) {
20855 * Target program is an fentry/fexit which is already attached
20856 * to another tracing program. More levels of nesting
20857 * attachment are not allowed.
20859 bpf_log(log, "Cannot nest tracing program attach more than once\n");
20862 } else if (tgt_prog->type == prog->type) {
20864 * To avoid potential call chain cycles, prevent attaching of a
20865 * program extension to another extension. It's ok to attach
20866 * fentry/fexit to extension program.
20868 bpf_log(log, "Cannot recursively attach\n");
20871 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
20873 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
20874 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
20875 /* Program extensions can extend all program types
20876 * except fentry/fexit. The reason is the following.
20877 * The fentry/fexit programs are used for performance
20878 * analysis, stats and can be attached to any program
20879 * type. When extension program is replacing XDP function
20880 * it is necessary to allow performance analysis of all
20881 * functions. Both original XDP program and its program
20882 * extension. Hence attaching fentry/fexit to
20883 * BPF_PROG_TYPE_EXT is allowed. If extending of
20884 * fentry/fexit was allowed it would be possible to create
20885 * long call chain fentry->extension->fentry->extension
20886 * beyond reasonable stack size. Hence extending fentry
20889 bpf_log(log, "Cannot extend fentry/fexit\n");
20893 if (prog_extension) {
20894 bpf_log(log, "Cannot replace kernel functions\n");
20899 switch (prog->expected_attach_type) {
20900 case BPF_TRACE_RAW_TP:
20903 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
20906 if (!btf_type_is_typedef(t)) {
20907 bpf_log(log, "attach_btf_id %u is not a typedef\n",
20911 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
20912 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
20916 tname += sizeof(prefix) - 1;
20917 t = btf_type_by_id(btf, t->type);
20918 if (!btf_type_is_ptr(t))
20919 /* should never happen in valid vmlinux build */
20921 t = btf_type_by_id(btf, t->type);
20922 if (!btf_type_is_func_proto(t))
20923 /* should never happen in valid vmlinux build */
20927 case BPF_TRACE_ITER:
20928 if (!btf_type_is_func(t)) {
20929 bpf_log(log, "attach_btf_id %u is not a function\n",
20933 t = btf_type_by_id(btf, t->type);
20934 if (!btf_type_is_func_proto(t))
20936 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20941 if (!prog_extension)
20944 case BPF_MODIFY_RETURN:
20946 case BPF_LSM_CGROUP:
20947 case BPF_TRACE_FENTRY:
20948 case BPF_TRACE_FEXIT:
20949 if (!btf_type_is_func(t)) {
20950 bpf_log(log, "attach_btf_id %u is not a function\n",
20954 if (prog_extension &&
20955 btf_check_type_match(log, prog, btf, t))
20957 t = btf_type_by_id(btf, t->type);
20958 if (!btf_type_is_func_proto(t))
20961 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
20962 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
20963 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
20966 if (tgt_prog && conservative)
20969 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20975 addr = (long) tgt_prog->bpf_func;
20977 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20979 if (btf_is_module(btf)) {
20980 mod = btf_try_get_module(btf);
20982 addr = find_kallsyms_symbol_value(mod, tname);
20986 addr = kallsyms_lookup_name(tname);
20991 "The address of function %s cannot be found\n",
20997 if (prog->sleepable) {
20999 switch (prog->type) {
21000 case BPF_PROG_TYPE_TRACING:
21002 /* fentry/fexit/fmod_ret progs can be sleepable if they are
21003 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
21005 if (!check_non_sleepable_error_inject(btf_id) &&
21006 within_error_injection_list(addr))
21008 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
21009 * in the fmodret id set with the KF_SLEEPABLE flag.
21012 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
21015 if (flags && (*flags & KF_SLEEPABLE))
21019 case BPF_PROG_TYPE_LSM:
21020 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
21021 * Only some of them are sleepable.
21023 if (bpf_lsm_is_sleepable_hook(btf_id))
21031 bpf_log(log, "%s is not sleepable\n", tname);
21034 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
21037 bpf_log(log, "can't modify return codes of BPF programs\n");
21041 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
21042 !check_attach_modify_return(addr, tname))
21046 bpf_log(log, "%s() is not modifiable\n", tname);
21053 tgt_info->tgt_addr = addr;
21054 tgt_info->tgt_name = tname;
21055 tgt_info->tgt_type = t;
21056 tgt_info->tgt_mod = mod;
21060 BTF_SET_START(btf_id_deny)
21063 BTF_ID(func, migrate_disable)
21064 BTF_ID(func, migrate_enable)
21066 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
21067 BTF_ID(func, rcu_read_unlock_strict)
21069 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
21070 BTF_ID(func, preempt_count_add)
21071 BTF_ID(func, preempt_count_sub)
21073 #ifdef CONFIG_PREEMPT_RCU
21074 BTF_ID(func, __rcu_read_lock)
21075 BTF_ID(func, __rcu_read_unlock)
21077 BTF_SET_END(btf_id_deny)
21079 static bool can_be_sleepable(struct bpf_prog *prog)
21081 if (prog->type == BPF_PROG_TYPE_TRACING) {
21082 switch (prog->expected_attach_type) {
21083 case BPF_TRACE_FENTRY:
21084 case BPF_TRACE_FEXIT:
21085 case BPF_MODIFY_RETURN:
21086 case BPF_TRACE_ITER:
21092 return prog->type == BPF_PROG_TYPE_LSM ||
21093 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
21094 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
21097 static int check_attach_btf_id(struct bpf_verifier_env *env)
21099 struct bpf_prog *prog = env->prog;
21100 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
21101 struct bpf_attach_target_info tgt_info = {};
21102 u32 btf_id = prog->aux->attach_btf_id;
21103 struct bpf_trampoline *tr;
21107 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
21108 if (prog->sleepable)
21109 /* attach_btf_id checked to be zero already */
21111 verbose(env, "Syscall programs can only be sleepable\n");
21115 if (prog->sleepable && !can_be_sleepable(prog)) {
21116 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
21120 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
21121 return check_struct_ops_btf_id(env);
21123 if (prog->type != BPF_PROG_TYPE_TRACING &&
21124 prog->type != BPF_PROG_TYPE_LSM &&
21125 prog->type != BPF_PROG_TYPE_EXT)
21128 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
21132 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
21133 /* to make freplace equivalent to their targets, they need to
21134 * inherit env->ops and expected_attach_type for the rest of the
21137 env->ops = bpf_verifier_ops[tgt_prog->type];
21138 prog->expected_attach_type = tgt_prog->expected_attach_type;
21141 /* store info about the attachment target that will be used later */
21142 prog->aux->attach_func_proto = tgt_info.tgt_type;
21143 prog->aux->attach_func_name = tgt_info.tgt_name;
21144 prog->aux->mod = tgt_info.tgt_mod;
21147 prog->aux->saved_dst_prog_type = tgt_prog->type;
21148 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
21151 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
21152 prog->aux->attach_btf_trace = true;
21154 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
21155 if (!bpf_iter_prog_supported(prog))
21160 if (prog->type == BPF_PROG_TYPE_LSM) {
21161 ret = bpf_lsm_verify_prog(&env->log, prog);
21164 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
21165 btf_id_set_contains(&btf_id_deny, btf_id)) {
21169 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
21170 tr = bpf_trampoline_get(key, &tgt_info);
21174 if (tgt_prog && tgt_prog->aux->tail_call_reachable)
21175 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
21177 prog->aux->dst_trampoline = tr;
21181 struct btf *bpf_get_btf_vmlinux(void)
21183 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
21184 mutex_lock(&bpf_verifier_lock);
21186 btf_vmlinux = btf_parse_vmlinux();
21187 mutex_unlock(&bpf_verifier_lock);
21189 return btf_vmlinux;
21192 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
21194 u64 start_time = ktime_get_ns();
21195 struct bpf_verifier_env *env;
21196 int i, len, ret = -EINVAL, err;
21200 /* no program is valid */
21201 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
21204 /* 'struct bpf_verifier_env' can be global, but since it's not small,
21205 * allocate/free it every time bpf_check() is called
21207 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
21213 len = (*prog)->len;
21214 env->insn_aux_data =
21215 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
21217 if (!env->insn_aux_data)
21219 for (i = 0; i < len; i++)
21220 env->insn_aux_data[i].orig_idx = i;
21222 env->ops = bpf_verifier_ops[env->prog->type];
21223 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
21225 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
21226 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
21227 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
21228 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
21229 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
21231 bpf_get_btf_vmlinux();
21233 /* grab the mutex to protect few globals used by verifier */
21235 mutex_lock(&bpf_verifier_lock);
21237 /* user could have requested verbose verifier output
21238 * and supplied buffer to store the verification trace
21240 ret = bpf_vlog_init(&env->log, attr->log_level,
21241 (char __user *) (unsigned long) attr->log_buf,
21246 mark_verifier_state_clean(env);
21248 if (IS_ERR(btf_vmlinux)) {
21249 /* Either gcc or pahole or kernel are broken. */
21250 verbose(env, "in-kernel BTF is malformed\n");
21251 ret = PTR_ERR(btf_vmlinux);
21252 goto skip_full_check;
21255 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
21256 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
21257 env->strict_alignment = true;
21258 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
21259 env->strict_alignment = false;
21262 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
21263 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
21265 env->explored_states = kvcalloc(state_htab_size(env),
21266 sizeof(struct bpf_verifier_state_list *),
21269 if (!env->explored_states)
21270 goto skip_full_check;
21272 ret = check_btf_info_early(env, attr, uattr);
21274 goto skip_full_check;
21276 ret = add_subprog_and_kfunc(env);
21278 goto skip_full_check;
21280 ret = check_subprogs(env);
21282 goto skip_full_check;
21284 ret = check_btf_info(env, attr, uattr);
21286 goto skip_full_check;
21288 ret = check_attach_btf_id(env);
21290 goto skip_full_check;
21292 ret = resolve_pseudo_ldimm64(env);
21294 goto skip_full_check;
21296 if (bpf_prog_is_offloaded(env->prog->aux)) {
21297 ret = bpf_prog_offload_verifier_prep(env->prog);
21299 goto skip_full_check;
21302 ret = check_cfg(env);
21304 goto skip_full_check;
21306 ret = do_check_main(env);
21307 ret = ret ?: do_check_subprogs(env);
21309 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
21310 ret = bpf_prog_offload_finalize(env);
21313 kvfree(env->explored_states);
21316 ret = check_max_stack_depth(env);
21318 /* instruction rewrites happen after this point */
21320 ret = optimize_bpf_loop(env);
21324 opt_hard_wire_dead_code_branches(env);
21326 ret = opt_remove_dead_code(env);
21328 ret = opt_remove_nops(env);
21331 sanitize_dead_code(env);
21335 /* program is valid, convert *(u32*)(ctx + off) accesses */
21336 ret = convert_ctx_accesses(env);
21339 ret = do_misc_fixups(env);
21341 /* do 32-bit optimization after insn patching has done so those patched
21342 * insns could be handled correctly.
21344 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
21345 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
21346 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
21351 ret = fixup_call_args(env);
21353 env->verification_time = ktime_get_ns() - start_time;
21354 print_verification_stats(env);
21355 env->prog->aux->verified_insns = env->insn_processed;
21357 /* preserve original error even if log finalization is successful */
21358 err = bpf_vlog_finalize(&env->log, &log_true_size);
21362 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
21363 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
21364 &log_true_size, sizeof(log_true_size))) {
21366 goto err_release_maps;
21370 goto err_release_maps;
21372 if (env->used_map_cnt) {
21373 /* if program passed verifier, update used_maps in bpf_prog_info */
21374 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
21375 sizeof(env->used_maps[0]),
21378 if (!env->prog->aux->used_maps) {
21380 goto err_release_maps;
21383 memcpy(env->prog->aux->used_maps, env->used_maps,
21384 sizeof(env->used_maps[0]) * env->used_map_cnt);
21385 env->prog->aux->used_map_cnt = env->used_map_cnt;
21387 if (env->used_btf_cnt) {
21388 /* if program passed verifier, update used_btfs in bpf_prog_aux */
21389 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
21390 sizeof(env->used_btfs[0]),
21392 if (!env->prog->aux->used_btfs) {
21394 goto err_release_maps;
21397 memcpy(env->prog->aux->used_btfs, env->used_btfs,
21398 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
21399 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
21401 if (env->used_map_cnt || env->used_btf_cnt) {
21402 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
21403 * bpf_ld_imm64 instructions
21405 convert_pseudo_ld_imm64(env);
21408 adjust_btf_func(env);
21411 if (!env->prog->aux->used_maps)
21412 /* if we didn't copy map pointers into bpf_prog_info, release
21413 * them now. Otherwise free_used_maps() will release them.
21416 if (!env->prog->aux->used_btfs)
21419 /* extension progs temporarily inherit the attach_type of their targets
21420 for verification purposes, so set it back to zero before returning
21422 if (env->prog->type == BPF_PROG_TYPE_EXT)
21423 env->prog->expected_attach_type = 0;
21427 module_put(env->attach_btf_mod);
21430 mutex_unlock(&bpf_verifier_lock);
21431 vfree(env->insn_aux_data);