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 u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5687 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5688 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5689 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5691 [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5694 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5696 /* A referenced register is always trusted. */
5697 if (reg->ref_obj_id)
5700 /* Types listed in the reg2btf_ids are always trusted */
5701 if (reg2btf_ids[base_type(reg->type)])
5704 /* If a register is not referenced, it is trusted if it has the
5705 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5706 * other type modifiers may be safe, but we elect to take an opt-in
5707 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5710 * Eventually, we should make PTR_TRUSTED the single source of truth
5711 * for whether a register is trusted.
5713 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5714 !bpf_type_has_unsafe_modifiers(reg->type);
5717 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5719 return reg->type & MEM_RCU;
5722 static void clear_trusted_flags(enum bpf_type_flag *flag)
5724 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5727 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5728 const struct bpf_reg_state *reg,
5729 int off, int size, bool strict)
5731 struct tnum reg_off;
5734 /* Byte size accesses are always allowed. */
5735 if (!strict || size == 1)
5738 /* For platforms that do not have a Kconfig enabling
5739 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5740 * NET_IP_ALIGN is universally set to '2'. And on platforms
5741 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5742 * to this code only in strict mode where we want to emulate
5743 * the NET_IP_ALIGN==2 checking. Therefore use an
5744 * unconditional IP align value of '2'.
5748 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5749 if (!tnum_is_aligned(reg_off, size)) {
5752 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5754 "misaligned packet access off %d+%s+%d+%d size %d\n",
5755 ip_align, tn_buf, reg->off, off, size);
5762 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5763 const struct bpf_reg_state *reg,
5764 const char *pointer_desc,
5765 int off, int size, bool strict)
5767 struct tnum reg_off;
5769 /* Byte size accesses are always allowed. */
5770 if (!strict || size == 1)
5773 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5774 if (!tnum_is_aligned(reg_off, size)) {
5777 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5778 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5779 pointer_desc, tn_buf, reg->off, off, size);
5786 static int check_ptr_alignment(struct bpf_verifier_env *env,
5787 const struct bpf_reg_state *reg, int off,
5788 int size, bool strict_alignment_once)
5790 bool strict = env->strict_alignment || strict_alignment_once;
5791 const char *pointer_desc = "";
5793 switch (reg->type) {
5795 case PTR_TO_PACKET_META:
5796 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5797 * right in front, treat it the very same way.
5799 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5800 case PTR_TO_FLOW_KEYS:
5801 pointer_desc = "flow keys ";
5803 case PTR_TO_MAP_KEY:
5804 pointer_desc = "key ";
5806 case PTR_TO_MAP_VALUE:
5807 pointer_desc = "value ";
5810 pointer_desc = "context ";
5813 pointer_desc = "stack ";
5814 /* The stack spill tracking logic in check_stack_write_fixed_off()
5815 * and check_stack_read_fixed_off() relies on stack accesses being
5821 pointer_desc = "sock ";
5823 case PTR_TO_SOCK_COMMON:
5824 pointer_desc = "sock_common ";
5826 case PTR_TO_TCP_SOCK:
5827 pointer_desc = "tcp_sock ";
5829 case PTR_TO_XDP_SOCK:
5830 pointer_desc = "xdp_sock ";
5837 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5841 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
5843 if (env->prog->jit_requested)
5844 return round_up(stack_depth, 16);
5846 /* round up to 32-bytes, since this is granularity
5847 * of interpreter stack size
5849 return round_up(max_t(u32, stack_depth, 1), 32);
5852 /* starting from main bpf function walk all instructions of the function
5853 * and recursively walk all callees that given function can call.
5854 * Ignore jump and exit insns.
5855 * Since recursion is prevented by check_cfg() this algorithm
5856 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5858 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5860 struct bpf_subprog_info *subprog = env->subprog_info;
5861 struct bpf_insn *insn = env->prog->insnsi;
5862 int depth = 0, frame = 0, i, subprog_end;
5863 bool tail_call_reachable = false;
5864 int ret_insn[MAX_CALL_FRAMES];
5865 int ret_prog[MAX_CALL_FRAMES];
5868 i = subprog[idx].start;
5870 /* protect against potential stack overflow that might happen when
5871 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5872 * depth for such case down to 256 so that the worst case scenario
5873 * would result in 8k stack size (32 which is tailcall limit * 256 =
5876 * To get the idea what might happen, see an example:
5877 * func1 -> sub rsp, 128
5878 * subfunc1 -> sub rsp, 256
5879 * tailcall1 -> add rsp, 256
5880 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5881 * subfunc2 -> sub rsp, 64
5882 * subfunc22 -> sub rsp, 128
5883 * tailcall2 -> add rsp, 128
5884 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5886 * tailcall will unwind the current stack frame but it will not get rid
5887 * of caller's stack as shown on the example above.
5889 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5891 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5895 depth += round_up_stack_depth(env, subprog[idx].stack_depth);
5896 if (depth > MAX_BPF_STACK) {
5897 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5902 subprog_end = subprog[idx + 1].start;
5903 for (; i < subprog_end; i++) {
5904 int next_insn, sidx;
5906 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5909 if (!is_bpf_throw_kfunc(insn + i))
5911 if (subprog[idx].is_cb)
5913 for (int c = 0; c < frame && !err; c++) {
5914 if (subprog[ret_prog[c]].is_cb) {
5922 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5927 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5929 /* remember insn and function to return to */
5930 ret_insn[frame] = i + 1;
5931 ret_prog[frame] = idx;
5933 /* find the callee */
5934 next_insn = i + insn[i].imm + 1;
5935 sidx = find_subprog(env, next_insn);
5937 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5941 if (subprog[sidx].is_async_cb) {
5942 if (subprog[sidx].has_tail_call) {
5943 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5946 /* async callbacks don't increase bpf prog stack size unless called directly */
5947 if (!bpf_pseudo_call(insn + i))
5949 if (subprog[sidx].is_exception_cb) {
5950 verbose(env, "insn %d cannot call exception cb directly\n", i);
5957 if (subprog[idx].has_tail_call)
5958 tail_call_reachable = true;
5961 if (frame >= MAX_CALL_FRAMES) {
5962 verbose(env, "the call stack of %d frames is too deep !\n",
5968 /* if tail call got detected across bpf2bpf calls then mark each of the
5969 * currently present subprog frames as tail call reachable subprogs;
5970 * this info will be utilized by JIT so that we will be preserving the
5971 * tail call counter throughout bpf2bpf calls combined with tailcalls
5973 if (tail_call_reachable)
5974 for (j = 0; j < frame; j++) {
5975 if (subprog[ret_prog[j]].is_exception_cb) {
5976 verbose(env, "cannot tail call within exception cb\n");
5979 subprog[ret_prog[j]].tail_call_reachable = true;
5981 if (subprog[0].tail_call_reachable)
5982 env->prog->aux->tail_call_reachable = true;
5984 /* end of for() loop means the last insn of the 'subprog'
5985 * was reached. Doesn't matter whether it was JA or EXIT
5989 depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
5991 i = ret_insn[frame];
5992 idx = ret_prog[frame];
5996 static int check_max_stack_depth(struct bpf_verifier_env *env)
5998 struct bpf_subprog_info *si = env->subprog_info;
6001 for (int i = 0; i < env->subprog_cnt; i++) {
6002 if (!i || si[i].is_async_cb) {
6003 ret = check_max_stack_depth_subprog(env, i);
6012 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6013 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6014 const struct bpf_insn *insn, int idx)
6016 int start = idx + insn->imm + 1, subprog;
6018 subprog = find_subprog(env, start);
6020 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6024 return env->subprog_info[subprog].stack_depth;
6028 static int __check_buffer_access(struct bpf_verifier_env *env,
6029 const char *buf_info,
6030 const struct bpf_reg_state *reg,
6031 int regno, int off, int size)
6035 "R%d invalid %s buffer access: off=%d, size=%d\n",
6036 regno, buf_info, off, size);
6039 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6042 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6044 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6045 regno, off, tn_buf);
6052 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6053 const struct bpf_reg_state *reg,
6054 int regno, int off, int size)
6058 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6062 if (off + size > env->prog->aux->max_tp_access)
6063 env->prog->aux->max_tp_access = off + size;
6068 static int check_buffer_access(struct bpf_verifier_env *env,
6069 const struct bpf_reg_state *reg,
6070 int regno, int off, int size,
6071 bool zero_size_allowed,
6074 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6077 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6081 if (off + size > *max_access)
6082 *max_access = off + size;
6087 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6088 static void zext_32_to_64(struct bpf_reg_state *reg)
6090 reg->var_off = tnum_subreg(reg->var_off);
6091 __reg_assign_32_into_64(reg);
6094 /* truncate register to smaller size (in bytes)
6095 * must be called with size < BPF_REG_SIZE
6097 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6101 /* clear high bits in bit representation */
6102 reg->var_off = tnum_cast(reg->var_off, size);
6104 /* fix arithmetic bounds */
6105 mask = ((u64)1 << (size * 8)) - 1;
6106 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6107 reg->umin_value &= mask;
6108 reg->umax_value &= mask;
6110 reg->umin_value = 0;
6111 reg->umax_value = mask;
6113 reg->smin_value = reg->umin_value;
6114 reg->smax_value = reg->umax_value;
6116 /* If size is smaller than 32bit register the 32bit register
6117 * values are also truncated so we push 64-bit bounds into
6118 * 32-bit bounds. Above were truncated < 32-bits already.
6121 __mark_reg32_unbounded(reg);
6123 reg_bounds_sync(reg);
6126 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6129 reg->smin_value = reg->s32_min_value = S8_MIN;
6130 reg->smax_value = reg->s32_max_value = S8_MAX;
6131 } else if (size == 2) {
6132 reg->smin_value = reg->s32_min_value = S16_MIN;
6133 reg->smax_value = reg->s32_max_value = S16_MAX;
6136 reg->smin_value = reg->s32_min_value = S32_MIN;
6137 reg->smax_value = reg->s32_max_value = S32_MAX;
6139 reg->umin_value = reg->u32_min_value = 0;
6140 reg->umax_value = U64_MAX;
6141 reg->u32_max_value = U32_MAX;
6142 reg->var_off = tnum_unknown;
6145 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6147 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6148 u64 top_smax_value, top_smin_value;
6149 u64 num_bits = size * 8;
6151 if (tnum_is_const(reg->var_off)) {
6152 u64_cval = reg->var_off.value;
6154 reg->var_off = tnum_const((s8)u64_cval);
6156 reg->var_off = tnum_const((s16)u64_cval);
6159 reg->var_off = tnum_const((s32)u64_cval);
6161 u64_cval = reg->var_off.value;
6162 reg->smax_value = reg->smin_value = u64_cval;
6163 reg->umax_value = reg->umin_value = u64_cval;
6164 reg->s32_max_value = reg->s32_min_value = u64_cval;
6165 reg->u32_max_value = reg->u32_min_value = u64_cval;
6169 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6170 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6172 if (top_smax_value != top_smin_value)
6175 /* find the s64_min and s64_min after sign extension */
6177 init_s64_max = (s8)reg->smax_value;
6178 init_s64_min = (s8)reg->smin_value;
6179 } else if (size == 2) {
6180 init_s64_max = (s16)reg->smax_value;
6181 init_s64_min = (s16)reg->smin_value;
6183 init_s64_max = (s32)reg->smax_value;
6184 init_s64_min = (s32)reg->smin_value;
6187 s64_max = max(init_s64_max, init_s64_min);
6188 s64_min = min(init_s64_max, init_s64_min);
6190 /* both of s64_max/s64_min positive or negative */
6191 if ((s64_max >= 0) == (s64_min >= 0)) {
6192 reg->smin_value = reg->s32_min_value = s64_min;
6193 reg->smax_value = reg->s32_max_value = s64_max;
6194 reg->umin_value = reg->u32_min_value = s64_min;
6195 reg->umax_value = reg->u32_max_value = s64_max;
6196 reg->var_off = tnum_range(s64_min, s64_max);
6201 set_sext64_default_val(reg, size);
6204 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6207 reg->s32_min_value = S8_MIN;
6208 reg->s32_max_value = S8_MAX;
6211 reg->s32_min_value = S16_MIN;
6212 reg->s32_max_value = S16_MAX;
6214 reg->u32_min_value = 0;
6215 reg->u32_max_value = U32_MAX;
6218 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6220 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6221 u32 top_smax_value, top_smin_value;
6222 u32 num_bits = size * 8;
6224 if (tnum_is_const(reg->var_off)) {
6225 u32_val = reg->var_off.value;
6227 reg->var_off = tnum_const((s8)u32_val);
6229 reg->var_off = tnum_const((s16)u32_val);
6231 u32_val = reg->var_off.value;
6232 reg->s32_min_value = reg->s32_max_value = u32_val;
6233 reg->u32_min_value = reg->u32_max_value = u32_val;
6237 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6238 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6240 if (top_smax_value != top_smin_value)
6243 /* find the s32_min and s32_min after sign extension */
6245 init_s32_max = (s8)reg->s32_max_value;
6246 init_s32_min = (s8)reg->s32_min_value;
6249 init_s32_max = (s16)reg->s32_max_value;
6250 init_s32_min = (s16)reg->s32_min_value;
6252 s32_max = max(init_s32_max, init_s32_min);
6253 s32_min = min(init_s32_max, init_s32_min);
6255 if ((s32_min >= 0) == (s32_max >= 0)) {
6256 reg->s32_min_value = s32_min;
6257 reg->s32_max_value = s32_max;
6258 reg->u32_min_value = (u32)s32_min;
6259 reg->u32_max_value = (u32)s32_max;
6264 set_sext32_default_val(reg, size);
6267 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6269 /* A map is considered read-only if the following condition are true:
6271 * 1) BPF program side cannot change any of the map content. The
6272 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6273 * and was set at map creation time.
6274 * 2) The map value(s) have been initialized from user space by a
6275 * loader and then "frozen", such that no new map update/delete
6276 * operations from syscall side are possible for the rest of
6277 * the map's lifetime from that point onwards.
6278 * 3) Any parallel/pending map update/delete operations from syscall
6279 * side have been completed. Only after that point, it's safe to
6280 * assume that map value(s) are immutable.
6282 return (map->map_flags & BPF_F_RDONLY_PROG) &&
6283 READ_ONCE(map->frozen) &&
6284 !bpf_map_write_active(map);
6287 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6294 err = map->ops->map_direct_value_addr(map, &addr, off);
6297 ptr = (void *)(long)addr + off;
6301 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6304 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6307 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6318 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
6319 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
6320 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
6323 * Allow list few fields as RCU trusted or full trusted.
6324 * This logic doesn't allow mix tagging and will be removed once GCC supports
6328 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6329 BTF_TYPE_SAFE_RCU(struct task_struct) {
6330 const cpumask_t *cpus_ptr;
6331 struct css_set __rcu *cgroups;
6332 struct task_struct __rcu *real_parent;
6333 struct task_struct *group_leader;
6336 BTF_TYPE_SAFE_RCU(struct cgroup) {
6337 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6338 struct kernfs_node *kn;
6341 BTF_TYPE_SAFE_RCU(struct css_set) {
6342 struct cgroup *dfl_cgrp;
6345 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6346 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6347 struct file __rcu *exe_file;
6350 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6351 * because bpf prog accessible sockets are SOCK_RCU_FREE.
6353 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6357 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6361 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6362 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6363 struct seq_file *seq;
6366 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6367 struct bpf_iter_meta *meta;
6368 struct task_struct *task;
6371 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6375 BTF_TYPE_SAFE_TRUSTED(struct file) {
6376 struct inode *f_inode;
6379 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6380 /* no negative dentry-s in places where bpf can see it */
6381 struct inode *d_inode;
6384 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6388 static bool type_is_rcu(struct bpf_verifier_env *env,
6389 struct bpf_reg_state *reg,
6390 const char *field_name, u32 btf_id)
6392 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6393 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6394 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6396 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6399 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6400 struct bpf_reg_state *reg,
6401 const char *field_name, u32 btf_id)
6403 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6404 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6405 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6407 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6410 static bool type_is_trusted(struct bpf_verifier_env *env,
6411 struct bpf_reg_state *reg,
6412 const char *field_name, u32 btf_id)
6414 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6415 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6416 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6417 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6418 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6419 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6421 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6424 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6425 struct bpf_reg_state *regs,
6426 int regno, int off, int size,
6427 enum bpf_access_type atype,
6430 struct bpf_reg_state *reg = regs + regno;
6431 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6432 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6433 const char *field_name = NULL;
6434 enum bpf_type_flag flag = 0;
6438 if (!env->allow_ptr_leaks) {
6440 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6444 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6446 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6452 "R%d is ptr_%s invalid negative access: off=%d\n",
6456 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6459 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6461 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6462 regno, tname, off, tn_buf);
6466 if (reg->type & MEM_USER) {
6468 "R%d is ptr_%s access user memory: off=%d\n",
6473 if (reg->type & MEM_PERCPU) {
6475 "R%d is ptr_%s access percpu memory: off=%d\n",
6480 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6481 if (!btf_is_kernel(reg->btf)) {
6482 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6485 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6487 /* Writes are permitted with default btf_struct_access for
6488 * program allocated objects (which always have ref_obj_id > 0),
6489 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6491 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6492 verbose(env, "only read is supported\n");
6496 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6497 !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6498 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6502 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6508 if (ret != PTR_TO_BTF_ID) {
6511 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6512 /* If this is an untrusted pointer, all pointers formed by walking it
6513 * also inherit the untrusted flag.
6515 flag = PTR_UNTRUSTED;
6517 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6518 /* By default any pointer obtained from walking a trusted pointer is no
6519 * longer trusted, unless the field being accessed has explicitly been
6520 * marked as inheriting its parent's state of trust (either full or RCU).
6522 * 'cgroups' pointer is untrusted if task->cgroups dereference
6523 * happened in a sleepable program outside of bpf_rcu_read_lock()
6524 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6525 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6527 * A regular RCU-protected pointer with __rcu tag can also be deemed
6528 * trusted if we are in an RCU CS. Such pointer can be NULL.
6530 if (type_is_trusted(env, reg, field_name, btf_id)) {
6531 flag |= PTR_TRUSTED;
6532 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6533 if (type_is_rcu(env, reg, field_name, btf_id)) {
6534 /* ignore __rcu tag and mark it MEM_RCU */
6536 } else if (flag & MEM_RCU ||
6537 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6538 /* __rcu tagged pointers can be NULL */
6539 flag |= MEM_RCU | PTR_MAYBE_NULL;
6541 /* We always trust them */
6542 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6543 flag & PTR_UNTRUSTED)
6544 flag &= ~PTR_UNTRUSTED;
6545 } else if (flag & (MEM_PERCPU | MEM_USER)) {
6548 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6549 clear_trusted_flags(&flag);
6553 * If not in RCU CS or MEM_RCU pointer can be NULL then
6554 * aggressively mark as untrusted otherwise such
6555 * pointers will be plain PTR_TO_BTF_ID without flags
6556 * and will be allowed to be passed into helpers for
6559 flag = PTR_UNTRUSTED;
6562 /* Old compat. Deprecated */
6563 clear_trusted_flags(&flag);
6566 if (atype == BPF_READ && value_regno >= 0)
6567 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6572 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6573 struct bpf_reg_state *regs,
6574 int regno, int off, int size,
6575 enum bpf_access_type atype,
6578 struct bpf_reg_state *reg = regs + regno;
6579 struct bpf_map *map = reg->map_ptr;
6580 struct bpf_reg_state map_reg;
6581 enum bpf_type_flag flag = 0;
6582 const struct btf_type *t;
6588 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6592 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6593 verbose(env, "map_ptr access not supported for map type %d\n",
6598 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6599 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6601 if (!env->allow_ptr_leaks) {
6603 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6609 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6614 if (atype != BPF_READ) {
6615 verbose(env, "only read from %s is supported\n", tname);
6619 /* Simulate access to a PTR_TO_BTF_ID */
6620 memset(&map_reg, 0, sizeof(map_reg));
6621 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6622 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6626 if (value_regno >= 0)
6627 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6632 /* Check that the stack access at the given offset is within bounds. The
6633 * maximum valid offset is -1.
6635 * The minimum valid offset is -MAX_BPF_STACK for writes, and
6636 * -state->allocated_stack for reads.
6638 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6640 struct bpf_func_state *state,
6641 enum bpf_access_type t)
6645 if (t == BPF_WRITE || env->allow_uninit_stack)
6646 min_valid_off = -MAX_BPF_STACK;
6648 min_valid_off = -state->allocated_stack;
6650 if (off < min_valid_off || off > -1)
6655 /* Check that the stack access at 'regno + off' falls within the maximum stack
6658 * 'off' includes `regno->offset`, but not its dynamic part (if any).
6660 static int check_stack_access_within_bounds(
6661 struct bpf_verifier_env *env,
6662 int regno, int off, int access_size,
6663 enum bpf_access_src src, enum bpf_access_type type)
6665 struct bpf_reg_state *regs = cur_regs(env);
6666 struct bpf_reg_state *reg = regs + regno;
6667 struct bpf_func_state *state = func(env, reg);
6668 s64 min_off, max_off;
6672 if (src == ACCESS_HELPER)
6673 /* We don't know if helpers are reading or writing (or both). */
6674 err_extra = " indirect access to";
6675 else if (type == BPF_READ)
6676 err_extra = " read from";
6678 err_extra = " write to";
6680 if (tnum_is_const(reg->var_off)) {
6681 min_off = (s64)reg->var_off.value + off;
6682 max_off = min_off + access_size;
6684 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6685 reg->smin_value <= -BPF_MAX_VAR_OFF) {
6686 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6690 min_off = reg->smin_value + off;
6691 max_off = reg->smax_value + off + access_size;
6694 err = check_stack_slot_within_bounds(env, min_off, state, type);
6695 if (!err && max_off > 0)
6696 err = -EINVAL; /* out of stack access into non-negative offsets */
6699 if (tnum_is_const(reg->var_off)) {
6700 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6701 err_extra, regno, off, access_size);
6705 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6706 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
6707 err_extra, regno, tn_buf, off, access_size);
6712 /* Note that there is no stack access with offset zero, so the needed stack
6713 * size is -min_off, not -min_off+1.
6715 return grow_stack_state(env, state, -min_off /* size */);
6718 /* check whether memory at (regno + off) is accessible for t = (read | write)
6719 * if t==write, value_regno is a register which value is stored into memory
6720 * if t==read, value_regno is a register which will receive the value from memory
6721 * if t==write && value_regno==-1, some unknown value is stored into memory
6722 * if t==read && value_regno==-1, don't care what we read from memory
6724 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6725 int off, int bpf_size, enum bpf_access_type t,
6726 int value_regno, bool strict_alignment_once, bool is_ldsx)
6728 struct bpf_reg_state *regs = cur_regs(env);
6729 struct bpf_reg_state *reg = regs + regno;
6732 size = bpf_size_to_bytes(bpf_size);
6736 /* alignment checks will add in reg->off themselves */
6737 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6741 /* for access checks, reg->off is just part of off */
6744 if (reg->type == PTR_TO_MAP_KEY) {
6745 if (t == BPF_WRITE) {
6746 verbose(env, "write to change key R%d not allowed\n", regno);
6750 err = check_mem_region_access(env, regno, off, size,
6751 reg->map_ptr->key_size, false);
6754 if (value_regno >= 0)
6755 mark_reg_unknown(env, regs, value_regno);
6756 } else if (reg->type == PTR_TO_MAP_VALUE) {
6757 struct btf_field *kptr_field = NULL;
6759 if (t == BPF_WRITE && value_regno >= 0 &&
6760 is_pointer_value(env, value_regno)) {
6761 verbose(env, "R%d leaks addr into map\n", value_regno);
6764 err = check_map_access_type(env, regno, off, size, t);
6767 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6770 if (tnum_is_const(reg->var_off))
6771 kptr_field = btf_record_find(reg->map_ptr->record,
6772 off + reg->var_off.value, BPF_KPTR);
6774 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6775 } else if (t == BPF_READ && value_regno >= 0) {
6776 struct bpf_map *map = reg->map_ptr;
6778 /* if map is read-only, track its contents as scalars */
6779 if (tnum_is_const(reg->var_off) &&
6780 bpf_map_is_rdonly(map) &&
6781 map->ops->map_direct_value_addr) {
6782 int map_off = off + reg->var_off.value;
6785 err = bpf_map_direct_read(map, map_off, size,
6790 regs[value_regno].type = SCALAR_VALUE;
6791 __mark_reg_known(®s[value_regno], val);
6793 mark_reg_unknown(env, regs, value_regno);
6796 } else if (base_type(reg->type) == PTR_TO_MEM) {
6797 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6799 if (type_may_be_null(reg->type)) {
6800 verbose(env, "R%d invalid mem access '%s'\n", regno,
6801 reg_type_str(env, reg->type));
6805 if (t == BPF_WRITE && rdonly_mem) {
6806 verbose(env, "R%d cannot write into %s\n",
6807 regno, reg_type_str(env, reg->type));
6811 if (t == BPF_WRITE && value_regno >= 0 &&
6812 is_pointer_value(env, value_regno)) {
6813 verbose(env, "R%d leaks addr into mem\n", value_regno);
6817 err = check_mem_region_access(env, regno, off, size,
6818 reg->mem_size, false);
6819 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6820 mark_reg_unknown(env, regs, value_regno);
6821 } else if (reg->type == PTR_TO_CTX) {
6822 enum bpf_reg_type reg_type = SCALAR_VALUE;
6823 struct btf *btf = NULL;
6826 if (t == BPF_WRITE && value_regno >= 0 &&
6827 is_pointer_value(env, value_regno)) {
6828 verbose(env, "R%d leaks addr into ctx\n", value_regno);
6832 err = check_ptr_off_reg(env, reg, regno);
6836 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
6839 verbose_linfo(env, insn_idx, "; ");
6840 if (!err && t == BPF_READ && value_regno >= 0) {
6841 /* ctx access returns either a scalar, or a
6842 * PTR_TO_PACKET[_META,_END]. In the latter
6843 * case, we know the offset is zero.
6845 if (reg_type == SCALAR_VALUE) {
6846 mark_reg_unknown(env, regs, value_regno);
6848 mark_reg_known_zero(env, regs,
6850 if (type_may_be_null(reg_type))
6851 regs[value_regno].id = ++env->id_gen;
6852 /* A load of ctx field could have different
6853 * actual load size with the one encoded in the
6854 * insn. When the dst is PTR, it is for sure not
6857 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6858 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6859 regs[value_regno].btf = btf;
6860 regs[value_regno].btf_id = btf_id;
6863 regs[value_regno].type = reg_type;
6866 } else if (reg->type == PTR_TO_STACK) {
6867 /* Basic bounds checks. */
6868 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6873 err = check_stack_read(env, regno, off, size,
6876 err = check_stack_write(env, regno, off, size,
6877 value_regno, insn_idx);
6878 } else if (reg_is_pkt_pointer(reg)) {
6879 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6880 verbose(env, "cannot write into packet\n");
6883 if (t == BPF_WRITE && value_regno >= 0 &&
6884 is_pointer_value(env, value_regno)) {
6885 verbose(env, "R%d leaks addr into packet\n",
6889 err = check_packet_access(env, regno, off, size, false);
6890 if (!err && t == BPF_READ && value_regno >= 0)
6891 mark_reg_unknown(env, regs, value_regno);
6892 } else if (reg->type == PTR_TO_FLOW_KEYS) {
6893 if (t == BPF_WRITE && value_regno >= 0 &&
6894 is_pointer_value(env, value_regno)) {
6895 verbose(env, "R%d leaks addr into flow keys\n",
6900 err = check_flow_keys_access(env, off, size);
6901 if (!err && t == BPF_READ && value_regno >= 0)
6902 mark_reg_unknown(env, regs, value_regno);
6903 } else if (type_is_sk_pointer(reg->type)) {
6904 if (t == BPF_WRITE) {
6905 verbose(env, "R%d cannot write into %s\n",
6906 regno, reg_type_str(env, reg->type));
6909 err = check_sock_access(env, insn_idx, regno, off, size, t);
6910 if (!err && value_regno >= 0)
6911 mark_reg_unknown(env, regs, value_regno);
6912 } else if (reg->type == PTR_TO_TP_BUFFER) {
6913 err = check_tp_buffer_access(env, reg, regno, off, size);
6914 if (!err && t == BPF_READ && value_regno >= 0)
6915 mark_reg_unknown(env, regs, value_regno);
6916 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6917 !type_may_be_null(reg->type)) {
6918 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6920 } else if (reg->type == CONST_PTR_TO_MAP) {
6921 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6923 } else if (base_type(reg->type) == PTR_TO_BUF) {
6924 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6928 if (t == BPF_WRITE) {
6929 verbose(env, "R%d cannot write into %s\n",
6930 regno, reg_type_str(env, reg->type));
6933 max_access = &env->prog->aux->max_rdonly_access;
6935 max_access = &env->prog->aux->max_rdwr_access;
6938 err = check_buffer_access(env, reg, regno, off, size, false,
6941 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6942 mark_reg_unknown(env, regs, value_regno);
6943 } else if (reg->type == PTR_TO_ARENA) {
6944 if (t == BPF_READ && value_regno >= 0)
6945 mark_reg_unknown(env, regs, value_regno);
6947 verbose(env, "R%d invalid mem access '%s'\n", regno,
6948 reg_type_str(env, reg->type));
6952 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6953 regs[value_regno].type == SCALAR_VALUE) {
6955 /* b/h/w load zero-extends, mark upper bits as known 0 */
6956 coerce_reg_to_size(®s[value_regno], size);
6958 coerce_reg_to_size_sx(®s[value_regno], size);
6963 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6968 switch (insn->imm) {
6970 case BPF_ADD | BPF_FETCH:
6972 case BPF_AND | BPF_FETCH:
6974 case BPF_OR | BPF_FETCH:
6976 case BPF_XOR | BPF_FETCH:
6981 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6985 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6986 verbose(env, "invalid atomic operand size\n");
6990 /* check src1 operand */
6991 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6995 /* check src2 operand */
6996 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7000 if (insn->imm == BPF_CMPXCHG) {
7001 /* Check comparison of R0 with memory location */
7002 const u32 aux_reg = BPF_REG_0;
7004 err = check_reg_arg(env, aux_reg, SRC_OP);
7008 if (is_pointer_value(env, aux_reg)) {
7009 verbose(env, "R%d leaks addr into mem\n", aux_reg);
7014 if (is_pointer_value(env, insn->src_reg)) {
7015 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7019 if (is_ctx_reg(env, insn->dst_reg) ||
7020 is_pkt_reg(env, insn->dst_reg) ||
7021 is_flow_key_reg(env, insn->dst_reg) ||
7022 is_sk_reg(env, insn->dst_reg)) {
7023 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7025 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7029 if (insn->imm & BPF_FETCH) {
7030 if (insn->imm == BPF_CMPXCHG)
7031 load_reg = BPF_REG_0;
7033 load_reg = insn->src_reg;
7035 /* check and record load of old value */
7036 err = check_reg_arg(env, load_reg, DST_OP);
7040 /* This instruction accesses a memory location but doesn't
7041 * actually load it into a register.
7046 /* Check whether we can read the memory, with second call for fetch
7047 * case to simulate the register fill.
7049 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7050 BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7051 if (!err && load_reg >= 0)
7052 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7053 BPF_SIZE(insn->code), BPF_READ, load_reg,
7058 /* Check whether we can write into the same memory. */
7059 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7060 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7066 /* When register 'regno' is used to read the stack (either directly or through
7067 * a helper function) make sure that it's within stack boundary and, depending
7068 * on the access type and privileges, that all elements of the stack are
7071 * 'off' includes 'regno->off', but not its dynamic part (if any).
7073 * All registers that have been spilled on the stack in the slots within the
7074 * read offsets are marked as read.
7076 static int check_stack_range_initialized(
7077 struct bpf_verifier_env *env, int regno, int off,
7078 int access_size, bool zero_size_allowed,
7079 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7081 struct bpf_reg_state *reg = reg_state(env, regno);
7082 struct bpf_func_state *state = func(env, reg);
7083 int err, min_off, max_off, i, j, slot, spi;
7084 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7085 enum bpf_access_type bounds_check_type;
7086 /* Some accesses can write anything into the stack, others are
7089 bool clobber = false;
7091 if (access_size == 0 && !zero_size_allowed) {
7092 verbose(env, "invalid zero-sized read\n");
7096 if (type == ACCESS_HELPER) {
7097 /* The bounds checks for writes are more permissive than for
7098 * reads. However, if raw_mode is not set, we'll do extra
7101 bounds_check_type = BPF_WRITE;
7104 bounds_check_type = BPF_READ;
7106 err = check_stack_access_within_bounds(env, regno, off, access_size,
7107 type, bounds_check_type);
7112 if (tnum_is_const(reg->var_off)) {
7113 min_off = max_off = reg->var_off.value + off;
7115 /* Variable offset is prohibited for unprivileged mode for
7116 * simplicity since it requires corresponding support in
7117 * Spectre masking for stack ALU.
7118 * See also retrieve_ptr_limit().
7120 if (!env->bypass_spec_v1) {
7123 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7124 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7125 regno, err_extra, tn_buf);
7128 /* Only initialized buffer on stack is allowed to be accessed
7129 * with variable offset. With uninitialized buffer it's hard to
7130 * guarantee that whole memory is marked as initialized on
7131 * helper return since specific bounds are unknown what may
7132 * cause uninitialized stack leaking.
7134 if (meta && meta->raw_mode)
7137 min_off = reg->smin_value + off;
7138 max_off = reg->smax_value + off;
7141 if (meta && meta->raw_mode) {
7142 /* Ensure we won't be overwriting dynptrs when simulating byte
7143 * by byte access in check_helper_call using meta.access_size.
7144 * This would be a problem if we have a helper in the future
7147 * helper(uninit_mem, len, dynptr)
7149 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7150 * may end up writing to dynptr itself when touching memory from
7151 * arg 1. This can be relaxed on a case by case basis for known
7152 * safe cases, but reject due to the possibilitiy of aliasing by
7155 for (i = min_off; i < max_off + access_size; i++) {
7156 int stack_off = -i - 1;
7159 /* raw_mode may write past allocated_stack */
7160 if (state->allocated_stack <= stack_off)
7162 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7163 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7167 meta->access_size = access_size;
7168 meta->regno = regno;
7172 for (i = min_off; i < max_off + access_size; i++) {
7176 spi = slot / BPF_REG_SIZE;
7177 if (state->allocated_stack <= slot) {
7178 verbose(env, "verifier bug: allocated_stack too small");
7182 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7183 if (*stype == STACK_MISC)
7185 if ((*stype == STACK_ZERO) ||
7186 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7188 /* helper can write anything into the stack */
7189 *stype = STACK_MISC;
7194 if (is_spilled_reg(&state->stack[spi]) &&
7195 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7196 env->allow_ptr_leaks)) {
7198 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7199 for (j = 0; j < BPF_REG_SIZE; j++)
7200 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7205 if (tnum_is_const(reg->var_off)) {
7206 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7207 err_extra, regno, min_off, i - min_off, access_size);
7211 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7212 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7213 err_extra, regno, tn_buf, i - min_off, access_size);
7217 /* reading any byte out of 8-byte 'spill_slot' will cause
7218 * the whole slot to be marked as 'read'
7220 mark_reg_read(env, &state->stack[spi].spilled_ptr,
7221 state->stack[spi].spilled_ptr.parent,
7223 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7224 * be sure that whether stack slot is written to or not. Hence,
7225 * we must still conservatively propagate reads upwards even if
7226 * helper may write to the entire memory range.
7232 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7233 int access_size, bool zero_size_allowed,
7234 struct bpf_call_arg_meta *meta)
7236 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7239 switch (base_type(reg->type)) {
7241 case PTR_TO_PACKET_META:
7242 return check_packet_access(env, regno, reg->off, access_size,
7244 case PTR_TO_MAP_KEY:
7245 if (meta && meta->raw_mode) {
7246 verbose(env, "R%d cannot write into %s\n", regno,
7247 reg_type_str(env, reg->type));
7250 return check_mem_region_access(env, regno, reg->off, access_size,
7251 reg->map_ptr->key_size, false);
7252 case PTR_TO_MAP_VALUE:
7253 if (check_map_access_type(env, regno, reg->off, access_size,
7254 meta && meta->raw_mode ? BPF_WRITE :
7257 return check_map_access(env, regno, reg->off, access_size,
7258 zero_size_allowed, ACCESS_HELPER);
7260 if (type_is_rdonly_mem(reg->type)) {
7261 if (meta && meta->raw_mode) {
7262 verbose(env, "R%d cannot write into %s\n", regno,
7263 reg_type_str(env, reg->type));
7267 return check_mem_region_access(env, regno, reg->off,
7268 access_size, reg->mem_size,
7271 if (type_is_rdonly_mem(reg->type)) {
7272 if (meta && meta->raw_mode) {
7273 verbose(env, "R%d cannot write into %s\n", regno,
7274 reg_type_str(env, reg->type));
7278 max_access = &env->prog->aux->max_rdonly_access;
7280 max_access = &env->prog->aux->max_rdwr_access;
7282 return check_buffer_access(env, reg, regno, reg->off,
7283 access_size, zero_size_allowed,
7286 return check_stack_range_initialized(
7288 regno, reg->off, access_size,
7289 zero_size_allowed, ACCESS_HELPER, meta);
7291 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7292 access_size, BPF_READ, -1);
7294 /* in case the function doesn't know how to access the context,
7295 * (because we are in a program of type SYSCALL for example), we
7296 * can not statically check its size.
7297 * Dynamically check it now.
7299 if (!env->ops->convert_ctx_access) {
7300 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7301 int offset = access_size - 1;
7303 /* Allow zero-byte read from PTR_TO_CTX */
7304 if (access_size == 0)
7305 return zero_size_allowed ? 0 : -EACCES;
7307 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7308 atype, -1, false, false);
7312 default: /* scalar_value or invalid ptr */
7313 /* Allow zero-byte read from NULL, regardless of pointer type */
7314 if (zero_size_allowed && access_size == 0 &&
7315 register_is_null(reg))
7318 verbose(env, "R%d type=%s ", regno,
7319 reg_type_str(env, reg->type));
7320 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7325 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7328 * @regno is the register containing the access size. regno-1 is the register
7329 * containing the pointer.
7331 static int check_mem_size_reg(struct bpf_verifier_env *env,
7332 struct bpf_reg_state *reg, u32 regno,
7333 bool zero_size_allowed,
7334 struct bpf_call_arg_meta *meta)
7338 /* This is used to refine r0 return value bounds for helpers
7339 * that enforce this value as an upper bound on return values.
7340 * See do_refine_retval_range() for helpers that can refine
7341 * the return value. C type of helper is u32 so we pull register
7342 * bound from umax_value however, if negative verifier errors
7343 * out. Only upper bounds can be learned because retval is an
7344 * int type and negative retvals are allowed.
7346 meta->msize_max_value = reg->umax_value;
7348 /* The register is SCALAR_VALUE; the access check
7349 * happens using its boundaries.
7351 if (!tnum_is_const(reg->var_off))
7352 /* For unprivileged variable accesses, disable raw
7353 * mode so that the program is required to
7354 * initialize all the memory that the helper could
7355 * just partially fill up.
7359 if (reg->smin_value < 0) {
7360 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7365 if (reg->umin_value == 0 && !zero_size_allowed) {
7366 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7367 regno, reg->umin_value, reg->umax_value);
7371 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7372 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7376 err = check_helper_mem_access(env, regno - 1,
7378 zero_size_allowed, meta);
7380 err = mark_chain_precision(env, regno);
7384 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7385 u32 regno, u32 mem_size)
7387 bool may_be_null = type_may_be_null(reg->type);
7388 struct bpf_reg_state saved_reg;
7389 struct bpf_call_arg_meta meta;
7392 if (register_is_null(reg))
7395 memset(&meta, 0, sizeof(meta));
7396 /* Assuming that the register contains a value check if the memory
7397 * access is safe. Temporarily save and restore the register's state as
7398 * the conversion shouldn't be visible to a caller.
7402 mark_ptr_not_null_reg(reg);
7405 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7406 /* Check access for BPF_WRITE */
7407 meta.raw_mode = true;
7408 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7416 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7419 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7420 bool may_be_null = type_may_be_null(mem_reg->type);
7421 struct bpf_reg_state saved_reg;
7422 struct bpf_call_arg_meta meta;
7425 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7427 memset(&meta, 0, sizeof(meta));
7430 saved_reg = *mem_reg;
7431 mark_ptr_not_null_reg(mem_reg);
7434 err = check_mem_size_reg(env, reg, regno, true, &meta);
7435 /* Check access for BPF_WRITE */
7436 meta.raw_mode = true;
7437 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7440 *mem_reg = saved_reg;
7444 /* Implementation details:
7445 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7446 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7447 * Two bpf_map_lookups (even with the same key) will have different reg->id.
7448 * Two separate bpf_obj_new will also have different reg->id.
7449 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7450 * clears reg->id after value_or_null->value transition, since the verifier only
7451 * cares about the range of access to valid map value pointer and doesn't care
7452 * about actual address of the map element.
7453 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7454 * reg->id > 0 after value_or_null->value transition. By doing so
7455 * two bpf_map_lookups will be considered two different pointers that
7456 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7457 * returned from bpf_obj_new.
7458 * The verifier allows taking only one bpf_spin_lock at a time to avoid
7460 * Since only one bpf_spin_lock is allowed the checks are simpler than
7461 * reg_is_refcounted() logic. The verifier needs to remember only
7462 * one spin_lock instead of array of acquired_refs.
7463 * cur_state->active_lock remembers which map value element or allocated
7464 * object got locked and clears it after bpf_spin_unlock.
7466 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7469 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7470 struct bpf_verifier_state *cur = env->cur_state;
7471 bool is_const = tnum_is_const(reg->var_off);
7472 u64 val = reg->var_off.value;
7473 struct bpf_map *map = NULL;
7474 struct btf *btf = NULL;
7475 struct btf_record *rec;
7479 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7483 if (reg->type == PTR_TO_MAP_VALUE) {
7487 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7495 rec = reg_btf_record(reg);
7496 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7497 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7498 map ? map->name : "kptr");
7501 if (rec->spin_lock_off != val + reg->off) {
7502 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7503 val + reg->off, rec->spin_lock_off);
7507 if (cur->active_lock.ptr) {
7509 "Locking two bpf_spin_locks are not allowed\n");
7513 cur->active_lock.ptr = map;
7515 cur->active_lock.ptr = btf;
7516 cur->active_lock.id = reg->id;
7525 if (!cur->active_lock.ptr) {
7526 verbose(env, "bpf_spin_unlock without taking a lock\n");
7529 if (cur->active_lock.ptr != ptr ||
7530 cur->active_lock.id != reg->id) {
7531 verbose(env, "bpf_spin_unlock of different lock\n");
7535 invalidate_non_owning_refs(env);
7537 cur->active_lock.ptr = NULL;
7538 cur->active_lock.id = 0;
7543 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7544 struct bpf_call_arg_meta *meta)
7546 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7547 bool is_const = tnum_is_const(reg->var_off);
7548 struct bpf_map *map = reg->map_ptr;
7549 u64 val = reg->var_off.value;
7553 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7558 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7562 if (!btf_record_has_field(map->record, BPF_TIMER)) {
7563 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7566 if (map->record->timer_off != val + reg->off) {
7567 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7568 val + reg->off, map->record->timer_off);
7571 if (meta->map_ptr) {
7572 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7575 meta->map_uid = reg->map_uid;
7576 meta->map_ptr = map;
7580 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7581 struct bpf_call_arg_meta *meta)
7583 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7584 struct bpf_map *map_ptr = reg->map_ptr;
7585 struct btf_field *kptr_field;
7588 if (!tnum_is_const(reg->var_off)) {
7590 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7594 if (!map_ptr->btf) {
7595 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7599 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7600 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7604 meta->map_ptr = map_ptr;
7605 kptr_off = reg->off + reg->var_off.value;
7606 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7608 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7611 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7612 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7615 meta->kptr_field = kptr_field;
7619 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7620 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7622 * In both cases we deal with the first 8 bytes, but need to mark the next 8
7623 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7624 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7626 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7627 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7628 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7629 * mutate the view of the dynptr and also possibly destroy it. In the latter
7630 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7631 * memory that dynptr points to.
7633 * The verifier will keep track both levels of mutation (bpf_dynptr's in
7634 * reg->type and the memory's in reg->dynptr.type), but there is no support for
7635 * readonly dynptr view yet, hence only the first case is tracked and checked.
7637 * This is consistent with how C applies the const modifier to a struct object,
7638 * where the pointer itself inside bpf_dynptr becomes const but not what it
7641 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7642 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7644 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7645 enum bpf_arg_type arg_type, int clone_ref_obj_id)
7647 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7650 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7651 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7653 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7654 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7658 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
7659 * constructing a mutable bpf_dynptr object.
7661 * Currently, this is only possible with PTR_TO_STACK
7662 * pointing to a region of at least 16 bytes which doesn't
7663 * contain an existing bpf_dynptr.
7665 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7666 * mutated or destroyed. However, the memory it points to
7669 * None - Points to a initialized dynptr that can be mutated and
7670 * destroyed, including mutation of the memory it points
7673 if (arg_type & MEM_UNINIT) {
7676 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7677 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7681 /* we write BPF_DW bits (8 bytes) at a time */
7682 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7683 err = check_mem_access(env, insn_idx, regno,
7684 i, BPF_DW, BPF_WRITE, -1, false, false);
7689 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7690 } else /* MEM_RDONLY and None case from above */ {
7691 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7692 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7693 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7697 if (!is_dynptr_reg_valid_init(env, reg)) {
7699 "Expected an initialized dynptr as arg #%d\n",
7704 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7705 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7707 "Expected a dynptr of type %s as arg #%d\n",
7708 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7712 err = mark_dynptr_read(env, reg);
7717 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7719 struct bpf_func_state *state = func(env, reg);
7721 return state->stack[spi].spilled_ptr.ref_obj_id;
7724 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7726 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7729 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7731 return meta->kfunc_flags & KF_ITER_NEW;
7734 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7736 return meta->kfunc_flags & KF_ITER_NEXT;
7739 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7741 return meta->kfunc_flags & KF_ITER_DESTROY;
7744 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7746 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7747 * kfunc is iter state pointer
7749 return arg == 0 && is_iter_kfunc(meta);
7752 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7753 struct bpf_kfunc_call_arg_meta *meta)
7755 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7756 const struct btf_type *t;
7757 const struct btf_param *arg;
7758 int spi, err, i, nr_slots;
7761 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7762 arg = &btf_params(meta->func_proto)[0];
7763 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
7764 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
7765 nr_slots = t->size / BPF_REG_SIZE;
7767 if (is_iter_new_kfunc(meta)) {
7768 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7769 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7770 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7771 iter_type_str(meta->btf, btf_id), regno);
7775 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7776 err = check_mem_access(env, insn_idx, regno,
7777 i, BPF_DW, BPF_WRITE, -1, false, false);
7782 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7786 /* iter_next() or iter_destroy() expect initialized iter state*/
7787 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7792 verbose(env, "expected an initialized iter_%s as arg #%d\n",
7793 iter_type_str(meta->btf, btf_id), regno);
7796 verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7802 spi = iter_get_spi(env, reg, nr_slots);
7806 err = mark_iter_read(env, reg, spi, nr_slots);
7810 /* remember meta->iter info for process_iter_next_call() */
7811 meta->iter.spi = spi;
7812 meta->iter.frameno = reg->frameno;
7813 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7815 if (is_iter_destroy_kfunc(meta)) {
7816 err = unmark_stack_slots_iter(env, reg, nr_slots);
7825 /* Look for a previous loop entry at insn_idx: nearest parent state
7826 * stopped at insn_idx with callsites matching those in cur->frame.
7828 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7829 struct bpf_verifier_state *cur,
7832 struct bpf_verifier_state_list *sl;
7833 struct bpf_verifier_state *st;
7835 /* Explored states are pushed in stack order, most recent states come first */
7836 sl = *explored_state(env, insn_idx);
7837 for (; sl; sl = sl->next) {
7838 /* If st->branches != 0 state is a part of current DFS verification path,
7839 * hence cur & st for a loop.
7842 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7843 st->dfs_depth < cur->dfs_depth)
7850 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7851 static bool regs_exact(const struct bpf_reg_state *rold,
7852 const struct bpf_reg_state *rcur,
7853 struct bpf_idmap *idmap);
7855 static void maybe_widen_reg(struct bpf_verifier_env *env,
7856 struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7857 struct bpf_idmap *idmap)
7859 if (rold->type != SCALAR_VALUE)
7861 if (rold->type != rcur->type)
7863 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7865 __mark_reg_unknown(env, rcur);
7868 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7869 struct bpf_verifier_state *old,
7870 struct bpf_verifier_state *cur)
7872 struct bpf_func_state *fold, *fcur;
7875 reset_idmap_scratch(env);
7876 for (fr = old->curframe; fr >= 0; fr--) {
7877 fold = old->frame[fr];
7878 fcur = cur->frame[fr];
7880 for (i = 0; i < MAX_BPF_REG; i++)
7881 maybe_widen_reg(env,
7884 &env->idmap_scratch);
7886 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7887 if (!is_spilled_reg(&fold->stack[i]) ||
7888 !is_spilled_reg(&fcur->stack[i]))
7891 maybe_widen_reg(env,
7892 &fold->stack[i].spilled_ptr,
7893 &fcur->stack[i].spilled_ptr,
7894 &env->idmap_scratch);
7900 /* process_iter_next_call() is called when verifier gets to iterator's next
7901 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7902 * to it as just "iter_next()" in comments below.
7904 * BPF verifier relies on a crucial contract for any iter_next()
7905 * implementation: it should *eventually* return NULL, and once that happens
7906 * it should keep returning NULL. That is, once iterator exhausts elements to
7907 * iterate, it should never reset or spuriously return new elements.
7909 * With the assumption of such contract, process_iter_next_call() simulates
7910 * a fork in the verifier state to validate loop logic correctness and safety
7911 * without having to simulate infinite amount of iterations.
7913 * In current state, we first assume that iter_next() returned NULL and
7914 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7915 * conditions we should not form an infinite loop and should eventually reach
7918 * Besides that, we also fork current state and enqueue it for later
7919 * verification. In a forked state we keep iterator state as ACTIVE
7920 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7921 * also bump iteration depth to prevent erroneous infinite loop detection
7922 * later on (see iter_active_depths_differ() comment for details). In this
7923 * state we assume that we'll eventually loop back to another iter_next()
7924 * calls (it could be in exactly same location or in some other instruction,
7925 * it doesn't matter, we don't make any unnecessary assumptions about this,
7926 * everything revolves around iterator state in a stack slot, not which
7927 * instruction is calling iter_next()). When that happens, we either will come
7928 * to iter_next() with equivalent state and can conclude that next iteration
7929 * will proceed in exactly the same way as we just verified, so it's safe to
7930 * assume that loop converges. If not, we'll go on another iteration
7931 * simulation with a different input state, until all possible starting states
7932 * are validated or we reach maximum number of instructions limit.
7934 * This way, we will either exhaustively discover all possible input states
7935 * that iterator loop can start with and eventually will converge, or we'll
7936 * effectively regress into bounded loop simulation logic and either reach
7937 * maximum number of instructions if loop is not provably convergent, or there
7938 * is some statically known limit on number of iterations (e.g., if there is
7939 * an explicit `if n > 100 then break;` statement somewhere in the loop).
7941 * Iteration convergence logic in is_state_visited() relies on exact
7942 * states comparison, which ignores read and precision marks.
7943 * This is necessary because read and precision marks are not finalized
7944 * while in the loop. Exact comparison might preclude convergence for
7945 * simple programs like below:
7948 * while(iter_next(&it))
7951 * At each iteration step i++ would produce a new distinct state and
7952 * eventually instruction processing limit would be reached.
7954 * To avoid such behavior speculatively forget (widen) range for
7955 * imprecise scalar registers, if those registers were not precise at the
7956 * end of the previous iteration and do not match exactly.
7958 * This is a conservative heuristic that allows to verify wide range of programs,
7959 * however it precludes verification of programs that conjure an
7960 * imprecise value on the first loop iteration and use it as precise on a second.
7961 * For example, the following safe program would fail to verify:
7963 * struct bpf_num_iter it;
7966 * bpf_iter_num_new(&it, 0, 10);
7967 * while (bpf_iter_num_next(&it)) {
7970 * i = 7; // Because i changed verifier would forget
7971 * // it's range on second loop entry.
7973 * arr[i] = 42; // This would fail to verify.
7976 * bpf_iter_num_destroy(&it);
7978 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7979 struct bpf_kfunc_call_arg_meta *meta)
7981 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7982 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7983 struct bpf_reg_state *cur_iter, *queued_iter;
7984 int iter_frameno = meta->iter.frameno;
7985 int iter_spi = meta->iter.spi;
7987 BTF_TYPE_EMIT(struct bpf_iter);
7989 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7991 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7992 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7993 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7994 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7998 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7999 /* Because iter_next() call is a checkpoint is_state_visitied()
8000 * should guarantee parent state with same call sites and insn_idx.
8002 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8003 !same_callsites(cur_st->parent, cur_st)) {
8004 verbose(env, "bug: bad parent state for iter next call");
8007 /* Note cur_st->parent in the call below, it is necessary to skip
8008 * checkpoint created for cur_st by is_state_visited()
8009 * right at this instruction.
8011 prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8012 /* branch out active iter state */
8013 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8017 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8018 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8019 queued_iter->iter.depth++;
8021 widen_imprecise_scalars(env, prev_st, queued_st);
8023 queued_fr = queued_st->frame[queued_st->curframe];
8024 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8027 /* switch to DRAINED state, but keep the depth unchanged */
8028 /* mark current iter state as drained and assume returned NULL */
8029 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8030 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8035 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8037 return type == ARG_CONST_SIZE ||
8038 type == ARG_CONST_SIZE_OR_ZERO;
8041 static bool arg_type_is_release(enum bpf_arg_type type)
8043 return type & OBJ_RELEASE;
8046 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8048 return base_type(type) == ARG_PTR_TO_DYNPTR;
8051 static int int_ptr_type_to_size(enum bpf_arg_type type)
8053 if (type == ARG_PTR_TO_INT)
8055 else if (type == ARG_PTR_TO_LONG)
8061 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8062 const struct bpf_call_arg_meta *meta,
8063 enum bpf_arg_type *arg_type)
8065 if (!meta->map_ptr) {
8066 /* kernel subsystem misconfigured verifier */
8067 verbose(env, "invalid map_ptr to access map->type\n");
8071 switch (meta->map_ptr->map_type) {
8072 case BPF_MAP_TYPE_SOCKMAP:
8073 case BPF_MAP_TYPE_SOCKHASH:
8074 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8075 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8077 verbose(env, "invalid arg_type for sockmap/sockhash\n");
8081 case BPF_MAP_TYPE_BLOOM_FILTER:
8082 if (meta->func_id == BPF_FUNC_map_peek_elem)
8083 *arg_type = ARG_PTR_TO_MAP_VALUE;
8091 struct bpf_reg_types {
8092 const enum bpf_reg_type types[10];
8096 static const struct bpf_reg_types sock_types = {
8106 static const struct bpf_reg_types btf_id_sock_common_types = {
8113 PTR_TO_BTF_ID | PTR_TRUSTED,
8115 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8119 static const struct bpf_reg_types mem_types = {
8127 PTR_TO_MEM | MEM_RINGBUF,
8129 PTR_TO_BTF_ID | PTR_TRUSTED,
8133 static const struct bpf_reg_types int_ptr_types = {
8143 static const struct bpf_reg_types spin_lock_types = {
8146 PTR_TO_BTF_ID | MEM_ALLOC,
8150 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8151 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8152 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8153 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8154 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8155 static const struct bpf_reg_types btf_ptr_types = {
8158 PTR_TO_BTF_ID | PTR_TRUSTED,
8159 PTR_TO_BTF_ID | MEM_RCU,
8162 static const struct bpf_reg_types percpu_btf_ptr_types = {
8164 PTR_TO_BTF_ID | MEM_PERCPU,
8165 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8166 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8169 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8170 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8171 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8172 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8173 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8174 static const struct bpf_reg_types dynptr_types = {
8177 CONST_PTR_TO_DYNPTR,
8181 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8182 [ARG_PTR_TO_MAP_KEY] = &mem_types,
8183 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
8184 [ARG_CONST_SIZE] = &scalar_types,
8185 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
8186 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
8187 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
8188 [ARG_PTR_TO_CTX] = &context_types,
8189 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
8191 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
8193 [ARG_PTR_TO_SOCKET] = &fullsock_types,
8194 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
8195 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
8196 [ARG_PTR_TO_MEM] = &mem_types,
8197 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
8198 [ARG_PTR_TO_INT] = &int_ptr_types,
8199 [ARG_PTR_TO_LONG] = &int_ptr_types,
8200 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
8201 [ARG_PTR_TO_FUNC] = &func_ptr_types,
8202 [ARG_PTR_TO_STACK] = &stack_ptr_types,
8203 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
8204 [ARG_PTR_TO_TIMER] = &timer_types,
8205 [ARG_PTR_TO_KPTR] = &kptr_types,
8206 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
8209 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8210 enum bpf_arg_type arg_type,
8211 const u32 *arg_btf_id,
8212 struct bpf_call_arg_meta *meta)
8214 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8215 enum bpf_reg_type expected, type = reg->type;
8216 const struct bpf_reg_types *compatible;
8219 compatible = compatible_reg_types[base_type(arg_type)];
8221 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8225 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8226 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8228 * Same for MAYBE_NULL:
8230 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8231 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8233 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8235 * Therefore we fold these flags depending on the arg_type before comparison.
8237 if (arg_type & MEM_RDONLY)
8238 type &= ~MEM_RDONLY;
8239 if (arg_type & PTR_MAYBE_NULL)
8240 type &= ~PTR_MAYBE_NULL;
8241 if (base_type(arg_type) == ARG_PTR_TO_MEM)
8242 type &= ~DYNPTR_TYPE_FLAG_MASK;
8244 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) {
8246 type &= ~MEM_PERCPU;
8249 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8250 expected = compatible->types[i];
8251 if (expected == NOT_INIT)
8254 if (type == expected)
8258 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8259 for (j = 0; j + 1 < i; j++)
8260 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8261 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8265 if (base_type(reg->type) != PTR_TO_BTF_ID)
8268 if (compatible == &mem_types) {
8269 if (!(arg_type & MEM_RDONLY)) {
8271 "%s() may write into memory pointed by R%d type=%s\n",
8272 func_id_name(meta->func_id),
8273 regno, reg_type_str(env, reg->type));
8279 switch ((int)reg->type) {
8281 case PTR_TO_BTF_ID | PTR_TRUSTED:
8282 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
8283 case PTR_TO_BTF_ID | MEM_RCU:
8284 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8285 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8287 /* For bpf_sk_release, it needs to match against first member
8288 * 'struct sock_common', hence make an exception for it. This
8289 * allows bpf_sk_release to work for multiple socket types.
8291 bool strict_type_match = arg_type_is_release(arg_type) &&
8292 meta->func_id != BPF_FUNC_sk_release;
8294 if (type_may_be_null(reg->type) &&
8295 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8296 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8301 if (!compatible->btf_id) {
8302 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8305 arg_btf_id = compatible->btf_id;
8308 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8309 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8312 if (arg_btf_id == BPF_PTR_POISON) {
8313 verbose(env, "verifier internal error:");
8314 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8319 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8320 btf_vmlinux, *arg_btf_id,
8321 strict_type_match)) {
8322 verbose(env, "R%d is of type %s but %s is expected\n",
8323 regno, btf_type_name(reg->btf, reg->btf_id),
8324 btf_type_name(btf_vmlinux, *arg_btf_id));
8330 case PTR_TO_BTF_ID | MEM_ALLOC:
8331 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8332 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8333 meta->func_id != BPF_FUNC_kptr_xchg) {
8334 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8337 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8338 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8342 case PTR_TO_BTF_ID | MEM_PERCPU:
8343 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8344 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8345 /* Handled by helper specific checks */
8348 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8354 static struct btf_field *
8355 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8357 struct btf_field *field;
8358 struct btf_record *rec;
8360 rec = reg_btf_record(reg);
8364 field = btf_record_find(rec, off, fields);
8371 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8372 const struct bpf_reg_state *reg, int regno,
8373 enum bpf_arg_type arg_type)
8375 u32 type = reg->type;
8377 /* When referenced register is passed to release function, its fixed
8380 * We will check arg_type_is_release reg has ref_obj_id when storing
8381 * meta->release_regno.
8383 if (arg_type_is_release(arg_type)) {
8384 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8385 * may not directly point to the object being released, but to
8386 * dynptr pointing to such object, which might be at some offset
8387 * on the stack. In that case, we simply to fallback to the
8390 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8393 /* Doing check_ptr_off_reg check for the offset will catch this
8394 * because fixed_off_ok is false, but checking here allows us
8395 * to give the user a better error message.
8398 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8402 return __check_ptr_off_reg(env, reg, regno, false);
8406 /* Pointer types where both fixed and variable offset is explicitly allowed: */
8409 case PTR_TO_PACKET_META:
8410 case PTR_TO_MAP_KEY:
8411 case PTR_TO_MAP_VALUE:
8413 case PTR_TO_MEM | MEM_RDONLY:
8414 case PTR_TO_MEM | MEM_RINGBUF:
8416 case PTR_TO_BUF | MEM_RDONLY:
8420 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8424 case PTR_TO_BTF_ID | MEM_ALLOC:
8425 case PTR_TO_BTF_ID | PTR_TRUSTED:
8426 case PTR_TO_BTF_ID | MEM_RCU:
8427 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8428 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8429 /* When referenced PTR_TO_BTF_ID is passed to release function,
8430 * its fixed offset must be 0. In the other cases, fixed offset
8431 * can be non-zero. This was already checked above. So pass
8432 * fixed_off_ok as true to allow fixed offset for all other
8433 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8434 * still need to do checks instead of returning.
8436 return __check_ptr_off_reg(env, reg, regno, true);
8438 return __check_ptr_off_reg(env, reg, regno, false);
8442 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8443 const struct bpf_func_proto *fn,
8444 struct bpf_reg_state *regs)
8446 struct bpf_reg_state *state = NULL;
8449 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8450 if (arg_type_is_dynptr(fn->arg_type[i])) {
8452 verbose(env, "verifier internal error: multiple dynptr args\n");
8455 state = ®s[BPF_REG_1 + i];
8459 verbose(env, "verifier internal error: no dynptr arg found\n");
8464 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8466 struct bpf_func_state *state = func(env, reg);
8469 if (reg->type == CONST_PTR_TO_DYNPTR)
8471 spi = dynptr_get_spi(env, reg);
8474 return state->stack[spi].spilled_ptr.id;
8477 static int dynptr_ref_obj_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)
8483 return reg->ref_obj_id;
8484 spi = dynptr_get_spi(env, reg);
8487 return state->stack[spi].spilled_ptr.ref_obj_id;
8490 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8491 struct bpf_reg_state *reg)
8493 struct bpf_func_state *state = func(env, reg);
8496 if (reg->type == CONST_PTR_TO_DYNPTR)
8497 return reg->dynptr.type;
8499 spi = __get_spi(reg->off);
8501 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8502 return BPF_DYNPTR_TYPE_INVALID;
8505 return state->stack[spi].spilled_ptr.dynptr.type;
8508 static int check_reg_const_str(struct bpf_verifier_env *env,
8509 struct bpf_reg_state *reg, u32 regno)
8511 struct bpf_map *map = reg->map_ptr;
8517 if (reg->type != PTR_TO_MAP_VALUE)
8520 if (!bpf_map_is_rdonly(map)) {
8521 verbose(env, "R%d does not point to a readonly map'\n", regno);
8525 if (!tnum_is_const(reg->var_off)) {
8526 verbose(env, "R%d is not a constant address'\n", regno);
8530 if (!map->ops->map_direct_value_addr) {
8531 verbose(env, "no direct value access support for this map type\n");
8535 err = check_map_access(env, regno, reg->off,
8536 map->value_size - reg->off, false,
8541 map_off = reg->off + reg->var_off.value;
8542 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8544 verbose(env, "direct value access on string failed\n");
8548 str_ptr = (char *)(long)(map_addr);
8549 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8550 verbose(env, "string is not zero-terminated\n");
8556 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8557 struct bpf_call_arg_meta *meta,
8558 const struct bpf_func_proto *fn,
8561 u32 regno = BPF_REG_1 + arg;
8562 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8563 enum bpf_arg_type arg_type = fn->arg_type[arg];
8564 enum bpf_reg_type type = reg->type;
8565 u32 *arg_btf_id = NULL;
8568 if (arg_type == ARG_DONTCARE)
8571 err = check_reg_arg(env, regno, SRC_OP);
8575 if (arg_type == ARG_ANYTHING) {
8576 if (is_pointer_value(env, regno)) {
8577 verbose(env, "R%d leaks addr into helper function\n",
8584 if (type_is_pkt_pointer(type) &&
8585 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8586 verbose(env, "helper access to the packet is not allowed\n");
8590 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8591 err = resolve_map_arg_type(env, meta, &arg_type);
8596 if (register_is_null(reg) && type_may_be_null(arg_type))
8597 /* A NULL register has a SCALAR_VALUE type, so skip
8600 goto skip_type_check;
8602 /* arg_btf_id and arg_size are in a union. */
8603 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8604 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8605 arg_btf_id = fn->arg_btf_id[arg];
8607 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8611 err = check_func_arg_reg_off(env, reg, regno, arg_type);
8616 if (arg_type_is_release(arg_type)) {
8617 if (arg_type_is_dynptr(arg_type)) {
8618 struct bpf_func_state *state = func(env, reg);
8621 /* Only dynptr created on stack can be released, thus
8622 * the get_spi and stack state checks for spilled_ptr
8623 * should only be done before process_dynptr_func for
8626 if (reg->type == PTR_TO_STACK) {
8627 spi = dynptr_get_spi(env, reg);
8628 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8629 verbose(env, "arg %d is an unacquired reference\n", regno);
8633 verbose(env, "cannot release unowned const bpf_dynptr\n");
8636 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8637 verbose(env, "R%d must be referenced when passed to release function\n",
8641 if (meta->release_regno) {
8642 verbose(env, "verifier internal error: more than one release argument\n");
8645 meta->release_regno = regno;
8648 if (reg->ref_obj_id) {
8649 if (meta->ref_obj_id) {
8650 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8651 regno, reg->ref_obj_id,
8655 meta->ref_obj_id = reg->ref_obj_id;
8658 switch (base_type(arg_type)) {
8659 case ARG_CONST_MAP_PTR:
8660 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8661 if (meta->map_ptr) {
8662 /* Use map_uid (which is unique id of inner map) to reject:
8663 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8664 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8665 * if (inner_map1 && inner_map2) {
8666 * timer = bpf_map_lookup_elem(inner_map1);
8668 * // mismatch would have been allowed
8669 * bpf_timer_init(timer, inner_map2);
8672 * Comparing map_ptr is enough to distinguish normal and outer maps.
8674 if (meta->map_ptr != reg->map_ptr ||
8675 meta->map_uid != reg->map_uid) {
8677 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8678 meta->map_uid, reg->map_uid);
8682 meta->map_ptr = reg->map_ptr;
8683 meta->map_uid = reg->map_uid;
8685 case ARG_PTR_TO_MAP_KEY:
8686 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8687 * check that [key, key + map->key_size) are within
8688 * stack limits and initialized
8690 if (!meta->map_ptr) {
8691 /* in function declaration map_ptr must come before
8692 * map_key, so that it's verified and known before
8693 * we have to check map_key here. Otherwise it means
8694 * that kernel subsystem misconfigured verifier
8696 verbose(env, "invalid map_ptr to access map->key\n");
8699 err = check_helper_mem_access(env, regno,
8700 meta->map_ptr->key_size, false,
8703 case ARG_PTR_TO_MAP_VALUE:
8704 if (type_may_be_null(arg_type) && register_is_null(reg))
8707 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8708 * check [value, value + map->value_size) validity
8710 if (!meta->map_ptr) {
8711 /* kernel subsystem misconfigured verifier */
8712 verbose(env, "invalid map_ptr to access map->value\n");
8715 meta->raw_mode = arg_type & MEM_UNINIT;
8716 err = check_helper_mem_access(env, regno,
8717 meta->map_ptr->value_size, false,
8720 case ARG_PTR_TO_PERCPU_BTF_ID:
8722 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8725 meta->ret_btf = reg->btf;
8726 meta->ret_btf_id = reg->btf_id;
8728 case ARG_PTR_TO_SPIN_LOCK:
8729 if (in_rbtree_lock_required_cb(env)) {
8730 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8733 if (meta->func_id == BPF_FUNC_spin_lock) {
8734 err = process_spin_lock(env, regno, true);
8737 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8738 err = process_spin_lock(env, regno, false);
8742 verbose(env, "verifier internal error\n");
8746 case ARG_PTR_TO_TIMER:
8747 err = process_timer_func(env, regno, meta);
8751 case ARG_PTR_TO_FUNC:
8752 meta->subprogno = reg->subprogno;
8754 case ARG_PTR_TO_MEM:
8755 /* The access to this pointer is only checked when we hit the
8756 * next is_mem_size argument below.
8758 meta->raw_mode = arg_type & MEM_UNINIT;
8759 if (arg_type & MEM_FIXED_SIZE) {
8760 err = check_helper_mem_access(env, regno,
8761 fn->arg_size[arg], false,
8765 case ARG_CONST_SIZE:
8766 err = check_mem_size_reg(env, reg, regno, false, meta);
8768 case ARG_CONST_SIZE_OR_ZERO:
8769 err = check_mem_size_reg(env, reg, regno, true, meta);
8771 case ARG_PTR_TO_DYNPTR:
8772 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8776 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8777 if (!tnum_is_const(reg->var_off)) {
8778 verbose(env, "R%d is not a known constant'\n",
8782 meta->mem_size = reg->var_off.value;
8783 err = mark_chain_precision(env, regno);
8787 case ARG_PTR_TO_INT:
8788 case ARG_PTR_TO_LONG:
8790 int size = int_ptr_type_to_size(arg_type);
8792 err = check_helper_mem_access(env, regno, size, false, meta);
8795 err = check_ptr_alignment(env, reg, 0, size, true);
8798 case ARG_PTR_TO_CONST_STR:
8800 err = check_reg_const_str(env, reg, regno);
8805 case ARG_PTR_TO_KPTR:
8806 err = process_kptr_func(env, regno, meta);
8815 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8817 enum bpf_attach_type eatype = env->prog->expected_attach_type;
8818 enum bpf_prog_type type = resolve_prog_type(env->prog);
8820 if (func_id != BPF_FUNC_map_update_elem)
8823 /* It's not possible to get access to a locked struct sock in these
8824 * contexts, so updating is safe.
8827 case BPF_PROG_TYPE_TRACING:
8828 if (eatype == BPF_TRACE_ITER)
8831 case BPF_PROG_TYPE_SOCKET_FILTER:
8832 case BPF_PROG_TYPE_SCHED_CLS:
8833 case BPF_PROG_TYPE_SCHED_ACT:
8834 case BPF_PROG_TYPE_XDP:
8835 case BPF_PROG_TYPE_SK_REUSEPORT:
8836 case BPF_PROG_TYPE_FLOW_DISSECTOR:
8837 case BPF_PROG_TYPE_SK_LOOKUP:
8843 verbose(env, "cannot update sockmap in this context\n");
8847 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8849 return env->prog->jit_requested &&
8850 bpf_jit_supports_subprog_tailcalls();
8853 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8854 struct bpf_map *map, int func_id)
8859 /* We need a two way check, first is from map perspective ... */
8860 switch (map->map_type) {
8861 case BPF_MAP_TYPE_PROG_ARRAY:
8862 if (func_id != BPF_FUNC_tail_call)
8865 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8866 if (func_id != BPF_FUNC_perf_event_read &&
8867 func_id != BPF_FUNC_perf_event_output &&
8868 func_id != BPF_FUNC_skb_output &&
8869 func_id != BPF_FUNC_perf_event_read_value &&
8870 func_id != BPF_FUNC_xdp_output)
8873 case BPF_MAP_TYPE_RINGBUF:
8874 if (func_id != BPF_FUNC_ringbuf_output &&
8875 func_id != BPF_FUNC_ringbuf_reserve &&
8876 func_id != BPF_FUNC_ringbuf_query &&
8877 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8878 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8879 func_id != BPF_FUNC_ringbuf_discard_dynptr)
8882 case BPF_MAP_TYPE_USER_RINGBUF:
8883 if (func_id != BPF_FUNC_user_ringbuf_drain)
8886 case BPF_MAP_TYPE_STACK_TRACE:
8887 if (func_id != BPF_FUNC_get_stackid)
8890 case BPF_MAP_TYPE_CGROUP_ARRAY:
8891 if (func_id != BPF_FUNC_skb_under_cgroup &&
8892 func_id != BPF_FUNC_current_task_under_cgroup)
8895 case BPF_MAP_TYPE_CGROUP_STORAGE:
8896 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8897 if (func_id != BPF_FUNC_get_local_storage)
8900 case BPF_MAP_TYPE_DEVMAP:
8901 case BPF_MAP_TYPE_DEVMAP_HASH:
8902 if (func_id != BPF_FUNC_redirect_map &&
8903 func_id != BPF_FUNC_map_lookup_elem)
8906 /* Restrict bpf side of cpumap and xskmap, open when use-cases
8909 case BPF_MAP_TYPE_CPUMAP:
8910 if (func_id != BPF_FUNC_redirect_map)
8913 case BPF_MAP_TYPE_XSKMAP:
8914 if (func_id != BPF_FUNC_redirect_map &&
8915 func_id != BPF_FUNC_map_lookup_elem)
8918 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8919 case BPF_MAP_TYPE_HASH_OF_MAPS:
8920 if (func_id != BPF_FUNC_map_lookup_elem)
8923 case BPF_MAP_TYPE_SOCKMAP:
8924 if (func_id != BPF_FUNC_sk_redirect_map &&
8925 func_id != BPF_FUNC_sock_map_update &&
8926 func_id != BPF_FUNC_map_delete_elem &&
8927 func_id != BPF_FUNC_msg_redirect_map &&
8928 func_id != BPF_FUNC_sk_select_reuseport &&
8929 func_id != BPF_FUNC_map_lookup_elem &&
8930 !may_update_sockmap(env, func_id))
8933 case BPF_MAP_TYPE_SOCKHASH:
8934 if (func_id != BPF_FUNC_sk_redirect_hash &&
8935 func_id != BPF_FUNC_sock_hash_update &&
8936 func_id != BPF_FUNC_map_delete_elem &&
8937 func_id != BPF_FUNC_msg_redirect_hash &&
8938 func_id != BPF_FUNC_sk_select_reuseport &&
8939 func_id != BPF_FUNC_map_lookup_elem &&
8940 !may_update_sockmap(env, func_id))
8943 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8944 if (func_id != BPF_FUNC_sk_select_reuseport)
8947 case BPF_MAP_TYPE_QUEUE:
8948 case BPF_MAP_TYPE_STACK:
8949 if (func_id != BPF_FUNC_map_peek_elem &&
8950 func_id != BPF_FUNC_map_pop_elem &&
8951 func_id != BPF_FUNC_map_push_elem)
8954 case BPF_MAP_TYPE_SK_STORAGE:
8955 if (func_id != BPF_FUNC_sk_storage_get &&
8956 func_id != BPF_FUNC_sk_storage_delete &&
8957 func_id != BPF_FUNC_kptr_xchg)
8960 case BPF_MAP_TYPE_INODE_STORAGE:
8961 if (func_id != BPF_FUNC_inode_storage_get &&
8962 func_id != BPF_FUNC_inode_storage_delete &&
8963 func_id != BPF_FUNC_kptr_xchg)
8966 case BPF_MAP_TYPE_TASK_STORAGE:
8967 if (func_id != BPF_FUNC_task_storage_get &&
8968 func_id != BPF_FUNC_task_storage_delete &&
8969 func_id != BPF_FUNC_kptr_xchg)
8972 case BPF_MAP_TYPE_CGRP_STORAGE:
8973 if (func_id != BPF_FUNC_cgrp_storage_get &&
8974 func_id != BPF_FUNC_cgrp_storage_delete &&
8975 func_id != BPF_FUNC_kptr_xchg)
8978 case BPF_MAP_TYPE_BLOOM_FILTER:
8979 if (func_id != BPF_FUNC_map_peek_elem &&
8980 func_id != BPF_FUNC_map_push_elem)
8987 /* ... and second from the function itself. */
8989 case BPF_FUNC_tail_call:
8990 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8992 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8993 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8997 case BPF_FUNC_perf_event_read:
8998 case BPF_FUNC_perf_event_output:
8999 case BPF_FUNC_perf_event_read_value:
9000 case BPF_FUNC_skb_output:
9001 case BPF_FUNC_xdp_output:
9002 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
9005 case BPF_FUNC_ringbuf_output:
9006 case BPF_FUNC_ringbuf_reserve:
9007 case BPF_FUNC_ringbuf_query:
9008 case BPF_FUNC_ringbuf_reserve_dynptr:
9009 case BPF_FUNC_ringbuf_submit_dynptr:
9010 case BPF_FUNC_ringbuf_discard_dynptr:
9011 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
9014 case BPF_FUNC_user_ringbuf_drain:
9015 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
9018 case BPF_FUNC_get_stackid:
9019 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
9022 case BPF_FUNC_current_task_under_cgroup:
9023 case BPF_FUNC_skb_under_cgroup:
9024 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
9027 case BPF_FUNC_redirect_map:
9028 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
9029 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9030 map->map_type != BPF_MAP_TYPE_CPUMAP &&
9031 map->map_type != BPF_MAP_TYPE_XSKMAP)
9034 case BPF_FUNC_sk_redirect_map:
9035 case BPF_FUNC_msg_redirect_map:
9036 case BPF_FUNC_sock_map_update:
9037 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9040 case BPF_FUNC_sk_redirect_hash:
9041 case BPF_FUNC_msg_redirect_hash:
9042 case BPF_FUNC_sock_hash_update:
9043 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
9046 case BPF_FUNC_get_local_storage:
9047 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9048 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9051 case BPF_FUNC_sk_select_reuseport:
9052 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9053 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9054 map->map_type != BPF_MAP_TYPE_SOCKHASH)
9057 case BPF_FUNC_map_pop_elem:
9058 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9059 map->map_type != BPF_MAP_TYPE_STACK)
9062 case BPF_FUNC_map_peek_elem:
9063 case BPF_FUNC_map_push_elem:
9064 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9065 map->map_type != BPF_MAP_TYPE_STACK &&
9066 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9069 case BPF_FUNC_map_lookup_percpu_elem:
9070 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9071 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9072 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9075 case BPF_FUNC_sk_storage_get:
9076 case BPF_FUNC_sk_storage_delete:
9077 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9080 case BPF_FUNC_inode_storage_get:
9081 case BPF_FUNC_inode_storage_delete:
9082 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9085 case BPF_FUNC_task_storage_get:
9086 case BPF_FUNC_task_storage_delete:
9087 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9090 case BPF_FUNC_cgrp_storage_get:
9091 case BPF_FUNC_cgrp_storage_delete:
9092 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9101 verbose(env, "cannot pass map_type %d into func %s#%d\n",
9102 map->map_type, func_id_name(func_id), func_id);
9106 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9110 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9112 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9114 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9116 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9118 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9121 /* We only support one arg being in raw mode at the moment,
9122 * which is sufficient for the helper functions we have
9128 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9130 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9131 bool has_size = fn->arg_size[arg] != 0;
9132 bool is_next_size = false;
9134 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9135 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9137 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9138 return is_next_size;
9140 return has_size == is_next_size || is_next_size == is_fixed;
9143 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9145 /* bpf_xxx(..., buf, len) call will access 'len'
9146 * bytes from memory 'buf'. Both arg types need
9147 * to be paired, so make sure there's no buggy
9148 * helper function specification.
9150 if (arg_type_is_mem_size(fn->arg1_type) ||
9151 check_args_pair_invalid(fn, 0) ||
9152 check_args_pair_invalid(fn, 1) ||
9153 check_args_pair_invalid(fn, 2) ||
9154 check_args_pair_invalid(fn, 3) ||
9155 check_args_pair_invalid(fn, 4))
9161 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9165 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9166 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9167 return !!fn->arg_btf_id[i];
9168 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9169 return fn->arg_btf_id[i] == BPF_PTR_POISON;
9170 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9171 /* arg_btf_id and arg_size are in a union. */
9172 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9173 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9180 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9182 return check_raw_mode_ok(fn) &&
9183 check_arg_pair_ok(fn) &&
9184 check_btf_id_ok(fn) ? 0 : -EINVAL;
9187 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9188 * are now invalid, so turn them into unknown SCALAR_VALUE.
9190 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9191 * since these slices point to packet data.
9193 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9195 struct bpf_func_state *state;
9196 struct bpf_reg_state *reg;
9198 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9199 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9200 mark_reg_invalid(env, reg);
9206 BEYOND_PKT_END = -2,
9209 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9211 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9212 struct bpf_reg_state *reg = &state->regs[regn];
9214 if (reg->type != PTR_TO_PACKET)
9215 /* PTR_TO_PACKET_META is not supported yet */
9218 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9219 * How far beyond pkt_end it goes is unknown.
9220 * if (!range_open) it's the case of pkt >= pkt_end
9221 * if (range_open) it's the case of pkt > pkt_end
9222 * hence this pointer is at least 1 byte bigger than pkt_end
9225 reg->range = BEYOND_PKT_END;
9227 reg->range = AT_PKT_END;
9230 /* The pointer with the specified id has released its reference to kernel
9231 * resources. Identify all copies of the same pointer and clear the reference.
9233 static int release_reference(struct bpf_verifier_env *env,
9236 struct bpf_func_state *state;
9237 struct bpf_reg_state *reg;
9240 err = release_reference_state(cur_func(env), ref_obj_id);
9244 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9245 if (reg->ref_obj_id == ref_obj_id)
9246 mark_reg_invalid(env, reg);
9252 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9254 struct bpf_func_state *unused;
9255 struct bpf_reg_state *reg;
9257 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9258 if (type_is_non_owning_ref(reg->type))
9259 mark_reg_invalid(env, reg);
9263 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9264 struct bpf_reg_state *regs)
9268 /* after the call registers r0 - r5 were scratched */
9269 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9270 mark_reg_not_init(env, regs, caller_saved[i]);
9271 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9275 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9276 struct bpf_func_state *caller,
9277 struct bpf_func_state *callee,
9280 static int set_callee_state(struct bpf_verifier_env *env,
9281 struct bpf_func_state *caller,
9282 struct bpf_func_state *callee, int insn_idx);
9284 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9285 set_callee_state_fn set_callee_state_cb,
9286 struct bpf_verifier_state *state)
9288 struct bpf_func_state *caller, *callee;
9291 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9292 verbose(env, "the call stack of %d frames is too deep\n",
9293 state->curframe + 2);
9297 if (state->frame[state->curframe + 1]) {
9298 verbose(env, "verifier bug. Frame %d already allocated\n",
9299 state->curframe + 1);
9303 caller = state->frame[state->curframe];
9304 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9307 state->frame[state->curframe + 1] = callee;
9309 /* callee cannot access r0, r6 - r9 for reading and has to write
9310 * into its own stack before reading from it.
9311 * callee can read/write into caller's stack
9313 init_func_state(env, callee,
9314 /* remember the callsite, it will be used by bpf_exit */
9316 state->curframe + 1 /* frameno within this callchain */,
9317 subprog /* subprog number within this prog */);
9318 /* Transfer references to the callee */
9319 err = copy_reference_state(callee, caller);
9320 err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9324 /* only increment it after check_reg_arg() finished */
9330 free_func_state(callee);
9331 state->frame[state->curframe + 1] = NULL;
9335 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9336 const struct btf *btf,
9337 struct bpf_reg_state *regs)
9339 struct bpf_subprog_info *sub = subprog_info(env, subprog);
9340 struct bpf_verifier_log *log = &env->log;
9344 ret = btf_prepare_func_args(env, subprog);
9348 /* check that BTF function arguments match actual types that the
9351 for (i = 0; i < sub->arg_cnt; i++) {
9353 struct bpf_reg_state *reg = ®s[regno];
9354 struct bpf_subprog_arg_info *arg = &sub->args[i];
9356 if (arg->arg_type == ARG_ANYTHING) {
9357 if (reg->type != SCALAR_VALUE) {
9358 bpf_log(log, "R%d is not a scalar\n", regno);
9361 } else if (arg->arg_type == ARG_PTR_TO_CTX) {
9362 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9365 /* If function expects ctx type in BTF check that caller
9366 * is passing PTR_TO_CTX.
9368 if (reg->type != PTR_TO_CTX) {
9369 bpf_log(log, "arg#%d expects pointer to ctx\n", i);
9372 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9373 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9376 if (check_mem_reg(env, reg, regno, arg->mem_size))
9378 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
9379 bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
9382 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
9384 * Can pass any value and the kernel won't crash, but
9385 * only PTR_TO_ARENA or SCALAR make sense. Everything
9386 * else is a bug in the bpf program. Point it out to
9387 * the user at the verification time instead of
9388 * run-time debug nightmare.
9390 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
9391 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
9394 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
9395 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
9398 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
9399 struct bpf_call_arg_meta meta;
9402 if (register_is_null(reg) && type_may_be_null(arg->arg_type))
9405 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
9406 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
9407 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
9411 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
9420 /* Compare BTF of a function call with given bpf_reg_state.
9422 * EFAULT - there is a verifier bug. Abort verification.
9423 * EINVAL - there is a type mismatch or BTF is not available.
9424 * 0 - BTF matches with what bpf_reg_state expects.
9425 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9427 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9428 struct bpf_reg_state *regs)
9430 struct bpf_prog *prog = env->prog;
9431 struct btf *btf = prog->aux->btf;
9435 if (!prog->aux->func_info)
9438 btf_id = prog->aux->func_info[subprog].type_id;
9442 if (prog->aux->func_info_aux[subprog].unreliable)
9445 err = btf_check_func_arg_match(env, subprog, btf, regs);
9446 /* Compiler optimizations can remove arguments from static functions
9447 * or mismatched type can be passed into a global function.
9448 * In such cases mark the function as unreliable from BTF point of view.
9451 prog->aux->func_info_aux[subprog].unreliable = true;
9455 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9456 int insn_idx, int subprog,
9457 set_callee_state_fn set_callee_state_cb)
9459 struct bpf_verifier_state *state = env->cur_state, *callback_state;
9460 struct bpf_func_state *caller, *callee;
9463 caller = state->frame[state->curframe];
9464 err = btf_check_subprog_call(env, subprog, caller->regs);
9468 /* set_callee_state is used for direct subprog calls, but we are
9469 * interested in validating only BPF helpers that can call subprogs as
9472 env->subprog_info[subprog].is_cb = true;
9473 if (bpf_pseudo_kfunc_call(insn) &&
9474 !is_sync_callback_calling_kfunc(insn->imm)) {
9475 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9476 func_id_name(insn->imm), insn->imm);
9478 } else if (!bpf_pseudo_kfunc_call(insn) &&
9479 !is_callback_calling_function(insn->imm)) { /* helper */
9480 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9481 func_id_name(insn->imm), insn->imm);
9485 if (is_async_callback_calling_insn(insn)) {
9486 struct bpf_verifier_state *async_cb;
9488 /* there is no real recursion here. timer callbacks are async */
9489 env->subprog_info[subprog].is_async_cb = true;
9490 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9494 callee = async_cb->frame[0];
9495 callee->async_entry_cnt = caller->async_entry_cnt + 1;
9497 /* Convert bpf_timer_set_callback() args into timer callback args */
9498 err = set_callee_state_cb(env, caller, callee, insn_idx);
9505 /* for callback functions enqueue entry to callback and
9506 * proceed with next instruction within current frame.
9508 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9509 if (!callback_state)
9512 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9517 callback_state->callback_unroll_depth++;
9518 callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9519 caller->callback_depth = 0;
9523 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9526 struct bpf_verifier_state *state = env->cur_state;
9527 struct bpf_func_state *caller;
9528 int err, subprog, target_insn;
9530 target_insn = *insn_idx + insn->imm + 1;
9531 subprog = find_subprog(env, target_insn);
9533 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9537 caller = state->frame[state->curframe];
9538 err = btf_check_subprog_call(env, subprog, caller->regs);
9541 if (subprog_is_global(env, subprog)) {
9542 const char *sub_name = subprog_name(env, subprog);
9544 /* Only global subprogs cannot be called with a lock held. */
9545 if (env->cur_state->active_lock.ptr) {
9546 verbose(env, "global function calls are not allowed while holding a lock,\n"
9547 "use static function instead\n");
9552 verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9557 verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9559 /* mark global subprog for verifying after main prog */
9560 subprog_aux(env, subprog)->called = true;
9561 clear_caller_saved_regs(env, caller->regs);
9563 /* All global functions return a 64-bit SCALAR_VALUE */
9564 mark_reg_unknown(env, caller->regs, BPF_REG_0);
9565 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9567 /* continue with next insn after call */
9571 /* for regular function entry setup new frame and continue
9574 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9578 clear_caller_saved_regs(env, caller->regs);
9580 /* and go analyze first insn of the callee */
9581 *insn_idx = env->subprog_info[subprog].start - 1;
9583 if (env->log.level & BPF_LOG_LEVEL) {
9584 verbose(env, "caller:\n");
9585 print_verifier_state(env, caller, true);
9586 verbose(env, "callee:\n");
9587 print_verifier_state(env, state->frame[state->curframe], true);
9593 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9594 struct bpf_func_state *caller,
9595 struct bpf_func_state *callee)
9597 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9598 * void *callback_ctx, u64 flags);
9599 * callback_fn(struct bpf_map *map, void *key, void *value,
9600 * void *callback_ctx);
9602 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9604 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9605 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9606 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9608 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9609 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9610 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9612 /* pointer to stack or null */
9613 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9616 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9620 static int set_callee_state(struct bpf_verifier_env *env,
9621 struct bpf_func_state *caller,
9622 struct bpf_func_state *callee, int insn_idx)
9626 /* copy r1 - r5 args that callee can access. The copy includes parent
9627 * pointers, which connects us up to the liveness chain
9629 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9630 callee->regs[i] = caller->regs[i];
9634 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9635 struct bpf_func_state *caller,
9636 struct bpf_func_state *callee,
9639 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9640 struct bpf_map *map;
9643 if (bpf_map_ptr_poisoned(insn_aux)) {
9644 verbose(env, "tail_call abusing map_ptr\n");
9648 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9649 if (!map->ops->map_set_for_each_callback_args ||
9650 !map->ops->map_for_each_callback) {
9651 verbose(env, "callback function not allowed for map\n");
9655 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9659 callee->in_callback_fn = true;
9660 callee->callback_ret_range = retval_range(0, 1);
9664 static int set_loop_callback_state(struct bpf_verifier_env *env,
9665 struct bpf_func_state *caller,
9666 struct bpf_func_state *callee,
9669 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9671 * callback_fn(u32 index, void *callback_ctx);
9673 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9674 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9677 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9678 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9679 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9681 callee->in_callback_fn = true;
9682 callee->callback_ret_range = retval_range(0, 1);
9686 static int set_timer_callback_state(struct bpf_verifier_env *env,
9687 struct bpf_func_state *caller,
9688 struct bpf_func_state *callee,
9691 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9693 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9694 * callback_fn(struct bpf_map *map, void *key, void *value);
9696 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9697 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9698 callee->regs[BPF_REG_1].map_ptr = map_ptr;
9700 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9701 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9702 callee->regs[BPF_REG_2].map_ptr = map_ptr;
9704 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9705 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9706 callee->regs[BPF_REG_3].map_ptr = map_ptr;
9709 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9710 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9711 callee->in_async_callback_fn = true;
9712 callee->callback_ret_range = retval_range(0, 1);
9716 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9717 struct bpf_func_state *caller,
9718 struct bpf_func_state *callee,
9721 /* bpf_find_vma(struct task_struct *task, u64 addr,
9722 * void *callback_fn, void *callback_ctx, u64 flags)
9723 * (callback_fn)(struct task_struct *task,
9724 * struct vm_area_struct *vma, void *callback_ctx);
9726 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9728 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9729 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9730 callee->regs[BPF_REG_2].btf = btf_vmlinux;
9731 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
9733 /* pointer to stack or null */
9734 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9737 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9738 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9739 callee->in_callback_fn = true;
9740 callee->callback_ret_range = retval_range(0, 1);
9744 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9745 struct bpf_func_state *caller,
9746 struct bpf_func_state *callee,
9749 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9750 * callback_ctx, u64 flags);
9751 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9753 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9754 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9755 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9758 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9759 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9760 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9762 callee->in_callback_fn = true;
9763 callee->callback_ret_range = retval_range(0, 1);
9767 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9768 struct bpf_func_state *caller,
9769 struct bpf_func_state *callee,
9772 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9773 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9775 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9776 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9777 * by this point, so look at 'root'
9779 struct btf_field *field;
9781 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9783 if (!field || !field->graph_root.value_btf_id)
9786 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9787 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9788 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9789 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9791 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9792 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9793 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9794 callee->in_callback_fn = true;
9795 callee->callback_ret_range = retval_range(0, 1);
9799 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9801 /* Are we currently verifying the callback for a rbtree helper that must
9802 * be called with lock held? If so, no need to complain about unreleased
9805 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9807 struct bpf_verifier_state *state = env->cur_state;
9808 struct bpf_insn *insn = env->prog->insnsi;
9809 struct bpf_func_state *callee;
9812 if (!state->curframe)
9815 callee = state->frame[state->curframe];
9817 if (!callee->in_callback_fn)
9820 kfunc_btf_id = insn[callee->callsite].imm;
9821 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9824 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
9826 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
9829 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9831 struct bpf_verifier_state *state = env->cur_state, *prev_st;
9832 struct bpf_func_state *caller, *callee;
9833 struct bpf_reg_state *r0;
9834 bool in_callback_fn;
9837 callee = state->frame[state->curframe];
9838 r0 = &callee->regs[BPF_REG_0];
9839 if (r0->type == PTR_TO_STACK) {
9840 /* technically it's ok to return caller's stack pointer
9841 * (or caller's caller's pointer) back to the caller,
9842 * since these pointers are valid. Only current stack
9843 * pointer will be invalid as soon as function exits,
9844 * but let's be conservative
9846 verbose(env, "cannot return stack pointer to the caller\n");
9850 caller = state->frame[state->curframe - 1];
9851 if (callee->in_callback_fn) {
9852 if (r0->type != SCALAR_VALUE) {
9853 verbose(env, "R0 not a scalar value\n");
9857 /* we are going to rely on register's precise value */
9858 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9859 err = err ?: mark_chain_precision(env, BPF_REG_0);
9863 /* enforce R0 return value range */
9864 if (!retval_range_within(callee->callback_ret_range, r0)) {
9865 verbose_invalid_scalar(env, r0, callee->callback_ret_range,
9866 "At callback return", "R0");
9869 if (!calls_callback(env, callee->callsite)) {
9870 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9871 *insn_idx, callee->callsite);
9875 /* return to the caller whatever r0 had in the callee */
9876 caller->regs[BPF_REG_0] = *r0;
9879 /* callback_fn frame should have released its own additions to parent's
9880 * reference state at this point, or check_reference_leak would
9881 * complain, hence it must be the same as the caller. There is no need
9884 if (!callee->in_callback_fn) {
9885 /* Transfer references to the caller */
9886 err = copy_reference_state(caller, callee);
9891 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9892 * there function call logic would reschedule callback visit. If iteration
9893 * converges is_state_visited() would prune that visit eventually.
9895 in_callback_fn = callee->in_callback_fn;
9897 *insn_idx = callee->callsite;
9899 *insn_idx = callee->callsite + 1;
9901 if (env->log.level & BPF_LOG_LEVEL) {
9902 verbose(env, "returning from callee:\n");
9903 print_verifier_state(env, callee, true);
9904 verbose(env, "to caller at %d:\n", *insn_idx);
9905 print_verifier_state(env, caller, true);
9907 /* clear everything in the callee. In case of exceptional exits using
9908 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
9909 free_func_state(callee);
9910 state->frame[state->curframe--] = NULL;
9912 /* for callbacks widen imprecise scalars to make programs like below verify:
9914 * struct ctx { int i; }
9915 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9917 * struct ctx = { .i = 0; }
9918 * bpf_loop(100, cb, &ctx, 0);
9920 * This is similar to what is done in process_iter_next_call() for open
9923 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9925 err = widen_imprecise_scalars(env, prev_st, state);
9932 static int do_refine_retval_range(struct bpf_verifier_env *env,
9933 struct bpf_reg_state *regs, int ret_type,
9935 struct bpf_call_arg_meta *meta)
9937 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
9939 if (ret_type != RET_INTEGER)
9943 case BPF_FUNC_get_stack:
9944 case BPF_FUNC_get_task_stack:
9945 case BPF_FUNC_probe_read_str:
9946 case BPF_FUNC_probe_read_kernel_str:
9947 case BPF_FUNC_probe_read_user_str:
9948 ret_reg->smax_value = meta->msize_max_value;
9949 ret_reg->s32_max_value = meta->msize_max_value;
9950 ret_reg->smin_value = -MAX_ERRNO;
9951 ret_reg->s32_min_value = -MAX_ERRNO;
9952 reg_bounds_sync(ret_reg);
9954 case BPF_FUNC_get_smp_processor_id:
9955 ret_reg->umax_value = nr_cpu_ids - 1;
9956 ret_reg->u32_max_value = nr_cpu_ids - 1;
9957 ret_reg->smax_value = nr_cpu_ids - 1;
9958 ret_reg->s32_max_value = nr_cpu_ids - 1;
9959 ret_reg->umin_value = 0;
9960 ret_reg->u32_min_value = 0;
9961 ret_reg->smin_value = 0;
9962 ret_reg->s32_min_value = 0;
9963 reg_bounds_sync(ret_reg);
9967 return reg_bounds_sanity_check(env, ret_reg, "retval");
9971 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9972 int func_id, int insn_idx)
9974 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9975 struct bpf_map *map = meta->map_ptr;
9977 if (func_id != BPF_FUNC_tail_call &&
9978 func_id != BPF_FUNC_map_lookup_elem &&
9979 func_id != BPF_FUNC_map_update_elem &&
9980 func_id != BPF_FUNC_map_delete_elem &&
9981 func_id != BPF_FUNC_map_push_elem &&
9982 func_id != BPF_FUNC_map_pop_elem &&
9983 func_id != BPF_FUNC_map_peek_elem &&
9984 func_id != BPF_FUNC_for_each_map_elem &&
9985 func_id != BPF_FUNC_redirect_map &&
9986 func_id != BPF_FUNC_map_lookup_percpu_elem)
9990 verbose(env, "kernel subsystem misconfigured verifier\n");
9994 /* In case of read-only, some additional restrictions
9995 * need to be applied in order to prevent altering the
9996 * state of the map from program side.
9998 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9999 (func_id == BPF_FUNC_map_delete_elem ||
10000 func_id == BPF_FUNC_map_update_elem ||
10001 func_id == BPF_FUNC_map_push_elem ||
10002 func_id == BPF_FUNC_map_pop_elem)) {
10003 verbose(env, "write into map forbidden\n");
10007 if (!BPF_MAP_PTR(aux->map_ptr_state))
10008 bpf_map_ptr_store(aux, meta->map_ptr,
10009 !meta->map_ptr->bypass_spec_v1);
10010 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
10011 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
10012 !meta->map_ptr->bypass_spec_v1);
10017 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10018 int func_id, int insn_idx)
10020 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10021 struct bpf_reg_state *regs = cur_regs(env), *reg;
10022 struct bpf_map *map = meta->map_ptr;
10026 if (func_id != BPF_FUNC_tail_call)
10028 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
10029 verbose(env, "kernel subsystem misconfigured verifier\n");
10033 reg = ®s[BPF_REG_3];
10034 val = reg->var_off.value;
10035 max = map->max_entries;
10037 if (!(is_reg_const(reg, false) && val < max)) {
10038 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10042 err = mark_chain_precision(env, BPF_REG_3);
10045 if (bpf_map_key_unseen(aux))
10046 bpf_map_key_store(aux, val);
10047 else if (!bpf_map_key_poisoned(aux) &&
10048 bpf_map_key_immediate(aux) != val)
10049 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10053 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
10055 struct bpf_func_state *state = cur_func(env);
10056 bool refs_lingering = false;
10059 if (!exception_exit && state->frameno && !state->in_callback_fn)
10062 for (i = 0; i < state->acquired_refs; i++) {
10063 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
10065 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
10066 state->refs[i].id, state->refs[i].insn_idx);
10067 refs_lingering = true;
10069 return refs_lingering ? -EINVAL : 0;
10072 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10073 struct bpf_reg_state *regs)
10075 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
10076 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
10077 struct bpf_map *fmt_map = fmt_reg->map_ptr;
10078 struct bpf_bprintf_data data = {};
10079 int err, fmt_map_off, num_args;
10083 /* data must be an array of u64 */
10084 if (data_len_reg->var_off.value % 8)
10086 num_args = data_len_reg->var_off.value / 8;
10088 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10089 * and map_direct_value_addr is set.
10091 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
10092 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10095 verbose(env, "verifier bug\n");
10098 fmt = (char *)(long)fmt_addr + fmt_map_off;
10100 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10101 * can focus on validating the format specifiers.
10103 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10105 verbose(env, "Invalid format string\n");
10110 static int check_get_func_ip(struct bpf_verifier_env *env)
10112 enum bpf_prog_type type = resolve_prog_type(env->prog);
10113 int func_id = BPF_FUNC_get_func_ip;
10115 if (type == BPF_PROG_TYPE_TRACING) {
10116 if (!bpf_prog_has_trampoline(env->prog)) {
10117 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10118 func_id_name(func_id), func_id);
10122 } else if (type == BPF_PROG_TYPE_KPROBE) {
10126 verbose(env, "func %s#%d not supported for program type %d\n",
10127 func_id_name(func_id), func_id, type);
10131 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10133 return &env->insn_aux_data[env->insn_idx];
10136 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10138 struct bpf_reg_state *regs = cur_regs(env);
10139 struct bpf_reg_state *reg = ®s[BPF_REG_4];
10140 bool reg_is_null = register_is_null(reg);
10143 mark_chain_precision(env, BPF_REG_4);
10145 return reg_is_null;
10148 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10150 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10152 if (!state->initialized) {
10153 state->initialized = 1;
10154 state->fit_for_inline = loop_flag_is_zero(env);
10155 state->callback_subprogno = subprogno;
10159 if (!state->fit_for_inline)
10162 state->fit_for_inline = (loop_flag_is_zero(env) &&
10163 state->callback_subprogno == subprogno);
10166 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10169 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10170 bool returns_cpu_specific_alloc_ptr = false;
10171 const struct bpf_func_proto *fn = NULL;
10172 enum bpf_return_type ret_type;
10173 enum bpf_type_flag ret_flag;
10174 struct bpf_reg_state *regs;
10175 struct bpf_call_arg_meta meta;
10176 int insn_idx = *insn_idx_p;
10178 int i, err, func_id;
10180 /* find function prototype */
10181 func_id = insn->imm;
10182 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
10183 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
10188 if (env->ops->get_func_proto)
10189 fn = env->ops->get_func_proto(func_id, env->prog);
10191 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
10196 /* eBPF programs must be GPL compatible to use GPL-ed functions */
10197 if (!env->prog->gpl_compatible && fn->gpl_only) {
10198 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10202 if (fn->allowed && !fn->allowed(env->prog)) {
10203 verbose(env, "helper call is not allowed in probe\n");
10207 if (!in_sleepable(env) && fn->might_sleep) {
10208 verbose(env, "helper call might sleep in a non-sleepable prog\n");
10212 /* With LD_ABS/IND some JITs save/restore skb from r1. */
10213 changes_data = bpf_helper_changes_pkt_data(fn->func);
10214 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10215 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10216 func_id_name(func_id), func_id);
10220 memset(&meta, 0, sizeof(meta));
10221 meta.pkt_access = fn->pkt_access;
10223 err = check_func_proto(fn, func_id);
10225 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10226 func_id_name(func_id), func_id);
10230 if (env->cur_state->active_rcu_lock) {
10231 if (fn->might_sleep) {
10232 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10233 func_id_name(func_id), func_id);
10237 if (in_sleepable(env) && is_storage_get_function(func_id))
10238 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10241 meta.func_id = func_id;
10243 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10244 err = check_func_arg(env, i, &meta, fn, insn_idx);
10249 err = record_func_map(env, &meta, func_id, insn_idx);
10253 err = record_func_key(env, &meta, func_id, insn_idx);
10257 /* Mark slots with STACK_MISC in case of raw mode, stack offset
10258 * is inferred from register state.
10260 for (i = 0; i < meta.access_size; i++) {
10261 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10262 BPF_WRITE, -1, false, false);
10267 regs = cur_regs(env);
10269 if (meta.release_regno) {
10271 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10272 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10273 * is safe to do directly.
10275 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10276 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10277 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10280 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
10281 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10282 u32 ref_obj_id = meta.ref_obj_id;
10283 bool in_rcu = in_rcu_cs(env);
10284 struct bpf_func_state *state;
10285 struct bpf_reg_state *reg;
10287 err = release_reference_state(cur_func(env), ref_obj_id);
10289 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10290 if (reg->ref_obj_id == ref_obj_id) {
10291 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10292 reg->ref_obj_id = 0;
10293 reg->type &= ~MEM_ALLOC;
10294 reg->type |= MEM_RCU;
10296 mark_reg_invalid(env, reg);
10301 } else if (meta.ref_obj_id) {
10302 err = release_reference(env, meta.ref_obj_id);
10303 } else if (register_is_null(®s[meta.release_regno])) {
10304 /* meta.ref_obj_id can only be 0 if register that is meant to be
10305 * released is NULL, which must be > R0.
10310 verbose(env, "func %s#%d reference has not been acquired before\n",
10311 func_id_name(func_id), func_id);
10317 case BPF_FUNC_tail_call:
10318 err = check_reference_leak(env, false);
10320 verbose(env, "tail_call would lead to reference leak\n");
10324 case BPF_FUNC_get_local_storage:
10325 /* check that flags argument in get_local_storage(map, flags) is 0,
10326 * this is required because get_local_storage() can't return an error.
10328 if (!register_is_null(®s[BPF_REG_2])) {
10329 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10333 case BPF_FUNC_for_each_map_elem:
10334 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10335 set_map_elem_callback_state);
10337 case BPF_FUNC_timer_set_callback:
10338 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10339 set_timer_callback_state);
10341 case BPF_FUNC_find_vma:
10342 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10343 set_find_vma_callback_state);
10345 case BPF_FUNC_snprintf:
10346 err = check_bpf_snprintf_call(env, regs);
10348 case BPF_FUNC_loop:
10349 update_loop_inline_state(env, meta.subprogno);
10350 /* Verifier relies on R1 value to determine if bpf_loop() iteration
10351 * is finished, thus mark it precise.
10353 err = mark_chain_precision(env, BPF_REG_1);
10356 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10357 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10358 set_loop_callback_state);
10360 cur_func(env)->callback_depth = 0;
10361 if (env->log.level & BPF_LOG_LEVEL2)
10362 verbose(env, "frame%d bpf_loop iteration limit reached\n",
10363 env->cur_state->curframe);
10366 case BPF_FUNC_dynptr_from_mem:
10367 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10368 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10369 reg_type_str(env, regs[BPF_REG_1].type));
10373 case BPF_FUNC_set_retval:
10374 if (prog_type == BPF_PROG_TYPE_LSM &&
10375 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10376 if (!env->prog->aux->attach_func_proto->type) {
10377 /* Make sure programs that attach to void
10378 * hooks don't try to modify return value.
10380 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10385 case BPF_FUNC_dynptr_data:
10387 struct bpf_reg_state *reg;
10388 int id, ref_obj_id;
10390 reg = get_dynptr_arg_reg(env, fn, regs);
10395 if (meta.dynptr_id) {
10396 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10399 if (meta.ref_obj_id) {
10400 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10404 id = dynptr_id(env, reg);
10406 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10410 ref_obj_id = dynptr_ref_obj_id(env, reg);
10411 if (ref_obj_id < 0) {
10412 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10416 meta.dynptr_id = id;
10417 meta.ref_obj_id = ref_obj_id;
10421 case BPF_FUNC_dynptr_write:
10423 enum bpf_dynptr_type dynptr_type;
10424 struct bpf_reg_state *reg;
10426 reg = get_dynptr_arg_reg(env, fn, regs);
10430 dynptr_type = dynptr_get_type(env, reg);
10431 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10434 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10435 /* this will trigger clear_all_pkt_pointers(), which will
10436 * invalidate all dynptr slices associated with the skb
10438 changes_data = true;
10442 case BPF_FUNC_per_cpu_ptr:
10443 case BPF_FUNC_this_cpu_ptr:
10445 struct bpf_reg_state *reg = ®s[BPF_REG_1];
10446 const struct btf_type *type;
10448 if (reg->type & MEM_RCU) {
10449 type = btf_type_by_id(reg->btf, reg->btf_id);
10450 if (!type || !btf_type_is_struct(type)) {
10451 verbose(env, "Helper has invalid btf/btf_id in R1\n");
10454 returns_cpu_specific_alloc_ptr = true;
10455 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10459 case BPF_FUNC_user_ringbuf_drain:
10460 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10461 set_user_ringbuf_callback_state);
10468 /* reset caller saved regs */
10469 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10470 mark_reg_not_init(env, regs, caller_saved[i]);
10471 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10474 /* helper call returns 64-bit value. */
10475 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10477 /* update return register (already marked as written above) */
10478 ret_type = fn->ret_type;
10479 ret_flag = type_flag(ret_type);
10481 switch (base_type(ret_type)) {
10483 /* sets type to SCALAR_VALUE */
10484 mark_reg_unknown(env, regs, BPF_REG_0);
10487 regs[BPF_REG_0].type = NOT_INIT;
10489 case RET_PTR_TO_MAP_VALUE:
10490 /* There is no offset yet applied, variable or fixed */
10491 mark_reg_known_zero(env, regs, BPF_REG_0);
10492 /* remember map_ptr, so that check_map_access()
10493 * can check 'value_size' boundary of memory access
10494 * to map element returned from bpf_map_lookup_elem()
10496 if (meta.map_ptr == NULL) {
10498 "kernel subsystem misconfigured verifier\n");
10501 regs[BPF_REG_0].map_ptr = meta.map_ptr;
10502 regs[BPF_REG_0].map_uid = meta.map_uid;
10503 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10504 if (!type_may_be_null(ret_type) &&
10505 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10506 regs[BPF_REG_0].id = ++env->id_gen;
10509 case RET_PTR_TO_SOCKET:
10510 mark_reg_known_zero(env, regs, BPF_REG_0);
10511 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10513 case RET_PTR_TO_SOCK_COMMON:
10514 mark_reg_known_zero(env, regs, BPF_REG_0);
10515 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10517 case RET_PTR_TO_TCP_SOCK:
10518 mark_reg_known_zero(env, regs, BPF_REG_0);
10519 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10521 case RET_PTR_TO_MEM:
10522 mark_reg_known_zero(env, regs, BPF_REG_0);
10523 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10524 regs[BPF_REG_0].mem_size = meta.mem_size;
10526 case RET_PTR_TO_MEM_OR_BTF_ID:
10528 const struct btf_type *t;
10530 mark_reg_known_zero(env, regs, BPF_REG_0);
10531 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10532 if (!btf_type_is_struct(t)) {
10534 const struct btf_type *ret;
10537 /* resolve the type size of ksym. */
10538 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10540 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10541 verbose(env, "unable to resolve the size of type '%s': %ld\n",
10542 tname, PTR_ERR(ret));
10545 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10546 regs[BPF_REG_0].mem_size = tsize;
10548 if (returns_cpu_specific_alloc_ptr) {
10549 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10551 /* MEM_RDONLY may be carried from ret_flag, but it
10552 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10553 * it will confuse the check of PTR_TO_BTF_ID in
10554 * check_mem_access().
10556 ret_flag &= ~MEM_RDONLY;
10557 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10560 regs[BPF_REG_0].btf = meta.ret_btf;
10561 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10565 case RET_PTR_TO_BTF_ID:
10567 struct btf *ret_btf;
10570 mark_reg_known_zero(env, regs, BPF_REG_0);
10571 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10572 if (func_id == BPF_FUNC_kptr_xchg) {
10573 ret_btf = meta.kptr_field->kptr.btf;
10574 ret_btf_id = meta.kptr_field->kptr.btf_id;
10575 if (!btf_is_kernel(ret_btf)) {
10576 regs[BPF_REG_0].type |= MEM_ALLOC;
10577 if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10578 regs[BPF_REG_0].type |= MEM_PERCPU;
10581 if (fn->ret_btf_id == BPF_PTR_POISON) {
10582 verbose(env, "verifier internal error:");
10583 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10584 func_id_name(func_id));
10587 ret_btf = btf_vmlinux;
10588 ret_btf_id = *fn->ret_btf_id;
10590 if (ret_btf_id == 0) {
10591 verbose(env, "invalid return type %u of func %s#%d\n",
10592 base_type(ret_type), func_id_name(func_id),
10596 regs[BPF_REG_0].btf = ret_btf;
10597 regs[BPF_REG_0].btf_id = ret_btf_id;
10601 verbose(env, "unknown return type %u of func %s#%d\n",
10602 base_type(ret_type), func_id_name(func_id), func_id);
10606 if (type_may_be_null(regs[BPF_REG_0].type))
10607 regs[BPF_REG_0].id = ++env->id_gen;
10609 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10610 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10611 func_id_name(func_id), func_id);
10615 if (is_dynptr_ref_function(func_id))
10616 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10618 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10619 /* For release_reference() */
10620 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10621 } else if (is_acquire_function(func_id, meta.map_ptr)) {
10622 int id = acquire_reference_state(env, insn_idx);
10626 /* For mark_ptr_or_null_reg() */
10627 regs[BPF_REG_0].id = id;
10628 /* For release_reference() */
10629 regs[BPF_REG_0].ref_obj_id = id;
10632 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
10636 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10640 if ((func_id == BPF_FUNC_get_stack ||
10641 func_id == BPF_FUNC_get_task_stack) &&
10642 !env->prog->has_callchain_buf) {
10643 const char *err_str;
10645 #ifdef CONFIG_PERF_EVENTS
10646 err = get_callchain_buffers(sysctl_perf_event_max_stack);
10647 err_str = "cannot get callchain buffer for func %s#%d\n";
10650 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10653 verbose(env, err_str, func_id_name(func_id), func_id);
10657 env->prog->has_callchain_buf = true;
10660 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10661 env->prog->call_get_stack = true;
10663 if (func_id == BPF_FUNC_get_func_ip) {
10664 if (check_get_func_ip(env))
10666 env->prog->call_get_func_ip = true;
10670 clear_all_pkt_pointers(env);
10674 /* mark_btf_func_reg_size() is used when the reg size is determined by
10675 * the BTF func_proto's return value size and argument.
10677 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10680 struct bpf_reg_state *reg = &cur_regs(env)[regno];
10682 if (regno == BPF_REG_0) {
10683 /* Function return value */
10684 reg->live |= REG_LIVE_WRITTEN;
10685 reg->subreg_def = reg_size == sizeof(u64) ?
10686 DEF_NOT_SUBREG : env->insn_idx + 1;
10688 /* Function argument */
10689 if (reg_size == sizeof(u64)) {
10690 mark_insn_zext(env, reg);
10691 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10693 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10698 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10700 return meta->kfunc_flags & KF_ACQUIRE;
10703 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10705 return meta->kfunc_flags & KF_RELEASE;
10708 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10710 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10713 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10715 return meta->kfunc_flags & KF_SLEEPABLE;
10718 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10720 return meta->kfunc_flags & KF_DESTRUCTIVE;
10723 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10725 return meta->kfunc_flags & KF_RCU;
10728 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10730 return meta->kfunc_flags & KF_RCU_PROTECTED;
10733 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10734 const struct btf_param *arg,
10735 const struct bpf_reg_state *reg)
10737 const struct btf_type *t;
10739 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10740 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10743 return btf_param_match_suffix(btf, arg, "__sz");
10746 static bool is_kfunc_arg_const_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, "__szk");
10759 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10761 return btf_param_match_suffix(btf, arg, "__opt");
10764 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10766 return btf_param_match_suffix(btf, arg, "__k");
10769 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10771 return btf_param_match_suffix(btf, arg, "__ign");
10774 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
10776 return btf_param_match_suffix(btf, arg, "__map");
10779 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10781 return btf_param_match_suffix(btf, arg, "__alloc");
10784 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10786 return btf_param_match_suffix(btf, arg, "__uninit");
10789 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10791 return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
10794 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10796 return btf_param_match_suffix(btf, arg, "__nullable");
10799 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
10801 return btf_param_match_suffix(btf, arg, "__str");
10804 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10805 const struct btf_param *arg,
10808 int len, target_len = strlen(name);
10809 const char *param_name;
10811 param_name = btf_name_by_offset(btf, arg->name_off);
10812 if (str_is_empty(param_name))
10814 len = strlen(param_name);
10815 if (len != target_len)
10817 if (strcmp(param_name, name))
10825 KF_ARG_LIST_HEAD_ID,
10826 KF_ARG_LIST_NODE_ID,
10831 BTF_ID_LIST(kf_arg_btf_ids)
10832 BTF_ID(struct, bpf_dynptr_kern)
10833 BTF_ID(struct, bpf_list_head)
10834 BTF_ID(struct, bpf_list_node)
10835 BTF_ID(struct, bpf_rb_root)
10836 BTF_ID(struct, bpf_rb_node)
10838 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10839 const struct btf_param *arg, int type)
10841 const struct btf_type *t;
10844 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10847 if (!btf_type_is_ptr(t))
10849 t = btf_type_skip_modifiers(btf, t->type, &res_id);
10852 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10855 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10857 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10860 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10862 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10865 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10867 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10870 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10872 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10875 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10877 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10880 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10881 const struct btf_param *arg)
10883 const struct btf_type *t;
10885 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10892 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10893 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10894 const struct btf *btf,
10895 const struct btf_type *t, int rec)
10897 const struct btf_type *member_type;
10898 const struct btf_member *member;
10901 if (!btf_type_is_struct(t))
10904 for_each_member(i, t, member) {
10905 const struct btf_array *array;
10907 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10908 if (btf_type_is_struct(member_type)) {
10910 verbose(env, "max struct nesting depth exceeded\n");
10913 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10917 if (btf_type_is_array(member_type)) {
10918 array = btf_array(member_type);
10919 if (!array->nelems)
10921 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10922 if (!btf_type_is_scalar(member_type))
10926 if (!btf_type_is_scalar(member_type))
10932 enum kfunc_ptr_arg_type {
10934 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
10935 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10936 KF_ARG_PTR_TO_DYNPTR,
10937 KF_ARG_PTR_TO_ITER,
10938 KF_ARG_PTR_TO_LIST_HEAD,
10939 KF_ARG_PTR_TO_LIST_NODE,
10940 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
10942 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
10943 KF_ARG_PTR_TO_CALLBACK,
10944 KF_ARG_PTR_TO_RB_ROOT,
10945 KF_ARG_PTR_TO_RB_NODE,
10946 KF_ARG_PTR_TO_NULL,
10947 KF_ARG_PTR_TO_CONST_STR,
10951 enum special_kfunc_type {
10952 KF_bpf_obj_new_impl,
10953 KF_bpf_obj_drop_impl,
10954 KF_bpf_refcount_acquire_impl,
10955 KF_bpf_list_push_front_impl,
10956 KF_bpf_list_push_back_impl,
10957 KF_bpf_list_pop_front,
10958 KF_bpf_list_pop_back,
10959 KF_bpf_cast_to_kern_ctx,
10960 KF_bpf_rdonly_cast,
10961 KF_bpf_rcu_read_lock,
10962 KF_bpf_rcu_read_unlock,
10963 KF_bpf_rbtree_remove,
10964 KF_bpf_rbtree_add_impl,
10965 KF_bpf_rbtree_first,
10966 KF_bpf_dynptr_from_skb,
10967 KF_bpf_dynptr_from_xdp,
10968 KF_bpf_dynptr_slice,
10969 KF_bpf_dynptr_slice_rdwr,
10970 KF_bpf_dynptr_clone,
10971 KF_bpf_percpu_obj_new_impl,
10972 KF_bpf_percpu_obj_drop_impl,
10974 KF_bpf_iter_css_task_new,
10977 BTF_SET_START(special_kfunc_set)
10978 BTF_ID(func, bpf_obj_new_impl)
10979 BTF_ID(func, bpf_obj_drop_impl)
10980 BTF_ID(func, bpf_refcount_acquire_impl)
10981 BTF_ID(func, bpf_list_push_front_impl)
10982 BTF_ID(func, bpf_list_push_back_impl)
10983 BTF_ID(func, bpf_list_pop_front)
10984 BTF_ID(func, bpf_list_pop_back)
10985 BTF_ID(func, bpf_cast_to_kern_ctx)
10986 BTF_ID(func, bpf_rdonly_cast)
10987 BTF_ID(func, bpf_rbtree_remove)
10988 BTF_ID(func, bpf_rbtree_add_impl)
10989 BTF_ID(func, bpf_rbtree_first)
10990 BTF_ID(func, bpf_dynptr_from_skb)
10991 BTF_ID(func, bpf_dynptr_from_xdp)
10992 BTF_ID(func, bpf_dynptr_slice)
10993 BTF_ID(func, bpf_dynptr_slice_rdwr)
10994 BTF_ID(func, bpf_dynptr_clone)
10995 BTF_ID(func, bpf_percpu_obj_new_impl)
10996 BTF_ID(func, bpf_percpu_obj_drop_impl)
10997 BTF_ID(func, bpf_throw)
10998 #ifdef CONFIG_CGROUPS
10999 BTF_ID(func, bpf_iter_css_task_new)
11001 BTF_SET_END(special_kfunc_set)
11003 BTF_ID_LIST(special_kfunc_list)
11004 BTF_ID(func, bpf_obj_new_impl)
11005 BTF_ID(func, bpf_obj_drop_impl)
11006 BTF_ID(func, bpf_refcount_acquire_impl)
11007 BTF_ID(func, bpf_list_push_front_impl)
11008 BTF_ID(func, bpf_list_push_back_impl)
11009 BTF_ID(func, bpf_list_pop_front)
11010 BTF_ID(func, bpf_list_pop_back)
11011 BTF_ID(func, bpf_cast_to_kern_ctx)
11012 BTF_ID(func, bpf_rdonly_cast)
11013 BTF_ID(func, bpf_rcu_read_lock)
11014 BTF_ID(func, bpf_rcu_read_unlock)
11015 BTF_ID(func, bpf_rbtree_remove)
11016 BTF_ID(func, bpf_rbtree_add_impl)
11017 BTF_ID(func, bpf_rbtree_first)
11018 BTF_ID(func, bpf_dynptr_from_skb)
11019 BTF_ID(func, bpf_dynptr_from_xdp)
11020 BTF_ID(func, bpf_dynptr_slice)
11021 BTF_ID(func, bpf_dynptr_slice_rdwr)
11022 BTF_ID(func, bpf_dynptr_clone)
11023 BTF_ID(func, bpf_percpu_obj_new_impl)
11024 BTF_ID(func, bpf_percpu_obj_drop_impl)
11025 BTF_ID(func, bpf_throw)
11026 #ifdef CONFIG_CGROUPS
11027 BTF_ID(func, bpf_iter_css_task_new)
11032 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
11034 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
11035 meta->arg_owning_ref) {
11039 return meta->kfunc_flags & KF_RET_NULL;
11042 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
11044 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
11047 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
11049 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11052 static enum kfunc_ptr_arg_type
11053 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
11054 struct bpf_kfunc_call_arg_meta *meta,
11055 const struct btf_type *t, const struct btf_type *ref_t,
11056 const char *ref_tname, const struct btf_param *args,
11057 int argno, int nargs)
11059 u32 regno = argno + 1;
11060 struct bpf_reg_state *regs = cur_regs(env);
11061 struct bpf_reg_state *reg = ®s[regno];
11062 bool arg_mem_size = false;
11064 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
11065 return KF_ARG_PTR_TO_CTX;
11067 /* In this function, we verify the kfunc's BTF as per the argument type,
11068 * leaving the rest of the verification with respect to the register
11069 * type to our caller. When a set of conditions hold in the BTF type of
11070 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11072 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
11073 return KF_ARG_PTR_TO_CTX;
11075 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
11076 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11078 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
11079 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11081 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
11082 return KF_ARG_PTR_TO_DYNPTR;
11084 if (is_kfunc_arg_iter(meta, argno))
11085 return KF_ARG_PTR_TO_ITER;
11087 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
11088 return KF_ARG_PTR_TO_LIST_HEAD;
11090 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
11091 return KF_ARG_PTR_TO_LIST_NODE;
11093 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
11094 return KF_ARG_PTR_TO_RB_ROOT;
11096 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
11097 return KF_ARG_PTR_TO_RB_NODE;
11099 if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
11100 return KF_ARG_PTR_TO_CONST_STR;
11102 if (is_kfunc_arg_map(meta->btf, &args[argno]))
11103 return KF_ARG_PTR_TO_MAP;
11105 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11106 if (!btf_type_is_struct(ref_t)) {
11107 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11108 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11111 return KF_ARG_PTR_TO_BTF_ID;
11114 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11115 return KF_ARG_PTR_TO_CALLBACK;
11117 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11118 return KF_ARG_PTR_TO_NULL;
11120 if (argno + 1 < nargs &&
11121 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
11122 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
11123 arg_mem_size = true;
11125 /* This is the catch all argument type of register types supported by
11126 * check_helper_mem_access. However, we only allow when argument type is
11127 * pointer to scalar, or struct composed (recursively) of scalars. When
11128 * arg_mem_size is true, the pointer can be void *.
11130 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11131 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11132 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11133 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11136 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11139 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11140 struct bpf_reg_state *reg,
11141 const struct btf_type *ref_t,
11142 const char *ref_tname, u32 ref_id,
11143 struct bpf_kfunc_call_arg_meta *meta,
11146 const struct btf_type *reg_ref_t;
11147 bool strict_type_match = false;
11148 const struct btf *reg_btf;
11149 const char *reg_ref_tname;
11152 if (base_type(reg->type) == PTR_TO_BTF_ID) {
11153 reg_btf = reg->btf;
11154 reg_ref_id = reg->btf_id;
11156 reg_btf = btf_vmlinux;
11157 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11160 /* Enforce strict type matching for calls to kfuncs that are acquiring
11161 * or releasing a reference, or are no-cast aliases. We do _not_
11162 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11163 * as we want to enable BPF programs to pass types that are bitwise
11164 * equivalent without forcing them to explicitly cast with something
11165 * like bpf_cast_to_kern_ctx().
11167 * For example, say we had a type like the following:
11169 * struct bpf_cpumask {
11170 * cpumask_t cpumask;
11171 * refcount_t usage;
11174 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11175 * to a struct cpumask, so it would be safe to pass a struct
11176 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11178 * The philosophy here is similar to how we allow scalars of different
11179 * types to be passed to kfuncs as long as the size is the same. The
11180 * only difference here is that we're simply allowing
11181 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11184 if (is_kfunc_acquire(meta) ||
11185 (is_kfunc_release(meta) && reg->ref_obj_id) ||
11186 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11187 strict_type_match = true;
11189 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
11191 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
11192 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11193 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
11194 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11195 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11196 btf_type_str(reg_ref_t), reg_ref_tname);
11202 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11204 struct bpf_verifier_state *state = env->cur_state;
11205 struct btf_record *rec = reg_btf_record(reg);
11207 if (!state->active_lock.ptr) {
11208 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11212 if (type_flag(reg->type) & NON_OWN_REF) {
11213 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11217 reg->type |= NON_OWN_REF;
11218 if (rec->refcount_off >= 0)
11219 reg->type |= MEM_RCU;
11224 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11226 struct bpf_func_state *state, *unused;
11227 struct bpf_reg_state *reg;
11230 state = cur_func(env);
11233 verbose(env, "verifier internal error: ref_obj_id is zero for "
11234 "owning -> non-owning conversion\n");
11238 for (i = 0; i < state->acquired_refs; i++) {
11239 if (state->refs[i].id != ref_obj_id)
11242 /* Clear ref_obj_id here so release_reference doesn't clobber
11245 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11246 if (reg->ref_obj_id == ref_obj_id) {
11247 reg->ref_obj_id = 0;
11248 ref_set_non_owning(env, reg);
11254 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11258 /* Implementation details:
11260 * Each register points to some region of memory, which we define as an
11261 * allocation. Each allocation may embed a bpf_spin_lock which protects any
11262 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11263 * allocation. The lock and the data it protects are colocated in the same
11266 * Hence, everytime a register holds a pointer value pointing to such
11267 * allocation, the verifier preserves a unique reg->id for it.
11269 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11270 * bpf_spin_lock is called.
11272 * To enable this, lock state in the verifier captures two values:
11273 * active_lock.ptr = Register's type specific pointer
11274 * active_lock.id = A unique ID for each register pointer value
11276 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11277 * supported register types.
11279 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11280 * allocated objects is the reg->btf pointer.
11282 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11283 * can establish the provenance of the map value statically for each distinct
11284 * lookup into such maps. They always contain a single map value hence unique
11285 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11287 * So, in case of global variables, they use array maps with max_entries = 1,
11288 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11289 * into the same map value as max_entries is 1, as described above).
11291 * In case of inner map lookups, the inner map pointer has same map_ptr as the
11292 * outer map pointer (in verifier context), but each lookup into an inner map
11293 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11294 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11295 * will get different reg->id assigned to each lookup, hence different
11298 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11299 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11300 * returned from bpf_obj_new. Each allocation receives a new reg->id.
11302 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11307 switch ((int)reg->type) {
11308 case PTR_TO_MAP_VALUE:
11309 ptr = reg->map_ptr;
11311 case PTR_TO_BTF_ID | MEM_ALLOC:
11315 verbose(env, "verifier internal error: unknown reg type for lock check\n");
11320 if (!env->cur_state->active_lock.ptr)
11322 if (env->cur_state->active_lock.ptr != ptr ||
11323 env->cur_state->active_lock.id != id) {
11324 verbose(env, "held lock and object are not in the same allocation\n");
11330 static bool is_bpf_list_api_kfunc(u32 btf_id)
11332 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11333 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11334 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11335 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11338 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11340 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11341 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11342 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11345 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11347 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11348 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11351 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11353 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11356 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11358 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11359 insn->imm == special_kfunc_list[KF_bpf_throw];
11362 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11364 return is_bpf_rbtree_api_kfunc(btf_id);
11367 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11368 enum btf_field_type head_field_type,
11373 switch (head_field_type) {
11374 case BPF_LIST_HEAD:
11375 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11378 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11381 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11382 btf_field_type_name(head_field_type));
11387 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11388 btf_field_type_name(head_field_type));
11392 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11393 enum btf_field_type node_field_type,
11398 switch (node_field_type) {
11399 case BPF_LIST_NODE:
11400 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11401 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11404 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11405 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11408 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11409 btf_field_type_name(node_field_type));
11414 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11415 btf_field_type_name(node_field_type));
11420 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11421 struct bpf_reg_state *reg, u32 regno,
11422 struct bpf_kfunc_call_arg_meta *meta,
11423 enum btf_field_type head_field_type,
11424 struct btf_field **head_field)
11426 const char *head_type_name;
11427 struct btf_field *field;
11428 struct btf_record *rec;
11431 if (meta->btf != btf_vmlinux) {
11432 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11436 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11439 head_type_name = btf_field_type_name(head_field_type);
11440 if (!tnum_is_const(reg->var_off)) {
11442 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11443 regno, head_type_name);
11447 rec = reg_btf_record(reg);
11448 head_off = reg->off + reg->var_off.value;
11449 field = btf_record_find(rec, head_off, head_field_type);
11451 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11455 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11456 if (check_reg_allocation_locked(env, reg)) {
11457 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11458 rec->spin_lock_off, head_type_name);
11463 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11466 *head_field = field;
11470 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11471 struct bpf_reg_state *reg, u32 regno,
11472 struct bpf_kfunc_call_arg_meta *meta)
11474 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11475 &meta->arg_list_head.field);
11478 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11479 struct bpf_reg_state *reg, u32 regno,
11480 struct bpf_kfunc_call_arg_meta *meta)
11482 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11483 &meta->arg_rbtree_root.field);
11487 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11488 struct bpf_reg_state *reg, u32 regno,
11489 struct bpf_kfunc_call_arg_meta *meta,
11490 enum btf_field_type head_field_type,
11491 enum btf_field_type node_field_type,
11492 struct btf_field **node_field)
11494 const char *node_type_name;
11495 const struct btf_type *et, *t;
11496 struct btf_field *field;
11499 if (meta->btf != btf_vmlinux) {
11500 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11504 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11507 node_type_name = btf_field_type_name(node_field_type);
11508 if (!tnum_is_const(reg->var_off)) {
11510 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11511 regno, node_type_name);
11515 node_off = reg->off + reg->var_off.value;
11516 field = reg_find_field_offset(reg, node_off, node_field_type);
11517 if (!field || field->offset != node_off) {
11518 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11522 field = *node_field;
11524 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11525 t = btf_type_by_id(reg->btf, reg->btf_id);
11526 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11527 field->graph_root.value_btf_id, true)) {
11528 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11529 "in struct %s, but arg is at offset=%d in struct %s\n",
11530 btf_field_type_name(head_field_type),
11531 btf_field_type_name(node_field_type),
11532 field->graph_root.node_offset,
11533 btf_name_by_offset(field->graph_root.btf, et->name_off),
11534 node_off, btf_name_by_offset(reg->btf, t->name_off));
11537 meta->arg_btf = reg->btf;
11538 meta->arg_btf_id = reg->btf_id;
11540 if (node_off != field->graph_root.node_offset) {
11541 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11542 node_off, btf_field_type_name(node_field_type),
11543 field->graph_root.node_offset,
11544 btf_name_by_offset(field->graph_root.btf, et->name_off));
11551 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11552 struct bpf_reg_state *reg, u32 regno,
11553 struct bpf_kfunc_call_arg_meta *meta)
11555 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11556 BPF_LIST_HEAD, BPF_LIST_NODE,
11557 &meta->arg_list_head.field);
11560 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11561 struct bpf_reg_state *reg, u32 regno,
11562 struct bpf_kfunc_call_arg_meta *meta)
11564 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11565 BPF_RB_ROOT, BPF_RB_NODE,
11566 &meta->arg_rbtree_root.field);
11570 * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11571 * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11572 * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11573 * them can only be attached to some specific hook points.
11575 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11577 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11579 switch (prog_type) {
11580 case BPF_PROG_TYPE_LSM:
11582 case BPF_PROG_TYPE_TRACING:
11583 if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11587 return in_sleepable(env);
11591 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11594 const char *func_name = meta->func_name, *ref_tname;
11595 const struct btf *btf = meta->btf;
11596 const struct btf_param *args;
11597 struct btf_record *rec;
11601 args = (const struct btf_param *)(meta->func_proto + 1);
11602 nargs = btf_type_vlen(meta->func_proto);
11603 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11604 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11605 MAX_BPF_FUNC_REG_ARGS);
11609 /* Check that BTF function arguments match actual types that the
11612 for (i = 0; i < nargs; i++) {
11613 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
11614 const struct btf_type *t, *ref_t, *resolve_ret;
11615 enum bpf_arg_type arg_type = ARG_DONTCARE;
11616 u32 regno = i + 1, ref_id, type_size;
11617 bool is_ret_buf_sz = false;
11620 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11622 if (is_kfunc_arg_ignore(btf, &args[i]))
11625 if (btf_type_is_scalar(t)) {
11626 if (reg->type != SCALAR_VALUE) {
11627 verbose(env, "R%d is not a scalar\n", regno);
11631 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11632 if (meta->arg_constant.found) {
11633 verbose(env, "verifier internal error: only one constant argument permitted\n");
11636 if (!tnum_is_const(reg->var_off)) {
11637 verbose(env, "R%d must be a known constant\n", regno);
11640 ret = mark_chain_precision(env, regno);
11643 meta->arg_constant.found = true;
11644 meta->arg_constant.value = reg->var_off.value;
11645 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11646 meta->r0_rdonly = true;
11647 is_ret_buf_sz = true;
11648 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11649 is_ret_buf_sz = true;
11652 if (is_ret_buf_sz) {
11653 if (meta->r0_size) {
11654 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11658 if (!tnum_is_const(reg->var_off)) {
11659 verbose(env, "R%d is not a const\n", regno);
11663 meta->r0_size = reg->var_off.value;
11664 ret = mark_chain_precision(env, regno);
11671 if (!btf_type_is_ptr(t)) {
11672 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11676 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11677 (register_is_null(reg) || type_may_be_null(reg->type)) &&
11678 !is_kfunc_arg_nullable(meta->btf, &args[i])) {
11679 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11683 if (reg->ref_obj_id) {
11684 if (is_kfunc_release(meta) && meta->ref_obj_id) {
11685 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11686 regno, reg->ref_obj_id,
11690 meta->ref_obj_id = reg->ref_obj_id;
11691 if (is_kfunc_release(meta))
11692 meta->release_regno = regno;
11695 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11696 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11698 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11699 if (kf_arg_type < 0)
11700 return kf_arg_type;
11702 switch (kf_arg_type) {
11703 case KF_ARG_PTR_TO_NULL:
11705 case KF_ARG_PTR_TO_MAP:
11706 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11707 case KF_ARG_PTR_TO_BTF_ID:
11708 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11711 if (!is_trusted_reg(reg)) {
11712 if (!is_kfunc_rcu(meta)) {
11713 verbose(env, "R%d must be referenced or trusted\n", regno);
11716 if (!is_rcu_reg(reg)) {
11717 verbose(env, "R%d must be a rcu pointer\n", regno);
11723 case KF_ARG_PTR_TO_CTX:
11724 /* Trusted arguments have the same offset checks as release arguments */
11725 arg_type |= OBJ_RELEASE;
11727 case KF_ARG_PTR_TO_DYNPTR:
11728 case KF_ARG_PTR_TO_ITER:
11729 case KF_ARG_PTR_TO_LIST_HEAD:
11730 case KF_ARG_PTR_TO_LIST_NODE:
11731 case KF_ARG_PTR_TO_RB_ROOT:
11732 case KF_ARG_PTR_TO_RB_NODE:
11733 case KF_ARG_PTR_TO_MEM:
11734 case KF_ARG_PTR_TO_MEM_SIZE:
11735 case KF_ARG_PTR_TO_CALLBACK:
11736 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11737 case KF_ARG_PTR_TO_CONST_STR:
11738 /* Trusted by default */
11745 if (is_kfunc_release(meta) && reg->ref_obj_id)
11746 arg_type |= OBJ_RELEASE;
11747 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11751 switch (kf_arg_type) {
11752 case KF_ARG_PTR_TO_CTX:
11753 if (reg->type != PTR_TO_CTX) {
11754 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11758 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11759 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11762 meta->ret_btf_id = ret;
11765 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11766 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
11767 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
11768 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
11771 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
11772 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
11773 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
11777 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11780 if (!reg->ref_obj_id) {
11781 verbose(env, "allocated object must be referenced\n");
11784 if (meta->btf == btf_vmlinux) {
11785 meta->arg_btf = reg->btf;
11786 meta->arg_btf_id = reg->btf_id;
11789 case KF_ARG_PTR_TO_DYNPTR:
11791 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11792 int clone_ref_obj_id = 0;
11794 if (reg->type != PTR_TO_STACK &&
11795 reg->type != CONST_PTR_TO_DYNPTR) {
11796 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11800 if (reg->type == CONST_PTR_TO_DYNPTR)
11801 dynptr_arg_type |= MEM_RDONLY;
11803 if (is_kfunc_arg_uninit(btf, &args[i]))
11804 dynptr_arg_type |= MEM_UNINIT;
11806 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11807 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11808 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11809 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11810 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11811 (dynptr_arg_type & MEM_UNINIT)) {
11812 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11814 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11815 verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11819 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11820 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11821 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11822 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11827 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11831 if (!(dynptr_arg_type & MEM_UNINIT)) {
11832 int id = dynptr_id(env, reg);
11835 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11838 meta->initialized_dynptr.id = id;
11839 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11840 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11845 case KF_ARG_PTR_TO_ITER:
11846 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
11847 if (!check_css_task_iter_allowlist(env)) {
11848 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
11852 ret = process_iter_arg(env, regno, insn_idx, meta);
11856 case KF_ARG_PTR_TO_LIST_HEAD:
11857 if (reg->type != PTR_TO_MAP_VALUE &&
11858 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11859 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11862 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11863 verbose(env, "allocated object must be referenced\n");
11866 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11870 case KF_ARG_PTR_TO_RB_ROOT:
11871 if (reg->type != PTR_TO_MAP_VALUE &&
11872 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11873 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11876 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11877 verbose(env, "allocated object must be referenced\n");
11880 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11884 case KF_ARG_PTR_TO_LIST_NODE:
11885 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11886 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11889 if (!reg->ref_obj_id) {
11890 verbose(env, "allocated object must be referenced\n");
11893 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11897 case KF_ARG_PTR_TO_RB_NODE:
11898 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11899 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11900 verbose(env, "rbtree_remove node input must be non-owning ref\n");
11903 if (in_rbtree_lock_required_cb(env)) {
11904 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11908 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11909 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11912 if (!reg->ref_obj_id) {
11913 verbose(env, "allocated object must be referenced\n");
11918 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11922 case KF_ARG_PTR_TO_MAP:
11923 /* If argument has '__map' suffix expect 'struct bpf_map *' */
11924 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
11925 ref_t = btf_type_by_id(btf_vmlinux, ref_id);
11926 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11928 case KF_ARG_PTR_TO_BTF_ID:
11929 /* Only base_type is checked, further checks are done here */
11930 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11931 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11932 !reg2btf_ids[base_type(reg->type)]) {
11933 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11934 verbose(env, "expected %s or socket\n",
11935 reg_type_str(env, base_type(reg->type) |
11936 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11939 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11943 case KF_ARG_PTR_TO_MEM:
11944 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11945 if (IS_ERR(resolve_ret)) {
11946 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11947 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11950 ret = check_mem_reg(env, reg, regno, type_size);
11954 case KF_ARG_PTR_TO_MEM_SIZE:
11956 struct bpf_reg_state *buff_reg = ®s[regno];
11957 const struct btf_param *buff_arg = &args[i];
11958 struct bpf_reg_state *size_reg = ®s[regno + 1];
11959 const struct btf_param *size_arg = &args[i + 1];
11961 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11962 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11964 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11969 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11970 if (meta->arg_constant.found) {
11971 verbose(env, "verifier internal error: only one constant argument permitted\n");
11974 if (!tnum_is_const(size_reg->var_off)) {
11975 verbose(env, "R%d must be a known constant\n", regno + 1);
11978 meta->arg_constant.found = true;
11979 meta->arg_constant.value = size_reg->var_off.value;
11982 /* Skip next '__sz' or '__szk' argument */
11986 case KF_ARG_PTR_TO_CALLBACK:
11987 if (reg->type != PTR_TO_FUNC) {
11988 verbose(env, "arg%d expected pointer to func\n", i);
11991 meta->subprogno = reg->subprogno;
11993 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11994 if (!type_is_ptr_alloc_obj(reg->type)) {
11995 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11998 if (!type_is_non_owning_ref(reg->type))
11999 meta->arg_owning_ref = true;
12001 rec = reg_btf_record(reg);
12003 verbose(env, "verifier internal error: Couldn't find btf_record\n");
12007 if (rec->refcount_off < 0) {
12008 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
12012 meta->arg_btf = reg->btf;
12013 meta->arg_btf_id = reg->btf_id;
12015 case KF_ARG_PTR_TO_CONST_STR:
12016 if (reg->type != PTR_TO_MAP_VALUE) {
12017 verbose(env, "arg#%d doesn't point to a const string\n", i);
12020 ret = check_reg_const_str(env, reg, regno);
12027 if (is_kfunc_release(meta) && !meta->release_regno) {
12028 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
12036 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
12037 struct bpf_insn *insn,
12038 struct bpf_kfunc_call_arg_meta *meta,
12039 const char **kfunc_name)
12041 const struct btf_type *func, *func_proto;
12042 u32 func_id, *kfunc_flags;
12043 const char *func_name;
12044 struct btf *desc_btf;
12047 *kfunc_name = NULL;
12052 desc_btf = find_kfunc_desc_btf(env, insn->off);
12053 if (IS_ERR(desc_btf))
12054 return PTR_ERR(desc_btf);
12056 func_id = insn->imm;
12057 func = btf_type_by_id(desc_btf, func_id);
12058 func_name = btf_name_by_offset(desc_btf, func->name_off);
12060 *kfunc_name = func_name;
12061 func_proto = btf_type_by_id(desc_btf, func->type);
12063 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
12064 if (!kfunc_flags) {
12068 memset(meta, 0, sizeof(*meta));
12069 meta->btf = desc_btf;
12070 meta->func_id = func_id;
12071 meta->kfunc_flags = *kfunc_flags;
12072 meta->func_proto = func_proto;
12073 meta->func_name = func_name;
12078 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
12080 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12083 const struct btf_type *t, *ptr_type;
12084 u32 i, nargs, ptr_type_id, release_ref_obj_id;
12085 struct bpf_reg_state *regs = cur_regs(env);
12086 const char *func_name, *ptr_type_name;
12087 bool sleepable, rcu_lock, rcu_unlock;
12088 struct bpf_kfunc_call_arg_meta meta;
12089 struct bpf_insn_aux_data *insn_aux;
12090 int err, insn_idx = *insn_idx_p;
12091 const struct btf_param *args;
12092 const struct btf_type *ret_t;
12093 struct btf *desc_btf;
12095 /* skip for now, but return error when we find this in fixup_kfunc_call */
12099 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
12100 if (err == -EACCES && func_name)
12101 verbose(env, "calling kernel function %s is not allowed\n", func_name);
12104 desc_btf = meta.btf;
12105 insn_aux = &env->insn_aux_data[insn_idx];
12107 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
12109 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12110 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12114 sleepable = is_kfunc_sleepable(&meta);
12115 if (sleepable && !in_sleepable(env)) {
12116 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12120 /* Check the arguments */
12121 err = check_kfunc_args(env, &meta, insn_idx);
12125 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12126 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12127 set_rbtree_add_callback_state);
12129 verbose(env, "kfunc %s#%d failed callback verification\n",
12130 func_name, meta.func_id);
12135 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
12136 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
12138 if (env->cur_state->active_rcu_lock) {
12139 struct bpf_func_state *state;
12140 struct bpf_reg_state *reg;
12141 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
12143 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
12144 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
12149 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
12151 } else if (rcu_unlock) {
12152 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
12153 if (reg->type & MEM_RCU) {
12154 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
12155 reg->type |= PTR_UNTRUSTED;
12158 env->cur_state->active_rcu_lock = false;
12159 } else if (sleepable) {
12160 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
12163 } else if (rcu_lock) {
12164 env->cur_state->active_rcu_lock = true;
12165 } else if (rcu_unlock) {
12166 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
12170 /* In case of release function, we get register number of refcounted
12171 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
12173 if (meta.release_regno) {
12174 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
12176 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12177 func_name, meta.func_id);
12182 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12183 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12184 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12185 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
12186 insn_aux->insert_off = regs[BPF_REG_2].off;
12187 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
12188 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
12190 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
12191 func_name, meta.func_id);
12195 err = release_reference(env, release_ref_obj_id);
12197 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12198 func_name, meta.func_id);
12203 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12204 if (!bpf_jit_supports_exceptions()) {
12205 verbose(env, "JIT does not support calling kfunc %s#%d\n",
12206 func_name, meta.func_id);
12209 env->seen_exception = true;
12211 /* In the case of the default callback, the cookie value passed
12212 * to bpf_throw becomes the return value of the program.
12214 if (!env->exception_callback_subprog) {
12215 err = check_return_code(env, BPF_REG_1, "R1");
12221 for (i = 0; i < CALLER_SAVED_REGS; i++)
12222 mark_reg_not_init(env, regs, caller_saved[i]);
12224 /* Check return type */
12225 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
12227 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
12228 /* Only exception is bpf_obj_new_impl */
12229 if (meta.btf != btf_vmlinux ||
12230 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
12231 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
12232 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
12233 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12238 if (btf_type_is_scalar(t)) {
12239 mark_reg_unknown(env, regs, BPF_REG_0);
12240 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12241 } else if (btf_type_is_ptr(t)) {
12242 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12244 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12245 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12246 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12247 struct btf_struct_meta *struct_meta;
12248 struct btf *ret_btf;
12251 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12254 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12255 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12259 ret_btf = env->prog->aux->btf;
12260 ret_btf_id = meta.arg_constant.value;
12262 /* This may be NULL due to user not supplying a BTF */
12264 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12268 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12269 if (!ret_t || !__btf_type_is_struct(ret_t)) {
12270 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12274 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12275 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
12276 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
12277 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
12281 if (!bpf_global_percpu_ma_set) {
12282 mutex_lock(&bpf_percpu_ma_lock);
12283 if (!bpf_global_percpu_ma_set) {
12284 /* Charge memory allocated with bpf_global_percpu_ma to
12285 * root memcg. The obj_cgroup for root memcg is NULL.
12287 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
12289 bpf_global_percpu_ma_set = true;
12291 mutex_unlock(&bpf_percpu_ma_lock);
12296 mutex_lock(&bpf_percpu_ma_lock);
12297 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
12298 mutex_unlock(&bpf_percpu_ma_lock);
12303 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12304 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12305 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12306 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12311 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12316 mark_reg_known_zero(env, regs, BPF_REG_0);
12317 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12318 regs[BPF_REG_0].btf = ret_btf;
12319 regs[BPF_REG_0].btf_id = ret_btf_id;
12320 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12321 regs[BPF_REG_0].type |= MEM_PERCPU;
12323 insn_aux->obj_new_size = ret_t->size;
12324 insn_aux->kptr_struct_meta = struct_meta;
12325 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12326 mark_reg_known_zero(env, regs, BPF_REG_0);
12327 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12328 regs[BPF_REG_0].btf = meta.arg_btf;
12329 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12331 insn_aux->kptr_struct_meta =
12332 btf_find_struct_meta(meta.arg_btf,
12334 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12335 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12336 struct btf_field *field = meta.arg_list_head.field;
12338 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12339 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12340 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12341 struct btf_field *field = meta.arg_rbtree_root.field;
12343 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12344 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12345 mark_reg_known_zero(env, regs, BPF_REG_0);
12346 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12347 regs[BPF_REG_0].btf = desc_btf;
12348 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12349 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12350 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12351 if (!ret_t || !btf_type_is_struct(ret_t)) {
12353 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12357 mark_reg_known_zero(env, regs, BPF_REG_0);
12358 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12359 regs[BPF_REG_0].btf = desc_btf;
12360 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12361 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12362 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12363 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12365 mark_reg_known_zero(env, regs, BPF_REG_0);
12367 if (!meta.arg_constant.found) {
12368 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12372 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12374 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12375 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12377 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12378 regs[BPF_REG_0].type |= MEM_RDONLY;
12380 /* this will set env->seen_direct_write to true */
12381 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12382 verbose(env, "the prog does not allow writes to packet data\n");
12387 if (!meta.initialized_dynptr.id) {
12388 verbose(env, "verifier internal error: no dynptr id\n");
12391 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12393 /* we don't need to set BPF_REG_0's ref obj id
12394 * because packet slices are not refcounted (see
12395 * dynptr_type_refcounted)
12398 verbose(env, "kernel function %s unhandled dynamic return type\n",
12402 } else if (btf_type_is_void(ptr_type)) {
12403 /* kfunc returning 'void *' is equivalent to returning scalar */
12404 mark_reg_unknown(env, regs, BPF_REG_0);
12405 } else if (!__btf_type_is_struct(ptr_type)) {
12406 if (!meta.r0_size) {
12409 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12411 meta.r0_rdonly = true;
12414 if (!meta.r0_size) {
12415 ptr_type_name = btf_name_by_offset(desc_btf,
12416 ptr_type->name_off);
12418 "kernel function %s returns pointer type %s %s is not supported\n",
12420 btf_type_str(ptr_type),
12425 mark_reg_known_zero(env, regs, BPF_REG_0);
12426 regs[BPF_REG_0].type = PTR_TO_MEM;
12427 regs[BPF_REG_0].mem_size = meta.r0_size;
12429 if (meta.r0_rdonly)
12430 regs[BPF_REG_0].type |= MEM_RDONLY;
12432 /* Ensures we don't access the memory after a release_reference() */
12433 if (meta.ref_obj_id)
12434 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12436 mark_reg_known_zero(env, regs, BPF_REG_0);
12437 regs[BPF_REG_0].btf = desc_btf;
12438 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12439 regs[BPF_REG_0].btf_id = ptr_type_id;
12442 if (is_kfunc_ret_null(&meta)) {
12443 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12444 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12445 regs[BPF_REG_0].id = ++env->id_gen;
12447 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12448 if (is_kfunc_acquire(&meta)) {
12449 int id = acquire_reference_state(env, insn_idx);
12453 if (is_kfunc_ret_null(&meta))
12454 regs[BPF_REG_0].id = id;
12455 regs[BPF_REG_0].ref_obj_id = id;
12456 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12457 ref_set_non_owning(env, ®s[BPF_REG_0]);
12460 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
12461 regs[BPF_REG_0].id = ++env->id_gen;
12462 } else if (btf_type_is_void(t)) {
12463 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12464 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12465 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12466 insn_aux->kptr_struct_meta =
12467 btf_find_struct_meta(meta.arg_btf,
12473 nargs = btf_type_vlen(meta.func_proto);
12474 args = (const struct btf_param *)(meta.func_proto + 1);
12475 for (i = 0; i < nargs; i++) {
12478 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12479 if (btf_type_is_ptr(t))
12480 mark_btf_func_reg_size(env, regno, sizeof(void *));
12482 /* scalar. ensured by btf_check_kfunc_arg_match() */
12483 mark_btf_func_reg_size(env, regno, t->size);
12486 if (is_iter_next_kfunc(&meta)) {
12487 err = process_iter_next_call(env, insn_idx, &meta);
12495 static bool signed_add_overflows(s64 a, s64 b)
12497 /* Do the add in u64, where overflow is well-defined */
12498 s64 res = (s64)((u64)a + (u64)b);
12505 static bool signed_add32_overflows(s32 a, s32 b)
12507 /* Do the add in u32, where overflow is well-defined */
12508 s32 res = (s32)((u32)a + (u32)b);
12515 static bool signed_sub_overflows(s64 a, s64 b)
12517 /* Do the sub in u64, where overflow is well-defined */
12518 s64 res = (s64)((u64)a - (u64)b);
12525 static bool signed_sub32_overflows(s32 a, s32 b)
12527 /* Do the sub in u32, where overflow is well-defined */
12528 s32 res = (s32)((u32)a - (u32)b);
12535 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12536 const struct bpf_reg_state *reg,
12537 enum bpf_reg_type type)
12539 bool known = tnum_is_const(reg->var_off);
12540 s64 val = reg->var_off.value;
12541 s64 smin = reg->smin_value;
12543 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12544 verbose(env, "math between %s pointer and %lld is not allowed\n",
12545 reg_type_str(env, type), val);
12549 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12550 verbose(env, "%s pointer offset %d is not allowed\n",
12551 reg_type_str(env, type), reg->off);
12555 if (smin == S64_MIN) {
12556 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12557 reg_type_str(env, type));
12561 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12562 verbose(env, "value %lld makes %s pointer be out of bounds\n",
12563 smin, reg_type_str(env, type));
12571 REASON_BOUNDS = -1,
12578 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12579 u32 *alu_limit, bool mask_to_left)
12581 u32 max = 0, ptr_limit = 0;
12583 switch (ptr_reg->type) {
12585 /* Offset 0 is out-of-bounds, but acceptable start for the
12586 * left direction, see BPF_REG_FP. Also, unknown scalar
12587 * offset where we would need to deal with min/max bounds is
12588 * currently prohibited for unprivileged.
12590 max = MAX_BPF_STACK + mask_to_left;
12591 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12593 case PTR_TO_MAP_VALUE:
12594 max = ptr_reg->map_ptr->value_size;
12595 ptr_limit = (mask_to_left ?
12596 ptr_reg->smin_value :
12597 ptr_reg->umax_value) + ptr_reg->off;
12600 return REASON_TYPE;
12603 if (ptr_limit >= max)
12604 return REASON_LIMIT;
12605 *alu_limit = ptr_limit;
12609 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12610 const struct bpf_insn *insn)
12612 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12615 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12616 u32 alu_state, u32 alu_limit)
12618 /* If we arrived here from different branches with different
12619 * state or limits to sanitize, then this won't work.
12621 if (aux->alu_state &&
12622 (aux->alu_state != alu_state ||
12623 aux->alu_limit != alu_limit))
12624 return REASON_PATHS;
12626 /* Corresponding fixup done in do_misc_fixups(). */
12627 aux->alu_state = alu_state;
12628 aux->alu_limit = alu_limit;
12632 static int sanitize_val_alu(struct bpf_verifier_env *env,
12633 struct bpf_insn *insn)
12635 struct bpf_insn_aux_data *aux = cur_aux(env);
12637 if (can_skip_alu_sanitation(env, insn))
12640 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12643 static bool sanitize_needed(u8 opcode)
12645 return opcode == BPF_ADD || opcode == BPF_SUB;
12648 struct bpf_sanitize_info {
12649 struct bpf_insn_aux_data aux;
12653 static struct bpf_verifier_state *
12654 sanitize_speculative_path(struct bpf_verifier_env *env,
12655 const struct bpf_insn *insn,
12656 u32 next_idx, u32 curr_idx)
12658 struct bpf_verifier_state *branch;
12659 struct bpf_reg_state *regs;
12661 branch = push_stack(env, next_idx, curr_idx, true);
12662 if (branch && insn) {
12663 regs = branch->frame[branch->curframe]->regs;
12664 if (BPF_SRC(insn->code) == BPF_K) {
12665 mark_reg_unknown(env, regs, insn->dst_reg);
12666 } else if (BPF_SRC(insn->code) == BPF_X) {
12667 mark_reg_unknown(env, regs, insn->dst_reg);
12668 mark_reg_unknown(env, regs, insn->src_reg);
12674 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12675 struct bpf_insn *insn,
12676 const struct bpf_reg_state *ptr_reg,
12677 const struct bpf_reg_state *off_reg,
12678 struct bpf_reg_state *dst_reg,
12679 struct bpf_sanitize_info *info,
12680 const bool commit_window)
12682 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12683 struct bpf_verifier_state *vstate = env->cur_state;
12684 bool off_is_imm = tnum_is_const(off_reg->var_off);
12685 bool off_is_neg = off_reg->smin_value < 0;
12686 bool ptr_is_dst_reg = ptr_reg == dst_reg;
12687 u8 opcode = BPF_OP(insn->code);
12688 u32 alu_state, alu_limit;
12689 struct bpf_reg_state tmp;
12693 if (can_skip_alu_sanitation(env, insn))
12696 /* We already marked aux for masking from non-speculative
12697 * paths, thus we got here in the first place. We only care
12698 * to explore bad access from here.
12700 if (vstate->speculative)
12703 if (!commit_window) {
12704 if (!tnum_is_const(off_reg->var_off) &&
12705 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12706 return REASON_BOUNDS;
12708 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
12709 (opcode == BPF_SUB && !off_is_neg);
12712 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12716 if (commit_window) {
12717 /* In commit phase we narrow the masking window based on
12718 * the observed pointer move after the simulated operation.
12720 alu_state = info->aux.alu_state;
12721 alu_limit = abs(info->aux.alu_limit - alu_limit);
12723 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12724 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12725 alu_state |= ptr_is_dst_reg ?
12726 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12728 /* Limit pruning on unknown scalars to enable deep search for
12729 * potential masking differences from other program paths.
12732 env->explore_alu_limits = true;
12735 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12739 /* If we're in commit phase, we're done here given we already
12740 * pushed the truncated dst_reg into the speculative verification
12743 * Also, when register is a known constant, we rewrite register-based
12744 * operation to immediate-based, and thus do not need masking (and as
12745 * a consequence, do not need to simulate the zero-truncation either).
12747 if (commit_window || off_is_imm)
12750 /* Simulate and find potential out-of-bounds access under
12751 * speculative execution from truncation as a result of
12752 * masking when off was not within expected range. If off
12753 * sits in dst, then we temporarily need to move ptr there
12754 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12755 * for cases where we use K-based arithmetic in one direction
12756 * and truncated reg-based in the other in order to explore
12759 if (!ptr_is_dst_reg) {
12761 copy_register_state(dst_reg, ptr_reg);
12763 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12765 if (!ptr_is_dst_reg && ret)
12767 return !ret ? REASON_STACK : 0;
12770 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12772 struct bpf_verifier_state *vstate = env->cur_state;
12774 /* If we simulate paths under speculation, we don't update the
12775 * insn as 'seen' such that when we verify unreachable paths in
12776 * the non-speculative domain, sanitize_dead_code() can still
12777 * rewrite/sanitize them.
12779 if (!vstate->speculative)
12780 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12783 static int sanitize_err(struct bpf_verifier_env *env,
12784 const struct bpf_insn *insn, int reason,
12785 const struct bpf_reg_state *off_reg,
12786 const struct bpf_reg_state *dst_reg)
12788 static const char *err = "pointer arithmetic with it prohibited for !root";
12789 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12790 u32 dst = insn->dst_reg, src = insn->src_reg;
12793 case REASON_BOUNDS:
12794 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12795 off_reg == dst_reg ? dst : src, err);
12798 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12799 off_reg == dst_reg ? src : dst, err);
12802 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12806 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12810 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12814 verbose(env, "verifier internal error: unknown reason (%d)\n",
12822 /* check that stack access falls within stack limits and that 'reg' doesn't
12823 * have a variable offset.
12825 * Variable offset is prohibited for unprivileged mode for simplicity since it
12826 * requires corresponding support in Spectre masking for stack ALU. See also
12827 * retrieve_ptr_limit().
12830 * 'off' includes 'reg->off'.
12832 static int check_stack_access_for_ptr_arithmetic(
12833 struct bpf_verifier_env *env,
12835 const struct bpf_reg_state *reg,
12838 if (!tnum_is_const(reg->var_off)) {
12841 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12842 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12843 regno, tn_buf, off);
12847 if (off >= 0 || off < -MAX_BPF_STACK) {
12848 verbose(env, "R%d stack pointer arithmetic goes out of range, "
12849 "prohibited for !root; off=%d\n", regno, off);
12856 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12857 const struct bpf_insn *insn,
12858 const struct bpf_reg_state *dst_reg)
12860 u32 dst = insn->dst_reg;
12862 /* For unprivileged we require that resulting offset must be in bounds
12863 * in order to be able to sanitize access later on.
12865 if (env->bypass_spec_v1)
12868 switch (dst_reg->type) {
12870 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12871 dst_reg->off + dst_reg->var_off.value))
12874 case PTR_TO_MAP_VALUE:
12875 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12876 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12877 "prohibited for !root\n", dst);
12888 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12889 * Caller should also handle BPF_MOV case separately.
12890 * If we return -EACCES, caller may want to try again treating pointer as a
12891 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
12893 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12894 struct bpf_insn *insn,
12895 const struct bpf_reg_state *ptr_reg,
12896 const struct bpf_reg_state *off_reg)
12898 struct bpf_verifier_state *vstate = env->cur_state;
12899 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12900 struct bpf_reg_state *regs = state->regs, *dst_reg;
12901 bool known = tnum_is_const(off_reg->var_off);
12902 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12903 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12904 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12905 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12906 struct bpf_sanitize_info info = {};
12907 u8 opcode = BPF_OP(insn->code);
12908 u32 dst = insn->dst_reg;
12911 dst_reg = ®s[dst];
12913 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12914 smin_val > smax_val || umin_val > umax_val) {
12915 /* Taint dst register if offset had invalid bounds derived from
12916 * e.g. dead branches.
12918 __mark_reg_unknown(env, dst_reg);
12922 if (BPF_CLASS(insn->code) != BPF_ALU64) {
12923 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12924 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12925 __mark_reg_unknown(env, dst_reg);
12930 "R%d 32-bit pointer arithmetic prohibited\n",
12935 if (ptr_reg->type & PTR_MAYBE_NULL) {
12936 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12937 dst, reg_type_str(env, ptr_reg->type));
12941 switch (base_type(ptr_reg->type)) {
12943 case PTR_TO_MAP_VALUE:
12944 case PTR_TO_MAP_KEY:
12946 case PTR_TO_PACKET_META:
12947 case PTR_TO_PACKET:
12948 case PTR_TO_TP_BUFFER:
12949 case PTR_TO_BTF_ID:
12953 case CONST_PTR_TO_DYNPTR:
12955 case PTR_TO_FLOW_KEYS:
12959 case CONST_PTR_TO_MAP:
12960 /* smin_val represents the known value */
12961 if (known && smin_val == 0 && opcode == BPF_ADD)
12965 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12966 dst, reg_type_str(env, ptr_reg->type));
12970 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12971 * The id may be overwritten later if we create a new variable offset.
12973 dst_reg->type = ptr_reg->type;
12974 dst_reg->id = ptr_reg->id;
12976 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12977 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12980 /* pointer types do not carry 32-bit bounds at the moment. */
12981 __mark_reg32_unbounded(dst_reg);
12983 if (sanitize_needed(opcode)) {
12984 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12987 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12992 /* We can take a fixed offset as long as it doesn't overflow
12993 * the s32 'off' field
12995 if (known && (ptr_reg->off + smin_val ==
12996 (s64)(s32)(ptr_reg->off + smin_val))) {
12997 /* pointer += K. Accumulate it into fixed offset */
12998 dst_reg->smin_value = smin_ptr;
12999 dst_reg->smax_value = smax_ptr;
13000 dst_reg->umin_value = umin_ptr;
13001 dst_reg->umax_value = umax_ptr;
13002 dst_reg->var_off = ptr_reg->var_off;
13003 dst_reg->off = ptr_reg->off + smin_val;
13004 dst_reg->raw = ptr_reg->raw;
13007 /* A new variable offset is created. Note that off_reg->off
13008 * == 0, since it's a scalar.
13009 * dst_reg gets the pointer type and since some positive
13010 * integer value was added to the pointer, give it a new 'id'
13011 * if it's a PTR_TO_PACKET.
13012 * this creates a new 'base' pointer, off_reg (variable) gets
13013 * added into the variable offset, and we copy the fixed offset
13016 if (signed_add_overflows(smin_ptr, smin_val) ||
13017 signed_add_overflows(smax_ptr, smax_val)) {
13018 dst_reg->smin_value = S64_MIN;
13019 dst_reg->smax_value = S64_MAX;
13021 dst_reg->smin_value = smin_ptr + smin_val;
13022 dst_reg->smax_value = smax_ptr + smax_val;
13024 if (umin_ptr + umin_val < umin_ptr ||
13025 umax_ptr + umax_val < umax_ptr) {
13026 dst_reg->umin_value = 0;
13027 dst_reg->umax_value = U64_MAX;
13029 dst_reg->umin_value = umin_ptr + umin_val;
13030 dst_reg->umax_value = umax_ptr + umax_val;
13032 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
13033 dst_reg->off = ptr_reg->off;
13034 dst_reg->raw = ptr_reg->raw;
13035 if (reg_is_pkt_pointer(ptr_reg)) {
13036 dst_reg->id = ++env->id_gen;
13037 /* something was added to pkt_ptr, set range to zero */
13038 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13042 if (dst_reg == off_reg) {
13043 /* scalar -= pointer. Creates an unknown scalar */
13044 verbose(env, "R%d tried to subtract pointer from scalar\n",
13048 /* We don't allow subtraction from FP, because (according to
13049 * test_verifier.c test "invalid fp arithmetic", JITs might not
13050 * be able to deal with it.
13052 if (ptr_reg->type == PTR_TO_STACK) {
13053 verbose(env, "R%d subtraction from stack pointer prohibited\n",
13057 if (known && (ptr_reg->off - smin_val ==
13058 (s64)(s32)(ptr_reg->off - smin_val))) {
13059 /* pointer -= K. Subtract it from fixed offset */
13060 dst_reg->smin_value = smin_ptr;
13061 dst_reg->smax_value = smax_ptr;
13062 dst_reg->umin_value = umin_ptr;
13063 dst_reg->umax_value = umax_ptr;
13064 dst_reg->var_off = ptr_reg->var_off;
13065 dst_reg->id = ptr_reg->id;
13066 dst_reg->off = ptr_reg->off - smin_val;
13067 dst_reg->raw = ptr_reg->raw;
13070 /* A new variable offset is created. If the subtrahend is known
13071 * nonnegative, then any reg->range we had before is still good.
13073 if (signed_sub_overflows(smin_ptr, smax_val) ||
13074 signed_sub_overflows(smax_ptr, smin_val)) {
13075 /* Overflow possible, we know nothing */
13076 dst_reg->smin_value = S64_MIN;
13077 dst_reg->smax_value = S64_MAX;
13079 dst_reg->smin_value = smin_ptr - smax_val;
13080 dst_reg->smax_value = smax_ptr - smin_val;
13082 if (umin_ptr < umax_val) {
13083 /* Overflow possible, we know nothing */
13084 dst_reg->umin_value = 0;
13085 dst_reg->umax_value = U64_MAX;
13087 /* Cannot overflow (as long as bounds are consistent) */
13088 dst_reg->umin_value = umin_ptr - umax_val;
13089 dst_reg->umax_value = umax_ptr - umin_val;
13091 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
13092 dst_reg->off = ptr_reg->off;
13093 dst_reg->raw = ptr_reg->raw;
13094 if (reg_is_pkt_pointer(ptr_reg)) {
13095 dst_reg->id = ++env->id_gen;
13096 /* something was added to pkt_ptr, set range to zero */
13098 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13104 /* bitwise ops on pointers are troublesome, prohibit. */
13105 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
13106 dst, bpf_alu_string[opcode >> 4]);
13109 /* other operators (e.g. MUL,LSH) produce non-pointer results */
13110 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
13111 dst, bpf_alu_string[opcode >> 4]);
13115 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
13117 reg_bounds_sync(dst_reg);
13118 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
13120 if (sanitize_needed(opcode)) {
13121 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13124 return sanitize_err(env, insn, ret, off_reg, dst_reg);
13130 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13131 struct bpf_reg_state *src_reg)
13133 s32 smin_val = src_reg->s32_min_value;
13134 s32 smax_val = src_reg->s32_max_value;
13135 u32 umin_val = src_reg->u32_min_value;
13136 u32 umax_val = src_reg->u32_max_value;
13138 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
13139 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
13140 dst_reg->s32_min_value = S32_MIN;
13141 dst_reg->s32_max_value = S32_MAX;
13143 dst_reg->s32_min_value += smin_val;
13144 dst_reg->s32_max_value += smax_val;
13146 if (dst_reg->u32_min_value + umin_val < umin_val ||
13147 dst_reg->u32_max_value + umax_val < umax_val) {
13148 dst_reg->u32_min_value = 0;
13149 dst_reg->u32_max_value = U32_MAX;
13151 dst_reg->u32_min_value += umin_val;
13152 dst_reg->u32_max_value += umax_val;
13156 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13157 struct bpf_reg_state *src_reg)
13159 s64 smin_val = src_reg->smin_value;
13160 s64 smax_val = src_reg->smax_value;
13161 u64 umin_val = src_reg->umin_value;
13162 u64 umax_val = src_reg->umax_value;
13164 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
13165 signed_add_overflows(dst_reg->smax_value, smax_val)) {
13166 dst_reg->smin_value = S64_MIN;
13167 dst_reg->smax_value = S64_MAX;
13169 dst_reg->smin_value += smin_val;
13170 dst_reg->smax_value += smax_val;
13172 if (dst_reg->umin_value + umin_val < umin_val ||
13173 dst_reg->umax_value + umax_val < umax_val) {
13174 dst_reg->umin_value = 0;
13175 dst_reg->umax_value = U64_MAX;
13177 dst_reg->umin_value += umin_val;
13178 dst_reg->umax_value += umax_val;
13182 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13183 struct bpf_reg_state *src_reg)
13185 s32 smin_val = src_reg->s32_min_value;
13186 s32 smax_val = src_reg->s32_max_value;
13187 u32 umin_val = src_reg->u32_min_value;
13188 u32 umax_val = src_reg->u32_max_value;
13190 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
13191 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
13192 /* Overflow possible, we know nothing */
13193 dst_reg->s32_min_value = S32_MIN;
13194 dst_reg->s32_max_value = S32_MAX;
13196 dst_reg->s32_min_value -= smax_val;
13197 dst_reg->s32_max_value -= smin_val;
13199 if (dst_reg->u32_min_value < umax_val) {
13200 /* Overflow possible, we know nothing */
13201 dst_reg->u32_min_value = 0;
13202 dst_reg->u32_max_value = U32_MAX;
13204 /* Cannot overflow (as long as bounds are consistent) */
13205 dst_reg->u32_min_value -= umax_val;
13206 dst_reg->u32_max_value -= umin_val;
13210 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13211 struct bpf_reg_state *src_reg)
13213 s64 smin_val = src_reg->smin_value;
13214 s64 smax_val = src_reg->smax_value;
13215 u64 umin_val = src_reg->umin_value;
13216 u64 umax_val = src_reg->umax_value;
13218 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
13219 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
13220 /* Overflow possible, we know nothing */
13221 dst_reg->smin_value = S64_MIN;
13222 dst_reg->smax_value = S64_MAX;
13224 dst_reg->smin_value -= smax_val;
13225 dst_reg->smax_value -= smin_val;
13227 if (dst_reg->umin_value < umax_val) {
13228 /* Overflow possible, we know nothing */
13229 dst_reg->umin_value = 0;
13230 dst_reg->umax_value = U64_MAX;
13232 /* Cannot overflow (as long as bounds are consistent) */
13233 dst_reg->umin_value -= umax_val;
13234 dst_reg->umax_value -= umin_val;
13238 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13239 struct bpf_reg_state *src_reg)
13241 s32 smin_val = src_reg->s32_min_value;
13242 u32 umin_val = src_reg->u32_min_value;
13243 u32 umax_val = src_reg->u32_max_value;
13245 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13246 /* Ain't nobody got time to multiply that sign */
13247 __mark_reg32_unbounded(dst_reg);
13250 /* Both values are positive, so we can work with unsigned and
13251 * copy the result to signed (unless it exceeds S32_MAX).
13253 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13254 /* Potential overflow, we know nothing */
13255 __mark_reg32_unbounded(dst_reg);
13258 dst_reg->u32_min_value *= umin_val;
13259 dst_reg->u32_max_value *= umax_val;
13260 if (dst_reg->u32_max_value > S32_MAX) {
13261 /* Overflow possible, we know nothing */
13262 dst_reg->s32_min_value = S32_MIN;
13263 dst_reg->s32_max_value = S32_MAX;
13265 dst_reg->s32_min_value = dst_reg->u32_min_value;
13266 dst_reg->s32_max_value = dst_reg->u32_max_value;
13270 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13271 struct bpf_reg_state *src_reg)
13273 s64 smin_val = src_reg->smin_value;
13274 u64 umin_val = src_reg->umin_value;
13275 u64 umax_val = src_reg->umax_value;
13277 if (smin_val < 0 || dst_reg->smin_value < 0) {
13278 /* Ain't nobody got time to multiply that sign */
13279 __mark_reg64_unbounded(dst_reg);
13282 /* Both values are positive, so we can work with unsigned and
13283 * copy the result to signed (unless it exceeds S64_MAX).
13285 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13286 /* Potential overflow, we know nothing */
13287 __mark_reg64_unbounded(dst_reg);
13290 dst_reg->umin_value *= umin_val;
13291 dst_reg->umax_value *= umax_val;
13292 if (dst_reg->umax_value > S64_MAX) {
13293 /* Overflow possible, we know nothing */
13294 dst_reg->smin_value = S64_MIN;
13295 dst_reg->smax_value = S64_MAX;
13297 dst_reg->smin_value = dst_reg->umin_value;
13298 dst_reg->smax_value = dst_reg->umax_value;
13302 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13303 struct bpf_reg_state *src_reg)
13305 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13306 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13307 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13308 s32 smin_val = src_reg->s32_min_value;
13309 u32 umax_val = src_reg->u32_max_value;
13311 if (src_known && dst_known) {
13312 __mark_reg32_known(dst_reg, var32_off.value);
13316 /* We get our minimum from the var_off, since that's inherently
13317 * bitwise. Our maximum is the minimum of the operands' maxima.
13319 dst_reg->u32_min_value = var32_off.value;
13320 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13321 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13322 /* Lose signed bounds when ANDing negative numbers,
13323 * ain't nobody got time for that.
13325 dst_reg->s32_min_value = S32_MIN;
13326 dst_reg->s32_max_value = S32_MAX;
13328 /* ANDing two positives gives a positive, so safe to
13329 * cast result into s64.
13331 dst_reg->s32_min_value = dst_reg->u32_min_value;
13332 dst_reg->s32_max_value = dst_reg->u32_max_value;
13336 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13337 struct bpf_reg_state *src_reg)
13339 bool src_known = tnum_is_const(src_reg->var_off);
13340 bool dst_known = tnum_is_const(dst_reg->var_off);
13341 s64 smin_val = src_reg->smin_value;
13342 u64 umax_val = src_reg->umax_value;
13344 if (src_known && dst_known) {
13345 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13349 /* We get our minimum from the var_off, since that's inherently
13350 * bitwise. Our maximum is the minimum of the operands' maxima.
13352 dst_reg->umin_value = dst_reg->var_off.value;
13353 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13354 if (dst_reg->smin_value < 0 || smin_val < 0) {
13355 /* Lose signed bounds when ANDing negative numbers,
13356 * ain't nobody got time for that.
13358 dst_reg->smin_value = S64_MIN;
13359 dst_reg->smax_value = S64_MAX;
13361 /* ANDing two positives gives a positive, so safe to
13362 * cast result into s64.
13364 dst_reg->smin_value = dst_reg->umin_value;
13365 dst_reg->smax_value = dst_reg->umax_value;
13367 /* We may learn something more from the var_off */
13368 __update_reg_bounds(dst_reg);
13371 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13372 struct bpf_reg_state *src_reg)
13374 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13375 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13376 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13377 s32 smin_val = src_reg->s32_min_value;
13378 u32 umin_val = src_reg->u32_min_value;
13380 if (src_known && dst_known) {
13381 __mark_reg32_known(dst_reg, var32_off.value);
13385 /* We get our maximum from the var_off, and our minimum is the
13386 * maximum of the operands' minima
13388 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13389 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13390 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13391 /* Lose signed bounds when ORing negative numbers,
13392 * ain't nobody got time for that.
13394 dst_reg->s32_min_value = S32_MIN;
13395 dst_reg->s32_max_value = S32_MAX;
13397 /* ORing two positives gives a positive, so safe to
13398 * cast result into s64.
13400 dst_reg->s32_min_value = dst_reg->u32_min_value;
13401 dst_reg->s32_max_value = dst_reg->u32_max_value;
13405 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13406 struct bpf_reg_state *src_reg)
13408 bool src_known = tnum_is_const(src_reg->var_off);
13409 bool dst_known = tnum_is_const(dst_reg->var_off);
13410 s64 smin_val = src_reg->smin_value;
13411 u64 umin_val = src_reg->umin_value;
13413 if (src_known && dst_known) {
13414 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13418 /* We get our maximum from the var_off, and our minimum is the
13419 * maximum of the operands' minima
13421 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13422 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13423 if (dst_reg->smin_value < 0 || smin_val < 0) {
13424 /* Lose signed bounds when ORing negative numbers,
13425 * ain't nobody got time for that.
13427 dst_reg->smin_value = S64_MIN;
13428 dst_reg->smax_value = S64_MAX;
13430 /* ORing two positives gives a positive, so safe to
13431 * cast result into s64.
13433 dst_reg->smin_value = dst_reg->umin_value;
13434 dst_reg->smax_value = dst_reg->umax_value;
13436 /* We may learn something more from the var_off */
13437 __update_reg_bounds(dst_reg);
13440 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13441 struct bpf_reg_state *src_reg)
13443 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13444 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13445 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13446 s32 smin_val = src_reg->s32_min_value;
13448 if (src_known && dst_known) {
13449 __mark_reg32_known(dst_reg, var32_off.value);
13453 /* We get both minimum and maximum from the var32_off. */
13454 dst_reg->u32_min_value = var32_off.value;
13455 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13457 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13458 /* XORing two positive sign numbers gives a positive,
13459 * so safe to cast u32 result into s32.
13461 dst_reg->s32_min_value = dst_reg->u32_min_value;
13462 dst_reg->s32_max_value = dst_reg->u32_max_value;
13464 dst_reg->s32_min_value = S32_MIN;
13465 dst_reg->s32_max_value = S32_MAX;
13469 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13470 struct bpf_reg_state *src_reg)
13472 bool src_known = tnum_is_const(src_reg->var_off);
13473 bool dst_known = tnum_is_const(dst_reg->var_off);
13474 s64 smin_val = src_reg->smin_value;
13476 if (src_known && dst_known) {
13477 /* dst_reg->var_off.value has been updated earlier */
13478 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13482 /* We get both minimum and maximum from the var_off. */
13483 dst_reg->umin_value = dst_reg->var_off.value;
13484 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13486 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13487 /* XORing two positive sign numbers gives a positive,
13488 * so safe to cast u64 result into s64.
13490 dst_reg->smin_value = dst_reg->umin_value;
13491 dst_reg->smax_value = dst_reg->umax_value;
13493 dst_reg->smin_value = S64_MIN;
13494 dst_reg->smax_value = S64_MAX;
13497 __update_reg_bounds(dst_reg);
13500 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13501 u64 umin_val, u64 umax_val)
13503 /* We lose all sign bit information (except what we can pick
13506 dst_reg->s32_min_value = S32_MIN;
13507 dst_reg->s32_max_value = S32_MAX;
13508 /* If we might shift our top bit out, then we know nothing */
13509 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13510 dst_reg->u32_min_value = 0;
13511 dst_reg->u32_max_value = U32_MAX;
13513 dst_reg->u32_min_value <<= umin_val;
13514 dst_reg->u32_max_value <<= umax_val;
13518 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13519 struct bpf_reg_state *src_reg)
13521 u32 umax_val = src_reg->u32_max_value;
13522 u32 umin_val = src_reg->u32_min_value;
13523 /* u32 alu operation will zext upper bits */
13524 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13526 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13527 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13528 /* Not required but being careful mark reg64 bounds as unknown so
13529 * that we are forced to pick them up from tnum and zext later and
13530 * if some path skips this step we are still safe.
13532 __mark_reg64_unbounded(dst_reg);
13533 __update_reg32_bounds(dst_reg);
13536 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13537 u64 umin_val, u64 umax_val)
13539 /* Special case <<32 because it is a common compiler pattern to sign
13540 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13541 * positive we know this shift will also be positive so we can track
13542 * bounds correctly. Otherwise we lose all sign bit information except
13543 * what we can pick up from var_off. Perhaps we can generalize this
13544 * later to shifts of any length.
13546 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13547 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13549 dst_reg->smax_value = S64_MAX;
13551 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13552 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13554 dst_reg->smin_value = S64_MIN;
13556 /* If we might shift our top bit out, then we know nothing */
13557 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13558 dst_reg->umin_value = 0;
13559 dst_reg->umax_value = U64_MAX;
13561 dst_reg->umin_value <<= umin_val;
13562 dst_reg->umax_value <<= umax_val;
13566 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13567 struct bpf_reg_state *src_reg)
13569 u64 umax_val = src_reg->umax_value;
13570 u64 umin_val = src_reg->umin_value;
13572 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
13573 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13574 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13576 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13577 /* We may learn something more from the var_off */
13578 __update_reg_bounds(dst_reg);
13581 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13582 struct bpf_reg_state *src_reg)
13584 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13585 u32 umax_val = src_reg->u32_max_value;
13586 u32 umin_val = src_reg->u32_min_value;
13588 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13589 * be negative, then either:
13590 * 1) src_reg might be zero, so the sign bit of the result is
13591 * unknown, so we lose our signed bounds
13592 * 2) it's known negative, thus the unsigned bounds capture the
13594 * 3) the signed bounds cross zero, so they tell us nothing
13596 * If the value in dst_reg is known nonnegative, then again the
13597 * unsigned bounds capture the signed bounds.
13598 * Thus, in all cases it suffices to blow away our signed bounds
13599 * and rely on inferring new ones from the unsigned bounds and
13600 * var_off of the result.
13602 dst_reg->s32_min_value = S32_MIN;
13603 dst_reg->s32_max_value = S32_MAX;
13605 dst_reg->var_off = tnum_rshift(subreg, umin_val);
13606 dst_reg->u32_min_value >>= umax_val;
13607 dst_reg->u32_max_value >>= umin_val;
13609 __mark_reg64_unbounded(dst_reg);
13610 __update_reg32_bounds(dst_reg);
13613 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13614 struct bpf_reg_state *src_reg)
13616 u64 umax_val = src_reg->umax_value;
13617 u64 umin_val = src_reg->umin_value;
13619 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13620 * be negative, then either:
13621 * 1) src_reg might be zero, so the sign bit of the result is
13622 * unknown, so we lose our signed bounds
13623 * 2) it's known negative, thus the unsigned bounds capture the
13625 * 3) the signed bounds cross zero, so they tell us nothing
13627 * If the value in dst_reg is known nonnegative, then again the
13628 * unsigned bounds capture the signed bounds.
13629 * Thus, in all cases it suffices to blow away our signed bounds
13630 * and rely on inferring new ones from the unsigned bounds and
13631 * var_off of the result.
13633 dst_reg->smin_value = S64_MIN;
13634 dst_reg->smax_value = S64_MAX;
13635 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13636 dst_reg->umin_value >>= umax_val;
13637 dst_reg->umax_value >>= umin_val;
13639 /* Its not easy to operate on alu32 bounds here because it depends
13640 * on bits being shifted in. Take easy way out and mark unbounded
13641 * so we can recalculate later from tnum.
13643 __mark_reg32_unbounded(dst_reg);
13644 __update_reg_bounds(dst_reg);
13647 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13648 struct bpf_reg_state *src_reg)
13650 u64 umin_val = src_reg->u32_min_value;
13652 /* Upon reaching here, src_known is true and
13653 * umax_val is equal to umin_val.
13655 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13656 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13658 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13660 /* blow away the dst_reg umin_value/umax_value and rely on
13661 * dst_reg var_off to refine the result.
13663 dst_reg->u32_min_value = 0;
13664 dst_reg->u32_max_value = U32_MAX;
13666 __mark_reg64_unbounded(dst_reg);
13667 __update_reg32_bounds(dst_reg);
13670 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13671 struct bpf_reg_state *src_reg)
13673 u64 umin_val = src_reg->umin_value;
13675 /* Upon reaching here, src_known is true and umax_val is equal
13678 dst_reg->smin_value >>= umin_val;
13679 dst_reg->smax_value >>= umin_val;
13681 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13683 /* blow away the dst_reg umin_value/umax_value and rely on
13684 * dst_reg var_off to refine the result.
13686 dst_reg->umin_value = 0;
13687 dst_reg->umax_value = U64_MAX;
13689 /* Its not easy to operate on alu32 bounds here because it depends
13690 * on bits being shifted in from upper 32-bits. Take easy way out
13691 * and mark unbounded so we can recalculate later from tnum.
13693 __mark_reg32_unbounded(dst_reg);
13694 __update_reg_bounds(dst_reg);
13697 /* WARNING: This function does calculations on 64-bit values, but the actual
13698 * execution may occur on 32-bit values. Therefore, things like bitshifts
13699 * need extra checks in the 32-bit case.
13701 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13702 struct bpf_insn *insn,
13703 struct bpf_reg_state *dst_reg,
13704 struct bpf_reg_state src_reg)
13706 struct bpf_reg_state *regs = cur_regs(env);
13707 u8 opcode = BPF_OP(insn->code);
13709 s64 smin_val, smax_val;
13710 u64 umin_val, umax_val;
13711 s32 s32_min_val, s32_max_val;
13712 u32 u32_min_val, u32_max_val;
13713 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13714 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13717 smin_val = src_reg.smin_value;
13718 smax_val = src_reg.smax_value;
13719 umin_val = src_reg.umin_value;
13720 umax_val = src_reg.umax_value;
13722 s32_min_val = src_reg.s32_min_value;
13723 s32_max_val = src_reg.s32_max_value;
13724 u32_min_val = src_reg.u32_min_value;
13725 u32_max_val = src_reg.u32_max_value;
13728 src_known = tnum_subreg_is_const(src_reg.var_off);
13730 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13731 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13732 /* Taint dst register if offset had invalid bounds
13733 * derived from e.g. dead branches.
13735 __mark_reg_unknown(env, dst_reg);
13739 src_known = tnum_is_const(src_reg.var_off);
13741 (smin_val != smax_val || umin_val != umax_val)) ||
13742 smin_val > smax_val || umin_val > umax_val) {
13743 /* Taint dst register if offset had invalid bounds
13744 * derived from e.g. dead branches.
13746 __mark_reg_unknown(env, dst_reg);
13752 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13753 __mark_reg_unknown(env, dst_reg);
13757 if (sanitize_needed(opcode)) {
13758 ret = sanitize_val_alu(env, insn);
13760 return sanitize_err(env, insn, ret, NULL, NULL);
13763 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13764 * There are two classes of instructions: The first class we track both
13765 * alu32 and alu64 sign/unsigned bounds independently this provides the
13766 * greatest amount of precision when alu operations are mixed with jmp32
13767 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13768 * and BPF_OR. This is possible because these ops have fairly easy to
13769 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13770 * See alu32 verifier tests for examples. The second class of
13771 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13772 * with regards to tracking sign/unsigned bounds because the bits may
13773 * cross subreg boundaries in the alu64 case. When this happens we mark
13774 * the reg unbounded in the subreg bound space and use the resulting
13775 * tnum to calculate an approximation of the sign/unsigned bounds.
13779 scalar32_min_max_add(dst_reg, &src_reg);
13780 scalar_min_max_add(dst_reg, &src_reg);
13781 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13784 scalar32_min_max_sub(dst_reg, &src_reg);
13785 scalar_min_max_sub(dst_reg, &src_reg);
13786 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13789 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13790 scalar32_min_max_mul(dst_reg, &src_reg);
13791 scalar_min_max_mul(dst_reg, &src_reg);
13794 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13795 scalar32_min_max_and(dst_reg, &src_reg);
13796 scalar_min_max_and(dst_reg, &src_reg);
13799 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13800 scalar32_min_max_or(dst_reg, &src_reg);
13801 scalar_min_max_or(dst_reg, &src_reg);
13804 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13805 scalar32_min_max_xor(dst_reg, &src_reg);
13806 scalar_min_max_xor(dst_reg, &src_reg);
13809 if (umax_val >= insn_bitness) {
13810 /* Shifts greater than 31 or 63 are undefined.
13811 * This includes shifts by a negative number.
13813 mark_reg_unknown(env, regs, insn->dst_reg);
13817 scalar32_min_max_lsh(dst_reg, &src_reg);
13819 scalar_min_max_lsh(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_rsh(dst_reg, &src_reg);
13832 scalar_min_max_rsh(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_arsh(dst_reg, &src_reg);
13845 scalar_min_max_arsh(dst_reg, &src_reg);
13848 mark_reg_unknown(env, regs, insn->dst_reg);
13852 /* ALU32 ops are zero extended into 64bit register */
13854 zext_32_to_64(dst_reg);
13855 reg_bounds_sync(dst_reg);
13859 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13862 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13863 struct bpf_insn *insn)
13865 struct bpf_verifier_state *vstate = env->cur_state;
13866 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13867 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13868 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13869 u8 opcode = BPF_OP(insn->code);
13872 dst_reg = ®s[insn->dst_reg];
13875 if (dst_reg->type == PTR_TO_ARENA) {
13876 struct bpf_insn_aux_data *aux = cur_aux(env);
13878 if (BPF_CLASS(insn->code) == BPF_ALU64)
13880 * 32-bit operations zero upper bits automatically.
13881 * 64-bit operations need to be converted to 32.
13883 aux->needs_zext = true;
13885 /* Any arithmetic operations are allowed on arena pointers */
13889 if (dst_reg->type != SCALAR_VALUE)
13892 /* Make sure ID is cleared otherwise dst_reg min/max could be
13893 * incorrectly propagated into other registers by find_equal_scalars()
13896 if (BPF_SRC(insn->code) == BPF_X) {
13897 src_reg = ®s[insn->src_reg];
13898 if (src_reg->type != SCALAR_VALUE) {
13899 if (dst_reg->type != SCALAR_VALUE) {
13900 /* Combining two pointers by any ALU op yields
13901 * an arbitrary scalar. Disallow all math except
13902 * pointer subtraction
13904 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13905 mark_reg_unknown(env, regs, insn->dst_reg);
13908 verbose(env, "R%d pointer %s pointer prohibited\n",
13910 bpf_alu_string[opcode >> 4]);
13913 /* scalar += pointer
13914 * This is legal, but we have to reverse our
13915 * src/dest handling in computing the range
13917 err = mark_chain_precision(env, insn->dst_reg);
13920 return adjust_ptr_min_max_vals(env, insn,
13923 } else if (ptr_reg) {
13924 /* pointer += scalar */
13925 err = mark_chain_precision(env, insn->src_reg);
13928 return adjust_ptr_min_max_vals(env, insn,
13930 } else if (dst_reg->precise) {
13931 /* if dst_reg is precise, src_reg should be precise as well */
13932 err = mark_chain_precision(env, insn->src_reg);
13937 /* Pretend the src is a reg with a known value, since we only
13938 * need to be able to read from this state.
13940 off_reg.type = SCALAR_VALUE;
13941 __mark_reg_known(&off_reg, insn->imm);
13942 src_reg = &off_reg;
13943 if (ptr_reg) /* pointer += K */
13944 return adjust_ptr_min_max_vals(env, insn,
13948 /* Got here implies adding two SCALAR_VALUEs */
13949 if (WARN_ON_ONCE(ptr_reg)) {
13950 print_verifier_state(env, state, true);
13951 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13954 if (WARN_ON(!src_reg)) {
13955 print_verifier_state(env, state, true);
13956 verbose(env, "verifier internal error: no src_reg\n");
13959 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13962 /* check validity of 32-bit and 64-bit arithmetic operations */
13963 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13965 struct bpf_reg_state *regs = cur_regs(env);
13966 u8 opcode = BPF_OP(insn->code);
13969 if (opcode == BPF_END || opcode == BPF_NEG) {
13970 if (opcode == BPF_NEG) {
13971 if (BPF_SRC(insn->code) != BPF_K ||
13972 insn->src_reg != BPF_REG_0 ||
13973 insn->off != 0 || insn->imm != 0) {
13974 verbose(env, "BPF_NEG uses reserved fields\n");
13978 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13979 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13980 (BPF_CLASS(insn->code) == BPF_ALU64 &&
13981 BPF_SRC(insn->code) != BPF_TO_LE)) {
13982 verbose(env, "BPF_END uses reserved fields\n");
13987 /* check src operand */
13988 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13992 if (is_pointer_value(env, insn->dst_reg)) {
13993 verbose(env, "R%d pointer arithmetic prohibited\n",
13998 /* check dest operand */
13999 err = check_reg_arg(env, insn->dst_reg, DST_OP);
14003 } else if (opcode == BPF_MOV) {
14005 if (BPF_SRC(insn->code) == BPF_X) {
14006 if (BPF_CLASS(insn->code) == BPF_ALU) {
14007 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
14009 verbose(env, "BPF_MOV uses reserved fields\n");
14012 } else if (insn->off == BPF_ADDR_SPACE_CAST) {
14013 if (insn->imm != 1 && insn->imm != 1u << 16) {
14014 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
14018 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
14019 insn->off != 32) || insn->imm) {
14020 verbose(env, "BPF_MOV uses reserved fields\n");
14025 /* check src operand */
14026 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14030 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
14031 verbose(env, "BPF_MOV uses reserved fields\n");
14036 /* check dest operand, mark as required later */
14037 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14041 if (BPF_SRC(insn->code) == BPF_X) {
14042 struct bpf_reg_state *src_reg = regs + insn->src_reg;
14043 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
14045 if (BPF_CLASS(insn->code) == BPF_ALU64) {
14047 /* off == BPF_ADDR_SPACE_CAST */
14048 mark_reg_unknown(env, regs, insn->dst_reg);
14049 if (insn->imm == 1) /* cast from as(1) to as(0) */
14050 dst_reg->type = PTR_TO_ARENA;
14051 } else if (insn->off == 0) {
14053 * copy register state to dest reg
14055 assign_scalar_id_before_mov(env, src_reg);
14056 copy_register_state(dst_reg, src_reg);
14057 dst_reg->live |= REG_LIVE_WRITTEN;
14058 dst_reg->subreg_def = DEF_NOT_SUBREG;
14060 /* case: R1 = (s8, s16 s32)R2 */
14061 if (is_pointer_value(env, insn->src_reg)) {
14063 "R%d sign-extension part of pointer\n",
14066 } else if (src_reg->type == SCALAR_VALUE) {
14069 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14071 assign_scalar_id_before_mov(env, src_reg);
14072 copy_register_state(dst_reg, src_reg);
14075 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
14076 dst_reg->live |= REG_LIVE_WRITTEN;
14077 dst_reg->subreg_def = DEF_NOT_SUBREG;
14079 mark_reg_unknown(env, regs, insn->dst_reg);
14083 /* R1 = (u32) R2 */
14084 if (is_pointer_value(env, insn->src_reg)) {
14086 "R%d partial copy of pointer\n",
14089 } else if (src_reg->type == SCALAR_VALUE) {
14090 if (insn->off == 0) {
14091 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
14093 if (is_src_reg_u32)
14094 assign_scalar_id_before_mov(env, src_reg);
14095 copy_register_state(dst_reg, src_reg);
14096 /* Make sure ID is cleared if src_reg is not in u32
14097 * range otherwise dst_reg min/max could be incorrectly
14098 * propagated into src_reg by find_equal_scalars()
14100 if (!is_src_reg_u32)
14102 dst_reg->live |= REG_LIVE_WRITTEN;
14103 dst_reg->subreg_def = env->insn_idx + 1;
14105 /* case: W1 = (s8, s16)W2 */
14106 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14109 assign_scalar_id_before_mov(env, src_reg);
14110 copy_register_state(dst_reg, src_reg);
14113 dst_reg->live |= REG_LIVE_WRITTEN;
14114 dst_reg->subreg_def = env->insn_idx + 1;
14115 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
14118 mark_reg_unknown(env, regs,
14121 zext_32_to_64(dst_reg);
14122 reg_bounds_sync(dst_reg);
14126 * remember the value we stored into this reg
14128 /* clear any state __mark_reg_known doesn't set */
14129 mark_reg_unknown(env, regs, insn->dst_reg);
14130 regs[insn->dst_reg].type = SCALAR_VALUE;
14131 if (BPF_CLASS(insn->code) == BPF_ALU64) {
14132 __mark_reg_known(regs + insn->dst_reg,
14135 __mark_reg_known(regs + insn->dst_reg,
14140 } else if (opcode > BPF_END) {
14141 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
14144 } else { /* all other ALU ops: and, sub, xor, add, ... */
14146 if (BPF_SRC(insn->code) == BPF_X) {
14147 if (insn->imm != 0 || insn->off > 1 ||
14148 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14149 verbose(env, "BPF_ALU uses reserved fields\n");
14152 /* check src1 operand */
14153 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14157 if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
14158 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14159 verbose(env, "BPF_ALU uses reserved fields\n");
14164 /* check src2 operand */
14165 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14169 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
14170 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
14171 verbose(env, "div by zero\n");
14175 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
14176 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
14177 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
14179 if (insn->imm < 0 || insn->imm >= size) {
14180 verbose(env, "invalid shift %d\n", insn->imm);
14185 /* check dest operand */
14186 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14187 err = err ?: adjust_reg_min_max_vals(env, insn);
14192 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu");
14195 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
14196 struct bpf_reg_state *dst_reg,
14197 enum bpf_reg_type type,
14198 bool range_right_open)
14200 struct bpf_func_state *state;
14201 struct bpf_reg_state *reg;
14204 if (dst_reg->off < 0 ||
14205 (dst_reg->off == 0 && range_right_open))
14206 /* This doesn't give us any range */
14209 if (dst_reg->umax_value > MAX_PACKET_OFF ||
14210 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
14211 /* Risk of overflow. For instance, ptr + (1<<63) may be less
14212 * than pkt_end, but that's because it's also less than pkt.
14216 new_range = dst_reg->off;
14217 if (range_right_open)
14220 /* Examples for register markings:
14222 * pkt_data in dst register:
14226 * if (r2 > pkt_end) goto <handle exception>
14231 * if (r2 < pkt_end) goto <access okay>
14232 * <handle exception>
14235 * r2 == dst_reg, pkt_end == src_reg
14236 * r2=pkt(id=n,off=8,r=0)
14237 * r3=pkt(id=n,off=0,r=0)
14239 * pkt_data in src register:
14243 * if (pkt_end >= r2) goto <access okay>
14244 * <handle exception>
14248 * if (pkt_end <= r2) goto <handle exception>
14252 * pkt_end == dst_reg, r2 == src_reg
14253 * r2=pkt(id=n,off=8,r=0)
14254 * r3=pkt(id=n,off=0,r=0)
14256 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14257 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14258 * and [r3, r3 + 8-1) respectively is safe to access depending on
14262 /* If our ids match, then we must have the same max_value. And we
14263 * don't care about the other reg's fixed offset, since if it's too big
14264 * the range won't allow anything.
14265 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14267 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14268 if (reg->type == type && reg->id == dst_reg->id)
14269 /* keep the maximum range already checked */
14270 reg->range = max(reg->range, new_range);
14275 * <reg1> <op> <reg2>, currently assuming reg2 is a constant
14277 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14278 u8 opcode, bool is_jmp32)
14280 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
14281 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
14282 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
14283 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
14284 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
14285 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
14286 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
14287 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
14288 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
14289 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
14293 /* constants, umin/umax and smin/smax checks would be
14294 * redundant in this case because they all should match
14296 if (tnum_is_const(t1) && tnum_is_const(t2))
14297 return t1.value == t2.value;
14298 /* non-overlapping ranges */
14299 if (umin1 > umax2 || umax1 < umin2)
14301 if (smin1 > smax2 || smax1 < smin2)
14304 /* if 64-bit ranges are inconclusive, see if we can
14305 * utilize 32-bit subrange knowledge to eliminate
14306 * branches that can't be taken a priori
14308 if (reg1->u32_min_value > reg2->u32_max_value ||
14309 reg1->u32_max_value < reg2->u32_min_value)
14311 if (reg1->s32_min_value > reg2->s32_max_value ||
14312 reg1->s32_max_value < reg2->s32_min_value)
14317 /* constants, umin/umax and smin/smax checks would be
14318 * redundant in this case because they all should match
14320 if (tnum_is_const(t1) && tnum_is_const(t2))
14321 return t1.value != t2.value;
14322 /* non-overlapping ranges */
14323 if (umin1 > umax2 || umax1 < umin2)
14325 if (smin1 > smax2 || smax1 < smin2)
14328 /* if 64-bit ranges are inconclusive, see if we can
14329 * utilize 32-bit subrange knowledge to eliminate
14330 * branches that can't be taken a priori
14332 if (reg1->u32_min_value > reg2->u32_max_value ||
14333 reg1->u32_max_value < reg2->u32_min_value)
14335 if (reg1->s32_min_value > reg2->s32_max_value ||
14336 reg1->s32_max_value < reg2->s32_min_value)
14341 if (!is_reg_const(reg2, is_jmp32)) {
14345 if (!is_reg_const(reg2, is_jmp32))
14347 if ((~t1.mask & t1.value) & t2.value)
14349 if (!((t1.mask | t1.value) & t2.value))
14355 else if (umax1 <= umin2)
14361 else if (smax1 <= smin2)
14367 else if (umin1 >= umax2)
14373 else if (smin1 >= smax2)
14377 if (umin1 >= umax2)
14379 else if (umax1 < umin2)
14383 if (smin1 >= smax2)
14385 else if (smax1 < smin2)
14389 if (umax1 <= umin2)
14391 else if (umin1 > umax2)
14395 if (smax1 <= smin2)
14397 else if (smin1 > smax2)
14405 static int flip_opcode(u32 opcode)
14407 /* How can we transform "a <op> b" into "b <op> a"? */
14408 static const u8 opcode_flip[16] = {
14409 /* these stay the same */
14410 [BPF_JEQ >> 4] = BPF_JEQ,
14411 [BPF_JNE >> 4] = BPF_JNE,
14412 [BPF_JSET >> 4] = BPF_JSET,
14413 /* these swap "lesser" and "greater" (L and G in the opcodes) */
14414 [BPF_JGE >> 4] = BPF_JLE,
14415 [BPF_JGT >> 4] = BPF_JLT,
14416 [BPF_JLE >> 4] = BPF_JGE,
14417 [BPF_JLT >> 4] = BPF_JGT,
14418 [BPF_JSGE >> 4] = BPF_JSLE,
14419 [BPF_JSGT >> 4] = BPF_JSLT,
14420 [BPF_JSLE >> 4] = BPF_JSGE,
14421 [BPF_JSLT >> 4] = BPF_JSGT
14423 return opcode_flip[opcode >> 4];
14426 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14427 struct bpf_reg_state *src_reg,
14430 struct bpf_reg_state *pkt;
14432 if (src_reg->type == PTR_TO_PACKET_END) {
14434 } else if (dst_reg->type == PTR_TO_PACKET_END) {
14436 opcode = flip_opcode(opcode);
14441 if (pkt->range >= 0)
14446 /* pkt <= pkt_end */
14449 /* pkt > pkt_end */
14450 if (pkt->range == BEYOND_PKT_END)
14451 /* pkt has at last one extra byte beyond pkt_end */
14452 return opcode == BPF_JGT;
14455 /* pkt < pkt_end */
14458 /* pkt >= pkt_end */
14459 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14460 return opcode == BPF_JGE;
14466 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
14468 * 1 - branch will be taken and "goto target" will be executed
14469 * 0 - branch will not be taken and fall-through to next insn
14470 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
14473 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14474 u8 opcode, bool is_jmp32)
14476 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
14477 return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
14479 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
14482 /* arrange that reg2 is a scalar, and reg1 is a pointer */
14483 if (!is_reg_const(reg2, is_jmp32)) {
14484 opcode = flip_opcode(opcode);
14487 /* and ensure that reg2 is a constant */
14488 if (!is_reg_const(reg2, is_jmp32))
14491 if (!reg_not_null(reg1))
14494 /* If pointer is valid tests against zero will fail so we can
14495 * use this to direct branch taken.
14497 val = reg_const_value(reg2, is_jmp32);
14511 /* now deal with two scalars, but not necessarily constants */
14512 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
14515 /* Opcode that corresponds to a *false* branch condition.
14516 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
14518 static u8 rev_opcode(u8 opcode)
14521 case BPF_JEQ: return BPF_JNE;
14522 case BPF_JNE: return BPF_JEQ;
14523 /* JSET doesn't have it's reverse opcode in BPF, so add
14524 * BPF_X flag to denote the reverse of that operation
14526 case BPF_JSET: return BPF_JSET | BPF_X;
14527 case BPF_JSET | BPF_X: return BPF_JSET;
14528 case BPF_JGE: return BPF_JLT;
14529 case BPF_JGT: return BPF_JLE;
14530 case BPF_JLE: return BPF_JGT;
14531 case BPF_JLT: return BPF_JGE;
14532 case BPF_JSGE: return BPF_JSLT;
14533 case BPF_JSGT: return BPF_JSLE;
14534 case BPF_JSLE: return BPF_JSGT;
14535 case BPF_JSLT: return BPF_JSGE;
14540 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
14541 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14542 u8 opcode, bool is_jmp32)
14551 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14552 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14553 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14554 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14555 reg2->u32_min_value = reg1->u32_min_value;
14556 reg2->u32_max_value = reg1->u32_max_value;
14557 reg2->s32_min_value = reg1->s32_min_value;
14558 reg2->s32_max_value = reg1->s32_max_value;
14560 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
14561 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14562 reg2->var_off = tnum_with_subreg(reg2->var_off, t);
14564 reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
14565 reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14566 reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
14567 reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14568 reg2->umin_value = reg1->umin_value;
14569 reg2->umax_value = reg1->umax_value;
14570 reg2->smin_value = reg1->smin_value;
14571 reg2->smax_value = reg1->smax_value;
14573 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
14574 reg2->var_off = reg1->var_off;
14578 if (!is_reg_const(reg2, is_jmp32))
14580 if (!is_reg_const(reg2, is_jmp32))
14583 /* try to recompute the bound of reg1 if reg2 is a const and
14584 * is exactly the edge of reg1.
14586 val = reg_const_value(reg2, is_jmp32);
14588 /* u32_min_value is not equal to 0xffffffff at this point,
14589 * because otherwise u32_max_value is 0xffffffff as well,
14590 * in such a case both reg1 and reg2 would be constants,
14591 * jump would be predicted and reg_set_min_max() won't
14594 * Same reasoning works for all {u,s}{min,max}{32,64} cases
14597 if (reg1->u32_min_value == (u32)val)
14598 reg1->u32_min_value++;
14599 if (reg1->u32_max_value == (u32)val)
14600 reg1->u32_max_value--;
14601 if (reg1->s32_min_value == (s32)val)
14602 reg1->s32_min_value++;
14603 if (reg1->s32_max_value == (s32)val)
14604 reg1->s32_max_value--;
14606 if (reg1->umin_value == (u64)val)
14607 reg1->umin_value++;
14608 if (reg1->umax_value == (u64)val)
14609 reg1->umax_value--;
14610 if (reg1->smin_value == (s64)val)
14611 reg1->smin_value++;
14612 if (reg1->smax_value == (s64)val)
14613 reg1->smax_value--;
14617 if (!is_reg_const(reg2, is_jmp32))
14619 if (!is_reg_const(reg2, is_jmp32))
14621 val = reg_const_value(reg2, is_jmp32);
14622 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
14623 * requires single bit to learn something useful. E.g., if we
14624 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
14625 * are actually set? We can learn something definite only if
14626 * it's a single-bit value to begin with.
14628 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
14629 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
14630 * bit 1 is set, which we can readily use in adjustments.
14632 if (!is_power_of_2(val))
14635 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
14636 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14638 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
14641 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
14642 if (!is_reg_const(reg2, is_jmp32))
14644 if (!is_reg_const(reg2, is_jmp32))
14646 val = reg_const_value(reg2, is_jmp32);
14648 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
14649 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14651 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
14656 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14657 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14659 reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14660 reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
14665 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
14666 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
14668 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
14669 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
14674 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14675 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14677 reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14678 reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
14683 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
14684 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
14686 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
14687 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
14694 /* just reuse LE/LT logic above */
14695 opcode = flip_opcode(opcode);
14703 /* Adjusts the register min/max values in the case that the dst_reg and
14704 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
14705 * check, in which case we havea fake SCALAR_VALUE representing insn->imm).
14706 * Technically we can do similar adjustments for pointers to the same object,
14707 * but we don't support that right now.
14709 static int reg_set_min_max(struct bpf_verifier_env *env,
14710 struct bpf_reg_state *true_reg1,
14711 struct bpf_reg_state *true_reg2,
14712 struct bpf_reg_state *false_reg1,
14713 struct bpf_reg_state *false_reg2,
14714 u8 opcode, bool is_jmp32)
14718 /* If either register is a pointer, we can't learn anything about its
14719 * variable offset from the compare (unless they were a pointer into
14720 * the same object, but we don't bother with that).
14722 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
14725 /* fallthrough (FALSE) branch */
14726 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
14727 reg_bounds_sync(false_reg1);
14728 reg_bounds_sync(false_reg2);
14730 /* jump (TRUE) branch */
14731 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
14732 reg_bounds_sync(true_reg1);
14733 reg_bounds_sync(true_reg2);
14735 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
14736 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
14737 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
14738 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
14742 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14743 struct bpf_reg_state *reg, u32 id,
14746 if (type_may_be_null(reg->type) && reg->id == id &&
14747 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14748 /* Old offset (both fixed and variable parts) should have been
14749 * known-zero, because we don't allow pointer arithmetic on
14750 * pointers that might be NULL. If we see this happening, don't
14751 * convert the register.
14753 * But in some cases, some helpers that return local kptrs
14754 * advance offset for the returned pointer. In those cases, it
14755 * is fine to expect to see reg->off.
14757 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14759 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14760 WARN_ON_ONCE(reg->off))
14764 reg->type = SCALAR_VALUE;
14765 /* We don't need id and ref_obj_id from this point
14766 * onwards anymore, thus we should better reset it,
14767 * so that state pruning has chances to take effect.
14770 reg->ref_obj_id = 0;
14775 mark_ptr_not_null_reg(reg);
14777 if (!reg_may_point_to_spin_lock(reg)) {
14778 /* For not-NULL ptr, reg->ref_obj_id will be reset
14779 * in release_reference().
14781 * reg->id is still used by spin_lock ptr. Other
14782 * than spin_lock ptr type, reg->id can be reset.
14789 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14790 * be folded together at some point.
14792 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14795 struct bpf_func_state *state = vstate->frame[vstate->curframe];
14796 struct bpf_reg_state *regs = state->regs, *reg;
14797 u32 ref_obj_id = regs[regno].ref_obj_id;
14798 u32 id = regs[regno].id;
14800 if (ref_obj_id && ref_obj_id == id && is_null)
14801 /* regs[regno] is in the " == NULL" branch.
14802 * No one could have freed the reference state before
14803 * doing the NULL check.
14805 WARN_ON_ONCE(release_reference_state(state, id));
14807 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14808 mark_ptr_or_null_reg(state, reg, id, is_null);
14812 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14813 struct bpf_reg_state *dst_reg,
14814 struct bpf_reg_state *src_reg,
14815 struct bpf_verifier_state *this_branch,
14816 struct bpf_verifier_state *other_branch)
14818 if (BPF_SRC(insn->code) != BPF_X)
14821 /* Pointers are always 64-bit. */
14822 if (BPF_CLASS(insn->code) == BPF_JMP32)
14825 switch (BPF_OP(insn->code)) {
14827 if ((dst_reg->type == PTR_TO_PACKET &&
14828 src_reg->type == PTR_TO_PACKET_END) ||
14829 (dst_reg->type == PTR_TO_PACKET_META &&
14830 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14831 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14832 find_good_pkt_pointers(this_branch, dst_reg,
14833 dst_reg->type, false);
14834 mark_pkt_end(other_branch, insn->dst_reg, true);
14835 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14836 src_reg->type == PTR_TO_PACKET) ||
14837 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14838 src_reg->type == PTR_TO_PACKET_META)) {
14839 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
14840 find_good_pkt_pointers(other_branch, src_reg,
14841 src_reg->type, true);
14842 mark_pkt_end(this_branch, insn->src_reg, false);
14848 if ((dst_reg->type == PTR_TO_PACKET &&
14849 src_reg->type == PTR_TO_PACKET_END) ||
14850 (dst_reg->type == PTR_TO_PACKET_META &&
14851 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14852 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14853 find_good_pkt_pointers(other_branch, dst_reg,
14854 dst_reg->type, true);
14855 mark_pkt_end(this_branch, insn->dst_reg, false);
14856 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14857 src_reg->type == PTR_TO_PACKET) ||
14858 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14859 src_reg->type == PTR_TO_PACKET_META)) {
14860 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
14861 find_good_pkt_pointers(this_branch, src_reg,
14862 src_reg->type, false);
14863 mark_pkt_end(other_branch, insn->src_reg, true);
14869 if ((dst_reg->type == PTR_TO_PACKET &&
14870 src_reg->type == PTR_TO_PACKET_END) ||
14871 (dst_reg->type == PTR_TO_PACKET_META &&
14872 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14873 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14874 find_good_pkt_pointers(this_branch, dst_reg,
14875 dst_reg->type, true);
14876 mark_pkt_end(other_branch, insn->dst_reg, false);
14877 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14878 src_reg->type == PTR_TO_PACKET) ||
14879 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14880 src_reg->type == PTR_TO_PACKET_META)) {
14881 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14882 find_good_pkt_pointers(other_branch, src_reg,
14883 src_reg->type, false);
14884 mark_pkt_end(this_branch, insn->src_reg, true);
14890 if ((dst_reg->type == PTR_TO_PACKET &&
14891 src_reg->type == PTR_TO_PACKET_END) ||
14892 (dst_reg->type == PTR_TO_PACKET_META &&
14893 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14894 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14895 find_good_pkt_pointers(other_branch, dst_reg,
14896 dst_reg->type, false);
14897 mark_pkt_end(this_branch, insn->dst_reg, true);
14898 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14899 src_reg->type == PTR_TO_PACKET) ||
14900 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14901 src_reg->type == PTR_TO_PACKET_META)) {
14902 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14903 find_good_pkt_pointers(this_branch, src_reg,
14904 src_reg->type, true);
14905 mark_pkt_end(other_branch, insn->src_reg, false);
14917 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14918 struct bpf_reg_state *known_reg)
14920 struct bpf_func_state *state;
14921 struct bpf_reg_state *reg;
14923 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14924 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14925 copy_register_state(reg, known_reg);
14929 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14930 struct bpf_insn *insn, int *insn_idx)
14932 struct bpf_verifier_state *this_branch = env->cur_state;
14933 struct bpf_verifier_state *other_branch;
14934 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14935 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14936 struct bpf_reg_state *eq_branch_regs;
14937 struct bpf_reg_state fake_reg = {};
14938 u8 opcode = BPF_OP(insn->code);
14943 /* Only conditional jumps are expected to reach here. */
14944 if (opcode == BPF_JA || opcode > BPF_JCOND) {
14945 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14949 if (opcode == BPF_JCOND) {
14950 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
14951 int idx = *insn_idx;
14953 if (insn->code != (BPF_JMP | BPF_JCOND) ||
14954 insn->src_reg != BPF_MAY_GOTO ||
14955 insn->dst_reg || insn->imm || insn->off == 0) {
14956 verbose(env, "invalid may_goto off %d imm %d\n",
14957 insn->off, insn->imm);
14960 prev_st = find_prev_entry(env, cur_st->parent, idx);
14962 /* branch out 'fallthrough' insn as a new state to explore */
14963 queued_st = push_stack(env, idx + 1, idx, false);
14967 queued_st->may_goto_depth++;
14969 widen_imprecise_scalars(env, prev_st, queued_st);
14970 *insn_idx += insn->off;
14974 /* check src2 operand */
14975 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14979 dst_reg = ®s[insn->dst_reg];
14980 if (BPF_SRC(insn->code) == BPF_X) {
14981 if (insn->imm != 0) {
14982 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14986 /* check src1 operand */
14987 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14991 src_reg = ®s[insn->src_reg];
14992 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14993 is_pointer_value(env, insn->src_reg)) {
14994 verbose(env, "R%d pointer comparison prohibited\n",
14999 if (insn->src_reg != BPF_REG_0) {
15000 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15003 src_reg = &fake_reg;
15004 src_reg->type = SCALAR_VALUE;
15005 __mark_reg_known(src_reg, insn->imm);
15008 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
15009 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
15011 /* If we get here with a dst_reg pointer type it is because
15012 * above is_branch_taken() special cased the 0 comparison.
15014 if (!__is_pointer_value(false, dst_reg))
15015 err = mark_chain_precision(env, insn->dst_reg);
15016 if (BPF_SRC(insn->code) == BPF_X && !err &&
15017 !__is_pointer_value(false, src_reg))
15018 err = mark_chain_precision(env, insn->src_reg);
15024 /* Only follow the goto, ignore fall-through. If needed, push
15025 * the fall-through branch for simulation under speculative
15028 if (!env->bypass_spec_v1 &&
15029 !sanitize_speculative_path(env, insn, *insn_idx + 1,
15032 if (env->log.level & BPF_LOG_LEVEL)
15033 print_insn_state(env, this_branch->frame[this_branch->curframe]);
15034 *insn_idx += insn->off;
15036 } else if (pred == 0) {
15037 /* Only follow the fall-through branch, since that's where the
15038 * program will go. If needed, push the goto branch for
15039 * simulation under speculative execution.
15041 if (!env->bypass_spec_v1 &&
15042 !sanitize_speculative_path(env, insn,
15043 *insn_idx + insn->off + 1,
15046 if (env->log.level & BPF_LOG_LEVEL)
15047 print_insn_state(env, this_branch->frame[this_branch->curframe]);
15051 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
15055 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
15057 if (BPF_SRC(insn->code) == BPF_X) {
15058 err = reg_set_min_max(env,
15059 &other_branch_regs[insn->dst_reg],
15060 &other_branch_regs[insn->src_reg],
15061 dst_reg, src_reg, opcode, is_jmp32);
15062 } else /* BPF_SRC(insn->code) == BPF_K */ {
15063 err = reg_set_min_max(env,
15064 &other_branch_regs[insn->dst_reg],
15065 src_reg /* fake one */,
15066 dst_reg, src_reg /* same fake one */,
15072 if (BPF_SRC(insn->code) == BPF_X &&
15073 src_reg->type == SCALAR_VALUE && src_reg->id &&
15074 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
15075 find_equal_scalars(this_branch, src_reg);
15076 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
15078 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
15079 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
15080 find_equal_scalars(this_branch, dst_reg);
15081 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
15084 /* if one pointer register is compared to another pointer
15085 * register check if PTR_MAYBE_NULL could be lifted.
15086 * E.g. register A - maybe null
15087 * register B - not null
15088 * for JNE A, B, ... - A is not null in the false branch;
15089 * for JEQ A, B, ... - A is not null in the true branch.
15091 * Since PTR_TO_BTF_ID points to a kernel struct that does
15092 * not need to be null checked by the BPF program, i.e.,
15093 * could be null even without PTR_MAYBE_NULL marking, so
15094 * only propagate nullness when neither reg is that type.
15096 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
15097 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
15098 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
15099 base_type(src_reg->type) != PTR_TO_BTF_ID &&
15100 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
15101 eq_branch_regs = NULL;
15104 eq_branch_regs = other_branch_regs;
15107 eq_branch_regs = regs;
15113 if (eq_branch_regs) {
15114 if (type_may_be_null(src_reg->type))
15115 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
15117 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
15121 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
15122 * NOTE: these optimizations below are related with pointer comparison
15123 * which will never be JMP32.
15125 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
15126 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
15127 type_may_be_null(dst_reg->type)) {
15128 /* Mark all identical registers in each branch as either
15129 * safe or unknown depending R == 0 or R != 0 conditional.
15131 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
15132 opcode == BPF_JNE);
15133 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
15134 opcode == BPF_JEQ);
15135 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
15136 this_branch, other_branch) &&
15137 is_pointer_value(env, insn->dst_reg)) {
15138 verbose(env, "R%d pointer comparison prohibited\n",
15142 if (env->log.level & BPF_LOG_LEVEL)
15143 print_insn_state(env, this_branch->frame[this_branch->curframe]);
15147 /* verify BPF_LD_IMM64 instruction */
15148 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
15150 struct bpf_insn_aux_data *aux = cur_aux(env);
15151 struct bpf_reg_state *regs = cur_regs(env);
15152 struct bpf_reg_state *dst_reg;
15153 struct bpf_map *map;
15156 if (BPF_SIZE(insn->code) != BPF_DW) {
15157 verbose(env, "invalid BPF_LD_IMM insn\n");
15160 if (insn->off != 0) {
15161 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
15165 err = check_reg_arg(env, insn->dst_reg, DST_OP);
15169 dst_reg = ®s[insn->dst_reg];
15170 if (insn->src_reg == 0) {
15171 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
15173 dst_reg->type = SCALAR_VALUE;
15174 __mark_reg_known(®s[insn->dst_reg], imm);
15178 /* All special src_reg cases are listed below. From this point onwards
15179 * we either succeed and assign a corresponding dst_reg->type after
15180 * zeroing the offset, or fail and reject the program.
15182 mark_reg_known_zero(env, regs, insn->dst_reg);
15184 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
15185 dst_reg->type = aux->btf_var.reg_type;
15186 switch (base_type(dst_reg->type)) {
15188 dst_reg->mem_size = aux->btf_var.mem_size;
15190 case PTR_TO_BTF_ID:
15191 dst_reg->btf = aux->btf_var.btf;
15192 dst_reg->btf_id = aux->btf_var.btf_id;
15195 verbose(env, "bpf verifier is misconfigured\n");
15201 if (insn->src_reg == BPF_PSEUDO_FUNC) {
15202 struct bpf_prog_aux *aux = env->prog->aux;
15203 u32 subprogno = find_subprog(env,
15204 env->insn_idx + insn->imm + 1);
15206 if (!aux->func_info) {
15207 verbose(env, "missing btf func_info\n");
15210 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
15211 verbose(env, "callback function not static\n");
15215 dst_reg->type = PTR_TO_FUNC;
15216 dst_reg->subprogno = subprogno;
15220 map = env->used_maps[aux->map_index];
15221 dst_reg->map_ptr = map;
15223 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15224 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15225 if (map->map_type == BPF_MAP_TYPE_ARENA) {
15226 __mark_reg_unknown(env, dst_reg);
15229 dst_reg->type = PTR_TO_MAP_VALUE;
15230 dst_reg->off = aux->map_off;
15231 WARN_ON_ONCE(map->max_entries != 1);
15232 /* We want reg->id to be same (0) as map_value is not distinct */
15233 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15234 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15235 dst_reg->type = CONST_PTR_TO_MAP;
15237 verbose(env, "bpf verifier is misconfigured\n");
15244 static bool may_access_skb(enum bpf_prog_type type)
15247 case BPF_PROG_TYPE_SOCKET_FILTER:
15248 case BPF_PROG_TYPE_SCHED_CLS:
15249 case BPF_PROG_TYPE_SCHED_ACT:
15256 /* verify safety of LD_ABS|LD_IND instructions:
15257 * - they can only appear in the programs where ctx == skb
15258 * - since they are wrappers of function calls, they scratch R1-R5 registers,
15259 * preserve R6-R9, and store return value into R0
15262 * ctx == skb == R6 == CTX
15265 * SRC == any register
15266 * IMM == 32-bit immediate
15269 * R0 - 8/16/32-bit skb data converted to cpu endianness
15271 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15273 struct bpf_reg_state *regs = cur_regs(env);
15274 static const int ctx_reg = BPF_REG_6;
15275 u8 mode = BPF_MODE(insn->code);
15278 if (!may_access_skb(resolve_prog_type(env->prog))) {
15279 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15283 if (!env->ops->gen_ld_abs) {
15284 verbose(env, "bpf verifier is misconfigured\n");
15288 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15289 BPF_SIZE(insn->code) == BPF_DW ||
15290 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15291 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
15295 /* check whether implicit source operand (register R6) is readable */
15296 err = check_reg_arg(env, ctx_reg, SRC_OP);
15300 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15301 * gen_ld_abs() may terminate the program at runtime, leading to
15304 err = check_reference_leak(env, false);
15306 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15310 if (env->cur_state->active_lock.ptr) {
15311 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15315 if (env->cur_state->active_rcu_lock) {
15316 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15320 if (regs[ctx_reg].type != PTR_TO_CTX) {
15322 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
15326 if (mode == BPF_IND) {
15327 /* check explicit source operand */
15328 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15333 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
15337 /* reset caller saved regs to unreadable */
15338 for (i = 0; i < CALLER_SAVED_REGS; i++) {
15339 mark_reg_not_init(env, regs, caller_saved[i]);
15340 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15343 /* mark destination R0 register as readable, since it contains
15344 * the value fetched from the packet.
15345 * Already marked as written above.
15347 mark_reg_unknown(env, regs, BPF_REG_0);
15348 /* ld_abs load up to 32-bit skb data. */
15349 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
15353 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
15355 const char *exit_ctx = "At program exit";
15356 struct tnum enforce_attach_type_range = tnum_unknown;
15357 const struct bpf_prog *prog = env->prog;
15358 struct bpf_reg_state *reg;
15359 struct bpf_retval_range range = retval_range(0, 1);
15360 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15362 struct bpf_func_state *frame = env->cur_state->frame[0];
15363 const bool is_subprog = frame->subprogno;
15365 /* LSM and struct_ops func-ptr's return type could be "void" */
15366 if (!is_subprog || frame->in_exception_callback_fn) {
15367 switch (prog_type) {
15368 case BPF_PROG_TYPE_LSM:
15369 if (prog->expected_attach_type == BPF_LSM_CGROUP)
15370 /* See below, can be 0 or 0-1 depending on hook. */
15373 case BPF_PROG_TYPE_STRUCT_OPS:
15374 if (!prog->aux->attach_func_proto->type)
15382 /* eBPF calling convention is such that R0 is used
15383 * to return the value from eBPF program.
15384 * Make sure that it's readable at this time
15385 * of bpf_exit, which means that program wrote
15386 * something into it earlier
15388 err = check_reg_arg(env, regno, SRC_OP);
15392 if (is_pointer_value(env, regno)) {
15393 verbose(env, "R%d leaks addr as return value\n", regno);
15397 reg = cur_regs(env) + regno;
15399 if (frame->in_async_callback_fn) {
15400 /* enforce return zero from async callbacks like timer */
15401 exit_ctx = "At async callback return";
15402 range = retval_range(0, 0);
15403 goto enforce_retval;
15406 if (is_subprog && !frame->in_exception_callback_fn) {
15407 if (reg->type != SCALAR_VALUE) {
15408 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15409 regno, reg_type_str(env, reg->type));
15415 switch (prog_type) {
15416 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15417 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15418 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15419 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15420 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15421 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15422 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15423 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15424 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15425 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15426 range = retval_range(1, 1);
15427 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15428 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15429 range = retval_range(0, 3);
15431 case BPF_PROG_TYPE_CGROUP_SKB:
15432 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15433 range = retval_range(0, 3);
15434 enforce_attach_type_range = tnum_range(2, 3);
15437 case BPF_PROG_TYPE_CGROUP_SOCK:
15438 case BPF_PROG_TYPE_SOCK_OPS:
15439 case BPF_PROG_TYPE_CGROUP_DEVICE:
15440 case BPF_PROG_TYPE_CGROUP_SYSCTL:
15441 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15443 case BPF_PROG_TYPE_RAW_TRACEPOINT:
15444 if (!env->prog->aux->attach_btf_id)
15446 range = retval_range(0, 0);
15448 case BPF_PROG_TYPE_TRACING:
15449 switch (env->prog->expected_attach_type) {
15450 case BPF_TRACE_FENTRY:
15451 case BPF_TRACE_FEXIT:
15452 range = retval_range(0, 0);
15454 case BPF_TRACE_RAW_TP:
15455 case BPF_MODIFY_RETURN:
15457 case BPF_TRACE_ITER:
15463 case BPF_PROG_TYPE_SK_LOOKUP:
15464 range = retval_range(SK_DROP, SK_PASS);
15467 case BPF_PROG_TYPE_LSM:
15468 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15469 /* Regular BPF_PROG_TYPE_LSM programs can return
15474 if (!env->prog->aux->attach_func_proto->type) {
15475 /* Make sure programs that attach to void
15476 * hooks don't try to modify return value.
15478 range = retval_range(1, 1);
15482 case BPF_PROG_TYPE_NETFILTER:
15483 range = retval_range(NF_DROP, NF_ACCEPT);
15485 case BPF_PROG_TYPE_EXT:
15486 /* freplace program can return anything as its return value
15487 * depends on the to-be-replaced kernel func or bpf program.
15494 if (reg->type != SCALAR_VALUE) {
15495 verbose(env, "%s the register R%d is not a known value (%s)\n",
15496 exit_ctx, regno, reg_type_str(env, reg->type));
15500 err = mark_chain_precision(env, regno);
15504 if (!retval_range_within(range, reg)) {
15505 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
15507 prog->expected_attach_type == BPF_LSM_CGROUP &&
15508 prog_type == BPF_PROG_TYPE_LSM &&
15509 !prog->aux->attach_func_proto->type)
15510 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15514 if (!tnum_is_unknown(enforce_attach_type_range) &&
15515 tnum_in(enforce_attach_type_range, reg->var_off))
15516 env->prog->enforce_expected_attach_type = 1;
15520 /* non-recursive DFS pseudo code
15521 * 1 procedure DFS-iterative(G,v):
15522 * 2 label v as discovered
15523 * 3 let S be a stack
15525 * 5 while S is not empty
15527 * 7 if t is what we're looking for:
15529 * 9 for all edges e in G.adjacentEdges(t) do
15530 * 10 if edge e is already labelled
15531 * 11 continue with the next edge
15532 * 12 w <- G.adjacentVertex(t,e)
15533 * 13 if vertex w is not discovered and not explored
15534 * 14 label e as tree-edge
15535 * 15 label w as discovered
15538 * 18 else if vertex w is discovered
15539 * 19 label e as back-edge
15541 * 21 // vertex w is explored
15542 * 22 label e as forward- or cross-edge
15543 * 23 label t as explored
15547 * 0x10 - discovered
15548 * 0x11 - discovered and fall-through edge labelled
15549 * 0x12 - discovered and fall-through and branch edges labelled
15560 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15562 env->insn_aux_data[idx].prune_point = true;
15565 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15567 return env->insn_aux_data[insn_idx].prune_point;
15570 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15572 env->insn_aux_data[idx].force_checkpoint = true;
15575 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15577 return env->insn_aux_data[insn_idx].force_checkpoint;
15580 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15582 env->insn_aux_data[idx].calls_callback = true;
15585 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15587 return env->insn_aux_data[insn_idx].calls_callback;
15591 DONE_EXPLORING = 0,
15592 KEEP_EXPLORING = 1,
15595 /* t, w, e - match pseudo-code above:
15596 * t - index of current instruction
15597 * w - next instruction
15600 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15602 int *insn_stack = env->cfg.insn_stack;
15603 int *insn_state = env->cfg.insn_state;
15605 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15606 return DONE_EXPLORING;
15608 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15609 return DONE_EXPLORING;
15611 if (w < 0 || w >= env->prog->len) {
15612 verbose_linfo(env, t, "%d: ", t);
15613 verbose(env, "jump out of range from insn %d to %d\n", t, w);
15618 /* mark branch target for state pruning */
15619 mark_prune_point(env, w);
15620 mark_jmp_point(env, w);
15623 if (insn_state[w] == 0) {
15625 insn_state[t] = DISCOVERED | e;
15626 insn_state[w] = DISCOVERED;
15627 if (env->cfg.cur_stack >= env->prog->len)
15629 insn_stack[env->cfg.cur_stack++] = w;
15630 return KEEP_EXPLORING;
15631 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15632 if (env->bpf_capable)
15633 return DONE_EXPLORING;
15634 verbose_linfo(env, t, "%d: ", t);
15635 verbose_linfo(env, w, "%d: ", w);
15636 verbose(env, "back-edge from insn %d to %d\n", t, w);
15638 } else if (insn_state[w] == EXPLORED) {
15639 /* forward- or cross-edge */
15640 insn_state[t] = DISCOVERED | e;
15642 verbose(env, "insn state internal bug\n");
15645 return DONE_EXPLORING;
15648 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15649 struct bpf_verifier_env *env,
15654 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15655 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15659 mark_prune_point(env, t + insn_sz);
15660 /* when we exit from subprog, we need to record non-linear history */
15661 mark_jmp_point(env, t + insn_sz);
15663 if (visit_callee) {
15664 mark_prune_point(env, t);
15665 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15670 /* Visits the instruction at index t and returns one of the following:
15671 * < 0 - an error occurred
15672 * DONE_EXPLORING - the instruction was fully explored
15673 * KEEP_EXPLORING - there is still work to be done before it is fully explored
15675 static int visit_insn(int t, struct bpf_verifier_env *env)
15677 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15678 int ret, off, insn_sz;
15680 if (bpf_pseudo_func(insn))
15681 return visit_func_call_insn(t, insns, env, true);
15683 /* All non-branch instructions have a single fall-through edge. */
15684 if (BPF_CLASS(insn->code) != BPF_JMP &&
15685 BPF_CLASS(insn->code) != BPF_JMP32) {
15686 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15687 return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15690 switch (BPF_OP(insn->code)) {
15692 return DONE_EXPLORING;
15695 if (is_async_callback_calling_insn(insn))
15696 /* Mark this call insn as a prune point to trigger
15697 * is_state_visited() check before call itself is
15698 * processed by __check_func_call(). Otherwise new
15699 * async state will be pushed for further exploration.
15701 mark_prune_point(env, t);
15702 /* For functions that invoke callbacks it is not known how many times
15703 * callback would be called. Verifier models callback calling functions
15704 * by repeatedly visiting callback bodies and returning to origin call
15706 * In order to stop such iteration verifier needs to identify when a
15707 * state identical some state from a previous iteration is reached.
15708 * Check below forces creation of checkpoint before callback calling
15709 * instruction to allow search for such identical states.
15711 if (is_sync_callback_calling_insn(insn)) {
15712 mark_calls_callback(env, t);
15713 mark_force_checkpoint(env, t);
15714 mark_prune_point(env, t);
15715 mark_jmp_point(env, t);
15717 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15718 struct bpf_kfunc_call_arg_meta meta;
15720 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15721 if (ret == 0 && is_iter_next_kfunc(&meta)) {
15722 mark_prune_point(env, t);
15723 /* Checking and saving state checkpoints at iter_next() call
15724 * is crucial for fast convergence of open-coded iterator loop
15725 * logic, so we need to force it. If we don't do that,
15726 * is_state_visited() might skip saving a checkpoint, causing
15727 * unnecessarily long sequence of not checkpointed
15728 * instructions and jumps, leading to exhaustion of jump
15729 * history buffer, and potentially other undesired outcomes.
15730 * It is expected that with correct open-coded iterators
15731 * convergence will happen quickly, so we don't run a risk of
15732 * exhausting memory.
15734 mark_force_checkpoint(env, t);
15737 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15740 if (BPF_SRC(insn->code) != BPF_K)
15743 if (BPF_CLASS(insn->code) == BPF_JMP)
15748 /* unconditional jump with single edge */
15749 ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15753 mark_prune_point(env, t + off + 1);
15754 mark_jmp_point(env, t + off + 1);
15759 /* conditional jump with two edges */
15760 mark_prune_point(env, t);
15761 if (is_may_goto_insn(insn))
15762 mark_force_checkpoint(env, t);
15764 ret = push_insn(t, t + 1, FALLTHROUGH, env);
15768 return push_insn(t, t + insn->off + 1, BRANCH, env);
15772 /* non-recursive depth-first-search to detect loops in BPF program
15773 * loop == back-edge in directed graph
15775 static int check_cfg(struct bpf_verifier_env *env)
15777 int insn_cnt = env->prog->len;
15778 int *insn_stack, *insn_state;
15779 int ex_insn_beg, i, ret = 0;
15780 bool ex_done = false;
15782 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15786 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15788 kvfree(insn_state);
15792 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15793 insn_stack[0] = 0; /* 0 is the first instruction */
15794 env->cfg.cur_stack = 1;
15797 while (env->cfg.cur_stack > 0) {
15798 int t = insn_stack[env->cfg.cur_stack - 1];
15800 ret = visit_insn(t, env);
15802 case DONE_EXPLORING:
15803 insn_state[t] = EXPLORED;
15804 env->cfg.cur_stack--;
15806 case KEEP_EXPLORING:
15810 verbose(env, "visit_insn internal bug\n");
15817 if (env->cfg.cur_stack < 0) {
15818 verbose(env, "pop stack internal bug\n");
15823 if (env->exception_callback_subprog && !ex_done) {
15824 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
15826 insn_state[ex_insn_beg] = DISCOVERED;
15827 insn_stack[0] = ex_insn_beg;
15828 env->cfg.cur_stack = 1;
15833 for (i = 0; i < insn_cnt; i++) {
15834 struct bpf_insn *insn = &env->prog->insnsi[i];
15836 if (insn_state[i] != EXPLORED) {
15837 verbose(env, "unreachable insn %d\n", i);
15841 if (bpf_is_ldimm64(insn)) {
15842 if (insn_state[i + 1] != 0) {
15843 verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15847 i++; /* skip second half of ldimm64 */
15850 ret = 0; /* cfg looks good */
15853 kvfree(insn_state);
15854 kvfree(insn_stack);
15855 env->cfg.insn_state = env->cfg.insn_stack = NULL;
15859 static int check_abnormal_return(struct bpf_verifier_env *env)
15863 for (i = 1; i < env->subprog_cnt; i++) {
15864 if (env->subprog_info[i].has_ld_abs) {
15865 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15868 if (env->subprog_info[i].has_tail_call) {
15869 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15876 /* The minimum supported BTF func info size */
15877 #define MIN_BPF_FUNCINFO_SIZE 8
15878 #define MAX_FUNCINFO_REC_SIZE 252
15880 static int check_btf_func_early(struct bpf_verifier_env *env,
15881 const union bpf_attr *attr,
15884 u32 krec_size = sizeof(struct bpf_func_info);
15885 const struct btf_type *type, *func_proto;
15886 u32 i, nfuncs, urec_size, min_size;
15887 struct bpf_func_info *krecord;
15888 struct bpf_prog *prog;
15889 const struct btf *btf;
15890 u32 prev_offset = 0;
15894 nfuncs = attr->func_info_cnt;
15896 if (check_abnormal_return(env))
15901 urec_size = attr->func_info_rec_size;
15902 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15903 urec_size > MAX_FUNCINFO_REC_SIZE ||
15904 urec_size % sizeof(u32)) {
15905 verbose(env, "invalid func info rec size %u\n", urec_size);
15910 btf = prog->aux->btf;
15912 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15913 min_size = min_t(u32, krec_size, urec_size);
15915 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15919 for (i = 0; i < nfuncs; i++) {
15920 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15922 if (ret == -E2BIG) {
15923 verbose(env, "nonzero tailing record in func info");
15924 /* set the size kernel expects so loader can zero
15925 * out the rest of the record.
15927 if (copy_to_bpfptr_offset(uattr,
15928 offsetof(union bpf_attr, func_info_rec_size),
15929 &min_size, sizeof(min_size)))
15935 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15940 /* check insn_off */
15943 if (krecord[i].insn_off) {
15945 "nonzero insn_off %u for the first func info record",
15946 krecord[i].insn_off);
15949 } else if (krecord[i].insn_off <= prev_offset) {
15951 "same or smaller insn offset (%u) than previous func info record (%u)",
15952 krecord[i].insn_off, prev_offset);
15956 /* check type_id */
15957 type = btf_type_by_id(btf, krecord[i].type_id);
15958 if (!type || !btf_type_is_func(type)) {
15959 verbose(env, "invalid type id %d in func info",
15960 krecord[i].type_id);
15964 func_proto = btf_type_by_id(btf, type->type);
15965 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15966 /* btf_func_check() already verified it during BTF load */
15969 prev_offset = krecord[i].insn_off;
15970 bpfptr_add(&urecord, urec_size);
15973 prog->aux->func_info = krecord;
15974 prog->aux->func_info_cnt = nfuncs;
15982 static int check_btf_func(struct bpf_verifier_env *env,
15983 const union bpf_attr *attr,
15986 const struct btf_type *type, *func_proto, *ret_type;
15987 u32 i, nfuncs, urec_size;
15988 struct bpf_func_info *krecord;
15989 struct bpf_func_info_aux *info_aux = NULL;
15990 struct bpf_prog *prog;
15991 const struct btf *btf;
15993 bool scalar_return;
15996 nfuncs = attr->func_info_cnt;
15998 if (check_abnormal_return(env))
16002 if (nfuncs != env->subprog_cnt) {
16003 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
16007 urec_size = attr->func_info_rec_size;
16010 btf = prog->aux->btf;
16012 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
16014 krecord = prog->aux->func_info;
16015 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
16019 for (i = 0; i < nfuncs; i++) {
16020 /* check insn_off */
16023 if (env->subprog_info[i].start != krecord[i].insn_off) {
16024 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
16028 /* Already checked type_id */
16029 type = btf_type_by_id(btf, krecord[i].type_id);
16030 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
16031 /* Already checked func_proto */
16032 func_proto = btf_type_by_id(btf, type->type);
16034 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
16036 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
16037 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
16038 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
16041 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
16042 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
16046 bpfptr_add(&urecord, urec_size);
16049 prog->aux->func_info_aux = info_aux;
16057 static void adjust_btf_func(struct bpf_verifier_env *env)
16059 struct bpf_prog_aux *aux = env->prog->aux;
16062 if (!aux->func_info)
16065 /* func_info is not available for hidden subprogs */
16066 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
16067 aux->func_info[i].insn_off = env->subprog_info[i].start;
16070 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
16071 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
16073 static int check_btf_line(struct bpf_verifier_env *env,
16074 const union bpf_attr *attr,
16077 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
16078 struct bpf_subprog_info *sub;
16079 struct bpf_line_info *linfo;
16080 struct bpf_prog *prog;
16081 const struct btf *btf;
16085 nr_linfo = attr->line_info_cnt;
16088 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
16091 rec_size = attr->line_info_rec_size;
16092 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
16093 rec_size > MAX_LINEINFO_REC_SIZE ||
16094 rec_size & (sizeof(u32) - 1))
16097 /* Need to zero it in case the userspace may
16098 * pass in a smaller bpf_line_info object.
16100 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
16101 GFP_KERNEL | __GFP_NOWARN);
16106 btf = prog->aux->btf;
16109 sub = env->subprog_info;
16110 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
16111 expected_size = sizeof(struct bpf_line_info);
16112 ncopy = min_t(u32, expected_size, rec_size);
16113 for (i = 0; i < nr_linfo; i++) {
16114 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
16116 if (err == -E2BIG) {
16117 verbose(env, "nonzero tailing record in line_info");
16118 if (copy_to_bpfptr_offset(uattr,
16119 offsetof(union bpf_attr, line_info_rec_size),
16120 &expected_size, sizeof(expected_size)))
16126 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
16132 * Check insn_off to ensure
16133 * 1) strictly increasing AND
16134 * 2) bounded by prog->len
16136 * The linfo[0].insn_off == 0 check logically falls into
16137 * the later "missing bpf_line_info for func..." case
16138 * because the first linfo[0].insn_off must be the
16139 * first sub also and the first sub must have
16140 * subprog_info[0].start == 0.
16142 if ((i && linfo[i].insn_off <= prev_offset) ||
16143 linfo[i].insn_off >= prog->len) {
16144 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
16145 i, linfo[i].insn_off, prev_offset,
16151 if (!prog->insnsi[linfo[i].insn_off].code) {
16153 "Invalid insn code at line_info[%u].insn_off\n",
16159 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
16160 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
16161 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
16166 if (s != env->subprog_cnt) {
16167 if (linfo[i].insn_off == sub[s].start) {
16168 sub[s].linfo_idx = i;
16170 } else if (sub[s].start < linfo[i].insn_off) {
16171 verbose(env, "missing bpf_line_info for func#%u\n", s);
16177 prev_offset = linfo[i].insn_off;
16178 bpfptr_add(&ulinfo, rec_size);
16181 if (s != env->subprog_cnt) {
16182 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
16183 env->subprog_cnt - s, s);
16188 prog->aux->linfo = linfo;
16189 prog->aux->nr_linfo = nr_linfo;
16198 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
16199 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
16201 static int check_core_relo(struct bpf_verifier_env *env,
16202 const union bpf_attr *attr,
16205 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
16206 struct bpf_core_relo core_relo = {};
16207 struct bpf_prog *prog = env->prog;
16208 const struct btf *btf = prog->aux->btf;
16209 struct bpf_core_ctx ctx = {
16213 bpfptr_t u_core_relo;
16216 nr_core_relo = attr->core_relo_cnt;
16219 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
16222 rec_size = attr->core_relo_rec_size;
16223 if (rec_size < MIN_CORE_RELO_SIZE ||
16224 rec_size > MAX_CORE_RELO_SIZE ||
16225 rec_size % sizeof(u32))
16228 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
16229 expected_size = sizeof(struct bpf_core_relo);
16230 ncopy = min_t(u32, expected_size, rec_size);
16232 /* Unlike func_info and line_info, copy and apply each CO-RE
16233 * relocation record one at a time.
16235 for (i = 0; i < nr_core_relo; i++) {
16236 /* future proofing when sizeof(bpf_core_relo) changes */
16237 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
16239 if (err == -E2BIG) {
16240 verbose(env, "nonzero tailing record in core_relo");
16241 if (copy_to_bpfptr_offset(uattr,
16242 offsetof(union bpf_attr, core_relo_rec_size),
16243 &expected_size, sizeof(expected_size)))
16249 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16254 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16255 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16256 i, core_relo.insn_off, prog->len);
16261 err = bpf_core_apply(&ctx, &core_relo, i,
16262 &prog->insnsi[core_relo.insn_off / 8]);
16265 bpfptr_add(&u_core_relo, rec_size);
16270 static int check_btf_info_early(struct bpf_verifier_env *env,
16271 const union bpf_attr *attr,
16277 if (!attr->func_info_cnt && !attr->line_info_cnt) {
16278 if (check_abnormal_return(env))
16283 btf = btf_get_by_fd(attr->prog_btf_fd);
16285 return PTR_ERR(btf);
16286 if (btf_is_kernel(btf)) {
16290 env->prog->aux->btf = btf;
16292 err = check_btf_func_early(env, attr, uattr);
16298 static int check_btf_info(struct bpf_verifier_env *env,
16299 const union bpf_attr *attr,
16304 if (!attr->func_info_cnt && !attr->line_info_cnt) {
16305 if (check_abnormal_return(env))
16310 err = check_btf_func(env, attr, uattr);
16314 err = check_btf_line(env, attr, uattr);
16318 err = check_core_relo(env, attr, uattr);
16325 /* check %cur's range satisfies %old's */
16326 static bool range_within(const struct bpf_reg_state *old,
16327 const struct bpf_reg_state *cur)
16329 return old->umin_value <= cur->umin_value &&
16330 old->umax_value >= cur->umax_value &&
16331 old->smin_value <= cur->smin_value &&
16332 old->smax_value >= cur->smax_value &&
16333 old->u32_min_value <= cur->u32_min_value &&
16334 old->u32_max_value >= cur->u32_max_value &&
16335 old->s32_min_value <= cur->s32_min_value &&
16336 old->s32_max_value >= cur->s32_max_value;
16339 /* If in the old state two registers had the same id, then they need to have
16340 * the same id in the new state as well. But that id could be different from
16341 * the old state, so we need to track the mapping from old to new ids.
16342 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
16343 * regs with old id 5 must also have new id 9 for the new state to be safe. But
16344 * regs with a different old id could still have new id 9, we don't care about
16346 * So we look through our idmap to see if this old id has been seen before. If
16347 * so, we require the new id to match; otherwise, we add the id pair to the map.
16349 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16351 struct bpf_id_pair *map = idmap->map;
16354 /* either both IDs should be set or both should be zero */
16355 if (!!old_id != !!cur_id)
16358 if (old_id == 0) /* cur_id == 0 as well */
16361 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
16363 /* Reached an empty slot; haven't seen this id before */
16364 map[i].old = old_id;
16365 map[i].cur = cur_id;
16368 if (map[i].old == old_id)
16369 return map[i].cur == cur_id;
16370 if (map[i].cur == cur_id)
16373 /* We ran out of idmap slots, which should be impossible */
16378 /* Similar to check_ids(), but allocate a unique temporary ID
16379 * for 'old_id' or 'cur_id' of zero.
16380 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
16382 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16384 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
16385 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
16387 return check_ids(old_id, cur_id, idmap);
16390 static void clean_func_state(struct bpf_verifier_env *env,
16391 struct bpf_func_state *st)
16393 enum bpf_reg_liveness live;
16396 for (i = 0; i < BPF_REG_FP; i++) {
16397 live = st->regs[i].live;
16398 /* liveness must not touch this register anymore */
16399 st->regs[i].live |= REG_LIVE_DONE;
16400 if (!(live & REG_LIVE_READ))
16401 /* since the register is unused, clear its state
16402 * to make further comparison simpler
16404 __mark_reg_not_init(env, &st->regs[i]);
16407 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
16408 live = st->stack[i].spilled_ptr.live;
16409 /* liveness must not touch this stack slot anymore */
16410 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
16411 if (!(live & REG_LIVE_READ)) {
16412 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
16413 for (j = 0; j < BPF_REG_SIZE; j++)
16414 st->stack[i].slot_type[j] = STACK_INVALID;
16419 static void clean_verifier_state(struct bpf_verifier_env *env,
16420 struct bpf_verifier_state *st)
16424 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
16425 /* all regs in this state in all frames were already marked */
16428 for (i = 0; i <= st->curframe; i++)
16429 clean_func_state(env, st->frame[i]);
16432 /* the parentage chains form a tree.
16433 * the verifier states are added to state lists at given insn and
16434 * pushed into state stack for future exploration.
16435 * when the verifier reaches bpf_exit insn some of the verifer states
16436 * stored in the state lists have their final liveness state already,
16437 * but a lot of states will get revised from liveness point of view when
16438 * the verifier explores other branches.
16441 * 2: if r1 == 100 goto pc+1
16444 * when the verifier reaches exit insn the register r0 in the state list of
16445 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
16446 * of insn 2 and goes exploring further. At the insn 4 it will walk the
16447 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
16449 * Since the verifier pushes the branch states as it sees them while exploring
16450 * the program the condition of walking the branch instruction for the second
16451 * time means that all states below this branch were already explored and
16452 * their final liveness marks are already propagated.
16453 * Hence when the verifier completes the search of state list in is_state_visited()
16454 * we can call this clean_live_states() function to mark all liveness states
16455 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16456 * will not be used.
16457 * This function also clears the registers and stack for states that !READ
16458 * to simplify state merging.
16460 * Important note here that walking the same branch instruction in the callee
16461 * doesn't meant that the states are DONE. The verifier has to compare
16464 static void clean_live_states(struct bpf_verifier_env *env, int insn,
16465 struct bpf_verifier_state *cur)
16467 struct bpf_verifier_state_list *sl;
16469 sl = *explored_state(env, insn);
16471 if (sl->state.branches)
16473 if (sl->state.insn_idx != insn ||
16474 !same_callsites(&sl->state, cur))
16476 clean_verifier_state(env, &sl->state);
16482 static bool regs_exact(const struct bpf_reg_state *rold,
16483 const struct bpf_reg_state *rcur,
16484 struct bpf_idmap *idmap)
16486 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16487 check_ids(rold->id, rcur->id, idmap) &&
16488 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16497 /* Returns true if (rold safe implies rcur safe) */
16498 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
16499 struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
16500 enum exact_level exact)
16502 if (exact == EXACT)
16503 return regs_exact(rold, rcur, idmap);
16505 if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT)
16506 /* explored state didn't use this */
16508 if (rold->type == NOT_INIT) {
16509 if (exact == NOT_EXACT || rcur->type == NOT_INIT)
16510 /* explored state can't have used this */
16514 /* Enforce that register types have to match exactly, including their
16515 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16518 * One can make a point that using a pointer register as unbounded
16519 * SCALAR would be technically acceptable, but this could lead to
16520 * pointer leaks because scalars are allowed to leak while pointers
16521 * are not. We could make this safe in special cases if root is
16522 * calling us, but it's probably not worth the hassle.
16524 * Also, register types that are *not* MAYBE_NULL could technically be
16525 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16526 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16527 * to the same map).
16528 * However, if the old MAYBE_NULL register then got NULL checked,
16529 * doing so could have affected others with the same id, and we can't
16530 * check for that because we lost the id when we converted to
16531 * a non-MAYBE_NULL variant.
16532 * So, as a general rule we don't allow mixing MAYBE_NULL and
16533 * non-MAYBE_NULL registers as well.
16535 if (rold->type != rcur->type)
16538 switch (base_type(rold->type)) {
16540 if (env->explore_alu_limits) {
16541 /* explore_alu_limits disables tnum_in() and range_within()
16542 * logic and requires everything to be strict
16544 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16545 check_scalar_ids(rold->id, rcur->id, idmap);
16547 if (!rold->precise && exact == NOT_EXACT)
16549 /* Why check_ids() for scalar registers?
16551 * Consider the following BPF code:
16552 * 1: r6 = ... unbound scalar, ID=a ...
16553 * 2: r7 = ... unbound scalar, ID=b ...
16554 * 3: if (r6 > r7) goto +1
16556 * 5: if (r6 > X) goto ...
16557 * 6: ... memory operation using r7 ...
16559 * First verification path is [1-6]:
16560 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16561 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16562 * r7 <= X, because r6 and r7 share same id.
16563 * Next verification path is [1-4, 6].
16565 * Instruction (6) would be reached in two states:
16566 * I. r6{.id=b}, r7{.id=b} via path 1-6;
16567 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16569 * Use check_ids() to distinguish these states.
16571 * Also verify that new value satisfies old value range knowledge.
16573 return range_within(rold, rcur) &&
16574 tnum_in(rold->var_off, rcur->var_off) &&
16575 check_scalar_ids(rold->id, rcur->id, idmap);
16576 case PTR_TO_MAP_KEY:
16577 case PTR_TO_MAP_VALUE:
16580 case PTR_TO_TP_BUFFER:
16581 /* If the new min/max/var_off satisfy the old ones and
16582 * everything else matches, we are OK.
16584 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16585 range_within(rold, rcur) &&
16586 tnum_in(rold->var_off, rcur->var_off) &&
16587 check_ids(rold->id, rcur->id, idmap) &&
16588 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16589 case PTR_TO_PACKET_META:
16590 case PTR_TO_PACKET:
16591 /* We must have at least as much range as the old ptr
16592 * did, so that any accesses which were safe before are
16593 * still safe. This is true even if old range < old off,
16594 * since someone could have accessed through (ptr - k), or
16595 * even done ptr -= k in a register, to get a safe access.
16597 if (rold->range > rcur->range)
16599 /* If the offsets don't match, we can't trust our alignment;
16600 * nor can we be sure that we won't fall out of range.
16602 if (rold->off != rcur->off)
16604 /* id relations must be preserved */
16605 if (!check_ids(rold->id, rcur->id, idmap))
16607 /* new val must satisfy old val knowledge */
16608 return range_within(rold, rcur) &&
16609 tnum_in(rold->var_off, rcur->var_off);
16611 /* two stack pointers are equal only if they're pointing to
16612 * the same stack frame, since fp-8 in foo != fp-8 in bar
16614 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16618 return regs_exact(rold, rcur, idmap);
16622 static struct bpf_reg_state unbound_reg;
16624 static __init int unbound_reg_init(void)
16626 __mark_reg_unknown_imprecise(&unbound_reg);
16627 unbound_reg.live |= REG_LIVE_READ;
16630 late_initcall(unbound_reg_init);
16632 static bool is_stack_all_misc(struct bpf_verifier_env *env,
16633 struct bpf_stack_state *stack)
16637 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
16638 if ((stack->slot_type[i] == STACK_MISC) ||
16639 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
16647 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
16648 struct bpf_stack_state *stack)
16650 if (is_spilled_scalar_reg64(stack))
16651 return &stack->spilled_ptr;
16653 if (is_stack_all_misc(env, stack))
16654 return &unbound_reg;
16659 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16660 struct bpf_func_state *cur, struct bpf_idmap *idmap,
16661 enum exact_level exact)
16665 /* walk slots of the explored stack and ignore any additional
16666 * slots in the current stack, since explored(safe) state
16669 for (i = 0; i < old->allocated_stack; i++) {
16670 struct bpf_reg_state *old_reg, *cur_reg;
16672 spi = i / BPF_REG_SIZE;
16674 if (exact != NOT_EXACT &&
16675 old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16676 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16679 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)
16680 && exact == NOT_EXACT) {
16681 i += BPF_REG_SIZE - 1;
16682 /* explored state didn't use this */
16686 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16689 if (env->allow_uninit_stack &&
16690 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16693 /* explored stack has more populated slots than current stack
16694 * and these slots were used
16696 if (i >= cur->allocated_stack)
16699 /* 64-bit scalar spill vs all slots MISC and vice versa.
16700 * Load from all slots MISC produces unbound scalar.
16701 * Construct a fake register for such stack and call
16702 * regsafe() to ensure scalar ids are compared.
16704 old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
16705 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
16706 if (old_reg && cur_reg) {
16707 if (!regsafe(env, old_reg, cur_reg, idmap, exact))
16709 i += BPF_REG_SIZE - 1;
16713 /* if old state was safe with misc data in the stack
16714 * it will be safe with zero-initialized stack.
16715 * The opposite is not true
16717 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16718 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16720 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16721 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16722 /* Ex: old explored (safe) state has STACK_SPILL in
16723 * this stack slot, but current has STACK_MISC ->
16724 * this verifier states are not equivalent,
16725 * return false to continue verification of this path
16728 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16730 /* Both old and cur are having same slot_type */
16731 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16733 /* when explored and current stack slot are both storing
16734 * spilled registers, check that stored pointers types
16735 * are the same as well.
16736 * Ex: explored safe path could have stored
16737 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16738 * but current path has stored:
16739 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16740 * such verifier states are not equivalent.
16741 * return false to continue verification of this path
16743 if (!regsafe(env, &old->stack[spi].spilled_ptr,
16744 &cur->stack[spi].spilled_ptr, idmap, exact))
16748 old_reg = &old->stack[spi].spilled_ptr;
16749 cur_reg = &cur->stack[spi].spilled_ptr;
16750 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16751 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16752 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16756 old_reg = &old->stack[spi].spilled_ptr;
16757 cur_reg = &cur->stack[spi].spilled_ptr;
16758 /* iter.depth is not compared between states as it
16759 * doesn't matter for correctness and would otherwise
16760 * prevent convergence; we maintain it only to prevent
16761 * infinite loop check triggering, see
16762 * iter_active_depths_differ()
16764 if (old_reg->iter.btf != cur_reg->iter.btf ||
16765 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16766 old_reg->iter.state != cur_reg->iter.state ||
16767 /* ignore {old_reg,cur_reg}->iter.depth, see above */
16768 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16773 case STACK_INVALID:
16775 /* Ensure that new unhandled slot types return false by default */
16783 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16784 struct bpf_idmap *idmap)
16788 if (old->acquired_refs != cur->acquired_refs)
16791 for (i = 0; i < old->acquired_refs; i++) {
16792 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16799 /* compare two verifier states
16801 * all states stored in state_list are known to be valid, since
16802 * verifier reached 'bpf_exit' instruction through them
16804 * this function is called when verifier exploring different branches of
16805 * execution popped from the state stack. If it sees an old state that has
16806 * more strict register state and more strict stack state then this execution
16807 * branch doesn't need to be explored further, since verifier already
16808 * concluded that more strict state leads to valid finish.
16810 * Therefore two states are equivalent if register state is more conservative
16811 * and explored stack state is more conservative than the current one.
16814 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16815 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16817 * In other words if current stack state (one being explored) has more
16818 * valid slots than old one that already passed validation, it means
16819 * the verifier can stop exploring and conclude that current state is valid too
16821 * Similarly with registers. If explored state has register type as invalid
16822 * whereas register type in current state is meaningful, it means that
16823 * the current state will reach 'bpf_exit' instruction safely
16825 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16826 struct bpf_func_state *cur, enum exact_level exact)
16830 if (old->callback_depth > cur->callback_depth)
16833 for (i = 0; i < MAX_BPF_REG; i++)
16834 if (!regsafe(env, &old->regs[i], &cur->regs[i],
16835 &env->idmap_scratch, exact))
16838 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16841 if (!refsafe(old, cur, &env->idmap_scratch))
16847 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16849 env->idmap_scratch.tmp_id_gen = env->id_gen;
16850 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16853 static bool states_equal(struct bpf_verifier_env *env,
16854 struct bpf_verifier_state *old,
16855 struct bpf_verifier_state *cur,
16856 enum exact_level exact)
16860 if (old->curframe != cur->curframe)
16863 reset_idmap_scratch(env);
16865 /* Verification state from speculative execution simulation
16866 * must never prune a non-speculative execution one.
16868 if (old->speculative && !cur->speculative)
16871 if (old->active_lock.ptr != cur->active_lock.ptr)
16874 /* Old and cur active_lock's have to be either both present
16877 if (!!old->active_lock.id != !!cur->active_lock.id)
16880 if (old->active_lock.id &&
16881 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16884 if (old->active_rcu_lock != cur->active_rcu_lock)
16887 /* for states to be equal callsites have to be the same
16888 * and all frame states need to be equivalent
16890 for (i = 0; i <= old->curframe; i++) {
16891 if (old->frame[i]->callsite != cur->frame[i]->callsite)
16893 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16899 /* Return 0 if no propagation happened. Return negative error code if error
16900 * happened. Otherwise, return the propagated bit.
16902 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16903 struct bpf_reg_state *reg,
16904 struct bpf_reg_state *parent_reg)
16906 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16907 u8 flag = reg->live & REG_LIVE_READ;
16910 /* When comes here, read flags of PARENT_REG or REG could be any of
16911 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16912 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16914 if (parent_flag == REG_LIVE_READ64 ||
16915 /* Or if there is no read flag from REG. */
16917 /* Or if the read flag from REG is the same as PARENT_REG. */
16918 parent_flag == flag)
16921 err = mark_reg_read(env, reg, parent_reg, flag);
16928 /* A write screens off any subsequent reads; but write marks come from the
16929 * straight-line code between a state and its parent. When we arrive at an
16930 * equivalent state (jump target or such) we didn't arrive by the straight-line
16931 * code, so read marks in the state must propagate to the parent regardless
16932 * of the state's write marks. That's what 'parent == state->parent' comparison
16933 * in mark_reg_read() is for.
16935 static int propagate_liveness(struct bpf_verifier_env *env,
16936 const struct bpf_verifier_state *vstate,
16937 struct bpf_verifier_state *vparent)
16939 struct bpf_reg_state *state_reg, *parent_reg;
16940 struct bpf_func_state *state, *parent;
16941 int i, frame, err = 0;
16943 if (vparent->curframe != vstate->curframe) {
16944 WARN(1, "propagate_live: parent frame %d current frame %d\n",
16945 vparent->curframe, vstate->curframe);
16948 /* Propagate read liveness of registers... */
16949 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16950 for (frame = 0; frame <= vstate->curframe; frame++) {
16951 parent = vparent->frame[frame];
16952 state = vstate->frame[frame];
16953 parent_reg = parent->regs;
16954 state_reg = state->regs;
16955 /* We don't need to worry about FP liveness, it's read-only */
16956 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16957 err = propagate_liveness_reg(env, &state_reg[i],
16961 if (err == REG_LIVE_READ64)
16962 mark_insn_zext(env, &parent_reg[i]);
16965 /* Propagate stack slots. */
16966 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16967 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16968 parent_reg = &parent->stack[i].spilled_ptr;
16969 state_reg = &state->stack[i].spilled_ptr;
16970 err = propagate_liveness_reg(env, state_reg,
16979 /* find precise scalars in the previous equivalent state and
16980 * propagate them into the current state
16982 static int propagate_precision(struct bpf_verifier_env *env,
16983 const struct bpf_verifier_state *old)
16985 struct bpf_reg_state *state_reg;
16986 struct bpf_func_state *state;
16987 int i, err = 0, fr;
16990 for (fr = old->curframe; fr >= 0; fr--) {
16991 state = old->frame[fr];
16992 state_reg = state->regs;
16994 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16995 if (state_reg->type != SCALAR_VALUE ||
16996 !state_reg->precise ||
16997 !(state_reg->live & REG_LIVE_READ))
16999 if (env->log.level & BPF_LOG_LEVEL2) {
17001 verbose(env, "frame %d: propagating r%d", fr, i);
17003 verbose(env, ",r%d", i);
17005 bt_set_frame_reg(&env->bt, fr, i);
17009 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17010 if (!is_spilled_reg(&state->stack[i]))
17012 state_reg = &state->stack[i].spilled_ptr;
17013 if (state_reg->type != SCALAR_VALUE ||
17014 !state_reg->precise ||
17015 !(state_reg->live & REG_LIVE_READ))
17017 if (env->log.level & BPF_LOG_LEVEL2) {
17019 verbose(env, "frame %d: propagating fp%d",
17020 fr, (-i - 1) * BPF_REG_SIZE);
17022 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
17024 bt_set_frame_slot(&env->bt, fr, i);
17028 verbose(env, "\n");
17031 err = mark_chain_precision_batch(env);
17038 static bool states_maybe_looping(struct bpf_verifier_state *old,
17039 struct bpf_verifier_state *cur)
17041 struct bpf_func_state *fold, *fcur;
17042 int i, fr = cur->curframe;
17044 if (old->curframe != fr)
17047 fold = old->frame[fr];
17048 fcur = cur->frame[fr];
17049 for (i = 0; i < MAX_BPF_REG; i++)
17050 if (memcmp(&fold->regs[i], &fcur->regs[i],
17051 offsetof(struct bpf_reg_state, parent)))
17056 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
17058 return env->insn_aux_data[insn_idx].is_iter_next;
17061 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
17062 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
17063 * states to match, which otherwise would look like an infinite loop. So while
17064 * iter_next() calls are taken care of, we still need to be careful and
17065 * prevent erroneous and too eager declaration of "ininite loop", when
17066 * iterators are involved.
17068 * Here's a situation in pseudo-BPF assembly form:
17070 * 0: again: ; set up iter_next() call args
17071 * 1: r1 = &it ; <CHECKPOINT HERE>
17072 * 2: call bpf_iter_num_next ; this is iter_next() call
17073 * 3: if r0 == 0 goto done
17074 * 4: ... something useful here ...
17075 * 5: goto again ; another iteration
17078 * 8: call bpf_iter_num_destroy ; clean up iter state
17081 * This is a typical loop. Let's assume that we have a prune point at 1:,
17082 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
17083 * again`, assuming other heuristics don't get in a way).
17085 * When we first time come to 1:, let's say we have some state X. We proceed
17086 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
17087 * Now we come back to validate that forked ACTIVE state. We proceed through
17088 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
17089 * are converging. But the problem is that we don't know that yet, as this
17090 * convergence has to happen at iter_next() call site only. So if nothing is
17091 * done, at 1: verifier will use bounded loop logic and declare infinite
17092 * looping (and would be *technically* correct, if not for iterator's
17093 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
17094 * don't want that. So what we do in process_iter_next_call() when we go on
17095 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
17096 * a different iteration. So when we suspect an infinite loop, we additionally
17097 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
17098 * pretend we are not looping and wait for next iter_next() call.
17100 * This only applies to ACTIVE state. In DRAINED state we don't expect to
17101 * loop, because that would actually mean infinite loop, as DRAINED state is
17102 * "sticky", and so we'll keep returning into the same instruction with the
17103 * same state (at least in one of possible code paths).
17105 * This approach allows to keep infinite loop heuristic even in the face of
17106 * active iterator. E.g., C snippet below is and will be detected as
17107 * inifintely looping:
17109 * struct bpf_iter_num it;
17112 * bpf_iter_num_new(&it, 0, 10);
17113 * while ((p = bpf_iter_num_next(&t))) {
17115 * while (x--) {} // <<-- infinite loop here
17119 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
17121 struct bpf_reg_state *slot, *cur_slot;
17122 struct bpf_func_state *state;
17125 for (fr = old->curframe; fr >= 0; fr--) {
17126 state = old->frame[fr];
17127 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17128 if (state->stack[i].slot_type[0] != STACK_ITER)
17131 slot = &state->stack[i].spilled_ptr;
17132 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
17135 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
17136 if (cur_slot->iter.depth != slot->iter.depth)
17143 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
17145 struct bpf_verifier_state_list *new_sl;
17146 struct bpf_verifier_state_list *sl, **pprev;
17147 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
17148 int i, j, n, err, states_cnt = 0;
17149 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
17150 bool add_new_state = force_new_state;
17153 /* bpf progs typically have pruning point every 4 instructions
17154 * http://vger.kernel.org/bpfconf2019.html#session-1
17155 * Do not add new state for future pruning if the verifier hasn't seen
17156 * at least 2 jumps and at least 8 instructions.
17157 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
17158 * In tests that amounts to up to 50% reduction into total verifier
17159 * memory consumption and 20% verifier time speedup.
17161 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
17162 env->insn_processed - env->prev_insn_processed >= 8)
17163 add_new_state = true;
17165 pprev = explored_state(env, insn_idx);
17168 clean_live_states(env, insn_idx, cur);
17172 if (sl->state.insn_idx != insn_idx)
17175 if (sl->state.branches) {
17176 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
17178 if (frame->in_async_callback_fn &&
17179 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
17180 /* Different async_entry_cnt means that the verifier is
17181 * processing another entry into async callback.
17182 * Seeing the same state is not an indication of infinite
17183 * loop or infinite recursion.
17184 * But finding the same state doesn't mean that it's safe
17185 * to stop processing the current state. The previous state
17186 * hasn't yet reached bpf_exit, since state.branches > 0.
17187 * Checking in_async_callback_fn alone is not enough either.
17188 * Since the verifier still needs to catch infinite loops
17189 * inside async callbacks.
17191 goto skip_inf_loop_check;
17193 /* BPF open-coded iterators loop detection is special.
17194 * states_maybe_looping() logic is too simplistic in detecting
17195 * states that *might* be equivalent, because it doesn't know
17196 * about ID remapping, so don't even perform it.
17197 * See process_iter_next_call() and iter_active_depths_differ()
17198 * for overview of the logic. When current and one of parent
17199 * states are detected as equivalent, it's a good thing: we prove
17200 * convergence and can stop simulating further iterations.
17201 * It's safe to assume that iterator loop will finish, taking into
17202 * account iter_next() contract of eventually returning
17203 * sticky NULL result.
17205 * Note, that states have to be compared exactly in this case because
17206 * read and precision marks might not be finalized inside the loop.
17207 * E.g. as in the program below:
17210 * 2. r6 = bpf_get_prandom_u32()
17211 * 3. while (bpf_iter_num_next(&fp[-8])) {
17212 * 4. if (r6 != 42) {
17214 * 6. r6 = bpf_get_prandom_u32()
17219 * 11. r8 = *(u64 *)(r0 + 0)
17220 * 12. r6 = bpf_get_prandom_u32()
17223 * Here verifier would first visit path 1-3, create a checkpoint at 3
17224 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
17225 * not have read or precision mark for r7 yet, thus inexact states
17226 * comparison would discard current state with r7=-32
17227 * => unsafe memory access at 11 would not be caught.
17229 if (is_iter_next_insn(env, insn_idx)) {
17230 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
17231 struct bpf_func_state *cur_frame;
17232 struct bpf_reg_state *iter_state, *iter_reg;
17235 cur_frame = cur->frame[cur->curframe];
17236 /* btf_check_iter_kfuncs() enforces that
17237 * iter state pointer is always the first arg
17239 iter_reg = &cur_frame->regs[BPF_REG_1];
17240 /* current state is valid due to states_equal(),
17241 * so we can assume valid iter and reg state,
17242 * no need for extra (re-)validations
17244 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
17245 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
17246 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
17247 update_loop_entry(cur, &sl->state);
17251 goto skip_inf_loop_check;
17253 if (is_may_goto_insn_at(env, insn_idx)) {
17254 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
17255 update_loop_entry(cur, &sl->state);
17258 goto skip_inf_loop_check;
17260 if (calls_callback(env, insn_idx)) {
17261 if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
17263 goto skip_inf_loop_check;
17265 /* attempt to detect infinite loop to avoid unnecessary doomed work */
17266 if (states_maybe_looping(&sl->state, cur) &&
17267 states_equal(env, &sl->state, cur, EXACT) &&
17268 !iter_active_depths_differ(&sl->state, cur) &&
17269 sl->state.may_goto_depth == cur->may_goto_depth &&
17270 sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
17271 verbose_linfo(env, insn_idx, "; ");
17272 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
17273 verbose(env, "cur state:");
17274 print_verifier_state(env, cur->frame[cur->curframe], true);
17275 verbose(env, "old state:");
17276 print_verifier_state(env, sl->state.frame[cur->curframe], true);
17279 /* if the verifier is processing a loop, avoid adding new state
17280 * too often, since different loop iterations have distinct
17281 * states and may not help future pruning.
17282 * This threshold shouldn't be too low to make sure that
17283 * a loop with large bound will be rejected quickly.
17284 * The most abusive loop will be:
17286 * if r1 < 1000000 goto pc-2
17287 * 1M insn_procssed limit / 100 == 10k peak states.
17288 * This threshold shouldn't be too high either, since states
17289 * at the end of the loop are likely to be useful in pruning.
17291 skip_inf_loop_check:
17292 if (!force_new_state &&
17293 env->jmps_processed - env->prev_jmps_processed < 20 &&
17294 env->insn_processed - env->prev_insn_processed < 100)
17295 add_new_state = false;
17298 /* If sl->state is a part of a loop and this loop's entry is a part of
17299 * current verification path then states have to be compared exactly.
17300 * 'force_exact' is needed to catch the following case:
17302 * initial Here state 'succ' was processed first,
17303 * | it was eventually tracked to produce a
17304 * V state identical to 'hdr'.
17305 * .---------> hdr All branches from 'succ' had been explored
17306 * | | and thus 'succ' has its .branches == 0.
17308 * | .------... Suppose states 'cur' and 'succ' correspond
17309 * | | | to the same instruction + callsites.
17310 * | V V In such case it is necessary to check
17311 * | ... ... if 'succ' and 'cur' are states_equal().
17312 * | | | If 'succ' and 'cur' are a part of the
17313 * | V V same loop exact flag has to be set.
17314 * | succ <- cur To check if that is the case, verify
17315 * | | if loop entry of 'succ' is in current
17321 * Additional details are in the comment before get_loop_entry().
17323 loop_entry = get_loop_entry(&sl->state);
17324 force_exact = loop_entry && loop_entry->branches > 0;
17325 if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) {
17327 update_loop_entry(cur, loop_entry);
17330 /* reached equivalent register/stack state,
17331 * prune the search.
17332 * Registers read by the continuation are read by us.
17333 * If we have any write marks in env->cur_state, they
17334 * will prevent corresponding reads in the continuation
17335 * from reaching our parent (an explored_state). Our
17336 * own state will get the read marks recorded, but
17337 * they'll be immediately forgotten as we're pruning
17338 * this state and will pop a new one.
17340 err = propagate_liveness(env, &sl->state, cur);
17342 /* if previous state reached the exit with precision and
17343 * current state is equivalent to it (except precsion marks)
17344 * the precision needs to be propagated back in
17345 * the current state.
17347 if (is_jmp_point(env, env->insn_idx))
17348 err = err ? : push_jmp_history(env, cur, 0);
17349 err = err ? : propagate_precision(env, &sl->state);
17355 /* when new state is not going to be added do not increase miss count.
17356 * Otherwise several loop iterations will remove the state
17357 * recorded earlier. The goal of these heuristics is to have
17358 * states from some iterations of the loop (some in the beginning
17359 * and some at the end) to help pruning.
17363 /* heuristic to determine whether this state is beneficial
17364 * to keep checking from state equivalence point of view.
17365 * Higher numbers increase max_states_per_insn and verification time,
17366 * but do not meaningfully decrease insn_processed.
17367 * 'n' controls how many times state could miss before eviction.
17368 * Use bigger 'n' for checkpoints because evicting checkpoint states
17369 * too early would hinder iterator convergence.
17371 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
17372 if (sl->miss_cnt > sl->hit_cnt * n + n) {
17373 /* the state is unlikely to be useful. Remove it to
17374 * speed up verification
17377 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
17378 !sl->state.used_as_loop_entry) {
17379 u32 br = sl->state.branches;
17382 "BUG live_done but branches_to_explore %d\n",
17384 free_verifier_state(&sl->state, false);
17386 env->peak_states--;
17388 /* cannot free this state, since parentage chain may
17389 * walk it later. Add it for free_list instead to
17390 * be freed at the end of verification
17392 sl->next = env->free_list;
17393 env->free_list = sl;
17403 if (env->max_states_per_insn < states_cnt)
17404 env->max_states_per_insn = states_cnt;
17406 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
17409 if (!add_new_state)
17412 /* There were no equivalent states, remember the current one.
17413 * Technically the current state is not proven to be safe yet,
17414 * but it will either reach outer most bpf_exit (which means it's safe)
17415 * or it will be rejected. When there are no loops the verifier won't be
17416 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
17417 * again on the way to bpf_exit.
17418 * When looping the sl->state.branches will be > 0 and this state
17419 * will not be considered for equivalence until branches == 0.
17421 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
17424 env->total_states++;
17425 env->peak_states++;
17426 env->prev_jmps_processed = env->jmps_processed;
17427 env->prev_insn_processed = env->insn_processed;
17429 /* forget precise markings we inherited, see __mark_chain_precision */
17430 if (env->bpf_capable)
17431 mark_all_scalars_imprecise(env, cur);
17433 /* add new state to the head of linked list */
17434 new = &new_sl->state;
17435 err = copy_verifier_state(new, cur);
17437 free_verifier_state(new, false);
17441 new->insn_idx = insn_idx;
17442 WARN_ONCE(new->branches != 1,
17443 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
17446 cur->first_insn_idx = insn_idx;
17447 cur->dfs_depth = new->dfs_depth + 1;
17448 clear_jmp_history(cur);
17449 new_sl->next = *explored_state(env, insn_idx);
17450 *explored_state(env, insn_idx) = new_sl;
17451 /* connect new state to parentage chain. Current frame needs all
17452 * registers connected. Only r6 - r9 of the callers are alive (pushed
17453 * to the stack implicitly by JITs) so in callers' frames connect just
17454 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
17455 * the state of the call instruction (with WRITTEN set), and r0 comes
17456 * from callee with its full parentage chain, anyway.
17458 /* clear write marks in current state: the writes we did are not writes
17459 * our child did, so they don't screen off its reads from us.
17460 * (There are no read marks in current state, because reads always mark
17461 * their parent and current state never has children yet. Only
17462 * explored_states can get read marks.)
17464 for (j = 0; j <= cur->curframe; j++) {
17465 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
17466 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
17467 for (i = 0; i < BPF_REG_FP; i++)
17468 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
17471 /* all stack frames are accessible from callee, clear them all */
17472 for (j = 0; j <= cur->curframe; j++) {
17473 struct bpf_func_state *frame = cur->frame[j];
17474 struct bpf_func_state *newframe = new->frame[j];
17476 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
17477 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
17478 frame->stack[i].spilled_ptr.parent =
17479 &newframe->stack[i].spilled_ptr;
17485 /* Return true if it's OK to have the same insn return a different type. */
17486 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17488 switch (base_type(type)) {
17490 case PTR_TO_SOCKET:
17491 case PTR_TO_SOCK_COMMON:
17492 case PTR_TO_TCP_SOCK:
17493 case PTR_TO_XDP_SOCK:
17494 case PTR_TO_BTF_ID:
17502 /* If an instruction was previously used with particular pointer types, then we
17503 * need to be careful to avoid cases such as the below, where it may be ok
17504 * for one branch accessing the pointer, but not ok for the other branch:
17509 * R1 = some_other_valid_ptr;
17512 * R2 = *(u32 *)(R1 + 0);
17514 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17516 return src != prev && (!reg_type_mismatch_ok(src) ||
17517 !reg_type_mismatch_ok(prev));
17520 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17521 bool allow_trust_missmatch)
17523 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17525 if (*prev_type == NOT_INIT) {
17526 /* Saw a valid insn
17527 * dst_reg = *(u32 *)(src_reg + off)
17528 * save type to validate intersecting paths
17531 } else if (reg_type_mismatch(type, *prev_type)) {
17532 /* Abuser program is trying to use the same insn
17533 * dst_reg = *(u32*) (src_reg + off)
17534 * with different pointer types:
17535 * src_reg == ctx in one branch and
17536 * src_reg == stack|map in some other branch.
17539 if (allow_trust_missmatch &&
17540 base_type(type) == PTR_TO_BTF_ID &&
17541 base_type(*prev_type) == PTR_TO_BTF_ID) {
17543 * Have to support a use case when one path through
17544 * the program yields TRUSTED pointer while another
17545 * is UNTRUSTED. Fallback to UNTRUSTED to generate
17546 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17548 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17550 verbose(env, "same insn cannot be used with different pointers\n");
17558 static int do_check(struct bpf_verifier_env *env)
17560 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17561 struct bpf_verifier_state *state = env->cur_state;
17562 struct bpf_insn *insns = env->prog->insnsi;
17563 struct bpf_reg_state *regs;
17564 int insn_cnt = env->prog->len;
17565 bool do_print_state = false;
17566 int prev_insn_idx = -1;
17569 bool exception_exit = false;
17570 struct bpf_insn *insn;
17574 /* reset current history entry on each new instruction */
17575 env->cur_hist_ent = NULL;
17577 env->prev_insn_idx = prev_insn_idx;
17578 if (env->insn_idx >= insn_cnt) {
17579 verbose(env, "invalid insn idx %d insn_cnt %d\n",
17580 env->insn_idx, insn_cnt);
17584 insn = &insns[env->insn_idx];
17585 class = BPF_CLASS(insn->code);
17587 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17589 "BPF program is too large. Processed %d insn\n",
17590 env->insn_processed);
17594 state->last_insn_idx = env->prev_insn_idx;
17596 if (is_prune_point(env, env->insn_idx)) {
17597 err = is_state_visited(env, env->insn_idx);
17601 /* found equivalent state, can prune the search */
17602 if (env->log.level & BPF_LOG_LEVEL) {
17603 if (do_print_state)
17604 verbose(env, "\nfrom %d to %d%s: safe\n",
17605 env->prev_insn_idx, env->insn_idx,
17606 env->cur_state->speculative ?
17607 " (speculative execution)" : "");
17609 verbose(env, "%d: safe\n", env->insn_idx);
17611 goto process_bpf_exit;
17615 if (is_jmp_point(env, env->insn_idx)) {
17616 err = push_jmp_history(env, state, 0);
17621 if (signal_pending(current))
17624 if (need_resched())
17627 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17628 verbose(env, "\nfrom %d to %d%s:",
17629 env->prev_insn_idx, env->insn_idx,
17630 env->cur_state->speculative ?
17631 " (speculative execution)" : "");
17632 print_verifier_state(env, state->frame[state->curframe], true);
17633 do_print_state = false;
17636 if (env->log.level & BPF_LOG_LEVEL) {
17637 const struct bpf_insn_cbs cbs = {
17638 .cb_call = disasm_kfunc_name,
17639 .cb_print = verbose,
17640 .private_data = env,
17643 if (verifier_state_scratched(env))
17644 print_insn_state(env, state->frame[state->curframe]);
17646 verbose_linfo(env, env->insn_idx, "; ");
17647 env->prev_log_pos = env->log.end_pos;
17648 verbose(env, "%d: ", env->insn_idx);
17649 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17650 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17651 env->prev_log_pos = env->log.end_pos;
17654 if (bpf_prog_is_offloaded(env->prog->aux)) {
17655 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17656 env->prev_insn_idx);
17661 regs = cur_regs(env);
17662 sanitize_mark_insn_seen(env);
17663 prev_insn_idx = env->insn_idx;
17665 if (class == BPF_ALU || class == BPF_ALU64) {
17666 err = check_alu_op(env, insn);
17670 } else if (class == BPF_LDX) {
17671 enum bpf_reg_type src_reg_type;
17673 /* check for reserved fields is already done */
17675 /* check src operand */
17676 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17680 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17684 src_reg_type = regs[insn->src_reg].type;
17686 /* check that memory (src_reg + off) is readable,
17687 * the state of dst_reg will be updated by this func
17689 err = check_mem_access(env, env->insn_idx, insn->src_reg,
17690 insn->off, BPF_SIZE(insn->code),
17691 BPF_READ, insn->dst_reg, false,
17692 BPF_MODE(insn->code) == BPF_MEMSX);
17693 err = err ?: save_aux_ptr_type(env, src_reg_type, true);
17694 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx");
17697 } else if (class == BPF_STX) {
17698 enum bpf_reg_type dst_reg_type;
17700 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17701 err = check_atomic(env, env->insn_idx, insn);
17708 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17709 verbose(env, "BPF_STX uses reserved fields\n");
17713 /* check src1 operand */
17714 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17717 /* check src2 operand */
17718 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17722 dst_reg_type = regs[insn->dst_reg].type;
17724 /* check that memory (dst_reg + off) is writeable */
17725 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17726 insn->off, BPF_SIZE(insn->code),
17727 BPF_WRITE, insn->src_reg, false, false);
17731 err = save_aux_ptr_type(env, dst_reg_type, false);
17734 } else if (class == BPF_ST) {
17735 enum bpf_reg_type dst_reg_type;
17737 if (BPF_MODE(insn->code) != BPF_MEM ||
17738 insn->src_reg != BPF_REG_0) {
17739 verbose(env, "BPF_ST uses reserved fields\n");
17742 /* check src operand */
17743 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17747 dst_reg_type = regs[insn->dst_reg].type;
17749 /* check that memory (dst_reg + off) is writeable */
17750 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17751 insn->off, BPF_SIZE(insn->code),
17752 BPF_WRITE, -1, false, false);
17756 err = save_aux_ptr_type(env, dst_reg_type, false);
17759 } else if (class == BPF_JMP || class == BPF_JMP32) {
17760 u8 opcode = BPF_OP(insn->code);
17762 env->jmps_processed++;
17763 if (opcode == BPF_CALL) {
17764 if (BPF_SRC(insn->code) != BPF_K ||
17765 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17766 && insn->off != 0) ||
17767 (insn->src_reg != BPF_REG_0 &&
17768 insn->src_reg != BPF_PSEUDO_CALL &&
17769 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17770 insn->dst_reg != BPF_REG_0 ||
17771 class == BPF_JMP32) {
17772 verbose(env, "BPF_CALL uses reserved fields\n");
17776 if (env->cur_state->active_lock.ptr) {
17777 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17778 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17779 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17780 verbose(env, "function calls are not allowed while holding a lock\n");
17784 if (insn->src_reg == BPF_PSEUDO_CALL) {
17785 err = check_func_call(env, insn, &env->insn_idx);
17786 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17787 err = check_kfunc_call(env, insn, &env->insn_idx);
17788 if (!err && is_bpf_throw_kfunc(insn)) {
17789 exception_exit = true;
17790 goto process_bpf_exit_full;
17793 err = check_helper_call(env, insn, &env->insn_idx);
17798 mark_reg_scratched(env, BPF_REG_0);
17799 } else if (opcode == BPF_JA) {
17800 if (BPF_SRC(insn->code) != BPF_K ||
17801 insn->src_reg != BPF_REG_0 ||
17802 insn->dst_reg != BPF_REG_0 ||
17803 (class == BPF_JMP && insn->imm != 0) ||
17804 (class == BPF_JMP32 && insn->off != 0)) {
17805 verbose(env, "BPF_JA uses reserved fields\n");
17809 if (class == BPF_JMP)
17810 env->insn_idx += insn->off + 1;
17812 env->insn_idx += insn->imm + 1;
17815 } else if (opcode == BPF_EXIT) {
17816 if (BPF_SRC(insn->code) != BPF_K ||
17818 insn->src_reg != BPF_REG_0 ||
17819 insn->dst_reg != BPF_REG_0 ||
17820 class == BPF_JMP32) {
17821 verbose(env, "BPF_EXIT uses reserved fields\n");
17824 process_bpf_exit_full:
17825 if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) {
17826 verbose(env, "bpf_spin_unlock is missing\n");
17830 if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) {
17831 verbose(env, "bpf_rcu_read_unlock is missing\n");
17835 /* We must do check_reference_leak here before
17836 * prepare_func_exit to handle the case when
17837 * state->curframe > 0, it may be a callback
17838 * function, for which reference_state must
17839 * match caller reference state when it exits.
17841 err = check_reference_leak(env, exception_exit);
17845 /* The side effect of the prepare_func_exit
17846 * which is being skipped is that it frees
17847 * bpf_func_state. Typically, process_bpf_exit
17848 * will only be hit with outermost exit.
17849 * copy_verifier_state in pop_stack will handle
17850 * freeing of any extra bpf_func_state left over
17851 * from not processing all nested function
17852 * exits. We also skip return code checks as
17853 * they are not needed for exceptional exits.
17855 if (exception_exit)
17856 goto process_bpf_exit;
17858 if (state->curframe) {
17859 /* exit from nested function */
17860 err = prepare_func_exit(env, &env->insn_idx);
17863 do_print_state = true;
17867 err = check_return_code(env, BPF_REG_0, "R0");
17871 mark_verifier_state_scratched(env);
17872 update_branch_counts(env, env->cur_state);
17873 err = pop_stack(env, &prev_insn_idx,
17874 &env->insn_idx, pop_log);
17876 if (err != -ENOENT)
17880 do_print_state = true;
17884 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17888 } else if (class == BPF_LD) {
17889 u8 mode = BPF_MODE(insn->code);
17891 if (mode == BPF_ABS || mode == BPF_IND) {
17892 err = check_ld_abs(env, insn);
17896 } else if (mode == BPF_IMM) {
17897 err = check_ld_imm(env, insn);
17902 sanitize_mark_insn_seen(env);
17904 verbose(env, "invalid BPF_LD mode\n");
17908 verbose(env, "unknown insn class %d\n", class);
17918 static int find_btf_percpu_datasec(struct btf *btf)
17920 const struct btf_type *t;
17925 * Both vmlinux and module each have their own ".data..percpu"
17926 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17927 * types to look at only module's own BTF types.
17929 n = btf_nr_types(btf);
17930 if (btf_is_module(btf))
17931 i = btf_nr_types(btf_vmlinux);
17935 for(; i < n; i++) {
17936 t = btf_type_by_id(btf, i);
17937 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17940 tname = btf_name_by_offset(btf, t->name_off);
17941 if (!strcmp(tname, ".data..percpu"))
17948 /* replace pseudo btf_id with kernel symbol address */
17949 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17950 struct bpf_insn *insn,
17951 struct bpf_insn_aux_data *aux)
17953 const struct btf_var_secinfo *vsi;
17954 const struct btf_type *datasec;
17955 struct btf_mod_pair *btf_mod;
17956 const struct btf_type *t;
17957 const char *sym_name;
17958 bool percpu = false;
17959 u32 type, id = insn->imm;
17963 int i, btf_fd, err;
17965 btf_fd = insn[1].imm;
17967 btf = btf_get_by_fd(btf_fd);
17969 verbose(env, "invalid module BTF object FD specified.\n");
17973 if (!btf_vmlinux) {
17974 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17981 t = btf_type_by_id(btf, id);
17983 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17988 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17989 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17994 sym_name = btf_name_by_offset(btf, t->name_off);
17995 addr = kallsyms_lookup_name(sym_name);
17997 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
18002 insn[0].imm = (u32)addr;
18003 insn[1].imm = addr >> 32;
18005 if (btf_type_is_func(t)) {
18006 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18007 aux->btf_var.mem_size = 0;
18011 datasec_id = find_btf_percpu_datasec(btf);
18012 if (datasec_id > 0) {
18013 datasec = btf_type_by_id(btf, datasec_id);
18014 for_each_vsi(i, datasec, vsi) {
18015 if (vsi->type == id) {
18023 t = btf_type_skip_modifiers(btf, type, NULL);
18025 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
18026 aux->btf_var.btf = btf;
18027 aux->btf_var.btf_id = type;
18028 } else if (!btf_type_is_struct(t)) {
18029 const struct btf_type *ret;
18033 /* resolve the type size of ksym. */
18034 ret = btf_resolve_size(btf, t, &tsize);
18036 tname = btf_name_by_offset(btf, t->name_off);
18037 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
18038 tname, PTR_ERR(ret));
18042 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18043 aux->btf_var.mem_size = tsize;
18045 aux->btf_var.reg_type = PTR_TO_BTF_ID;
18046 aux->btf_var.btf = btf;
18047 aux->btf_var.btf_id = type;
18050 /* check whether we recorded this BTF (and maybe module) already */
18051 for (i = 0; i < env->used_btf_cnt; i++) {
18052 if (env->used_btfs[i].btf == btf) {
18058 if (env->used_btf_cnt >= MAX_USED_BTFS) {
18063 btf_mod = &env->used_btfs[env->used_btf_cnt];
18064 btf_mod->btf = btf;
18065 btf_mod->module = NULL;
18067 /* if we reference variables from kernel module, bump its refcount */
18068 if (btf_is_module(btf)) {
18069 btf_mod->module = btf_try_get_module(btf);
18070 if (!btf_mod->module) {
18076 env->used_btf_cnt++;
18084 static bool is_tracing_prog_type(enum bpf_prog_type type)
18087 case BPF_PROG_TYPE_KPROBE:
18088 case BPF_PROG_TYPE_TRACEPOINT:
18089 case BPF_PROG_TYPE_PERF_EVENT:
18090 case BPF_PROG_TYPE_RAW_TRACEPOINT:
18091 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
18098 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
18099 struct bpf_map *map,
18100 struct bpf_prog *prog)
18103 enum bpf_prog_type prog_type = resolve_prog_type(prog);
18105 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
18106 btf_record_has_field(map->record, BPF_RB_ROOT)) {
18107 if (is_tracing_prog_type(prog_type)) {
18108 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
18113 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
18114 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
18115 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
18119 if (is_tracing_prog_type(prog_type)) {
18120 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
18125 if (btf_record_has_field(map->record, BPF_TIMER)) {
18126 if (is_tracing_prog_type(prog_type)) {
18127 verbose(env, "tracing progs cannot use bpf_timer yet\n");
18132 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
18133 !bpf_offload_prog_map_match(prog, map)) {
18134 verbose(env, "offload device mismatch between prog and map\n");
18138 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
18139 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
18143 if (prog->sleepable)
18144 switch (map->map_type) {
18145 case BPF_MAP_TYPE_HASH:
18146 case BPF_MAP_TYPE_LRU_HASH:
18147 case BPF_MAP_TYPE_ARRAY:
18148 case BPF_MAP_TYPE_PERCPU_HASH:
18149 case BPF_MAP_TYPE_PERCPU_ARRAY:
18150 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
18151 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
18152 case BPF_MAP_TYPE_HASH_OF_MAPS:
18153 case BPF_MAP_TYPE_RINGBUF:
18154 case BPF_MAP_TYPE_USER_RINGBUF:
18155 case BPF_MAP_TYPE_INODE_STORAGE:
18156 case BPF_MAP_TYPE_SK_STORAGE:
18157 case BPF_MAP_TYPE_TASK_STORAGE:
18158 case BPF_MAP_TYPE_CGRP_STORAGE:
18159 case BPF_MAP_TYPE_QUEUE:
18160 case BPF_MAP_TYPE_STACK:
18161 case BPF_MAP_TYPE_ARENA:
18165 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
18172 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
18174 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
18175 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
18178 /* find and rewrite pseudo imm in ld_imm64 instructions:
18180 * 1. if it accesses map FD, replace it with actual map pointer.
18181 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
18183 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
18185 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
18187 struct bpf_insn *insn = env->prog->insnsi;
18188 int insn_cnt = env->prog->len;
18191 err = bpf_prog_calc_tag(env->prog);
18195 for (i = 0; i < insn_cnt; i++, insn++) {
18196 if (BPF_CLASS(insn->code) == BPF_LDX &&
18197 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
18199 verbose(env, "BPF_LDX uses reserved fields\n");
18203 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
18204 struct bpf_insn_aux_data *aux;
18205 struct bpf_map *map;
18210 if (i == insn_cnt - 1 || insn[1].code != 0 ||
18211 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
18212 insn[1].off != 0) {
18213 verbose(env, "invalid bpf_ld_imm64 insn\n");
18217 if (insn[0].src_reg == 0)
18218 /* valid generic load 64-bit imm */
18221 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
18222 aux = &env->insn_aux_data[i];
18223 err = check_pseudo_btf_id(env, insn, aux);
18229 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
18230 aux = &env->insn_aux_data[i];
18231 aux->ptr_type = PTR_TO_FUNC;
18235 /* In final convert_pseudo_ld_imm64() step, this is
18236 * converted into regular 64-bit imm load insn.
18238 switch (insn[0].src_reg) {
18239 case BPF_PSEUDO_MAP_VALUE:
18240 case BPF_PSEUDO_MAP_IDX_VALUE:
18242 case BPF_PSEUDO_MAP_FD:
18243 case BPF_PSEUDO_MAP_IDX:
18244 if (insn[1].imm == 0)
18248 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
18252 switch (insn[0].src_reg) {
18253 case BPF_PSEUDO_MAP_IDX_VALUE:
18254 case BPF_PSEUDO_MAP_IDX:
18255 if (bpfptr_is_null(env->fd_array)) {
18256 verbose(env, "fd_idx without fd_array is invalid\n");
18259 if (copy_from_bpfptr_offset(&fd, env->fd_array,
18260 insn[0].imm * sizeof(fd),
18270 map = __bpf_map_get(f);
18272 verbose(env, "fd %d is not pointing to valid bpf_map\n",
18274 return PTR_ERR(map);
18277 err = check_map_prog_compatibility(env, map, env->prog);
18283 aux = &env->insn_aux_data[i];
18284 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
18285 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
18286 addr = (unsigned long)map;
18288 u32 off = insn[1].imm;
18290 if (off >= BPF_MAX_VAR_OFF) {
18291 verbose(env, "direct value offset of %u is not allowed\n", off);
18296 if (!map->ops->map_direct_value_addr) {
18297 verbose(env, "no direct value access support for this map type\n");
18302 err = map->ops->map_direct_value_addr(map, &addr, off);
18304 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
18305 map->value_size, off);
18310 aux->map_off = off;
18314 insn[0].imm = (u32)addr;
18315 insn[1].imm = addr >> 32;
18317 /* check whether we recorded this map already */
18318 for (j = 0; j < env->used_map_cnt; j++) {
18319 if (env->used_maps[j] == map) {
18320 aux->map_index = j;
18326 if (env->used_map_cnt >= MAX_USED_MAPS) {
18331 if (env->prog->sleepable)
18332 atomic64_inc(&map->sleepable_refcnt);
18333 /* hold the map. If the program is rejected by verifier,
18334 * the map will be released by release_maps() or it
18335 * will be used by the valid program until it's unloaded
18336 * and all maps are released in bpf_free_used_maps()
18340 aux->map_index = env->used_map_cnt;
18341 env->used_maps[env->used_map_cnt++] = map;
18343 if (bpf_map_is_cgroup_storage(map) &&
18344 bpf_cgroup_storage_assign(env->prog->aux, map)) {
18345 verbose(env, "only one cgroup storage of each type is allowed\n");
18349 if (map->map_type == BPF_MAP_TYPE_ARENA) {
18350 if (env->prog->aux->arena) {
18351 verbose(env, "Only one arena per program\n");
18355 if (!env->allow_ptr_leaks || !env->bpf_capable) {
18356 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
18360 if (!env->prog->jit_requested) {
18361 verbose(env, "JIT is required to use arena\n");
18362 return -EOPNOTSUPP;
18364 if (!bpf_jit_supports_arena()) {
18365 verbose(env, "JIT doesn't support arena\n");
18366 return -EOPNOTSUPP;
18368 env->prog->aux->arena = (void *)map;
18369 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
18370 verbose(env, "arena's user address must be set via map_extra or mmap()\n");
18382 /* Basic sanity check before we invest more work here. */
18383 if (!bpf_opcode_in_insntable(insn->code)) {
18384 verbose(env, "unknown opcode %02x\n", insn->code);
18389 /* now all pseudo BPF_LD_IMM64 instructions load valid
18390 * 'struct bpf_map *' into a register instead of user map_fd.
18391 * These pointers will be used later by verifier to validate map access.
18396 /* drop refcnt of maps used by the rejected program */
18397 static void release_maps(struct bpf_verifier_env *env)
18399 __bpf_free_used_maps(env->prog->aux, env->used_maps,
18400 env->used_map_cnt);
18403 /* drop refcnt of maps used by the rejected program */
18404 static void release_btfs(struct bpf_verifier_env *env)
18406 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
18407 env->used_btf_cnt);
18410 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
18411 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
18413 struct bpf_insn *insn = env->prog->insnsi;
18414 int insn_cnt = env->prog->len;
18417 for (i = 0; i < insn_cnt; i++, insn++) {
18418 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18420 if (insn->src_reg == BPF_PSEUDO_FUNC)
18426 /* single env->prog->insni[off] instruction was replaced with the range
18427 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
18428 * [0, off) and [off, end) to new locations, so the patched range stays zero
18430 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
18431 struct bpf_insn_aux_data *new_data,
18432 struct bpf_prog *new_prog, u32 off, u32 cnt)
18434 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
18435 struct bpf_insn *insn = new_prog->insnsi;
18436 u32 old_seen = old_data[off].seen;
18440 /* aux info at OFF always needs adjustment, no matter fast path
18441 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
18442 * original insn at old prog.
18444 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
18448 prog_len = new_prog->len;
18450 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
18451 memcpy(new_data + off + cnt - 1, old_data + off,
18452 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
18453 for (i = off; i < off + cnt - 1; i++) {
18454 /* Expand insni[off]'s seen count to the patched range. */
18455 new_data[i].seen = old_seen;
18456 new_data[i].zext_dst = insn_has_def32(env, insn + i);
18458 env->insn_aux_data = new_data;
18462 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
18468 /* NOTE: fake 'exit' subprog should be updated as well. */
18469 for (i = 0; i <= env->subprog_cnt; i++) {
18470 if (env->subprog_info[i].start <= off)
18472 env->subprog_info[i].start += len - 1;
18476 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
18478 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
18479 int i, sz = prog->aux->size_poke_tab;
18480 struct bpf_jit_poke_descriptor *desc;
18482 for (i = 0; i < sz; i++) {
18484 if (desc->insn_idx <= off)
18486 desc->insn_idx += len - 1;
18490 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
18491 const struct bpf_insn *patch, u32 len)
18493 struct bpf_prog *new_prog;
18494 struct bpf_insn_aux_data *new_data = NULL;
18497 new_data = vzalloc(array_size(env->prog->len + len - 1,
18498 sizeof(struct bpf_insn_aux_data)));
18503 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
18504 if (IS_ERR(new_prog)) {
18505 if (PTR_ERR(new_prog) == -ERANGE)
18507 "insn %d cannot be patched due to 16-bit range\n",
18508 env->insn_aux_data[off].orig_idx);
18512 adjust_insn_aux_data(env, new_data, new_prog, off, len);
18513 adjust_subprog_starts(env, off, len);
18514 adjust_poke_descs(new_prog, off, len);
18518 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
18523 /* find first prog starting at or after off (first to remove) */
18524 for (i = 0; i < env->subprog_cnt; i++)
18525 if (env->subprog_info[i].start >= off)
18527 /* find first prog starting at or after off + cnt (first to stay) */
18528 for (j = i; j < env->subprog_cnt; j++)
18529 if (env->subprog_info[j].start >= off + cnt)
18531 /* if j doesn't start exactly at off + cnt, we are just removing
18532 * the front of previous prog
18534 if (env->subprog_info[j].start != off + cnt)
18538 struct bpf_prog_aux *aux = env->prog->aux;
18541 /* move fake 'exit' subprog as well */
18542 move = env->subprog_cnt + 1 - j;
18544 memmove(env->subprog_info + i,
18545 env->subprog_info + j,
18546 sizeof(*env->subprog_info) * move);
18547 env->subprog_cnt -= j - i;
18549 /* remove func_info */
18550 if (aux->func_info) {
18551 move = aux->func_info_cnt - j;
18553 memmove(aux->func_info + i,
18554 aux->func_info + j,
18555 sizeof(*aux->func_info) * move);
18556 aux->func_info_cnt -= j - i;
18557 /* func_info->insn_off is set after all code rewrites,
18558 * in adjust_btf_func() - no need to adjust
18562 /* convert i from "first prog to remove" to "first to adjust" */
18563 if (env->subprog_info[i].start == off)
18567 /* update fake 'exit' subprog as well */
18568 for (; i <= env->subprog_cnt; i++)
18569 env->subprog_info[i].start -= cnt;
18574 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18577 struct bpf_prog *prog = env->prog;
18578 u32 i, l_off, l_cnt, nr_linfo;
18579 struct bpf_line_info *linfo;
18581 nr_linfo = prog->aux->nr_linfo;
18585 linfo = prog->aux->linfo;
18587 /* find first line info to remove, count lines to be removed */
18588 for (i = 0; i < nr_linfo; i++)
18589 if (linfo[i].insn_off >= off)
18594 for (; i < nr_linfo; i++)
18595 if (linfo[i].insn_off < off + cnt)
18600 /* First live insn doesn't match first live linfo, it needs to "inherit"
18601 * last removed linfo. prog is already modified, so prog->len == off
18602 * means no live instructions after (tail of the program was removed).
18604 if (prog->len != off && l_cnt &&
18605 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18607 linfo[--i].insn_off = off + cnt;
18610 /* remove the line info which refer to the removed instructions */
18612 memmove(linfo + l_off, linfo + i,
18613 sizeof(*linfo) * (nr_linfo - i));
18615 prog->aux->nr_linfo -= l_cnt;
18616 nr_linfo = prog->aux->nr_linfo;
18619 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
18620 for (i = l_off; i < nr_linfo; i++)
18621 linfo[i].insn_off -= cnt;
18623 /* fix up all subprogs (incl. 'exit') which start >= off */
18624 for (i = 0; i <= env->subprog_cnt; i++)
18625 if (env->subprog_info[i].linfo_idx > l_off) {
18626 /* program may have started in the removed region but
18627 * may not be fully removed
18629 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18630 env->subprog_info[i].linfo_idx -= l_cnt;
18632 env->subprog_info[i].linfo_idx = l_off;
18638 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18640 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18641 unsigned int orig_prog_len = env->prog->len;
18644 if (bpf_prog_is_offloaded(env->prog->aux))
18645 bpf_prog_offload_remove_insns(env, off, cnt);
18647 err = bpf_remove_insns(env->prog, off, cnt);
18651 err = adjust_subprog_starts_after_remove(env, off, cnt);
18655 err = bpf_adj_linfo_after_remove(env, off, cnt);
18659 memmove(aux_data + off, aux_data + off + cnt,
18660 sizeof(*aux_data) * (orig_prog_len - off - cnt));
18665 /* The verifier does more data flow analysis than llvm and will not
18666 * explore branches that are dead at run time. Malicious programs can
18667 * have dead code too. Therefore replace all dead at-run-time code
18670 * Just nops are not optimal, e.g. if they would sit at the end of the
18671 * program and through another bug we would manage to jump there, then
18672 * we'd execute beyond program memory otherwise. Returning exception
18673 * code also wouldn't work since we can have subprogs where the dead
18674 * code could be located.
18676 static void sanitize_dead_code(struct bpf_verifier_env *env)
18678 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18679 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18680 struct bpf_insn *insn = env->prog->insnsi;
18681 const int insn_cnt = env->prog->len;
18684 for (i = 0; i < insn_cnt; i++) {
18685 if (aux_data[i].seen)
18687 memcpy(insn + i, &trap, sizeof(trap));
18688 aux_data[i].zext_dst = false;
18692 static bool insn_is_cond_jump(u8 code)
18697 if (BPF_CLASS(code) == BPF_JMP32)
18698 return op != BPF_JA;
18700 if (BPF_CLASS(code) != BPF_JMP)
18703 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18706 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18708 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18709 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18710 struct bpf_insn *insn = env->prog->insnsi;
18711 const int insn_cnt = env->prog->len;
18714 for (i = 0; i < insn_cnt; i++, insn++) {
18715 if (!insn_is_cond_jump(insn->code))
18718 if (!aux_data[i + 1].seen)
18719 ja.off = insn->off;
18720 else if (!aux_data[i + 1 + insn->off].seen)
18725 if (bpf_prog_is_offloaded(env->prog->aux))
18726 bpf_prog_offload_replace_insn(env, i, &ja);
18728 memcpy(insn, &ja, sizeof(ja));
18732 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18734 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18735 int insn_cnt = env->prog->len;
18738 for (i = 0; i < insn_cnt; i++) {
18742 while (i + j < insn_cnt && !aux_data[i + j].seen)
18747 err = verifier_remove_insns(env, i, j);
18750 insn_cnt = env->prog->len;
18756 static int opt_remove_nops(struct bpf_verifier_env *env)
18758 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18759 struct bpf_insn *insn = env->prog->insnsi;
18760 int insn_cnt = env->prog->len;
18763 for (i = 0; i < insn_cnt; i++) {
18764 if (memcmp(&insn[i], &ja, sizeof(ja)))
18767 err = verifier_remove_insns(env, i, 1);
18777 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18778 const union bpf_attr *attr)
18780 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18781 struct bpf_insn_aux_data *aux = env->insn_aux_data;
18782 int i, patch_len, delta = 0, len = env->prog->len;
18783 struct bpf_insn *insns = env->prog->insnsi;
18784 struct bpf_prog *new_prog;
18787 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18788 zext_patch[1] = BPF_ZEXT_REG(0);
18789 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18790 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18791 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18792 for (i = 0; i < len; i++) {
18793 int adj_idx = i + delta;
18794 struct bpf_insn insn;
18797 insn = insns[adj_idx];
18798 load_reg = insn_def_regno(&insn);
18799 if (!aux[adj_idx].zext_dst) {
18807 class = BPF_CLASS(code);
18808 if (load_reg == -1)
18811 /* NOTE: arg "reg" (the fourth one) is only used for
18812 * BPF_STX + SRC_OP, so it is safe to pass NULL
18815 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18816 if (class == BPF_LD &&
18817 BPF_MODE(code) == BPF_IMM)
18822 /* ctx load could be transformed into wider load. */
18823 if (class == BPF_LDX &&
18824 aux[adj_idx].ptr_type == PTR_TO_CTX)
18827 imm_rnd = get_random_u32();
18828 rnd_hi32_patch[0] = insn;
18829 rnd_hi32_patch[1].imm = imm_rnd;
18830 rnd_hi32_patch[3].dst_reg = load_reg;
18831 patch = rnd_hi32_patch;
18833 goto apply_patch_buffer;
18836 /* Add in an zero-extend instruction if a) the JIT has requested
18837 * it or b) it's a CMPXCHG.
18839 * The latter is because: BPF_CMPXCHG always loads a value into
18840 * R0, therefore always zero-extends. However some archs'
18841 * equivalent instruction only does this load when the
18842 * comparison is successful. This detail of CMPXCHG is
18843 * orthogonal to the general zero-extension behaviour of the
18844 * CPU, so it's treated independently of bpf_jit_needs_zext.
18846 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18849 /* Zero-extension is done by the caller. */
18850 if (bpf_pseudo_kfunc_call(&insn))
18853 if (WARN_ON(load_reg == -1)) {
18854 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18858 zext_patch[0] = insn;
18859 zext_patch[1].dst_reg = load_reg;
18860 zext_patch[1].src_reg = load_reg;
18861 patch = zext_patch;
18863 apply_patch_buffer:
18864 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18867 env->prog = new_prog;
18868 insns = new_prog->insnsi;
18869 aux = env->insn_aux_data;
18870 delta += patch_len - 1;
18876 /* convert load instructions that access fields of a context type into a
18877 * sequence of instructions that access fields of the underlying structure:
18878 * struct __sk_buff -> struct sk_buff
18879 * struct bpf_sock_ops -> struct sock
18881 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18883 const struct bpf_verifier_ops *ops = env->ops;
18884 int i, cnt, size, ctx_field_size, delta = 0;
18885 const int insn_cnt = env->prog->len;
18886 struct bpf_insn insn_buf[16], *insn;
18887 u32 target_size, size_default, off;
18888 struct bpf_prog *new_prog;
18889 enum bpf_access_type type;
18890 bool is_narrower_load;
18892 if (ops->gen_prologue || env->seen_direct_write) {
18893 if (!ops->gen_prologue) {
18894 verbose(env, "bpf verifier is misconfigured\n");
18897 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18899 if (cnt >= ARRAY_SIZE(insn_buf)) {
18900 verbose(env, "bpf verifier is misconfigured\n");
18903 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18907 env->prog = new_prog;
18912 if (bpf_prog_is_offloaded(env->prog->aux))
18915 insn = env->prog->insnsi + delta;
18917 for (i = 0; i < insn_cnt; i++, insn++) {
18918 bpf_convert_ctx_access_t convert_ctx_access;
18921 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18922 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18923 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18924 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18925 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18926 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18927 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18929 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18930 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18931 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18932 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18933 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18934 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18935 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18936 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18942 if (type == BPF_WRITE &&
18943 env->insn_aux_data[i + delta].sanitize_stack_spill) {
18944 struct bpf_insn patch[] = {
18949 cnt = ARRAY_SIZE(patch);
18950 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18955 env->prog = new_prog;
18956 insn = new_prog->insnsi + i + delta;
18960 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18962 if (!ops->convert_ctx_access)
18964 convert_ctx_access = ops->convert_ctx_access;
18966 case PTR_TO_SOCKET:
18967 case PTR_TO_SOCK_COMMON:
18968 convert_ctx_access = bpf_sock_convert_ctx_access;
18970 case PTR_TO_TCP_SOCK:
18971 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18973 case PTR_TO_XDP_SOCK:
18974 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18976 case PTR_TO_BTF_ID:
18977 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18978 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18979 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18980 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18981 * any faults for loads into such types. BPF_WRITE is disallowed
18984 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18985 if (type == BPF_READ) {
18986 if (BPF_MODE(insn->code) == BPF_MEM)
18987 insn->code = BPF_LDX | BPF_PROBE_MEM |
18988 BPF_SIZE((insn)->code);
18990 insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18991 BPF_SIZE((insn)->code);
18992 env->prog->aux->num_exentries++;
18996 if (BPF_MODE(insn->code) == BPF_MEMSX) {
18997 verbose(env, "sign extending loads from arena are not supported yet\n");
18998 return -EOPNOTSUPP;
19000 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
19001 env->prog->aux->num_exentries++;
19007 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
19008 size = BPF_LDST_BYTES(insn);
19009 mode = BPF_MODE(insn->code);
19011 /* If the read access is a narrower load of the field,
19012 * convert to a 4/8-byte load, to minimum program type specific
19013 * convert_ctx_access changes. If conversion is successful,
19014 * we will apply proper mask to the result.
19016 is_narrower_load = size < ctx_field_size;
19017 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
19019 if (is_narrower_load) {
19022 if (type == BPF_WRITE) {
19023 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
19028 if (ctx_field_size == 4)
19030 else if (ctx_field_size == 8)
19031 size_code = BPF_DW;
19033 insn->off = off & ~(size_default - 1);
19034 insn->code = BPF_LDX | BPF_MEM | size_code;
19038 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
19040 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
19041 (ctx_field_size && !target_size)) {
19042 verbose(env, "bpf verifier is misconfigured\n");
19046 if (is_narrower_load && size < target_size) {
19047 u8 shift = bpf_ctx_narrow_access_offset(
19048 off, size, size_default) * 8;
19049 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
19050 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
19053 if (ctx_field_size <= 4) {
19055 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
19058 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
19059 (1 << size * 8) - 1);
19062 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
19065 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
19066 (1ULL << size * 8) - 1);
19069 if (mode == BPF_MEMSX)
19070 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
19071 insn->dst_reg, insn->dst_reg,
19074 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19080 /* keep walking new program and skip insns we just inserted */
19081 env->prog = new_prog;
19082 insn = new_prog->insnsi + i + delta;
19088 static int jit_subprogs(struct bpf_verifier_env *env)
19090 struct bpf_prog *prog = env->prog, **func, *tmp;
19091 int i, j, subprog_start, subprog_end = 0, len, subprog;
19092 struct bpf_map *map_ptr;
19093 struct bpf_insn *insn;
19094 void *old_bpf_func;
19095 int err, num_exentries;
19097 if (env->subprog_cnt <= 1)
19100 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19101 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
19104 /* Upon error here we cannot fall back to interpreter but
19105 * need a hard reject of the program. Thus -EFAULT is
19106 * propagated in any case.
19108 subprog = find_subprog(env, i + insn->imm + 1);
19110 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
19111 i + insn->imm + 1);
19114 /* temporarily remember subprog id inside insn instead of
19115 * aux_data, since next loop will split up all insns into funcs
19117 insn->off = subprog;
19118 /* remember original imm in case JIT fails and fallback
19119 * to interpreter will be needed
19121 env->insn_aux_data[i].call_imm = insn->imm;
19122 /* point imm to __bpf_call_base+1 from JITs point of view */
19124 if (bpf_pseudo_func(insn))
19125 /* jit (e.g. x86_64) may emit fewer instructions
19126 * if it learns a u32 imm is the same as a u64 imm.
19127 * Force a non zero here.
19132 err = bpf_prog_alloc_jited_linfo(prog);
19134 goto out_undo_insn;
19137 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
19139 goto out_undo_insn;
19141 for (i = 0; i < env->subprog_cnt; i++) {
19142 subprog_start = subprog_end;
19143 subprog_end = env->subprog_info[i + 1].start;
19145 len = subprog_end - subprog_start;
19146 /* bpf_prog_run() doesn't call subprogs directly,
19147 * hence main prog stats include the runtime of subprogs.
19148 * subprogs don't have IDs and not reachable via prog_get_next_id
19149 * func[i]->stats will never be accessed and stays NULL
19151 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
19154 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
19155 len * sizeof(struct bpf_insn));
19156 func[i]->type = prog->type;
19157 func[i]->len = len;
19158 if (bpf_prog_calc_tag(func[i]))
19160 func[i]->is_func = 1;
19161 func[i]->aux->func_idx = i;
19162 /* Below members will be freed only at prog->aux */
19163 func[i]->aux->btf = prog->aux->btf;
19164 func[i]->aux->func_info = prog->aux->func_info;
19165 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
19166 func[i]->aux->poke_tab = prog->aux->poke_tab;
19167 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
19169 for (j = 0; j < prog->aux->size_poke_tab; j++) {
19170 struct bpf_jit_poke_descriptor *poke;
19172 poke = &prog->aux->poke_tab[j];
19173 if (poke->insn_idx < subprog_end &&
19174 poke->insn_idx >= subprog_start)
19175 poke->aux = func[i]->aux;
19178 func[i]->aux->name[0] = 'F';
19179 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
19180 func[i]->jit_requested = 1;
19181 func[i]->blinding_requested = prog->blinding_requested;
19182 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
19183 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
19184 func[i]->aux->linfo = prog->aux->linfo;
19185 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
19186 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
19187 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
19188 func[i]->aux->arena = prog->aux->arena;
19190 insn = func[i]->insnsi;
19191 for (j = 0; j < func[i]->len; j++, insn++) {
19192 if (BPF_CLASS(insn->code) == BPF_LDX &&
19193 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
19194 BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
19195 BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
19197 if ((BPF_CLASS(insn->code) == BPF_STX ||
19198 BPF_CLASS(insn->code) == BPF_ST) &&
19199 BPF_MODE(insn->code) == BPF_PROBE_MEM32)
19202 func[i]->aux->num_exentries = num_exentries;
19203 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
19204 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
19206 func[i]->aux->exception_boundary = env->seen_exception;
19207 func[i] = bpf_int_jit_compile(func[i]);
19208 if (!func[i]->jited) {
19215 /* at this point all bpf functions were successfully JITed
19216 * now populate all bpf_calls with correct addresses and
19217 * run last pass of JIT
19219 for (i = 0; i < env->subprog_cnt; i++) {
19220 insn = func[i]->insnsi;
19221 for (j = 0; j < func[i]->len; j++, insn++) {
19222 if (bpf_pseudo_func(insn)) {
19223 subprog = insn->off;
19224 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
19225 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
19228 if (!bpf_pseudo_call(insn))
19230 subprog = insn->off;
19231 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
19234 /* we use the aux data to keep a list of the start addresses
19235 * of the JITed images for each function in the program
19237 * for some architectures, such as powerpc64, the imm field
19238 * might not be large enough to hold the offset of the start
19239 * address of the callee's JITed image from __bpf_call_base
19241 * in such cases, we can lookup the start address of a callee
19242 * by using its subprog id, available from the off field of
19243 * the call instruction, as an index for this list
19245 func[i]->aux->func = func;
19246 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19247 func[i]->aux->real_func_cnt = env->subprog_cnt;
19249 for (i = 0; i < env->subprog_cnt; i++) {
19250 old_bpf_func = func[i]->bpf_func;
19251 tmp = bpf_int_jit_compile(func[i]);
19252 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
19253 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
19260 /* finally lock prog and jit images for all functions and
19261 * populate kallsysm. Begin at the first subprogram, since
19262 * bpf_prog_load will add the kallsyms for the main program.
19264 for (i = 1; i < env->subprog_cnt; i++) {
19265 bpf_prog_lock_ro(func[i]);
19266 bpf_prog_kallsyms_add(func[i]);
19269 /* Last step: make now unused interpreter insns from main
19270 * prog consistent for later dump requests, so they can
19271 * later look the same as if they were interpreted only.
19273 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19274 if (bpf_pseudo_func(insn)) {
19275 insn[0].imm = env->insn_aux_data[i].call_imm;
19276 insn[1].imm = insn->off;
19280 if (!bpf_pseudo_call(insn))
19282 insn->off = env->insn_aux_data[i].call_imm;
19283 subprog = find_subprog(env, i + insn->off + 1);
19284 insn->imm = subprog;
19288 prog->bpf_func = func[0]->bpf_func;
19289 prog->jited_len = func[0]->jited_len;
19290 prog->aux->extable = func[0]->aux->extable;
19291 prog->aux->num_exentries = func[0]->aux->num_exentries;
19292 prog->aux->func = func;
19293 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19294 prog->aux->real_func_cnt = env->subprog_cnt;
19295 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
19296 prog->aux->exception_boundary = func[0]->aux->exception_boundary;
19297 bpf_prog_jit_attempt_done(prog);
19300 /* We failed JIT'ing, so at this point we need to unregister poke
19301 * descriptors from subprogs, so that kernel is not attempting to
19302 * patch it anymore as we're freeing the subprog JIT memory.
19304 for (i = 0; i < prog->aux->size_poke_tab; i++) {
19305 map_ptr = prog->aux->poke_tab[i].tail_call.map;
19306 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
19308 /* At this point we're guaranteed that poke descriptors are not
19309 * live anymore. We can just unlink its descriptor table as it's
19310 * released with the main prog.
19312 for (i = 0; i < env->subprog_cnt; i++) {
19315 func[i]->aux->poke_tab = NULL;
19316 bpf_jit_free(func[i]);
19320 /* cleanup main prog to be interpreted */
19321 prog->jit_requested = 0;
19322 prog->blinding_requested = 0;
19323 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19324 if (!bpf_pseudo_call(insn))
19327 insn->imm = env->insn_aux_data[i].call_imm;
19329 bpf_prog_jit_attempt_done(prog);
19333 static int fixup_call_args(struct bpf_verifier_env *env)
19335 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19336 struct bpf_prog *prog = env->prog;
19337 struct bpf_insn *insn = prog->insnsi;
19338 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
19343 if (env->prog->jit_requested &&
19344 !bpf_prog_is_offloaded(env->prog->aux)) {
19345 err = jit_subprogs(env);
19348 if (err == -EFAULT)
19351 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19352 if (has_kfunc_call) {
19353 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
19356 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
19357 /* When JIT fails the progs with bpf2bpf calls and tail_calls
19358 * have to be rejected, since interpreter doesn't support them yet.
19360 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
19363 for (i = 0; i < prog->len; i++, insn++) {
19364 if (bpf_pseudo_func(insn)) {
19365 /* When JIT fails the progs with callback calls
19366 * have to be rejected, since interpreter doesn't support them yet.
19368 verbose(env, "callbacks are not allowed in non-JITed programs\n");
19372 if (!bpf_pseudo_call(insn))
19374 depth = get_callee_stack_depth(env, insn, i);
19377 bpf_patch_call_args(insn, depth);
19384 /* replace a generic kfunc with a specialized version if necessary */
19385 static void specialize_kfunc(struct bpf_verifier_env *env,
19386 u32 func_id, u16 offset, unsigned long *addr)
19388 struct bpf_prog *prog = env->prog;
19389 bool seen_direct_write;
19393 if (bpf_dev_bound_kfunc_id(func_id)) {
19394 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19396 *addr = (unsigned long)xdp_kfunc;
19399 /* fallback to default kfunc when not supported by netdev */
19405 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19406 seen_direct_write = env->seen_direct_write;
19407 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19410 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19412 /* restore env->seen_direct_write to its original value, since
19413 * may_access_direct_pkt_data mutates it
19415 env->seen_direct_write = seen_direct_write;
19419 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19420 u16 struct_meta_reg,
19421 u16 node_offset_reg,
19422 struct bpf_insn *insn,
19423 struct bpf_insn *insn_buf,
19426 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19427 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19429 insn_buf[0] = addr[0];
19430 insn_buf[1] = addr[1];
19431 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19432 insn_buf[3] = *insn;
19436 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19437 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
19439 const struct bpf_kfunc_desc *desc;
19442 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19448 /* insn->imm has the btf func_id. Replace it with an offset relative to
19449 * __bpf_call_base, unless the JIT needs to call functions that are
19450 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
19452 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
19454 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
19459 if (!bpf_jit_supports_far_kfunc_call())
19460 insn->imm = BPF_CALL_IMM(desc->addr);
19463 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
19464 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
19465 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19466 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19467 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
19469 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
19470 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19475 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19476 insn_buf[1] = addr[0];
19477 insn_buf[2] = addr[1];
19478 insn_buf[3] = *insn;
19480 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
19481 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
19482 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
19483 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19484 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19486 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
19487 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19492 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
19493 !kptr_struct_meta) {
19494 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19499 insn_buf[0] = addr[0];
19500 insn_buf[1] = addr[1];
19501 insn_buf[2] = *insn;
19503 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
19504 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
19505 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19506 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19507 int struct_meta_reg = BPF_REG_3;
19508 int node_offset_reg = BPF_REG_4;
19510 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
19511 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19512 struct_meta_reg = BPF_REG_4;
19513 node_offset_reg = BPF_REG_5;
19516 if (!kptr_struct_meta) {
19517 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19522 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19523 node_offset_reg, insn, insn_buf, cnt);
19524 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19525 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19526 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19532 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
19533 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
19535 struct bpf_subprog_info *info = env->subprog_info;
19536 int cnt = env->subprog_cnt;
19537 struct bpf_prog *prog;
19539 /* We only reserve one slot for hidden subprogs in subprog_info. */
19540 if (env->hidden_subprog_cnt) {
19541 verbose(env, "verifier internal error: only one hidden subprog supported\n");
19544 /* We're not patching any existing instruction, just appending the new
19545 * ones for the hidden subprog. Hence all of the adjustment operations
19546 * in bpf_patch_insn_data are no-ops.
19548 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
19552 info[cnt + 1].start = info[cnt].start;
19553 info[cnt].start = prog->len - len + 1;
19554 env->subprog_cnt++;
19555 env->hidden_subprog_cnt++;
19559 /* Do various post-verification rewrites in a single program pass.
19560 * These rewrites simplify JIT and interpreter implementations.
19562 static int do_misc_fixups(struct bpf_verifier_env *env)
19564 struct bpf_prog *prog = env->prog;
19565 enum bpf_attach_type eatype = prog->expected_attach_type;
19566 enum bpf_prog_type prog_type = resolve_prog_type(prog);
19567 struct bpf_insn *insn = prog->insnsi;
19568 const struct bpf_func_proto *fn;
19569 const int insn_cnt = prog->len;
19570 const struct bpf_map_ops *ops;
19571 struct bpf_insn_aux_data *aux;
19572 struct bpf_insn insn_buf[16];
19573 struct bpf_prog *new_prog;
19574 struct bpf_map *map_ptr;
19575 int i, ret, cnt, delta = 0, cur_subprog = 0;
19576 struct bpf_subprog_info *subprogs = env->subprog_info;
19577 u16 stack_depth = subprogs[cur_subprog].stack_depth;
19578 u16 stack_depth_extra = 0;
19580 if (env->seen_exception && !env->exception_callback_subprog) {
19581 struct bpf_insn patch[] = {
19582 env->prog->insnsi[insn_cnt - 1],
19583 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
19587 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
19591 insn = prog->insnsi;
19593 env->exception_callback_subprog = env->subprog_cnt - 1;
19594 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */
19595 mark_subprog_exc_cb(env, env->exception_callback_subprog);
19598 for (i = 0; i < insn_cnt;) {
19599 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
19600 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
19601 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
19602 /* convert to 32-bit mov that clears upper 32-bit */
19603 insn->code = BPF_ALU | BPF_MOV | BPF_X;
19604 /* clear off, so it's a normal 'wX = wY' from JIT pov */
19606 } /* cast from as(0) to as(1) should be handled by JIT */
19610 if (env->insn_aux_data[i + delta].needs_zext)
19611 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
19612 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
19614 /* Make divide-by-zero exceptions impossible. */
19615 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
19616 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
19617 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
19618 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
19619 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
19620 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
19621 struct bpf_insn *patchlet;
19622 struct bpf_insn chk_and_div[] = {
19623 /* [R,W]x div 0 -> 0 */
19624 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19625 BPF_JNE | BPF_K, insn->src_reg,
19627 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
19628 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19631 struct bpf_insn chk_and_mod[] = {
19632 /* [R,W]x mod 0 -> [R,W]x */
19633 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19634 BPF_JEQ | BPF_K, insn->src_reg,
19635 0, 1 + (is64 ? 0 : 1), 0),
19637 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19638 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
19641 patchlet = isdiv ? chk_and_div : chk_and_mod;
19642 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
19643 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
19645 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
19650 env->prog = prog = new_prog;
19651 insn = new_prog->insnsi + i + delta;
19655 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
19656 if (BPF_CLASS(insn->code) == BPF_LD &&
19657 (BPF_MODE(insn->code) == BPF_ABS ||
19658 BPF_MODE(insn->code) == BPF_IND)) {
19659 cnt = env->ops->gen_ld_abs(insn, insn_buf);
19660 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19661 verbose(env, "bpf verifier is misconfigured\n");
19665 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19670 env->prog = prog = new_prog;
19671 insn = new_prog->insnsi + i + delta;
19675 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
19676 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
19677 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
19678 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
19679 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
19680 struct bpf_insn *patch = &insn_buf[0];
19681 bool issrc, isneg, isimm;
19684 aux = &env->insn_aux_data[i + delta];
19685 if (!aux->alu_state ||
19686 aux->alu_state == BPF_ALU_NON_POINTER)
19689 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
19690 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
19691 BPF_ALU_SANITIZE_SRC;
19692 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
19694 off_reg = issrc ? insn->src_reg : insn->dst_reg;
19696 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19699 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19700 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19701 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
19702 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
19703 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
19704 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
19705 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
19708 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
19709 insn->src_reg = BPF_REG_AX;
19711 insn->code = insn->code == code_add ?
19712 code_sub : code_add;
19714 if (issrc && isneg && !isimm)
19715 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19716 cnt = patch - insn_buf;
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 if (is_may_goto_insn(insn)) {
19729 int stack_off = -stack_depth - 8;
19731 stack_depth_extra = 8;
19732 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
19733 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
19734 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
19735 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
19738 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19743 env->prog = prog = new_prog;
19744 insn = new_prog->insnsi + i + delta;
19748 if (insn->code != (BPF_JMP | BPF_CALL))
19750 if (insn->src_reg == BPF_PSEUDO_CALL)
19752 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19753 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19759 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19764 env->prog = prog = new_prog;
19765 insn = new_prog->insnsi + i + delta;
19769 if (insn->imm == BPF_FUNC_get_route_realm)
19770 prog->dst_needed = 1;
19771 if (insn->imm == BPF_FUNC_get_prandom_u32)
19772 bpf_user_rnd_init_once();
19773 if (insn->imm == BPF_FUNC_override_return)
19774 prog->kprobe_override = 1;
19775 if (insn->imm == BPF_FUNC_tail_call) {
19776 /* If we tail call into other programs, we
19777 * cannot make any assumptions since they can
19778 * be replaced dynamically during runtime in
19779 * the program array.
19781 prog->cb_access = 1;
19782 if (!allow_tail_call_in_subprogs(env))
19783 prog->aux->stack_depth = MAX_BPF_STACK;
19784 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19786 /* mark bpf_tail_call as different opcode to avoid
19787 * conditional branch in the interpreter for every normal
19788 * call and to prevent accidental JITing by JIT compiler
19789 * that doesn't support bpf_tail_call yet
19792 insn->code = BPF_JMP | BPF_TAIL_CALL;
19794 aux = &env->insn_aux_data[i + delta];
19795 if (env->bpf_capable && !prog->blinding_requested &&
19796 prog->jit_requested &&
19797 !bpf_map_key_poisoned(aux) &&
19798 !bpf_map_ptr_poisoned(aux) &&
19799 !bpf_map_ptr_unpriv(aux)) {
19800 struct bpf_jit_poke_descriptor desc = {
19801 .reason = BPF_POKE_REASON_TAIL_CALL,
19802 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19803 .tail_call.key = bpf_map_key_immediate(aux),
19804 .insn_idx = i + delta,
19807 ret = bpf_jit_add_poke_descriptor(prog, &desc);
19809 verbose(env, "adding tail call poke descriptor failed\n");
19813 insn->imm = ret + 1;
19817 if (!bpf_map_ptr_unpriv(aux))
19820 /* instead of changing every JIT dealing with tail_call
19821 * emit two extra insns:
19822 * if (index >= max_entries) goto out;
19823 * index &= array->index_mask;
19824 * to avoid out-of-bounds cpu speculation
19826 if (bpf_map_ptr_poisoned(aux)) {
19827 verbose(env, "tail_call abusing map_ptr\n");
19831 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19832 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19833 map_ptr->max_entries, 2);
19834 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19835 container_of(map_ptr,
19838 insn_buf[2] = *insn;
19840 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19845 env->prog = prog = new_prog;
19846 insn = new_prog->insnsi + i + delta;
19850 if (insn->imm == BPF_FUNC_timer_set_callback) {
19851 /* The verifier will process callback_fn as many times as necessary
19852 * with different maps and the register states prepared by
19853 * set_timer_callback_state will be accurate.
19855 * The following use case is valid:
19856 * map1 is shared by prog1, prog2, prog3.
19857 * prog1 calls bpf_timer_init for some map1 elements
19858 * prog2 calls bpf_timer_set_callback for some map1 elements.
19859 * Those that were not bpf_timer_init-ed will return -EINVAL.
19860 * prog3 calls bpf_timer_start for some map1 elements.
19861 * Those that were not both bpf_timer_init-ed and
19862 * bpf_timer_set_callback-ed will return -EINVAL.
19864 struct bpf_insn ld_addrs[2] = {
19865 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19868 insn_buf[0] = ld_addrs[0];
19869 insn_buf[1] = ld_addrs[1];
19870 insn_buf[2] = *insn;
19873 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19878 env->prog = prog = new_prog;
19879 insn = new_prog->insnsi + i + delta;
19880 goto patch_call_imm;
19883 if (is_storage_get_function(insn->imm)) {
19884 if (!in_sleepable(env) ||
19885 env->insn_aux_data[i + delta].storage_get_func_atomic)
19886 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19888 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19889 insn_buf[1] = *insn;
19892 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19897 env->prog = prog = new_prog;
19898 insn = new_prog->insnsi + i + delta;
19899 goto patch_call_imm;
19902 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
19903 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
19904 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
19905 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
19907 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
19908 insn_buf[1] = *insn;
19911 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19916 env->prog = prog = new_prog;
19917 insn = new_prog->insnsi + i + delta;
19918 goto patch_call_imm;
19921 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19922 * and other inlining handlers are currently limited to 64 bit
19925 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19926 (insn->imm == BPF_FUNC_map_lookup_elem ||
19927 insn->imm == BPF_FUNC_map_update_elem ||
19928 insn->imm == BPF_FUNC_map_delete_elem ||
19929 insn->imm == BPF_FUNC_map_push_elem ||
19930 insn->imm == BPF_FUNC_map_pop_elem ||
19931 insn->imm == BPF_FUNC_map_peek_elem ||
19932 insn->imm == BPF_FUNC_redirect_map ||
19933 insn->imm == BPF_FUNC_for_each_map_elem ||
19934 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19935 aux = &env->insn_aux_data[i + delta];
19936 if (bpf_map_ptr_poisoned(aux))
19937 goto patch_call_imm;
19939 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19940 ops = map_ptr->ops;
19941 if (insn->imm == BPF_FUNC_map_lookup_elem &&
19942 ops->map_gen_lookup) {
19943 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19944 if (cnt == -EOPNOTSUPP)
19945 goto patch_map_ops_generic;
19946 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19947 verbose(env, "bpf verifier is misconfigured\n");
19951 new_prog = bpf_patch_insn_data(env, i + delta,
19957 env->prog = prog = new_prog;
19958 insn = new_prog->insnsi + i + delta;
19962 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19963 (void *(*)(struct bpf_map *map, void *key))NULL));
19964 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19965 (long (*)(struct bpf_map *map, void *key))NULL));
19966 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19967 (long (*)(struct bpf_map *map, void *key, void *value,
19969 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19970 (long (*)(struct bpf_map *map, void *value,
19972 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19973 (long (*)(struct bpf_map *map, void *value))NULL));
19974 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19975 (long (*)(struct bpf_map *map, void *value))NULL));
19976 BUILD_BUG_ON(!__same_type(ops->map_redirect,
19977 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19978 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19979 (long (*)(struct bpf_map *map,
19980 bpf_callback_t callback_fn,
19981 void *callback_ctx,
19983 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19984 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19986 patch_map_ops_generic:
19987 switch (insn->imm) {
19988 case BPF_FUNC_map_lookup_elem:
19989 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19991 case BPF_FUNC_map_update_elem:
19992 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19994 case BPF_FUNC_map_delete_elem:
19995 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19997 case BPF_FUNC_map_push_elem:
19998 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
20000 case BPF_FUNC_map_pop_elem:
20001 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
20003 case BPF_FUNC_map_peek_elem:
20004 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
20006 case BPF_FUNC_redirect_map:
20007 insn->imm = BPF_CALL_IMM(ops->map_redirect);
20009 case BPF_FUNC_for_each_map_elem:
20010 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
20012 case BPF_FUNC_map_lookup_percpu_elem:
20013 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
20017 goto patch_call_imm;
20020 /* Implement bpf_jiffies64 inline. */
20021 if (prog->jit_requested && BITS_PER_LONG == 64 &&
20022 insn->imm == BPF_FUNC_jiffies64) {
20023 struct bpf_insn ld_jiffies_addr[2] = {
20024 BPF_LD_IMM64(BPF_REG_0,
20025 (unsigned long)&jiffies),
20028 insn_buf[0] = ld_jiffies_addr[0];
20029 insn_buf[1] = ld_jiffies_addr[1];
20030 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
20034 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
20040 env->prog = prog = new_prog;
20041 insn = new_prog->insnsi + i + delta;
20045 /* Implement bpf_get_func_arg inline. */
20046 if (prog_type == BPF_PROG_TYPE_TRACING &&
20047 insn->imm == BPF_FUNC_get_func_arg) {
20048 /* Load nr_args from ctx - 8 */
20049 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20050 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
20051 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
20052 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
20053 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
20054 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
20055 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
20056 insn_buf[7] = BPF_JMP_A(1);
20057 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
20060 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20065 env->prog = prog = new_prog;
20066 insn = new_prog->insnsi + i + delta;
20070 /* Implement bpf_get_func_ret inline. */
20071 if (prog_type == BPF_PROG_TYPE_TRACING &&
20072 insn->imm == BPF_FUNC_get_func_ret) {
20073 if (eatype == BPF_TRACE_FEXIT ||
20074 eatype == BPF_MODIFY_RETURN) {
20075 /* Load nr_args from ctx - 8 */
20076 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20077 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
20078 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
20079 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
20080 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
20081 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
20084 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
20088 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20093 env->prog = prog = new_prog;
20094 insn = new_prog->insnsi + i + delta;
20098 /* Implement get_func_arg_cnt inline. */
20099 if (prog_type == BPF_PROG_TYPE_TRACING &&
20100 insn->imm == BPF_FUNC_get_func_arg_cnt) {
20101 /* Load nr_args from ctx - 8 */
20102 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20104 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
20108 env->prog = prog = new_prog;
20109 insn = new_prog->insnsi + i + delta;
20113 /* Implement bpf_get_func_ip inline. */
20114 if (prog_type == BPF_PROG_TYPE_TRACING &&
20115 insn->imm == BPF_FUNC_get_func_ip) {
20116 /* Load IP address from ctx - 16 */
20117 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
20119 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
20123 env->prog = prog = new_prog;
20124 insn = new_prog->insnsi + i + delta;
20128 /* Implement bpf_kptr_xchg inline */
20129 if (prog->jit_requested && BITS_PER_LONG == 64 &&
20130 insn->imm == BPF_FUNC_kptr_xchg &&
20131 bpf_jit_supports_ptr_xchg()) {
20132 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
20133 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
20136 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20141 env->prog = prog = new_prog;
20142 insn = new_prog->insnsi + i + delta;
20146 fn = env->ops->get_func_proto(insn->imm, env->prog);
20147 /* all functions that have prototype and verifier allowed
20148 * programs to call them, must be real in-kernel functions
20152 "kernel subsystem misconfigured func %s#%d\n",
20153 func_id_name(insn->imm), insn->imm);
20156 insn->imm = fn->func - __bpf_call_base;
20158 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
20159 subprogs[cur_subprog].stack_depth += stack_depth_extra;
20160 subprogs[cur_subprog].stack_extra = stack_depth_extra;
20162 stack_depth = subprogs[cur_subprog].stack_depth;
20163 stack_depth_extra = 0;
20169 env->prog->aux->stack_depth = subprogs[0].stack_depth;
20170 for (i = 0; i < env->subprog_cnt; i++) {
20171 int subprog_start = subprogs[i].start;
20172 int stack_slots = subprogs[i].stack_extra / 8;
20176 if (stack_slots > 1) {
20177 verbose(env, "verifier bug: stack_slots supports may_goto only\n");
20181 /* Add ST insn to subprog prologue to init extra stack */
20182 insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP,
20183 -subprogs[i].stack_depth, BPF_MAX_LOOPS);
20184 /* Copy first actual insn to preserve it */
20185 insn_buf[1] = env->prog->insnsi[subprog_start];
20187 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2);
20190 env->prog = prog = new_prog;
20193 /* Since poke tab is now finalized, publish aux to tracker. */
20194 for (i = 0; i < prog->aux->size_poke_tab; i++) {
20195 map_ptr = prog->aux->poke_tab[i].tail_call.map;
20196 if (!map_ptr->ops->map_poke_track ||
20197 !map_ptr->ops->map_poke_untrack ||
20198 !map_ptr->ops->map_poke_run) {
20199 verbose(env, "bpf verifier is misconfigured\n");
20203 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
20205 verbose(env, "tracking tail call prog failed\n");
20210 sort_kfunc_descs_by_imm_off(env->prog);
20215 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
20218 u32 callback_subprogno,
20221 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
20222 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
20223 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
20224 int reg_loop_max = BPF_REG_6;
20225 int reg_loop_cnt = BPF_REG_7;
20226 int reg_loop_ctx = BPF_REG_8;
20228 struct bpf_prog *new_prog;
20229 u32 callback_start;
20230 u32 call_insn_offset;
20231 s32 callback_offset;
20233 /* This represents an inlined version of bpf_iter.c:bpf_loop,
20234 * be careful to modify this code in sync.
20236 struct bpf_insn insn_buf[] = {
20237 /* Return error and jump to the end of the patch if
20238 * expected number of iterations is too big.
20240 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
20241 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
20242 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
20243 /* spill R6, R7, R8 to use these as loop vars */
20244 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
20245 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
20246 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
20247 /* initialize loop vars */
20248 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
20249 BPF_MOV32_IMM(reg_loop_cnt, 0),
20250 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
20252 * if reg_loop_cnt >= reg_loop_max skip the loop body
20254 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
20256 * correct callback offset would be set after patching
20258 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
20259 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
20261 /* increment loop counter */
20262 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
20263 /* jump to loop header if callback returned 0 */
20264 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
20265 /* return value of bpf_loop,
20266 * set R0 to the number of iterations
20268 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
20269 /* restore original values of R6, R7, R8 */
20270 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
20271 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
20272 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
20275 *cnt = ARRAY_SIZE(insn_buf);
20276 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
20280 /* callback start is known only after patching */
20281 callback_start = env->subprog_info[callback_subprogno].start;
20282 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
20283 call_insn_offset = position + 12;
20284 callback_offset = callback_start - call_insn_offset - 1;
20285 new_prog->insnsi[call_insn_offset].imm = callback_offset;
20290 static bool is_bpf_loop_call(struct bpf_insn *insn)
20292 return insn->code == (BPF_JMP | BPF_CALL) &&
20293 insn->src_reg == 0 &&
20294 insn->imm == BPF_FUNC_loop;
20297 /* For all sub-programs in the program (including main) check
20298 * insn_aux_data to see if there are bpf_loop calls that require
20299 * inlining. If such calls are found the calls are replaced with a
20300 * sequence of instructions produced by `inline_bpf_loop` function and
20301 * subprog stack_depth is increased by the size of 3 registers.
20302 * This stack space is used to spill values of the R6, R7, R8. These
20303 * registers are used to store the loop bound, counter and context
20306 static int optimize_bpf_loop(struct bpf_verifier_env *env)
20308 struct bpf_subprog_info *subprogs = env->subprog_info;
20309 int i, cur_subprog = 0, cnt, delta = 0;
20310 struct bpf_insn *insn = env->prog->insnsi;
20311 int insn_cnt = env->prog->len;
20312 u16 stack_depth = subprogs[cur_subprog].stack_depth;
20313 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20314 u16 stack_depth_extra = 0;
20316 for (i = 0; i < insn_cnt; i++, insn++) {
20317 struct bpf_loop_inline_state *inline_state =
20318 &env->insn_aux_data[i + delta].loop_inline_state;
20320 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
20321 struct bpf_prog *new_prog;
20323 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
20324 new_prog = inline_bpf_loop(env,
20326 -(stack_depth + stack_depth_extra),
20327 inline_state->callback_subprogno,
20333 env->prog = new_prog;
20334 insn = new_prog->insnsi + i + delta;
20337 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
20338 subprogs[cur_subprog].stack_depth += stack_depth_extra;
20340 stack_depth = subprogs[cur_subprog].stack_depth;
20341 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20342 stack_depth_extra = 0;
20346 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20351 static void free_states(struct bpf_verifier_env *env)
20353 struct bpf_verifier_state_list *sl, *sln;
20356 sl = env->free_list;
20359 free_verifier_state(&sl->state, false);
20363 env->free_list = NULL;
20365 if (!env->explored_states)
20368 for (i = 0; i < state_htab_size(env); i++) {
20369 sl = env->explored_states[i];
20373 free_verifier_state(&sl->state, false);
20377 env->explored_states[i] = NULL;
20381 static int do_check_common(struct bpf_verifier_env *env, int subprog)
20383 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20384 struct bpf_subprog_info *sub = subprog_info(env, subprog);
20385 struct bpf_verifier_state *state;
20386 struct bpf_reg_state *regs;
20389 env->prev_linfo = NULL;
20392 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
20395 state->curframe = 0;
20396 state->speculative = false;
20397 state->branches = 1;
20398 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
20399 if (!state->frame[0]) {
20403 env->cur_state = state;
20404 init_func_state(env, state->frame[0],
20405 BPF_MAIN_FUNC /* callsite */,
20408 state->first_insn_idx = env->subprog_info[subprog].start;
20409 state->last_insn_idx = -1;
20411 regs = state->frame[state->curframe]->regs;
20412 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
20413 const char *sub_name = subprog_name(env, subprog);
20414 struct bpf_subprog_arg_info *arg;
20415 struct bpf_reg_state *reg;
20417 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
20418 ret = btf_prepare_func_args(env, subprog);
20422 if (subprog_is_exc_cb(env, subprog)) {
20423 state->frame[0]->in_exception_callback_fn = true;
20424 /* We have already ensured that the callback returns an integer, just
20425 * like all global subprogs. We need to determine it only has a single
20428 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
20429 verbose(env, "exception cb only supports single integer argument\n");
20434 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
20435 arg = &sub->args[i - BPF_REG_1];
20438 if (arg->arg_type == ARG_PTR_TO_CTX) {
20439 reg->type = PTR_TO_CTX;
20440 mark_reg_known_zero(env, regs, i);
20441 } else if (arg->arg_type == ARG_ANYTHING) {
20442 reg->type = SCALAR_VALUE;
20443 mark_reg_unknown(env, regs, i);
20444 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
20445 /* assume unspecial LOCAL dynptr type */
20446 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
20447 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
20448 reg->type = PTR_TO_MEM;
20449 if (arg->arg_type & PTR_MAYBE_NULL)
20450 reg->type |= PTR_MAYBE_NULL;
20451 mark_reg_known_zero(env, regs, i);
20452 reg->mem_size = arg->mem_size;
20453 reg->id = ++env->id_gen;
20454 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
20455 reg->type = PTR_TO_BTF_ID;
20456 if (arg->arg_type & PTR_MAYBE_NULL)
20457 reg->type |= PTR_MAYBE_NULL;
20458 if (arg->arg_type & PTR_UNTRUSTED)
20459 reg->type |= PTR_UNTRUSTED;
20460 if (arg->arg_type & PTR_TRUSTED)
20461 reg->type |= PTR_TRUSTED;
20462 mark_reg_known_zero(env, regs, i);
20463 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
20464 reg->btf_id = arg->btf_id;
20465 reg->id = ++env->id_gen;
20466 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
20467 /* caller can pass either PTR_TO_ARENA or SCALAR */
20468 mark_reg_unknown(env, regs, i);
20470 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
20471 i - BPF_REG_1, arg->arg_type);
20477 /* if main BPF program has associated BTF info, validate that
20478 * it's matching expected signature, and otherwise mark BTF
20479 * info for main program as unreliable
20481 if (env->prog->aux->func_info_aux) {
20482 ret = btf_prepare_func_args(env, 0);
20483 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
20484 env->prog->aux->func_info_aux[0].unreliable = true;
20487 /* 1st arg to a function */
20488 regs[BPF_REG_1].type = PTR_TO_CTX;
20489 mark_reg_known_zero(env, regs, BPF_REG_1);
20492 ret = do_check(env);
20494 /* check for NULL is necessary, since cur_state can be freed inside
20495 * do_check() under memory pressure.
20497 if (env->cur_state) {
20498 free_verifier_state(env->cur_state, true);
20499 env->cur_state = NULL;
20501 while (!pop_stack(env, NULL, NULL, false));
20502 if (!ret && pop_log)
20503 bpf_vlog_reset(&env->log, 0);
20508 /* Lazily verify all global functions based on their BTF, if they are called
20509 * from main BPF program or any of subprograms transitively.
20510 * BPF global subprogs called from dead code are not validated.
20511 * All callable global functions must pass verification.
20512 * Otherwise the whole program is rejected.
20523 * foo() will be verified first for R1=any_scalar_value. During verification it
20524 * will be assumed that bar() already verified successfully and call to bar()
20525 * from foo() will be checked for type match only. Later bar() will be verified
20526 * independently to check that it's safe for R1=any_scalar_value.
20528 static int do_check_subprogs(struct bpf_verifier_env *env)
20530 struct bpf_prog_aux *aux = env->prog->aux;
20531 struct bpf_func_info_aux *sub_aux;
20532 int i, ret, new_cnt;
20534 if (!aux->func_info)
20537 /* exception callback is presumed to be always called */
20538 if (env->exception_callback_subprog)
20539 subprog_aux(env, env->exception_callback_subprog)->called = true;
20543 for (i = 1; i < env->subprog_cnt; i++) {
20544 if (!subprog_is_global(env, i))
20547 sub_aux = subprog_aux(env, i);
20548 if (!sub_aux->called || sub_aux->verified)
20551 env->insn_idx = env->subprog_info[i].start;
20552 WARN_ON_ONCE(env->insn_idx == 0);
20553 ret = do_check_common(env, i);
20556 } else if (env->log.level & BPF_LOG_LEVEL) {
20557 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
20558 i, subprog_name(env, i));
20561 /* We verified new global subprog, it might have called some
20562 * more global subprogs that we haven't verified yet, so we
20563 * need to do another pass over subprogs to verify those.
20565 sub_aux->verified = true;
20569 /* We can't loop forever as we verify at least one global subprog on
20578 static int do_check_main(struct bpf_verifier_env *env)
20583 ret = do_check_common(env, 0);
20585 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20590 static void print_verification_stats(struct bpf_verifier_env *env)
20594 if (env->log.level & BPF_LOG_STATS) {
20595 verbose(env, "verification time %lld usec\n",
20596 div_u64(env->verification_time, 1000));
20597 verbose(env, "stack depth ");
20598 for (i = 0; i < env->subprog_cnt; i++) {
20599 u32 depth = env->subprog_info[i].stack_depth;
20601 verbose(env, "%d", depth);
20602 if (i + 1 < env->subprog_cnt)
20605 verbose(env, "\n");
20607 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
20608 "total_states %d peak_states %d mark_read %d\n",
20609 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
20610 env->max_states_per_insn, env->total_states,
20611 env->peak_states, env->longest_mark_read_walk);
20614 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
20616 const struct btf_type *t, *func_proto;
20617 const struct bpf_struct_ops_desc *st_ops_desc;
20618 const struct bpf_struct_ops *st_ops;
20619 const struct btf_member *member;
20620 struct bpf_prog *prog = env->prog;
20621 u32 btf_id, member_idx;
20625 if (!prog->gpl_compatible) {
20626 verbose(env, "struct ops programs must have a GPL compatible license\n");
20630 if (!prog->aux->attach_btf_id)
20633 btf = prog->aux->attach_btf;
20634 if (btf_is_module(btf)) {
20635 /* Make sure st_ops is valid through the lifetime of env */
20636 env->attach_btf_mod = btf_try_get_module(btf);
20637 if (!env->attach_btf_mod) {
20638 verbose(env, "struct_ops module %s is not found\n",
20639 btf_get_name(btf));
20644 btf_id = prog->aux->attach_btf_id;
20645 st_ops_desc = bpf_struct_ops_find(btf, btf_id);
20646 if (!st_ops_desc) {
20647 verbose(env, "attach_btf_id %u is not a supported struct\n",
20651 st_ops = st_ops_desc->st_ops;
20653 t = st_ops_desc->type;
20654 member_idx = prog->expected_attach_type;
20655 if (member_idx >= btf_type_vlen(t)) {
20656 verbose(env, "attach to invalid member idx %u of struct %s\n",
20657 member_idx, st_ops->name);
20661 member = &btf_type_member(t)[member_idx];
20662 mname = btf_name_by_offset(btf, member->name_off);
20663 func_proto = btf_type_resolve_func_ptr(btf, member->type,
20666 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
20667 mname, member_idx, st_ops->name);
20671 if (st_ops->check_member) {
20672 int err = st_ops->check_member(t, member, prog);
20675 verbose(env, "attach to unsupported member %s of struct %s\n",
20676 mname, st_ops->name);
20681 /* btf_ctx_access() used this to provide argument type info */
20682 prog->aux->ctx_arg_info =
20683 st_ops_desc->arg_info[member_idx].info;
20684 prog->aux->ctx_arg_info_size =
20685 st_ops_desc->arg_info[member_idx].cnt;
20687 prog->aux->attach_func_proto = func_proto;
20688 prog->aux->attach_func_name = mname;
20689 env->ops = st_ops->verifier_ops;
20693 #define SECURITY_PREFIX "security_"
20695 static int check_attach_modify_return(unsigned long addr, const char *func_name)
20697 if (within_error_injection_list(addr) ||
20698 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
20704 /* list of non-sleepable functions that are otherwise on
20705 * ALLOW_ERROR_INJECTION list
20707 BTF_SET_START(btf_non_sleepable_error_inject)
20708 /* Three functions below can be called from sleepable and non-sleepable context.
20709 * Assume non-sleepable from bpf safety point of view.
20711 BTF_ID(func, __filemap_add_folio)
20712 BTF_ID(func, should_fail_alloc_page)
20713 BTF_ID(func, should_failslab)
20714 BTF_SET_END(btf_non_sleepable_error_inject)
20716 static int check_non_sleepable_error_inject(u32 btf_id)
20718 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
20721 int bpf_check_attach_target(struct bpf_verifier_log *log,
20722 const struct bpf_prog *prog,
20723 const struct bpf_prog *tgt_prog,
20725 struct bpf_attach_target_info *tgt_info)
20727 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
20728 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
20729 const char prefix[] = "btf_trace_";
20730 int ret = 0, subprog = -1, i;
20731 const struct btf_type *t;
20732 bool conservative = true;
20736 struct module *mod = NULL;
20739 bpf_log(log, "Tracing programs must provide btf_id\n");
20742 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
20745 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
20748 t = btf_type_by_id(btf, btf_id);
20750 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
20753 tname = btf_name_by_offset(btf, t->name_off);
20755 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
20759 struct bpf_prog_aux *aux = tgt_prog->aux;
20761 if (bpf_prog_is_dev_bound(prog->aux) &&
20762 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
20763 bpf_log(log, "Target program bound device mismatch");
20767 for (i = 0; i < aux->func_info_cnt; i++)
20768 if (aux->func_info[i].type_id == btf_id) {
20772 if (subprog == -1) {
20773 bpf_log(log, "Subprog %s doesn't exist\n", tname);
20776 if (aux->func && aux->func[subprog]->aux->exception_cb) {
20778 "%s programs cannot attach to exception callback\n",
20779 prog_extension ? "Extension" : "FENTRY/FEXIT");
20782 conservative = aux->func_info_aux[subprog].unreliable;
20783 if (prog_extension) {
20784 if (conservative) {
20786 "Cannot replace static functions\n");
20789 if (!prog->jit_requested) {
20791 "Extension programs should be JITed\n");
20795 if (!tgt_prog->jited) {
20796 bpf_log(log, "Can attach to only JITed progs\n");
20799 if (prog_tracing) {
20800 if (aux->attach_tracing_prog) {
20802 * Target program is an fentry/fexit which is already attached
20803 * to another tracing program. More levels of nesting
20804 * attachment are not allowed.
20806 bpf_log(log, "Cannot nest tracing program attach more than once\n");
20809 } else if (tgt_prog->type == prog->type) {
20811 * To avoid potential call chain cycles, prevent attaching of a
20812 * program extension to another extension. It's ok to attach
20813 * fentry/fexit to extension program.
20815 bpf_log(log, "Cannot recursively attach\n");
20818 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
20820 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
20821 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
20822 /* Program extensions can extend all program types
20823 * except fentry/fexit. The reason is the following.
20824 * The fentry/fexit programs are used for performance
20825 * analysis, stats and can be attached to any program
20826 * type. When extension program is replacing XDP function
20827 * it is necessary to allow performance analysis of all
20828 * functions. Both original XDP program and its program
20829 * extension. Hence attaching fentry/fexit to
20830 * BPF_PROG_TYPE_EXT is allowed. If extending of
20831 * fentry/fexit was allowed it would be possible to create
20832 * long call chain fentry->extension->fentry->extension
20833 * beyond reasonable stack size. Hence extending fentry
20836 bpf_log(log, "Cannot extend fentry/fexit\n");
20840 if (prog_extension) {
20841 bpf_log(log, "Cannot replace kernel functions\n");
20846 switch (prog->expected_attach_type) {
20847 case BPF_TRACE_RAW_TP:
20850 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
20853 if (!btf_type_is_typedef(t)) {
20854 bpf_log(log, "attach_btf_id %u is not a typedef\n",
20858 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
20859 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
20863 tname += sizeof(prefix) - 1;
20864 t = btf_type_by_id(btf, t->type);
20865 if (!btf_type_is_ptr(t))
20866 /* should never happen in valid vmlinux build */
20868 t = btf_type_by_id(btf, t->type);
20869 if (!btf_type_is_func_proto(t))
20870 /* should never happen in valid vmlinux build */
20874 case BPF_TRACE_ITER:
20875 if (!btf_type_is_func(t)) {
20876 bpf_log(log, "attach_btf_id %u is not a function\n",
20880 t = btf_type_by_id(btf, t->type);
20881 if (!btf_type_is_func_proto(t))
20883 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20888 if (!prog_extension)
20891 case BPF_MODIFY_RETURN:
20893 case BPF_LSM_CGROUP:
20894 case BPF_TRACE_FENTRY:
20895 case BPF_TRACE_FEXIT:
20896 if (!btf_type_is_func(t)) {
20897 bpf_log(log, "attach_btf_id %u is not a function\n",
20901 if (prog_extension &&
20902 btf_check_type_match(log, prog, btf, t))
20904 t = btf_type_by_id(btf, t->type);
20905 if (!btf_type_is_func_proto(t))
20908 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
20909 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
20910 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
20913 if (tgt_prog && conservative)
20916 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20922 addr = (long) tgt_prog->bpf_func;
20924 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20926 if (btf_is_module(btf)) {
20927 mod = btf_try_get_module(btf);
20929 addr = find_kallsyms_symbol_value(mod, tname);
20933 addr = kallsyms_lookup_name(tname);
20938 "The address of function %s cannot be found\n",
20944 if (prog->sleepable) {
20946 switch (prog->type) {
20947 case BPF_PROG_TYPE_TRACING:
20949 /* fentry/fexit/fmod_ret progs can be sleepable if they are
20950 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20952 if (!check_non_sleepable_error_inject(btf_id) &&
20953 within_error_injection_list(addr))
20955 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
20956 * in the fmodret id set with the KF_SLEEPABLE flag.
20959 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20962 if (flags && (*flags & KF_SLEEPABLE))
20966 case BPF_PROG_TYPE_LSM:
20967 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
20968 * Only some of them are sleepable.
20970 if (bpf_lsm_is_sleepable_hook(btf_id))
20978 bpf_log(log, "%s is not sleepable\n", tname);
20981 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20984 bpf_log(log, "can't modify return codes of BPF programs\n");
20988 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20989 !check_attach_modify_return(addr, tname))
20993 bpf_log(log, "%s() is not modifiable\n", tname);
21000 tgt_info->tgt_addr = addr;
21001 tgt_info->tgt_name = tname;
21002 tgt_info->tgt_type = t;
21003 tgt_info->tgt_mod = mod;
21007 BTF_SET_START(btf_id_deny)
21010 BTF_ID(func, migrate_disable)
21011 BTF_ID(func, migrate_enable)
21013 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
21014 BTF_ID(func, rcu_read_unlock_strict)
21016 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
21017 BTF_ID(func, preempt_count_add)
21018 BTF_ID(func, preempt_count_sub)
21020 #ifdef CONFIG_PREEMPT_RCU
21021 BTF_ID(func, __rcu_read_lock)
21022 BTF_ID(func, __rcu_read_unlock)
21024 BTF_SET_END(btf_id_deny)
21026 static bool can_be_sleepable(struct bpf_prog *prog)
21028 if (prog->type == BPF_PROG_TYPE_TRACING) {
21029 switch (prog->expected_attach_type) {
21030 case BPF_TRACE_FENTRY:
21031 case BPF_TRACE_FEXIT:
21032 case BPF_MODIFY_RETURN:
21033 case BPF_TRACE_ITER:
21039 return prog->type == BPF_PROG_TYPE_LSM ||
21040 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
21041 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
21044 static int check_attach_btf_id(struct bpf_verifier_env *env)
21046 struct bpf_prog *prog = env->prog;
21047 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
21048 struct bpf_attach_target_info tgt_info = {};
21049 u32 btf_id = prog->aux->attach_btf_id;
21050 struct bpf_trampoline *tr;
21054 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
21055 if (prog->sleepable)
21056 /* attach_btf_id checked to be zero already */
21058 verbose(env, "Syscall programs can only be sleepable\n");
21062 if (prog->sleepable && !can_be_sleepable(prog)) {
21063 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
21067 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
21068 return check_struct_ops_btf_id(env);
21070 if (prog->type != BPF_PROG_TYPE_TRACING &&
21071 prog->type != BPF_PROG_TYPE_LSM &&
21072 prog->type != BPF_PROG_TYPE_EXT)
21075 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
21079 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
21080 /* to make freplace equivalent to their targets, they need to
21081 * inherit env->ops and expected_attach_type for the rest of the
21084 env->ops = bpf_verifier_ops[tgt_prog->type];
21085 prog->expected_attach_type = tgt_prog->expected_attach_type;
21088 /* store info about the attachment target that will be used later */
21089 prog->aux->attach_func_proto = tgt_info.tgt_type;
21090 prog->aux->attach_func_name = tgt_info.tgt_name;
21091 prog->aux->mod = tgt_info.tgt_mod;
21094 prog->aux->saved_dst_prog_type = tgt_prog->type;
21095 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
21098 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
21099 prog->aux->attach_btf_trace = true;
21101 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
21102 if (!bpf_iter_prog_supported(prog))
21107 if (prog->type == BPF_PROG_TYPE_LSM) {
21108 ret = bpf_lsm_verify_prog(&env->log, prog);
21111 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
21112 btf_id_set_contains(&btf_id_deny, btf_id)) {
21116 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
21117 tr = bpf_trampoline_get(key, &tgt_info);
21121 if (tgt_prog && tgt_prog->aux->tail_call_reachable)
21122 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
21124 prog->aux->dst_trampoline = tr;
21128 struct btf *bpf_get_btf_vmlinux(void)
21130 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
21131 mutex_lock(&bpf_verifier_lock);
21133 btf_vmlinux = btf_parse_vmlinux();
21134 mutex_unlock(&bpf_verifier_lock);
21136 return btf_vmlinux;
21139 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
21141 u64 start_time = ktime_get_ns();
21142 struct bpf_verifier_env *env;
21143 int i, len, ret = -EINVAL, err;
21147 /* no program is valid */
21148 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
21151 /* 'struct bpf_verifier_env' can be global, but since it's not small,
21152 * allocate/free it every time bpf_check() is called
21154 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
21160 len = (*prog)->len;
21161 env->insn_aux_data =
21162 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
21164 if (!env->insn_aux_data)
21166 for (i = 0; i < len; i++)
21167 env->insn_aux_data[i].orig_idx = i;
21169 env->ops = bpf_verifier_ops[env->prog->type];
21170 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
21172 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
21173 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
21174 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
21175 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
21176 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
21178 bpf_get_btf_vmlinux();
21180 /* grab the mutex to protect few globals used by verifier */
21182 mutex_lock(&bpf_verifier_lock);
21184 /* user could have requested verbose verifier output
21185 * and supplied buffer to store the verification trace
21187 ret = bpf_vlog_init(&env->log, attr->log_level,
21188 (char __user *) (unsigned long) attr->log_buf,
21193 mark_verifier_state_clean(env);
21195 if (IS_ERR(btf_vmlinux)) {
21196 /* Either gcc or pahole or kernel are broken. */
21197 verbose(env, "in-kernel BTF is malformed\n");
21198 ret = PTR_ERR(btf_vmlinux);
21199 goto skip_full_check;
21202 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
21203 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
21204 env->strict_alignment = true;
21205 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
21206 env->strict_alignment = false;
21209 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
21210 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
21212 env->explored_states = kvcalloc(state_htab_size(env),
21213 sizeof(struct bpf_verifier_state_list *),
21216 if (!env->explored_states)
21217 goto skip_full_check;
21219 ret = check_btf_info_early(env, attr, uattr);
21221 goto skip_full_check;
21223 ret = add_subprog_and_kfunc(env);
21225 goto skip_full_check;
21227 ret = check_subprogs(env);
21229 goto skip_full_check;
21231 ret = check_btf_info(env, attr, uattr);
21233 goto skip_full_check;
21235 ret = check_attach_btf_id(env);
21237 goto skip_full_check;
21239 ret = resolve_pseudo_ldimm64(env);
21241 goto skip_full_check;
21243 if (bpf_prog_is_offloaded(env->prog->aux)) {
21244 ret = bpf_prog_offload_verifier_prep(env->prog);
21246 goto skip_full_check;
21249 ret = check_cfg(env);
21251 goto skip_full_check;
21253 ret = do_check_main(env);
21254 ret = ret ?: do_check_subprogs(env);
21256 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
21257 ret = bpf_prog_offload_finalize(env);
21260 kvfree(env->explored_states);
21263 ret = check_max_stack_depth(env);
21265 /* instruction rewrites happen after this point */
21267 ret = optimize_bpf_loop(env);
21271 opt_hard_wire_dead_code_branches(env);
21273 ret = opt_remove_dead_code(env);
21275 ret = opt_remove_nops(env);
21278 sanitize_dead_code(env);
21282 /* program is valid, convert *(u32*)(ctx + off) accesses */
21283 ret = convert_ctx_accesses(env);
21286 ret = do_misc_fixups(env);
21288 /* do 32-bit optimization after insn patching has done so those patched
21289 * insns could be handled correctly.
21291 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
21292 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
21293 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
21298 ret = fixup_call_args(env);
21300 env->verification_time = ktime_get_ns() - start_time;
21301 print_verification_stats(env);
21302 env->prog->aux->verified_insns = env->insn_processed;
21304 /* preserve original error even if log finalization is successful */
21305 err = bpf_vlog_finalize(&env->log, &log_true_size);
21309 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
21310 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
21311 &log_true_size, sizeof(log_true_size))) {
21313 goto err_release_maps;
21317 goto err_release_maps;
21319 if (env->used_map_cnt) {
21320 /* if program passed verifier, update used_maps in bpf_prog_info */
21321 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
21322 sizeof(env->used_maps[0]),
21325 if (!env->prog->aux->used_maps) {
21327 goto err_release_maps;
21330 memcpy(env->prog->aux->used_maps, env->used_maps,
21331 sizeof(env->used_maps[0]) * env->used_map_cnt);
21332 env->prog->aux->used_map_cnt = env->used_map_cnt;
21334 if (env->used_btf_cnt) {
21335 /* if program passed verifier, update used_btfs in bpf_prog_aux */
21336 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
21337 sizeof(env->used_btfs[0]),
21339 if (!env->prog->aux->used_btfs) {
21341 goto err_release_maps;
21344 memcpy(env->prog->aux->used_btfs, env->used_btfs,
21345 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
21346 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
21348 if (env->used_map_cnt || env->used_btf_cnt) {
21349 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
21350 * bpf_ld_imm64 instructions
21352 convert_pseudo_ld_imm64(env);
21355 adjust_btf_func(env);
21358 if (!env->prog->aux->used_maps)
21359 /* if we didn't copy map pointers into bpf_prog_info, release
21360 * them now. Otherwise free_used_maps() will release them.
21363 if (!env->prog->aux->used_btfs)
21366 /* extension progs temporarily inherit the attach_type of their targets
21367 for verification purposes, so set it back to zero before returning
21369 if (env->prog->type == BPF_PROG_TYPE_EXT)
21370 env->prog->expected_attach_type = 0;
21374 module_put(env->attach_btf_mod);
21377 mutex_unlock(&bpf_verifier_lock);
21378 vfree(env->insn_aux_data);