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>
31 #include <linux/trace_events.h>
32 #include <linux/kallsyms.h>
36 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
37 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
38 [_id] = & _name ## _verifier_ops,
39 #define BPF_MAP_TYPE(_id, _ops)
40 #define BPF_LINK_TYPE(_id, _name)
41 #include <linux/bpf_types.h>
47 struct bpf_mem_alloc bpf_global_percpu_ma;
48 static bool bpf_global_percpu_ma_set;
50 /* bpf_check() is a static code analyzer that walks eBPF program
51 * instruction by instruction and updates register/stack state.
52 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
54 * The first pass is depth-first-search to check that the program is a DAG.
55 * It rejects the following programs:
56 * - larger than BPF_MAXINSNS insns
57 * - if loop is present (detected via back-edge)
58 * - unreachable insns exist (shouldn't be a forest. program = one function)
59 * - out of bounds or malformed jumps
60 * The second pass is all possible path descent from the 1st insn.
61 * Since it's analyzing all paths through the program, the length of the
62 * analysis is limited to 64k insn, which may be hit even if total number of
63 * insn is less then 4K, but there are too many branches that change stack/regs.
64 * Number of 'branches to be analyzed' is limited to 1k
66 * On entry to each instruction, each register has a type, and the instruction
67 * changes the types of the registers depending on instruction semantics.
68 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
71 * All registers are 64-bit.
72 * R0 - return register
73 * R1-R5 argument passing registers
74 * R6-R9 callee saved registers
75 * R10 - frame pointer read-only
77 * At the start of BPF program the register R1 contains a pointer to bpf_context
78 * and has type PTR_TO_CTX.
80 * Verifier tracks arithmetic operations on pointers in case:
81 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
82 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
83 * 1st insn copies R10 (which has FRAME_PTR) type into R1
84 * and 2nd arithmetic instruction is pattern matched to recognize
85 * that it wants to construct a pointer to some element within stack.
86 * So after 2nd insn, the register R1 has type PTR_TO_STACK
87 * (and -20 constant is saved for further stack bounds checking).
88 * Meaning that this reg is a pointer to stack plus known immediate constant.
90 * Most of the time the registers have SCALAR_VALUE type, which
91 * means the register has some value, but it's not a valid pointer.
92 * (like pointer plus pointer becomes SCALAR_VALUE type)
94 * When verifier sees load or store instructions the type of base register
95 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
96 * four pointer types recognized by check_mem_access() function.
98 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
99 * and the range of [ptr, ptr + map's value_size) is accessible.
101 * registers used to pass values to function calls are checked against
102 * function argument constraints.
104 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
105 * It means that the register type passed to this function must be
106 * PTR_TO_STACK and it will be used inside the function as
107 * 'pointer to map element key'
109 * For example the argument constraints for bpf_map_lookup_elem():
110 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
111 * .arg1_type = ARG_CONST_MAP_PTR,
112 * .arg2_type = ARG_PTR_TO_MAP_KEY,
114 * ret_type says that this function returns 'pointer to map elem value or null'
115 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
116 * 2nd argument should be a pointer to stack, which will be used inside
117 * the helper function as a pointer to map element key.
119 * On the kernel side the helper function looks like:
120 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
122 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
123 * void *key = (void *) (unsigned long) r2;
126 * here kernel can access 'key' and 'map' pointers safely, knowing that
127 * [key, key + map->key_size) bytes are valid and were initialized on
128 * the stack of eBPF program.
131 * Corresponding eBPF program may look like:
132 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
133 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
134 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
135 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
136 * here verifier looks at prototype of map_lookup_elem() and sees:
137 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
138 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
140 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
141 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
142 * and were initialized prior to this call.
143 * If it's ok, then verifier allows this BPF_CALL insn and looks at
144 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
145 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
146 * returns either pointer to map value or NULL.
148 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
149 * insn, the register holding that pointer in the true branch changes state to
150 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
151 * branch. See check_cond_jmp_op().
153 * After the call R0 is set to return type of the function and registers R1-R5
154 * are set to NOT_INIT to indicate that they are no longer readable.
156 * The following reference types represent a potential reference to a kernel
157 * resource which, after first being allocated, must be checked and freed by
159 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
161 * When the verifier sees a helper call return a reference type, it allocates a
162 * pointer id for the reference and stores it in the current function state.
163 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
164 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
165 * passes through a NULL-check conditional. For the branch wherein the state is
166 * changed to CONST_IMM, the verifier releases the reference.
168 * For each helper function that allocates a reference, such as
169 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
170 * bpf_sk_release(). When a reference type passes into the release function,
171 * the verifier also releases the reference. If any unchecked or unreleased
172 * reference remains at the end of the program, the verifier rejects it.
175 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
176 struct bpf_verifier_stack_elem {
177 /* verifier state is 'st'
178 * before processing instruction 'insn_idx'
179 * and after processing instruction 'prev_insn_idx'
181 struct bpf_verifier_state st;
184 struct bpf_verifier_stack_elem *next;
185 /* length of verifier log at the time this state was pushed on stack */
189 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
190 #define BPF_COMPLEXITY_LIMIT_STATES 64
192 #define BPF_MAP_KEY_POISON (1ULL << 63)
193 #define BPF_MAP_KEY_SEEN (1ULL << 62)
195 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE 512
197 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
198 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
199 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
200 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
201 static int ref_set_non_owning(struct bpf_verifier_env *env,
202 struct bpf_reg_state *reg);
203 static void specialize_kfunc(struct bpf_verifier_env *env,
204 u32 func_id, u16 offset, unsigned long *addr);
205 static bool is_trusted_reg(const struct bpf_reg_state *reg);
207 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
209 return aux->map_ptr_state.poison;
212 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
214 return aux->map_ptr_state.unpriv;
217 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
219 bool unpriv, bool poison)
221 unpriv |= bpf_map_ptr_unpriv(aux);
222 aux->map_ptr_state.unpriv = unpriv;
223 aux->map_ptr_state.poison = poison;
224 aux->map_ptr_state.map_ptr = map;
227 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
229 return aux->map_key_state & BPF_MAP_KEY_POISON;
232 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
234 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
237 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
239 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
242 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
244 bool poisoned = bpf_map_key_poisoned(aux);
246 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
247 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
250 static bool bpf_helper_call(const struct bpf_insn *insn)
252 return insn->code == (BPF_JMP | BPF_CALL) &&
256 static bool bpf_pseudo_call(const struct bpf_insn *insn)
258 return insn->code == (BPF_JMP | BPF_CALL) &&
259 insn->src_reg == BPF_PSEUDO_CALL;
262 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
264 return insn->code == (BPF_JMP | BPF_CALL) &&
265 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
268 struct bpf_call_arg_meta {
269 struct bpf_map *map_ptr;
286 struct btf_field *kptr_field;
289 struct bpf_kfunc_call_arg_meta {
294 const struct btf_type *func_proto;
295 const char *func_name;
308 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
309 * generally to pass info about user-defined local kptr types to later
311 * bpf_obj_drop/bpf_percpu_obj_drop
312 * Record the local kptr type to be drop'd
313 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
314 * Record the local kptr type to be refcount_incr'd and use
315 * arg_owning_ref to determine whether refcount_acquire should be
323 struct btf_field *field;
326 struct btf_field *field;
329 enum bpf_dynptr_type type;
332 } initialized_dynptr;
344 struct btf *btf_vmlinux;
346 static const char *btf_type_name(const struct btf *btf, u32 id)
348 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
351 static DEFINE_MUTEX(bpf_verifier_lock);
352 static DEFINE_MUTEX(bpf_percpu_ma_lock);
354 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
356 struct bpf_verifier_env *env = private_data;
359 if (!bpf_verifier_log_needed(&env->log))
363 bpf_verifier_vlog(&env->log, fmt, args);
367 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
368 struct bpf_reg_state *reg,
369 struct bpf_retval_range range, const char *ctx,
370 const char *reg_name)
374 verbose(env, "%s the register %s has", ctx, reg_name);
375 if (reg->smin_value > S64_MIN) {
376 verbose(env, " smin=%lld", reg->smin_value);
379 if (reg->smax_value < S64_MAX) {
380 verbose(env, " smax=%lld", reg->smax_value);
384 verbose(env, " unknown scalar value");
385 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
388 static bool reg_not_null(const struct bpf_reg_state *reg)
390 enum bpf_reg_type type;
393 if (type_may_be_null(type))
396 type = base_type(type);
397 return type == PTR_TO_SOCKET ||
398 type == PTR_TO_TCP_SOCK ||
399 type == PTR_TO_MAP_VALUE ||
400 type == PTR_TO_MAP_KEY ||
401 type == PTR_TO_SOCK_COMMON ||
402 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
406 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
408 struct btf_record *rec = NULL;
409 struct btf_struct_meta *meta;
411 if (reg->type == PTR_TO_MAP_VALUE) {
412 rec = reg->map_ptr->record;
413 } else if (type_is_ptr_alloc_obj(reg->type)) {
414 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
421 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
423 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
425 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
428 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
430 struct bpf_func_info *info;
432 if (!env->prog->aux->func_info)
435 info = &env->prog->aux->func_info[subprog];
436 return btf_type_name(env->prog->aux->btf, info->type_id);
439 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
441 struct bpf_subprog_info *info = subprog_info(env, subprog);
444 info->is_async_cb = true;
445 info->is_exception_cb = true;
448 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
450 return subprog_info(env, subprog)->is_exception_cb;
453 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
455 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
458 static bool type_is_rdonly_mem(u32 type)
460 return type & MEM_RDONLY;
463 static bool is_acquire_function(enum bpf_func_id func_id,
464 const struct bpf_map *map)
466 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
468 if (func_id == BPF_FUNC_sk_lookup_tcp ||
469 func_id == BPF_FUNC_sk_lookup_udp ||
470 func_id == BPF_FUNC_skc_lookup_tcp ||
471 func_id == BPF_FUNC_ringbuf_reserve ||
472 func_id == BPF_FUNC_kptr_xchg)
475 if (func_id == BPF_FUNC_map_lookup_elem &&
476 (map_type == BPF_MAP_TYPE_SOCKMAP ||
477 map_type == BPF_MAP_TYPE_SOCKHASH))
483 static bool is_ptr_cast_function(enum bpf_func_id func_id)
485 return func_id == BPF_FUNC_tcp_sock ||
486 func_id == BPF_FUNC_sk_fullsock ||
487 func_id == BPF_FUNC_skc_to_tcp_sock ||
488 func_id == BPF_FUNC_skc_to_tcp6_sock ||
489 func_id == BPF_FUNC_skc_to_udp6_sock ||
490 func_id == BPF_FUNC_skc_to_mptcp_sock ||
491 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
492 func_id == BPF_FUNC_skc_to_tcp_request_sock;
495 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
497 return func_id == BPF_FUNC_dynptr_data;
500 static bool is_sync_callback_calling_kfunc(u32 btf_id);
501 static bool is_async_callback_calling_kfunc(u32 btf_id);
502 static bool is_callback_calling_kfunc(u32 btf_id);
503 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
505 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id);
507 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
509 return func_id == BPF_FUNC_for_each_map_elem ||
510 func_id == BPF_FUNC_find_vma ||
511 func_id == BPF_FUNC_loop ||
512 func_id == BPF_FUNC_user_ringbuf_drain;
515 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
517 return func_id == BPF_FUNC_timer_set_callback;
520 static bool is_callback_calling_function(enum bpf_func_id func_id)
522 return is_sync_callback_calling_function(func_id) ||
523 is_async_callback_calling_function(func_id);
526 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
528 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
529 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
532 static bool is_async_callback_calling_insn(struct bpf_insn *insn)
534 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
535 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
538 static bool is_may_goto_insn(struct bpf_insn *insn)
540 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
543 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
545 return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
548 static bool is_storage_get_function(enum bpf_func_id func_id)
550 return func_id == BPF_FUNC_sk_storage_get ||
551 func_id == BPF_FUNC_inode_storage_get ||
552 func_id == BPF_FUNC_task_storage_get ||
553 func_id == BPF_FUNC_cgrp_storage_get;
556 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
557 const struct bpf_map *map)
559 int ref_obj_uses = 0;
561 if (is_ptr_cast_function(func_id))
563 if (is_acquire_function(func_id, map))
565 if (is_dynptr_ref_function(func_id))
568 return ref_obj_uses > 1;
571 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
573 return BPF_CLASS(insn->code) == BPF_STX &&
574 BPF_MODE(insn->code) == BPF_ATOMIC &&
575 insn->imm == BPF_CMPXCHG;
578 static int __get_spi(s32 off)
580 return (-off - 1) / BPF_REG_SIZE;
583 static struct bpf_func_state *func(struct bpf_verifier_env *env,
584 const struct bpf_reg_state *reg)
586 struct bpf_verifier_state *cur = env->cur_state;
588 return cur->frame[reg->frameno];
591 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
593 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
595 /* We need to check that slots between [spi - nr_slots + 1, spi] are
596 * within [0, allocated_stack).
598 * Please note that the spi grows downwards. For example, a dynptr
599 * takes the size of two stack slots; the first slot will be at
600 * spi and the second slot will be at spi - 1.
602 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
605 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
606 const char *obj_kind, int nr_slots)
610 if (!tnum_is_const(reg->var_off)) {
611 verbose(env, "%s has to be at a constant offset\n", obj_kind);
615 off = reg->off + reg->var_off.value;
616 if (off % BPF_REG_SIZE) {
617 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
621 spi = __get_spi(off);
622 if (spi + 1 < nr_slots) {
623 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
627 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
632 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
634 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
637 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
639 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
642 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
644 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
645 case DYNPTR_TYPE_LOCAL:
646 return BPF_DYNPTR_TYPE_LOCAL;
647 case DYNPTR_TYPE_RINGBUF:
648 return BPF_DYNPTR_TYPE_RINGBUF;
649 case DYNPTR_TYPE_SKB:
650 return BPF_DYNPTR_TYPE_SKB;
651 case DYNPTR_TYPE_XDP:
652 return BPF_DYNPTR_TYPE_XDP;
654 return BPF_DYNPTR_TYPE_INVALID;
658 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
661 case BPF_DYNPTR_TYPE_LOCAL:
662 return DYNPTR_TYPE_LOCAL;
663 case BPF_DYNPTR_TYPE_RINGBUF:
664 return DYNPTR_TYPE_RINGBUF;
665 case BPF_DYNPTR_TYPE_SKB:
666 return DYNPTR_TYPE_SKB;
667 case BPF_DYNPTR_TYPE_XDP:
668 return DYNPTR_TYPE_XDP;
674 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
676 return type == BPF_DYNPTR_TYPE_RINGBUF;
679 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
680 enum bpf_dynptr_type type,
681 bool first_slot, int dynptr_id);
683 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
684 struct bpf_reg_state *reg);
686 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
687 struct bpf_reg_state *sreg1,
688 struct bpf_reg_state *sreg2,
689 enum bpf_dynptr_type type)
691 int id = ++env->id_gen;
693 __mark_dynptr_reg(sreg1, type, true, id);
694 __mark_dynptr_reg(sreg2, type, false, id);
697 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
698 struct bpf_reg_state *reg,
699 enum bpf_dynptr_type type)
701 __mark_dynptr_reg(reg, type, true, ++env->id_gen);
704 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
705 struct bpf_func_state *state, int spi);
707 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
708 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
710 struct bpf_func_state *state = func(env, reg);
711 enum bpf_dynptr_type type;
714 spi = dynptr_get_spi(env, reg);
718 /* We cannot assume both spi and spi - 1 belong to the same dynptr,
719 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
720 * to ensure that for the following example:
723 * So marking spi = 2 should lead to destruction of both d1 and d2. In
724 * case they do belong to same dynptr, second call won't see slot_type
725 * as STACK_DYNPTR and will simply skip destruction.
727 err = destroy_if_dynptr_stack_slot(env, state, spi);
730 err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
734 for (i = 0; i < BPF_REG_SIZE; i++) {
735 state->stack[spi].slot_type[i] = STACK_DYNPTR;
736 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
739 type = arg_to_dynptr_type(arg_type);
740 if (type == BPF_DYNPTR_TYPE_INVALID)
743 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
744 &state->stack[spi - 1].spilled_ptr, type);
746 if (dynptr_type_refcounted(type)) {
747 /* The id is used to track proper releasing */
750 if (clone_ref_obj_id)
751 id = clone_ref_obj_id;
753 id = acquire_reference_state(env, insn_idx);
758 state->stack[spi].spilled_ptr.ref_obj_id = id;
759 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
762 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
763 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
768 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
772 for (i = 0; i < BPF_REG_SIZE; i++) {
773 state->stack[spi].slot_type[i] = STACK_INVALID;
774 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
777 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
778 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
780 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
782 * While we don't allow reading STACK_INVALID, it is still possible to
783 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
784 * helpers or insns can do partial read of that part without failing,
785 * but check_stack_range_initialized, check_stack_read_var_off, and
786 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
787 * the slot conservatively. Hence we need to prevent those liveness
790 * This was not a problem before because STACK_INVALID is only set by
791 * default (where the default reg state has its reg->parent as NULL), or
792 * in clean_live_states after REG_LIVE_DONE (at which point
793 * mark_reg_read won't walk reg->parent chain), but not randomly during
794 * verifier state exploration (like we did above). Hence, for our case
795 * parentage chain will still be live (i.e. reg->parent may be
796 * non-NULL), while earlier reg->parent was NULL, so we need
797 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
798 * done later on reads or by mark_dynptr_read as well to unnecessary
799 * mark registers in verifier state.
801 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
802 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
805 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
807 struct bpf_func_state *state = func(env, reg);
808 int spi, ref_obj_id, i;
810 spi = dynptr_get_spi(env, reg);
814 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
815 invalidate_dynptr(env, state, spi);
819 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
821 /* If the dynptr has a ref_obj_id, then we need to invalidate
824 * 1) Any dynptrs with a matching ref_obj_id (clones)
825 * 2) Any slices derived from this dynptr.
828 /* Invalidate any slices associated with this dynptr */
829 WARN_ON_ONCE(release_reference(env, ref_obj_id));
831 /* Invalidate any dynptr clones */
832 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
833 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
836 /* it should always be the case that if the ref obj id
837 * matches then the stack slot also belongs to a
840 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
841 verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
844 if (state->stack[i].spilled_ptr.dynptr.first_slot)
845 invalidate_dynptr(env, state, i);
851 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
852 struct bpf_reg_state *reg);
854 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
856 if (!env->allow_ptr_leaks)
857 __mark_reg_not_init(env, reg);
859 __mark_reg_unknown(env, reg);
862 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
863 struct bpf_func_state *state, int spi)
865 struct bpf_func_state *fstate;
866 struct bpf_reg_state *dreg;
869 /* We always ensure that STACK_DYNPTR is never set partially,
870 * hence just checking for slot_type[0] is enough. This is
871 * different for STACK_SPILL, where it may be only set for
872 * 1 byte, so code has to use is_spilled_reg.
874 if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
877 /* Reposition spi to first slot */
878 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
881 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
882 verbose(env, "cannot overwrite referenced dynptr\n");
886 mark_stack_slot_scratched(env, spi);
887 mark_stack_slot_scratched(env, spi - 1);
889 /* Writing partially to one dynptr stack slot destroys both. */
890 for (i = 0; i < BPF_REG_SIZE; i++) {
891 state->stack[spi].slot_type[i] = STACK_INVALID;
892 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
895 dynptr_id = state->stack[spi].spilled_ptr.id;
896 /* Invalidate any slices associated with this dynptr */
897 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
898 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
899 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
901 if (dreg->dynptr_id == dynptr_id)
902 mark_reg_invalid(env, dreg);
905 /* Do not release reference state, we are destroying dynptr on stack,
906 * not using some helper to release it. Just reset register.
908 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
909 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
911 /* Same reason as unmark_stack_slots_dynptr above */
912 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
913 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
918 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
922 if (reg->type == CONST_PTR_TO_DYNPTR)
925 spi = dynptr_get_spi(env, reg);
927 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
928 * error because this just means the stack state hasn't been updated yet.
929 * We will do check_mem_access to check and update stack bounds later.
931 if (spi < 0 && spi != -ERANGE)
934 /* We don't need to check if the stack slots are marked by previous
935 * dynptr initializations because we allow overwriting existing unreferenced
936 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
937 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
938 * touching are completely destructed before we reinitialize them for a new
939 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
940 * instead of delaying it until the end where the user will get "Unreleased
946 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
948 struct bpf_func_state *state = func(env, reg);
951 /* This already represents first slot of initialized bpf_dynptr.
953 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
954 * check_func_arg_reg_off's logic, so we don't need to check its
955 * offset and alignment.
957 if (reg->type == CONST_PTR_TO_DYNPTR)
960 spi = dynptr_get_spi(env, reg);
963 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
966 for (i = 0; i < BPF_REG_SIZE; i++) {
967 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
968 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
975 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
976 enum bpf_arg_type arg_type)
978 struct bpf_func_state *state = func(env, reg);
979 enum bpf_dynptr_type dynptr_type;
982 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
983 if (arg_type == ARG_PTR_TO_DYNPTR)
986 dynptr_type = arg_to_dynptr_type(arg_type);
987 if (reg->type == CONST_PTR_TO_DYNPTR) {
988 return reg->dynptr.type == dynptr_type;
990 spi = dynptr_get_spi(env, reg);
993 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
997 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
999 static bool in_rcu_cs(struct bpf_verifier_env *env);
1001 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1003 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1004 struct bpf_kfunc_call_arg_meta *meta,
1005 struct bpf_reg_state *reg, int insn_idx,
1006 struct btf *btf, u32 btf_id, int nr_slots)
1008 struct bpf_func_state *state = func(env, reg);
1011 spi = iter_get_spi(env, reg, nr_slots);
1015 id = acquire_reference_state(env, insn_idx);
1019 for (i = 0; i < nr_slots; i++) {
1020 struct bpf_stack_state *slot = &state->stack[spi - i];
1021 struct bpf_reg_state *st = &slot->spilled_ptr;
1023 __mark_reg_known_zero(st);
1024 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1025 if (is_kfunc_rcu_protected(meta)) {
1027 st->type |= MEM_RCU;
1029 st->type |= PTR_UNTRUSTED;
1031 st->live |= REG_LIVE_WRITTEN;
1032 st->ref_obj_id = i == 0 ? id : 0;
1034 st->iter.btf_id = btf_id;
1035 st->iter.state = BPF_ITER_STATE_ACTIVE;
1038 for (j = 0; j < BPF_REG_SIZE; j++)
1039 slot->slot_type[j] = STACK_ITER;
1041 mark_stack_slot_scratched(env, spi - i);
1047 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1048 struct bpf_reg_state *reg, int nr_slots)
1050 struct bpf_func_state *state = func(env, reg);
1053 spi = iter_get_spi(env, reg, nr_slots);
1057 for (i = 0; i < nr_slots; i++) {
1058 struct bpf_stack_state *slot = &state->stack[spi - i];
1059 struct bpf_reg_state *st = &slot->spilled_ptr;
1062 WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1064 __mark_reg_not_init(env, st);
1066 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1067 st->live |= REG_LIVE_WRITTEN;
1069 for (j = 0; j < BPF_REG_SIZE; j++)
1070 slot->slot_type[j] = STACK_INVALID;
1072 mark_stack_slot_scratched(env, spi - i);
1078 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1079 struct bpf_reg_state *reg, int nr_slots)
1081 struct bpf_func_state *state = func(env, reg);
1084 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1085 * will do check_mem_access to check and update stack bounds later, so
1086 * return true for that case.
1088 spi = iter_get_spi(env, reg, nr_slots);
1094 for (i = 0; i < nr_slots; i++) {
1095 struct bpf_stack_state *slot = &state->stack[spi - i];
1097 for (j = 0; j < BPF_REG_SIZE; j++)
1098 if (slot->slot_type[j] == STACK_ITER)
1105 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1106 struct btf *btf, u32 btf_id, int nr_slots)
1108 struct bpf_func_state *state = func(env, reg);
1111 spi = iter_get_spi(env, reg, nr_slots);
1115 for (i = 0; i < nr_slots; i++) {
1116 struct bpf_stack_state *slot = &state->stack[spi - i];
1117 struct bpf_reg_state *st = &slot->spilled_ptr;
1119 if (st->type & PTR_UNTRUSTED)
1121 /* only main (first) slot has ref_obj_id set */
1122 if (i == 0 && !st->ref_obj_id)
1124 if (i != 0 && st->ref_obj_id)
1126 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1129 for (j = 0; j < BPF_REG_SIZE; j++)
1130 if (slot->slot_type[j] != STACK_ITER)
1137 /* Check if given stack slot is "special":
1138 * - spilled register state (STACK_SPILL);
1139 * - dynptr state (STACK_DYNPTR);
1140 * - iter state (STACK_ITER).
1142 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1144 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1156 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1161 /* The reg state of a pointer or a bounded scalar was saved when
1162 * it was spilled to the stack.
1164 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1166 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1169 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1171 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1172 stack->spilled_ptr.type == SCALAR_VALUE;
1175 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1177 return stack->slot_type[0] == STACK_SPILL &&
1178 stack->spilled_ptr.type == SCALAR_VALUE;
1181 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1182 * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1183 * more precise STACK_ZERO.
1184 * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take
1185 * env->allow_ptr_leaks into account and force STACK_MISC, if necessary.
1187 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1189 if (*stype == STACK_ZERO)
1191 if (env->allow_ptr_leaks && *stype == STACK_INVALID)
1193 *stype = STACK_MISC;
1196 static void scrub_spilled_slot(u8 *stype)
1198 if (*stype != STACK_INVALID)
1199 *stype = STACK_MISC;
1202 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1203 * small to hold src. This is different from krealloc since we don't want to preserve
1204 * the contents of dst.
1206 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1209 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1215 if (ZERO_OR_NULL_PTR(src))
1218 if (unlikely(check_mul_overflow(n, size, &bytes)))
1221 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1222 dst = krealloc(orig, alloc_bytes, flags);
1228 memcpy(dst, src, bytes);
1230 return dst ? dst : ZERO_SIZE_PTR;
1233 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1234 * small to hold new_n items. new items are zeroed out if the array grows.
1236 * Contrary to krealloc_array, does not free arr if new_n is zero.
1238 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1243 if (!new_n || old_n == new_n)
1246 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1247 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1255 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1258 return arr ? arr : ZERO_SIZE_PTR;
1261 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1263 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1264 sizeof(struct bpf_reference_state), GFP_KERNEL);
1268 dst->acquired_refs = src->acquired_refs;
1272 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1274 size_t n = src->allocated_stack / BPF_REG_SIZE;
1276 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1281 dst->allocated_stack = src->allocated_stack;
1285 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1287 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1288 sizeof(struct bpf_reference_state));
1292 state->acquired_refs = n;
1296 /* Possibly update state->allocated_stack to be at least size bytes. Also
1297 * possibly update the function's high-water mark in its bpf_subprog_info.
1299 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1301 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1303 /* The stack size is always a multiple of BPF_REG_SIZE. */
1304 size = round_up(size, BPF_REG_SIZE);
1305 n = size / BPF_REG_SIZE;
1310 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1314 state->allocated_stack = size;
1316 /* update known max for given subprogram */
1317 if (env->subprog_info[state->subprogno].stack_depth < size)
1318 env->subprog_info[state->subprogno].stack_depth = size;
1323 /* Acquire a pointer id from the env and update the state->refs to include
1324 * this new pointer reference.
1325 * On success, returns a valid pointer id to associate with the register
1326 * On failure, returns a negative errno.
1328 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1330 struct bpf_func_state *state = cur_func(env);
1331 int new_ofs = state->acquired_refs;
1334 err = resize_reference_state(state, state->acquired_refs + 1);
1338 state->refs[new_ofs].id = id;
1339 state->refs[new_ofs].insn_idx = insn_idx;
1340 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1345 /* release function corresponding to acquire_reference_state(). Idempotent. */
1346 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1350 last_idx = state->acquired_refs - 1;
1351 for (i = 0; i < state->acquired_refs; i++) {
1352 if (state->refs[i].id == ptr_id) {
1353 /* Cannot release caller references in callbacks */
1354 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1356 if (last_idx && i != last_idx)
1357 memcpy(&state->refs[i], &state->refs[last_idx],
1358 sizeof(*state->refs));
1359 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1360 state->acquired_refs--;
1367 static void free_func_state(struct bpf_func_state *state)
1372 kfree(state->stack);
1376 static void clear_jmp_history(struct bpf_verifier_state *state)
1378 kfree(state->jmp_history);
1379 state->jmp_history = NULL;
1380 state->jmp_history_cnt = 0;
1383 static void free_verifier_state(struct bpf_verifier_state *state,
1388 for (i = 0; i <= state->curframe; i++) {
1389 free_func_state(state->frame[i]);
1390 state->frame[i] = NULL;
1392 clear_jmp_history(state);
1397 /* copy verifier state from src to dst growing dst stack space
1398 * when necessary to accommodate larger src stack
1400 static int copy_func_state(struct bpf_func_state *dst,
1401 const struct bpf_func_state *src)
1405 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1406 err = copy_reference_state(dst, src);
1409 return copy_stack_state(dst, src);
1412 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1413 const struct bpf_verifier_state *src)
1415 struct bpf_func_state *dst;
1418 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1419 src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1421 if (!dst_state->jmp_history)
1423 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1425 /* if dst has more stack frames then src frame, free them, this is also
1426 * necessary in case of exceptional exits using bpf_throw.
1428 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1429 free_func_state(dst_state->frame[i]);
1430 dst_state->frame[i] = NULL;
1432 dst_state->speculative = src->speculative;
1433 dst_state->active_rcu_lock = src->active_rcu_lock;
1434 dst_state->active_preempt_lock = src->active_preempt_lock;
1435 dst_state->in_sleepable = src->in_sleepable;
1436 dst_state->curframe = src->curframe;
1437 dst_state->active_lock.ptr = src->active_lock.ptr;
1438 dst_state->active_lock.id = src->active_lock.id;
1439 dst_state->branches = src->branches;
1440 dst_state->parent = src->parent;
1441 dst_state->first_insn_idx = src->first_insn_idx;
1442 dst_state->last_insn_idx = src->last_insn_idx;
1443 dst_state->dfs_depth = src->dfs_depth;
1444 dst_state->callback_unroll_depth = src->callback_unroll_depth;
1445 dst_state->used_as_loop_entry = src->used_as_loop_entry;
1446 dst_state->may_goto_depth = src->may_goto_depth;
1447 for (i = 0; i <= src->curframe; i++) {
1448 dst = dst_state->frame[i];
1450 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1453 dst_state->frame[i] = dst;
1455 err = copy_func_state(dst, src->frame[i]);
1462 static u32 state_htab_size(struct bpf_verifier_env *env)
1464 return env->prog->len;
1467 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1469 struct bpf_verifier_state *cur = env->cur_state;
1470 struct bpf_func_state *state = cur->frame[cur->curframe];
1472 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1475 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1479 if (a->curframe != b->curframe)
1482 for (fr = a->curframe; fr >= 0; fr--)
1483 if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1489 /* Open coded iterators allow back-edges in the state graph in order to
1490 * check unbounded loops that iterators.
1492 * In is_state_visited() it is necessary to know if explored states are
1493 * part of some loops in order to decide whether non-exact states
1494 * comparison could be used:
1495 * - non-exact states comparison establishes sub-state relation and uses
1496 * read and precision marks to do so, these marks are propagated from
1497 * children states and thus are not guaranteed to be final in a loop;
1498 * - exact states comparison just checks if current and explored states
1499 * are identical (and thus form a back-edge).
1501 * Paper "A New Algorithm for Identifying Loops in Decompilation"
1502 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1503 * algorithm for loop structure detection and gives an overview of
1504 * relevant terminology. It also has helpful illustrations.
1506 * [1] https://api.semanticscholar.org/CorpusID:15784067
1508 * We use a similar algorithm but because loop nested structure is
1509 * irrelevant for verifier ours is significantly simpler and resembles
1510 * strongly connected components algorithm from Sedgewick's textbook.
1512 * Define topmost loop entry as a first node of the loop traversed in a
1513 * depth first search starting from initial state. The goal of the loop
1514 * tracking algorithm is to associate topmost loop entries with states
1515 * derived from these entries.
1517 * For each step in the DFS states traversal algorithm needs to identify
1518 * the following situations:
1520 * initial initial initial
1523 * ... ... .---------> hdr
1526 * cur .-> succ | .------...
1529 * succ '-- cur | ... ...
1539 * (A) successor state of cur (B) successor state of cur or it's entry
1540 * not yet traversed are in current DFS path, thus cur and succ
1541 * are members of the same outermost loop
1549 * .------... .------...
1552 * .-> hdr ... ... ...
1555 * | succ <- cur succ <- cur
1562 * (C) successor state of cur is a part of some loop but this loop
1563 * does not include cur or successor state is not in a loop at all.
1565 * Algorithm could be described as the following python code:
1567 * traversed = set() # Set of traversed nodes
1568 * entries = {} # Mapping from node to loop entry
1569 * depths = {} # Depth level assigned to graph node
1570 * path = set() # Current DFS path
1572 * # Find outermost loop entry known for n
1573 * def get_loop_entry(n):
1574 * h = entries.get(n, None)
1575 * while h in entries and entries[h] != h:
1579 * # Update n's loop entry if h's outermost entry comes
1580 * # before n's outermost entry in current DFS path.
1581 * def update_loop_entry(n, h):
1582 * n1 = get_loop_entry(n) or n
1583 * h1 = get_loop_entry(h) or h
1584 * if h1 in path and depths[h1] <= depths[n1]:
1587 * def dfs(n, depth):
1591 * for succ in G.successors(n):
1592 * if succ not in traversed:
1593 * # Case A: explore succ and update cur's loop entry
1594 * # only if succ's entry is in current DFS path.
1595 * dfs(succ, depth + 1)
1596 * h = get_loop_entry(succ)
1597 * update_loop_entry(n, h)
1599 * # Case B or C depending on `h1 in path` check in update_loop_entry().
1600 * update_loop_entry(n, succ)
1603 * To adapt this algorithm for use with verifier:
1604 * - use st->branch == 0 as a signal that DFS of succ had been finished
1605 * and cur's loop entry has to be updated (case A), handle this in
1606 * update_branch_counts();
1607 * - use st->branch > 0 as a signal that st is in the current DFS path;
1608 * - handle cases B and C in is_state_visited();
1609 * - update topmost loop entry for intermediate states in get_loop_entry().
1611 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1613 struct bpf_verifier_state *topmost = st->loop_entry, *old;
1615 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1616 topmost = topmost->loop_entry;
1617 /* Update loop entries for intermediate states to avoid this
1618 * traversal in future get_loop_entry() calls.
1620 while (st && st->loop_entry != topmost) {
1621 old = st->loop_entry;
1622 st->loop_entry = topmost;
1628 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1630 struct bpf_verifier_state *cur1, *hdr1;
1632 cur1 = get_loop_entry(cur) ?: cur;
1633 hdr1 = get_loop_entry(hdr) ?: hdr;
1634 /* The head1->branches check decides between cases B and C in
1635 * comment for get_loop_entry(). If hdr1->branches == 0 then
1636 * head's topmost loop entry is not in current DFS path,
1637 * hence 'cur' and 'hdr' are not in the same loop and there is
1638 * no need to update cur->loop_entry.
1640 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1641 cur->loop_entry = hdr;
1642 hdr->used_as_loop_entry = true;
1646 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1649 u32 br = --st->branches;
1651 /* br == 0 signals that DFS exploration for 'st' is finished,
1652 * thus it is necessary to update parent's loop entry if it
1653 * turned out that st is a part of some loop.
1654 * This is a part of 'case A' in get_loop_entry() comment.
1656 if (br == 0 && st->parent && st->loop_entry)
1657 update_loop_entry(st->parent, st->loop_entry);
1659 /* WARN_ON(br > 1) technically makes sense here,
1660 * but see comment in push_stack(), hence:
1662 WARN_ONCE((int)br < 0,
1663 "BUG update_branch_counts:branches_to_explore=%d\n",
1671 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1672 int *insn_idx, bool pop_log)
1674 struct bpf_verifier_state *cur = env->cur_state;
1675 struct bpf_verifier_stack_elem *elem, *head = env->head;
1678 if (env->head == NULL)
1682 err = copy_verifier_state(cur, &head->st);
1687 bpf_vlog_reset(&env->log, head->log_pos);
1689 *insn_idx = head->insn_idx;
1691 *prev_insn_idx = head->prev_insn_idx;
1693 free_verifier_state(&head->st, false);
1700 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1701 int insn_idx, int prev_insn_idx,
1704 struct bpf_verifier_state *cur = env->cur_state;
1705 struct bpf_verifier_stack_elem *elem;
1708 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1712 elem->insn_idx = insn_idx;
1713 elem->prev_insn_idx = prev_insn_idx;
1714 elem->next = env->head;
1715 elem->log_pos = env->log.end_pos;
1718 err = copy_verifier_state(&elem->st, cur);
1721 elem->st.speculative |= speculative;
1722 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1723 verbose(env, "The sequence of %d jumps is too complex.\n",
1727 if (elem->st.parent) {
1728 ++elem->st.parent->branches;
1729 /* WARN_ON(branches > 2) technically makes sense here,
1731 * 1. speculative states will bump 'branches' for non-branch
1733 * 2. is_state_visited() heuristics may decide not to create
1734 * a new state for a sequence of branches and all such current
1735 * and cloned states will be pointing to a single parent state
1736 * which might have large 'branches' count.
1741 free_verifier_state(env->cur_state, true);
1742 env->cur_state = NULL;
1743 /* pop all elements and return */
1744 while (!pop_stack(env, NULL, NULL, false));
1748 #define CALLER_SAVED_REGS 6
1749 static const int caller_saved[CALLER_SAVED_REGS] = {
1750 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1753 /* This helper doesn't clear reg->id */
1754 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1756 reg->var_off = tnum_const(imm);
1757 reg->smin_value = (s64)imm;
1758 reg->smax_value = (s64)imm;
1759 reg->umin_value = imm;
1760 reg->umax_value = imm;
1762 reg->s32_min_value = (s32)imm;
1763 reg->s32_max_value = (s32)imm;
1764 reg->u32_min_value = (u32)imm;
1765 reg->u32_max_value = (u32)imm;
1768 /* Mark the unknown part of a register (variable offset or scalar value) as
1769 * known to have the value @imm.
1771 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1773 /* Clear off and union(map_ptr, range) */
1774 memset(((u8 *)reg) + sizeof(reg->type), 0,
1775 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1777 reg->ref_obj_id = 0;
1778 ___mark_reg_known(reg, imm);
1781 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1783 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1784 reg->s32_min_value = (s32)imm;
1785 reg->s32_max_value = (s32)imm;
1786 reg->u32_min_value = (u32)imm;
1787 reg->u32_max_value = (u32)imm;
1790 /* Mark the 'variable offset' part of a register as zero. This should be
1791 * used only on registers holding a pointer type.
1793 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1795 __mark_reg_known(reg, 0);
1798 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1800 __mark_reg_known(reg, 0);
1801 reg->type = SCALAR_VALUE;
1802 /* all scalars are assumed imprecise initially (unless unprivileged,
1803 * in which case everything is forced to be precise)
1805 reg->precise = !env->bpf_capable;
1808 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1809 struct bpf_reg_state *regs, u32 regno)
1811 if (WARN_ON(regno >= MAX_BPF_REG)) {
1812 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1813 /* Something bad happened, let's kill all regs */
1814 for (regno = 0; regno < MAX_BPF_REG; regno++)
1815 __mark_reg_not_init(env, regs + regno);
1818 __mark_reg_known_zero(regs + regno);
1821 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1822 bool first_slot, int dynptr_id)
1824 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1825 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1826 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1828 __mark_reg_known_zero(reg);
1829 reg->type = CONST_PTR_TO_DYNPTR;
1830 /* Give each dynptr a unique id to uniquely associate slices to it. */
1831 reg->id = dynptr_id;
1832 reg->dynptr.type = type;
1833 reg->dynptr.first_slot = first_slot;
1836 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1838 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1839 const struct bpf_map *map = reg->map_ptr;
1841 if (map->inner_map_meta) {
1842 reg->type = CONST_PTR_TO_MAP;
1843 reg->map_ptr = map->inner_map_meta;
1844 /* transfer reg's id which is unique for every map_lookup_elem
1845 * as UID of the inner map.
1847 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1848 reg->map_uid = reg->id;
1849 if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE))
1850 reg->map_uid = reg->id;
1851 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1852 reg->type = PTR_TO_XDP_SOCK;
1853 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1854 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1855 reg->type = PTR_TO_SOCKET;
1857 reg->type = PTR_TO_MAP_VALUE;
1862 reg->type &= ~PTR_MAYBE_NULL;
1865 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1866 struct btf_field_graph_root *ds_head)
1868 __mark_reg_known_zero(®s[regno]);
1869 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1870 regs[regno].btf = ds_head->btf;
1871 regs[regno].btf_id = ds_head->value_btf_id;
1872 regs[regno].off = ds_head->node_offset;
1875 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1877 return type_is_pkt_pointer(reg->type);
1880 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1882 return reg_is_pkt_pointer(reg) ||
1883 reg->type == PTR_TO_PACKET_END;
1886 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1888 return base_type(reg->type) == PTR_TO_MEM &&
1889 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1892 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1893 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1894 enum bpf_reg_type which)
1896 /* The register can already have a range from prior markings.
1897 * This is fine as long as it hasn't been advanced from its
1900 return reg->type == which &&
1903 tnum_equals_const(reg->var_off, 0);
1906 /* Reset the min/max bounds of a register */
1907 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1909 reg->smin_value = S64_MIN;
1910 reg->smax_value = S64_MAX;
1911 reg->umin_value = 0;
1912 reg->umax_value = U64_MAX;
1914 reg->s32_min_value = S32_MIN;
1915 reg->s32_max_value = S32_MAX;
1916 reg->u32_min_value = 0;
1917 reg->u32_max_value = U32_MAX;
1920 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1922 reg->smin_value = S64_MIN;
1923 reg->smax_value = S64_MAX;
1924 reg->umin_value = 0;
1925 reg->umax_value = U64_MAX;
1928 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1930 reg->s32_min_value = S32_MIN;
1931 reg->s32_max_value = S32_MAX;
1932 reg->u32_min_value = 0;
1933 reg->u32_max_value = U32_MAX;
1936 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1938 struct tnum var32_off = tnum_subreg(reg->var_off);
1940 /* min signed is max(sign bit) | min(other bits) */
1941 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1942 var32_off.value | (var32_off.mask & S32_MIN));
1943 /* max signed is min(sign bit) | max(other bits) */
1944 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1945 var32_off.value | (var32_off.mask & S32_MAX));
1946 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1947 reg->u32_max_value = min(reg->u32_max_value,
1948 (u32)(var32_off.value | var32_off.mask));
1951 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1953 /* min signed is max(sign bit) | min(other bits) */
1954 reg->smin_value = max_t(s64, reg->smin_value,
1955 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1956 /* max signed is min(sign bit) | max(other bits) */
1957 reg->smax_value = min_t(s64, reg->smax_value,
1958 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1959 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1960 reg->umax_value = min(reg->umax_value,
1961 reg->var_off.value | reg->var_off.mask);
1964 static void __update_reg_bounds(struct bpf_reg_state *reg)
1966 __update_reg32_bounds(reg);
1967 __update_reg64_bounds(reg);
1970 /* Uses signed min/max values to inform unsigned, and vice-versa */
1971 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1973 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32
1974 * bits to improve our u32/s32 boundaries.
1976 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
1977 * u64) is pretty trivial, it's obvious that in u32 we'll also have
1978 * [10, 20] range. But this property holds for any 64-bit range as
1979 * long as upper 32 bits in that entire range of values stay the same.
1981 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
1982 * in decimal) has the same upper 32 bits throughout all the values in
1983 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
1986 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
1987 * following the rules outlined below about u64/s64 correspondence
1988 * (which equally applies to u32 vs s32 correspondence). In general it
1989 * depends on actual hexadecimal values of 32-bit range. They can form
1990 * only valid u32, or only valid s32 ranges in some cases.
1992 * So we use all these insights to derive bounds for subregisters here.
1994 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
1995 /* u64 to u32 casting preserves validity of low 32 bits as
1996 * a range, if upper 32 bits are the same
1998 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
1999 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2001 if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2002 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2003 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2006 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2007 /* low 32 bits should form a proper u32 range */
2008 if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2009 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2010 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2012 /* low 32 bits should form a proper s32 range */
2013 if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2014 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2015 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2018 /* Special case where upper bits form a small sequence of two
2019 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2020 * 0x00000000 is also valid), while lower bits form a proper s32 range
2021 * going from negative numbers to positive numbers. E.g., let's say we
2022 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2023 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2024 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2025 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2026 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2027 * upper 32 bits. As a random example, s64 range
2028 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2029 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2031 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2032 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2033 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2034 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2036 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2037 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2038 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2039 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2041 /* if u32 range forms a valid s32 range (due to matching sign bit),
2042 * try to learn from that
2044 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2045 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2046 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2048 /* If we cannot cross the sign boundary, then signed and unsigned bounds
2049 * are the same, so combine. This works even in the negative case, e.g.
2050 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2052 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2053 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2054 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2058 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2060 /* If u64 range forms a valid s64 range (due to matching sign bit),
2061 * try to learn from that. Let's do a bit of ASCII art to see when
2062 * this is happening. Let's take u64 range first:
2064 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
2065 * |-------------------------------|--------------------------------|
2067 * Valid u64 range is formed when umin and umax are anywhere in the
2068 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2069 * straightforward. Let's see how s64 range maps onto the same range
2070 * of values, annotated below the line for comparison:
2072 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
2073 * |-------------------------------|--------------------------------|
2074 * 0 S64_MAX S64_MIN -1
2076 * So s64 values basically start in the middle and they are logically
2077 * contiguous to the right of it, wrapping around from -1 to 0, and
2078 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2079 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2080 * more visually as mapped to sign-agnostic range of hex values.
2083 * _______________________________________________________________
2085 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
2086 * |-------------------------------|--------------------------------|
2087 * 0 S64_MAX S64_MIN -1
2089 * >------------------------------ ------------------------------->
2090 * s64 continues... s64 end s64 start s64 "midpoint"
2092 * What this means is that, in general, we can't always derive
2093 * something new about u64 from any random s64 range, and vice versa.
2095 * But we can do that in two particular cases. One is when entire
2096 * u64/s64 range is *entirely* contained within left half of the above
2097 * diagram or when it is *entirely* contained in the right half. I.e.:
2099 * |-------------------------------|--------------------------------|
2103 * [A, B] and [C, D] are contained entirely in their respective halves
2104 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2105 * will be non-negative both as u64 and s64 (and in fact it will be
2106 * identical ranges no matter the signedness). [C, D] treated as s64
2107 * will be a range of negative values, while in u64 it will be
2108 * non-negative range of values larger than 0x8000000000000000.
2110 * Now, any other range here can't be represented in both u64 and s64
2111 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2112 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2113 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2114 * for example. Similarly, valid s64 range [D, A] (going from negative
2115 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2116 * ranges as u64. Currently reg_state can't represent two segments per
2117 * numeric domain, so in such situations we can only derive maximal
2118 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2120 * So we use these facts to derive umin/umax from smin/smax and vice
2121 * versa only if they stay within the same "half". This is equivalent
2122 * to checking sign bit: lower half will have sign bit as zero, upper
2123 * half have sign bit 1. Below in code we simplify this by just
2124 * casting umin/umax as smin/smax and checking if they form valid
2125 * range, and vice versa. Those are equivalent checks.
2127 if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2128 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2129 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2131 /* If we cannot cross the sign boundary, then signed and unsigned bounds
2132 * are the same, so combine. This works even in the negative case, e.g.
2133 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2135 if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2136 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2137 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2141 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2143 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2144 * values on both sides of 64-bit range in hope to have tighter range.
2145 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2146 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2147 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2148 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2149 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2150 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2151 * We just need to make sure that derived bounds we are intersecting
2152 * with are well-formed ranges in respective s64 or u64 domain, just
2153 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2155 __u64 new_umin, new_umax;
2156 __s64 new_smin, new_smax;
2158 /* u32 -> u64 tightening, it's always well-formed */
2159 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2160 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2161 reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2162 reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2163 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2164 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2165 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2166 reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2167 reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2169 /* if s32 can be treated as valid u32 range, we can use it as well */
2170 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2171 /* s32 -> u64 tightening */
2172 new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2173 new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2174 reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2175 reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2176 /* s32 -> s64 tightening */
2177 new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2178 new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2179 reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2180 reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2183 /* Here we would like to handle a special case after sign extending load,
2184 * when upper bits for a 64-bit range are all 1s or all 0s.
2186 * Upper bits are all 1s when register is in a range:
2187 * [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
2188 * Upper bits are all 0s when register is in a range:
2189 * [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
2190 * Together this forms are continuous range:
2191 * [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
2193 * Now, suppose that register range is in fact tighter:
2194 * [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
2195 * Also suppose that it's 32-bit range is positive,
2196 * meaning that lower 32-bits of the full 64-bit register
2198 * [0x0000_0000, 0x7fff_ffff] (W)
2200 * If this happens, then any value in a range:
2201 * [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
2202 * is smaller than a lowest bound of the range (R):
2203 * 0xffff_ffff_8000_0000
2204 * which means that upper bits of the full 64-bit register
2205 * can't be all 1s, when lower bits are in range (W).
2208 * - 0xffff_ffff_8000_0000 == (s64)S32_MIN
2209 * - 0x0000_0000_7fff_ffff == (s64)S32_MAX
2210 * These relations are used in the conditions below.
2212 if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
2213 reg->smin_value = reg->s32_min_value;
2214 reg->smax_value = reg->s32_max_value;
2215 reg->umin_value = reg->s32_min_value;
2216 reg->umax_value = reg->s32_max_value;
2217 reg->var_off = tnum_intersect(reg->var_off,
2218 tnum_range(reg->smin_value, reg->smax_value));
2222 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2224 __reg32_deduce_bounds(reg);
2225 __reg64_deduce_bounds(reg);
2226 __reg_deduce_mixed_bounds(reg);
2229 /* Attempts to improve var_off based on unsigned min/max information */
2230 static void __reg_bound_offset(struct bpf_reg_state *reg)
2232 struct tnum var64_off = tnum_intersect(reg->var_off,
2233 tnum_range(reg->umin_value,
2235 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2236 tnum_range(reg->u32_min_value,
2237 reg->u32_max_value));
2239 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2242 static void reg_bounds_sync(struct bpf_reg_state *reg)
2244 /* We might have learned new bounds from the var_off. */
2245 __update_reg_bounds(reg);
2246 /* We might have learned something about the sign bit. */
2247 __reg_deduce_bounds(reg);
2248 __reg_deduce_bounds(reg);
2249 /* We might have learned some bits from the bounds. */
2250 __reg_bound_offset(reg);
2251 /* Intersecting with the old var_off might have improved our bounds
2252 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2253 * then new var_off is (0; 0x7f...fc) which improves our umax.
2255 __update_reg_bounds(reg);
2258 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2259 struct bpf_reg_state *reg, const char *ctx)
2263 if (reg->umin_value > reg->umax_value ||
2264 reg->smin_value > reg->smax_value ||
2265 reg->u32_min_value > reg->u32_max_value ||
2266 reg->s32_min_value > reg->s32_max_value) {
2267 msg = "range bounds violation";
2271 if (tnum_is_const(reg->var_off)) {
2272 u64 uval = reg->var_off.value;
2273 s64 sval = (s64)uval;
2275 if (reg->umin_value != uval || reg->umax_value != uval ||
2276 reg->smin_value != sval || reg->smax_value != sval) {
2277 msg = "const tnum out of sync with range bounds";
2282 if (tnum_subreg_is_const(reg->var_off)) {
2283 u32 uval32 = tnum_subreg(reg->var_off).value;
2284 s32 sval32 = (s32)uval32;
2286 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2287 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2288 msg = "const subreg tnum out of sync with range bounds";
2295 verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2296 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2297 ctx, msg, reg->umin_value, reg->umax_value,
2298 reg->smin_value, reg->smax_value,
2299 reg->u32_min_value, reg->u32_max_value,
2300 reg->s32_min_value, reg->s32_max_value,
2301 reg->var_off.value, reg->var_off.mask);
2302 if (env->test_reg_invariants)
2304 __mark_reg_unbounded(reg);
2308 static bool __reg32_bound_s64(s32 a)
2310 return a >= 0 && a <= S32_MAX;
2313 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2315 reg->umin_value = reg->u32_min_value;
2316 reg->umax_value = reg->u32_max_value;
2318 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2319 * be positive otherwise set to worse case bounds and refine later
2322 if (__reg32_bound_s64(reg->s32_min_value) &&
2323 __reg32_bound_s64(reg->s32_max_value)) {
2324 reg->smin_value = reg->s32_min_value;
2325 reg->smax_value = reg->s32_max_value;
2327 reg->smin_value = 0;
2328 reg->smax_value = U32_MAX;
2332 /* Mark a register as having a completely unknown (scalar) value. */
2333 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2336 * Clear type, off, and union(map_ptr, range) and
2337 * padding between 'type' and union
2339 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2340 reg->type = SCALAR_VALUE;
2342 reg->ref_obj_id = 0;
2343 reg->var_off = tnum_unknown;
2345 reg->precise = false;
2346 __mark_reg_unbounded(reg);
2349 /* Mark a register as having a completely unknown (scalar) value,
2350 * initialize .precise as true when not bpf capable.
2352 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2353 struct bpf_reg_state *reg)
2355 __mark_reg_unknown_imprecise(reg);
2356 reg->precise = !env->bpf_capable;
2359 static void mark_reg_unknown(struct bpf_verifier_env *env,
2360 struct bpf_reg_state *regs, u32 regno)
2362 if (WARN_ON(regno >= MAX_BPF_REG)) {
2363 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2364 /* Something bad happened, let's kill all regs except FP */
2365 for (regno = 0; regno < BPF_REG_FP; regno++)
2366 __mark_reg_not_init(env, regs + regno);
2369 __mark_reg_unknown(env, regs + regno);
2372 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2373 struct bpf_reg_state *regs,
2378 struct bpf_reg_state *reg = regs + regno;
2380 reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
2381 reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
2383 reg->smin_value = max_t(s64, reg->smin_value, s32_min);
2384 reg->smax_value = min_t(s64, reg->smax_value, s32_max);
2386 reg_bounds_sync(reg);
2388 return reg_bounds_sanity_check(env, reg, "s32_range");
2391 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2392 struct bpf_reg_state *reg)
2394 __mark_reg_unknown(env, reg);
2395 reg->type = NOT_INIT;
2398 static void mark_reg_not_init(struct bpf_verifier_env *env,
2399 struct bpf_reg_state *regs, u32 regno)
2401 if (WARN_ON(regno >= MAX_BPF_REG)) {
2402 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2403 /* Something bad happened, let's kill all regs except FP */
2404 for (regno = 0; regno < BPF_REG_FP; regno++)
2405 __mark_reg_not_init(env, regs + regno);
2408 __mark_reg_not_init(env, regs + regno);
2411 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2412 struct bpf_reg_state *regs, u32 regno,
2413 enum bpf_reg_type reg_type,
2414 struct btf *btf, u32 btf_id,
2415 enum bpf_type_flag flag)
2417 if (reg_type == SCALAR_VALUE) {
2418 mark_reg_unknown(env, regs, regno);
2421 mark_reg_known_zero(env, regs, regno);
2422 regs[regno].type = PTR_TO_BTF_ID | flag;
2423 regs[regno].btf = btf;
2424 regs[regno].btf_id = btf_id;
2425 if (type_may_be_null(flag))
2426 regs[regno].id = ++env->id_gen;
2429 #define DEF_NOT_SUBREG (0)
2430 static void init_reg_state(struct bpf_verifier_env *env,
2431 struct bpf_func_state *state)
2433 struct bpf_reg_state *regs = state->regs;
2436 for (i = 0; i < MAX_BPF_REG; i++) {
2437 mark_reg_not_init(env, regs, i);
2438 regs[i].live = REG_LIVE_NONE;
2439 regs[i].parent = NULL;
2440 regs[i].subreg_def = DEF_NOT_SUBREG;
2444 regs[BPF_REG_FP].type = PTR_TO_STACK;
2445 mark_reg_known_zero(env, regs, BPF_REG_FP);
2446 regs[BPF_REG_FP].frameno = state->frameno;
2449 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2451 return (struct bpf_retval_range){ minval, maxval };
2454 #define BPF_MAIN_FUNC (-1)
2455 static void init_func_state(struct bpf_verifier_env *env,
2456 struct bpf_func_state *state,
2457 int callsite, int frameno, int subprogno)
2459 state->callsite = callsite;
2460 state->frameno = frameno;
2461 state->subprogno = subprogno;
2462 state->callback_ret_range = retval_range(0, 0);
2463 init_reg_state(env, state);
2464 mark_verifier_state_scratched(env);
2467 /* Similar to push_stack(), but for async callbacks */
2468 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2469 int insn_idx, int prev_insn_idx,
2470 int subprog, bool is_sleepable)
2472 struct bpf_verifier_stack_elem *elem;
2473 struct bpf_func_state *frame;
2475 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2479 elem->insn_idx = insn_idx;
2480 elem->prev_insn_idx = prev_insn_idx;
2481 elem->next = env->head;
2482 elem->log_pos = env->log.end_pos;
2485 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2487 "The sequence of %d jumps is too complex for async cb.\n",
2491 /* Unlike push_stack() do not copy_verifier_state().
2492 * The caller state doesn't matter.
2493 * This is async callback. It starts in a fresh stack.
2494 * Initialize it similar to do_check_common().
2496 elem->st.branches = 1;
2497 elem->st.in_sleepable = is_sleepable;
2498 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2501 init_func_state(env, frame,
2502 BPF_MAIN_FUNC /* callsite */,
2503 0 /* frameno within this callchain */,
2504 subprog /* subprog number within this prog */);
2505 elem->st.frame[0] = frame;
2508 free_verifier_state(env->cur_state, true);
2509 env->cur_state = NULL;
2510 /* pop all elements and return */
2511 while (!pop_stack(env, NULL, NULL, false));
2517 SRC_OP, /* register is used as source operand */
2518 DST_OP, /* register is used as destination operand */
2519 DST_OP_NO_MARK /* same as above, check only, don't mark */
2522 static int cmp_subprogs(const void *a, const void *b)
2524 return ((struct bpf_subprog_info *)a)->start -
2525 ((struct bpf_subprog_info *)b)->start;
2528 static int find_subprog(struct bpf_verifier_env *env, int off)
2530 struct bpf_subprog_info *p;
2532 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2533 sizeof(env->subprog_info[0]), cmp_subprogs);
2536 return p - env->subprog_info;
2540 static int add_subprog(struct bpf_verifier_env *env, int off)
2542 int insn_cnt = env->prog->len;
2545 if (off >= insn_cnt || off < 0) {
2546 verbose(env, "call to invalid destination\n");
2549 ret = find_subprog(env, off);
2552 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2553 verbose(env, "too many subprograms\n");
2556 /* determine subprog starts. The end is one before the next starts */
2557 env->subprog_info[env->subprog_cnt++].start = off;
2558 sort(env->subprog_info, env->subprog_cnt,
2559 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2560 return env->subprog_cnt - 1;
2563 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2565 struct bpf_prog_aux *aux = env->prog->aux;
2566 struct btf *btf = aux->btf;
2567 const struct btf_type *t;
2568 u32 main_btf_id, id;
2572 /* Non-zero func_info_cnt implies valid btf */
2573 if (!aux->func_info_cnt)
2575 main_btf_id = aux->func_info[0].type_id;
2577 t = btf_type_by_id(btf, main_btf_id);
2579 verbose(env, "invalid btf id for main subprog in func_info\n");
2583 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2585 ret = PTR_ERR(name);
2586 /* If there is no tag present, there is no exception callback */
2589 else if (ret == -EEXIST)
2590 verbose(env, "multiple exception callback tags for main subprog\n");
2594 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2596 verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2600 t = btf_type_by_id(btf, id);
2601 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2602 verbose(env, "exception callback '%s' must have global linkage\n", name);
2606 for (i = 0; i < aux->func_info_cnt; i++) {
2607 if (aux->func_info[i].type_id != id)
2609 ret = aux->func_info[i].insn_off;
2610 /* Further func_info and subprog checks will also happen
2611 * later, so assume this is the right insn_off for now.
2614 verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2619 verbose(env, "exception callback type id not found in func_info\n");
2625 #define MAX_KFUNC_DESCS 256
2626 #define MAX_KFUNC_BTFS 256
2628 struct bpf_kfunc_desc {
2629 struct btf_func_model func_model;
2636 struct bpf_kfunc_btf {
2638 struct module *module;
2642 struct bpf_kfunc_desc_tab {
2643 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2644 * verification. JITs do lookups by bpf_insn, where func_id may not be
2645 * available, therefore at the end of verification do_misc_fixups()
2646 * sorts this by imm and offset.
2648 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2652 struct bpf_kfunc_btf_tab {
2653 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2657 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2659 const struct bpf_kfunc_desc *d0 = a;
2660 const struct bpf_kfunc_desc *d1 = b;
2662 /* func_id is not greater than BTF_MAX_TYPE */
2663 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2666 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2668 const struct bpf_kfunc_btf *d0 = a;
2669 const struct bpf_kfunc_btf *d1 = b;
2671 return d0->offset - d1->offset;
2674 static const struct bpf_kfunc_desc *
2675 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2677 struct bpf_kfunc_desc desc = {
2681 struct bpf_kfunc_desc_tab *tab;
2683 tab = prog->aux->kfunc_tab;
2684 return bsearch(&desc, tab->descs, tab->nr_descs,
2685 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2688 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2689 u16 btf_fd_idx, u8 **func_addr)
2691 const struct bpf_kfunc_desc *desc;
2693 desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2697 *func_addr = (u8 *)desc->addr;
2701 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2704 struct bpf_kfunc_btf kf_btf = { .offset = offset };
2705 struct bpf_kfunc_btf_tab *tab;
2706 struct bpf_kfunc_btf *b;
2711 tab = env->prog->aux->kfunc_btf_tab;
2712 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2713 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2715 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2716 verbose(env, "too many different module BTFs\n");
2717 return ERR_PTR(-E2BIG);
2720 if (bpfptr_is_null(env->fd_array)) {
2721 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2722 return ERR_PTR(-EPROTO);
2725 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2726 offset * sizeof(btf_fd),
2728 return ERR_PTR(-EFAULT);
2730 btf = btf_get_by_fd(btf_fd);
2732 verbose(env, "invalid module BTF fd specified\n");
2736 if (!btf_is_module(btf)) {
2737 verbose(env, "BTF fd for kfunc is not a module BTF\n");
2739 return ERR_PTR(-EINVAL);
2742 mod = btf_try_get_module(btf);
2745 return ERR_PTR(-ENXIO);
2748 b = &tab->descs[tab->nr_descs++];
2753 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2754 kfunc_btf_cmp_by_off, NULL);
2759 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2764 while (tab->nr_descs--) {
2765 module_put(tab->descs[tab->nr_descs].module);
2766 btf_put(tab->descs[tab->nr_descs].btf);
2771 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2775 /* In the future, this can be allowed to increase limit
2776 * of fd index into fd_array, interpreted as u16.
2778 verbose(env, "negative offset disallowed for kernel module function call\n");
2779 return ERR_PTR(-EINVAL);
2782 return __find_kfunc_desc_btf(env, offset);
2784 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2787 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2789 const struct btf_type *func, *func_proto;
2790 struct bpf_kfunc_btf_tab *btf_tab;
2791 struct bpf_kfunc_desc_tab *tab;
2792 struct bpf_prog_aux *prog_aux;
2793 struct bpf_kfunc_desc *desc;
2794 const char *func_name;
2795 struct btf *desc_btf;
2796 unsigned long call_imm;
2800 prog_aux = env->prog->aux;
2801 tab = prog_aux->kfunc_tab;
2802 btf_tab = prog_aux->kfunc_btf_tab;
2805 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2809 if (!env->prog->jit_requested) {
2810 verbose(env, "JIT is required for calling kernel function\n");
2814 if (!bpf_jit_supports_kfunc_call()) {
2815 verbose(env, "JIT does not support calling kernel function\n");
2819 if (!env->prog->gpl_compatible) {
2820 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2824 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2827 prog_aux->kfunc_tab = tab;
2830 /* func_id == 0 is always invalid, but instead of returning an error, be
2831 * conservative and wait until the code elimination pass before returning
2832 * error, so that invalid calls that get pruned out can be in BPF programs
2833 * loaded from userspace. It is also required that offset be untouched
2836 if (!func_id && !offset)
2839 if (!btf_tab && offset) {
2840 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2843 prog_aux->kfunc_btf_tab = btf_tab;
2846 desc_btf = find_kfunc_desc_btf(env, offset);
2847 if (IS_ERR(desc_btf)) {
2848 verbose(env, "failed to find BTF for kernel function\n");
2849 return PTR_ERR(desc_btf);
2852 if (find_kfunc_desc(env->prog, func_id, offset))
2855 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2856 verbose(env, "too many different kernel function calls\n");
2860 func = btf_type_by_id(desc_btf, func_id);
2861 if (!func || !btf_type_is_func(func)) {
2862 verbose(env, "kernel btf_id %u is not a function\n",
2866 func_proto = btf_type_by_id(desc_btf, func->type);
2867 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2868 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2873 func_name = btf_name_by_offset(desc_btf, func->name_off);
2874 addr = kallsyms_lookup_name(func_name);
2876 verbose(env, "cannot find address for kernel function %s\n",
2880 specialize_kfunc(env, func_id, offset, &addr);
2882 if (bpf_jit_supports_far_kfunc_call()) {
2885 call_imm = BPF_CALL_IMM(addr);
2886 /* Check whether the relative offset overflows desc->imm */
2887 if ((unsigned long)(s32)call_imm != call_imm) {
2888 verbose(env, "address of kernel function %s is out of range\n",
2894 if (bpf_dev_bound_kfunc_id(func_id)) {
2895 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2900 desc = &tab->descs[tab->nr_descs++];
2901 desc->func_id = func_id;
2902 desc->imm = call_imm;
2903 desc->offset = offset;
2905 err = btf_distill_func_proto(&env->log, desc_btf,
2906 func_proto, func_name,
2909 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2910 kfunc_desc_cmp_by_id_off, NULL);
2914 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2916 const struct bpf_kfunc_desc *d0 = a;
2917 const struct bpf_kfunc_desc *d1 = b;
2919 if (d0->imm != d1->imm)
2920 return d0->imm < d1->imm ? -1 : 1;
2921 if (d0->offset != d1->offset)
2922 return d0->offset < d1->offset ? -1 : 1;
2926 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2928 struct bpf_kfunc_desc_tab *tab;
2930 tab = prog->aux->kfunc_tab;
2934 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2935 kfunc_desc_cmp_by_imm_off, NULL);
2938 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2940 return !!prog->aux->kfunc_tab;
2943 const struct btf_func_model *
2944 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2945 const struct bpf_insn *insn)
2947 const struct bpf_kfunc_desc desc = {
2949 .offset = insn->off,
2951 const struct bpf_kfunc_desc *res;
2952 struct bpf_kfunc_desc_tab *tab;
2954 tab = prog->aux->kfunc_tab;
2955 res = bsearch(&desc, tab->descs, tab->nr_descs,
2956 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2958 return res ? &res->func_model : NULL;
2961 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2963 struct bpf_subprog_info *subprog = env->subprog_info;
2964 int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2965 struct bpf_insn *insn = env->prog->insnsi;
2967 /* Add entry function. */
2968 ret = add_subprog(env, 0);
2972 for (i = 0; i < insn_cnt; i++, insn++) {
2973 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2974 !bpf_pseudo_kfunc_call(insn))
2977 if (!env->bpf_capable) {
2978 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2982 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2983 ret = add_subprog(env, i + insn->imm + 1);
2985 ret = add_kfunc_call(env, insn->imm, insn->off);
2991 ret = bpf_find_exception_callback_insn_off(env);
2996 /* If ex_cb_insn > 0, this means that the main program has a subprog
2997 * marked using BTF decl tag to serve as the exception callback.
3000 ret = add_subprog(env, ex_cb_insn);
3003 for (i = 1; i < env->subprog_cnt; i++) {
3004 if (env->subprog_info[i].start != ex_cb_insn)
3006 env->exception_callback_subprog = i;
3007 mark_subprog_exc_cb(env, i);
3012 /* Add a fake 'exit' subprog which could simplify subprog iteration
3013 * logic. 'subprog_cnt' should not be increased.
3015 subprog[env->subprog_cnt].start = insn_cnt;
3017 if (env->log.level & BPF_LOG_LEVEL2)
3018 for (i = 0; i < env->subprog_cnt; i++)
3019 verbose(env, "func#%d @%d\n", i, subprog[i].start);
3024 static int check_subprogs(struct bpf_verifier_env *env)
3026 int i, subprog_start, subprog_end, off, cur_subprog = 0;
3027 struct bpf_subprog_info *subprog = env->subprog_info;
3028 struct bpf_insn *insn = env->prog->insnsi;
3029 int insn_cnt = env->prog->len;
3031 /* now check that all jumps are within the same subprog */
3032 subprog_start = subprog[cur_subprog].start;
3033 subprog_end = subprog[cur_subprog + 1].start;
3034 for (i = 0; i < insn_cnt; i++) {
3035 u8 code = insn[i].code;
3037 if (code == (BPF_JMP | BPF_CALL) &&
3038 insn[i].src_reg == 0 &&
3039 insn[i].imm == BPF_FUNC_tail_call) {
3040 subprog[cur_subprog].has_tail_call = true;
3041 subprog[cur_subprog].tail_call_reachable = true;
3043 if (BPF_CLASS(code) == BPF_LD &&
3044 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3045 subprog[cur_subprog].has_ld_abs = true;
3046 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3048 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3050 if (code == (BPF_JMP32 | BPF_JA))
3051 off = i + insn[i].imm + 1;
3053 off = i + insn[i].off + 1;
3054 if (off < subprog_start || off >= subprog_end) {
3055 verbose(env, "jump out of range from insn %d to %d\n", i, off);
3059 if (i == subprog_end - 1) {
3060 /* to avoid fall-through from one subprog into another
3061 * the last insn of the subprog should be either exit
3062 * or unconditional jump back or bpf_throw call
3064 if (code != (BPF_JMP | BPF_EXIT) &&
3065 code != (BPF_JMP32 | BPF_JA) &&
3066 code != (BPF_JMP | BPF_JA)) {
3067 verbose(env, "last insn is not an exit or jmp\n");
3070 subprog_start = subprog_end;
3072 if (cur_subprog < env->subprog_cnt)
3073 subprog_end = subprog[cur_subprog + 1].start;
3079 /* Parentage chain of this register (or stack slot) should take care of all
3080 * issues like callee-saved registers, stack slot allocation time, etc.
3082 static int mark_reg_read(struct bpf_verifier_env *env,
3083 const struct bpf_reg_state *state,
3084 struct bpf_reg_state *parent, u8 flag)
3086 bool writes = parent == state->parent; /* Observe write marks */
3090 /* if read wasn't screened by an earlier write ... */
3091 if (writes && state->live & REG_LIVE_WRITTEN)
3093 if (parent->live & REG_LIVE_DONE) {
3094 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3095 reg_type_str(env, parent->type),
3096 parent->var_off.value, parent->off);
3099 /* The first condition is more likely to be true than the
3100 * second, checked it first.
3102 if ((parent->live & REG_LIVE_READ) == flag ||
3103 parent->live & REG_LIVE_READ64)
3104 /* The parentage chain never changes and
3105 * this parent was already marked as LIVE_READ.
3106 * There is no need to keep walking the chain again and
3107 * keep re-marking all parents as LIVE_READ.
3108 * This case happens when the same register is read
3109 * multiple times without writes into it in-between.
3110 * Also, if parent has the stronger REG_LIVE_READ64 set,
3111 * then no need to set the weak REG_LIVE_READ32.
3114 /* ... then we depend on parent's value */
3115 parent->live |= flag;
3116 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3117 if (flag == REG_LIVE_READ64)
3118 parent->live &= ~REG_LIVE_READ32;
3120 parent = state->parent;
3125 if (env->longest_mark_read_walk < cnt)
3126 env->longest_mark_read_walk = cnt;
3130 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3132 struct bpf_func_state *state = func(env, reg);
3135 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
3136 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3139 if (reg->type == CONST_PTR_TO_DYNPTR)
3141 spi = dynptr_get_spi(env, reg);
3144 /* Caller ensures dynptr is valid and initialized, which means spi is in
3145 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3148 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3149 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3152 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3153 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3156 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3157 int spi, int nr_slots)
3159 struct bpf_func_state *state = func(env, reg);
3162 for (i = 0; i < nr_slots; i++) {
3163 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3165 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3169 mark_stack_slot_scratched(env, spi - i);
3175 /* This function is supposed to be used by the following 32-bit optimization
3176 * code only. It returns TRUE if the source or destination register operates
3177 * on 64-bit, otherwise return FALSE.
3179 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3180 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3185 class = BPF_CLASS(code);
3187 if (class == BPF_JMP) {
3188 /* BPF_EXIT for "main" will reach here. Return TRUE
3193 if (op == BPF_CALL) {
3194 /* BPF to BPF call will reach here because of marking
3195 * caller saved clobber with DST_OP_NO_MARK for which we
3196 * don't care the register def because they are anyway
3197 * marked as NOT_INIT already.
3199 if (insn->src_reg == BPF_PSEUDO_CALL)
3201 /* Helper call will reach here because of arg type
3202 * check, conservatively return TRUE.
3211 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3214 if (class == BPF_ALU64 || class == BPF_JMP ||
3215 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3218 if (class == BPF_ALU || class == BPF_JMP32)
3221 if (class == BPF_LDX) {
3223 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3224 /* LDX source must be ptr. */
3228 if (class == BPF_STX) {
3229 /* BPF_STX (including atomic variants) has multiple source
3230 * operands, one of which is a ptr. Check whether the caller is
3233 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3235 return BPF_SIZE(code) == BPF_DW;
3238 if (class == BPF_LD) {
3239 u8 mode = BPF_MODE(code);
3242 if (mode == BPF_IMM)
3245 /* Both LD_IND and LD_ABS return 32-bit data. */
3249 /* Implicit ctx ptr. */
3250 if (regno == BPF_REG_6)
3253 /* Explicit source could be any width. */
3257 if (class == BPF_ST)
3258 /* The only source register for BPF_ST is a ptr. */
3261 /* Conservatively return true at default. */
3265 /* Return the regno defined by the insn, or -1. */
3266 static int insn_def_regno(const struct bpf_insn *insn)
3268 switch (BPF_CLASS(insn->code)) {
3274 if ((BPF_MODE(insn->code) == BPF_ATOMIC ||
3275 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) &&
3276 (insn->imm & BPF_FETCH)) {
3277 if (insn->imm == BPF_CMPXCHG)
3280 return insn->src_reg;
3285 return insn->dst_reg;
3289 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3290 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3292 int dst_reg = insn_def_regno(insn);
3297 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3300 static void mark_insn_zext(struct bpf_verifier_env *env,
3301 struct bpf_reg_state *reg)
3303 s32 def_idx = reg->subreg_def;
3305 if (def_idx == DEF_NOT_SUBREG)
3308 env->insn_aux_data[def_idx - 1].zext_dst = true;
3309 /* The dst will be zero extended, so won't be sub-register anymore. */
3310 reg->subreg_def = DEF_NOT_SUBREG;
3313 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3314 enum reg_arg_type t)
3316 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3317 struct bpf_reg_state *reg;
3320 if (regno >= MAX_BPF_REG) {
3321 verbose(env, "R%d is invalid\n", regno);
3325 mark_reg_scratched(env, regno);
3328 rw64 = is_reg64(env, insn, regno, reg, t);
3330 /* check whether register used as source operand can be read */
3331 if (reg->type == NOT_INIT) {
3332 verbose(env, "R%d !read_ok\n", regno);
3335 /* We don't need to worry about FP liveness because it's read-only */
3336 if (regno == BPF_REG_FP)
3340 mark_insn_zext(env, reg);
3342 return mark_reg_read(env, reg, reg->parent,
3343 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3345 /* check whether register used as dest operand can be written to */
3346 if (regno == BPF_REG_FP) {
3347 verbose(env, "frame pointer is read only\n");
3350 reg->live |= REG_LIVE_WRITTEN;
3351 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3353 mark_reg_unknown(env, regs, regno);
3358 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3359 enum reg_arg_type t)
3361 struct bpf_verifier_state *vstate = env->cur_state;
3362 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3364 return __check_reg_arg(env, state->regs, regno, t);
3367 static int insn_stack_access_flags(int frameno, int spi)
3369 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3372 static int insn_stack_access_spi(int insn_flags)
3374 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3377 static int insn_stack_access_frameno(int insn_flags)
3379 return insn_flags & INSN_F_FRAMENO_MASK;
3382 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3384 env->insn_aux_data[idx].jmp_point = true;
3387 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3389 return env->insn_aux_data[insn_idx].jmp_point;
3392 #define LR_FRAMENO_BITS 3
3393 #define LR_SPI_BITS 6
3394 #define LR_ENTRY_BITS (LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3395 #define LR_SIZE_BITS 4
3396 #define LR_FRAMENO_MASK ((1ull << LR_FRAMENO_BITS) - 1)
3397 #define LR_SPI_MASK ((1ull << LR_SPI_BITS) - 1)
3398 #define LR_SIZE_MASK ((1ull << LR_SIZE_BITS) - 1)
3399 #define LR_SPI_OFF LR_FRAMENO_BITS
3400 #define LR_IS_REG_OFF (LR_SPI_BITS + LR_FRAMENO_BITS)
3401 #define LINKED_REGS_MAX 6
3412 struct linked_regs {
3414 struct linked_reg entries[LINKED_REGS_MAX];
3417 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3419 if (s->cnt < LINKED_REGS_MAX)
3420 return &s->entries[s->cnt++];
3425 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
3426 * number of elements currently in stack.
3427 * Pack one history entry for linked registers as 10 bits in the following format:
3429 * - 6-bits spi_or_reg
3432 static u64 linked_regs_pack(struct linked_regs *s)
3437 for (i = 0; i < s->cnt; ++i) {
3438 struct linked_reg *e = &s->entries[i];
3442 tmp |= e->spi << LR_SPI_OFF;
3443 tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3445 val <<= LR_ENTRY_BITS;
3448 val <<= LR_SIZE_BITS;
3453 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3457 s->cnt = val & LR_SIZE_MASK;
3458 val >>= LR_SIZE_BITS;
3460 for (i = 0; i < s->cnt; ++i) {
3461 struct linked_reg *e = &s->entries[i];
3463 e->frameno = val & LR_FRAMENO_MASK;
3464 e->spi = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3465 e->is_reg = (val >> LR_IS_REG_OFF) & 0x1;
3466 val >>= LR_ENTRY_BITS;
3470 /* for any branch, call, exit record the history of jmps in the given state */
3471 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3472 int insn_flags, u64 linked_regs)
3474 u32 cnt = cur->jmp_history_cnt;
3475 struct bpf_jmp_history_entry *p;
3478 /* combine instruction flags if we already recorded this instruction */
3479 if (env->cur_hist_ent) {
3480 /* atomic instructions push insn_flags twice, for READ and
3481 * WRITE sides, but they should agree on stack slot
3483 WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
3484 (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3485 "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
3486 env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3487 env->cur_hist_ent->flags |= insn_flags;
3488 WARN_ONCE(env->cur_hist_ent->linked_regs != 0,
3489 "verifier insn history bug: insn_idx %d linked_regs != 0: %#llx\n",
3490 env->insn_idx, env->cur_hist_ent->linked_regs);
3491 env->cur_hist_ent->linked_regs = linked_regs;
3496 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3497 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3500 cur->jmp_history = p;
3502 p = &cur->jmp_history[cnt - 1];
3503 p->idx = env->insn_idx;
3504 p->prev_idx = env->prev_insn_idx;
3505 p->flags = insn_flags;
3506 p->linked_regs = linked_regs;
3507 cur->jmp_history_cnt = cnt;
3508 env->cur_hist_ent = p;
3513 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3514 u32 hist_end, int insn_idx)
3516 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3517 return &st->jmp_history[hist_end - 1];
3521 /* Backtrack one insn at a time. If idx is not at the top of recorded
3522 * history then previous instruction came from straight line execution.
3523 * Return -ENOENT if we exhausted all instructions within given state.
3525 * It's legal to have a bit of a looping with the same starting and ending
3526 * insn index within the same state, e.g.: 3->4->5->3, so just because current
3527 * instruction index is the same as state's first_idx doesn't mean we are
3528 * done. If there is still some jump history left, we should keep going. We
3529 * need to take into account that we might have a jump history between given
3530 * state's parent and itself, due to checkpointing. In this case, we'll have
3531 * history entry recording a jump from last instruction of parent state and
3532 * first instruction of given state.
3534 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3539 if (i == st->first_insn_idx) {
3542 if (cnt == 1 && st->jmp_history[0].idx == i)
3546 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3547 i = st->jmp_history[cnt - 1].prev_idx;
3555 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3557 const struct btf_type *func;
3558 struct btf *desc_btf;
3560 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3563 desc_btf = find_kfunc_desc_btf(data, insn->off);
3564 if (IS_ERR(desc_btf))
3567 func = btf_type_by_id(desc_btf, insn->imm);
3568 return btf_name_by_offset(desc_btf, func->name_off);
3571 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3576 static inline void bt_reset(struct backtrack_state *bt)
3578 struct bpf_verifier_env *env = bt->env;
3580 memset(bt, 0, sizeof(*bt));
3584 static inline u32 bt_empty(struct backtrack_state *bt)
3589 for (i = 0; i <= bt->frame; i++)
3590 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3595 static inline int bt_subprog_enter(struct backtrack_state *bt)
3597 if (bt->frame == MAX_CALL_FRAMES - 1) {
3598 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3599 WARN_ONCE(1, "verifier backtracking bug");
3606 static inline int bt_subprog_exit(struct backtrack_state *bt)
3608 if (bt->frame == 0) {
3609 verbose(bt->env, "BUG subprog exit from frame 0\n");
3610 WARN_ONCE(1, "verifier backtracking bug");
3617 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3619 bt->reg_masks[frame] |= 1 << reg;
3622 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3624 bt->reg_masks[frame] &= ~(1 << reg);
3627 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3629 bt_set_frame_reg(bt, bt->frame, reg);
3632 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3634 bt_clear_frame_reg(bt, bt->frame, reg);
3637 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3639 bt->stack_masks[frame] |= 1ull << slot;
3642 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3644 bt->stack_masks[frame] &= ~(1ull << slot);
3647 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3649 return bt->reg_masks[frame];
3652 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3654 return bt->reg_masks[bt->frame];
3657 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3659 return bt->stack_masks[frame];
3662 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3664 return bt->stack_masks[bt->frame];
3667 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3669 return bt->reg_masks[bt->frame] & (1 << reg);
3672 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
3674 return bt->reg_masks[frame] & (1 << reg);
3677 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
3679 return bt->stack_masks[frame] & (1ull << slot);
3682 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3683 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3685 DECLARE_BITMAP(mask, 64);
3691 bitmap_from_u64(mask, reg_mask);
3692 for_each_set_bit(i, mask, 32) {
3693 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3701 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3702 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3704 DECLARE_BITMAP(mask, 64);
3710 bitmap_from_u64(mask, stack_mask);
3711 for_each_set_bit(i, mask, 64) {
3712 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3721 /* If any register R in hist->linked_regs is marked as precise in bt,
3722 * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
3724 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
3726 struct linked_regs linked_regs;
3727 bool some_precise = false;
3730 if (!hist || hist->linked_regs == 0)
3733 linked_regs_unpack(hist->linked_regs, &linked_regs);
3734 for (i = 0; i < linked_regs.cnt; ++i) {
3735 struct linked_reg *e = &linked_regs.entries[i];
3737 if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
3738 (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
3739 some_precise = true;
3747 for (i = 0; i < linked_regs.cnt; ++i) {
3748 struct linked_reg *e = &linked_regs.entries[i];
3751 bt_set_frame_reg(bt, e->frameno, e->regno);
3753 bt_set_frame_slot(bt, e->frameno, e->spi);
3757 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3759 /* For given verifier state backtrack_insn() is called from the last insn to
3760 * the first insn. Its purpose is to compute a bitmask of registers and
3761 * stack slots that needs precision in the parent verifier state.
3763 * @idx is an index of the instruction we are currently processing;
3764 * @subseq_idx is an index of the subsequent instruction that:
3765 * - *would be* executed next, if jump history is viewed in forward order;
3766 * - *was* processed previously during backtracking.
3768 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3769 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
3771 const struct bpf_insn_cbs cbs = {
3772 .cb_call = disasm_kfunc_name,
3773 .cb_print = verbose,
3774 .private_data = env,
3776 struct bpf_insn *insn = env->prog->insnsi + idx;
3777 u8 class = BPF_CLASS(insn->code);
3778 u8 opcode = BPF_OP(insn->code);
3779 u8 mode = BPF_MODE(insn->code);
3780 u32 dreg = insn->dst_reg;
3781 u32 sreg = insn->src_reg;
3784 if (insn->code == 0)
3786 if (env->log.level & BPF_LOG_LEVEL2) {
3787 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3788 verbose(env, "mark_precise: frame%d: regs=%s ",
3789 bt->frame, env->tmp_str_buf);
3790 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3791 verbose(env, "stack=%s before ", env->tmp_str_buf);
3792 verbose(env, "%d: ", idx);
3793 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3796 /* If there is a history record that some registers gained range at this insn,
3797 * propagate precision marks to those registers, so that bt_is_reg_set()
3798 * accounts for these registers.
3800 bt_sync_linked_regs(bt, hist);
3802 if (class == BPF_ALU || class == BPF_ALU64) {
3803 if (!bt_is_reg_set(bt, dreg))
3805 if (opcode == BPF_END || opcode == BPF_NEG) {
3806 /* sreg is reserved and unused
3807 * dreg still need precision before this insn
3810 } else if (opcode == BPF_MOV) {
3811 if (BPF_SRC(insn->code) == BPF_X) {
3812 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3813 * dreg needs precision after this insn
3814 * sreg needs precision before this insn
3816 bt_clear_reg(bt, dreg);
3817 if (sreg != BPF_REG_FP)
3818 bt_set_reg(bt, sreg);
3821 * dreg needs precision after this insn.
3822 * Corresponding register is already marked
3823 * as precise=true in this verifier state.
3824 * No further markings in parent are necessary
3826 bt_clear_reg(bt, dreg);
3829 if (BPF_SRC(insn->code) == BPF_X) {
3831 * both dreg and sreg need precision
3834 if (sreg != BPF_REG_FP)
3835 bt_set_reg(bt, sreg);
3837 * dreg still needs precision before this insn
3840 } else if (class == BPF_LDX) {
3841 if (!bt_is_reg_set(bt, dreg))
3843 bt_clear_reg(bt, dreg);
3845 /* scalars can only be spilled into stack w/o losing precision.
3846 * Load from any other memory can be zero extended.
3847 * The desire to keep that precision is already indicated
3848 * by 'precise' mark in corresponding register of this state.
3849 * No further tracking necessary.
3851 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3853 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3854 * that [fp - off] slot contains scalar that needs to be
3855 * tracked with precision
3857 spi = insn_stack_access_spi(hist->flags);
3858 fr = insn_stack_access_frameno(hist->flags);
3859 bt_set_frame_slot(bt, fr, spi);
3860 } else if (class == BPF_STX || class == BPF_ST) {
3861 if (bt_is_reg_set(bt, dreg))
3862 /* stx & st shouldn't be using _scalar_ dst_reg
3863 * to access memory. It means backtracking
3864 * encountered a case of pointer subtraction.
3867 /* scalars can only be spilled into stack */
3868 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3870 spi = insn_stack_access_spi(hist->flags);
3871 fr = insn_stack_access_frameno(hist->flags);
3872 if (!bt_is_frame_slot_set(bt, fr, spi))
3874 bt_clear_frame_slot(bt, fr, spi);
3875 if (class == BPF_STX)
3876 bt_set_reg(bt, sreg);
3877 } else if (class == BPF_JMP || class == BPF_JMP32) {
3878 if (bpf_pseudo_call(insn)) {
3879 int subprog_insn_idx, subprog;
3881 subprog_insn_idx = idx + insn->imm + 1;
3882 subprog = find_subprog(env, subprog_insn_idx);
3886 if (subprog_is_global(env, subprog)) {
3887 /* check that jump history doesn't have any
3888 * extra instructions from subprog; the next
3889 * instruction after call to global subprog
3890 * should be literally next instruction in
3893 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3894 /* r1-r5 are invalidated after subprog call,
3895 * so for global func call it shouldn't be set
3898 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3899 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3900 WARN_ONCE(1, "verifier backtracking bug");
3903 /* global subprog always sets R0 */
3904 bt_clear_reg(bt, BPF_REG_0);
3907 /* static subprog call instruction, which
3908 * means that we are exiting current subprog,
3909 * so only r1-r5 could be still requested as
3910 * precise, r0 and r6-r10 or any stack slot in
3911 * the current frame should be zero by now
3913 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3914 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3915 WARN_ONCE(1, "verifier backtracking bug");
3918 /* we are now tracking register spills correctly,
3919 * so any instance of leftover slots is a bug
3921 if (bt_stack_mask(bt) != 0) {
3922 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3923 WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
3926 /* propagate r1-r5 to the caller */
3927 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3928 if (bt_is_reg_set(bt, i)) {
3929 bt_clear_reg(bt, i);
3930 bt_set_frame_reg(bt, bt->frame - 1, i);
3933 if (bt_subprog_exit(bt))
3937 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3938 /* exit from callback subprog to callback-calling helper or
3939 * kfunc call. Use idx/subseq_idx check to discern it from
3940 * straight line code backtracking.
3941 * Unlike the subprog call handling above, we shouldn't
3942 * propagate precision of r1-r5 (if any requested), as they are
3943 * not actually arguments passed directly to callback subprogs
3945 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3946 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3947 WARN_ONCE(1, "verifier backtracking bug");
3950 if (bt_stack_mask(bt) != 0) {
3951 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3952 WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
3955 /* clear r1-r5 in callback subprog's mask */
3956 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3957 bt_clear_reg(bt, i);
3958 if (bt_subprog_exit(bt))
3961 } else if (opcode == BPF_CALL) {
3962 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3963 * catch this error later. Make backtracking conservative
3966 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3968 /* regular helper call sets R0 */
3969 bt_clear_reg(bt, BPF_REG_0);
3970 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3971 /* if backtracing was looking for registers R1-R5
3972 * they should have been found already.
3974 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3975 WARN_ONCE(1, "verifier backtracking bug");
3978 } else if (opcode == BPF_EXIT) {
3981 /* Backtracking to a nested function call, 'idx' is a part of
3982 * the inner frame 'subseq_idx' is a part of the outer frame.
3983 * In case of a regular function call, instructions giving
3984 * precision to registers R1-R5 should have been found already.
3985 * In case of a callback, it is ok to have R1-R5 marked for
3986 * backtracking, as these registers are set by the function
3987 * invoking callback.
3989 if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3990 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3991 bt_clear_reg(bt, i);
3992 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3993 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3994 WARN_ONCE(1, "verifier backtracking bug");
3998 /* BPF_EXIT in subprog or callback always returns
3999 * right after the call instruction, so by checking
4000 * whether the instruction at subseq_idx-1 is subprog
4001 * call or not we can distinguish actual exit from
4002 * *subprog* from exit from *callback*. In the former
4003 * case, we need to propagate r0 precision, if
4004 * necessary. In the former we never do that.
4006 r0_precise = subseq_idx - 1 >= 0 &&
4007 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
4008 bt_is_reg_set(bt, BPF_REG_0);
4010 bt_clear_reg(bt, BPF_REG_0);
4011 if (bt_subprog_enter(bt))
4015 bt_set_reg(bt, BPF_REG_0);
4016 /* r6-r9 and stack slots will stay set in caller frame
4017 * bitmasks until we return back from callee(s)
4020 } else if (BPF_SRC(insn->code) == BPF_X) {
4021 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
4024 * Both dreg and sreg need precision before
4025 * this insn. If only sreg was marked precise
4026 * before it would be equally necessary to
4027 * propagate it to dreg.
4029 bt_set_reg(bt, dreg);
4030 bt_set_reg(bt, sreg);
4031 } else if (BPF_SRC(insn->code) == BPF_K) {
4033 * Only dreg still needs precision before
4034 * this insn, so for the K-based conditional
4035 * there is nothing new to be marked.
4038 } else if (class == BPF_LD) {
4039 if (!bt_is_reg_set(bt, dreg))
4041 bt_clear_reg(bt, dreg);
4042 /* It's ld_imm64 or ld_abs or ld_ind.
4043 * For ld_imm64 no further tracking of precision
4044 * into parent is necessary
4046 if (mode == BPF_IND || mode == BPF_ABS)
4047 /* to be analyzed */
4050 /* Propagate precision marks to linked registers, to account for
4051 * registers marked as precise in this function.
4053 bt_sync_linked_regs(bt, hist);
4057 /* the scalar precision tracking algorithm:
4058 * . at the start all registers have precise=false.
4059 * . scalar ranges are tracked as normal through alu and jmp insns.
4060 * . once precise value of the scalar register is used in:
4061 * . ptr + scalar alu
4062 * . if (scalar cond K|scalar)
4063 * . helper_call(.., scalar, ...) where ARG_CONST is expected
4064 * backtrack through the verifier states and mark all registers and
4065 * stack slots with spilled constants that these scalar regisers
4066 * should be precise.
4067 * . during state pruning two registers (or spilled stack slots)
4068 * are equivalent if both are not precise.
4070 * Note the verifier cannot simply walk register parentage chain,
4071 * since many different registers and stack slots could have been
4072 * used to compute single precise scalar.
4074 * The approach of starting with precise=true for all registers and then
4075 * backtrack to mark a register as not precise when the verifier detects
4076 * that program doesn't care about specific value (e.g., when helper
4077 * takes register as ARG_ANYTHING parameter) is not safe.
4079 * It's ok to walk single parentage chain of the verifier states.
4080 * It's possible that this backtracking will go all the way till 1st insn.
4081 * All other branches will be explored for needing precision later.
4083 * The backtracking needs to deal with cases like:
4084 * 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)
4087 * if r5 > 0x79f goto pc+7
4088 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4091 * call bpf_perf_event_output#25
4092 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4096 * call foo // uses callee's r6 inside to compute r0
4100 * to track above reg_mask/stack_mask needs to be independent for each frame.
4102 * Also if parent's curframe > frame where backtracking started,
4103 * the verifier need to mark registers in both frames, otherwise callees
4104 * may incorrectly prune callers. This is similar to
4105 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4107 * For now backtracking falls back into conservative marking.
4109 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4110 struct bpf_verifier_state *st)
4112 struct bpf_func_state *func;
4113 struct bpf_reg_state *reg;
4116 if (env->log.level & BPF_LOG_LEVEL2) {
4117 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4121 /* big hammer: mark all scalars precise in this path.
4122 * pop_stack may still get !precise scalars.
4123 * We also skip current state and go straight to first parent state,
4124 * because precision markings in current non-checkpointed state are
4125 * not needed. See why in the comment in __mark_chain_precision below.
4127 for (st = st->parent; st; st = st->parent) {
4128 for (i = 0; i <= st->curframe; i++) {
4129 func = st->frame[i];
4130 for (j = 0; j < BPF_REG_FP; j++) {
4131 reg = &func->regs[j];
4132 if (reg->type != SCALAR_VALUE || reg->precise)
4134 reg->precise = true;
4135 if (env->log.level & BPF_LOG_LEVEL2) {
4136 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4140 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4141 if (!is_spilled_reg(&func->stack[j]))
4143 reg = &func->stack[j].spilled_ptr;
4144 if (reg->type != SCALAR_VALUE || reg->precise)
4146 reg->precise = true;
4147 if (env->log.level & BPF_LOG_LEVEL2) {
4148 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4156 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4158 struct bpf_func_state *func;
4159 struct bpf_reg_state *reg;
4162 for (i = 0; i <= st->curframe; i++) {
4163 func = st->frame[i];
4164 for (j = 0; j < BPF_REG_FP; j++) {
4165 reg = &func->regs[j];
4166 if (reg->type != SCALAR_VALUE)
4168 reg->precise = false;
4170 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4171 if (!is_spilled_reg(&func->stack[j]))
4173 reg = &func->stack[j].spilled_ptr;
4174 if (reg->type != SCALAR_VALUE)
4176 reg->precise = false;
4182 * __mark_chain_precision() backtracks BPF program instruction sequence and
4183 * chain of verifier states making sure that register *regno* (if regno >= 0)
4184 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4185 * SCALARS, as well as any other registers and slots that contribute to
4186 * a tracked state of given registers/stack slots, depending on specific BPF
4187 * assembly instructions (see backtrack_insns() for exact instruction handling
4188 * logic). This backtracking relies on recorded jmp_history and is able to
4189 * traverse entire chain of parent states. This process ends only when all the
4190 * necessary registers/slots and their transitive dependencies are marked as
4193 * One important and subtle aspect is that precise marks *do not matter* in
4194 * the currently verified state (current state). It is important to understand
4195 * why this is the case.
4197 * First, note that current state is the state that is not yet "checkpointed",
4198 * i.e., it is not yet put into env->explored_states, and it has no children
4199 * states as well. It's ephemeral, and can end up either a) being discarded if
4200 * compatible explored state is found at some point or BPF_EXIT instruction is
4201 * reached or b) checkpointed and put into env->explored_states, branching out
4202 * into one or more children states.
4204 * In the former case, precise markings in current state are completely
4205 * ignored by state comparison code (see regsafe() for details). Only
4206 * checkpointed ("old") state precise markings are important, and if old
4207 * state's register/slot is precise, regsafe() assumes current state's
4208 * register/slot as precise and checks value ranges exactly and precisely. If
4209 * states turn out to be compatible, current state's necessary precise
4210 * markings and any required parent states' precise markings are enforced
4211 * after the fact with propagate_precision() logic, after the fact. But it's
4212 * important to realize that in this case, even after marking current state
4213 * registers/slots as precise, we immediately discard current state. So what
4214 * actually matters is any of the precise markings propagated into current
4215 * state's parent states, which are always checkpointed (due to b) case above).
4216 * As such, for scenario a) it doesn't matter if current state has precise
4217 * markings set or not.
4219 * Now, for the scenario b), checkpointing and forking into child(ren)
4220 * state(s). Note that before current state gets to checkpointing step, any
4221 * processed instruction always assumes precise SCALAR register/slot
4222 * knowledge: if precise value or range is useful to prune jump branch, BPF
4223 * verifier takes this opportunity enthusiastically. Similarly, when
4224 * register's value is used to calculate offset or memory address, exact
4225 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4226 * what we mentioned above about state comparison ignoring precise markings
4227 * during state comparison, BPF verifier ignores and also assumes precise
4228 * markings *at will* during instruction verification process. But as verifier
4229 * assumes precision, it also propagates any precision dependencies across
4230 * parent states, which are not yet finalized, so can be further restricted
4231 * based on new knowledge gained from restrictions enforced by their children
4232 * states. This is so that once those parent states are finalized, i.e., when
4233 * they have no more active children state, state comparison logic in
4234 * is_state_visited() would enforce strict and precise SCALAR ranges, if
4235 * required for correctness.
4237 * To build a bit more intuition, note also that once a state is checkpointed,
4238 * the path we took to get to that state is not important. This is crucial
4239 * property for state pruning. When state is checkpointed and finalized at
4240 * some instruction index, it can be correctly and safely used to "short
4241 * circuit" any *compatible* state that reaches exactly the same instruction
4242 * index. I.e., if we jumped to that instruction from a completely different
4243 * code path than original finalized state was derived from, it doesn't
4244 * matter, current state can be discarded because from that instruction
4245 * forward having a compatible state will ensure we will safely reach the
4246 * exit. States describe preconditions for further exploration, but completely
4247 * forget the history of how we got here.
4249 * This also means that even if we needed precise SCALAR range to get to
4250 * finalized state, but from that point forward *that same* SCALAR register is
4251 * never used in a precise context (i.e., it's precise value is not needed for
4252 * correctness), it's correct and safe to mark such register as "imprecise"
4253 * (i.e., precise marking set to false). This is what we rely on when we do
4254 * not set precise marking in current state. If no child state requires
4255 * precision for any given SCALAR register, it's safe to dictate that it can
4256 * be imprecise. If any child state does require this register to be precise,
4257 * we'll mark it precise later retroactively during precise markings
4258 * propagation from child state to parent states.
4260 * Skipping precise marking setting in current state is a mild version of
4261 * relying on the above observation. But we can utilize this property even
4262 * more aggressively by proactively forgetting any precise marking in the
4263 * current state (which we inherited from the parent state), right before we
4264 * checkpoint it and branch off into new child state. This is done by
4265 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4266 * finalized states which help in short circuiting more future states.
4268 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4270 struct backtrack_state *bt = &env->bt;
4271 struct bpf_verifier_state *st = env->cur_state;
4272 int first_idx = st->first_insn_idx;
4273 int last_idx = env->insn_idx;
4274 int subseq_idx = -1;
4275 struct bpf_func_state *func;
4276 struct bpf_reg_state *reg;
4277 bool skip_first = true;
4280 if (!env->bpf_capable)
4283 /* set frame number from which we are starting to backtrack */
4284 bt_init(bt, env->cur_state->curframe);
4286 /* Do sanity checks against current state of register and/or stack
4287 * slot, but don't set precise flag in current state, as precision
4288 * tracking in the current state is unnecessary.
4290 func = st->frame[bt->frame];
4292 reg = &func->regs[regno];
4293 if (reg->type != SCALAR_VALUE) {
4294 WARN_ONCE(1, "backtracing misuse");
4297 bt_set_reg(bt, regno);
4304 DECLARE_BITMAP(mask, 64);
4305 u32 history = st->jmp_history_cnt;
4306 struct bpf_jmp_history_entry *hist;
4308 if (env->log.level & BPF_LOG_LEVEL2) {
4309 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4310 bt->frame, last_idx, first_idx, subseq_idx);
4314 /* we are at the entry into subprog, which
4315 * is expected for global funcs, but only if
4316 * requested precise registers are R1-R5
4317 * (which are global func's input arguments)
4319 if (st->curframe == 0 &&
4320 st->frame[0]->subprogno > 0 &&
4321 st->frame[0]->callsite == BPF_MAIN_FUNC &&
4322 bt_stack_mask(bt) == 0 &&
4323 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4324 bitmap_from_u64(mask, bt_reg_mask(bt));
4325 for_each_set_bit(i, mask, 32) {
4326 reg = &st->frame[0]->regs[i];
4327 bt_clear_reg(bt, i);
4328 if (reg->type == SCALAR_VALUE)
4329 reg->precise = true;
4334 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4335 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4336 WARN_ONCE(1, "verifier backtracking bug");
4340 for (i = last_idx;;) {
4345 hist = get_jmp_hist_entry(st, history, i);
4346 err = backtrack_insn(env, i, subseq_idx, hist, bt);
4348 if (err == -ENOTSUPP) {
4349 mark_all_scalars_precise(env, env->cur_state);
4356 /* Found assignment(s) into tracked register in this state.
4357 * Since this state is already marked, just return.
4358 * Nothing to be tracked further in the parent state.
4362 i = get_prev_insn_idx(st, i, &history);
4365 if (i >= env->prog->len) {
4366 /* This can happen if backtracking reached insn 0
4367 * and there are still reg_mask or stack_mask
4369 * It means the backtracking missed the spot where
4370 * particular register was initialized with a constant.
4372 verbose(env, "BUG backtracking idx %d\n", i);
4373 WARN_ONCE(1, "verifier backtracking bug");
4381 for (fr = bt->frame; fr >= 0; fr--) {
4382 func = st->frame[fr];
4383 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4384 for_each_set_bit(i, mask, 32) {
4385 reg = &func->regs[i];
4386 if (reg->type != SCALAR_VALUE) {
4387 bt_clear_frame_reg(bt, fr, i);
4391 bt_clear_frame_reg(bt, fr, i);
4393 reg->precise = true;
4396 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4397 for_each_set_bit(i, mask, 64) {
4398 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4399 verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
4400 i, func->allocated_stack / BPF_REG_SIZE);
4401 WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
4405 if (!is_spilled_scalar_reg(&func->stack[i])) {
4406 bt_clear_frame_slot(bt, fr, i);
4409 reg = &func->stack[i].spilled_ptr;
4411 bt_clear_frame_slot(bt, fr, i);
4413 reg->precise = true;
4415 if (env->log.level & BPF_LOG_LEVEL2) {
4416 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4417 bt_frame_reg_mask(bt, fr));
4418 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4419 fr, env->tmp_str_buf);
4420 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4421 bt_frame_stack_mask(bt, fr));
4422 verbose(env, "stack=%s: ", env->tmp_str_buf);
4423 print_verifier_state(env, func, true);
4430 subseq_idx = first_idx;
4431 last_idx = st->last_insn_idx;
4432 first_idx = st->first_insn_idx;
4435 /* if we still have requested precise regs or slots, we missed
4436 * something (e.g., stack access through non-r10 register), so
4437 * fallback to marking all precise
4439 if (!bt_empty(bt)) {
4440 mark_all_scalars_precise(env, env->cur_state);
4447 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4449 return __mark_chain_precision(env, regno);
4452 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4453 * desired reg and stack masks across all relevant frames
4455 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4457 return __mark_chain_precision(env, -1);
4460 static bool is_spillable_regtype(enum bpf_reg_type type)
4462 switch (base_type(type)) {
4463 case PTR_TO_MAP_VALUE:
4467 case PTR_TO_PACKET_META:
4468 case PTR_TO_PACKET_END:
4469 case PTR_TO_FLOW_KEYS:
4470 case CONST_PTR_TO_MAP:
4472 case PTR_TO_SOCK_COMMON:
4473 case PTR_TO_TCP_SOCK:
4474 case PTR_TO_XDP_SOCK:
4479 case PTR_TO_MAP_KEY:
4487 /* Does this register contain a constant zero? */
4488 static bool register_is_null(struct bpf_reg_state *reg)
4490 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4493 /* check if register is a constant scalar value */
4494 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4496 return reg->type == SCALAR_VALUE &&
4497 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4500 /* assuming is_reg_const() is true, return constant value of a register */
4501 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4503 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4506 static bool __is_pointer_value(bool allow_ptr_leaks,
4507 const struct bpf_reg_state *reg)
4509 if (allow_ptr_leaks)
4512 return reg->type != SCALAR_VALUE;
4515 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4516 struct bpf_reg_state *src_reg)
4518 if (src_reg->type != SCALAR_VALUE)
4521 if (src_reg->id & BPF_ADD_CONST) {
4523 * The verifier is processing rX = rY insn and
4524 * rY->id has special linked register already.
4525 * Cleared it, since multiple rX += const are not supported.
4531 if (!src_reg->id && !tnum_is_const(src_reg->var_off))
4532 /* Ensure that src_reg has a valid ID that will be copied to
4533 * dst_reg and then will be used by sync_linked_regs() to
4534 * propagate min/max range.
4536 src_reg->id = ++env->id_gen;
4539 /* Copy src state preserving dst->parent and dst->live fields */
4540 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4542 struct bpf_reg_state *parent = dst->parent;
4543 enum bpf_reg_liveness live = dst->live;
4546 dst->parent = parent;
4550 static void save_register_state(struct bpf_verifier_env *env,
4551 struct bpf_func_state *state,
4552 int spi, struct bpf_reg_state *reg,
4557 copy_register_state(&state->stack[spi].spilled_ptr, reg);
4558 if (size == BPF_REG_SIZE)
4559 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4561 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4562 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4564 /* size < 8 bytes spill */
4566 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4569 static bool is_bpf_st_mem(struct bpf_insn *insn)
4571 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4574 static int get_reg_width(struct bpf_reg_state *reg)
4576 return fls64(reg->umax_value);
4579 /* See comment for mark_fastcall_pattern_for_call() */
4580 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
4581 struct bpf_func_state *state, int insn_idx, int off)
4583 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
4584 struct bpf_insn_aux_data *aux = env->insn_aux_data;
4587 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
4589 /* access to the region [max_stack_depth .. fastcall_stack_off)
4590 * from something that is not a part of the fastcall pattern,
4591 * disable fastcall rewrites for current subprogram by setting
4592 * fastcall_stack_off to a value smaller than any possible offset.
4594 subprog->fastcall_stack_off = S16_MIN;
4595 /* reset fastcall aux flags within subprogram,
4596 * happens at most once per subprogram
4598 for (i = subprog->start; i < (subprog + 1)->start; ++i) {
4599 aux[i].fastcall_spills_num = 0;
4600 aux[i].fastcall_pattern = 0;
4604 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4605 * stack boundary and alignment are checked in check_mem_access()
4607 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4608 /* stack frame we're writing to */
4609 struct bpf_func_state *state,
4610 int off, int size, int value_regno,
4613 struct bpf_func_state *cur; /* state of the current function */
4614 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4615 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4616 struct bpf_reg_state *reg = NULL;
4617 int insn_flags = insn_stack_access_flags(state->frameno, spi);
4619 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4620 * so it's aligned access and [off, off + size) are within stack limits
4622 if (!env->allow_ptr_leaks &&
4623 is_spilled_reg(&state->stack[spi]) &&
4624 size != BPF_REG_SIZE) {
4625 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4629 cur = env->cur_state->frame[env->cur_state->curframe];
4630 if (value_regno >= 0)
4631 reg = &cur->regs[value_regno];
4632 if (!env->bypass_spec_v4) {
4633 bool sanitize = reg && is_spillable_regtype(reg->type);
4635 for (i = 0; i < size; i++) {
4636 u8 type = state->stack[spi].slot_type[i];
4638 if (type != STACK_MISC && type != STACK_ZERO) {
4645 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4648 err = destroy_if_dynptr_stack_slot(env, state, spi);
4652 check_fastcall_stack_contract(env, state, insn_idx, off);
4653 mark_stack_slot_scratched(env, spi);
4654 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
4655 bool reg_value_fits;
4657 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
4658 /* Make sure that reg had an ID to build a relation on spill. */
4660 assign_scalar_id_before_mov(env, reg);
4661 save_register_state(env, state, spi, reg, size);
4662 /* Break the relation on a narrowing spill. */
4663 if (!reg_value_fits)
4664 state->stack[spi].spilled_ptr.id = 0;
4665 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4667 struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
4669 memset(tmp_reg, 0, sizeof(*tmp_reg));
4670 __mark_reg_known(tmp_reg, insn->imm);
4671 tmp_reg->type = SCALAR_VALUE;
4672 save_register_state(env, state, spi, tmp_reg, size);
4673 } else if (reg && is_spillable_regtype(reg->type)) {
4674 /* register containing pointer is being spilled into stack */
4675 if (size != BPF_REG_SIZE) {
4676 verbose_linfo(env, insn_idx, "; ");
4677 verbose(env, "invalid size of register spill\n");
4680 if (state != cur && reg->type == PTR_TO_STACK) {
4681 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4684 save_register_state(env, state, spi, reg, size);
4686 u8 type = STACK_MISC;
4688 /* regular write of data into stack destroys any spilled ptr */
4689 state->stack[spi].spilled_ptr.type = NOT_INIT;
4690 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4691 if (is_stack_slot_special(&state->stack[spi]))
4692 for (i = 0; i < BPF_REG_SIZE; i++)
4693 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4695 /* only mark the slot as written if all 8 bytes were written
4696 * otherwise read propagation may incorrectly stop too soon
4697 * when stack slots are partially written.
4698 * This heuristic means that read propagation will be
4699 * conservative, since it will add reg_live_read marks
4700 * to stack slots all the way to first state when programs
4701 * writes+reads less than 8 bytes
4703 if (size == BPF_REG_SIZE)
4704 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4706 /* when we zero initialize stack slots mark them as such */
4707 if ((reg && register_is_null(reg)) ||
4708 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4709 /* STACK_ZERO case happened because register spill
4710 * wasn't properly aligned at the stack slot boundary,
4711 * so it's not a register spill anymore; force
4712 * originating register to be precise to make
4713 * STACK_ZERO correct for subsequent states
4715 err = mark_chain_precision(env, value_regno);
4721 /* Mark slots affected by this stack write. */
4722 for (i = 0; i < size; i++)
4723 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
4724 insn_flags = 0; /* not a register spill */
4728 return push_jmp_history(env, env->cur_state, insn_flags, 0);
4732 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4733 * known to contain a variable offset.
4734 * This function checks whether the write is permitted and conservatively
4735 * tracks the effects of the write, considering that each stack slot in the
4736 * dynamic range is potentially written to.
4738 * 'off' includes 'regno->off'.
4739 * 'value_regno' can be -1, meaning that an unknown value is being written to
4742 * Spilled pointers in range are not marked as written because we don't know
4743 * what's going to be actually written. This means that read propagation for
4744 * future reads cannot be terminated by this write.
4746 * For privileged programs, uninitialized stack slots are considered
4747 * initialized by this write (even though we don't know exactly what offsets
4748 * are going to be written to). The idea is that we don't want the verifier to
4749 * reject future reads that access slots written to through variable offsets.
4751 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4752 /* func where register points to */
4753 struct bpf_func_state *state,
4754 int ptr_regno, int off, int size,
4755 int value_regno, int insn_idx)
4757 struct bpf_func_state *cur; /* state of the current function */
4758 int min_off, max_off;
4760 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4761 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4762 bool writing_zero = false;
4763 /* set if the fact that we're writing a zero is used to let any
4764 * stack slots remain STACK_ZERO
4766 bool zero_used = false;
4768 cur = env->cur_state->frame[env->cur_state->curframe];
4769 ptr_reg = &cur->regs[ptr_regno];
4770 min_off = ptr_reg->smin_value + off;
4771 max_off = ptr_reg->smax_value + off + size;
4772 if (value_regno >= 0)
4773 value_reg = &cur->regs[value_regno];
4774 if ((value_reg && register_is_null(value_reg)) ||
4775 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4776 writing_zero = true;
4778 for (i = min_off; i < max_off; i++) {
4782 err = destroy_if_dynptr_stack_slot(env, state, spi);
4787 check_fastcall_stack_contract(env, state, insn_idx, min_off);
4788 /* Variable offset writes destroy any spilled pointers in range. */
4789 for (i = min_off; i < max_off; i++) {
4790 u8 new_type, *stype;
4794 spi = slot / BPF_REG_SIZE;
4795 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4796 mark_stack_slot_scratched(env, spi);
4798 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4799 /* Reject the write if range we may write to has not
4800 * been initialized beforehand. If we didn't reject
4801 * here, the ptr status would be erased below (even
4802 * though not all slots are actually overwritten),
4803 * possibly opening the door to leaks.
4805 * We do however catch STACK_INVALID case below, and
4806 * only allow reading possibly uninitialized memory
4807 * later for CAP_PERFMON, as the write may not happen to
4810 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4815 /* If writing_zero and the spi slot contains a spill of value 0,
4816 * maintain the spill type.
4818 if (writing_zero && *stype == STACK_SPILL &&
4819 is_spilled_scalar_reg(&state->stack[spi])) {
4820 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
4822 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
4828 /* Erase all other spilled pointers. */
4829 state->stack[spi].spilled_ptr.type = NOT_INIT;
4831 /* Update the slot type. */
4832 new_type = STACK_MISC;
4833 if (writing_zero && *stype == STACK_ZERO) {
4834 new_type = STACK_ZERO;
4837 /* If the slot is STACK_INVALID, we check whether it's OK to
4838 * pretend that it will be initialized by this write. The slot
4839 * might not actually be written to, and so if we mark it as
4840 * initialized future reads might leak uninitialized memory.
4841 * For privileged programs, we will accept such reads to slots
4842 * that may or may not be written because, if we're reject
4843 * them, the error would be too confusing.
4845 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4846 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4853 /* backtracking doesn't work for STACK_ZERO yet. */
4854 err = mark_chain_precision(env, value_regno);
4861 /* When register 'dst_regno' is assigned some values from stack[min_off,
4862 * max_off), we set the register's type according to the types of the
4863 * respective stack slots. If all the stack values are known to be zeros, then
4864 * so is the destination reg. Otherwise, the register is considered to be
4865 * SCALAR. This function does not deal with register filling; the caller must
4866 * ensure that all spilled registers in the stack range have been marked as
4869 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4870 /* func where src register points to */
4871 struct bpf_func_state *ptr_state,
4872 int min_off, int max_off, int dst_regno)
4874 struct bpf_verifier_state *vstate = env->cur_state;
4875 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4880 for (i = min_off; i < max_off; i++) {
4882 spi = slot / BPF_REG_SIZE;
4883 mark_stack_slot_scratched(env, spi);
4884 stype = ptr_state->stack[spi].slot_type;
4885 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4889 if (zeros == max_off - min_off) {
4890 /* Any access_size read into register is zero extended,
4891 * so the whole register == const_zero.
4893 __mark_reg_const_zero(env, &state->regs[dst_regno]);
4895 /* have read misc data from the stack */
4896 mark_reg_unknown(env, state->regs, dst_regno);
4898 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4901 /* Read the stack at 'off' and put the results into the register indicated by
4902 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4905 * 'dst_regno' can be -1, meaning that the read value is not going to a
4908 * The access is assumed to be within the current stack bounds.
4910 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4911 /* func where src register points to */
4912 struct bpf_func_state *reg_state,
4913 int off, int size, int dst_regno)
4915 struct bpf_verifier_state *vstate = env->cur_state;
4916 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4917 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4918 struct bpf_reg_state *reg;
4920 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
4922 stype = reg_state->stack[spi].slot_type;
4923 reg = ®_state->stack[spi].spilled_ptr;
4925 mark_stack_slot_scratched(env, spi);
4926 check_fastcall_stack_contract(env, state, env->insn_idx, off);
4928 if (is_spilled_reg(®_state->stack[spi])) {
4931 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4934 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4935 if (reg->type != SCALAR_VALUE) {
4936 verbose_linfo(env, env->insn_idx, "; ");
4937 verbose(env, "invalid size of register fill\n");
4941 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4945 if (size <= spill_size &&
4946 bpf_stack_narrow_access_ok(off, size, spill_size)) {
4947 /* The earlier check_reg_arg() has decided the
4948 * subreg_def for this insn. Save it first.
4950 s32 subreg_def = state->regs[dst_regno].subreg_def;
4952 copy_register_state(&state->regs[dst_regno], reg);
4953 state->regs[dst_regno].subreg_def = subreg_def;
4955 /* Break the relation on a narrowing fill.
4956 * coerce_reg_to_size will adjust the boundaries.
4958 if (get_reg_width(reg) > size * BITS_PER_BYTE)
4959 state->regs[dst_regno].id = 0;
4961 int spill_cnt = 0, zero_cnt = 0;
4963 for (i = 0; i < size; i++) {
4964 type = stype[(slot - i) % BPF_REG_SIZE];
4965 if (type == STACK_SPILL) {
4969 if (type == STACK_MISC)
4971 if (type == STACK_ZERO) {
4975 if (type == STACK_INVALID && env->allow_uninit_stack)
4977 verbose(env, "invalid read from stack off %d+%d size %d\n",
4982 if (spill_cnt == size &&
4983 tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
4984 __mark_reg_const_zero(env, &state->regs[dst_regno]);
4985 /* this IS register fill, so keep insn_flags */
4986 } else if (zero_cnt == size) {
4987 /* similarly to mark_reg_stack_read(), preserve zeroes */
4988 __mark_reg_const_zero(env, &state->regs[dst_regno]);
4989 insn_flags = 0; /* not restoring original register state */
4991 mark_reg_unknown(env, state->regs, dst_regno);
4992 insn_flags = 0; /* not restoring original register state */
4995 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4996 } else if (dst_regno >= 0) {
4997 /* restore register state from stack */
4998 copy_register_state(&state->regs[dst_regno], reg);
4999 /* mark reg as written since spilled pointer state likely
5000 * has its liveness marks cleared by is_state_visited()
5001 * which resets stack/reg liveness for state transitions
5003 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5004 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
5005 /* If dst_regno==-1, the caller is asking us whether
5006 * it is acceptable to use this value as a SCALAR_VALUE
5008 * We must not allow unprivileged callers to do that
5009 * with spilled pointers.
5011 verbose(env, "leaking pointer from stack off %d\n",
5015 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5017 for (i = 0; i < size; i++) {
5018 type = stype[(slot - i) % BPF_REG_SIZE];
5019 if (type == STACK_MISC)
5021 if (type == STACK_ZERO)
5023 if (type == STACK_INVALID && env->allow_uninit_stack)
5025 verbose(env, "invalid read from stack off %d+%d size %d\n",
5029 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5031 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5032 insn_flags = 0; /* we are not restoring spilled register */
5035 return push_jmp_history(env, env->cur_state, insn_flags, 0);
5039 enum bpf_access_src {
5040 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
5041 ACCESS_HELPER = 2, /* the access is performed by a helper */
5044 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5045 int regno, int off, int access_size,
5046 bool zero_size_allowed,
5047 enum bpf_access_src type,
5048 struct bpf_call_arg_meta *meta);
5050 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5052 return cur_regs(env) + regno;
5055 /* Read the stack at 'ptr_regno + off' and put the result into the register
5057 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5058 * but not its variable offset.
5059 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5061 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5062 * filling registers (i.e. reads of spilled register cannot be detected when
5063 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5064 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5065 * offset; for a fixed offset check_stack_read_fixed_off should be used
5068 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5069 int ptr_regno, int off, int size, int dst_regno)
5071 /* The state of the source register. */
5072 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5073 struct bpf_func_state *ptr_state = func(env, reg);
5075 int min_off, max_off;
5077 /* Note that we pass a NULL meta, so raw access will not be permitted.
5079 err = check_stack_range_initialized(env, ptr_regno, off, size,
5080 false, ACCESS_DIRECT, NULL);
5084 min_off = reg->smin_value + off;
5085 max_off = reg->smax_value + off;
5086 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5087 check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
5091 /* check_stack_read dispatches to check_stack_read_fixed_off or
5092 * check_stack_read_var_off.
5094 * The caller must ensure that the offset falls within the allocated stack
5097 * 'dst_regno' is a register which will receive the value from the stack. It
5098 * can be -1, meaning that the read value is not going to a register.
5100 static int check_stack_read(struct bpf_verifier_env *env,
5101 int ptr_regno, int off, int size,
5104 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5105 struct bpf_func_state *state = func(env, reg);
5107 /* Some accesses are only permitted with a static offset. */
5108 bool var_off = !tnum_is_const(reg->var_off);
5110 /* The offset is required to be static when reads don't go to a
5111 * register, in order to not leak pointers (see
5112 * check_stack_read_fixed_off).
5114 if (dst_regno < 0 && var_off) {
5117 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5118 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5122 /* Variable offset is prohibited for unprivileged mode for simplicity
5123 * since it requires corresponding support in Spectre masking for stack
5124 * ALU. See also retrieve_ptr_limit(). The check in
5125 * check_stack_access_for_ptr_arithmetic() called by
5126 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5127 * with variable offsets, therefore no check is required here. Further,
5128 * just checking it here would be insufficient as speculative stack
5129 * writes could still lead to unsafe speculative behaviour.
5132 off += reg->var_off.value;
5133 err = check_stack_read_fixed_off(env, state, off, size,
5136 /* Variable offset stack reads need more conservative handling
5137 * than fixed offset ones. Note that dst_regno >= 0 on this
5140 err = check_stack_read_var_off(env, ptr_regno, off, size,
5147 /* check_stack_write dispatches to check_stack_write_fixed_off or
5148 * check_stack_write_var_off.
5150 * 'ptr_regno' is the register used as a pointer into the stack.
5151 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5152 * 'value_regno' is the register whose value we're writing to the stack. It can
5153 * be -1, meaning that we're not writing from a register.
5155 * The caller must ensure that the offset falls within the maximum stack size.
5157 static int check_stack_write(struct bpf_verifier_env *env,
5158 int ptr_regno, int off, int size,
5159 int value_regno, int insn_idx)
5161 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5162 struct bpf_func_state *state = func(env, reg);
5165 if (tnum_is_const(reg->var_off)) {
5166 off += reg->var_off.value;
5167 err = check_stack_write_fixed_off(env, state, off, size,
5168 value_regno, insn_idx);
5170 /* Variable offset stack reads need more conservative handling
5171 * than fixed offset ones.
5173 err = check_stack_write_var_off(env, state,
5174 ptr_regno, off, size,
5175 value_regno, insn_idx);
5180 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5181 int off, int size, enum bpf_access_type type)
5183 struct bpf_reg_state *regs = cur_regs(env);
5184 struct bpf_map *map = regs[regno].map_ptr;
5185 u32 cap = bpf_map_flags_to_cap(map);
5187 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5188 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5189 map->value_size, off, size);
5193 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5194 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5195 map->value_size, off, size);
5202 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5203 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5204 int off, int size, u32 mem_size,
5205 bool zero_size_allowed)
5207 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5208 struct bpf_reg_state *reg;
5210 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5213 reg = &cur_regs(env)[regno];
5214 switch (reg->type) {
5215 case PTR_TO_MAP_KEY:
5216 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5217 mem_size, off, size);
5219 case PTR_TO_MAP_VALUE:
5220 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5221 mem_size, off, size);
5224 case PTR_TO_PACKET_META:
5225 case PTR_TO_PACKET_END:
5226 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5227 off, size, regno, reg->id, off, mem_size);
5231 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5232 mem_size, off, size);
5238 /* check read/write into a memory region with possible variable offset */
5239 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5240 int off, int size, u32 mem_size,
5241 bool zero_size_allowed)
5243 struct bpf_verifier_state *vstate = env->cur_state;
5244 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5245 struct bpf_reg_state *reg = &state->regs[regno];
5248 /* We may have adjusted the register pointing to memory region, so we
5249 * need to try adding each of min_value and max_value to off
5250 * to make sure our theoretical access will be safe.
5252 * The minimum value is only important with signed
5253 * comparisons where we can't assume the floor of a
5254 * value is 0. If we are using signed variables for our
5255 * index'es we need to make sure that whatever we use
5256 * will have a set floor within our range.
5258 if (reg->smin_value < 0 &&
5259 (reg->smin_value == S64_MIN ||
5260 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5261 reg->smin_value + off < 0)) {
5262 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5266 err = __check_mem_access(env, regno, reg->smin_value + off, size,
5267 mem_size, zero_size_allowed);
5269 verbose(env, "R%d min value is outside of the allowed memory range\n",
5274 /* If we haven't set a max value then we need to bail since we can't be
5275 * sure we won't do bad things.
5276 * If reg->umax_value + off could overflow, treat that as unbounded too.
5278 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5279 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5283 err = __check_mem_access(env, regno, reg->umax_value + off, size,
5284 mem_size, zero_size_allowed);
5286 verbose(env, "R%d max value is outside of the allowed memory range\n",
5294 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5295 const struct bpf_reg_state *reg, int regno,
5298 /* Access to this pointer-typed register or passing it to a helper
5299 * is only allowed in its original, unmodified form.
5303 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5304 reg_type_str(env, reg->type), regno, reg->off);
5308 if (!fixed_off_ok && reg->off) {
5309 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5310 reg_type_str(env, reg->type), regno, reg->off);
5314 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5317 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5318 verbose(env, "variable %s access var_off=%s disallowed\n",
5319 reg_type_str(env, reg->type), tn_buf);
5326 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5327 const struct bpf_reg_state *reg, int regno)
5329 return __check_ptr_off_reg(env, reg, regno, false);
5332 static int map_kptr_match_type(struct bpf_verifier_env *env,
5333 struct btf_field *kptr_field,
5334 struct bpf_reg_state *reg, u32 regno)
5336 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5338 const char *reg_name = "";
5340 if (btf_is_kernel(reg->btf)) {
5341 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5343 /* Only unreferenced case accepts untrusted pointers */
5344 if (kptr_field->type == BPF_KPTR_UNREF)
5345 perm_flags |= PTR_UNTRUSTED;
5347 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5348 if (kptr_field->type == BPF_KPTR_PERCPU)
5349 perm_flags |= MEM_PERCPU;
5352 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5355 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5356 reg_name = btf_type_name(reg->btf, reg->btf_id);
5358 /* For ref_ptr case, release function check should ensure we get one
5359 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5360 * normal store of unreferenced kptr, we must ensure var_off is zero.
5361 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5362 * reg->off and reg->ref_obj_id are not needed here.
5364 if (__check_ptr_off_reg(env, reg, regno, true))
5367 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5368 * we also need to take into account the reg->off.
5370 * We want to support cases like:
5378 * v = func(); // PTR_TO_BTF_ID
5379 * val->foo = v; // reg->off is zero, btf and btf_id match type
5380 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5381 * // first member type of struct after comparison fails
5382 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5385 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5386 * is zero. We must also ensure that btf_struct_ids_match does not walk
5387 * the struct to match type against first member of struct, i.e. reject
5388 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5389 * strict mode to true for type match.
5391 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5392 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5393 kptr_field->type != BPF_KPTR_UNREF))
5397 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5398 reg_type_str(env, reg->type), reg_name);
5399 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5400 if (kptr_field->type == BPF_KPTR_UNREF)
5401 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5408 static bool in_sleepable(struct bpf_verifier_env *env)
5410 return env->prog->sleepable ||
5411 (env->cur_state && env->cur_state->in_sleepable);
5414 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5415 * can dereference RCU protected pointers and result is PTR_TRUSTED.
5417 static bool in_rcu_cs(struct bpf_verifier_env *env)
5419 return env->cur_state->active_rcu_lock ||
5420 env->cur_state->active_lock.ptr ||
5424 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5425 BTF_SET_START(rcu_protected_types)
5426 BTF_ID(struct, prog_test_ref_kfunc)
5427 #ifdef CONFIG_CGROUPS
5428 BTF_ID(struct, cgroup)
5430 #ifdef CONFIG_BPF_JIT
5431 BTF_ID(struct, bpf_cpumask)
5433 BTF_ID(struct, task_struct)
5434 BTF_ID(struct, bpf_crypto_ctx)
5435 BTF_SET_END(rcu_protected_types)
5437 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5439 if (!btf_is_kernel(btf))
5441 return btf_id_set_contains(&rcu_protected_types, btf_id);
5444 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5446 struct btf_struct_meta *meta;
5448 if (btf_is_kernel(kptr_field->kptr.btf))
5451 meta = btf_find_struct_meta(kptr_field->kptr.btf,
5452 kptr_field->kptr.btf_id);
5454 return meta ? meta->record : NULL;
5457 static bool rcu_safe_kptr(const struct btf_field *field)
5459 const struct btf_field_kptr *kptr = &field->kptr;
5461 return field->type == BPF_KPTR_PERCPU ||
5462 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5465 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5467 struct btf_record *rec;
5470 ret = PTR_MAYBE_NULL;
5471 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5473 if (kptr_field->type == BPF_KPTR_PERCPU)
5475 else if (!btf_is_kernel(kptr_field->kptr.btf))
5478 rec = kptr_pointee_btf_record(kptr_field);
5479 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5482 ret |= PTR_UNTRUSTED;
5488 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5489 int value_regno, int insn_idx,
5490 struct btf_field *kptr_field)
5492 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5493 int class = BPF_CLASS(insn->code);
5494 struct bpf_reg_state *val_reg;
5496 /* Things we already checked for in check_map_access and caller:
5497 * - Reject cases where variable offset may touch kptr
5498 * - size of access (must be BPF_DW)
5499 * - tnum_is_const(reg->var_off)
5500 * - kptr_field->offset == off + reg->var_off.value
5502 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5503 if (BPF_MODE(insn->code) != BPF_MEM) {
5504 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5508 /* We only allow loading referenced kptr, since it will be marked as
5509 * untrusted, similar to unreferenced kptr.
5511 if (class != BPF_LDX &&
5512 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5513 verbose(env, "store to referenced kptr disallowed\n");
5517 if (class == BPF_LDX) {
5518 val_reg = reg_state(env, value_regno);
5519 /* We can simply mark the value_regno receiving the pointer
5520 * value from map as PTR_TO_BTF_ID, with the correct type.
5522 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5523 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5524 } else if (class == BPF_STX) {
5525 val_reg = reg_state(env, value_regno);
5526 if (!register_is_null(val_reg) &&
5527 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5529 } else if (class == BPF_ST) {
5531 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5532 kptr_field->offset);
5536 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5542 /* check read/write into a map element with possible variable offset */
5543 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5544 int off, int size, bool zero_size_allowed,
5545 enum bpf_access_src src)
5547 struct bpf_verifier_state *vstate = env->cur_state;
5548 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5549 struct bpf_reg_state *reg = &state->regs[regno];
5550 struct bpf_map *map = reg->map_ptr;
5551 struct btf_record *rec;
5554 err = check_mem_region_access(env, regno, off, size, map->value_size,
5559 if (IS_ERR_OR_NULL(map->record))
5562 for (i = 0; i < rec->cnt; i++) {
5563 struct btf_field *field = &rec->fields[i];
5564 u32 p = field->offset;
5566 /* If any part of a field can be touched by load/store, reject
5567 * this program. To check that [x1, x2) overlaps with [y1, y2),
5568 * it is sufficient to check x1 < y2 && y1 < x2.
5570 if (reg->smin_value + off < p + field->size &&
5571 p < reg->umax_value + off + size) {
5572 switch (field->type) {
5573 case BPF_KPTR_UNREF:
5575 case BPF_KPTR_PERCPU:
5576 if (src != ACCESS_DIRECT) {
5577 verbose(env, "kptr cannot be accessed indirectly by helper\n");
5580 if (!tnum_is_const(reg->var_off)) {
5581 verbose(env, "kptr access cannot have variable offset\n");
5584 if (p != off + reg->var_off.value) {
5585 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5586 p, off + reg->var_off.value);
5589 if (size != bpf_size_to_bytes(BPF_DW)) {
5590 verbose(env, "kptr access size must be BPF_DW\n");
5595 verbose(env, "%s cannot be accessed directly by load/store\n",
5596 btf_field_type_name(field->type));
5604 #define MAX_PACKET_OFF 0xffff
5606 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5607 const struct bpf_call_arg_meta *meta,
5608 enum bpf_access_type t)
5610 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5612 switch (prog_type) {
5613 /* Program types only with direct read access go here! */
5614 case BPF_PROG_TYPE_LWT_IN:
5615 case BPF_PROG_TYPE_LWT_OUT:
5616 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5617 case BPF_PROG_TYPE_SK_REUSEPORT:
5618 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5619 case BPF_PROG_TYPE_CGROUP_SKB:
5624 /* Program types with direct read + write access go here! */
5625 case BPF_PROG_TYPE_SCHED_CLS:
5626 case BPF_PROG_TYPE_SCHED_ACT:
5627 case BPF_PROG_TYPE_XDP:
5628 case BPF_PROG_TYPE_LWT_XMIT:
5629 case BPF_PROG_TYPE_SK_SKB:
5630 case BPF_PROG_TYPE_SK_MSG:
5632 return meta->pkt_access;
5634 env->seen_direct_write = true;
5637 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5639 env->seen_direct_write = true;
5648 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5649 int size, bool zero_size_allowed)
5651 struct bpf_reg_state *regs = cur_regs(env);
5652 struct bpf_reg_state *reg = ®s[regno];
5655 /* We may have added a variable offset to the packet pointer; but any
5656 * reg->range we have comes after that. We are only checking the fixed
5660 /* We don't allow negative numbers, because we aren't tracking enough
5661 * detail to prove they're safe.
5663 if (reg->smin_value < 0) {
5664 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5669 err = reg->range < 0 ? -EINVAL :
5670 __check_mem_access(env, regno, off, size, reg->range,
5673 verbose(env, "R%d offset is outside of the packet\n", regno);
5677 /* __check_mem_access has made sure "off + size - 1" is within u16.
5678 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5679 * otherwise find_good_pkt_pointers would have refused to set range info
5680 * that __check_mem_access would have rejected this pkt access.
5681 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5683 env->prog->aux->max_pkt_offset =
5684 max_t(u32, env->prog->aux->max_pkt_offset,
5685 off + reg->umax_value + size - 1);
5690 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
5691 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5692 enum bpf_access_type t, enum bpf_reg_type *reg_type,
5693 struct btf **btf, u32 *btf_id, bool *is_retval, bool is_ldsx)
5695 struct bpf_insn_access_aux info = {
5696 .reg_type = *reg_type,
5702 if (env->ops->is_valid_access &&
5703 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5704 /* A non zero info.ctx_field_size indicates that this field is a
5705 * candidate for later verifier transformation to load the whole
5706 * field and then apply a mask when accessed with a narrower
5707 * access than actual ctx access size. A zero info.ctx_field_size
5708 * will only allow for whole field access and rejects any other
5709 * type of narrower access.
5711 *reg_type = info.reg_type;
5712 *is_retval = info.is_retval;
5714 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5716 *btf_id = info.btf_id;
5718 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5720 /* remember the offset of last byte accessed in ctx */
5721 if (env->prog->aux->max_ctx_offset < off + size)
5722 env->prog->aux->max_ctx_offset = off + size;
5726 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5730 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5733 if (size < 0 || off < 0 ||
5734 (u64)off + size > sizeof(struct bpf_flow_keys)) {
5735 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5742 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5743 u32 regno, int off, int size,
5744 enum bpf_access_type t)
5746 struct bpf_reg_state *regs = cur_regs(env);
5747 struct bpf_reg_state *reg = ®s[regno];
5748 struct bpf_insn_access_aux info = {};
5751 if (reg->smin_value < 0) {
5752 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5757 switch (reg->type) {
5758 case PTR_TO_SOCK_COMMON:
5759 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5762 valid = bpf_sock_is_valid_access(off, size, t, &info);
5764 case PTR_TO_TCP_SOCK:
5765 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5767 case PTR_TO_XDP_SOCK:
5768 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5776 env->insn_aux_data[insn_idx].ctx_field_size =
5777 info.ctx_field_size;
5781 verbose(env, "R%d invalid %s access off=%d size=%d\n",
5782 regno, reg_type_str(env, reg->type), off, size);
5787 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5789 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5792 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5794 const struct bpf_reg_state *reg = reg_state(env, regno);
5796 return reg->type == PTR_TO_CTX;
5799 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5801 const struct bpf_reg_state *reg = reg_state(env, regno);
5803 return type_is_sk_pointer(reg->type);
5806 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5808 const struct bpf_reg_state *reg = reg_state(env, regno);
5810 return type_is_pkt_pointer(reg->type);
5813 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5815 const struct bpf_reg_state *reg = reg_state(env, regno);
5817 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5818 return reg->type == PTR_TO_FLOW_KEYS;
5821 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
5823 const struct bpf_reg_state *reg = reg_state(env, regno);
5825 return reg->type == PTR_TO_ARENA;
5828 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5830 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5831 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5832 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5834 [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5837 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5839 /* A referenced register is always trusted. */
5840 if (reg->ref_obj_id)
5843 /* Types listed in the reg2btf_ids are always trusted */
5844 if (reg2btf_ids[base_type(reg->type)] &&
5845 !bpf_type_has_unsafe_modifiers(reg->type))
5848 /* If a register is not referenced, it is trusted if it has the
5849 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5850 * other type modifiers may be safe, but we elect to take an opt-in
5851 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5854 * Eventually, we should make PTR_TRUSTED the single source of truth
5855 * for whether a register is trusted.
5857 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5858 !bpf_type_has_unsafe_modifiers(reg->type);
5861 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5863 return reg->type & MEM_RCU;
5866 static void clear_trusted_flags(enum bpf_type_flag *flag)
5868 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5871 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5872 const struct bpf_reg_state *reg,
5873 int off, int size, bool strict)
5875 struct tnum reg_off;
5878 /* Byte size accesses are always allowed. */
5879 if (!strict || size == 1)
5882 /* For platforms that do not have a Kconfig enabling
5883 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5884 * NET_IP_ALIGN is universally set to '2'. And on platforms
5885 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5886 * to this code only in strict mode where we want to emulate
5887 * the NET_IP_ALIGN==2 checking. Therefore use an
5888 * unconditional IP align value of '2'.
5892 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5893 if (!tnum_is_aligned(reg_off, size)) {
5896 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5898 "misaligned packet access off %d+%s+%d+%d size %d\n",
5899 ip_align, tn_buf, reg->off, off, size);
5906 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5907 const struct bpf_reg_state *reg,
5908 const char *pointer_desc,
5909 int off, int size, bool strict)
5911 struct tnum reg_off;
5913 /* Byte size accesses are always allowed. */
5914 if (!strict || size == 1)
5917 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5918 if (!tnum_is_aligned(reg_off, size)) {
5921 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5922 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5923 pointer_desc, tn_buf, reg->off, off, size);
5930 static int check_ptr_alignment(struct bpf_verifier_env *env,
5931 const struct bpf_reg_state *reg, int off,
5932 int size, bool strict_alignment_once)
5934 bool strict = env->strict_alignment || strict_alignment_once;
5935 const char *pointer_desc = "";
5937 switch (reg->type) {
5939 case PTR_TO_PACKET_META:
5940 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5941 * right in front, treat it the very same way.
5943 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5944 case PTR_TO_FLOW_KEYS:
5945 pointer_desc = "flow keys ";
5947 case PTR_TO_MAP_KEY:
5948 pointer_desc = "key ";
5950 case PTR_TO_MAP_VALUE:
5951 pointer_desc = "value ";
5954 pointer_desc = "context ";
5957 pointer_desc = "stack ";
5958 /* The stack spill tracking logic in check_stack_write_fixed_off()
5959 * and check_stack_read_fixed_off() relies on stack accesses being
5965 pointer_desc = "sock ";
5967 case PTR_TO_SOCK_COMMON:
5968 pointer_desc = "sock_common ";
5970 case PTR_TO_TCP_SOCK:
5971 pointer_desc = "tcp_sock ";
5973 case PTR_TO_XDP_SOCK:
5974 pointer_desc = "xdp_sock ";
5981 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5985 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
5987 if (env->prog->jit_requested)
5988 return round_up(stack_depth, 16);
5990 /* round up to 32-bytes, since this is granularity
5991 * of interpreter stack size
5993 return round_up(max_t(u32, stack_depth, 1), 32);
5996 /* starting from main bpf function walk all instructions of the function
5997 * and recursively walk all callees that given function can call.
5998 * Ignore jump and exit insns.
5999 * Since recursion is prevented by check_cfg() this algorithm
6000 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
6002 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
6004 struct bpf_subprog_info *subprog = env->subprog_info;
6005 struct bpf_insn *insn = env->prog->insnsi;
6006 int depth = 0, frame = 0, i, subprog_end;
6007 bool tail_call_reachable = false;
6008 int ret_insn[MAX_CALL_FRAMES];
6009 int ret_prog[MAX_CALL_FRAMES];
6012 i = subprog[idx].start;
6014 /* protect against potential stack overflow that might happen when
6015 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
6016 * depth for such case down to 256 so that the worst case scenario
6017 * would result in 8k stack size (32 which is tailcall limit * 256 =
6020 * To get the idea what might happen, see an example:
6021 * func1 -> sub rsp, 128
6022 * subfunc1 -> sub rsp, 256
6023 * tailcall1 -> add rsp, 256
6024 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6025 * subfunc2 -> sub rsp, 64
6026 * subfunc22 -> sub rsp, 128
6027 * tailcall2 -> add rsp, 128
6028 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6030 * tailcall will unwind the current stack frame but it will not get rid
6031 * of caller's stack as shown on the example above.
6033 if (idx && subprog[idx].has_tail_call && depth >= 256) {
6035 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6039 depth += round_up_stack_depth(env, subprog[idx].stack_depth);
6040 if (depth > MAX_BPF_STACK) {
6041 verbose(env, "combined stack size of %d calls is %d. Too large\n",
6046 subprog_end = subprog[idx + 1].start;
6047 for (; i < subprog_end; i++) {
6048 int next_insn, sidx;
6050 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6053 if (!is_bpf_throw_kfunc(insn + i))
6055 if (subprog[idx].is_cb)
6057 for (int c = 0; c < frame && !err; c++) {
6058 if (subprog[ret_prog[c]].is_cb) {
6066 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6071 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6073 /* remember insn and function to return to */
6074 ret_insn[frame] = i + 1;
6075 ret_prog[frame] = idx;
6077 /* find the callee */
6078 next_insn = i + insn[i].imm + 1;
6079 sidx = find_subprog(env, next_insn);
6081 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6085 if (subprog[sidx].is_async_cb) {
6086 if (subprog[sidx].has_tail_call) {
6087 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
6090 /* async callbacks don't increase bpf prog stack size unless called directly */
6091 if (!bpf_pseudo_call(insn + i))
6093 if (subprog[sidx].is_exception_cb) {
6094 verbose(env, "insn %d cannot call exception cb directly\n", i);
6101 if (subprog[idx].has_tail_call)
6102 tail_call_reachable = true;
6105 if (frame >= MAX_CALL_FRAMES) {
6106 verbose(env, "the call stack of %d frames is too deep !\n",
6112 /* if tail call got detected across bpf2bpf calls then mark each of the
6113 * currently present subprog frames as tail call reachable subprogs;
6114 * this info will be utilized by JIT so that we will be preserving the
6115 * tail call counter throughout bpf2bpf calls combined with tailcalls
6117 if (tail_call_reachable)
6118 for (j = 0; j < frame; j++) {
6119 if (subprog[ret_prog[j]].is_exception_cb) {
6120 verbose(env, "cannot tail call within exception cb\n");
6123 subprog[ret_prog[j]].tail_call_reachable = true;
6125 if (subprog[0].tail_call_reachable)
6126 env->prog->aux->tail_call_reachable = true;
6128 /* end of for() loop means the last insn of the 'subprog'
6129 * was reached. Doesn't matter whether it was JA or EXIT
6133 depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6135 i = ret_insn[frame];
6136 idx = ret_prog[frame];
6140 static int check_max_stack_depth(struct bpf_verifier_env *env)
6142 struct bpf_subprog_info *si = env->subprog_info;
6145 for (int i = 0; i < env->subprog_cnt; i++) {
6146 if (!i || si[i].is_async_cb) {
6147 ret = check_max_stack_depth_subprog(env, i);
6156 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6157 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6158 const struct bpf_insn *insn, int idx)
6160 int start = idx + insn->imm + 1, subprog;
6162 subprog = find_subprog(env, start);
6164 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6168 return env->subprog_info[subprog].stack_depth;
6172 static int __check_buffer_access(struct bpf_verifier_env *env,
6173 const char *buf_info,
6174 const struct bpf_reg_state *reg,
6175 int regno, int off, int size)
6179 "R%d invalid %s buffer access: off=%d, size=%d\n",
6180 regno, buf_info, off, size);
6183 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6186 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6188 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6189 regno, off, tn_buf);
6196 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6197 const struct bpf_reg_state *reg,
6198 int regno, int off, int size)
6202 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6206 if (off + size > env->prog->aux->max_tp_access)
6207 env->prog->aux->max_tp_access = off + size;
6212 static int check_buffer_access(struct bpf_verifier_env *env,
6213 const struct bpf_reg_state *reg,
6214 int regno, int off, int size,
6215 bool zero_size_allowed,
6218 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6221 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6225 if (off + size > *max_access)
6226 *max_access = off + size;
6231 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6232 static void zext_32_to_64(struct bpf_reg_state *reg)
6234 reg->var_off = tnum_subreg(reg->var_off);
6235 __reg_assign_32_into_64(reg);
6238 /* truncate register to smaller size (in bytes)
6239 * must be called with size < BPF_REG_SIZE
6241 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6245 /* clear high bits in bit representation */
6246 reg->var_off = tnum_cast(reg->var_off, size);
6248 /* fix arithmetic bounds */
6249 mask = ((u64)1 << (size * 8)) - 1;
6250 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6251 reg->umin_value &= mask;
6252 reg->umax_value &= mask;
6254 reg->umin_value = 0;
6255 reg->umax_value = mask;
6257 reg->smin_value = reg->umin_value;
6258 reg->smax_value = reg->umax_value;
6260 /* If size is smaller than 32bit register the 32bit register
6261 * values are also truncated so we push 64-bit bounds into
6262 * 32-bit bounds. Above were truncated < 32-bits already.
6265 __mark_reg32_unbounded(reg);
6267 reg_bounds_sync(reg);
6270 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6273 reg->smin_value = reg->s32_min_value = S8_MIN;
6274 reg->smax_value = reg->s32_max_value = S8_MAX;
6275 } else if (size == 2) {
6276 reg->smin_value = reg->s32_min_value = S16_MIN;
6277 reg->smax_value = reg->s32_max_value = S16_MAX;
6280 reg->smin_value = reg->s32_min_value = S32_MIN;
6281 reg->smax_value = reg->s32_max_value = S32_MAX;
6283 reg->umin_value = reg->u32_min_value = 0;
6284 reg->umax_value = U64_MAX;
6285 reg->u32_max_value = U32_MAX;
6286 reg->var_off = tnum_unknown;
6289 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6291 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6292 u64 top_smax_value, top_smin_value;
6293 u64 num_bits = size * 8;
6295 if (tnum_is_const(reg->var_off)) {
6296 u64_cval = reg->var_off.value;
6298 reg->var_off = tnum_const((s8)u64_cval);
6300 reg->var_off = tnum_const((s16)u64_cval);
6303 reg->var_off = tnum_const((s32)u64_cval);
6305 u64_cval = reg->var_off.value;
6306 reg->smax_value = reg->smin_value = u64_cval;
6307 reg->umax_value = reg->umin_value = u64_cval;
6308 reg->s32_max_value = reg->s32_min_value = u64_cval;
6309 reg->u32_max_value = reg->u32_min_value = u64_cval;
6313 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6314 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6316 if (top_smax_value != top_smin_value)
6319 /* find the s64_min and s64_min after sign extension */
6321 init_s64_max = (s8)reg->smax_value;
6322 init_s64_min = (s8)reg->smin_value;
6323 } else if (size == 2) {
6324 init_s64_max = (s16)reg->smax_value;
6325 init_s64_min = (s16)reg->smin_value;
6327 init_s64_max = (s32)reg->smax_value;
6328 init_s64_min = (s32)reg->smin_value;
6331 s64_max = max(init_s64_max, init_s64_min);
6332 s64_min = min(init_s64_max, init_s64_min);
6334 /* both of s64_max/s64_min positive or negative */
6335 if ((s64_max >= 0) == (s64_min >= 0)) {
6336 reg->smin_value = reg->s32_min_value = s64_min;
6337 reg->smax_value = reg->s32_max_value = s64_max;
6338 reg->umin_value = reg->u32_min_value = s64_min;
6339 reg->umax_value = reg->u32_max_value = s64_max;
6340 reg->var_off = tnum_range(s64_min, s64_max);
6345 set_sext64_default_val(reg, size);
6348 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6351 reg->s32_min_value = S8_MIN;
6352 reg->s32_max_value = S8_MAX;
6355 reg->s32_min_value = S16_MIN;
6356 reg->s32_max_value = S16_MAX;
6358 reg->u32_min_value = 0;
6359 reg->u32_max_value = U32_MAX;
6360 reg->var_off = tnum_subreg(tnum_unknown);
6363 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6365 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6366 u32 top_smax_value, top_smin_value;
6367 u32 num_bits = size * 8;
6369 if (tnum_is_const(reg->var_off)) {
6370 u32_val = reg->var_off.value;
6372 reg->var_off = tnum_const((s8)u32_val);
6374 reg->var_off = tnum_const((s16)u32_val);
6376 u32_val = reg->var_off.value;
6377 reg->s32_min_value = reg->s32_max_value = u32_val;
6378 reg->u32_min_value = reg->u32_max_value = u32_val;
6382 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6383 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6385 if (top_smax_value != top_smin_value)
6388 /* find the s32_min and s32_min after sign extension */
6390 init_s32_max = (s8)reg->s32_max_value;
6391 init_s32_min = (s8)reg->s32_min_value;
6394 init_s32_max = (s16)reg->s32_max_value;
6395 init_s32_min = (s16)reg->s32_min_value;
6397 s32_max = max(init_s32_max, init_s32_min);
6398 s32_min = min(init_s32_max, init_s32_min);
6400 if ((s32_min >= 0) == (s32_max >= 0)) {
6401 reg->s32_min_value = s32_min;
6402 reg->s32_max_value = s32_max;
6403 reg->u32_min_value = (u32)s32_min;
6404 reg->u32_max_value = (u32)s32_max;
6405 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6410 set_sext32_default_val(reg, size);
6413 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6415 /* A map is considered read-only if the following condition are true:
6417 * 1) BPF program side cannot change any of the map content. The
6418 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6419 * and was set at map creation time.
6420 * 2) The map value(s) have been initialized from user space by a
6421 * loader and then "frozen", such that no new map update/delete
6422 * operations from syscall side are possible for the rest of
6423 * the map's lifetime from that point onwards.
6424 * 3) Any parallel/pending map update/delete operations from syscall
6425 * side have been completed. Only after that point, it's safe to
6426 * assume that map value(s) are immutable.
6428 return (map->map_flags & BPF_F_RDONLY_PROG) &&
6429 READ_ONCE(map->frozen) &&
6430 !bpf_map_write_active(map);
6433 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6440 err = map->ops->map_direct_value_addr(map, &addr, off);
6443 ptr = (void *)(long)addr + off;
6447 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6450 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6453 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6464 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
6465 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
6466 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
6467 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null)
6470 * Allow list few fields as RCU trusted or full trusted.
6471 * This logic doesn't allow mix tagging and will be removed once GCC supports
6475 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6476 BTF_TYPE_SAFE_RCU(struct task_struct) {
6477 const cpumask_t *cpus_ptr;
6478 struct css_set __rcu *cgroups;
6479 struct task_struct __rcu *real_parent;
6480 struct task_struct *group_leader;
6483 BTF_TYPE_SAFE_RCU(struct cgroup) {
6484 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6485 struct kernfs_node *kn;
6488 BTF_TYPE_SAFE_RCU(struct css_set) {
6489 struct cgroup *dfl_cgrp;
6492 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6493 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6494 struct file __rcu *exe_file;
6497 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6498 * because bpf prog accessible sockets are SOCK_RCU_FREE.
6500 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6504 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6508 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6509 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6510 struct seq_file *seq;
6513 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6514 struct bpf_iter_meta *meta;
6515 struct task_struct *task;
6518 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6522 BTF_TYPE_SAFE_TRUSTED(struct file) {
6523 struct inode *f_inode;
6526 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6527 /* no negative dentry-s in places where bpf can see it */
6528 struct inode *d_inode;
6531 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6535 static bool type_is_rcu(struct bpf_verifier_env *env,
6536 struct bpf_reg_state *reg,
6537 const char *field_name, u32 btf_id)
6539 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6540 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6541 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6543 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6546 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6547 struct bpf_reg_state *reg,
6548 const char *field_name, u32 btf_id)
6550 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6551 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6552 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6554 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6557 static bool type_is_trusted(struct bpf_verifier_env *env,
6558 struct bpf_reg_state *reg,
6559 const char *field_name, u32 btf_id)
6561 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6562 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6563 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6564 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6565 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6567 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6570 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6571 struct bpf_reg_state *reg,
6572 const char *field_name, u32 btf_id)
6574 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6576 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6577 "__safe_trusted_or_null");
6580 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6581 struct bpf_reg_state *regs,
6582 int regno, int off, int size,
6583 enum bpf_access_type atype,
6586 struct bpf_reg_state *reg = regs + regno;
6587 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6588 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6589 const char *field_name = NULL;
6590 enum bpf_type_flag flag = 0;
6594 if (!env->allow_ptr_leaks) {
6596 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6600 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6602 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6608 "R%d is ptr_%s invalid negative access: off=%d\n",
6612 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6615 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6617 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6618 regno, tname, off, tn_buf);
6622 if (reg->type & MEM_USER) {
6624 "R%d is ptr_%s access user memory: off=%d\n",
6629 if (reg->type & MEM_PERCPU) {
6631 "R%d is ptr_%s access percpu memory: off=%d\n",
6636 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6637 if (!btf_is_kernel(reg->btf)) {
6638 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6641 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6643 /* Writes are permitted with default btf_struct_access for
6644 * program allocated objects (which always have ref_obj_id > 0),
6645 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6647 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6648 verbose(env, "only read is supported\n");
6652 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6653 !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6654 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6658 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6664 if (ret != PTR_TO_BTF_ID) {
6667 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6668 /* If this is an untrusted pointer, all pointers formed by walking it
6669 * also inherit the untrusted flag.
6671 flag = PTR_UNTRUSTED;
6673 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6674 /* By default any pointer obtained from walking a trusted pointer is no
6675 * longer trusted, unless the field being accessed has explicitly been
6676 * marked as inheriting its parent's state of trust (either full or RCU).
6678 * 'cgroups' pointer is untrusted if task->cgroups dereference
6679 * happened in a sleepable program outside of bpf_rcu_read_lock()
6680 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6681 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6683 * A regular RCU-protected pointer with __rcu tag can also be deemed
6684 * trusted if we are in an RCU CS. Such pointer can be NULL.
6686 if (type_is_trusted(env, reg, field_name, btf_id)) {
6687 flag |= PTR_TRUSTED;
6688 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
6689 flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
6690 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6691 if (type_is_rcu(env, reg, field_name, btf_id)) {
6692 /* ignore __rcu tag and mark it MEM_RCU */
6694 } else if (flag & MEM_RCU ||
6695 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6696 /* __rcu tagged pointers can be NULL */
6697 flag |= MEM_RCU | PTR_MAYBE_NULL;
6699 /* We always trust them */
6700 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6701 flag & PTR_UNTRUSTED)
6702 flag &= ~PTR_UNTRUSTED;
6703 } else if (flag & (MEM_PERCPU | MEM_USER)) {
6706 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6707 clear_trusted_flags(&flag);
6711 * If not in RCU CS or MEM_RCU pointer can be NULL then
6712 * aggressively mark as untrusted otherwise such
6713 * pointers will be plain PTR_TO_BTF_ID without flags
6714 * and will be allowed to be passed into helpers for
6717 flag = PTR_UNTRUSTED;
6720 /* Old compat. Deprecated */
6721 clear_trusted_flags(&flag);
6724 if (atype == BPF_READ && value_regno >= 0)
6725 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6730 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6731 struct bpf_reg_state *regs,
6732 int regno, int off, int size,
6733 enum bpf_access_type atype,
6736 struct bpf_reg_state *reg = regs + regno;
6737 struct bpf_map *map = reg->map_ptr;
6738 struct bpf_reg_state map_reg;
6739 enum bpf_type_flag flag = 0;
6740 const struct btf_type *t;
6746 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6750 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6751 verbose(env, "map_ptr access not supported for map type %d\n",
6756 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6757 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6759 if (!env->allow_ptr_leaks) {
6761 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6767 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6772 if (atype != BPF_READ) {
6773 verbose(env, "only read from %s is supported\n", tname);
6777 /* Simulate access to a PTR_TO_BTF_ID */
6778 memset(&map_reg, 0, sizeof(map_reg));
6779 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6780 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6784 if (value_regno >= 0)
6785 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6790 /* Check that the stack access at the given offset is within bounds. The
6791 * maximum valid offset is -1.
6793 * The minimum valid offset is -MAX_BPF_STACK for writes, and
6794 * -state->allocated_stack for reads.
6796 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6798 struct bpf_func_state *state,
6799 enum bpf_access_type t)
6801 struct bpf_insn_aux_data *aux = &env->insn_aux_data[env->insn_idx];
6802 int min_valid_off, max_bpf_stack;
6804 /* If accessing instruction is a spill/fill from bpf_fastcall pattern,
6805 * add room for all caller saved registers below MAX_BPF_STACK.
6806 * In case if bpf_fastcall rewrite won't happen maximal stack depth
6807 * would be checked by check_max_stack_depth_subprog().
6809 max_bpf_stack = MAX_BPF_STACK;
6810 if (aux->fastcall_pattern)
6811 max_bpf_stack += CALLER_SAVED_REGS * BPF_REG_SIZE;
6813 if (t == BPF_WRITE || env->allow_uninit_stack)
6814 min_valid_off = -max_bpf_stack;
6816 min_valid_off = -state->allocated_stack;
6818 if (off < min_valid_off || off > -1)
6823 /* Check that the stack access at 'regno + off' falls within the maximum stack
6826 * 'off' includes `regno->offset`, but not its dynamic part (if any).
6828 static int check_stack_access_within_bounds(
6829 struct bpf_verifier_env *env,
6830 int regno, int off, int access_size,
6831 enum bpf_access_src src, enum bpf_access_type type)
6833 struct bpf_reg_state *regs = cur_regs(env);
6834 struct bpf_reg_state *reg = regs + regno;
6835 struct bpf_func_state *state = func(env, reg);
6836 s64 min_off, max_off;
6840 if (src == ACCESS_HELPER)
6841 /* We don't know if helpers are reading or writing (or both). */
6842 err_extra = " indirect access to";
6843 else if (type == BPF_READ)
6844 err_extra = " read from";
6846 err_extra = " write to";
6848 if (tnum_is_const(reg->var_off)) {
6849 min_off = (s64)reg->var_off.value + off;
6850 max_off = min_off + access_size;
6852 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6853 reg->smin_value <= -BPF_MAX_VAR_OFF) {
6854 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6858 min_off = reg->smin_value + off;
6859 max_off = reg->smax_value + off + access_size;
6862 err = check_stack_slot_within_bounds(env, min_off, state, type);
6863 if (!err && max_off > 0)
6864 err = -EINVAL; /* out of stack access into non-negative offsets */
6865 if (!err && access_size < 0)
6866 /* access_size should not be negative (or overflow an int); others checks
6867 * along the way should have prevented such an access.
6869 err = -EFAULT; /* invalid negative access size; integer overflow? */
6872 if (tnum_is_const(reg->var_off)) {
6873 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6874 err_extra, regno, off, access_size);
6878 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6879 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
6880 err_extra, regno, tn_buf, off, access_size);
6885 /* Note that there is no stack access with offset zero, so the needed stack
6886 * size is -min_off, not -min_off+1.
6888 return grow_stack_state(env, state, -min_off /* size */);
6891 static bool get_func_retval_range(struct bpf_prog *prog,
6892 struct bpf_retval_range *range)
6894 if (prog->type == BPF_PROG_TYPE_LSM &&
6895 prog->expected_attach_type == BPF_LSM_MAC &&
6896 !bpf_lsm_get_retval_range(prog, range)) {
6902 /* check whether memory at (regno + off) is accessible for t = (read | write)
6903 * if t==write, value_regno is a register which value is stored into memory
6904 * if t==read, value_regno is a register which will receive the value from memory
6905 * if t==write && value_regno==-1, some unknown value is stored into memory
6906 * if t==read && value_regno==-1, don't care what we read from memory
6908 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6909 int off, int bpf_size, enum bpf_access_type t,
6910 int value_regno, bool strict_alignment_once, bool is_ldsx)
6912 struct bpf_reg_state *regs = cur_regs(env);
6913 struct bpf_reg_state *reg = regs + regno;
6916 size = bpf_size_to_bytes(bpf_size);
6920 /* alignment checks will add in reg->off themselves */
6921 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6925 /* for access checks, reg->off is just part of off */
6928 if (reg->type == PTR_TO_MAP_KEY) {
6929 if (t == BPF_WRITE) {
6930 verbose(env, "write to change key R%d not allowed\n", regno);
6934 err = check_mem_region_access(env, regno, off, size,
6935 reg->map_ptr->key_size, false);
6938 if (value_regno >= 0)
6939 mark_reg_unknown(env, regs, value_regno);
6940 } else if (reg->type == PTR_TO_MAP_VALUE) {
6941 struct btf_field *kptr_field = NULL;
6943 if (t == BPF_WRITE && value_regno >= 0 &&
6944 is_pointer_value(env, value_regno)) {
6945 verbose(env, "R%d leaks addr into map\n", value_regno);
6948 err = check_map_access_type(env, regno, off, size, t);
6951 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6954 if (tnum_is_const(reg->var_off))
6955 kptr_field = btf_record_find(reg->map_ptr->record,
6956 off + reg->var_off.value, BPF_KPTR);
6958 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6959 } else if (t == BPF_READ && value_regno >= 0) {
6960 struct bpf_map *map = reg->map_ptr;
6962 /* if map is read-only, track its contents as scalars */
6963 if (tnum_is_const(reg->var_off) &&
6964 bpf_map_is_rdonly(map) &&
6965 map->ops->map_direct_value_addr) {
6966 int map_off = off + reg->var_off.value;
6969 err = bpf_map_direct_read(map, map_off, size,
6974 regs[value_regno].type = SCALAR_VALUE;
6975 __mark_reg_known(®s[value_regno], val);
6977 mark_reg_unknown(env, regs, value_regno);
6980 } else if (base_type(reg->type) == PTR_TO_MEM) {
6981 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6983 if (type_may_be_null(reg->type)) {
6984 verbose(env, "R%d invalid mem access '%s'\n", regno,
6985 reg_type_str(env, reg->type));
6989 if (t == BPF_WRITE && rdonly_mem) {
6990 verbose(env, "R%d cannot write into %s\n",
6991 regno, reg_type_str(env, reg->type));
6995 if (t == BPF_WRITE && value_regno >= 0 &&
6996 is_pointer_value(env, value_regno)) {
6997 verbose(env, "R%d leaks addr into mem\n", value_regno);
7001 err = check_mem_region_access(env, regno, off, size,
7002 reg->mem_size, false);
7003 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7004 mark_reg_unknown(env, regs, value_regno);
7005 } else if (reg->type == PTR_TO_CTX) {
7006 bool is_retval = false;
7007 struct bpf_retval_range range;
7008 enum bpf_reg_type reg_type = SCALAR_VALUE;
7009 struct btf *btf = NULL;
7012 if (t == BPF_WRITE && value_regno >= 0 &&
7013 is_pointer_value(env, value_regno)) {
7014 verbose(env, "R%d leaks addr into ctx\n", value_regno);
7018 err = check_ptr_off_reg(env, reg, regno);
7022 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
7023 &btf_id, &is_retval, is_ldsx);
7025 verbose_linfo(env, insn_idx, "; ");
7026 if (!err && t == BPF_READ && value_regno >= 0) {
7027 /* ctx access returns either a scalar, or a
7028 * PTR_TO_PACKET[_META,_END]. In the latter
7029 * case, we know the offset is zero.
7031 if (reg_type == SCALAR_VALUE) {
7032 if (is_retval && get_func_retval_range(env->prog, &range)) {
7033 err = __mark_reg_s32_range(env, regs, value_regno,
7034 range.minval, range.maxval);
7038 mark_reg_unknown(env, regs, value_regno);
7041 mark_reg_known_zero(env, regs,
7043 if (type_may_be_null(reg_type))
7044 regs[value_regno].id = ++env->id_gen;
7045 /* A load of ctx field could have different
7046 * actual load size with the one encoded in the
7047 * insn. When the dst is PTR, it is for sure not
7050 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
7051 if (base_type(reg_type) == PTR_TO_BTF_ID) {
7052 regs[value_regno].btf = btf;
7053 regs[value_regno].btf_id = btf_id;
7056 regs[value_regno].type = reg_type;
7059 } else if (reg->type == PTR_TO_STACK) {
7060 /* Basic bounds checks. */
7061 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
7066 err = check_stack_read(env, regno, off, size,
7069 err = check_stack_write(env, regno, off, size,
7070 value_regno, insn_idx);
7071 } else if (reg_is_pkt_pointer(reg)) {
7072 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7073 verbose(env, "cannot write into packet\n");
7076 if (t == BPF_WRITE && value_regno >= 0 &&
7077 is_pointer_value(env, value_regno)) {
7078 verbose(env, "R%d leaks addr into packet\n",
7082 err = check_packet_access(env, regno, off, size, false);
7083 if (!err && t == BPF_READ && value_regno >= 0)
7084 mark_reg_unknown(env, regs, value_regno);
7085 } else if (reg->type == PTR_TO_FLOW_KEYS) {
7086 if (t == BPF_WRITE && value_regno >= 0 &&
7087 is_pointer_value(env, value_regno)) {
7088 verbose(env, "R%d leaks addr into flow keys\n",
7093 err = check_flow_keys_access(env, off, size);
7094 if (!err && t == BPF_READ && value_regno >= 0)
7095 mark_reg_unknown(env, regs, value_regno);
7096 } else if (type_is_sk_pointer(reg->type)) {
7097 if (t == BPF_WRITE) {
7098 verbose(env, "R%d cannot write into %s\n",
7099 regno, reg_type_str(env, reg->type));
7102 err = check_sock_access(env, insn_idx, regno, off, size, t);
7103 if (!err && value_regno >= 0)
7104 mark_reg_unknown(env, regs, value_regno);
7105 } else if (reg->type == PTR_TO_TP_BUFFER) {
7106 err = check_tp_buffer_access(env, reg, regno, off, size);
7107 if (!err && t == BPF_READ && value_regno >= 0)
7108 mark_reg_unknown(env, regs, value_regno);
7109 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7110 !type_may_be_null(reg->type)) {
7111 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7113 } else if (reg->type == CONST_PTR_TO_MAP) {
7114 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7116 } else if (base_type(reg->type) == PTR_TO_BUF) {
7117 bool rdonly_mem = type_is_rdonly_mem(reg->type);
7121 if (t == BPF_WRITE) {
7122 verbose(env, "R%d cannot write into %s\n",
7123 regno, reg_type_str(env, reg->type));
7126 max_access = &env->prog->aux->max_rdonly_access;
7128 max_access = &env->prog->aux->max_rdwr_access;
7131 err = check_buffer_access(env, reg, regno, off, size, false,
7134 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7135 mark_reg_unknown(env, regs, value_regno);
7136 } else if (reg->type == PTR_TO_ARENA) {
7137 if (t == BPF_READ && value_regno >= 0)
7138 mark_reg_unknown(env, regs, value_regno);
7140 verbose(env, "R%d invalid mem access '%s'\n", regno,
7141 reg_type_str(env, reg->type));
7145 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7146 regs[value_regno].type == SCALAR_VALUE) {
7148 /* b/h/w load zero-extends, mark upper bits as known 0 */
7149 coerce_reg_to_size(®s[value_regno], size);
7151 coerce_reg_to_size_sx(®s[value_regno], size);
7156 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7157 bool allow_trust_mismatch);
7159 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
7164 switch (insn->imm) {
7166 case BPF_ADD | BPF_FETCH:
7168 case BPF_AND | BPF_FETCH:
7170 case BPF_OR | BPF_FETCH:
7172 case BPF_XOR | BPF_FETCH:
7177 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
7181 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7182 verbose(env, "invalid atomic operand size\n");
7186 /* check src1 operand */
7187 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7191 /* check src2 operand */
7192 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7196 if (insn->imm == BPF_CMPXCHG) {
7197 /* Check comparison of R0 with memory location */
7198 const u32 aux_reg = BPF_REG_0;
7200 err = check_reg_arg(env, aux_reg, SRC_OP);
7204 if (is_pointer_value(env, aux_reg)) {
7205 verbose(env, "R%d leaks addr into mem\n", aux_reg);
7210 if (is_pointer_value(env, insn->src_reg)) {
7211 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7215 if (is_ctx_reg(env, insn->dst_reg) ||
7216 is_pkt_reg(env, insn->dst_reg) ||
7217 is_flow_key_reg(env, insn->dst_reg) ||
7218 is_sk_reg(env, insn->dst_reg) ||
7219 (is_arena_reg(env, insn->dst_reg) && !bpf_jit_supports_insn(insn, true))) {
7220 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7222 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7226 if (insn->imm & BPF_FETCH) {
7227 if (insn->imm == BPF_CMPXCHG)
7228 load_reg = BPF_REG_0;
7230 load_reg = insn->src_reg;
7232 /* check and record load of old value */
7233 err = check_reg_arg(env, load_reg, DST_OP);
7237 /* This instruction accesses a memory location but doesn't
7238 * actually load it into a register.
7243 /* Check whether we can read the memory, with second call for fetch
7244 * case to simulate the register fill.
7246 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7247 BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7248 if (!err && load_reg >= 0)
7249 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7250 BPF_SIZE(insn->code), BPF_READ, load_reg,
7255 if (is_arena_reg(env, insn->dst_reg)) {
7256 err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7260 /* Check whether we can write into the same memory. */
7261 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7262 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7268 /* When register 'regno' is used to read the stack (either directly or through
7269 * a helper function) make sure that it's within stack boundary and, depending
7270 * on the access type and privileges, that all elements of the stack are
7273 * 'off' includes 'regno->off', but not its dynamic part (if any).
7275 * All registers that have been spilled on the stack in the slots within the
7276 * read offsets are marked as read.
7278 static int check_stack_range_initialized(
7279 struct bpf_verifier_env *env, int regno, int off,
7280 int access_size, bool zero_size_allowed,
7281 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7283 struct bpf_reg_state *reg = reg_state(env, regno);
7284 struct bpf_func_state *state = func(env, reg);
7285 int err, min_off, max_off, i, j, slot, spi;
7286 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7287 enum bpf_access_type bounds_check_type;
7288 /* Some accesses can write anything into the stack, others are
7291 bool clobber = false;
7293 if (access_size == 0 && !zero_size_allowed) {
7294 verbose(env, "invalid zero-sized read\n");
7298 if (type == ACCESS_HELPER) {
7299 /* The bounds checks for writes are more permissive than for
7300 * reads. However, if raw_mode is not set, we'll do extra
7303 bounds_check_type = BPF_WRITE;
7306 bounds_check_type = BPF_READ;
7308 err = check_stack_access_within_bounds(env, regno, off, access_size,
7309 type, bounds_check_type);
7314 if (tnum_is_const(reg->var_off)) {
7315 min_off = max_off = reg->var_off.value + off;
7317 /* Variable offset is prohibited for unprivileged mode for
7318 * simplicity since it requires corresponding support in
7319 * Spectre masking for stack ALU.
7320 * See also retrieve_ptr_limit().
7322 if (!env->bypass_spec_v1) {
7325 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7326 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7327 regno, err_extra, tn_buf);
7330 /* Only initialized buffer on stack is allowed to be accessed
7331 * with variable offset. With uninitialized buffer it's hard to
7332 * guarantee that whole memory is marked as initialized on
7333 * helper return since specific bounds are unknown what may
7334 * cause uninitialized stack leaking.
7336 if (meta && meta->raw_mode)
7339 min_off = reg->smin_value + off;
7340 max_off = reg->smax_value + off;
7343 if (meta && meta->raw_mode) {
7344 /* Ensure we won't be overwriting dynptrs when simulating byte
7345 * by byte access in check_helper_call using meta.access_size.
7346 * This would be a problem if we have a helper in the future
7349 * helper(uninit_mem, len, dynptr)
7351 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7352 * may end up writing to dynptr itself when touching memory from
7353 * arg 1. This can be relaxed on a case by case basis for known
7354 * safe cases, but reject due to the possibilitiy of aliasing by
7357 for (i = min_off; i < max_off + access_size; i++) {
7358 int stack_off = -i - 1;
7361 /* raw_mode may write past allocated_stack */
7362 if (state->allocated_stack <= stack_off)
7364 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7365 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7369 meta->access_size = access_size;
7370 meta->regno = regno;
7374 for (i = min_off; i < max_off + access_size; i++) {
7378 spi = slot / BPF_REG_SIZE;
7379 if (state->allocated_stack <= slot) {
7380 verbose(env, "verifier bug: allocated_stack too small");
7384 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7385 if (*stype == STACK_MISC)
7387 if ((*stype == STACK_ZERO) ||
7388 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7390 /* helper can write anything into the stack */
7391 *stype = STACK_MISC;
7396 if (is_spilled_reg(&state->stack[spi]) &&
7397 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7398 env->allow_ptr_leaks)) {
7400 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7401 for (j = 0; j < BPF_REG_SIZE; j++)
7402 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7407 if (tnum_is_const(reg->var_off)) {
7408 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7409 err_extra, regno, min_off, i - min_off, access_size);
7413 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7414 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7415 err_extra, regno, tn_buf, i - min_off, access_size);
7419 /* reading any byte out of 8-byte 'spill_slot' will cause
7420 * the whole slot to be marked as 'read'
7422 mark_reg_read(env, &state->stack[spi].spilled_ptr,
7423 state->stack[spi].spilled_ptr.parent,
7425 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7426 * be sure that whether stack slot is written to or not. Hence,
7427 * we must still conservatively propagate reads upwards even if
7428 * helper may write to the entire memory range.
7434 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7435 int access_size, bool zero_size_allowed,
7436 struct bpf_call_arg_meta *meta)
7438 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7441 switch (base_type(reg->type)) {
7443 case PTR_TO_PACKET_META:
7444 return check_packet_access(env, regno, reg->off, access_size,
7446 case PTR_TO_MAP_KEY:
7447 if (meta && meta->raw_mode) {
7448 verbose(env, "R%d cannot write into %s\n", regno,
7449 reg_type_str(env, reg->type));
7452 return check_mem_region_access(env, regno, reg->off, access_size,
7453 reg->map_ptr->key_size, false);
7454 case PTR_TO_MAP_VALUE:
7455 if (check_map_access_type(env, regno, reg->off, access_size,
7456 meta && meta->raw_mode ? BPF_WRITE :
7459 return check_map_access(env, regno, reg->off, access_size,
7460 zero_size_allowed, ACCESS_HELPER);
7462 if (type_is_rdonly_mem(reg->type)) {
7463 if (meta && meta->raw_mode) {
7464 verbose(env, "R%d cannot write into %s\n", regno,
7465 reg_type_str(env, reg->type));
7469 return check_mem_region_access(env, regno, reg->off,
7470 access_size, reg->mem_size,
7473 if (type_is_rdonly_mem(reg->type)) {
7474 if (meta && meta->raw_mode) {
7475 verbose(env, "R%d cannot write into %s\n", regno,
7476 reg_type_str(env, reg->type));
7480 max_access = &env->prog->aux->max_rdonly_access;
7482 max_access = &env->prog->aux->max_rdwr_access;
7484 return check_buffer_access(env, reg, regno, reg->off,
7485 access_size, zero_size_allowed,
7488 return check_stack_range_initialized(
7490 regno, reg->off, access_size,
7491 zero_size_allowed, ACCESS_HELPER, meta);
7493 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7494 access_size, BPF_READ, -1);
7496 /* in case the function doesn't know how to access the context,
7497 * (because we are in a program of type SYSCALL for example), we
7498 * can not statically check its size.
7499 * Dynamically check it now.
7501 if (!env->ops->convert_ctx_access) {
7502 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7503 int offset = access_size - 1;
7505 /* Allow zero-byte read from PTR_TO_CTX */
7506 if (access_size == 0)
7507 return zero_size_allowed ? 0 : -EACCES;
7509 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7510 atype, -1, false, false);
7514 default: /* scalar_value or invalid ptr */
7515 /* Allow zero-byte read from NULL, regardless of pointer type */
7516 if (zero_size_allowed && access_size == 0 &&
7517 register_is_null(reg))
7520 verbose(env, "R%d type=%s ", regno,
7521 reg_type_str(env, reg->type));
7522 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7527 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7530 * @regno is the register containing the access size. regno-1 is the register
7531 * containing the pointer.
7533 static int check_mem_size_reg(struct bpf_verifier_env *env,
7534 struct bpf_reg_state *reg, u32 regno,
7535 bool zero_size_allowed,
7536 struct bpf_call_arg_meta *meta)
7540 /* This is used to refine r0 return value bounds for helpers
7541 * that enforce this value as an upper bound on return values.
7542 * See do_refine_retval_range() for helpers that can refine
7543 * the return value. C type of helper is u32 so we pull register
7544 * bound from umax_value however, if negative verifier errors
7545 * out. Only upper bounds can be learned because retval is an
7546 * int type and negative retvals are allowed.
7548 meta->msize_max_value = reg->umax_value;
7550 /* The register is SCALAR_VALUE; the access check
7551 * happens using its boundaries.
7553 if (!tnum_is_const(reg->var_off))
7554 /* For unprivileged variable accesses, disable raw
7555 * mode so that the program is required to
7556 * initialize all the memory that the helper could
7557 * just partially fill up.
7561 if (reg->smin_value < 0) {
7562 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7567 if (reg->umin_value == 0 && !zero_size_allowed) {
7568 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7569 regno, reg->umin_value, reg->umax_value);
7573 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7574 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7578 err = check_helper_mem_access(env, regno - 1,
7580 zero_size_allowed, meta);
7582 err = mark_chain_precision(env, regno);
7586 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7587 u32 regno, u32 mem_size)
7589 bool may_be_null = type_may_be_null(reg->type);
7590 struct bpf_reg_state saved_reg;
7591 struct bpf_call_arg_meta meta;
7594 if (register_is_null(reg))
7597 memset(&meta, 0, sizeof(meta));
7598 /* Assuming that the register contains a value check if the memory
7599 * access is safe. Temporarily save and restore the register's state as
7600 * the conversion shouldn't be visible to a caller.
7604 mark_ptr_not_null_reg(reg);
7607 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7608 /* Check access for BPF_WRITE */
7609 meta.raw_mode = true;
7610 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7618 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7621 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7622 bool may_be_null = type_may_be_null(mem_reg->type);
7623 struct bpf_reg_state saved_reg;
7624 struct bpf_call_arg_meta meta;
7627 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7629 memset(&meta, 0, sizeof(meta));
7632 saved_reg = *mem_reg;
7633 mark_ptr_not_null_reg(mem_reg);
7636 err = check_mem_size_reg(env, reg, regno, true, &meta);
7637 /* Check access for BPF_WRITE */
7638 meta.raw_mode = true;
7639 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7642 *mem_reg = saved_reg;
7646 /* Implementation details:
7647 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7648 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7649 * Two bpf_map_lookups (even with the same key) will have different reg->id.
7650 * Two separate bpf_obj_new will also have different reg->id.
7651 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7652 * clears reg->id after value_or_null->value transition, since the verifier only
7653 * cares about the range of access to valid map value pointer and doesn't care
7654 * about actual address of the map element.
7655 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7656 * reg->id > 0 after value_or_null->value transition. By doing so
7657 * two bpf_map_lookups will be considered two different pointers that
7658 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7659 * returned from bpf_obj_new.
7660 * The verifier allows taking only one bpf_spin_lock at a time to avoid
7662 * Since only one bpf_spin_lock is allowed the checks are simpler than
7663 * reg_is_refcounted() logic. The verifier needs to remember only
7664 * one spin_lock instead of array of acquired_refs.
7665 * cur_state->active_lock remembers which map value element or allocated
7666 * object got locked and clears it after bpf_spin_unlock.
7668 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7671 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7672 struct bpf_verifier_state *cur = env->cur_state;
7673 bool is_const = tnum_is_const(reg->var_off);
7674 u64 val = reg->var_off.value;
7675 struct bpf_map *map = NULL;
7676 struct btf *btf = NULL;
7677 struct btf_record *rec;
7681 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7685 if (reg->type == PTR_TO_MAP_VALUE) {
7689 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7697 rec = reg_btf_record(reg);
7698 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7699 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7700 map ? map->name : "kptr");
7703 if (rec->spin_lock_off != val + reg->off) {
7704 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7705 val + reg->off, rec->spin_lock_off);
7709 if (cur->active_lock.ptr) {
7711 "Locking two bpf_spin_locks are not allowed\n");
7715 cur->active_lock.ptr = map;
7717 cur->active_lock.ptr = btf;
7718 cur->active_lock.id = reg->id;
7727 if (!cur->active_lock.ptr) {
7728 verbose(env, "bpf_spin_unlock without taking a lock\n");
7731 if (cur->active_lock.ptr != ptr ||
7732 cur->active_lock.id != reg->id) {
7733 verbose(env, "bpf_spin_unlock of different lock\n");
7737 invalidate_non_owning_refs(env);
7739 cur->active_lock.ptr = NULL;
7740 cur->active_lock.id = 0;
7745 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7746 struct bpf_call_arg_meta *meta)
7748 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7749 bool is_const = tnum_is_const(reg->var_off);
7750 struct bpf_map *map = reg->map_ptr;
7751 u64 val = reg->var_off.value;
7755 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7760 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7764 if (!btf_record_has_field(map->record, BPF_TIMER)) {
7765 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7768 if (map->record->timer_off != val + reg->off) {
7769 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7770 val + reg->off, map->record->timer_off);
7773 if (meta->map_ptr) {
7774 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7777 meta->map_uid = reg->map_uid;
7778 meta->map_ptr = map;
7782 static int process_wq_func(struct bpf_verifier_env *env, int regno,
7783 struct bpf_kfunc_call_arg_meta *meta)
7785 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7786 struct bpf_map *map = reg->map_ptr;
7787 u64 val = reg->var_off.value;
7789 if (map->record->wq_off != val + reg->off) {
7790 verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n",
7791 val + reg->off, map->record->wq_off);
7794 meta->map.uid = reg->map_uid;
7795 meta->map.ptr = map;
7799 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7800 struct bpf_call_arg_meta *meta)
7802 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7803 struct btf_field *kptr_field;
7804 struct bpf_map *map_ptr;
7805 struct btf_record *rec;
7808 if (type_is_ptr_alloc_obj(reg->type)) {
7809 rec = reg_btf_record(reg);
7810 } else { /* PTR_TO_MAP_VALUE */
7811 map_ptr = reg->map_ptr;
7812 if (!map_ptr->btf) {
7813 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7817 rec = map_ptr->record;
7818 meta->map_ptr = map_ptr;
7821 if (!tnum_is_const(reg->var_off)) {
7823 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7828 if (!btf_record_has_field(rec, BPF_KPTR)) {
7829 verbose(env, "R%d has no valid kptr\n", regno);
7833 kptr_off = reg->off + reg->var_off.value;
7834 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
7836 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7839 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7840 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7843 meta->kptr_field = kptr_field;
7847 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7848 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7850 * In both cases we deal with the first 8 bytes, but need to mark the next 8
7851 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7852 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7854 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7855 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7856 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7857 * mutate the view of the dynptr and also possibly destroy it. In the latter
7858 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7859 * memory that dynptr points to.
7861 * The verifier will keep track both levels of mutation (bpf_dynptr's in
7862 * reg->type and the memory's in reg->dynptr.type), but there is no support for
7863 * readonly dynptr view yet, hence only the first case is tracked and checked.
7865 * This is consistent with how C applies the const modifier to a struct object,
7866 * where the pointer itself inside bpf_dynptr becomes const but not what it
7869 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7870 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7872 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7873 enum bpf_arg_type arg_type, int clone_ref_obj_id)
7875 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7878 if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
7880 "arg#%d expected pointer to stack or const struct bpf_dynptr\n",
7885 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7886 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7888 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7889 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7893 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
7894 * constructing a mutable bpf_dynptr object.
7896 * Currently, this is only possible with PTR_TO_STACK
7897 * pointing to a region of at least 16 bytes which doesn't
7898 * contain an existing bpf_dynptr.
7900 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7901 * mutated or destroyed. However, the memory it points to
7904 * None - Points to a initialized dynptr that can be mutated and
7905 * destroyed, including mutation of the memory it points
7908 if (arg_type & MEM_UNINIT) {
7911 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7912 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7916 /* we write BPF_DW bits (8 bytes) at a time */
7917 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7918 err = check_mem_access(env, insn_idx, regno,
7919 i, BPF_DW, BPF_WRITE, -1, false, false);
7924 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7925 } else /* MEM_RDONLY and None case from above */ {
7926 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7927 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7928 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7932 if (!is_dynptr_reg_valid_init(env, reg)) {
7934 "Expected an initialized dynptr as arg #%d\n",
7939 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7940 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7942 "Expected a dynptr of type %s as arg #%d\n",
7943 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7947 err = mark_dynptr_read(env, reg);
7952 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7954 struct bpf_func_state *state = func(env, reg);
7956 return state->stack[spi].spilled_ptr.ref_obj_id;
7959 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7961 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7964 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7966 return meta->kfunc_flags & KF_ITER_NEW;
7969 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7971 return meta->kfunc_flags & KF_ITER_NEXT;
7974 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7976 return meta->kfunc_flags & KF_ITER_DESTROY;
7979 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
7980 const struct btf_param *arg)
7982 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7983 * kfunc is iter state pointer
7985 if (is_iter_kfunc(meta))
7986 return arg_idx == 0;
7988 /* iter passed as an argument to a generic kfunc */
7989 return btf_param_match_suffix(meta->btf, arg, "__iter");
7992 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7993 struct bpf_kfunc_call_arg_meta *meta)
7995 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7996 const struct btf_type *t;
7997 int spi, err, i, nr_slots, btf_id;
7999 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8000 * ensures struct convention, so we wouldn't need to do any BTF
8001 * validation here. But given iter state can be passed as a parameter
8002 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8003 * conservative here.
8005 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
8007 verbose(env, "expected valid iter pointer as arg #%d\n", regno);
8010 t = btf_type_by_id(meta->btf, btf_id);
8011 nr_slots = t->size / BPF_REG_SIZE;
8013 if (is_iter_new_kfunc(meta)) {
8014 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
8015 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8016 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
8017 iter_type_str(meta->btf, btf_id), regno);
8021 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8022 err = check_mem_access(env, insn_idx, regno,
8023 i, BPF_DW, BPF_WRITE, -1, false, false);
8028 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8032 /* iter_next() or iter_destroy(), as well as any kfunc
8033 * accepting iter argument, expect initialized iter state
8035 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8040 verbose(env, "expected an initialized iter_%s as arg #%d\n",
8041 iter_type_str(meta->btf, btf_id), regno);
8044 verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8050 spi = iter_get_spi(env, reg, nr_slots);
8054 err = mark_iter_read(env, reg, spi, nr_slots);
8058 /* remember meta->iter info for process_iter_next_call() */
8059 meta->iter.spi = spi;
8060 meta->iter.frameno = reg->frameno;
8061 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
8063 if (is_iter_destroy_kfunc(meta)) {
8064 err = unmark_stack_slots_iter(env, reg, nr_slots);
8073 /* Look for a previous loop entry at insn_idx: nearest parent state
8074 * stopped at insn_idx with callsites matching those in cur->frame.
8076 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8077 struct bpf_verifier_state *cur,
8080 struct bpf_verifier_state_list *sl;
8081 struct bpf_verifier_state *st;
8083 /* Explored states are pushed in stack order, most recent states come first */
8084 sl = *explored_state(env, insn_idx);
8085 for (; sl; sl = sl->next) {
8086 /* If st->branches != 0 state is a part of current DFS verification path,
8087 * hence cur & st for a loop.
8090 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8091 st->dfs_depth < cur->dfs_depth)
8098 static void reset_idmap_scratch(struct bpf_verifier_env *env);
8099 static bool regs_exact(const struct bpf_reg_state *rold,
8100 const struct bpf_reg_state *rcur,
8101 struct bpf_idmap *idmap);
8103 static void maybe_widen_reg(struct bpf_verifier_env *env,
8104 struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8105 struct bpf_idmap *idmap)
8107 if (rold->type != SCALAR_VALUE)
8109 if (rold->type != rcur->type)
8111 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
8113 __mark_reg_unknown(env, rcur);
8116 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8117 struct bpf_verifier_state *old,
8118 struct bpf_verifier_state *cur)
8120 struct bpf_func_state *fold, *fcur;
8123 reset_idmap_scratch(env);
8124 for (fr = old->curframe; fr >= 0; fr--) {
8125 fold = old->frame[fr];
8126 fcur = cur->frame[fr];
8128 for (i = 0; i < MAX_BPF_REG; i++)
8129 maybe_widen_reg(env,
8132 &env->idmap_scratch);
8134 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
8135 if (!is_spilled_reg(&fold->stack[i]) ||
8136 !is_spilled_reg(&fcur->stack[i]))
8139 maybe_widen_reg(env,
8140 &fold->stack[i].spilled_ptr,
8141 &fcur->stack[i].spilled_ptr,
8142 &env->idmap_scratch);
8148 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8149 struct bpf_kfunc_call_arg_meta *meta)
8151 int iter_frameno = meta->iter.frameno;
8152 int iter_spi = meta->iter.spi;
8154 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8157 /* process_iter_next_call() is called when verifier gets to iterator's next
8158 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
8159 * to it as just "iter_next()" in comments below.
8161 * BPF verifier relies on a crucial contract for any iter_next()
8162 * implementation: it should *eventually* return NULL, and once that happens
8163 * it should keep returning NULL. That is, once iterator exhausts elements to
8164 * iterate, it should never reset or spuriously return new elements.
8166 * With the assumption of such contract, process_iter_next_call() simulates
8167 * a fork in the verifier state to validate loop logic correctness and safety
8168 * without having to simulate infinite amount of iterations.
8170 * In current state, we first assume that iter_next() returned NULL and
8171 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
8172 * conditions we should not form an infinite loop and should eventually reach
8175 * Besides that, we also fork current state and enqueue it for later
8176 * verification. In a forked state we keep iterator state as ACTIVE
8177 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
8178 * also bump iteration depth to prevent erroneous infinite loop detection
8179 * later on (see iter_active_depths_differ() comment for details). In this
8180 * state we assume that we'll eventually loop back to another iter_next()
8181 * calls (it could be in exactly same location or in some other instruction,
8182 * it doesn't matter, we don't make any unnecessary assumptions about this,
8183 * everything revolves around iterator state in a stack slot, not which
8184 * instruction is calling iter_next()). When that happens, we either will come
8185 * to iter_next() with equivalent state and can conclude that next iteration
8186 * will proceed in exactly the same way as we just verified, so it's safe to
8187 * assume that loop converges. If not, we'll go on another iteration
8188 * simulation with a different input state, until all possible starting states
8189 * are validated or we reach maximum number of instructions limit.
8191 * This way, we will either exhaustively discover all possible input states
8192 * that iterator loop can start with and eventually will converge, or we'll
8193 * effectively regress into bounded loop simulation logic and either reach
8194 * maximum number of instructions if loop is not provably convergent, or there
8195 * is some statically known limit on number of iterations (e.g., if there is
8196 * an explicit `if n > 100 then break;` statement somewhere in the loop).
8198 * Iteration convergence logic in is_state_visited() relies on exact
8199 * states comparison, which ignores read and precision marks.
8200 * This is necessary because read and precision marks are not finalized
8201 * while in the loop. Exact comparison might preclude convergence for
8202 * simple programs like below:
8205 * while(iter_next(&it))
8208 * At each iteration step i++ would produce a new distinct state and
8209 * eventually instruction processing limit would be reached.
8211 * To avoid such behavior speculatively forget (widen) range for
8212 * imprecise scalar registers, if those registers were not precise at the
8213 * end of the previous iteration and do not match exactly.
8215 * This is a conservative heuristic that allows to verify wide range of programs,
8216 * however it precludes verification of programs that conjure an
8217 * imprecise value on the first loop iteration and use it as precise on a second.
8218 * For example, the following safe program would fail to verify:
8220 * struct bpf_num_iter it;
8223 * bpf_iter_num_new(&it, 0, 10);
8224 * while (bpf_iter_num_next(&it)) {
8227 * i = 7; // Because i changed verifier would forget
8228 * // it's range on second loop entry.
8230 * arr[i] = 42; // This would fail to verify.
8233 * bpf_iter_num_destroy(&it);
8235 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8236 struct bpf_kfunc_call_arg_meta *meta)
8238 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8239 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8240 struct bpf_reg_state *cur_iter, *queued_iter;
8242 BTF_TYPE_EMIT(struct bpf_iter);
8244 cur_iter = get_iter_from_state(cur_st, meta);
8246 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8247 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8248 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
8249 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8253 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
8254 /* Because iter_next() call is a checkpoint is_state_visitied()
8255 * should guarantee parent state with same call sites and insn_idx.
8257 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8258 !same_callsites(cur_st->parent, cur_st)) {
8259 verbose(env, "bug: bad parent state for iter next call");
8262 /* Note cur_st->parent in the call below, it is necessary to skip
8263 * checkpoint created for cur_st by is_state_visited()
8264 * right at this instruction.
8266 prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8267 /* branch out active iter state */
8268 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8272 queued_iter = get_iter_from_state(queued_st, meta);
8273 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8274 queued_iter->iter.depth++;
8276 widen_imprecise_scalars(env, prev_st, queued_st);
8278 queued_fr = queued_st->frame[queued_st->curframe];
8279 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8282 /* switch to DRAINED state, but keep the depth unchanged */
8283 /* mark current iter state as drained and assume returned NULL */
8284 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8285 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8290 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8292 return type == ARG_CONST_SIZE ||
8293 type == ARG_CONST_SIZE_OR_ZERO;
8296 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
8298 return base_type(type) == ARG_PTR_TO_MEM &&
8302 static bool arg_type_is_release(enum bpf_arg_type type)
8304 return type & OBJ_RELEASE;
8307 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8309 return base_type(type) == ARG_PTR_TO_DYNPTR;
8312 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8313 const struct bpf_call_arg_meta *meta,
8314 enum bpf_arg_type *arg_type)
8316 if (!meta->map_ptr) {
8317 /* kernel subsystem misconfigured verifier */
8318 verbose(env, "invalid map_ptr to access map->type\n");
8322 switch (meta->map_ptr->map_type) {
8323 case BPF_MAP_TYPE_SOCKMAP:
8324 case BPF_MAP_TYPE_SOCKHASH:
8325 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8326 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8328 verbose(env, "invalid arg_type for sockmap/sockhash\n");
8332 case BPF_MAP_TYPE_BLOOM_FILTER:
8333 if (meta->func_id == BPF_FUNC_map_peek_elem)
8334 *arg_type = ARG_PTR_TO_MAP_VALUE;
8342 struct bpf_reg_types {
8343 const enum bpf_reg_type types[10];
8347 static const struct bpf_reg_types sock_types = {
8357 static const struct bpf_reg_types btf_id_sock_common_types = {
8364 PTR_TO_BTF_ID | PTR_TRUSTED,
8366 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8370 static const struct bpf_reg_types mem_types = {
8378 PTR_TO_MEM | MEM_RINGBUF,
8380 PTR_TO_BTF_ID | PTR_TRUSTED,
8384 static const struct bpf_reg_types spin_lock_types = {
8387 PTR_TO_BTF_ID | MEM_ALLOC,
8391 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8392 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8393 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8394 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8395 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8396 static const struct bpf_reg_types btf_ptr_types = {
8399 PTR_TO_BTF_ID | PTR_TRUSTED,
8400 PTR_TO_BTF_ID | MEM_RCU,
8403 static const struct bpf_reg_types percpu_btf_ptr_types = {
8405 PTR_TO_BTF_ID | MEM_PERCPU,
8406 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8407 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8410 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8411 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8412 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8413 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8414 static const struct bpf_reg_types kptr_xchg_dest_types = {
8417 PTR_TO_BTF_ID | MEM_ALLOC
8420 static const struct bpf_reg_types dynptr_types = {
8423 CONST_PTR_TO_DYNPTR,
8427 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8428 [ARG_PTR_TO_MAP_KEY] = &mem_types,
8429 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
8430 [ARG_CONST_SIZE] = &scalar_types,
8431 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
8432 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
8433 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
8434 [ARG_PTR_TO_CTX] = &context_types,
8435 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
8437 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
8439 [ARG_PTR_TO_SOCKET] = &fullsock_types,
8440 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
8441 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
8442 [ARG_PTR_TO_MEM] = &mem_types,
8443 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
8444 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
8445 [ARG_PTR_TO_FUNC] = &func_ptr_types,
8446 [ARG_PTR_TO_STACK] = &stack_ptr_types,
8447 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
8448 [ARG_PTR_TO_TIMER] = &timer_types,
8449 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types,
8450 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
8453 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8454 enum bpf_arg_type arg_type,
8455 const u32 *arg_btf_id,
8456 struct bpf_call_arg_meta *meta)
8458 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8459 enum bpf_reg_type expected, type = reg->type;
8460 const struct bpf_reg_types *compatible;
8463 compatible = compatible_reg_types[base_type(arg_type)];
8465 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8469 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8470 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8472 * Same for MAYBE_NULL:
8474 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8475 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8477 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8479 * Therefore we fold these flags depending on the arg_type before comparison.
8481 if (arg_type & MEM_RDONLY)
8482 type &= ~MEM_RDONLY;
8483 if (arg_type & PTR_MAYBE_NULL)
8484 type &= ~PTR_MAYBE_NULL;
8485 if (base_type(arg_type) == ARG_PTR_TO_MEM)
8486 type &= ~DYNPTR_TYPE_FLAG_MASK;
8488 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
8489 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
8491 type &= ~MEM_PERCPU;
8494 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8495 expected = compatible->types[i];
8496 if (expected == NOT_INIT)
8499 if (type == expected)
8503 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8504 for (j = 0; j + 1 < i; j++)
8505 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8506 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8510 if (base_type(reg->type) != PTR_TO_BTF_ID)
8513 if (compatible == &mem_types) {
8514 if (!(arg_type & MEM_RDONLY)) {
8516 "%s() may write into memory pointed by R%d type=%s\n",
8517 func_id_name(meta->func_id),
8518 regno, reg_type_str(env, reg->type));
8524 switch ((int)reg->type) {
8526 case PTR_TO_BTF_ID | PTR_TRUSTED:
8527 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
8528 case PTR_TO_BTF_ID | MEM_RCU:
8529 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8530 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8532 /* For bpf_sk_release, it needs to match against first member
8533 * 'struct sock_common', hence make an exception for it. This
8534 * allows bpf_sk_release to work for multiple socket types.
8536 bool strict_type_match = arg_type_is_release(arg_type) &&
8537 meta->func_id != BPF_FUNC_sk_release;
8539 if (type_may_be_null(reg->type) &&
8540 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8541 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8546 if (!compatible->btf_id) {
8547 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8550 arg_btf_id = compatible->btf_id;
8553 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8554 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8557 if (arg_btf_id == BPF_PTR_POISON) {
8558 verbose(env, "verifier internal error:");
8559 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8564 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8565 btf_vmlinux, *arg_btf_id,
8566 strict_type_match)) {
8567 verbose(env, "R%d is of type %s but %s is expected\n",
8568 regno, btf_type_name(reg->btf, reg->btf_id),
8569 btf_type_name(btf_vmlinux, *arg_btf_id));
8575 case PTR_TO_BTF_ID | MEM_ALLOC:
8576 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8577 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8578 meta->func_id != BPF_FUNC_kptr_xchg) {
8579 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8582 /* Check if local kptr in src arg matches kptr in dst arg */
8583 if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
8584 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8588 case PTR_TO_BTF_ID | MEM_PERCPU:
8589 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8590 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8591 /* Handled by helper specific checks */
8594 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8600 static struct btf_field *
8601 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8603 struct btf_field *field;
8604 struct btf_record *rec;
8606 rec = reg_btf_record(reg);
8610 field = btf_record_find(rec, off, fields);
8617 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8618 const struct bpf_reg_state *reg, int regno,
8619 enum bpf_arg_type arg_type)
8621 u32 type = reg->type;
8623 /* When referenced register is passed to release function, its fixed
8626 * We will check arg_type_is_release reg has ref_obj_id when storing
8627 * meta->release_regno.
8629 if (arg_type_is_release(arg_type)) {
8630 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8631 * may not directly point to the object being released, but to
8632 * dynptr pointing to such object, which might be at some offset
8633 * on the stack. In that case, we simply to fallback to the
8636 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8639 /* Doing check_ptr_off_reg check for the offset will catch this
8640 * because fixed_off_ok is false, but checking here allows us
8641 * to give the user a better error message.
8644 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8648 return __check_ptr_off_reg(env, reg, regno, false);
8652 /* Pointer types where both fixed and variable offset is explicitly allowed: */
8655 case PTR_TO_PACKET_META:
8656 case PTR_TO_MAP_KEY:
8657 case PTR_TO_MAP_VALUE:
8659 case PTR_TO_MEM | MEM_RDONLY:
8660 case PTR_TO_MEM | MEM_RINGBUF:
8662 case PTR_TO_BUF | MEM_RDONLY:
8666 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8670 case PTR_TO_BTF_ID | MEM_ALLOC:
8671 case PTR_TO_BTF_ID | PTR_TRUSTED:
8672 case PTR_TO_BTF_ID | MEM_RCU:
8673 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8674 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8675 /* When referenced PTR_TO_BTF_ID is passed to release function,
8676 * its fixed offset must be 0. In the other cases, fixed offset
8677 * can be non-zero. This was already checked above. So pass
8678 * fixed_off_ok as true to allow fixed offset for all other
8679 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8680 * still need to do checks instead of returning.
8682 return __check_ptr_off_reg(env, reg, regno, true);
8684 return __check_ptr_off_reg(env, reg, regno, false);
8688 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8689 const struct bpf_func_proto *fn,
8690 struct bpf_reg_state *regs)
8692 struct bpf_reg_state *state = NULL;
8695 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8696 if (arg_type_is_dynptr(fn->arg_type[i])) {
8698 verbose(env, "verifier internal error: multiple dynptr args\n");
8701 state = ®s[BPF_REG_1 + i];
8705 verbose(env, "verifier internal error: no dynptr arg found\n");
8710 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8712 struct bpf_func_state *state = func(env, reg);
8715 if (reg->type == CONST_PTR_TO_DYNPTR)
8717 spi = dynptr_get_spi(env, reg);
8720 return state->stack[spi].spilled_ptr.id;
8723 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8725 struct bpf_func_state *state = func(env, reg);
8728 if (reg->type == CONST_PTR_TO_DYNPTR)
8729 return reg->ref_obj_id;
8730 spi = dynptr_get_spi(env, reg);
8733 return state->stack[spi].spilled_ptr.ref_obj_id;
8736 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8737 struct bpf_reg_state *reg)
8739 struct bpf_func_state *state = func(env, reg);
8742 if (reg->type == CONST_PTR_TO_DYNPTR)
8743 return reg->dynptr.type;
8745 spi = __get_spi(reg->off);
8747 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8748 return BPF_DYNPTR_TYPE_INVALID;
8751 return state->stack[spi].spilled_ptr.dynptr.type;
8754 static int check_reg_const_str(struct bpf_verifier_env *env,
8755 struct bpf_reg_state *reg, u32 regno)
8757 struct bpf_map *map = reg->map_ptr;
8763 if (reg->type != PTR_TO_MAP_VALUE)
8766 if (!bpf_map_is_rdonly(map)) {
8767 verbose(env, "R%d does not point to a readonly map'\n", regno);
8771 if (!tnum_is_const(reg->var_off)) {
8772 verbose(env, "R%d is not a constant address'\n", regno);
8776 if (!map->ops->map_direct_value_addr) {
8777 verbose(env, "no direct value access support for this map type\n");
8781 err = check_map_access(env, regno, reg->off,
8782 map->value_size - reg->off, false,
8787 map_off = reg->off + reg->var_off.value;
8788 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8790 verbose(env, "direct value access on string failed\n");
8794 str_ptr = (char *)(long)(map_addr);
8795 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8796 verbose(env, "string is not zero-terminated\n");
8802 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8803 struct bpf_call_arg_meta *meta,
8804 const struct bpf_func_proto *fn,
8807 u32 regno = BPF_REG_1 + arg;
8808 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8809 enum bpf_arg_type arg_type = fn->arg_type[arg];
8810 enum bpf_reg_type type = reg->type;
8811 u32 *arg_btf_id = NULL;
8814 if (arg_type == ARG_DONTCARE)
8817 err = check_reg_arg(env, regno, SRC_OP);
8821 if (arg_type == ARG_ANYTHING) {
8822 if (is_pointer_value(env, regno)) {
8823 verbose(env, "R%d leaks addr into helper function\n",
8830 if (type_is_pkt_pointer(type) &&
8831 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8832 verbose(env, "helper access to the packet is not allowed\n");
8836 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8837 err = resolve_map_arg_type(env, meta, &arg_type);
8842 if (register_is_null(reg) && type_may_be_null(arg_type))
8843 /* A NULL register has a SCALAR_VALUE type, so skip
8846 goto skip_type_check;
8848 /* arg_btf_id and arg_size are in a union. */
8849 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8850 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8851 arg_btf_id = fn->arg_btf_id[arg];
8853 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8857 err = check_func_arg_reg_off(env, reg, regno, arg_type);
8862 if (arg_type_is_release(arg_type)) {
8863 if (arg_type_is_dynptr(arg_type)) {
8864 struct bpf_func_state *state = func(env, reg);
8867 /* Only dynptr created on stack can be released, thus
8868 * the get_spi and stack state checks for spilled_ptr
8869 * should only be done before process_dynptr_func for
8872 if (reg->type == PTR_TO_STACK) {
8873 spi = dynptr_get_spi(env, reg);
8874 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8875 verbose(env, "arg %d is an unacquired reference\n", regno);
8879 verbose(env, "cannot release unowned const bpf_dynptr\n");
8882 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8883 verbose(env, "R%d must be referenced when passed to release function\n",
8887 if (meta->release_regno) {
8888 verbose(env, "verifier internal error: more than one release argument\n");
8891 meta->release_regno = regno;
8894 if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
8895 if (meta->ref_obj_id) {
8896 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8897 regno, reg->ref_obj_id,
8901 meta->ref_obj_id = reg->ref_obj_id;
8904 switch (base_type(arg_type)) {
8905 case ARG_CONST_MAP_PTR:
8906 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8907 if (meta->map_ptr) {
8908 /* Use map_uid (which is unique id of inner map) to reject:
8909 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8910 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8911 * if (inner_map1 && inner_map2) {
8912 * timer = bpf_map_lookup_elem(inner_map1);
8914 * // mismatch would have been allowed
8915 * bpf_timer_init(timer, inner_map2);
8918 * Comparing map_ptr is enough to distinguish normal and outer maps.
8920 if (meta->map_ptr != reg->map_ptr ||
8921 meta->map_uid != reg->map_uid) {
8923 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8924 meta->map_uid, reg->map_uid);
8928 meta->map_ptr = reg->map_ptr;
8929 meta->map_uid = reg->map_uid;
8931 case ARG_PTR_TO_MAP_KEY:
8932 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8933 * check that [key, key + map->key_size) are within
8934 * stack limits and initialized
8936 if (!meta->map_ptr) {
8937 /* in function declaration map_ptr must come before
8938 * map_key, so that it's verified and known before
8939 * we have to check map_key here. Otherwise it means
8940 * that kernel subsystem misconfigured verifier
8942 verbose(env, "invalid map_ptr to access map->key\n");
8945 err = check_helper_mem_access(env, regno,
8946 meta->map_ptr->key_size, false,
8949 case ARG_PTR_TO_MAP_VALUE:
8950 if (type_may_be_null(arg_type) && register_is_null(reg))
8953 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8954 * check [value, value + map->value_size) validity
8956 if (!meta->map_ptr) {
8957 /* kernel subsystem misconfigured verifier */
8958 verbose(env, "invalid map_ptr to access map->value\n");
8961 meta->raw_mode = arg_type & MEM_UNINIT;
8962 err = check_helper_mem_access(env, regno,
8963 meta->map_ptr->value_size, false,
8966 case ARG_PTR_TO_PERCPU_BTF_ID:
8968 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8971 meta->ret_btf = reg->btf;
8972 meta->ret_btf_id = reg->btf_id;
8974 case ARG_PTR_TO_SPIN_LOCK:
8975 if (in_rbtree_lock_required_cb(env)) {
8976 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8979 if (meta->func_id == BPF_FUNC_spin_lock) {
8980 err = process_spin_lock(env, regno, true);
8983 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8984 err = process_spin_lock(env, regno, false);
8988 verbose(env, "verifier internal error\n");
8992 case ARG_PTR_TO_TIMER:
8993 err = process_timer_func(env, regno, meta);
8997 case ARG_PTR_TO_FUNC:
8998 meta->subprogno = reg->subprogno;
9000 case ARG_PTR_TO_MEM:
9001 /* The access to this pointer is only checked when we hit the
9002 * next is_mem_size argument below.
9004 meta->raw_mode = arg_type & MEM_UNINIT;
9005 if (arg_type & MEM_FIXED_SIZE) {
9006 err = check_helper_mem_access(env, regno, fn->arg_size[arg], false, meta);
9009 if (arg_type & MEM_ALIGNED)
9010 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
9013 case ARG_CONST_SIZE:
9014 err = check_mem_size_reg(env, reg, regno, false, meta);
9016 case ARG_CONST_SIZE_OR_ZERO:
9017 err = check_mem_size_reg(env, reg, regno, true, meta);
9019 case ARG_PTR_TO_DYNPTR:
9020 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
9024 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9025 if (!tnum_is_const(reg->var_off)) {
9026 verbose(env, "R%d is not a known constant'\n",
9030 meta->mem_size = reg->var_off.value;
9031 err = mark_chain_precision(env, regno);
9035 case ARG_PTR_TO_CONST_STR:
9037 err = check_reg_const_str(env, reg, regno);
9042 case ARG_KPTR_XCHG_DEST:
9043 err = process_kptr_func(env, regno, meta);
9052 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
9054 enum bpf_attach_type eatype = env->prog->expected_attach_type;
9055 enum bpf_prog_type type = resolve_prog_type(env->prog);
9057 if (func_id != BPF_FUNC_map_update_elem &&
9058 func_id != BPF_FUNC_map_delete_elem)
9061 /* It's not possible to get access to a locked struct sock in these
9062 * contexts, so updating is safe.
9065 case BPF_PROG_TYPE_TRACING:
9066 if (eatype == BPF_TRACE_ITER)
9069 case BPF_PROG_TYPE_SOCK_OPS:
9070 /* map_update allowed only via dedicated helpers with event type checks */
9071 if (func_id == BPF_FUNC_map_delete_elem)
9074 case BPF_PROG_TYPE_SOCKET_FILTER:
9075 case BPF_PROG_TYPE_SCHED_CLS:
9076 case BPF_PROG_TYPE_SCHED_ACT:
9077 case BPF_PROG_TYPE_XDP:
9078 case BPF_PROG_TYPE_SK_REUSEPORT:
9079 case BPF_PROG_TYPE_FLOW_DISSECTOR:
9080 case BPF_PROG_TYPE_SK_LOOKUP:
9086 verbose(env, "cannot update sockmap in this context\n");
9090 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
9092 return env->prog->jit_requested &&
9093 bpf_jit_supports_subprog_tailcalls();
9096 static int check_map_func_compatibility(struct bpf_verifier_env *env,
9097 struct bpf_map *map, int func_id)
9102 /* We need a two way check, first is from map perspective ... */
9103 switch (map->map_type) {
9104 case BPF_MAP_TYPE_PROG_ARRAY:
9105 if (func_id != BPF_FUNC_tail_call)
9108 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
9109 if (func_id != BPF_FUNC_perf_event_read &&
9110 func_id != BPF_FUNC_perf_event_output &&
9111 func_id != BPF_FUNC_skb_output &&
9112 func_id != BPF_FUNC_perf_event_read_value &&
9113 func_id != BPF_FUNC_xdp_output)
9116 case BPF_MAP_TYPE_RINGBUF:
9117 if (func_id != BPF_FUNC_ringbuf_output &&
9118 func_id != BPF_FUNC_ringbuf_reserve &&
9119 func_id != BPF_FUNC_ringbuf_query &&
9120 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
9121 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
9122 func_id != BPF_FUNC_ringbuf_discard_dynptr)
9125 case BPF_MAP_TYPE_USER_RINGBUF:
9126 if (func_id != BPF_FUNC_user_ringbuf_drain)
9129 case BPF_MAP_TYPE_STACK_TRACE:
9130 if (func_id != BPF_FUNC_get_stackid)
9133 case BPF_MAP_TYPE_CGROUP_ARRAY:
9134 if (func_id != BPF_FUNC_skb_under_cgroup &&
9135 func_id != BPF_FUNC_current_task_under_cgroup)
9138 case BPF_MAP_TYPE_CGROUP_STORAGE:
9139 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
9140 if (func_id != BPF_FUNC_get_local_storage)
9143 case BPF_MAP_TYPE_DEVMAP:
9144 case BPF_MAP_TYPE_DEVMAP_HASH:
9145 if (func_id != BPF_FUNC_redirect_map &&
9146 func_id != BPF_FUNC_map_lookup_elem)
9149 /* Restrict bpf side of cpumap and xskmap, open when use-cases
9152 case BPF_MAP_TYPE_CPUMAP:
9153 if (func_id != BPF_FUNC_redirect_map)
9156 case BPF_MAP_TYPE_XSKMAP:
9157 if (func_id != BPF_FUNC_redirect_map &&
9158 func_id != BPF_FUNC_map_lookup_elem)
9161 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
9162 case BPF_MAP_TYPE_HASH_OF_MAPS:
9163 if (func_id != BPF_FUNC_map_lookup_elem)
9166 case BPF_MAP_TYPE_SOCKMAP:
9167 if (func_id != BPF_FUNC_sk_redirect_map &&
9168 func_id != BPF_FUNC_sock_map_update &&
9169 func_id != BPF_FUNC_msg_redirect_map &&
9170 func_id != BPF_FUNC_sk_select_reuseport &&
9171 func_id != BPF_FUNC_map_lookup_elem &&
9172 !may_update_sockmap(env, func_id))
9175 case BPF_MAP_TYPE_SOCKHASH:
9176 if (func_id != BPF_FUNC_sk_redirect_hash &&
9177 func_id != BPF_FUNC_sock_hash_update &&
9178 func_id != BPF_FUNC_msg_redirect_hash &&
9179 func_id != BPF_FUNC_sk_select_reuseport &&
9180 func_id != BPF_FUNC_map_lookup_elem &&
9181 !may_update_sockmap(env, func_id))
9184 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
9185 if (func_id != BPF_FUNC_sk_select_reuseport)
9188 case BPF_MAP_TYPE_QUEUE:
9189 case BPF_MAP_TYPE_STACK:
9190 if (func_id != BPF_FUNC_map_peek_elem &&
9191 func_id != BPF_FUNC_map_pop_elem &&
9192 func_id != BPF_FUNC_map_push_elem)
9195 case BPF_MAP_TYPE_SK_STORAGE:
9196 if (func_id != BPF_FUNC_sk_storage_get &&
9197 func_id != BPF_FUNC_sk_storage_delete &&
9198 func_id != BPF_FUNC_kptr_xchg)
9201 case BPF_MAP_TYPE_INODE_STORAGE:
9202 if (func_id != BPF_FUNC_inode_storage_get &&
9203 func_id != BPF_FUNC_inode_storage_delete &&
9204 func_id != BPF_FUNC_kptr_xchg)
9207 case BPF_MAP_TYPE_TASK_STORAGE:
9208 if (func_id != BPF_FUNC_task_storage_get &&
9209 func_id != BPF_FUNC_task_storage_delete &&
9210 func_id != BPF_FUNC_kptr_xchg)
9213 case BPF_MAP_TYPE_CGRP_STORAGE:
9214 if (func_id != BPF_FUNC_cgrp_storage_get &&
9215 func_id != BPF_FUNC_cgrp_storage_delete &&
9216 func_id != BPF_FUNC_kptr_xchg)
9219 case BPF_MAP_TYPE_BLOOM_FILTER:
9220 if (func_id != BPF_FUNC_map_peek_elem &&
9221 func_id != BPF_FUNC_map_push_elem)
9228 /* ... and second from the function itself. */
9230 case BPF_FUNC_tail_call:
9231 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
9233 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
9234 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
9238 case BPF_FUNC_perf_event_read:
9239 case BPF_FUNC_perf_event_output:
9240 case BPF_FUNC_perf_event_read_value:
9241 case BPF_FUNC_skb_output:
9242 case BPF_FUNC_xdp_output:
9243 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
9246 case BPF_FUNC_ringbuf_output:
9247 case BPF_FUNC_ringbuf_reserve:
9248 case BPF_FUNC_ringbuf_query:
9249 case BPF_FUNC_ringbuf_reserve_dynptr:
9250 case BPF_FUNC_ringbuf_submit_dynptr:
9251 case BPF_FUNC_ringbuf_discard_dynptr:
9252 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
9255 case BPF_FUNC_user_ringbuf_drain:
9256 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
9259 case BPF_FUNC_get_stackid:
9260 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
9263 case BPF_FUNC_current_task_under_cgroup:
9264 case BPF_FUNC_skb_under_cgroup:
9265 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
9268 case BPF_FUNC_redirect_map:
9269 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
9270 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9271 map->map_type != BPF_MAP_TYPE_CPUMAP &&
9272 map->map_type != BPF_MAP_TYPE_XSKMAP)
9275 case BPF_FUNC_sk_redirect_map:
9276 case BPF_FUNC_msg_redirect_map:
9277 case BPF_FUNC_sock_map_update:
9278 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9281 case BPF_FUNC_sk_redirect_hash:
9282 case BPF_FUNC_msg_redirect_hash:
9283 case BPF_FUNC_sock_hash_update:
9284 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
9287 case BPF_FUNC_get_local_storage:
9288 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9289 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9292 case BPF_FUNC_sk_select_reuseport:
9293 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9294 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9295 map->map_type != BPF_MAP_TYPE_SOCKHASH)
9298 case BPF_FUNC_map_pop_elem:
9299 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9300 map->map_type != BPF_MAP_TYPE_STACK)
9303 case BPF_FUNC_map_peek_elem:
9304 case BPF_FUNC_map_push_elem:
9305 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9306 map->map_type != BPF_MAP_TYPE_STACK &&
9307 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9310 case BPF_FUNC_map_lookup_percpu_elem:
9311 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9312 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9313 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9316 case BPF_FUNC_sk_storage_get:
9317 case BPF_FUNC_sk_storage_delete:
9318 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9321 case BPF_FUNC_inode_storage_get:
9322 case BPF_FUNC_inode_storage_delete:
9323 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9326 case BPF_FUNC_task_storage_get:
9327 case BPF_FUNC_task_storage_delete:
9328 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9331 case BPF_FUNC_cgrp_storage_get:
9332 case BPF_FUNC_cgrp_storage_delete:
9333 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9342 verbose(env, "cannot pass map_type %d into func %s#%d\n",
9343 map->map_type, func_id_name(func_id), func_id);
9347 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9351 if (arg_type_is_raw_mem(fn->arg1_type))
9353 if (arg_type_is_raw_mem(fn->arg2_type))
9355 if (arg_type_is_raw_mem(fn->arg3_type))
9357 if (arg_type_is_raw_mem(fn->arg4_type))
9359 if (arg_type_is_raw_mem(fn->arg5_type))
9362 /* We only support one arg being in raw mode at the moment,
9363 * which is sufficient for the helper functions we have
9369 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9371 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9372 bool has_size = fn->arg_size[arg] != 0;
9373 bool is_next_size = false;
9375 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9376 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9378 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9379 return is_next_size;
9381 return has_size == is_next_size || is_next_size == is_fixed;
9384 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9386 /* bpf_xxx(..., buf, len) call will access 'len'
9387 * bytes from memory 'buf'. Both arg types need
9388 * to be paired, so make sure there's no buggy
9389 * helper function specification.
9391 if (arg_type_is_mem_size(fn->arg1_type) ||
9392 check_args_pair_invalid(fn, 0) ||
9393 check_args_pair_invalid(fn, 1) ||
9394 check_args_pair_invalid(fn, 2) ||
9395 check_args_pair_invalid(fn, 3) ||
9396 check_args_pair_invalid(fn, 4))
9402 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9406 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9407 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9408 return !!fn->arg_btf_id[i];
9409 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9410 return fn->arg_btf_id[i] == BPF_PTR_POISON;
9411 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9412 /* arg_btf_id and arg_size are in a union. */
9413 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9414 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9421 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9423 return check_raw_mode_ok(fn) &&
9424 check_arg_pair_ok(fn) &&
9425 check_btf_id_ok(fn) ? 0 : -EINVAL;
9428 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9429 * are now invalid, so turn them into unknown SCALAR_VALUE.
9431 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9432 * since these slices point to packet data.
9434 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9436 struct bpf_func_state *state;
9437 struct bpf_reg_state *reg;
9439 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9440 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9441 mark_reg_invalid(env, reg);
9447 BEYOND_PKT_END = -2,
9450 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9452 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9453 struct bpf_reg_state *reg = &state->regs[regn];
9455 if (reg->type != PTR_TO_PACKET)
9456 /* PTR_TO_PACKET_META is not supported yet */
9459 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9460 * How far beyond pkt_end it goes is unknown.
9461 * if (!range_open) it's the case of pkt >= pkt_end
9462 * if (range_open) it's the case of pkt > pkt_end
9463 * hence this pointer is at least 1 byte bigger than pkt_end
9466 reg->range = BEYOND_PKT_END;
9468 reg->range = AT_PKT_END;
9471 /* The pointer with the specified id has released its reference to kernel
9472 * resources. Identify all copies of the same pointer and clear the reference.
9474 static int release_reference(struct bpf_verifier_env *env,
9477 struct bpf_func_state *state;
9478 struct bpf_reg_state *reg;
9481 err = release_reference_state(cur_func(env), ref_obj_id);
9485 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9486 if (reg->ref_obj_id == ref_obj_id)
9487 mark_reg_invalid(env, reg);
9493 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9495 struct bpf_func_state *unused;
9496 struct bpf_reg_state *reg;
9498 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9499 if (type_is_non_owning_ref(reg->type))
9500 mark_reg_invalid(env, reg);
9504 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9505 struct bpf_reg_state *regs)
9509 /* after the call registers r0 - r5 were scratched */
9510 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9511 mark_reg_not_init(env, regs, caller_saved[i]);
9512 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9516 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9517 struct bpf_func_state *caller,
9518 struct bpf_func_state *callee,
9521 static int set_callee_state(struct bpf_verifier_env *env,
9522 struct bpf_func_state *caller,
9523 struct bpf_func_state *callee, int insn_idx);
9525 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9526 set_callee_state_fn set_callee_state_cb,
9527 struct bpf_verifier_state *state)
9529 struct bpf_func_state *caller, *callee;
9532 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9533 verbose(env, "the call stack of %d frames is too deep\n",
9534 state->curframe + 2);
9538 if (state->frame[state->curframe + 1]) {
9539 verbose(env, "verifier bug. Frame %d already allocated\n",
9540 state->curframe + 1);
9544 caller = state->frame[state->curframe];
9545 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9548 state->frame[state->curframe + 1] = callee;
9550 /* callee cannot access r0, r6 - r9 for reading and has to write
9551 * into its own stack before reading from it.
9552 * callee can read/write into caller's stack
9554 init_func_state(env, callee,
9555 /* remember the callsite, it will be used by bpf_exit */
9557 state->curframe + 1 /* frameno within this callchain */,
9558 subprog /* subprog number within this prog */);
9559 /* Transfer references to the callee */
9560 err = copy_reference_state(callee, caller);
9561 err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9565 /* only increment it after check_reg_arg() finished */
9571 free_func_state(callee);
9572 state->frame[state->curframe + 1] = NULL;
9576 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9577 const struct btf *btf,
9578 struct bpf_reg_state *regs)
9580 struct bpf_subprog_info *sub = subprog_info(env, subprog);
9581 struct bpf_verifier_log *log = &env->log;
9585 ret = btf_prepare_func_args(env, subprog);
9589 /* check that BTF function arguments match actual types that the
9592 for (i = 0; i < sub->arg_cnt; i++) {
9594 struct bpf_reg_state *reg = ®s[regno];
9595 struct bpf_subprog_arg_info *arg = &sub->args[i];
9597 if (arg->arg_type == ARG_ANYTHING) {
9598 if (reg->type != SCALAR_VALUE) {
9599 bpf_log(log, "R%d is not a scalar\n", regno);
9602 } else if (arg->arg_type == ARG_PTR_TO_CTX) {
9603 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9606 /* If function expects ctx type in BTF check that caller
9607 * is passing PTR_TO_CTX.
9609 if (reg->type != PTR_TO_CTX) {
9610 bpf_log(log, "arg#%d expects pointer to ctx\n", i);
9613 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9614 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9617 if (check_mem_reg(env, reg, regno, arg->mem_size))
9619 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
9620 bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
9623 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
9625 * Can pass any value and the kernel won't crash, but
9626 * only PTR_TO_ARENA or SCALAR make sense. Everything
9627 * else is a bug in the bpf program. Point it out to
9628 * the user at the verification time instead of
9629 * run-time debug nightmare.
9631 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
9632 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
9635 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
9636 ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
9640 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
9643 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
9644 struct bpf_call_arg_meta meta;
9647 if (register_is_null(reg) && type_may_be_null(arg->arg_type))
9650 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
9651 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
9652 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
9656 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
9665 /* Compare BTF of a function call with given bpf_reg_state.
9667 * EFAULT - there is a verifier bug. Abort verification.
9668 * EINVAL - there is a type mismatch or BTF is not available.
9669 * 0 - BTF matches with what bpf_reg_state expects.
9670 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9672 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9673 struct bpf_reg_state *regs)
9675 struct bpf_prog *prog = env->prog;
9676 struct btf *btf = prog->aux->btf;
9680 if (!prog->aux->func_info)
9683 btf_id = prog->aux->func_info[subprog].type_id;
9687 if (prog->aux->func_info_aux[subprog].unreliable)
9690 err = btf_check_func_arg_match(env, subprog, btf, regs);
9691 /* Compiler optimizations can remove arguments from static functions
9692 * or mismatched type can be passed into a global function.
9693 * In such cases mark the function as unreliable from BTF point of view.
9696 prog->aux->func_info_aux[subprog].unreliable = true;
9700 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9701 int insn_idx, int subprog,
9702 set_callee_state_fn set_callee_state_cb)
9704 struct bpf_verifier_state *state = env->cur_state, *callback_state;
9705 struct bpf_func_state *caller, *callee;
9708 caller = state->frame[state->curframe];
9709 err = btf_check_subprog_call(env, subprog, caller->regs);
9713 /* set_callee_state is used for direct subprog calls, but we are
9714 * interested in validating only BPF helpers that can call subprogs as
9717 env->subprog_info[subprog].is_cb = true;
9718 if (bpf_pseudo_kfunc_call(insn) &&
9719 !is_callback_calling_kfunc(insn->imm)) {
9720 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9721 func_id_name(insn->imm), insn->imm);
9723 } else if (!bpf_pseudo_kfunc_call(insn) &&
9724 !is_callback_calling_function(insn->imm)) { /* helper */
9725 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9726 func_id_name(insn->imm), insn->imm);
9730 if (is_async_callback_calling_insn(insn)) {
9731 struct bpf_verifier_state *async_cb;
9733 /* there is no real recursion here. timer and workqueue callbacks are async */
9734 env->subprog_info[subprog].is_async_cb = true;
9735 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9737 is_bpf_wq_set_callback_impl_kfunc(insn->imm));
9740 callee = async_cb->frame[0];
9741 callee->async_entry_cnt = caller->async_entry_cnt + 1;
9743 /* Convert bpf_timer_set_callback() args into timer callback args */
9744 err = set_callee_state_cb(env, caller, callee, insn_idx);
9751 /* for callback functions enqueue entry to callback and
9752 * proceed with next instruction within current frame.
9754 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9755 if (!callback_state)
9758 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9763 callback_state->callback_unroll_depth++;
9764 callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9765 caller->callback_depth = 0;
9769 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9772 struct bpf_verifier_state *state = env->cur_state;
9773 struct bpf_func_state *caller;
9774 int err, subprog, target_insn;
9776 target_insn = *insn_idx + insn->imm + 1;
9777 subprog = find_subprog(env, target_insn);
9779 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9783 caller = state->frame[state->curframe];
9784 err = btf_check_subprog_call(env, subprog, caller->regs);
9787 if (subprog_is_global(env, subprog)) {
9788 const char *sub_name = subprog_name(env, subprog);
9790 /* Only global subprogs cannot be called with a lock held. */
9791 if (env->cur_state->active_lock.ptr) {
9792 verbose(env, "global function calls are not allowed while holding a lock,\n"
9793 "use static function instead\n");
9797 /* Only global subprogs cannot be called with preemption disabled. */
9798 if (env->cur_state->active_preempt_lock) {
9799 verbose(env, "global function calls are not allowed with preemption disabled,\n"
9800 "use static function instead\n");
9805 verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9810 verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9812 /* mark global subprog for verifying after main prog */
9813 subprog_aux(env, subprog)->called = true;
9814 clear_caller_saved_regs(env, caller->regs);
9816 /* All global functions return a 64-bit SCALAR_VALUE */
9817 mark_reg_unknown(env, caller->regs, BPF_REG_0);
9818 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9820 /* continue with next insn after call */
9824 /* for regular function entry setup new frame and continue
9827 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9831 clear_caller_saved_regs(env, caller->regs);
9833 /* and go analyze first insn of the callee */
9834 *insn_idx = env->subprog_info[subprog].start - 1;
9836 if (env->log.level & BPF_LOG_LEVEL) {
9837 verbose(env, "caller:\n");
9838 print_verifier_state(env, caller, true);
9839 verbose(env, "callee:\n");
9840 print_verifier_state(env, state->frame[state->curframe], true);
9846 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9847 struct bpf_func_state *caller,
9848 struct bpf_func_state *callee)
9850 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9851 * void *callback_ctx, u64 flags);
9852 * callback_fn(struct bpf_map *map, void *key, void *value,
9853 * void *callback_ctx);
9855 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9857 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9858 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9859 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9861 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9862 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9863 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9865 /* pointer to stack or null */
9866 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9869 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9873 static int set_callee_state(struct bpf_verifier_env *env,
9874 struct bpf_func_state *caller,
9875 struct bpf_func_state *callee, int insn_idx)
9879 /* copy r1 - r5 args that callee can access. The copy includes parent
9880 * pointers, which connects us up to the liveness chain
9882 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9883 callee->regs[i] = caller->regs[i];
9887 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9888 struct bpf_func_state *caller,
9889 struct bpf_func_state *callee,
9892 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9893 struct bpf_map *map;
9896 /* valid map_ptr and poison value does not matter */
9897 map = insn_aux->map_ptr_state.map_ptr;
9898 if (!map->ops->map_set_for_each_callback_args ||
9899 !map->ops->map_for_each_callback) {
9900 verbose(env, "callback function not allowed for map\n");
9904 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9908 callee->in_callback_fn = true;
9909 callee->callback_ret_range = retval_range(0, 1);
9913 static int set_loop_callback_state(struct bpf_verifier_env *env,
9914 struct bpf_func_state *caller,
9915 struct bpf_func_state *callee,
9918 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9920 * callback_fn(u64 index, void *callback_ctx);
9922 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9923 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9926 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9927 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9928 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9930 callee->in_callback_fn = true;
9931 callee->callback_ret_range = retval_range(0, 1);
9935 static int set_timer_callback_state(struct bpf_verifier_env *env,
9936 struct bpf_func_state *caller,
9937 struct bpf_func_state *callee,
9940 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9942 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9943 * callback_fn(struct bpf_map *map, void *key, void *value);
9945 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9946 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9947 callee->regs[BPF_REG_1].map_ptr = map_ptr;
9949 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9950 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9951 callee->regs[BPF_REG_2].map_ptr = map_ptr;
9953 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9954 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9955 callee->regs[BPF_REG_3].map_ptr = map_ptr;
9958 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9959 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9960 callee->in_async_callback_fn = true;
9961 callee->callback_ret_range = retval_range(0, 1);
9965 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9966 struct bpf_func_state *caller,
9967 struct bpf_func_state *callee,
9970 /* bpf_find_vma(struct task_struct *task, u64 addr,
9971 * void *callback_fn, void *callback_ctx, u64 flags)
9972 * (callback_fn)(struct task_struct *task,
9973 * struct vm_area_struct *vma, void *callback_ctx);
9975 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9977 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9978 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9979 callee->regs[BPF_REG_2].btf = btf_vmlinux;
9980 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
9982 /* pointer to stack or null */
9983 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9986 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9987 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9988 callee->in_callback_fn = true;
9989 callee->callback_ret_range = retval_range(0, 1);
9993 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9994 struct bpf_func_state *caller,
9995 struct bpf_func_state *callee,
9998 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9999 * callback_ctx, u64 flags);
10000 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
10002 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
10003 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
10004 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10007 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10008 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10009 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10011 callee->in_callback_fn = true;
10012 callee->callback_ret_range = retval_range(0, 1);
10016 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
10017 struct bpf_func_state *caller,
10018 struct bpf_func_state *callee,
10021 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
10022 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
10024 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
10025 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
10026 * by this point, so look at 'root'
10028 struct btf_field *field;
10030 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
10032 if (!field || !field->graph_root.value_btf_id)
10035 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
10036 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
10037 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
10038 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
10040 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10041 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10042 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10043 callee->in_callback_fn = true;
10044 callee->callback_ret_range = retval_range(0, 1);
10048 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
10050 /* Are we currently verifying the callback for a rbtree helper that must
10051 * be called with lock held? If so, no need to complain about unreleased
10054 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
10056 struct bpf_verifier_state *state = env->cur_state;
10057 struct bpf_insn *insn = env->prog->insnsi;
10058 struct bpf_func_state *callee;
10061 if (!state->curframe)
10064 callee = state->frame[state->curframe];
10066 if (!callee->in_callback_fn)
10069 kfunc_btf_id = insn[callee->callsite].imm;
10070 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
10073 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
10077 return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
10079 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
10082 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
10084 struct bpf_verifier_state *state = env->cur_state, *prev_st;
10085 struct bpf_func_state *caller, *callee;
10086 struct bpf_reg_state *r0;
10087 bool in_callback_fn;
10090 callee = state->frame[state->curframe];
10091 r0 = &callee->regs[BPF_REG_0];
10092 if (r0->type == PTR_TO_STACK) {
10093 /* technically it's ok to return caller's stack pointer
10094 * (or caller's caller's pointer) back to the caller,
10095 * since these pointers are valid. Only current stack
10096 * pointer will be invalid as soon as function exits,
10097 * but let's be conservative
10099 verbose(env, "cannot return stack pointer to the caller\n");
10103 caller = state->frame[state->curframe - 1];
10104 if (callee->in_callback_fn) {
10105 if (r0->type != SCALAR_VALUE) {
10106 verbose(env, "R0 not a scalar value\n");
10110 /* we are going to rely on register's precise value */
10111 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
10112 err = err ?: mark_chain_precision(env, BPF_REG_0);
10116 /* enforce R0 return value range, and bpf_callback_t returns 64bit */
10117 if (!retval_range_within(callee->callback_ret_range, r0, false)) {
10118 verbose_invalid_scalar(env, r0, callee->callback_ret_range,
10119 "At callback return", "R0");
10122 if (!calls_callback(env, callee->callsite)) {
10123 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
10124 *insn_idx, callee->callsite);
10128 /* return to the caller whatever r0 had in the callee */
10129 caller->regs[BPF_REG_0] = *r0;
10132 /* callback_fn frame should have released its own additions to parent's
10133 * reference state at this point, or check_reference_leak would
10134 * complain, hence it must be the same as the caller. There is no need
10137 if (!callee->in_callback_fn) {
10138 /* Transfer references to the caller */
10139 err = copy_reference_state(caller, callee);
10144 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
10145 * there function call logic would reschedule callback visit. If iteration
10146 * converges is_state_visited() would prune that visit eventually.
10148 in_callback_fn = callee->in_callback_fn;
10149 if (in_callback_fn)
10150 *insn_idx = callee->callsite;
10152 *insn_idx = callee->callsite + 1;
10154 if (env->log.level & BPF_LOG_LEVEL) {
10155 verbose(env, "returning from callee:\n");
10156 print_verifier_state(env, callee, true);
10157 verbose(env, "to caller at %d:\n", *insn_idx);
10158 print_verifier_state(env, caller, true);
10160 /* clear everything in the callee. In case of exceptional exits using
10161 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
10162 free_func_state(callee);
10163 state->frame[state->curframe--] = NULL;
10165 /* for callbacks widen imprecise scalars to make programs like below verify:
10167 * struct ctx { int i; }
10168 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
10170 * struct ctx = { .i = 0; }
10171 * bpf_loop(100, cb, &ctx, 0);
10173 * This is similar to what is done in process_iter_next_call() for open
10176 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
10178 err = widen_imprecise_scalars(env, prev_st, state);
10185 static int do_refine_retval_range(struct bpf_verifier_env *env,
10186 struct bpf_reg_state *regs, int ret_type,
10188 struct bpf_call_arg_meta *meta)
10190 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
10192 if (ret_type != RET_INTEGER)
10196 case BPF_FUNC_get_stack:
10197 case BPF_FUNC_get_task_stack:
10198 case BPF_FUNC_probe_read_str:
10199 case BPF_FUNC_probe_read_kernel_str:
10200 case BPF_FUNC_probe_read_user_str:
10201 ret_reg->smax_value = meta->msize_max_value;
10202 ret_reg->s32_max_value = meta->msize_max_value;
10203 ret_reg->smin_value = -MAX_ERRNO;
10204 ret_reg->s32_min_value = -MAX_ERRNO;
10205 reg_bounds_sync(ret_reg);
10207 case BPF_FUNC_get_smp_processor_id:
10208 ret_reg->umax_value = nr_cpu_ids - 1;
10209 ret_reg->u32_max_value = nr_cpu_ids - 1;
10210 ret_reg->smax_value = nr_cpu_ids - 1;
10211 ret_reg->s32_max_value = nr_cpu_ids - 1;
10212 ret_reg->umin_value = 0;
10213 ret_reg->u32_min_value = 0;
10214 ret_reg->smin_value = 0;
10215 ret_reg->s32_min_value = 0;
10216 reg_bounds_sync(ret_reg);
10220 return reg_bounds_sanity_check(env, ret_reg, "retval");
10224 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10225 int func_id, int insn_idx)
10227 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10228 struct bpf_map *map = meta->map_ptr;
10230 if (func_id != BPF_FUNC_tail_call &&
10231 func_id != BPF_FUNC_map_lookup_elem &&
10232 func_id != BPF_FUNC_map_update_elem &&
10233 func_id != BPF_FUNC_map_delete_elem &&
10234 func_id != BPF_FUNC_map_push_elem &&
10235 func_id != BPF_FUNC_map_pop_elem &&
10236 func_id != BPF_FUNC_map_peek_elem &&
10237 func_id != BPF_FUNC_for_each_map_elem &&
10238 func_id != BPF_FUNC_redirect_map &&
10239 func_id != BPF_FUNC_map_lookup_percpu_elem)
10243 verbose(env, "kernel subsystem misconfigured verifier\n");
10247 /* In case of read-only, some additional restrictions
10248 * need to be applied in order to prevent altering the
10249 * state of the map from program side.
10251 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
10252 (func_id == BPF_FUNC_map_delete_elem ||
10253 func_id == BPF_FUNC_map_update_elem ||
10254 func_id == BPF_FUNC_map_push_elem ||
10255 func_id == BPF_FUNC_map_pop_elem)) {
10256 verbose(env, "write into map forbidden\n");
10260 if (!aux->map_ptr_state.map_ptr)
10261 bpf_map_ptr_store(aux, meta->map_ptr,
10262 !meta->map_ptr->bypass_spec_v1, false);
10263 else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
10264 bpf_map_ptr_store(aux, meta->map_ptr,
10265 !meta->map_ptr->bypass_spec_v1, true);
10270 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10271 int func_id, int insn_idx)
10273 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10274 struct bpf_reg_state *regs = cur_regs(env), *reg;
10275 struct bpf_map *map = meta->map_ptr;
10279 if (func_id != BPF_FUNC_tail_call)
10281 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
10282 verbose(env, "kernel subsystem misconfigured verifier\n");
10286 reg = ®s[BPF_REG_3];
10287 val = reg->var_off.value;
10288 max = map->max_entries;
10290 if (!(is_reg_const(reg, false) && val < max)) {
10291 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10295 err = mark_chain_precision(env, BPF_REG_3);
10298 if (bpf_map_key_unseen(aux))
10299 bpf_map_key_store(aux, val);
10300 else if (!bpf_map_key_poisoned(aux) &&
10301 bpf_map_key_immediate(aux) != val)
10302 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10306 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
10308 struct bpf_func_state *state = cur_func(env);
10309 bool refs_lingering = false;
10312 if (!exception_exit && state->frameno && !state->in_callback_fn)
10315 for (i = 0; i < state->acquired_refs; i++) {
10316 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
10318 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
10319 state->refs[i].id, state->refs[i].insn_idx);
10320 refs_lingering = true;
10322 return refs_lingering ? -EINVAL : 0;
10325 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10326 struct bpf_reg_state *regs)
10328 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
10329 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
10330 struct bpf_map *fmt_map = fmt_reg->map_ptr;
10331 struct bpf_bprintf_data data = {};
10332 int err, fmt_map_off, num_args;
10336 /* data must be an array of u64 */
10337 if (data_len_reg->var_off.value % 8)
10339 num_args = data_len_reg->var_off.value / 8;
10341 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10342 * and map_direct_value_addr is set.
10344 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
10345 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10348 verbose(env, "verifier bug\n");
10351 fmt = (char *)(long)fmt_addr + fmt_map_off;
10353 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10354 * can focus on validating the format specifiers.
10356 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10358 verbose(env, "Invalid format string\n");
10363 static int check_get_func_ip(struct bpf_verifier_env *env)
10365 enum bpf_prog_type type = resolve_prog_type(env->prog);
10366 int func_id = BPF_FUNC_get_func_ip;
10368 if (type == BPF_PROG_TYPE_TRACING) {
10369 if (!bpf_prog_has_trampoline(env->prog)) {
10370 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10371 func_id_name(func_id), func_id);
10375 } else if (type == BPF_PROG_TYPE_KPROBE) {
10379 verbose(env, "func %s#%d not supported for program type %d\n",
10380 func_id_name(func_id), func_id, type);
10384 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10386 return &env->insn_aux_data[env->insn_idx];
10389 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10391 struct bpf_reg_state *regs = cur_regs(env);
10392 struct bpf_reg_state *reg = ®s[BPF_REG_4];
10393 bool reg_is_null = register_is_null(reg);
10396 mark_chain_precision(env, BPF_REG_4);
10398 return reg_is_null;
10401 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10403 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10405 if (!state->initialized) {
10406 state->initialized = 1;
10407 state->fit_for_inline = loop_flag_is_zero(env);
10408 state->callback_subprogno = subprogno;
10412 if (!state->fit_for_inline)
10415 state->fit_for_inline = (loop_flag_is_zero(env) &&
10416 state->callback_subprogno == subprogno);
10419 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
10420 const struct bpf_func_proto **ptr)
10422 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
10425 if (!env->ops->get_func_proto)
10428 *ptr = env->ops->get_func_proto(func_id, env->prog);
10429 return *ptr ? 0 : -EINVAL;
10432 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10435 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10436 bool returns_cpu_specific_alloc_ptr = false;
10437 const struct bpf_func_proto *fn = NULL;
10438 enum bpf_return_type ret_type;
10439 enum bpf_type_flag ret_flag;
10440 struct bpf_reg_state *regs;
10441 struct bpf_call_arg_meta meta;
10442 int insn_idx = *insn_idx_p;
10444 int i, err, func_id;
10446 /* find function prototype */
10447 func_id = insn->imm;
10448 err = get_helper_proto(env, insn->imm, &fn);
10449 if (err == -ERANGE) {
10450 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
10455 verbose(env, "program of this type cannot use helper %s#%d\n",
10456 func_id_name(func_id), func_id);
10460 /* eBPF programs must be GPL compatible to use GPL-ed functions */
10461 if (!env->prog->gpl_compatible && fn->gpl_only) {
10462 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10466 if (fn->allowed && !fn->allowed(env->prog)) {
10467 verbose(env, "helper call is not allowed in probe\n");
10471 if (!in_sleepable(env) && fn->might_sleep) {
10472 verbose(env, "helper call might sleep in a non-sleepable prog\n");
10476 /* With LD_ABS/IND some JITs save/restore skb from r1. */
10477 changes_data = bpf_helper_changes_pkt_data(fn->func);
10478 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10479 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10480 func_id_name(func_id), func_id);
10484 memset(&meta, 0, sizeof(meta));
10485 meta.pkt_access = fn->pkt_access;
10487 err = check_func_proto(fn, func_id);
10489 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10490 func_id_name(func_id), func_id);
10494 if (env->cur_state->active_rcu_lock) {
10495 if (fn->might_sleep) {
10496 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10497 func_id_name(func_id), func_id);
10501 if (in_sleepable(env) && is_storage_get_function(func_id))
10502 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10505 if (env->cur_state->active_preempt_lock) {
10506 if (fn->might_sleep) {
10507 verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
10508 func_id_name(func_id), func_id);
10512 if (in_sleepable(env) && is_storage_get_function(func_id))
10513 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10516 meta.func_id = func_id;
10518 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10519 err = check_func_arg(env, i, &meta, fn, insn_idx);
10524 err = record_func_map(env, &meta, func_id, insn_idx);
10528 err = record_func_key(env, &meta, func_id, insn_idx);
10532 /* Mark slots with STACK_MISC in case of raw mode, stack offset
10533 * is inferred from register state.
10535 for (i = 0; i < meta.access_size; i++) {
10536 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10537 BPF_WRITE, -1, false, false);
10542 regs = cur_regs(env);
10544 if (meta.release_regno) {
10546 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10547 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10548 * is safe to do directly.
10550 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10551 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10552 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10555 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
10556 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10557 u32 ref_obj_id = meta.ref_obj_id;
10558 bool in_rcu = in_rcu_cs(env);
10559 struct bpf_func_state *state;
10560 struct bpf_reg_state *reg;
10562 err = release_reference_state(cur_func(env), ref_obj_id);
10564 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10565 if (reg->ref_obj_id == ref_obj_id) {
10566 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10567 reg->ref_obj_id = 0;
10568 reg->type &= ~MEM_ALLOC;
10569 reg->type |= MEM_RCU;
10571 mark_reg_invalid(env, reg);
10576 } else if (meta.ref_obj_id) {
10577 err = release_reference(env, meta.ref_obj_id);
10578 } else if (register_is_null(®s[meta.release_regno])) {
10579 /* meta.ref_obj_id can only be 0 if register that is meant to be
10580 * released is NULL, which must be > R0.
10585 verbose(env, "func %s#%d reference has not been acquired before\n",
10586 func_id_name(func_id), func_id);
10592 case BPF_FUNC_tail_call:
10593 err = check_reference_leak(env, false);
10595 verbose(env, "tail_call would lead to reference leak\n");
10599 case BPF_FUNC_get_local_storage:
10600 /* check that flags argument in get_local_storage(map, flags) is 0,
10601 * this is required because get_local_storage() can't return an error.
10603 if (!register_is_null(®s[BPF_REG_2])) {
10604 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10608 case BPF_FUNC_for_each_map_elem:
10609 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10610 set_map_elem_callback_state);
10612 case BPF_FUNC_timer_set_callback:
10613 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10614 set_timer_callback_state);
10616 case BPF_FUNC_find_vma:
10617 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10618 set_find_vma_callback_state);
10620 case BPF_FUNC_snprintf:
10621 err = check_bpf_snprintf_call(env, regs);
10623 case BPF_FUNC_loop:
10624 update_loop_inline_state(env, meta.subprogno);
10625 /* Verifier relies on R1 value to determine if bpf_loop() iteration
10626 * is finished, thus mark it precise.
10628 err = mark_chain_precision(env, BPF_REG_1);
10631 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10632 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10633 set_loop_callback_state);
10635 cur_func(env)->callback_depth = 0;
10636 if (env->log.level & BPF_LOG_LEVEL2)
10637 verbose(env, "frame%d bpf_loop iteration limit reached\n",
10638 env->cur_state->curframe);
10641 case BPF_FUNC_dynptr_from_mem:
10642 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10643 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10644 reg_type_str(env, regs[BPF_REG_1].type));
10648 case BPF_FUNC_set_retval:
10649 if (prog_type == BPF_PROG_TYPE_LSM &&
10650 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10651 if (!env->prog->aux->attach_func_proto->type) {
10652 /* Make sure programs that attach to void
10653 * hooks don't try to modify return value.
10655 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10660 case BPF_FUNC_dynptr_data:
10662 struct bpf_reg_state *reg;
10663 int id, ref_obj_id;
10665 reg = get_dynptr_arg_reg(env, fn, regs);
10670 if (meta.dynptr_id) {
10671 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10674 if (meta.ref_obj_id) {
10675 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10679 id = dynptr_id(env, reg);
10681 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10685 ref_obj_id = dynptr_ref_obj_id(env, reg);
10686 if (ref_obj_id < 0) {
10687 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10691 meta.dynptr_id = id;
10692 meta.ref_obj_id = ref_obj_id;
10696 case BPF_FUNC_dynptr_write:
10698 enum bpf_dynptr_type dynptr_type;
10699 struct bpf_reg_state *reg;
10701 reg = get_dynptr_arg_reg(env, fn, regs);
10705 dynptr_type = dynptr_get_type(env, reg);
10706 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10709 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10710 /* this will trigger clear_all_pkt_pointers(), which will
10711 * invalidate all dynptr slices associated with the skb
10713 changes_data = true;
10717 case BPF_FUNC_per_cpu_ptr:
10718 case BPF_FUNC_this_cpu_ptr:
10720 struct bpf_reg_state *reg = ®s[BPF_REG_1];
10721 const struct btf_type *type;
10723 if (reg->type & MEM_RCU) {
10724 type = btf_type_by_id(reg->btf, reg->btf_id);
10725 if (!type || !btf_type_is_struct(type)) {
10726 verbose(env, "Helper has invalid btf/btf_id in R1\n");
10729 returns_cpu_specific_alloc_ptr = true;
10730 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10734 case BPF_FUNC_user_ringbuf_drain:
10735 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10736 set_user_ringbuf_callback_state);
10743 /* reset caller saved regs */
10744 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10745 mark_reg_not_init(env, regs, caller_saved[i]);
10746 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10749 /* helper call returns 64-bit value. */
10750 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10752 /* update return register (already marked as written above) */
10753 ret_type = fn->ret_type;
10754 ret_flag = type_flag(ret_type);
10756 switch (base_type(ret_type)) {
10758 /* sets type to SCALAR_VALUE */
10759 mark_reg_unknown(env, regs, BPF_REG_0);
10762 regs[BPF_REG_0].type = NOT_INIT;
10764 case RET_PTR_TO_MAP_VALUE:
10765 /* There is no offset yet applied, variable or fixed */
10766 mark_reg_known_zero(env, regs, BPF_REG_0);
10767 /* remember map_ptr, so that check_map_access()
10768 * can check 'value_size' boundary of memory access
10769 * to map element returned from bpf_map_lookup_elem()
10771 if (meta.map_ptr == NULL) {
10773 "kernel subsystem misconfigured verifier\n");
10776 regs[BPF_REG_0].map_ptr = meta.map_ptr;
10777 regs[BPF_REG_0].map_uid = meta.map_uid;
10778 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10779 if (!type_may_be_null(ret_type) &&
10780 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10781 regs[BPF_REG_0].id = ++env->id_gen;
10784 case RET_PTR_TO_SOCKET:
10785 mark_reg_known_zero(env, regs, BPF_REG_0);
10786 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10788 case RET_PTR_TO_SOCK_COMMON:
10789 mark_reg_known_zero(env, regs, BPF_REG_0);
10790 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10792 case RET_PTR_TO_TCP_SOCK:
10793 mark_reg_known_zero(env, regs, BPF_REG_0);
10794 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10796 case RET_PTR_TO_MEM:
10797 mark_reg_known_zero(env, regs, BPF_REG_0);
10798 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10799 regs[BPF_REG_0].mem_size = meta.mem_size;
10801 case RET_PTR_TO_MEM_OR_BTF_ID:
10803 const struct btf_type *t;
10805 mark_reg_known_zero(env, regs, BPF_REG_0);
10806 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10807 if (!btf_type_is_struct(t)) {
10809 const struct btf_type *ret;
10812 /* resolve the type size of ksym. */
10813 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10815 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10816 verbose(env, "unable to resolve the size of type '%s': %ld\n",
10817 tname, PTR_ERR(ret));
10820 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10821 regs[BPF_REG_0].mem_size = tsize;
10823 if (returns_cpu_specific_alloc_ptr) {
10824 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10826 /* MEM_RDONLY may be carried from ret_flag, but it
10827 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10828 * it will confuse the check of PTR_TO_BTF_ID in
10829 * check_mem_access().
10831 ret_flag &= ~MEM_RDONLY;
10832 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10835 regs[BPF_REG_0].btf = meta.ret_btf;
10836 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10840 case RET_PTR_TO_BTF_ID:
10842 struct btf *ret_btf;
10845 mark_reg_known_zero(env, regs, BPF_REG_0);
10846 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10847 if (func_id == BPF_FUNC_kptr_xchg) {
10848 ret_btf = meta.kptr_field->kptr.btf;
10849 ret_btf_id = meta.kptr_field->kptr.btf_id;
10850 if (!btf_is_kernel(ret_btf)) {
10851 regs[BPF_REG_0].type |= MEM_ALLOC;
10852 if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10853 regs[BPF_REG_0].type |= MEM_PERCPU;
10856 if (fn->ret_btf_id == BPF_PTR_POISON) {
10857 verbose(env, "verifier internal error:");
10858 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10859 func_id_name(func_id));
10862 ret_btf = btf_vmlinux;
10863 ret_btf_id = *fn->ret_btf_id;
10865 if (ret_btf_id == 0) {
10866 verbose(env, "invalid return type %u of func %s#%d\n",
10867 base_type(ret_type), func_id_name(func_id),
10871 regs[BPF_REG_0].btf = ret_btf;
10872 regs[BPF_REG_0].btf_id = ret_btf_id;
10876 verbose(env, "unknown return type %u of func %s#%d\n",
10877 base_type(ret_type), func_id_name(func_id), func_id);
10881 if (type_may_be_null(regs[BPF_REG_0].type))
10882 regs[BPF_REG_0].id = ++env->id_gen;
10884 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10885 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10886 func_id_name(func_id), func_id);
10890 if (is_dynptr_ref_function(func_id))
10891 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10893 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10894 /* For release_reference() */
10895 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10896 } else if (is_acquire_function(func_id, meta.map_ptr)) {
10897 int id = acquire_reference_state(env, insn_idx);
10901 /* For mark_ptr_or_null_reg() */
10902 regs[BPF_REG_0].id = id;
10903 /* For release_reference() */
10904 regs[BPF_REG_0].ref_obj_id = id;
10907 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
10911 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10915 if ((func_id == BPF_FUNC_get_stack ||
10916 func_id == BPF_FUNC_get_task_stack) &&
10917 !env->prog->has_callchain_buf) {
10918 const char *err_str;
10920 #ifdef CONFIG_PERF_EVENTS
10921 err = get_callchain_buffers(sysctl_perf_event_max_stack);
10922 err_str = "cannot get callchain buffer for func %s#%d\n";
10925 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10928 verbose(env, err_str, func_id_name(func_id), func_id);
10932 env->prog->has_callchain_buf = true;
10935 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10936 env->prog->call_get_stack = true;
10938 if (func_id == BPF_FUNC_get_func_ip) {
10939 if (check_get_func_ip(env))
10941 env->prog->call_get_func_ip = true;
10945 clear_all_pkt_pointers(env);
10949 /* mark_btf_func_reg_size() is used when the reg size is determined by
10950 * the BTF func_proto's return value size and argument.
10952 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10955 struct bpf_reg_state *reg = &cur_regs(env)[regno];
10957 if (regno == BPF_REG_0) {
10958 /* Function return value */
10959 reg->live |= REG_LIVE_WRITTEN;
10960 reg->subreg_def = reg_size == sizeof(u64) ?
10961 DEF_NOT_SUBREG : env->insn_idx + 1;
10963 /* Function argument */
10964 if (reg_size == sizeof(u64)) {
10965 mark_insn_zext(env, reg);
10966 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10968 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10973 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10975 return meta->kfunc_flags & KF_ACQUIRE;
10978 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10980 return meta->kfunc_flags & KF_RELEASE;
10983 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10985 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10988 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10990 return meta->kfunc_flags & KF_SLEEPABLE;
10993 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10995 return meta->kfunc_flags & KF_DESTRUCTIVE;
10998 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
11000 return meta->kfunc_flags & KF_RCU;
11003 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
11005 return meta->kfunc_flags & KF_RCU_PROTECTED;
11008 static bool is_kfunc_arg_mem_size(const struct btf *btf,
11009 const struct btf_param *arg,
11010 const struct bpf_reg_state *reg)
11012 const struct btf_type *t;
11014 t = btf_type_skip_modifiers(btf, arg->type, NULL);
11015 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11018 return btf_param_match_suffix(btf, arg, "__sz");
11021 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
11022 const struct btf_param *arg,
11023 const struct bpf_reg_state *reg)
11025 const struct btf_type *t;
11027 t = btf_type_skip_modifiers(btf, arg->type, NULL);
11028 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11031 return btf_param_match_suffix(btf, arg, "__szk");
11034 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
11036 return btf_param_match_suffix(btf, arg, "__opt");
11039 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
11041 return btf_param_match_suffix(btf, arg, "__k");
11044 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
11046 return btf_param_match_suffix(btf, arg, "__ign");
11049 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
11051 return btf_param_match_suffix(btf, arg, "__map");
11054 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
11056 return btf_param_match_suffix(btf, arg, "__alloc");
11059 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
11061 return btf_param_match_suffix(btf, arg, "__uninit");
11064 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
11066 return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
11069 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
11071 return btf_param_match_suffix(btf, arg, "__nullable");
11074 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
11076 return btf_param_match_suffix(btf, arg, "__str");
11079 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
11080 const struct btf_param *arg,
11083 int len, target_len = strlen(name);
11084 const char *param_name;
11086 param_name = btf_name_by_offset(btf, arg->name_off);
11087 if (str_is_empty(param_name))
11089 len = strlen(param_name);
11090 if (len != target_len)
11092 if (strcmp(param_name, name))
11100 KF_ARG_LIST_HEAD_ID,
11101 KF_ARG_LIST_NODE_ID,
11104 KF_ARG_WORKQUEUE_ID,
11107 BTF_ID_LIST(kf_arg_btf_ids)
11108 BTF_ID(struct, bpf_dynptr)
11109 BTF_ID(struct, bpf_list_head)
11110 BTF_ID(struct, bpf_list_node)
11111 BTF_ID(struct, bpf_rb_root)
11112 BTF_ID(struct, bpf_rb_node)
11113 BTF_ID(struct, bpf_wq)
11115 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
11116 const struct btf_param *arg, int type)
11118 const struct btf_type *t;
11121 t = btf_type_skip_modifiers(btf, arg->type, NULL);
11124 if (!btf_type_is_ptr(t))
11126 t = btf_type_skip_modifiers(btf, t->type, &res_id);
11129 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
11132 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
11134 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
11137 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
11139 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
11142 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
11144 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
11147 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
11149 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
11152 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
11154 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
11157 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
11159 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
11162 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
11163 const struct btf_param *arg)
11165 const struct btf_type *t;
11167 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
11174 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
11175 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
11176 const struct btf *btf,
11177 const struct btf_type *t, int rec)
11179 const struct btf_type *member_type;
11180 const struct btf_member *member;
11183 if (!btf_type_is_struct(t))
11186 for_each_member(i, t, member) {
11187 const struct btf_array *array;
11189 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
11190 if (btf_type_is_struct(member_type)) {
11192 verbose(env, "max struct nesting depth exceeded\n");
11195 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
11199 if (btf_type_is_array(member_type)) {
11200 array = btf_array(member_type);
11201 if (!array->nelems)
11203 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
11204 if (!btf_type_is_scalar(member_type))
11208 if (!btf_type_is_scalar(member_type))
11214 enum kfunc_ptr_arg_type {
11216 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
11217 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
11218 KF_ARG_PTR_TO_DYNPTR,
11219 KF_ARG_PTR_TO_ITER,
11220 KF_ARG_PTR_TO_LIST_HEAD,
11221 KF_ARG_PTR_TO_LIST_NODE,
11222 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
11224 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
11225 KF_ARG_PTR_TO_CALLBACK,
11226 KF_ARG_PTR_TO_RB_ROOT,
11227 KF_ARG_PTR_TO_RB_NODE,
11228 KF_ARG_PTR_TO_NULL,
11229 KF_ARG_PTR_TO_CONST_STR,
11231 KF_ARG_PTR_TO_WORKQUEUE,
11234 enum special_kfunc_type {
11235 KF_bpf_obj_new_impl,
11236 KF_bpf_obj_drop_impl,
11237 KF_bpf_refcount_acquire_impl,
11238 KF_bpf_list_push_front_impl,
11239 KF_bpf_list_push_back_impl,
11240 KF_bpf_list_pop_front,
11241 KF_bpf_list_pop_back,
11242 KF_bpf_cast_to_kern_ctx,
11243 KF_bpf_rdonly_cast,
11244 KF_bpf_rcu_read_lock,
11245 KF_bpf_rcu_read_unlock,
11246 KF_bpf_rbtree_remove,
11247 KF_bpf_rbtree_add_impl,
11248 KF_bpf_rbtree_first,
11249 KF_bpf_dynptr_from_skb,
11250 KF_bpf_dynptr_from_xdp,
11251 KF_bpf_dynptr_slice,
11252 KF_bpf_dynptr_slice_rdwr,
11253 KF_bpf_dynptr_clone,
11254 KF_bpf_percpu_obj_new_impl,
11255 KF_bpf_percpu_obj_drop_impl,
11257 KF_bpf_wq_set_callback_impl,
11258 KF_bpf_preempt_disable,
11259 KF_bpf_preempt_enable,
11260 KF_bpf_iter_css_task_new,
11261 KF_bpf_session_cookie,
11262 KF_bpf_get_kmem_cache,
11265 BTF_SET_START(special_kfunc_set)
11266 BTF_ID(func, bpf_obj_new_impl)
11267 BTF_ID(func, bpf_obj_drop_impl)
11268 BTF_ID(func, bpf_refcount_acquire_impl)
11269 BTF_ID(func, bpf_list_push_front_impl)
11270 BTF_ID(func, bpf_list_push_back_impl)
11271 BTF_ID(func, bpf_list_pop_front)
11272 BTF_ID(func, bpf_list_pop_back)
11273 BTF_ID(func, bpf_cast_to_kern_ctx)
11274 BTF_ID(func, bpf_rdonly_cast)
11275 BTF_ID(func, bpf_rbtree_remove)
11276 BTF_ID(func, bpf_rbtree_add_impl)
11277 BTF_ID(func, bpf_rbtree_first)
11278 BTF_ID(func, bpf_dynptr_from_skb)
11279 BTF_ID(func, bpf_dynptr_from_xdp)
11280 BTF_ID(func, bpf_dynptr_slice)
11281 BTF_ID(func, bpf_dynptr_slice_rdwr)
11282 BTF_ID(func, bpf_dynptr_clone)
11283 BTF_ID(func, bpf_percpu_obj_new_impl)
11284 BTF_ID(func, bpf_percpu_obj_drop_impl)
11285 BTF_ID(func, bpf_throw)
11286 BTF_ID(func, bpf_wq_set_callback_impl)
11287 #ifdef CONFIG_CGROUPS
11288 BTF_ID(func, bpf_iter_css_task_new)
11290 BTF_SET_END(special_kfunc_set)
11292 BTF_ID_LIST(special_kfunc_list)
11293 BTF_ID(func, bpf_obj_new_impl)
11294 BTF_ID(func, bpf_obj_drop_impl)
11295 BTF_ID(func, bpf_refcount_acquire_impl)
11296 BTF_ID(func, bpf_list_push_front_impl)
11297 BTF_ID(func, bpf_list_push_back_impl)
11298 BTF_ID(func, bpf_list_pop_front)
11299 BTF_ID(func, bpf_list_pop_back)
11300 BTF_ID(func, bpf_cast_to_kern_ctx)
11301 BTF_ID(func, bpf_rdonly_cast)
11302 BTF_ID(func, bpf_rcu_read_lock)
11303 BTF_ID(func, bpf_rcu_read_unlock)
11304 BTF_ID(func, bpf_rbtree_remove)
11305 BTF_ID(func, bpf_rbtree_add_impl)
11306 BTF_ID(func, bpf_rbtree_first)
11307 BTF_ID(func, bpf_dynptr_from_skb)
11308 BTF_ID(func, bpf_dynptr_from_xdp)
11309 BTF_ID(func, bpf_dynptr_slice)
11310 BTF_ID(func, bpf_dynptr_slice_rdwr)
11311 BTF_ID(func, bpf_dynptr_clone)
11312 BTF_ID(func, bpf_percpu_obj_new_impl)
11313 BTF_ID(func, bpf_percpu_obj_drop_impl)
11314 BTF_ID(func, bpf_throw)
11315 BTF_ID(func, bpf_wq_set_callback_impl)
11316 BTF_ID(func, bpf_preempt_disable)
11317 BTF_ID(func, bpf_preempt_enable)
11318 #ifdef CONFIG_CGROUPS
11319 BTF_ID(func, bpf_iter_css_task_new)
11323 #ifdef CONFIG_BPF_EVENTS
11324 BTF_ID(func, bpf_session_cookie)
11328 BTF_ID(func, bpf_get_kmem_cache)
11330 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
11332 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
11333 meta->arg_owning_ref) {
11337 return meta->kfunc_flags & KF_RET_NULL;
11340 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
11342 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
11345 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
11347 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11350 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
11352 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
11355 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
11357 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
11360 static enum kfunc_ptr_arg_type
11361 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
11362 struct bpf_kfunc_call_arg_meta *meta,
11363 const struct btf_type *t, const struct btf_type *ref_t,
11364 const char *ref_tname, const struct btf_param *args,
11365 int argno, int nargs)
11367 u32 regno = argno + 1;
11368 struct bpf_reg_state *regs = cur_regs(env);
11369 struct bpf_reg_state *reg = ®s[regno];
11370 bool arg_mem_size = false;
11372 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
11373 return KF_ARG_PTR_TO_CTX;
11375 /* In this function, we verify the kfunc's BTF as per the argument type,
11376 * leaving the rest of the verification with respect to the register
11377 * type to our caller. When a set of conditions hold in the BTF type of
11378 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11380 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
11381 return KF_ARG_PTR_TO_CTX;
11383 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11384 return KF_ARG_PTR_TO_NULL;
11386 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
11387 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11389 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
11390 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11392 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
11393 return KF_ARG_PTR_TO_DYNPTR;
11395 if (is_kfunc_arg_iter(meta, argno, &args[argno]))
11396 return KF_ARG_PTR_TO_ITER;
11398 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
11399 return KF_ARG_PTR_TO_LIST_HEAD;
11401 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
11402 return KF_ARG_PTR_TO_LIST_NODE;
11404 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
11405 return KF_ARG_PTR_TO_RB_ROOT;
11407 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
11408 return KF_ARG_PTR_TO_RB_NODE;
11410 if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
11411 return KF_ARG_PTR_TO_CONST_STR;
11413 if (is_kfunc_arg_map(meta->btf, &args[argno]))
11414 return KF_ARG_PTR_TO_MAP;
11416 if (is_kfunc_arg_wq(meta->btf, &args[argno]))
11417 return KF_ARG_PTR_TO_WORKQUEUE;
11419 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11420 if (!btf_type_is_struct(ref_t)) {
11421 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11422 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11425 return KF_ARG_PTR_TO_BTF_ID;
11428 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11429 return KF_ARG_PTR_TO_CALLBACK;
11431 if (argno + 1 < nargs &&
11432 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
11433 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
11434 arg_mem_size = true;
11436 /* This is the catch all argument type of register types supported by
11437 * check_helper_mem_access. However, we only allow when argument type is
11438 * pointer to scalar, or struct composed (recursively) of scalars. When
11439 * arg_mem_size is true, the pointer can be void *.
11441 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11442 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11443 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11444 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11447 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11450 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11451 struct bpf_reg_state *reg,
11452 const struct btf_type *ref_t,
11453 const char *ref_tname, u32 ref_id,
11454 struct bpf_kfunc_call_arg_meta *meta,
11457 const struct btf_type *reg_ref_t;
11458 bool strict_type_match = false;
11459 const struct btf *reg_btf;
11460 const char *reg_ref_tname;
11461 bool taking_projection;
11465 if (base_type(reg->type) == PTR_TO_BTF_ID) {
11466 reg_btf = reg->btf;
11467 reg_ref_id = reg->btf_id;
11469 reg_btf = btf_vmlinux;
11470 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11473 /* Enforce strict type matching for calls to kfuncs that are acquiring
11474 * or releasing a reference, or are no-cast aliases. We do _not_
11475 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11476 * as we want to enable BPF programs to pass types that are bitwise
11477 * equivalent without forcing them to explicitly cast with something
11478 * like bpf_cast_to_kern_ctx().
11480 * For example, say we had a type like the following:
11482 * struct bpf_cpumask {
11483 * cpumask_t cpumask;
11484 * refcount_t usage;
11487 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11488 * to a struct cpumask, so it would be safe to pass a struct
11489 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11491 * The philosophy here is similar to how we allow scalars of different
11492 * types to be passed to kfuncs as long as the size is the same. The
11493 * only difference here is that we're simply allowing
11494 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11497 if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
11498 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11499 strict_type_match = true;
11501 WARN_ON_ONCE(is_kfunc_release(meta) &&
11502 (reg->off || !tnum_is_const(reg->var_off) ||
11503 reg->var_off.value));
11505 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
11506 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11507 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
11508 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
11509 * actually use it -- it must cast to the underlying type. So we allow
11510 * caller to pass in the underlying type.
11512 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
11513 if (!taking_projection && !struct_same) {
11514 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11515 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11516 btf_type_str(reg_ref_t), reg_ref_tname);
11522 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11524 struct bpf_verifier_state *state = env->cur_state;
11525 struct btf_record *rec = reg_btf_record(reg);
11527 if (!state->active_lock.ptr) {
11528 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11532 if (type_flag(reg->type) & NON_OWN_REF) {
11533 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11537 reg->type |= NON_OWN_REF;
11538 if (rec->refcount_off >= 0)
11539 reg->type |= MEM_RCU;
11544 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11546 struct bpf_func_state *state, *unused;
11547 struct bpf_reg_state *reg;
11550 state = cur_func(env);
11553 verbose(env, "verifier internal error: ref_obj_id is zero for "
11554 "owning -> non-owning conversion\n");
11558 for (i = 0; i < state->acquired_refs; i++) {
11559 if (state->refs[i].id != ref_obj_id)
11562 /* Clear ref_obj_id here so release_reference doesn't clobber
11565 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11566 if (reg->ref_obj_id == ref_obj_id) {
11567 reg->ref_obj_id = 0;
11568 ref_set_non_owning(env, reg);
11574 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11578 /* Implementation details:
11580 * Each register points to some region of memory, which we define as an
11581 * allocation. Each allocation may embed a bpf_spin_lock which protects any
11582 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11583 * allocation. The lock and the data it protects are colocated in the same
11586 * Hence, everytime a register holds a pointer value pointing to such
11587 * allocation, the verifier preserves a unique reg->id for it.
11589 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11590 * bpf_spin_lock is called.
11592 * To enable this, lock state in the verifier captures two values:
11593 * active_lock.ptr = Register's type specific pointer
11594 * active_lock.id = A unique ID for each register pointer value
11596 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11597 * supported register types.
11599 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11600 * allocated objects is the reg->btf pointer.
11602 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11603 * can establish the provenance of the map value statically for each distinct
11604 * lookup into such maps. They always contain a single map value hence unique
11605 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11607 * So, in case of global variables, they use array maps with max_entries = 1,
11608 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11609 * into the same map value as max_entries is 1, as described above).
11611 * In case of inner map lookups, the inner map pointer has same map_ptr as the
11612 * outer map pointer (in verifier context), but each lookup into an inner map
11613 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11614 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11615 * will get different reg->id assigned to each lookup, hence different
11618 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11619 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11620 * returned from bpf_obj_new. Each allocation receives a new reg->id.
11622 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11627 switch ((int)reg->type) {
11628 case PTR_TO_MAP_VALUE:
11629 ptr = reg->map_ptr;
11631 case PTR_TO_BTF_ID | MEM_ALLOC:
11635 verbose(env, "verifier internal error: unknown reg type for lock check\n");
11640 if (!env->cur_state->active_lock.ptr)
11642 if (env->cur_state->active_lock.ptr != ptr ||
11643 env->cur_state->active_lock.id != id) {
11644 verbose(env, "held lock and object are not in the same allocation\n");
11650 static bool is_bpf_list_api_kfunc(u32 btf_id)
11652 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11653 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11654 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11655 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11658 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11660 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11661 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11662 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11665 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11667 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11668 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11671 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11673 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11676 static bool is_async_callback_calling_kfunc(u32 btf_id)
11678 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
11681 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11683 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11684 insn->imm == special_kfunc_list[KF_bpf_throw];
11687 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
11689 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
11692 static bool is_callback_calling_kfunc(u32 btf_id)
11694 return is_sync_callback_calling_kfunc(btf_id) ||
11695 is_async_callback_calling_kfunc(btf_id);
11698 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11700 return is_bpf_rbtree_api_kfunc(btf_id);
11703 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11704 enum btf_field_type head_field_type,
11709 switch (head_field_type) {
11710 case BPF_LIST_HEAD:
11711 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11714 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11717 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11718 btf_field_type_name(head_field_type));
11723 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11724 btf_field_type_name(head_field_type));
11728 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11729 enum btf_field_type node_field_type,
11734 switch (node_field_type) {
11735 case BPF_LIST_NODE:
11736 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11737 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11740 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11741 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11744 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11745 btf_field_type_name(node_field_type));
11750 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11751 btf_field_type_name(node_field_type));
11756 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11757 struct bpf_reg_state *reg, u32 regno,
11758 struct bpf_kfunc_call_arg_meta *meta,
11759 enum btf_field_type head_field_type,
11760 struct btf_field **head_field)
11762 const char *head_type_name;
11763 struct btf_field *field;
11764 struct btf_record *rec;
11767 if (meta->btf != btf_vmlinux) {
11768 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11772 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11775 head_type_name = btf_field_type_name(head_field_type);
11776 if (!tnum_is_const(reg->var_off)) {
11778 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11779 regno, head_type_name);
11783 rec = reg_btf_record(reg);
11784 head_off = reg->off + reg->var_off.value;
11785 field = btf_record_find(rec, head_off, head_field_type);
11787 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11791 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11792 if (check_reg_allocation_locked(env, reg)) {
11793 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11794 rec->spin_lock_off, head_type_name);
11799 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11802 *head_field = field;
11806 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11807 struct bpf_reg_state *reg, u32 regno,
11808 struct bpf_kfunc_call_arg_meta *meta)
11810 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11811 &meta->arg_list_head.field);
11814 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11815 struct bpf_reg_state *reg, u32 regno,
11816 struct bpf_kfunc_call_arg_meta *meta)
11818 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11819 &meta->arg_rbtree_root.field);
11823 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11824 struct bpf_reg_state *reg, u32 regno,
11825 struct bpf_kfunc_call_arg_meta *meta,
11826 enum btf_field_type head_field_type,
11827 enum btf_field_type node_field_type,
11828 struct btf_field **node_field)
11830 const char *node_type_name;
11831 const struct btf_type *et, *t;
11832 struct btf_field *field;
11835 if (meta->btf != btf_vmlinux) {
11836 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11840 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11843 node_type_name = btf_field_type_name(node_field_type);
11844 if (!tnum_is_const(reg->var_off)) {
11846 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11847 regno, node_type_name);
11851 node_off = reg->off + reg->var_off.value;
11852 field = reg_find_field_offset(reg, node_off, node_field_type);
11854 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11858 field = *node_field;
11860 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11861 t = btf_type_by_id(reg->btf, reg->btf_id);
11862 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11863 field->graph_root.value_btf_id, true)) {
11864 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11865 "in struct %s, but arg is at offset=%d in struct %s\n",
11866 btf_field_type_name(head_field_type),
11867 btf_field_type_name(node_field_type),
11868 field->graph_root.node_offset,
11869 btf_name_by_offset(field->graph_root.btf, et->name_off),
11870 node_off, btf_name_by_offset(reg->btf, t->name_off));
11873 meta->arg_btf = reg->btf;
11874 meta->arg_btf_id = reg->btf_id;
11876 if (node_off != field->graph_root.node_offset) {
11877 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11878 node_off, btf_field_type_name(node_field_type),
11879 field->graph_root.node_offset,
11880 btf_name_by_offset(field->graph_root.btf, et->name_off));
11887 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11888 struct bpf_reg_state *reg, u32 regno,
11889 struct bpf_kfunc_call_arg_meta *meta)
11891 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11892 BPF_LIST_HEAD, BPF_LIST_NODE,
11893 &meta->arg_list_head.field);
11896 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11897 struct bpf_reg_state *reg, u32 regno,
11898 struct bpf_kfunc_call_arg_meta *meta)
11900 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11901 BPF_RB_ROOT, BPF_RB_NODE,
11902 &meta->arg_rbtree_root.field);
11906 * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11907 * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11908 * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11909 * them can only be attached to some specific hook points.
11911 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11913 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11915 switch (prog_type) {
11916 case BPF_PROG_TYPE_LSM:
11918 case BPF_PROG_TYPE_TRACING:
11919 if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11923 return in_sleepable(env);
11927 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11930 const char *func_name = meta->func_name, *ref_tname;
11931 const struct btf *btf = meta->btf;
11932 const struct btf_param *args;
11933 struct btf_record *rec;
11937 args = (const struct btf_param *)(meta->func_proto + 1);
11938 nargs = btf_type_vlen(meta->func_proto);
11939 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11940 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11941 MAX_BPF_FUNC_REG_ARGS);
11945 /* Check that BTF function arguments match actual types that the
11948 for (i = 0; i < nargs; i++) {
11949 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
11950 const struct btf_type *t, *ref_t, *resolve_ret;
11951 enum bpf_arg_type arg_type = ARG_DONTCARE;
11952 u32 regno = i + 1, ref_id, type_size;
11953 bool is_ret_buf_sz = false;
11956 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11958 if (is_kfunc_arg_ignore(btf, &args[i]))
11961 if (btf_type_is_scalar(t)) {
11962 if (reg->type != SCALAR_VALUE) {
11963 verbose(env, "R%d is not a scalar\n", regno);
11967 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11968 if (meta->arg_constant.found) {
11969 verbose(env, "verifier internal error: only one constant argument permitted\n");
11972 if (!tnum_is_const(reg->var_off)) {
11973 verbose(env, "R%d must be a known constant\n", regno);
11976 ret = mark_chain_precision(env, regno);
11979 meta->arg_constant.found = true;
11980 meta->arg_constant.value = reg->var_off.value;
11981 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11982 meta->r0_rdonly = true;
11983 is_ret_buf_sz = true;
11984 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11985 is_ret_buf_sz = true;
11988 if (is_ret_buf_sz) {
11989 if (meta->r0_size) {
11990 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11994 if (!tnum_is_const(reg->var_off)) {
11995 verbose(env, "R%d is not a const\n", regno);
11999 meta->r0_size = reg->var_off.value;
12000 ret = mark_chain_precision(env, regno);
12007 if (!btf_type_is_ptr(t)) {
12008 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
12012 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
12013 (register_is_null(reg) || type_may_be_null(reg->type)) &&
12014 !is_kfunc_arg_nullable(meta->btf, &args[i])) {
12015 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
12019 if (reg->ref_obj_id) {
12020 if (is_kfunc_release(meta) && meta->ref_obj_id) {
12021 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
12022 regno, reg->ref_obj_id,
12026 meta->ref_obj_id = reg->ref_obj_id;
12027 if (is_kfunc_release(meta))
12028 meta->release_regno = regno;
12031 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
12032 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12034 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
12035 if (kf_arg_type < 0)
12036 return kf_arg_type;
12038 switch (kf_arg_type) {
12039 case KF_ARG_PTR_TO_NULL:
12041 case KF_ARG_PTR_TO_MAP:
12042 if (!reg->map_ptr) {
12043 verbose(env, "pointer in R%d isn't map pointer\n", regno);
12046 if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) {
12047 /* Use map_uid (which is unique id of inner map) to reject:
12048 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
12049 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
12050 * if (inner_map1 && inner_map2) {
12051 * wq = bpf_map_lookup_elem(inner_map1);
12053 * // mismatch would have been allowed
12054 * bpf_wq_init(wq, inner_map2);
12057 * Comparing map_ptr is enough to distinguish normal and outer maps.
12059 if (meta->map.ptr != reg->map_ptr ||
12060 meta->map.uid != reg->map_uid) {
12062 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
12063 meta->map.uid, reg->map_uid);
12067 meta->map.ptr = reg->map_ptr;
12068 meta->map.uid = reg->map_uid;
12070 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
12071 case KF_ARG_PTR_TO_BTF_ID:
12072 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
12075 if (!is_trusted_reg(reg)) {
12076 if (!is_kfunc_rcu(meta)) {
12077 verbose(env, "R%d must be referenced or trusted\n", regno);
12080 if (!is_rcu_reg(reg)) {
12081 verbose(env, "R%d must be a rcu pointer\n", regno);
12086 case KF_ARG_PTR_TO_CTX:
12087 case KF_ARG_PTR_TO_DYNPTR:
12088 case KF_ARG_PTR_TO_ITER:
12089 case KF_ARG_PTR_TO_LIST_HEAD:
12090 case KF_ARG_PTR_TO_LIST_NODE:
12091 case KF_ARG_PTR_TO_RB_ROOT:
12092 case KF_ARG_PTR_TO_RB_NODE:
12093 case KF_ARG_PTR_TO_MEM:
12094 case KF_ARG_PTR_TO_MEM_SIZE:
12095 case KF_ARG_PTR_TO_CALLBACK:
12096 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12097 case KF_ARG_PTR_TO_CONST_STR:
12098 case KF_ARG_PTR_TO_WORKQUEUE:
12105 if (is_kfunc_release(meta) && reg->ref_obj_id)
12106 arg_type |= OBJ_RELEASE;
12107 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
12111 switch (kf_arg_type) {
12112 case KF_ARG_PTR_TO_CTX:
12113 if (reg->type != PTR_TO_CTX) {
12114 verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
12115 i, reg_type_str(env, reg->type));
12119 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12120 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
12123 meta->ret_btf_id = ret;
12126 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
12127 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
12128 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
12129 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
12132 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
12133 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12134 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
12138 verbose(env, "arg#%d expected pointer to allocated object\n", i);
12141 if (!reg->ref_obj_id) {
12142 verbose(env, "allocated object must be referenced\n");
12145 if (meta->btf == btf_vmlinux) {
12146 meta->arg_btf = reg->btf;
12147 meta->arg_btf_id = reg->btf_id;
12150 case KF_ARG_PTR_TO_DYNPTR:
12152 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
12153 int clone_ref_obj_id = 0;
12155 if (reg->type == CONST_PTR_TO_DYNPTR)
12156 dynptr_arg_type |= MEM_RDONLY;
12158 if (is_kfunc_arg_uninit(btf, &args[i]))
12159 dynptr_arg_type |= MEM_UNINIT;
12161 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
12162 dynptr_arg_type |= DYNPTR_TYPE_SKB;
12163 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
12164 dynptr_arg_type |= DYNPTR_TYPE_XDP;
12165 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
12166 (dynptr_arg_type & MEM_UNINIT)) {
12167 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
12169 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
12170 verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
12174 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
12175 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
12176 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
12177 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
12182 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
12186 if (!(dynptr_arg_type & MEM_UNINIT)) {
12187 int id = dynptr_id(env, reg);
12190 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
12193 meta->initialized_dynptr.id = id;
12194 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
12195 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
12200 case KF_ARG_PTR_TO_ITER:
12201 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
12202 if (!check_css_task_iter_allowlist(env)) {
12203 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
12207 ret = process_iter_arg(env, regno, insn_idx, meta);
12211 case KF_ARG_PTR_TO_LIST_HEAD:
12212 if (reg->type != PTR_TO_MAP_VALUE &&
12213 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12214 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
12217 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
12218 verbose(env, "allocated object must be referenced\n");
12221 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
12225 case KF_ARG_PTR_TO_RB_ROOT:
12226 if (reg->type != PTR_TO_MAP_VALUE &&
12227 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12228 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
12231 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
12232 verbose(env, "allocated object must be referenced\n");
12235 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
12239 case KF_ARG_PTR_TO_LIST_NODE:
12240 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12241 verbose(env, "arg#%d expected pointer to allocated object\n", i);
12244 if (!reg->ref_obj_id) {
12245 verbose(env, "allocated object must be referenced\n");
12248 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
12252 case KF_ARG_PTR_TO_RB_NODE:
12253 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
12254 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
12255 verbose(env, "rbtree_remove node input must be non-owning ref\n");
12258 if (in_rbtree_lock_required_cb(env)) {
12259 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
12263 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12264 verbose(env, "arg#%d expected pointer to allocated object\n", i);
12267 if (!reg->ref_obj_id) {
12268 verbose(env, "allocated object must be referenced\n");
12273 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
12277 case KF_ARG_PTR_TO_MAP:
12278 /* If argument has '__map' suffix expect 'struct bpf_map *' */
12279 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
12280 ref_t = btf_type_by_id(btf_vmlinux, ref_id);
12281 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12283 case KF_ARG_PTR_TO_BTF_ID:
12284 /* Only base_type is checked, further checks are done here */
12285 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
12286 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
12287 !reg2btf_ids[base_type(reg->type)]) {
12288 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
12289 verbose(env, "expected %s or socket\n",
12290 reg_type_str(env, base_type(reg->type) |
12291 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
12294 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
12298 case KF_ARG_PTR_TO_MEM:
12299 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
12300 if (IS_ERR(resolve_ret)) {
12301 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
12302 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
12305 ret = check_mem_reg(env, reg, regno, type_size);
12309 case KF_ARG_PTR_TO_MEM_SIZE:
12311 struct bpf_reg_state *buff_reg = ®s[regno];
12312 const struct btf_param *buff_arg = &args[i];
12313 struct bpf_reg_state *size_reg = ®s[regno + 1];
12314 const struct btf_param *size_arg = &args[i + 1];
12316 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
12317 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
12319 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
12324 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
12325 if (meta->arg_constant.found) {
12326 verbose(env, "verifier internal error: only one constant argument permitted\n");
12329 if (!tnum_is_const(size_reg->var_off)) {
12330 verbose(env, "R%d must be a known constant\n", regno + 1);
12333 meta->arg_constant.found = true;
12334 meta->arg_constant.value = size_reg->var_off.value;
12337 /* Skip next '__sz' or '__szk' argument */
12341 case KF_ARG_PTR_TO_CALLBACK:
12342 if (reg->type != PTR_TO_FUNC) {
12343 verbose(env, "arg%d expected pointer to func\n", i);
12346 meta->subprogno = reg->subprogno;
12348 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12349 if (!type_is_ptr_alloc_obj(reg->type)) {
12350 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
12353 if (!type_is_non_owning_ref(reg->type))
12354 meta->arg_owning_ref = true;
12356 rec = reg_btf_record(reg);
12358 verbose(env, "verifier internal error: Couldn't find btf_record\n");
12362 if (rec->refcount_off < 0) {
12363 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
12367 meta->arg_btf = reg->btf;
12368 meta->arg_btf_id = reg->btf_id;
12370 case KF_ARG_PTR_TO_CONST_STR:
12371 if (reg->type != PTR_TO_MAP_VALUE) {
12372 verbose(env, "arg#%d doesn't point to a const string\n", i);
12375 ret = check_reg_const_str(env, reg, regno);
12379 case KF_ARG_PTR_TO_WORKQUEUE:
12380 if (reg->type != PTR_TO_MAP_VALUE) {
12381 verbose(env, "arg#%d doesn't point to a map value\n", i);
12384 ret = process_wq_func(env, regno, meta);
12391 if (is_kfunc_release(meta) && !meta->release_regno) {
12392 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
12400 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
12401 struct bpf_insn *insn,
12402 struct bpf_kfunc_call_arg_meta *meta,
12403 const char **kfunc_name)
12405 const struct btf_type *func, *func_proto;
12406 u32 func_id, *kfunc_flags;
12407 const char *func_name;
12408 struct btf *desc_btf;
12411 *kfunc_name = NULL;
12416 desc_btf = find_kfunc_desc_btf(env, insn->off);
12417 if (IS_ERR(desc_btf))
12418 return PTR_ERR(desc_btf);
12420 func_id = insn->imm;
12421 func = btf_type_by_id(desc_btf, func_id);
12422 func_name = btf_name_by_offset(desc_btf, func->name_off);
12424 *kfunc_name = func_name;
12425 func_proto = btf_type_by_id(desc_btf, func->type);
12427 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
12428 if (!kfunc_flags) {
12432 memset(meta, 0, sizeof(*meta));
12433 meta->btf = desc_btf;
12434 meta->func_id = func_id;
12435 meta->kfunc_flags = *kfunc_flags;
12436 meta->func_proto = func_proto;
12437 meta->func_name = func_name;
12442 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
12444 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12447 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
12448 u32 i, nargs, ptr_type_id, release_ref_obj_id;
12449 struct bpf_reg_state *regs = cur_regs(env);
12450 const char *func_name, *ptr_type_name;
12451 const struct btf_type *t, *ptr_type;
12452 struct bpf_kfunc_call_arg_meta meta;
12453 struct bpf_insn_aux_data *insn_aux;
12454 int err, insn_idx = *insn_idx_p;
12455 const struct btf_param *args;
12456 const struct btf_type *ret_t;
12457 struct btf *desc_btf;
12459 /* skip for now, but return error when we find this in fixup_kfunc_call */
12463 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
12464 if (err == -EACCES && func_name)
12465 verbose(env, "calling kernel function %s is not allowed\n", func_name);
12468 desc_btf = meta.btf;
12469 insn_aux = &env->insn_aux_data[insn_idx];
12471 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
12473 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12474 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12478 sleepable = is_kfunc_sleepable(&meta);
12479 if (sleepable && !in_sleepable(env)) {
12480 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12484 /* Check the arguments */
12485 err = check_kfunc_args(env, &meta, insn_idx);
12489 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12490 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12491 set_rbtree_add_callback_state);
12493 verbose(env, "kfunc %s#%d failed callback verification\n",
12494 func_name, meta.func_id);
12499 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
12500 meta.r0_size = sizeof(u64);
12501 meta.r0_rdonly = false;
12504 if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
12505 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12506 set_timer_callback_state);
12508 verbose(env, "kfunc %s#%d failed callback verification\n",
12509 func_name, meta.func_id);
12514 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
12515 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
12517 preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
12518 preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
12520 if (env->cur_state->active_rcu_lock) {
12521 struct bpf_func_state *state;
12522 struct bpf_reg_state *reg;
12523 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
12525 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
12526 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
12531 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
12533 } else if (rcu_unlock) {
12534 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
12535 if (reg->type & MEM_RCU) {
12536 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
12537 reg->type |= PTR_UNTRUSTED;
12540 env->cur_state->active_rcu_lock = false;
12541 } else if (sleepable) {
12542 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
12545 } else if (rcu_lock) {
12546 env->cur_state->active_rcu_lock = true;
12547 } else if (rcu_unlock) {
12548 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
12552 if (env->cur_state->active_preempt_lock) {
12553 if (preempt_disable) {
12554 env->cur_state->active_preempt_lock++;
12555 } else if (preempt_enable) {
12556 env->cur_state->active_preempt_lock--;
12557 } else if (sleepable) {
12558 verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
12561 } else if (preempt_disable) {
12562 env->cur_state->active_preempt_lock++;
12563 } else if (preempt_enable) {
12564 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
12568 /* In case of release function, we get register number of refcounted
12569 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
12571 if (meta.release_regno) {
12572 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
12574 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12575 func_name, meta.func_id);
12580 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12581 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12582 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12583 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
12584 insn_aux->insert_off = regs[BPF_REG_2].off;
12585 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
12586 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
12588 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
12589 func_name, meta.func_id);
12593 err = release_reference(env, release_ref_obj_id);
12595 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12596 func_name, meta.func_id);
12601 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12602 if (!bpf_jit_supports_exceptions()) {
12603 verbose(env, "JIT does not support calling kfunc %s#%d\n",
12604 func_name, meta.func_id);
12607 env->seen_exception = true;
12609 /* In the case of the default callback, the cookie value passed
12610 * to bpf_throw becomes the return value of the program.
12612 if (!env->exception_callback_subprog) {
12613 err = check_return_code(env, BPF_REG_1, "R1");
12619 for (i = 0; i < CALLER_SAVED_REGS; i++)
12620 mark_reg_not_init(env, regs, caller_saved[i]);
12622 /* Check return type */
12623 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
12625 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
12626 /* Only exception is bpf_obj_new_impl */
12627 if (meta.btf != btf_vmlinux ||
12628 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
12629 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
12630 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
12631 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12636 if (btf_type_is_scalar(t)) {
12637 mark_reg_unknown(env, regs, BPF_REG_0);
12638 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12639 } else if (btf_type_is_ptr(t)) {
12640 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12642 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12643 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12644 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12645 struct btf_struct_meta *struct_meta;
12646 struct btf *ret_btf;
12649 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12652 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12653 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12657 ret_btf = env->prog->aux->btf;
12658 ret_btf_id = meta.arg_constant.value;
12660 /* This may be NULL due to user not supplying a BTF */
12662 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12666 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12667 if (!ret_t || !__btf_type_is_struct(ret_t)) {
12668 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12672 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12673 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
12674 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
12675 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
12679 if (!bpf_global_percpu_ma_set) {
12680 mutex_lock(&bpf_percpu_ma_lock);
12681 if (!bpf_global_percpu_ma_set) {
12682 /* Charge memory allocated with bpf_global_percpu_ma to
12683 * root memcg. The obj_cgroup for root memcg is NULL.
12685 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
12687 bpf_global_percpu_ma_set = true;
12689 mutex_unlock(&bpf_percpu_ma_lock);
12694 mutex_lock(&bpf_percpu_ma_lock);
12695 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
12696 mutex_unlock(&bpf_percpu_ma_lock);
12701 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12702 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12703 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12704 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12709 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12714 mark_reg_known_zero(env, regs, BPF_REG_0);
12715 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12716 regs[BPF_REG_0].btf = ret_btf;
12717 regs[BPF_REG_0].btf_id = ret_btf_id;
12718 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12719 regs[BPF_REG_0].type |= MEM_PERCPU;
12721 insn_aux->obj_new_size = ret_t->size;
12722 insn_aux->kptr_struct_meta = struct_meta;
12723 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12724 mark_reg_known_zero(env, regs, BPF_REG_0);
12725 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12726 regs[BPF_REG_0].btf = meta.arg_btf;
12727 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12729 insn_aux->kptr_struct_meta =
12730 btf_find_struct_meta(meta.arg_btf,
12732 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12733 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12734 struct btf_field *field = meta.arg_list_head.field;
12736 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12737 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12738 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12739 struct btf_field *field = meta.arg_rbtree_root.field;
12741 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12742 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12743 mark_reg_known_zero(env, regs, BPF_REG_0);
12744 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12745 regs[BPF_REG_0].btf = desc_btf;
12746 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12747 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12748 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12749 if (!ret_t || !btf_type_is_struct(ret_t)) {
12751 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12755 mark_reg_known_zero(env, regs, BPF_REG_0);
12756 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12757 regs[BPF_REG_0].btf = desc_btf;
12758 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12759 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12760 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12761 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12763 mark_reg_known_zero(env, regs, BPF_REG_0);
12765 if (!meta.arg_constant.found) {
12766 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12770 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12772 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12773 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12775 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12776 regs[BPF_REG_0].type |= MEM_RDONLY;
12778 /* this will set env->seen_direct_write to true */
12779 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12780 verbose(env, "the prog does not allow writes to packet data\n");
12785 if (!meta.initialized_dynptr.id) {
12786 verbose(env, "verifier internal error: no dynptr id\n");
12789 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12791 /* we don't need to set BPF_REG_0's ref obj id
12792 * because packet slices are not refcounted (see
12793 * dynptr_type_refcounted)
12796 verbose(env, "kernel function %s unhandled dynamic return type\n",
12800 } else if (btf_type_is_void(ptr_type)) {
12801 /* kfunc returning 'void *' is equivalent to returning scalar */
12802 mark_reg_unknown(env, regs, BPF_REG_0);
12803 } else if (!__btf_type_is_struct(ptr_type)) {
12804 if (!meta.r0_size) {
12807 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12809 meta.r0_rdonly = true;
12812 if (!meta.r0_size) {
12813 ptr_type_name = btf_name_by_offset(desc_btf,
12814 ptr_type->name_off);
12816 "kernel function %s returns pointer type %s %s is not supported\n",
12818 btf_type_str(ptr_type),
12823 mark_reg_known_zero(env, regs, BPF_REG_0);
12824 regs[BPF_REG_0].type = PTR_TO_MEM;
12825 regs[BPF_REG_0].mem_size = meta.r0_size;
12827 if (meta.r0_rdonly)
12828 regs[BPF_REG_0].type |= MEM_RDONLY;
12830 /* Ensures we don't access the memory after a release_reference() */
12831 if (meta.ref_obj_id)
12832 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12834 mark_reg_known_zero(env, regs, BPF_REG_0);
12835 regs[BPF_REG_0].btf = desc_btf;
12836 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12837 regs[BPF_REG_0].btf_id = ptr_type_id;
12839 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
12840 regs[BPF_REG_0].type |= PTR_UNTRUSTED;
12842 if (is_iter_next_kfunc(&meta)) {
12843 struct bpf_reg_state *cur_iter;
12845 cur_iter = get_iter_from_state(env->cur_state, &meta);
12847 if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
12848 regs[BPF_REG_0].type |= MEM_RCU;
12850 regs[BPF_REG_0].type |= PTR_TRUSTED;
12854 if (is_kfunc_ret_null(&meta)) {
12855 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12856 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12857 regs[BPF_REG_0].id = ++env->id_gen;
12859 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12860 if (is_kfunc_acquire(&meta)) {
12861 int id = acquire_reference_state(env, insn_idx);
12865 if (is_kfunc_ret_null(&meta))
12866 regs[BPF_REG_0].id = id;
12867 regs[BPF_REG_0].ref_obj_id = id;
12868 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12869 ref_set_non_owning(env, ®s[BPF_REG_0]);
12872 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
12873 regs[BPF_REG_0].id = ++env->id_gen;
12874 } else if (btf_type_is_void(t)) {
12875 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12876 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12877 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12878 insn_aux->kptr_struct_meta =
12879 btf_find_struct_meta(meta.arg_btf,
12885 nargs = btf_type_vlen(meta.func_proto);
12886 args = (const struct btf_param *)(meta.func_proto + 1);
12887 for (i = 0; i < nargs; i++) {
12890 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12891 if (btf_type_is_ptr(t))
12892 mark_btf_func_reg_size(env, regno, sizeof(void *));
12894 /* scalar. ensured by btf_check_kfunc_arg_match() */
12895 mark_btf_func_reg_size(env, regno, t->size);
12898 if (is_iter_next_kfunc(&meta)) {
12899 err = process_iter_next_call(env, insn_idx, &meta);
12907 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12908 const struct bpf_reg_state *reg,
12909 enum bpf_reg_type type)
12911 bool known = tnum_is_const(reg->var_off);
12912 s64 val = reg->var_off.value;
12913 s64 smin = reg->smin_value;
12915 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12916 verbose(env, "math between %s pointer and %lld is not allowed\n",
12917 reg_type_str(env, type), val);
12921 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12922 verbose(env, "%s pointer offset %d is not allowed\n",
12923 reg_type_str(env, type), reg->off);
12927 if (smin == S64_MIN) {
12928 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12929 reg_type_str(env, type));
12933 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12934 verbose(env, "value %lld makes %s pointer be out of bounds\n",
12935 smin, reg_type_str(env, type));
12943 REASON_BOUNDS = -1,
12950 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12951 u32 *alu_limit, bool mask_to_left)
12953 u32 max = 0, ptr_limit = 0;
12955 switch (ptr_reg->type) {
12957 /* Offset 0 is out-of-bounds, but acceptable start for the
12958 * left direction, see BPF_REG_FP. Also, unknown scalar
12959 * offset where we would need to deal with min/max bounds is
12960 * currently prohibited for unprivileged.
12962 max = MAX_BPF_STACK + mask_to_left;
12963 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12965 case PTR_TO_MAP_VALUE:
12966 max = ptr_reg->map_ptr->value_size;
12967 ptr_limit = (mask_to_left ?
12968 ptr_reg->smin_value :
12969 ptr_reg->umax_value) + ptr_reg->off;
12972 return REASON_TYPE;
12975 if (ptr_limit >= max)
12976 return REASON_LIMIT;
12977 *alu_limit = ptr_limit;
12981 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12982 const struct bpf_insn *insn)
12984 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12987 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12988 u32 alu_state, u32 alu_limit)
12990 /* If we arrived here from different branches with different
12991 * state or limits to sanitize, then this won't work.
12993 if (aux->alu_state &&
12994 (aux->alu_state != alu_state ||
12995 aux->alu_limit != alu_limit))
12996 return REASON_PATHS;
12998 /* Corresponding fixup done in do_misc_fixups(). */
12999 aux->alu_state = alu_state;
13000 aux->alu_limit = alu_limit;
13004 static int sanitize_val_alu(struct bpf_verifier_env *env,
13005 struct bpf_insn *insn)
13007 struct bpf_insn_aux_data *aux = cur_aux(env);
13009 if (can_skip_alu_sanitation(env, insn))
13012 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
13015 static bool sanitize_needed(u8 opcode)
13017 return opcode == BPF_ADD || opcode == BPF_SUB;
13020 struct bpf_sanitize_info {
13021 struct bpf_insn_aux_data aux;
13025 static struct bpf_verifier_state *
13026 sanitize_speculative_path(struct bpf_verifier_env *env,
13027 const struct bpf_insn *insn,
13028 u32 next_idx, u32 curr_idx)
13030 struct bpf_verifier_state *branch;
13031 struct bpf_reg_state *regs;
13033 branch = push_stack(env, next_idx, curr_idx, true);
13034 if (branch && insn) {
13035 regs = branch->frame[branch->curframe]->regs;
13036 if (BPF_SRC(insn->code) == BPF_K) {
13037 mark_reg_unknown(env, regs, insn->dst_reg);
13038 } else if (BPF_SRC(insn->code) == BPF_X) {
13039 mark_reg_unknown(env, regs, insn->dst_reg);
13040 mark_reg_unknown(env, regs, insn->src_reg);
13046 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
13047 struct bpf_insn *insn,
13048 const struct bpf_reg_state *ptr_reg,
13049 const struct bpf_reg_state *off_reg,
13050 struct bpf_reg_state *dst_reg,
13051 struct bpf_sanitize_info *info,
13052 const bool commit_window)
13054 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
13055 struct bpf_verifier_state *vstate = env->cur_state;
13056 bool off_is_imm = tnum_is_const(off_reg->var_off);
13057 bool off_is_neg = off_reg->smin_value < 0;
13058 bool ptr_is_dst_reg = ptr_reg == dst_reg;
13059 u8 opcode = BPF_OP(insn->code);
13060 u32 alu_state, alu_limit;
13061 struct bpf_reg_state tmp;
13065 if (can_skip_alu_sanitation(env, insn))
13068 /* We already marked aux for masking from non-speculative
13069 * paths, thus we got here in the first place. We only care
13070 * to explore bad access from here.
13072 if (vstate->speculative)
13075 if (!commit_window) {
13076 if (!tnum_is_const(off_reg->var_off) &&
13077 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
13078 return REASON_BOUNDS;
13080 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
13081 (opcode == BPF_SUB && !off_is_neg);
13084 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
13088 if (commit_window) {
13089 /* In commit phase we narrow the masking window based on
13090 * the observed pointer move after the simulated operation.
13092 alu_state = info->aux.alu_state;
13093 alu_limit = abs(info->aux.alu_limit - alu_limit);
13095 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
13096 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
13097 alu_state |= ptr_is_dst_reg ?
13098 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
13100 /* Limit pruning on unknown scalars to enable deep search for
13101 * potential masking differences from other program paths.
13104 env->explore_alu_limits = true;
13107 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
13111 /* If we're in commit phase, we're done here given we already
13112 * pushed the truncated dst_reg into the speculative verification
13115 * Also, when register is a known constant, we rewrite register-based
13116 * operation to immediate-based, and thus do not need masking (and as
13117 * a consequence, do not need to simulate the zero-truncation either).
13119 if (commit_window || off_is_imm)
13122 /* Simulate and find potential out-of-bounds access under
13123 * speculative execution from truncation as a result of
13124 * masking when off was not within expected range. If off
13125 * sits in dst, then we temporarily need to move ptr there
13126 * to simulate dst (== 0) +/-= ptr. Needed, for example,
13127 * for cases where we use K-based arithmetic in one direction
13128 * and truncated reg-based in the other in order to explore
13131 if (!ptr_is_dst_reg) {
13133 copy_register_state(dst_reg, ptr_reg);
13135 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
13137 if (!ptr_is_dst_reg && ret)
13139 return !ret ? REASON_STACK : 0;
13142 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
13144 struct bpf_verifier_state *vstate = env->cur_state;
13146 /* If we simulate paths under speculation, we don't update the
13147 * insn as 'seen' such that when we verify unreachable paths in
13148 * the non-speculative domain, sanitize_dead_code() can still
13149 * rewrite/sanitize them.
13151 if (!vstate->speculative)
13152 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
13155 static int sanitize_err(struct bpf_verifier_env *env,
13156 const struct bpf_insn *insn, int reason,
13157 const struct bpf_reg_state *off_reg,
13158 const struct bpf_reg_state *dst_reg)
13160 static const char *err = "pointer arithmetic with it prohibited for !root";
13161 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
13162 u32 dst = insn->dst_reg, src = insn->src_reg;
13165 case REASON_BOUNDS:
13166 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
13167 off_reg == dst_reg ? dst : src, err);
13170 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
13171 off_reg == dst_reg ? src : dst, err);
13174 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
13178 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
13182 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
13186 verbose(env, "verifier internal error: unknown reason (%d)\n",
13194 /* check that stack access falls within stack limits and that 'reg' doesn't
13195 * have a variable offset.
13197 * Variable offset is prohibited for unprivileged mode for simplicity since it
13198 * requires corresponding support in Spectre masking for stack ALU. See also
13199 * retrieve_ptr_limit().
13202 * 'off' includes 'reg->off'.
13204 static int check_stack_access_for_ptr_arithmetic(
13205 struct bpf_verifier_env *env,
13207 const struct bpf_reg_state *reg,
13210 if (!tnum_is_const(reg->var_off)) {
13213 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
13214 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
13215 regno, tn_buf, off);
13219 if (off >= 0 || off < -MAX_BPF_STACK) {
13220 verbose(env, "R%d stack pointer arithmetic goes out of range, "
13221 "prohibited for !root; off=%d\n", regno, off);
13228 static int sanitize_check_bounds(struct bpf_verifier_env *env,
13229 const struct bpf_insn *insn,
13230 const struct bpf_reg_state *dst_reg)
13232 u32 dst = insn->dst_reg;
13234 /* For unprivileged we require that resulting offset must be in bounds
13235 * in order to be able to sanitize access later on.
13237 if (env->bypass_spec_v1)
13240 switch (dst_reg->type) {
13242 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
13243 dst_reg->off + dst_reg->var_off.value))
13246 case PTR_TO_MAP_VALUE:
13247 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
13248 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
13249 "prohibited for !root\n", dst);
13260 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
13261 * Caller should also handle BPF_MOV case separately.
13262 * If we return -EACCES, caller may want to try again treating pointer as a
13263 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
13265 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
13266 struct bpf_insn *insn,
13267 const struct bpf_reg_state *ptr_reg,
13268 const struct bpf_reg_state *off_reg)
13270 struct bpf_verifier_state *vstate = env->cur_state;
13271 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13272 struct bpf_reg_state *regs = state->regs, *dst_reg;
13273 bool known = tnum_is_const(off_reg->var_off);
13274 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
13275 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
13276 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
13277 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
13278 struct bpf_sanitize_info info = {};
13279 u8 opcode = BPF_OP(insn->code);
13280 u32 dst = insn->dst_reg;
13283 dst_reg = ®s[dst];
13285 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
13286 smin_val > smax_val || umin_val > umax_val) {
13287 /* Taint dst register if offset had invalid bounds derived from
13288 * e.g. dead branches.
13290 __mark_reg_unknown(env, dst_reg);
13294 if (BPF_CLASS(insn->code) != BPF_ALU64) {
13295 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
13296 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13297 __mark_reg_unknown(env, dst_reg);
13302 "R%d 32-bit pointer arithmetic prohibited\n",
13307 if (ptr_reg->type & PTR_MAYBE_NULL) {
13308 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
13309 dst, reg_type_str(env, ptr_reg->type));
13313 switch (base_type(ptr_reg->type)) {
13315 case PTR_TO_MAP_VALUE:
13316 case PTR_TO_MAP_KEY:
13318 case PTR_TO_PACKET_META:
13319 case PTR_TO_PACKET:
13320 case PTR_TO_TP_BUFFER:
13321 case PTR_TO_BTF_ID:
13325 case CONST_PTR_TO_DYNPTR:
13327 case PTR_TO_FLOW_KEYS:
13331 case CONST_PTR_TO_MAP:
13332 /* smin_val represents the known value */
13333 if (known && smin_val == 0 && opcode == BPF_ADD)
13337 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
13338 dst, reg_type_str(env, ptr_reg->type));
13342 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
13343 * The id may be overwritten later if we create a new variable offset.
13345 dst_reg->type = ptr_reg->type;
13346 dst_reg->id = ptr_reg->id;
13348 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
13349 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
13352 /* pointer types do not carry 32-bit bounds at the moment. */
13353 __mark_reg32_unbounded(dst_reg);
13355 if (sanitize_needed(opcode)) {
13356 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
13359 return sanitize_err(env, insn, ret, off_reg, dst_reg);
13364 /* We can take a fixed offset as long as it doesn't overflow
13365 * the s32 'off' field
13367 if (known && (ptr_reg->off + smin_val ==
13368 (s64)(s32)(ptr_reg->off + smin_val))) {
13369 /* pointer += K. Accumulate it into fixed offset */
13370 dst_reg->smin_value = smin_ptr;
13371 dst_reg->smax_value = smax_ptr;
13372 dst_reg->umin_value = umin_ptr;
13373 dst_reg->umax_value = umax_ptr;
13374 dst_reg->var_off = ptr_reg->var_off;
13375 dst_reg->off = ptr_reg->off + smin_val;
13376 dst_reg->raw = ptr_reg->raw;
13379 /* A new variable offset is created. Note that off_reg->off
13380 * == 0, since it's a scalar.
13381 * dst_reg gets the pointer type and since some positive
13382 * integer value was added to the pointer, give it a new 'id'
13383 * if it's a PTR_TO_PACKET.
13384 * this creates a new 'base' pointer, off_reg (variable) gets
13385 * added into the variable offset, and we copy the fixed offset
13388 if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
13389 check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
13390 dst_reg->smin_value = S64_MIN;
13391 dst_reg->smax_value = S64_MAX;
13393 if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
13394 check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
13395 dst_reg->umin_value = 0;
13396 dst_reg->umax_value = U64_MAX;
13398 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
13399 dst_reg->off = ptr_reg->off;
13400 dst_reg->raw = ptr_reg->raw;
13401 if (reg_is_pkt_pointer(ptr_reg)) {
13402 dst_reg->id = ++env->id_gen;
13403 /* something was added to pkt_ptr, set range to zero */
13404 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13408 if (dst_reg == off_reg) {
13409 /* scalar -= pointer. Creates an unknown scalar */
13410 verbose(env, "R%d tried to subtract pointer from scalar\n",
13414 /* We don't allow subtraction from FP, because (according to
13415 * test_verifier.c test "invalid fp arithmetic", JITs might not
13416 * be able to deal with it.
13418 if (ptr_reg->type == PTR_TO_STACK) {
13419 verbose(env, "R%d subtraction from stack pointer prohibited\n",
13423 if (known && (ptr_reg->off - smin_val ==
13424 (s64)(s32)(ptr_reg->off - smin_val))) {
13425 /* pointer -= K. Subtract it from fixed offset */
13426 dst_reg->smin_value = smin_ptr;
13427 dst_reg->smax_value = smax_ptr;
13428 dst_reg->umin_value = umin_ptr;
13429 dst_reg->umax_value = umax_ptr;
13430 dst_reg->var_off = ptr_reg->var_off;
13431 dst_reg->id = ptr_reg->id;
13432 dst_reg->off = ptr_reg->off - smin_val;
13433 dst_reg->raw = ptr_reg->raw;
13436 /* A new variable offset is created. If the subtrahend is known
13437 * nonnegative, then any reg->range we had before is still good.
13439 if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
13440 check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
13441 /* Overflow possible, we know nothing */
13442 dst_reg->smin_value = S64_MIN;
13443 dst_reg->smax_value = S64_MAX;
13445 if (umin_ptr < umax_val) {
13446 /* Overflow possible, we know nothing */
13447 dst_reg->umin_value = 0;
13448 dst_reg->umax_value = U64_MAX;
13450 /* Cannot overflow (as long as bounds are consistent) */
13451 dst_reg->umin_value = umin_ptr - umax_val;
13452 dst_reg->umax_value = umax_ptr - umin_val;
13454 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
13455 dst_reg->off = ptr_reg->off;
13456 dst_reg->raw = ptr_reg->raw;
13457 if (reg_is_pkt_pointer(ptr_reg)) {
13458 dst_reg->id = ++env->id_gen;
13459 /* something was added to pkt_ptr, set range to zero */
13461 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13467 /* bitwise ops on pointers are troublesome, prohibit. */
13468 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
13469 dst, bpf_alu_string[opcode >> 4]);
13472 /* other operators (e.g. MUL,LSH) produce non-pointer results */
13473 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
13474 dst, bpf_alu_string[opcode >> 4]);
13478 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
13480 reg_bounds_sync(dst_reg);
13481 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
13483 if (sanitize_needed(opcode)) {
13484 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13487 return sanitize_err(env, insn, ret, off_reg, dst_reg);
13493 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13494 struct bpf_reg_state *src_reg)
13496 s32 *dst_smin = &dst_reg->s32_min_value;
13497 s32 *dst_smax = &dst_reg->s32_max_value;
13498 u32 *dst_umin = &dst_reg->u32_min_value;
13499 u32 *dst_umax = &dst_reg->u32_max_value;
13501 if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
13502 check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
13503 *dst_smin = S32_MIN;
13504 *dst_smax = S32_MAX;
13506 if (check_add_overflow(*dst_umin, src_reg->u32_min_value, dst_umin) ||
13507 check_add_overflow(*dst_umax, src_reg->u32_max_value, dst_umax)) {
13509 *dst_umax = U32_MAX;
13513 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13514 struct bpf_reg_state *src_reg)
13516 s64 *dst_smin = &dst_reg->smin_value;
13517 s64 *dst_smax = &dst_reg->smax_value;
13518 u64 *dst_umin = &dst_reg->umin_value;
13519 u64 *dst_umax = &dst_reg->umax_value;
13521 if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
13522 check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
13523 *dst_smin = S64_MIN;
13524 *dst_smax = S64_MAX;
13526 if (check_add_overflow(*dst_umin, src_reg->umin_value, dst_umin) ||
13527 check_add_overflow(*dst_umax, src_reg->umax_value, dst_umax)) {
13529 *dst_umax = U64_MAX;
13533 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13534 struct bpf_reg_state *src_reg)
13536 s32 *dst_smin = &dst_reg->s32_min_value;
13537 s32 *dst_smax = &dst_reg->s32_max_value;
13538 u32 umin_val = src_reg->u32_min_value;
13539 u32 umax_val = src_reg->u32_max_value;
13541 if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
13542 check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
13543 /* Overflow possible, we know nothing */
13544 *dst_smin = S32_MIN;
13545 *dst_smax = S32_MAX;
13547 if (dst_reg->u32_min_value < umax_val) {
13548 /* Overflow possible, we know nothing */
13549 dst_reg->u32_min_value = 0;
13550 dst_reg->u32_max_value = U32_MAX;
13552 /* Cannot overflow (as long as bounds are consistent) */
13553 dst_reg->u32_min_value -= umax_val;
13554 dst_reg->u32_max_value -= umin_val;
13558 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13559 struct bpf_reg_state *src_reg)
13561 s64 *dst_smin = &dst_reg->smin_value;
13562 s64 *dst_smax = &dst_reg->smax_value;
13563 u64 umin_val = src_reg->umin_value;
13564 u64 umax_val = src_reg->umax_value;
13566 if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
13567 check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
13568 /* Overflow possible, we know nothing */
13569 *dst_smin = S64_MIN;
13570 *dst_smax = S64_MAX;
13572 if (dst_reg->umin_value < umax_val) {
13573 /* Overflow possible, we know nothing */
13574 dst_reg->umin_value = 0;
13575 dst_reg->umax_value = U64_MAX;
13577 /* Cannot overflow (as long as bounds are consistent) */
13578 dst_reg->umin_value -= umax_val;
13579 dst_reg->umax_value -= umin_val;
13583 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13584 struct bpf_reg_state *src_reg)
13586 s32 smin_val = src_reg->s32_min_value;
13587 u32 umin_val = src_reg->u32_min_value;
13588 u32 umax_val = src_reg->u32_max_value;
13590 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13591 /* Ain't nobody got time to multiply that sign */
13592 __mark_reg32_unbounded(dst_reg);
13595 /* Both values are positive, so we can work with unsigned and
13596 * copy the result to signed (unless it exceeds S32_MAX).
13598 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13599 /* Potential overflow, we know nothing */
13600 __mark_reg32_unbounded(dst_reg);
13603 dst_reg->u32_min_value *= umin_val;
13604 dst_reg->u32_max_value *= umax_val;
13605 if (dst_reg->u32_max_value > S32_MAX) {
13606 /* Overflow possible, we know nothing */
13607 dst_reg->s32_min_value = S32_MIN;
13608 dst_reg->s32_max_value = S32_MAX;
13610 dst_reg->s32_min_value = dst_reg->u32_min_value;
13611 dst_reg->s32_max_value = dst_reg->u32_max_value;
13615 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13616 struct bpf_reg_state *src_reg)
13618 s64 smin_val = src_reg->smin_value;
13619 u64 umin_val = src_reg->umin_value;
13620 u64 umax_val = src_reg->umax_value;
13622 if (smin_val < 0 || dst_reg->smin_value < 0) {
13623 /* Ain't nobody got time to multiply that sign */
13624 __mark_reg64_unbounded(dst_reg);
13627 /* Both values are positive, so we can work with unsigned and
13628 * copy the result to signed (unless it exceeds S64_MAX).
13630 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13631 /* Potential overflow, we know nothing */
13632 __mark_reg64_unbounded(dst_reg);
13635 dst_reg->umin_value *= umin_val;
13636 dst_reg->umax_value *= umax_val;
13637 if (dst_reg->umax_value > S64_MAX) {
13638 /* Overflow possible, we know nothing */
13639 dst_reg->smin_value = S64_MIN;
13640 dst_reg->smax_value = S64_MAX;
13642 dst_reg->smin_value = dst_reg->umin_value;
13643 dst_reg->smax_value = dst_reg->umax_value;
13647 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13648 struct bpf_reg_state *src_reg)
13650 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13651 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13652 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13653 u32 umax_val = src_reg->u32_max_value;
13655 if (src_known && dst_known) {
13656 __mark_reg32_known(dst_reg, var32_off.value);
13660 /* We get our minimum from the var_off, since that's inherently
13661 * bitwise. Our maximum is the minimum of the operands' maxima.
13663 dst_reg->u32_min_value = var32_off.value;
13664 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13666 /* Safe to set s32 bounds by casting u32 result into s32 when u32
13667 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13669 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13670 dst_reg->s32_min_value = dst_reg->u32_min_value;
13671 dst_reg->s32_max_value = dst_reg->u32_max_value;
13673 dst_reg->s32_min_value = S32_MIN;
13674 dst_reg->s32_max_value = S32_MAX;
13678 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13679 struct bpf_reg_state *src_reg)
13681 bool src_known = tnum_is_const(src_reg->var_off);
13682 bool dst_known = tnum_is_const(dst_reg->var_off);
13683 u64 umax_val = src_reg->umax_value;
13685 if (src_known && dst_known) {
13686 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13690 /* We get our minimum from the var_off, since that's inherently
13691 * bitwise. Our maximum is the minimum of the operands' maxima.
13693 dst_reg->umin_value = dst_reg->var_off.value;
13694 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13696 /* Safe to set s64 bounds by casting u64 result into s64 when u64
13697 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
13699 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
13700 dst_reg->smin_value = dst_reg->umin_value;
13701 dst_reg->smax_value = dst_reg->umax_value;
13703 dst_reg->smin_value = S64_MIN;
13704 dst_reg->smax_value = S64_MAX;
13706 /* We may learn something more from the var_off */
13707 __update_reg_bounds(dst_reg);
13710 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13711 struct bpf_reg_state *src_reg)
13713 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13714 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13715 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13716 u32 umin_val = src_reg->u32_min_value;
13718 if (src_known && dst_known) {
13719 __mark_reg32_known(dst_reg, var32_off.value);
13723 /* We get our maximum from the var_off, and our minimum is the
13724 * maximum of the operands' minima
13726 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13727 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13729 /* Safe to set s32 bounds by casting u32 result into s32 when u32
13730 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13732 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13733 dst_reg->s32_min_value = dst_reg->u32_min_value;
13734 dst_reg->s32_max_value = dst_reg->u32_max_value;
13736 dst_reg->s32_min_value = S32_MIN;
13737 dst_reg->s32_max_value = S32_MAX;
13741 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13742 struct bpf_reg_state *src_reg)
13744 bool src_known = tnum_is_const(src_reg->var_off);
13745 bool dst_known = tnum_is_const(dst_reg->var_off);
13746 u64 umin_val = src_reg->umin_value;
13748 if (src_known && dst_known) {
13749 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13753 /* We get our maximum from the var_off, and our minimum is the
13754 * maximum of the operands' minima
13756 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13757 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13759 /* Safe to set s64 bounds by casting u64 result into s64 when u64
13760 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
13762 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
13763 dst_reg->smin_value = dst_reg->umin_value;
13764 dst_reg->smax_value = dst_reg->umax_value;
13766 dst_reg->smin_value = S64_MIN;
13767 dst_reg->smax_value = S64_MAX;
13769 /* We may learn something more from the var_off */
13770 __update_reg_bounds(dst_reg);
13773 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13774 struct bpf_reg_state *src_reg)
13776 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13777 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13778 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13780 if (src_known && dst_known) {
13781 __mark_reg32_known(dst_reg, var32_off.value);
13785 /* We get both minimum and maximum from the var32_off. */
13786 dst_reg->u32_min_value = var32_off.value;
13787 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13789 /* Safe to set s32 bounds by casting u32 result into s32 when u32
13790 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13792 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13793 dst_reg->s32_min_value = dst_reg->u32_min_value;
13794 dst_reg->s32_max_value = dst_reg->u32_max_value;
13796 dst_reg->s32_min_value = S32_MIN;
13797 dst_reg->s32_max_value = S32_MAX;
13801 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13802 struct bpf_reg_state *src_reg)
13804 bool src_known = tnum_is_const(src_reg->var_off);
13805 bool dst_known = tnum_is_const(dst_reg->var_off);
13807 if (src_known && dst_known) {
13808 /* dst_reg->var_off.value has been updated earlier */
13809 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13813 /* We get both minimum and maximum from the var_off. */
13814 dst_reg->umin_value = dst_reg->var_off.value;
13815 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13817 /* Safe to set s64 bounds by casting u64 result into s64 when u64
13818 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
13820 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
13821 dst_reg->smin_value = dst_reg->umin_value;
13822 dst_reg->smax_value = dst_reg->umax_value;
13824 dst_reg->smin_value = S64_MIN;
13825 dst_reg->smax_value = S64_MAX;
13828 __update_reg_bounds(dst_reg);
13831 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13832 u64 umin_val, u64 umax_val)
13834 /* We lose all sign bit information (except what we can pick
13837 dst_reg->s32_min_value = S32_MIN;
13838 dst_reg->s32_max_value = S32_MAX;
13839 /* If we might shift our top bit out, then we know nothing */
13840 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13841 dst_reg->u32_min_value = 0;
13842 dst_reg->u32_max_value = U32_MAX;
13844 dst_reg->u32_min_value <<= umin_val;
13845 dst_reg->u32_max_value <<= umax_val;
13849 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13850 struct bpf_reg_state *src_reg)
13852 u32 umax_val = src_reg->u32_max_value;
13853 u32 umin_val = src_reg->u32_min_value;
13854 /* u32 alu operation will zext upper bits */
13855 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13857 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13858 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13859 /* Not required but being careful mark reg64 bounds as unknown so
13860 * that we are forced to pick them up from tnum and zext later and
13861 * if some path skips this step we are still safe.
13863 __mark_reg64_unbounded(dst_reg);
13864 __update_reg32_bounds(dst_reg);
13867 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13868 u64 umin_val, u64 umax_val)
13870 /* Special case <<32 because it is a common compiler pattern to sign
13871 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13872 * positive we know this shift will also be positive so we can track
13873 * bounds correctly. Otherwise we lose all sign bit information except
13874 * what we can pick up from var_off. Perhaps we can generalize this
13875 * later to shifts of any length.
13877 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13878 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13880 dst_reg->smax_value = S64_MAX;
13882 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13883 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13885 dst_reg->smin_value = S64_MIN;
13887 /* If we might shift our top bit out, then we know nothing */
13888 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13889 dst_reg->umin_value = 0;
13890 dst_reg->umax_value = U64_MAX;
13892 dst_reg->umin_value <<= umin_val;
13893 dst_reg->umax_value <<= umax_val;
13897 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13898 struct bpf_reg_state *src_reg)
13900 u64 umax_val = src_reg->umax_value;
13901 u64 umin_val = src_reg->umin_value;
13903 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
13904 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13905 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13907 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13908 /* We may learn something more from the var_off */
13909 __update_reg_bounds(dst_reg);
13912 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13913 struct bpf_reg_state *src_reg)
13915 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13916 u32 umax_val = src_reg->u32_max_value;
13917 u32 umin_val = src_reg->u32_min_value;
13919 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13920 * be negative, then either:
13921 * 1) src_reg might be zero, so the sign bit of the result is
13922 * unknown, so we lose our signed bounds
13923 * 2) it's known negative, thus the unsigned bounds capture the
13925 * 3) the signed bounds cross zero, so they tell us nothing
13927 * If the value in dst_reg is known nonnegative, then again the
13928 * unsigned bounds capture the signed bounds.
13929 * Thus, in all cases it suffices to blow away our signed bounds
13930 * and rely on inferring new ones from the unsigned bounds and
13931 * var_off of the result.
13933 dst_reg->s32_min_value = S32_MIN;
13934 dst_reg->s32_max_value = S32_MAX;
13936 dst_reg->var_off = tnum_rshift(subreg, umin_val);
13937 dst_reg->u32_min_value >>= umax_val;
13938 dst_reg->u32_max_value >>= umin_val;
13940 __mark_reg64_unbounded(dst_reg);
13941 __update_reg32_bounds(dst_reg);
13944 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13945 struct bpf_reg_state *src_reg)
13947 u64 umax_val = src_reg->umax_value;
13948 u64 umin_val = src_reg->umin_value;
13950 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13951 * be negative, then either:
13952 * 1) src_reg might be zero, so the sign bit of the result is
13953 * unknown, so we lose our signed bounds
13954 * 2) it's known negative, thus the unsigned bounds capture the
13956 * 3) the signed bounds cross zero, so they tell us nothing
13958 * If the value in dst_reg is known nonnegative, then again the
13959 * unsigned bounds capture the signed bounds.
13960 * Thus, in all cases it suffices to blow away our signed bounds
13961 * and rely on inferring new ones from the unsigned bounds and
13962 * var_off of the result.
13964 dst_reg->smin_value = S64_MIN;
13965 dst_reg->smax_value = S64_MAX;
13966 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13967 dst_reg->umin_value >>= umax_val;
13968 dst_reg->umax_value >>= umin_val;
13970 /* Its not easy to operate on alu32 bounds here because it depends
13971 * on bits being shifted in. Take easy way out and mark unbounded
13972 * so we can recalculate later from tnum.
13974 __mark_reg32_unbounded(dst_reg);
13975 __update_reg_bounds(dst_reg);
13978 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13979 struct bpf_reg_state *src_reg)
13981 u64 umin_val = src_reg->u32_min_value;
13983 /* Upon reaching here, src_known is true and
13984 * umax_val is equal to umin_val.
13986 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13987 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13989 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13991 /* blow away the dst_reg umin_value/umax_value and rely on
13992 * dst_reg var_off to refine the result.
13994 dst_reg->u32_min_value = 0;
13995 dst_reg->u32_max_value = U32_MAX;
13997 __mark_reg64_unbounded(dst_reg);
13998 __update_reg32_bounds(dst_reg);
14001 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
14002 struct bpf_reg_state *src_reg)
14004 u64 umin_val = src_reg->umin_value;
14006 /* Upon reaching here, src_known is true and umax_val is equal
14009 dst_reg->smin_value >>= umin_val;
14010 dst_reg->smax_value >>= umin_val;
14012 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
14014 /* blow away the dst_reg umin_value/umax_value and rely on
14015 * dst_reg var_off to refine the result.
14017 dst_reg->umin_value = 0;
14018 dst_reg->umax_value = U64_MAX;
14020 /* Its not easy to operate on alu32 bounds here because it depends
14021 * on bits being shifted in from upper 32-bits. Take easy way out
14022 * and mark unbounded so we can recalculate later from tnum.
14024 __mark_reg32_unbounded(dst_reg);
14025 __update_reg_bounds(dst_reg);
14028 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
14029 const struct bpf_reg_state *src_reg)
14031 bool src_is_const = false;
14032 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
14034 if (insn_bitness == 32) {
14035 if (tnum_subreg_is_const(src_reg->var_off)
14036 && src_reg->s32_min_value == src_reg->s32_max_value
14037 && src_reg->u32_min_value == src_reg->u32_max_value)
14038 src_is_const = true;
14040 if (tnum_is_const(src_reg->var_off)
14041 && src_reg->smin_value == src_reg->smax_value
14042 && src_reg->umin_value == src_reg->umax_value)
14043 src_is_const = true;
14046 switch (BPF_OP(insn->code)) {
14055 /* Shift operators range is only computable if shift dimension operand
14056 * is a constant. Shifts greater than 31 or 63 are undefined. This
14057 * includes shifts by a negative number.
14062 return (src_is_const && src_reg->umax_value < insn_bitness);
14068 /* WARNING: This function does calculations on 64-bit values, but the actual
14069 * execution may occur on 32-bit values. Therefore, things like bitshifts
14070 * need extra checks in the 32-bit case.
14072 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
14073 struct bpf_insn *insn,
14074 struct bpf_reg_state *dst_reg,
14075 struct bpf_reg_state src_reg)
14077 u8 opcode = BPF_OP(insn->code);
14078 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
14081 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
14082 __mark_reg_unknown(env, dst_reg);
14086 if (sanitize_needed(opcode)) {
14087 ret = sanitize_val_alu(env, insn);
14089 return sanitize_err(env, insn, ret, NULL, NULL);
14092 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
14093 * There are two classes of instructions: The first class we track both
14094 * alu32 and alu64 sign/unsigned bounds independently this provides the
14095 * greatest amount of precision when alu operations are mixed with jmp32
14096 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
14097 * and BPF_OR. This is possible because these ops have fairly easy to
14098 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
14099 * See alu32 verifier tests for examples. The second class of
14100 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
14101 * with regards to tracking sign/unsigned bounds because the bits may
14102 * cross subreg boundaries in the alu64 case. When this happens we mark
14103 * the reg unbounded in the subreg bound space and use the resulting
14104 * tnum to calculate an approximation of the sign/unsigned bounds.
14108 scalar32_min_max_add(dst_reg, &src_reg);
14109 scalar_min_max_add(dst_reg, &src_reg);
14110 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
14113 scalar32_min_max_sub(dst_reg, &src_reg);
14114 scalar_min_max_sub(dst_reg, &src_reg);
14115 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
14118 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
14119 scalar32_min_max_mul(dst_reg, &src_reg);
14120 scalar_min_max_mul(dst_reg, &src_reg);
14123 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
14124 scalar32_min_max_and(dst_reg, &src_reg);
14125 scalar_min_max_and(dst_reg, &src_reg);
14128 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
14129 scalar32_min_max_or(dst_reg, &src_reg);
14130 scalar_min_max_or(dst_reg, &src_reg);
14133 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
14134 scalar32_min_max_xor(dst_reg, &src_reg);
14135 scalar_min_max_xor(dst_reg, &src_reg);
14139 scalar32_min_max_lsh(dst_reg, &src_reg);
14141 scalar_min_max_lsh(dst_reg, &src_reg);
14145 scalar32_min_max_rsh(dst_reg, &src_reg);
14147 scalar_min_max_rsh(dst_reg, &src_reg);
14151 scalar32_min_max_arsh(dst_reg, &src_reg);
14153 scalar_min_max_arsh(dst_reg, &src_reg);
14159 /* ALU32 ops are zero extended into 64bit register */
14161 zext_32_to_64(dst_reg);
14162 reg_bounds_sync(dst_reg);
14166 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
14169 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
14170 struct bpf_insn *insn)
14172 struct bpf_verifier_state *vstate = env->cur_state;
14173 struct bpf_func_state *state = vstate->frame[vstate->curframe];
14174 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
14175 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
14176 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
14177 u8 opcode = BPF_OP(insn->code);
14180 dst_reg = ®s[insn->dst_reg];
14183 if (dst_reg->type == PTR_TO_ARENA) {
14184 struct bpf_insn_aux_data *aux = cur_aux(env);
14186 if (BPF_CLASS(insn->code) == BPF_ALU64)
14188 * 32-bit operations zero upper bits automatically.
14189 * 64-bit operations need to be converted to 32.
14191 aux->needs_zext = true;
14193 /* Any arithmetic operations are allowed on arena pointers */
14197 if (dst_reg->type != SCALAR_VALUE)
14200 if (BPF_SRC(insn->code) == BPF_X) {
14201 src_reg = ®s[insn->src_reg];
14202 if (src_reg->type != SCALAR_VALUE) {
14203 if (dst_reg->type != SCALAR_VALUE) {
14204 /* Combining two pointers by any ALU op yields
14205 * an arbitrary scalar. Disallow all math except
14206 * pointer subtraction
14208 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14209 mark_reg_unknown(env, regs, insn->dst_reg);
14212 verbose(env, "R%d pointer %s pointer prohibited\n",
14214 bpf_alu_string[opcode >> 4]);
14217 /* scalar += pointer
14218 * This is legal, but we have to reverse our
14219 * src/dest handling in computing the range
14221 err = mark_chain_precision(env, insn->dst_reg);
14224 return adjust_ptr_min_max_vals(env, insn,
14227 } else if (ptr_reg) {
14228 /* pointer += scalar */
14229 err = mark_chain_precision(env, insn->src_reg);
14232 return adjust_ptr_min_max_vals(env, insn,
14234 } else if (dst_reg->precise) {
14235 /* if dst_reg is precise, src_reg should be precise as well */
14236 err = mark_chain_precision(env, insn->src_reg);
14241 /* Pretend the src is a reg with a known value, since we only
14242 * need to be able to read from this state.
14244 off_reg.type = SCALAR_VALUE;
14245 __mark_reg_known(&off_reg, insn->imm);
14246 src_reg = &off_reg;
14247 if (ptr_reg) /* pointer += K */
14248 return adjust_ptr_min_max_vals(env, insn,
14252 /* Got here implies adding two SCALAR_VALUEs */
14253 if (WARN_ON_ONCE(ptr_reg)) {
14254 print_verifier_state(env, state, true);
14255 verbose(env, "verifier internal error: unexpected ptr_reg\n");
14258 if (WARN_ON(!src_reg)) {
14259 print_verifier_state(env, state, true);
14260 verbose(env, "verifier internal error: no src_reg\n");
14263 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
14267 * Compilers can generate the code
14270 * if r2 < 1000 goto ...
14271 * use r1 in memory access
14272 * So remember constant delta between r2 and r1 and update r1 after
14275 if (env->bpf_capable && BPF_OP(insn->code) == BPF_ADD &&
14276 dst_reg->id && is_reg_const(src_reg, alu32)) {
14277 u64 val = reg_const_value(src_reg, alu32);
14279 if ((dst_reg->id & BPF_ADD_CONST) ||
14280 /* prevent overflow in sync_linked_regs() later */
14281 val > (u32)S32_MAX) {
14283 * If the register already went through rX += val
14284 * we cannot accumulate another val into rx->off.
14289 dst_reg->id |= BPF_ADD_CONST;
14290 dst_reg->off = val;
14294 * Make sure ID is cleared otherwise dst_reg min/max could be
14295 * incorrectly propagated into other registers by sync_linked_regs()
14302 /* check validity of 32-bit and 64-bit arithmetic operations */
14303 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
14305 struct bpf_reg_state *regs = cur_regs(env);
14306 u8 opcode = BPF_OP(insn->code);
14309 if (opcode == BPF_END || opcode == BPF_NEG) {
14310 if (opcode == BPF_NEG) {
14311 if (BPF_SRC(insn->code) != BPF_K ||
14312 insn->src_reg != BPF_REG_0 ||
14313 insn->off != 0 || insn->imm != 0) {
14314 verbose(env, "BPF_NEG uses reserved fields\n");
14318 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
14319 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
14320 (BPF_CLASS(insn->code) == BPF_ALU64 &&
14321 BPF_SRC(insn->code) != BPF_TO_LE)) {
14322 verbose(env, "BPF_END uses reserved fields\n");
14327 /* check src operand */
14328 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14332 if (is_pointer_value(env, insn->dst_reg)) {
14333 verbose(env, "R%d pointer arithmetic prohibited\n",
14338 /* check dest operand */
14339 err = check_reg_arg(env, insn->dst_reg, DST_OP);
14343 } else if (opcode == BPF_MOV) {
14345 if (BPF_SRC(insn->code) == BPF_X) {
14346 if (BPF_CLASS(insn->code) == BPF_ALU) {
14347 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
14349 verbose(env, "BPF_MOV uses reserved fields\n");
14352 } else if (insn->off == BPF_ADDR_SPACE_CAST) {
14353 if (insn->imm != 1 && insn->imm != 1u << 16) {
14354 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
14357 if (!env->prog->aux->arena) {
14358 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
14362 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
14363 insn->off != 32) || insn->imm) {
14364 verbose(env, "BPF_MOV uses reserved fields\n");
14369 /* check src operand */
14370 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14374 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
14375 verbose(env, "BPF_MOV uses reserved fields\n");
14380 /* check dest operand, mark as required later */
14381 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14385 if (BPF_SRC(insn->code) == BPF_X) {
14386 struct bpf_reg_state *src_reg = regs + insn->src_reg;
14387 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
14389 if (BPF_CLASS(insn->code) == BPF_ALU64) {
14391 /* off == BPF_ADDR_SPACE_CAST */
14392 mark_reg_unknown(env, regs, insn->dst_reg);
14393 if (insn->imm == 1) { /* cast from as(1) to as(0) */
14394 dst_reg->type = PTR_TO_ARENA;
14395 /* PTR_TO_ARENA is 32-bit */
14396 dst_reg->subreg_def = env->insn_idx + 1;
14398 } else if (insn->off == 0) {
14400 * copy register state to dest reg
14402 assign_scalar_id_before_mov(env, src_reg);
14403 copy_register_state(dst_reg, src_reg);
14404 dst_reg->live |= REG_LIVE_WRITTEN;
14405 dst_reg->subreg_def = DEF_NOT_SUBREG;
14407 /* case: R1 = (s8, s16 s32)R2 */
14408 if (is_pointer_value(env, insn->src_reg)) {
14410 "R%d sign-extension part of pointer\n",
14413 } else if (src_reg->type == SCALAR_VALUE) {
14416 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14418 assign_scalar_id_before_mov(env, src_reg);
14419 copy_register_state(dst_reg, src_reg);
14422 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
14423 dst_reg->live |= REG_LIVE_WRITTEN;
14424 dst_reg->subreg_def = DEF_NOT_SUBREG;
14426 mark_reg_unknown(env, regs, insn->dst_reg);
14430 /* R1 = (u32) R2 */
14431 if (is_pointer_value(env, insn->src_reg)) {
14433 "R%d partial copy of pointer\n",
14436 } else if (src_reg->type == SCALAR_VALUE) {
14437 if (insn->off == 0) {
14438 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
14440 if (is_src_reg_u32)
14441 assign_scalar_id_before_mov(env, src_reg);
14442 copy_register_state(dst_reg, src_reg);
14443 /* Make sure ID is cleared if src_reg is not in u32
14444 * range otherwise dst_reg min/max could be incorrectly
14445 * propagated into src_reg by sync_linked_regs()
14447 if (!is_src_reg_u32)
14449 dst_reg->live |= REG_LIVE_WRITTEN;
14450 dst_reg->subreg_def = env->insn_idx + 1;
14452 /* case: W1 = (s8, s16)W2 */
14453 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14456 assign_scalar_id_before_mov(env, src_reg);
14457 copy_register_state(dst_reg, src_reg);
14460 dst_reg->live |= REG_LIVE_WRITTEN;
14461 dst_reg->subreg_def = env->insn_idx + 1;
14462 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
14465 mark_reg_unknown(env, regs,
14468 zext_32_to_64(dst_reg);
14469 reg_bounds_sync(dst_reg);
14473 * remember the value we stored into this reg
14475 /* clear any state __mark_reg_known doesn't set */
14476 mark_reg_unknown(env, regs, insn->dst_reg);
14477 regs[insn->dst_reg].type = SCALAR_VALUE;
14478 if (BPF_CLASS(insn->code) == BPF_ALU64) {
14479 __mark_reg_known(regs + insn->dst_reg,
14482 __mark_reg_known(regs + insn->dst_reg,
14487 } else if (opcode > BPF_END) {
14488 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
14491 } else { /* all other ALU ops: and, sub, xor, add, ... */
14493 if (BPF_SRC(insn->code) == BPF_X) {
14494 if (insn->imm != 0 || insn->off > 1 ||
14495 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14496 verbose(env, "BPF_ALU uses reserved fields\n");
14499 /* check src1 operand */
14500 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14504 if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
14505 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14506 verbose(env, "BPF_ALU uses reserved fields\n");
14511 /* check src2 operand */
14512 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14516 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
14517 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
14518 verbose(env, "div by zero\n");
14522 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
14523 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
14524 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
14526 if (insn->imm < 0 || insn->imm >= size) {
14527 verbose(env, "invalid shift %d\n", insn->imm);
14532 /* check dest operand */
14533 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14534 err = err ?: adjust_reg_min_max_vals(env, insn);
14539 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu");
14542 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
14543 struct bpf_reg_state *dst_reg,
14544 enum bpf_reg_type type,
14545 bool range_right_open)
14547 struct bpf_func_state *state;
14548 struct bpf_reg_state *reg;
14551 if (dst_reg->off < 0 ||
14552 (dst_reg->off == 0 && range_right_open))
14553 /* This doesn't give us any range */
14556 if (dst_reg->umax_value > MAX_PACKET_OFF ||
14557 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
14558 /* Risk of overflow. For instance, ptr + (1<<63) may be less
14559 * than pkt_end, but that's because it's also less than pkt.
14563 new_range = dst_reg->off;
14564 if (range_right_open)
14567 /* Examples for register markings:
14569 * pkt_data in dst register:
14573 * if (r2 > pkt_end) goto <handle exception>
14578 * if (r2 < pkt_end) goto <access okay>
14579 * <handle exception>
14582 * r2 == dst_reg, pkt_end == src_reg
14583 * r2=pkt(id=n,off=8,r=0)
14584 * r3=pkt(id=n,off=0,r=0)
14586 * pkt_data in src register:
14590 * if (pkt_end >= r2) goto <access okay>
14591 * <handle exception>
14595 * if (pkt_end <= r2) goto <handle exception>
14599 * pkt_end == dst_reg, r2 == src_reg
14600 * r2=pkt(id=n,off=8,r=0)
14601 * r3=pkt(id=n,off=0,r=0)
14603 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14604 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14605 * and [r3, r3 + 8-1) respectively is safe to access depending on
14609 /* If our ids match, then we must have the same max_value. And we
14610 * don't care about the other reg's fixed offset, since if it's too big
14611 * the range won't allow anything.
14612 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14614 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14615 if (reg->type == type && reg->id == dst_reg->id)
14616 /* keep the maximum range already checked */
14617 reg->range = max(reg->range, new_range);
14622 * <reg1> <op> <reg2>, currently assuming reg2 is a constant
14624 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14625 u8 opcode, bool is_jmp32)
14627 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
14628 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
14629 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
14630 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
14631 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
14632 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
14633 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
14634 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
14635 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
14636 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
14640 /* constants, umin/umax and smin/smax checks would be
14641 * redundant in this case because they all should match
14643 if (tnum_is_const(t1) && tnum_is_const(t2))
14644 return t1.value == t2.value;
14645 /* non-overlapping ranges */
14646 if (umin1 > umax2 || umax1 < umin2)
14648 if (smin1 > smax2 || smax1 < smin2)
14651 /* if 64-bit ranges are inconclusive, see if we can
14652 * utilize 32-bit subrange knowledge to eliminate
14653 * branches that can't be taken a priori
14655 if (reg1->u32_min_value > reg2->u32_max_value ||
14656 reg1->u32_max_value < reg2->u32_min_value)
14658 if (reg1->s32_min_value > reg2->s32_max_value ||
14659 reg1->s32_max_value < reg2->s32_min_value)
14664 /* constants, umin/umax and smin/smax checks would be
14665 * redundant in this case because they all should match
14667 if (tnum_is_const(t1) && tnum_is_const(t2))
14668 return t1.value != t2.value;
14669 /* non-overlapping ranges */
14670 if (umin1 > umax2 || umax1 < umin2)
14672 if (smin1 > smax2 || smax1 < smin2)
14675 /* if 64-bit ranges are inconclusive, see if we can
14676 * utilize 32-bit subrange knowledge to eliminate
14677 * branches that can't be taken a priori
14679 if (reg1->u32_min_value > reg2->u32_max_value ||
14680 reg1->u32_max_value < reg2->u32_min_value)
14682 if (reg1->s32_min_value > reg2->s32_max_value ||
14683 reg1->s32_max_value < reg2->s32_min_value)
14688 if (!is_reg_const(reg2, is_jmp32)) {
14692 if (!is_reg_const(reg2, is_jmp32))
14694 if ((~t1.mask & t1.value) & t2.value)
14696 if (!((t1.mask | t1.value) & t2.value))
14702 else if (umax1 <= umin2)
14708 else if (smax1 <= smin2)
14714 else if (umin1 >= umax2)
14720 else if (smin1 >= smax2)
14724 if (umin1 >= umax2)
14726 else if (umax1 < umin2)
14730 if (smin1 >= smax2)
14732 else if (smax1 < smin2)
14736 if (umax1 <= umin2)
14738 else if (umin1 > umax2)
14742 if (smax1 <= smin2)
14744 else if (smin1 > smax2)
14752 static int flip_opcode(u32 opcode)
14754 /* How can we transform "a <op> b" into "b <op> a"? */
14755 static const u8 opcode_flip[16] = {
14756 /* these stay the same */
14757 [BPF_JEQ >> 4] = BPF_JEQ,
14758 [BPF_JNE >> 4] = BPF_JNE,
14759 [BPF_JSET >> 4] = BPF_JSET,
14760 /* these swap "lesser" and "greater" (L and G in the opcodes) */
14761 [BPF_JGE >> 4] = BPF_JLE,
14762 [BPF_JGT >> 4] = BPF_JLT,
14763 [BPF_JLE >> 4] = BPF_JGE,
14764 [BPF_JLT >> 4] = BPF_JGT,
14765 [BPF_JSGE >> 4] = BPF_JSLE,
14766 [BPF_JSGT >> 4] = BPF_JSLT,
14767 [BPF_JSLE >> 4] = BPF_JSGE,
14768 [BPF_JSLT >> 4] = BPF_JSGT
14770 return opcode_flip[opcode >> 4];
14773 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14774 struct bpf_reg_state *src_reg,
14777 struct bpf_reg_state *pkt;
14779 if (src_reg->type == PTR_TO_PACKET_END) {
14781 } else if (dst_reg->type == PTR_TO_PACKET_END) {
14783 opcode = flip_opcode(opcode);
14788 if (pkt->range >= 0)
14793 /* pkt <= pkt_end */
14796 /* pkt > pkt_end */
14797 if (pkt->range == BEYOND_PKT_END)
14798 /* pkt has at last one extra byte beyond pkt_end */
14799 return opcode == BPF_JGT;
14802 /* pkt < pkt_end */
14805 /* pkt >= pkt_end */
14806 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14807 return opcode == BPF_JGE;
14813 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
14815 * 1 - branch will be taken and "goto target" will be executed
14816 * 0 - branch will not be taken and fall-through to next insn
14817 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
14820 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14821 u8 opcode, bool is_jmp32)
14823 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
14824 return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
14826 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
14829 /* arrange that reg2 is a scalar, and reg1 is a pointer */
14830 if (!is_reg_const(reg2, is_jmp32)) {
14831 opcode = flip_opcode(opcode);
14834 /* and ensure that reg2 is a constant */
14835 if (!is_reg_const(reg2, is_jmp32))
14838 if (!reg_not_null(reg1))
14841 /* If pointer is valid tests against zero will fail so we can
14842 * use this to direct branch taken.
14844 val = reg_const_value(reg2, is_jmp32);
14858 /* now deal with two scalars, but not necessarily constants */
14859 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
14862 /* Opcode that corresponds to a *false* branch condition.
14863 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
14865 static u8 rev_opcode(u8 opcode)
14868 case BPF_JEQ: return BPF_JNE;
14869 case BPF_JNE: return BPF_JEQ;
14870 /* JSET doesn't have it's reverse opcode in BPF, so add
14871 * BPF_X flag to denote the reverse of that operation
14873 case BPF_JSET: return BPF_JSET | BPF_X;
14874 case BPF_JSET | BPF_X: return BPF_JSET;
14875 case BPF_JGE: return BPF_JLT;
14876 case BPF_JGT: return BPF_JLE;
14877 case BPF_JLE: return BPF_JGT;
14878 case BPF_JLT: return BPF_JGE;
14879 case BPF_JSGE: return BPF_JSLT;
14880 case BPF_JSGT: return BPF_JSLE;
14881 case BPF_JSLE: return BPF_JSGT;
14882 case BPF_JSLT: return BPF_JSGE;
14887 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
14888 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14889 u8 opcode, bool is_jmp32)
14894 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
14900 opcode = flip_opcode(opcode);
14910 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14911 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14912 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14913 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14914 reg2->u32_min_value = reg1->u32_min_value;
14915 reg2->u32_max_value = reg1->u32_max_value;
14916 reg2->s32_min_value = reg1->s32_min_value;
14917 reg2->s32_max_value = reg1->s32_max_value;
14919 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
14920 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14921 reg2->var_off = tnum_with_subreg(reg2->var_off, t);
14923 reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
14924 reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14925 reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
14926 reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14927 reg2->umin_value = reg1->umin_value;
14928 reg2->umax_value = reg1->umax_value;
14929 reg2->smin_value = reg1->smin_value;
14930 reg2->smax_value = reg1->smax_value;
14932 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
14933 reg2->var_off = reg1->var_off;
14937 if (!is_reg_const(reg2, is_jmp32))
14939 if (!is_reg_const(reg2, is_jmp32))
14942 /* try to recompute the bound of reg1 if reg2 is a const and
14943 * is exactly the edge of reg1.
14945 val = reg_const_value(reg2, is_jmp32);
14947 /* u32_min_value is not equal to 0xffffffff at this point,
14948 * because otherwise u32_max_value is 0xffffffff as well,
14949 * in such a case both reg1 and reg2 would be constants,
14950 * jump would be predicted and reg_set_min_max() won't
14953 * Same reasoning works for all {u,s}{min,max}{32,64} cases
14956 if (reg1->u32_min_value == (u32)val)
14957 reg1->u32_min_value++;
14958 if (reg1->u32_max_value == (u32)val)
14959 reg1->u32_max_value--;
14960 if (reg1->s32_min_value == (s32)val)
14961 reg1->s32_min_value++;
14962 if (reg1->s32_max_value == (s32)val)
14963 reg1->s32_max_value--;
14965 if (reg1->umin_value == (u64)val)
14966 reg1->umin_value++;
14967 if (reg1->umax_value == (u64)val)
14968 reg1->umax_value--;
14969 if (reg1->smin_value == (s64)val)
14970 reg1->smin_value++;
14971 if (reg1->smax_value == (s64)val)
14972 reg1->smax_value--;
14976 if (!is_reg_const(reg2, is_jmp32))
14978 if (!is_reg_const(reg2, is_jmp32))
14980 val = reg_const_value(reg2, is_jmp32);
14981 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
14982 * requires single bit to learn something useful. E.g., if we
14983 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
14984 * are actually set? We can learn something definite only if
14985 * it's a single-bit value to begin with.
14987 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
14988 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
14989 * bit 1 is set, which we can readily use in adjustments.
14991 if (!is_power_of_2(val))
14994 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
14995 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14997 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
15000 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
15001 if (!is_reg_const(reg2, is_jmp32))
15003 if (!is_reg_const(reg2, is_jmp32))
15005 val = reg_const_value(reg2, is_jmp32);
15007 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
15008 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
15010 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
15015 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
15016 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
15018 reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
15019 reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
15024 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
15025 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
15027 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
15028 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
15033 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
15034 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
15036 reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
15037 reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
15042 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
15043 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
15045 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
15046 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
15054 /* Adjusts the register min/max values in the case that the dst_reg and
15055 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
15056 * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
15057 * Technically we can do similar adjustments for pointers to the same object,
15058 * but we don't support that right now.
15060 static int reg_set_min_max(struct bpf_verifier_env *env,
15061 struct bpf_reg_state *true_reg1,
15062 struct bpf_reg_state *true_reg2,
15063 struct bpf_reg_state *false_reg1,
15064 struct bpf_reg_state *false_reg2,
15065 u8 opcode, bool is_jmp32)
15069 /* If either register is a pointer, we can't learn anything about its
15070 * variable offset from the compare (unless they were a pointer into
15071 * the same object, but we don't bother with that).
15073 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
15076 /* fallthrough (FALSE) branch */
15077 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
15078 reg_bounds_sync(false_reg1);
15079 reg_bounds_sync(false_reg2);
15081 /* jump (TRUE) branch */
15082 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
15083 reg_bounds_sync(true_reg1);
15084 reg_bounds_sync(true_reg2);
15086 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
15087 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
15088 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
15089 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
15093 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
15094 struct bpf_reg_state *reg, u32 id,
15097 if (type_may_be_null(reg->type) && reg->id == id &&
15098 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
15099 /* Old offset (both fixed and variable parts) should have been
15100 * known-zero, because we don't allow pointer arithmetic on
15101 * pointers that might be NULL. If we see this happening, don't
15102 * convert the register.
15104 * But in some cases, some helpers that return local kptrs
15105 * advance offset for the returned pointer. In those cases, it
15106 * is fine to expect to see reg->off.
15108 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
15110 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
15111 WARN_ON_ONCE(reg->off))
15115 reg->type = SCALAR_VALUE;
15116 /* We don't need id and ref_obj_id from this point
15117 * onwards anymore, thus we should better reset it,
15118 * so that state pruning has chances to take effect.
15121 reg->ref_obj_id = 0;
15126 mark_ptr_not_null_reg(reg);
15128 if (!reg_may_point_to_spin_lock(reg)) {
15129 /* For not-NULL ptr, reg->ref_obj_id will be reset
15130 * in release_reference().
15132 * reg->id is still used by spin_lock ptr. Other
15133 * than spin_lock ptr type, reg->id can be reset.
15140 /* The logic is similar to find_good_pkt_pointers(), both could eventually
15141 * be folded together at some point.
15143 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
15146 struct bpf_func_state *state = vstate->frame[vstate->curframe];
15147 struct bpf_reg_state *regs = state->regs, *reg;
15148 u32 ref_obj_id = regs[regno].ref_obj_id;
15149 u32 id = regs[regno].id;
15151 if (ref_obj_id && ref_obj_id == id && is_null)
15152 /* regs[regno] is in the " == NULL" branch.
15153 * No one could have freed the reference state before
15154 * doing the NULL check.
15156 WARN_ON_ONCE(release_reference_state(state, id));
15158 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15159 mark_ptr_or_null_reg(state, reg, id, is_null);
15163 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
15164 struct bpf_reg_state *dst_reg,
15165 struct bpf_reg_state *src_reg,
15166 struct bpf_verifier_state *this_branch,
15167 struct bpf_verifier_state *other_branch)
15169 if (BPF_SRC(insn->code) != BPF_X)
15172 /* Pointers are always 64-bit. */
15173 if (BPF_CLASS(insn->code) == BPF_JMP32)
15176 switch (BPF_OP(insn->code)) {
15178 if ((dst_reg->type == PTR_TO_PACKET &&
15179 src_reg->type == PTR_TO_PACKET_END) ||
15180 (dst_reg->type == PTR_TO_PACKET_META &&
15181 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15182 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
15183 find_good_pkt_pointers(this_branch, dst_reg,
15184 dst_reg->type, false);
15185 mark_pkt_end(other_branch, insn->dst_reg, true);
15186 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
15187 src_reg->type == PTR_TO_PACKET) ||
15188 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15189 src_reg->type == PTR_TO_PACKET_META)) {
15190 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
15191 find_good_pkt_pointers(other_branch, src_reg,
15192 src_reg->type, true);
15193 mark_pkt_end(this_branch, insn->src_reg, false);
15199 if ((dst_reg->type == PTR_TO_PACKET &&
15200 src_reg->type == PTR_TO_PACKET_END) ||
15201 (dst_reg->type == PTR_TO_PACKET_META &&
15202 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15203 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
15204 find_good_pkt_pointers(other_branch, dst_reg,
15205 dst_reg->type, true);
15206 mark_pkt_end(this_branch, insn->dst_reg, false);
15207 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
15208 src_reg->type == PTR_TO_PACKET) ||
15209 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15210 src_reg->type == PTR_TO_PACKET_META)) {
15211 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
15212 find_good_pkt_pointers(this_branch, src_reg,
15213 src_reg->type, false);
15214 mark_pkt_end(other_branch, insn->src_reg, true);
15220 if ((dst_reg->type == PTR_TO_PACKET &&
15221 src_reg->type == PTR_TO_PACKET_END) ||
15222 (dst_reg->type == PTR_TO_PACKET_META &&
15223 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15224 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
15225 find_good_pkt_pointers(this_branch, dst_reg,
15226 dst_reg->type, true);
15227 mark_pkt_end(other_branch, insn->dst_reg, false);
15228 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
15229 src_reg->type == PTR_TO_PACKET) ||
15230 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15231 src_reg->type == PTR_TO_PACKET_META)) {
15232 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
15233 find_good_pkt_pointers(other_branch, src_reg,
15234 src_reg->type, false);
15235 mark_pkt_end(this_branch, insn->src_reg, true);
15241 if ((dst_reg->type == PTR_TO_PACKET &&
15242 src_reg->type == PTR_TO_PACKET_END) ||
15243 (dst_reg->type == PTR_TO_PACKET_META &&
15244 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15245 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
15246 find_good_pkt_pointers(other_branch, dst_reg,
15247 dst_reg->type, false);
15248 mark_pkt_end(this_branch, insn->dst_reg, true);
15249 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
15250 src_reg->type == PTR_TO_PACKET) ||
15251 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15252 src_reg->type == PTR_TO_PACKET_META)) {
15253 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
15254 find_good_pkt_pointers(this_branch, src_reg,
15255 src_reg->type, true);
15256 mark_pkt_end(other_branch, insn->src_reg, false);
15268 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
15269 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
15271 struct linked_reg *e;
15273 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
15276 e = linked_regs_push(reg_set);
15278 e->frameno = frameno;
15279 e->is_reg = is_reg;
15280 e->regno = spi_or_reg;
15286 /* For all R being scalar registers or spilled scalar registers
15287 * in verifier state, save R in linked_regs if R->id == id.
15288 * If there are too many Rs sharing same id, reset id for leftover Rs.
15290 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
15291 struct linked_regs *linked_regs)
15293 struct bpf_func_state *func;
15294 struct bpf_reg_state *reg;
15297 id = id & ~BPF_ADD_CONST;
15298 for (i = vstate->curframe; i >= 0; i--) {
15299 func = vstate->frame[i];
15300 for (j = 0; j < BPF_REG_FP; j++) {
15301 reg = &func->regs[j];
15302 __collect_linked_regs(linked_regs, reg, id, i, j, true);
15304 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
15305 if (!is_spilled_reg(&func->stack[j]))
15307 reg = &func->stack[j].spilled_ptr;
15308 __collect_linked_regs(linked_regs, reg, id, i, j, false);
15313 /* For all R in linked_regs, copy known_reg range into R
15314 * if R->id == known_reg->id.
15316 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg,
15317 struct linked_regs *linked_regs)
15319 struct bpf_reg_state fake_reg;
15320 struct bpf_reg_state *reg;
15321 struct linked_reg *e;
15324 for (i = 0; i < linked_regs->cnt; ++i) {
15325 e = &linked_regs->entries[i];
15326 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
15327 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
15328 if (reg->type != SCALAR_VALUE || reg == known_reg)
15330 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
15332 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
15333 reg->off == known_reg->off) {
15334 copy_register_state(reg, known_reg);
15336 s32 saved_off = reg->off;
15338 fake_reg.type = SCALAR_VALUE;
15339 __mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
15341 /* reg = known_reg; reg += delta */
15342 copy_register_state(reg, known_reg);
15344 * Must preserve off, id and add_const flag,
15345 * otherwise another sync_linked_regs() will be incorrect.
15347 reg->off = saved_off;
15349 scalar32_min_max_add(reg, &fake_reg);
15350 scalar_min_max_add(reg, &fake_reg);
15351 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
15356 static int check_cond_jmp_op(struct bpf_verifier_env *env,
15357 struct bpf_insn *insn, int *insn_idx)
15359 struct bpf_verifier_state *this_branch = env->cur_state;
15360 struct bpf_verifier_state *other_branch;
15361 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
15362 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
15363 struct bpf_reg_state *eq_branch_regs;
15364 struct linked_regs linked_regs = {};
15365 u8 opcode = BPF_OP(insn->code);
15370 /* Only conditional jumps are expected to reach here. */
15371 if (opcode == BPF_JA || opcode > BPF_JCOND) {
15372 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
15376 if (opcode == BPF_JCOND) {
15377 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
15378 int idx = *insn_idx;
15380 if (insn->code != (BPF_JMP | BPF_JCOND) ||
15381 insn->src_reg != BPF_MAY_GOTO ||
15382 insn->dst_reg || insn->imm || insn->off == 0) {
15383 verbose(env, "invalid may_goto off %d imm %d\n",
15384 insn->off, insn->imm);
15387 prev_st = find_prev_entry(env, cur_st->parent, idx);
15389 /* branch out 'fallthrough' insn as a new state to explore */
15390 queued_st = push_stack(env, idx + 1, idx, false);
15394 queued_st->may_goto_depth++;
15396 widen_imprecise_scalars(env, prev_st, queued_st);
15397 *insn_idx += insn->off;
15401 /* check src2 operand */
15402 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15406 dst_reg = ®s[insn->dst_reg];
15407 if (BPF_SRC(insn->code) == BPF_X) {
15408 if (insn->imm != 0) {
15409 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15413 /* check src1 operand */
15414 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15418 src_reg = ®s[insn->src_reg];
15419 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
15420 is_pointer_value(env, insn->src_reg)) {
15421 verbose(env, "R%d pointer comparison prohibited\n",
15426 if (insn->src_reg != BPF_REG_0) {
15427 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15430 src_reg = &env->fake_reg[0];
15431 memset(src_reg, 0, sizeof(*src_reg));
15432 src_reg->type = SCALAR_VALUE;
15433 __mark_reg_known(src_reg, insn->imm);
15436 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
15437 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
15439 /* If we get here with a dst_reg pointer type it is because
15440 * above is_branch_taken() special cased the 0 comparison.
15442 if (!__is_pointer_value(false, dst_reg))
15443 err = mark_chain_precision(env, insn->dst_reg);
15444 if (BPF_SRC(insn->code) == BPF_X && !err &&
15445 !__is_pointer_value(false, src_reg))
15446 err = mark_chain_precision(env, insn->src_reg);
15452 /* Only follow the goto, ignore fall-through. If needed, push
15453 * the fall-through branch for simulation under speculative
15456 if (!env->bypass_spec_v1 &&
15457 !sanitize_speculative_path(env, insn, *insn_idx + 1,
15460 if (env->log.level & BPF_LOG_LEVEL)
15461 print_insn_state(env, this_branch->frame[this_branch->curframe]);
15462 *insn_idx += insn->off;
15464 } else if (pred == 0) {
15465 /* Only follow the fall-through branch, since that's where the
15466 * program will go. If needed, push the goto branch for
15467 * simulation under speculative execution.
15469 if (!env->bypass_spec_v1 &&
15470 !sanitize_speculative_path(env, insn,
15471 *insn_idx + insn->off + 1,
15474 if (env->log.level & BPF_LOG_LEVEL)
15475 print_insn_state(env, this_branch->frame[this_branch->curframe]);
15479 /* Push scalar registers sharing same ID to jump history,
15480 * do this before creating 'other_branch', so that both
15481 * 'this_branch' and 'other_branch' share this history
15482 * if parent state is created.
15484 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
15485 collect_linked_regs(this_branch, src_reg->id, &linked_regs);
15486 if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
15487 collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
15488 if (linked_regs.cnt > 1) {
15489 err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
15494 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
15498 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
15500 if (BPF_SRC(insn->code) == BPF_X) {
15501 err = reg_set_min_max(env,
15502 &other_branch_regs[insn->dst_reg],
15503 &other_branch_regs[insn->src_reg],
15504 dst_reg, src_reg, opcode, is_jmp32);
15505 } else /* BPF_SRC(insn->code) == BPF_K */ {
15506 /* reg_set_min_max() can mangle the fake_reg. Make a copy
15507 * so that these are two different memory locations. The
15508 * src_reg is not used beyond here in context of K.
15510 memcpy(&env->fake_reg[1], &env->fake_reg[0],
15511 sizeof(env->fake_reg[0]));
15512 err = reg_set_min_max(env,
15513 &other_branch_regs[insn->dst_reg],
15515 dst_reg, &env->fake_reg[1],
15521 if (BPF_SRC(insn->code) == BPF_X &&
15522 src_reg->type == SCALAR_VALUE && src_reg->id &&
15523 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
15524 sync_linked_regs(this_branch, src_reg, &linked_regs);
15525 sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs);
15527 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
15528 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
15529 sync_linked_regs(this_branch, dst_reg, &linked_regs);
15530 sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs);
15533 /* if one pointer register is compared to another pointer
15534 * register check if PTR_MAYBE_NULL could be lifted.
15535 * E.g. register A - maybe null
15536 * register B - not null
15537 * for JNE A, B, ... - A is not null in the false branch;
15538 * for JEQ A, B, ... - A is not null in the true branch.
15540 * Since PTR_TO_BTF_ID points to a kernel struct that does
15541 * not need to be null checked by the BPF program, i.e.,
15542 * could be null even without PTR_MAYBE_NULL marking, so
15543 * only propagate nullness when neither reg is that type.
15545 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
15546 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
15547 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
15548 base_type(src_reg->type) != PTR_TO_BTF_ID &&
15549 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
15550 eq_branch_regs = NULL;
15553 eq_branch_regs = other_branch_regs;
15556 eq_branch_regs = regs;
15562 if (eq_branch_regs) {
15563 if (type_may_be_null(src_reg->type))
15564 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
15566 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
15570 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
15571 * NOTE: these optimizations below are related with pointer comparison
15572 * which will never be JMP32.
15574 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
15575 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
15576 type_may_be_null(dst_reg->type)) {
15577 /* Mark all identical registers in each branch as either
15578 * safe or unknown depending R == 0 or R != 0 conditional.
15580 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
15581 opcode == BPF_JNE);
15582 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
15583 opcode == BPF_JEQ);
15584 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
15585 this_branch, other_branch) &&
15586 is_pointer_value(env, insn->dst_reg)) {
15587 verbose(env, "R%d pointer comparison prohibited\n",
15591 if (env->log.level & BPF_LOG_LEVEL)
15592 print_insn_state(env, this_branch->frame[this_branch->curframe]);
15596 /* verify BPF_LD_IMM64 instruction */
15597 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
15599 struct bpf_insn_aux_data *aux = cur_aux(env);
15600 struct bpf_reg_state *regs = cur_regs(env);
15601 struct bpf_reg_state *dst_reg;
15602 struct bpf_map *map;
15605 if (BPF_SIZE(insn->code) != BPF_DW) {
15606 verbose(env, "invalid BPF_LD_IMM insn\n");
15609 if (insn->off != 0) {
15610 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
15614 err = check_reg_arg(env, insn->dst_reg, DST_OP);
15618 dst_reg = ®s[insn->dst_reg];
15619 if (insn->src_reg == 0) {
15620 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
15622 dst_reg->type = SCALAR_VALUE;
15623 __mark_reg_known(®s[insn->dst_reg], imm);
15627 /* All special src_reg cases are listed below. From this point onwards
15628 * we either succeed and assign a corresponding dst_reg->type after
15629 * zeroing the offset, or fail and reject the program.
15631 mark_reg_known_zero(env, regs, insn->dst_reg);
15633 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
15634 dst_reg->type = aux->btf_var.reg_type;
15635 switch (base_type(dst_reg->type)) {
15637 dst_reg->mem_size = aux->btf_var.mem_size;
15639 case PTR_TO_BTF_ID:
15640 dst_reg->btf = aux->btf_var.btf;
15641 dst_reg->btf_id = aux->btf_var.btf_id;
15644 verbose(env, "bpf verifier is misconfigured\n");
15650 if (insn->src_reg == BPF_PSEUDO_FUNC) {
15651 struct bpf_prog_aux *aux = env->prog->aux;
15652 u32 subprogno = find_subprog(env,
15653 env->insn_idx + insn->imm + 1);
15655 if (!aux->func_info) {
15656 verbose(env, "missing btf func_info\n");
15659 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
15660 verbose(env, "callback function not static\n");
15664 dst_reg->type = PTR_TO_FUNC;
15665 dst_reg->subprogno = subprogno;
15669 map = env->used_maps[aux->map_index];
15670 dst_reg->map_ptr = map;
15672 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15673 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15674 if (map->map_type == BPF_MAP_TYPE_ARENA) {
15675 __mark_reg_unknown(env, dst_reg);
15678 dst_reg->type = PTR_TO_MAP_VALUE;
15679 dst_reg->off = aux->map_off;
15680 WARN_ON_ONCE(map->max_entries != 1);
15681 /* We want reg->id to be same (0) as map_value is not distinct */
15682 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15683 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15684 dst_reg->type = CONST_PTR_TO_MAP;
15686 verbose(env, "bpf verifier is misconfigured\n");
15693 static bool may_access_skb(enum bpf_prog_type type)
15696 case BPF_PROG_TYPE_SOCKET_FILTER:
15697 case BPF_PROG_TYPE_SCHED_CLS:
15698 case BPF_PROG_TYPE_SCHED_ACT:
15705 /* verify safety of LD_ABS|LD_IND instructions:
15706 * - they can only appear in the programs where ctx == skb
15707 * - since they are wrappers of function calls, they scratch R1-R5 registers,
15708 * preserve R6-R9, and store return value into R0
15711 * ctx == skb == R6 == CTX
15714 * SRC == any register
15715 * IMM == 32-bit immediate
15718 * R0 - 8/16/32-bit skb data converted to cpu endianness
15720 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15722 struct bpf_reg_state *regs = cur_regs(env);
15723 static const int ctx_reg = BPF_REG_6;
15724 u8 mode = BPF_MODE(insn->code);
15727 if (!may_access_skb(resolve_prog_type(env->prog))) {
15728 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15732 if (!env->ops->gen_ld_abs) {
15733 verbose(env, "bpf verifier is misconfigured\n");
15737 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15738 BPF_SIZE(insn->code) == BPF_DW ||
15739 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15740 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
15744 /* check whether implicit source operand (register R6) is readable */
15745 err = check_reg_arg(env, ctx_reg, SRC_OP);
15749 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15750 * gen_ld_abs() may terminate the program at runtime, leading to
15753 err = check_reference_leak(env, false);
15755 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15759 if (env->cur_state->active_lock.ptr) {
15760 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15764 if (env->cur_state->active_rcu_lock) {
15765 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15769 if (env->cur_state->active_preempt_lock) {
15770 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_preempt_disable-ed region\n");
15774 if (regs[ctx_reg].type != PTR_TO_CTX) {
15776 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
15780 if (mode == BPF_IND) {
15781 /* check explicit source operand */
15782 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15787 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
15791 /* reset caller saved regs to unreadable */
15792 for (i = 0; i < CALLER_SAVED_REGS; i++) {
15793 mark_reg_not_init(env, regs, caller_saved[i]);
15794 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15797 /* mark destination R0 register as readable, since it contains
15798 * the value fetched from the packet.
15799 * Already marked as written above.
15801 mark_reg_unknown(env, regs, BPF_REG_0);
15802 /* ld_abs load up to 32-bit skb data. */
15803 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
15807 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
15809 const char *exit_ctx = "At program exit";
15810 struct tnum enforce_attach_type_range = tnum_unknown;
15811 const struct bpf_prog *prog = env->prog;
15812 struct bpf_reg_state *reg;
15813 struct bpf_retval_range range = retval_range(0, 1);
15814 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15816 struct bpf_func_state *frame = env->cur_state->frame[0];
15817 const bool is_subprog = frame->subprogno;
15818 bool return_32bit = false;
15820 /* LSM and struct_ops func-ptr's return type could be "void" */
15821 if (!is_subprog || frame->in_exception_callback_fn) {
15822 switch (prog_type) {
15823 case BPF_PROG_TYPE_LSM:
15824 if (prog->expected_attach_type == BPF_LSM_CGROUP)
15825 /* See below, can be 0 or 0-1 depending on hook. */
15828 case BPF_PROG_TYPE_STRUCT_OPS:
15829 if (!prog->aux->attach_func_proto->type)
15837 /* eBPF calling convention is such that R0 is used
15838 * to return the value from eBPF program.
15839 * Make sure that it's readable at this time
15840 * of bpf_exit, which means that program wrote
15841 * something into it earlier
15843 err = check_reg_arg(env, regno, SRC_OP);
15847 if (is_pointer_value(env, regno)) {
15848 verbose(env, "R%d leaks addr as return value\n", regno);
15852 reg = cur_regs(env) + regno;
15854 if (frame->in_async_callback_fn) {
15855 /* enforce return zero from async callbacks like timer */
15856 exit_ctx = "At async callback return";
15857 range = retval_range(0, 0);
15858 goto enforce_retval;
15861 if (is_subprog && !frame->in_exception_callback_fn) {
15862 if (reg->type != SCALAR_VALUE) {
15863 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15864 regno, reg_type_str(env, reg->type));
15870 switch (prog_type) {
15871 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15872 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15873 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15874 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15875 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15876 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15877 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15878 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15879 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15880 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15881 range = retval_range(1, 1);
15882 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15883 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15884 range = retval_range(0, 3);
15886 case BPF_PROG_TYPE_CGROUP_SKB:
15887 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15888 range = retval_range(0, 3);
15889 enforce_attach_type_range = tnum_range(2, 3);
15892 case BPF_PROG_TYPE_CGROUP_SOCK:
15893 case BPF_PROG_TYPE_SOCK_OPS:
15894 case BPF_PROG_TYPE_CGROUP_DEVICE:
15895 case BPF_PROG_TYPE_CGROUP_SYSCTL:
15896 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15898 case BPF_PROG_TYPE_RAW_TRACEPOINT:
15899 if (!env->prog->aux->attach_btf_id)
15901 range = retval_range(0, 0);
15903 case BPF_PROG_TYPE_TRACING:
15904 switch (env->prog->expected_attach_type) {
15905 case BPF_TRACE_FENTRY:
15906 case BPF_TRACE_FEXIT:
15907 range = retval_range(0, 0);
15909 case BPF_TRACE_RAW_TP:
15910 case BPF_MODIFY_RETURN:
15912 case BPF_TRACE_ITER:
15918 case BPF_PROG_TYPE_SK_LOOKUP:
15919 range = retval_range(SK_DROP, SK_PASS);
15922 case BPF_PROG_TYPE_LSM:
15923 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15924 /* no range found, any return value is allowed */
15925 if (!get_func_retval_range(env->prog, &range))
15927 /* no restricted range, any return value is allowed */
15928 if (range.minval == S32_MIN && range.maxval == S32_MAX)
15930 return_32bit = true;
15931 } else if (!env->prog->aux->attach_func_proto->type) {
15932 /* Make sure programs that attach to void
15933 * hooks don't try to modify return value.
15935 range = retval_range(1, 1);
15939 case BPF_PROG_TYPE_NETFILTER:
15940 range = retval_range(NF_DROP, NF_ACCEPT);
15942 case BPF_PROG_TYPE_EXT:
15943 /* freplace program can return anything as its return value
15944 * depends on the to-be-replaced kernel func or bpf program.
15951 if (reg->type != SCALAR_VALUE) {
15952 verbose(env, "%s the register R%d is not a known value (%s)\n",
15953 exit_ctx, regno, reg_type_str(env, reg->type));
15957 err = mark_chain_precision(env, regno);
15961 if (!retval_range_within(range, reg, return_32bit)) {
15962 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
15964 prog->expected_attach_type == BPF_LSM_CGROUP &&
15965 prog_type == BPF_PROG_TYPE_LSM &&
15966 !prog->aux->attach_func_proto->type)
15967 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15971 if (!tnum_is_unknown(enforce_attach_type_range) &&
15972 tnum_in(enforce_attach_type_range, reg->var_off))
15973 env->prog->enforce_expected_attach_type = 1;
15977 /* non-recursive DFS pseudo code
15978 * 1 procedure DFS-iterative(G,v):
15979 * 2 label v as discovered
15980 * 3 let S be a stack
15982 * 5 while S is not empty
15984 * 7 if t is what we're looking for:
15986 * 9 for all edges e in G.adjacentEdges(t) do
15987 * 10 if edge e is already labelled
15988 * 11 continue with the next edge
15989 * 12 w <- G.adjacentVertex(t,e)
15990 * 13 if vertex w is not discovered and not explored
15991 * 14 label e as tree-edge
15992 * 15 label w as discovered
15995 * 18 else if vertex w is discovered
15996 * 19 label e as back-edge
15998 * 21 // vertex w is explored
15999 * 22 label e as forward- or cross-edge
16000 * 23 label t as explored
16004 * 0x10 - discovered
16005 * 0x11 - discovered and fall-through edge labelled
16006 * 0x12 - discovered and fall-through and branch edges labelled
16017 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
16019 env->insn_aux_data[idx].prune_point = true;
16022 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
16024 return env->insn_aux_data[insn_idx].prune_point;
16027 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
16029 env->insn_aux_data[idx].force_checkpoint = true;
16032 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
16034 return env->insn_aux_data[insn_idx].force_checkpoint;
16037 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
16039 env->insn_aux_data[idx].calls_callback = true;
16042 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
16044 return env->insn_aux_data[insn_idx].calls_callback;
16048 DONE_EXPLORING = 0,
16049 KEEP_EXPLORING = 1,
16052 /* t, w, e - match pseudo-code above:
16053 * t - index of current instruction
16054 * w - next instruction
16057 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
16059 int *insn_stack = env->cfg.insn_stack;
16060 int *insn_state = env->cfg.insn_state;
16062 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
16063 return DONE_EXPLORING;
16065 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
16066 return DONE_EXPLORING;
16068 if (w < 0 || w >= env->prog->len) {
16069 verbose_linfo(env, t, "%d: ", t);
16070 verbose(env, "jump out of range from insn %d to %d\n", t, w);
16075 /* mark branch target for state pruning */
16076 mark_prune_point(env, w);
16077 mark_jmp_point(env, w);
16080 if (insn_state[w] == 0) {
16082 insn_state[t] = DISCOVERED | e;
16083 insn_state[w] = DISCOVERED;
16084 if (env->cfg.cur_stack >= env->prog->len)
16086 insn_stack[env->cfg.cur_stack++] = w;
16087 return KEEP_EXPLORING;
16088 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
16089 if (env->bpf_capable)
16090 return DONE_EXPLORING;
16091 verbose_linfo(env, t, "%d: ", t);
16092 verbose_linfo(env, w, "%d: ", w);
16093 verbose(env, "back-edge from insn %d to %d\n", t, w);
16095 } else if (insn_state[w] == EXPLORED) {
16096 /* forward- or cross-edge */
16097 insn_state[t] = DISCOVERED | e;
16099 verbose(env, "insn state internal bug\n");
16102 return DONE_EXPLORING;
16105 static int visit_func_call_insn(int t, struct bpf_insn *insns,
16106 struct bpf_verifier_env *env,
16111 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
16112 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
16116 mark_prune_point(env, t + insn_sz);
16117 /* when we exit from subprog, we need to record non-linear history */
16118 mark_jmp_point(env, t + insn_sz);
16120 if (visit_callee) {
16121 mark_prune_point(env, t);
16122 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
16127 /* Bitmask with 1s for all caller saved registers */
16128 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
16130 /* Return a bitmask specifying which caller saved registers are
16131 * clobbered by a call to a helper *as if* this helper follows
16132 * bpf_fastcall contract:
16133 * - includes R0 if function is non-void;
16134 * - includes R1-R5 if corresponding parameter has is described
16135 * in the function prototype.
16137 static u32 helper_fastcall_clobber_mask(const struct bpf_func_proto *fn)
16143 if (fn->ret_type != RET_VOID)
16144 mask |= BIT(BPF_REG_0);
16145 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i)
16146 if (fn->arg_type[i] != ARG_DONTCARE)
16147 mask |= BIT(BPF_REG_1 + i);
16151 /* True if do_misc_fixups() replaces calls to helper number 'imm',
16152 * replacement patch is presumed to follow bpf_fastcall contract
16153 * (see mark_fastcall_pattern_for_call() below).
16155 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
16158 #ifdef CONFIG_X86_64
16159 case BPF_FUNC_get_smp_processor_id:
16160 return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
16167 /* Same as helper_fastcall_clobber_mask() but for kfuncs, see comment above */
16168 static u32 kfunc_fastcall_clobber_mask(struct bpf_kfunc_call_arg_meta *meta)
16172 vlen = btf_type_vlen(meta->func_proto);
16174 if (!btf_type_is_void(btf_type_by_id(meta->btf, meta->func_proto->type)))
16175 mask |= BIT(BPF_REG_0);
16176 for (i = 0; i < vlen; ++i)
16177 mask |= BIT(BPF_REG_1 + i);
16181 /* Same as verifier_inlines_helper_call() but for kfuncs, see comment above */
16182 static bool is_fastcall_kfunc_call(struct bpf_kfunc_call_arg_meta *meta)
16184 return meta->kfunc_flags & KF_FASTCALL;
16187 /* LLVM define a bpf_fastcall function attribute.
16188 * This attribute means that function scratches only some of
16189 * the caller saved registers defined by ABI.
16190 * For BPF the set of such registers could be defined as follows:
16191 * - R0 is scratched only if function is non-void;
16192 * - R1-R5 are scratched only if corresponding parameter type is defined
16193 * in the function prototype.
16195 * The contract between kernel and clang allows to simultaneously use
16196 * such functions and maintain backwards compatibility with old
16197 * kernels that don't understand bpf_fastcall calls:
16199 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
16200 * registers are not scratched by the call;
16202 * - as a post-processing step, clang visits each bpf_fastcall call and adds
16203 * spill/fill for every live r0-r5;
16205 * - stack offsets used for the spill/fill are allocated as lowest
16206 * stack offsets in whole function and are not used for any other
16209 * - when kernel loads a program, it looks for such patterns
16210 * (bpf_fastcall function surrounded by spills/fills) and checks if
16211 * spill/fill stack offsets are used exclusively in fastcall patterns;
16213 * - if so, and if verifier or current JIT inlines the call to the
16214 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
16215 * spill/fill pairs;
16217 * - when old kernel loads a program, presence of spill/fill pairs
16218 * keeps BPF program valid, albeit slightly less efficient.
16224 * *(u64 *)(r10 - 8) = r1; r1 = 1;
16225 * *(u64 *)(r10 - 16) = r2; r2 = 2;
16226 * call %[to_be_inlined] --> call %[to_be_inlined]
16227 * r2 = *(u64 *)(r10 - 16); r0 = r1;
16228 * r1 = *(u64 *)(r10 - 8); r0 += r2;
16233 * The purpose of mark_fastcall_pattern_for_call is to:
16234 * - look for such patterns;
16235 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
16236 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
16237 * - update env->subprog_info[*]->fastcall_stack_off to find an offset
16238 * at which bpf_fastcall spill/fill stack slots start;
16239 * - update env->subprog_info[*]->keep_fastcall_stack.
16241 * The .fastcall_pattern and .fastcall_stack_off are used by
16242 * check_fastcall_stack_contract() to check if every stack access to
16243 * fastcall spill/fill stack slot originates from spill/fill
16244 * instructions, members of fastcall patterns.
16246 * If such condition holds true for a subprogram, fastcall patterns could
16247 * be rewritten by remove_fastcall_spills_fills().
16248 * Otherwise bpf_fastcall patterns are not changed in the subprogram
16249 * (code, presumably, generated by an older clang version).
16251 * For example, it is *not* safe to remove spill/fill below:
16254 * *(u64 *)(r10 - 8) = r1; r1 = 1;
16255 * call %[to_be_inlined] --> call %[to_be_inlined]
16256 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!!
16257 * r0 = *(u64 *)(r10 - 8); r0 += r1;
16261 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
16262 struct bpf_subprog_info *subprog,
16263 int insn_idx, s16 lowest_off)
16265 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
16266 struct bpf_insn *call = &env->prog->insnsi[insn_idx];
16267 const struct bpf_func_proto *fn;
16268 u32 clobbered_regs_mask = ALL_CALLER_SAVED_REGS;
16269 u32 expected_regs_mask;
16270 bool can_be_inlined = false;
16274 if (bpf_helper_call(call)) {
16275 if (get_helper_proto(env, call->imm, &fn) < 0)
16276 /* error would be reported later */
16278 clobbered_regs_mask = helper_fastcall_clobber_mask(fn);
16279 can_be_inlined = fn->allow_fastcall &&
16280 (verifier_inlines_helper_call(env, call->imm) ||
16281 bpf_jit_inlines_helper_call(call->imm));
16284 if (bpf_pseudo_kfunc_call(call)) {
16285 struct bpf_kfunc_call_arg_meta meta;
16288 err = fetch_kfunc_meta(env, call, &meta, NULL);
16290 /* error would be reported later */
16293 clobbered_regs_mask = kfunc_fastcall_clobber_mask(&meta);
16294 can_be_inlined = is_fastcall_kfunc_call(&meta);
16297 if (clobbered_regs_mask == ALL_CALLER_SAVED_REGS)
16300 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
16301 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
16303 /* match pairs of form:
16305 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0)
16307 * call %[to_be_inlined]
16309 * rX = *(u64 *)(r10 - Y)
16311 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
16312 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
16314 stx = &insns[insn_idx - i];
16315 ldx = &insns[insn_idx + i];
16316 /* must be a stack spill/fill pair */
16317 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
16318 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
16319 stx->dst_reg != BPF_REG_10 ||
16320 ldx->src_reg != BPF_REG_10)
16322 /* must be a spill/fill for the same reg */
16323 if (stx->src_reg != ldx->dst_reg)
16325 /* must be one of the previously unseen registers */
16326 if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
16328 /* must be a spill/fill for the same expected offset,
16329 * no need to check offset alignment, BPF_DW stack access
16330 * is always 8-byte aligned.
16332 if (stx->off != off || ldx->off != off)
16334 expected_regs_mask &= ~BIT(stx->src_reg);
16335 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
16336 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
16341 /* Conditionally set 'fastcall_spills_num' to allow forward
16342 * compatibility when more helper functions are marked as
16343 * bpf_fastcall at compile time than current kernel supports, e.g:
16345 * 1: *(u64 *)(r10 - 8) = r1
16346 * 2: call A ;; assume A is bpf_fastcall for current kernel
16347 * 3: r1 = *(u64 *)(r10 - 8)
16348 * 4: *(u64 *)(r10 - 8) = r1
16349 * 5: call B ;; assume B is not bpf_fastcall for current kernel
16350 * 6: r1 = *(u64 *)(r10 - 8)
16352 * There is no need to block bpf_fastcall rewrite for such program.
16353 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
16354 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
16355 * does not remove spill/fill pair {4,6}.
16357 if (can_be_inlined)
16358 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
16360 subprog->keep_fastcall_stack = 1;
16361 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
16364 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
16366 struct bpf_subprog_info *subprog = env->subprog_info;
16367 struct bpf_insn *insn;
16371 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
16372 /* find lowest stack spill offset used in this subprog */
16374 for (i = subprog->start; i < (subprog + 1)->start; ++i) {
16375 insn = env->prog->insnsi + i;
16376 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
16377 insn->dst_reg != BPF_REG_10)
16379 lowest_off = min(lowest_off, insn->off);
16381 /* use this offset to find fastcall patterns */
16382 for (i = subprog->start; i < (subprog + 1)->start; ++i) {
16383 insn = env->prog->insnsi + i;
16384 if (insn->code != (BPF_JMP | BPF_CALL))
16386 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
16392 /* Visits the instruction at index t and returns one of the following:
16393 * < 0 - an error occurred
16394 * DONE_EXPLORING - the instruction was fully explored
16395 * KEEP_EXPLORING - there is still work to be done before it is fully explored
16397 static int visit_insn(int t, struct bpf_verifier_env *env)
16399 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
16400 int ret, off, insn_sz;
16402 if (bpf_pseudo_func(insn))
16403 return visit_func_call_insn(t, insns, env, true);
16405 /* All non-branch instructions have a single fall-through edge. */
16406 if (BPF_CLASS(insn->code) != BPF_JMP &&
16407 BPF_CLASS(insn->code) != BPF_JMP32) {
16408 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
16409 return push_insn(t, t + insn_sz, FALLTHROUGH, env);
16412 switch (BPF_OP(insn->code)) {
16414 return DONE_EXPLORING;
16417 if (is_async_callback_calling_insn(insn))
16418 /* Mark this call insn as a prune point to trigger
16419 * is_state_visited() check before call itself is
16420 * processed by __check_func_call(). Otherwise new
16421 * async state will be pushed for further exploration.
16423 mark_prune_point(env, t);
16424 /* For functions that invoke callbacks it is not known how many times
16425 * callback would be called. Verifier models callback calling functions
16426 * by repeatedly visiting callback bodies and returning to origin call
16428 * In order to stop such iteration verifier needs to identify when a
16429 * state identical some state from a previous iteration is reached.
16430 * Check below forces creation of checkpoint before callback calling
16431 * instruction to allow search for such identical states.
16433 if (is_sync_callback_calling_insn(insn)) {
16434 mark_calls_callback(env, t);
16435 mark_force_checkpoint(env, t);
16436 mark_prune_point(env, t);
16437 mark_jmp_point(env, t);
16439 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
16440 struct bpf_kfunc_call_arg_meta meta;
16442 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
16443 if (ret == 0 && is_iter_next_kfunc(&meta)) {
16444 mark_prune_point(env, t);
16445 /* Checking and saving state checkpoints at iter_next() call
16446 * is crucial for fast convergence of open-coded iterator loop
16447 * logic, so we need to force it. If we don't do that,
16448 * is_state_visited() might skip saving a checkpoint, causing
16449 * unnecessarily long sequence of not checkpointed
16450 * instructions and jumps, leading to exhaustion of jump
16451 * history buffer, and potentially other undesired outcomes.
16452 * It is expected that with correct open-coded iterators
16453 * convergence will happen quickly, so we don't run a risk of
16454 * exhausting memory.
16456 mark_force_checkpoint(env, t);
16459 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
16462 if (BPF_SRC(insn->code) != BPF_K)
16465 if (BPF_CLASS(insn->code) == BPF_JMP)
16470 /* unconditional jump with single edge */
16471 ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
16475 mark_prune_point(env, t + off + 1);
16476 mark_jmp_point(env, t + off + 1);
16481 /* conditional jump with two edges */
16482 mark_prune_point(env, t);
16483 if (is_may_goto_insn(insn))
16484 mark_force_checkpoint(env, t);
16486 ret = push_insn(t, t + 1, FALLTHROUGH, env);
16490 return push_insn(t, t + insn->off + 1, BRANCH, env);
16494 /* non-recursive depth-first-search to detect loops in BPF program
16495 * loop == back-edge in directed graph
16497 static int check_cfg(struct bpf_verifier_env *env)
16499 int insn_cnt = env->prog->len;
16500 int *insn_stack, *insn_state;
16501 int ex_insn_beg, i, ret = 0;
16502 bool ex_done = false;
16504 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
16508 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
16510 kvfree(insn_state);
16514 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
16515 insn_stack[0] = 0; /* 0 is the first instruction */
16516 env->cfg.cur_stack = 1;
16519 while (env->cfg.cur_stack > 0) {
16520 int t = insn_stack[env->cfg.cur_stack - 1];
16522 ret = visit_insn(t, env);
16524 case DONE_EXPLORING:
16525 insn_state[t] = EXPLORED;
16526 env->cfg.cur_stack--;
16528 case KEEP_EXPLORING:
16532 verbose(env, "visit_insn internal bug\n");
16539 if (env->cfg.cur_stack < 0) {
16540 verbose(env, "pop stack internal bug\n");
16545 if (env->exception_callback_subprog && !ex_done) {
16546 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
16548 insn_state[ex_insn_beg] = DISCOVERED;
16549 insn_stack[0] = ex_insn_beg;
16550 env->cfg.cur_stack = 1;
16555 for (i = 0; i < insn_cnt; i++) {
16556 struct bpf_insn *insn = &env->prog->insnsi[i];
16558 if (insn_state[i] != EXPLORED) {
16559 verbose(env, "unreachable insn %d\n", i);
16563 if (bpf_is_ldimm64(insn)) {
16564 if (insn_state[i + 1] != 0) {
16565 verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
16569 i++; /* skip second half of ldimm64 */
16572 ret = 0; /* cfg looks good */
16575 kvfree(insn_state);
16576 kvfree(insn_stack);
16577 env->cfg.insn_state = env->cfg.insn_stack = NULL;
16581 static int check_abnormal_return(struct bpf_verifier_env *env)
16585 for (i = 1; i < env->subprog_cnt; i++) {
16586 if (env->subprog_info[i].has_ld_abs) {
16587 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
16590 if (env->subprog_info[i].has_tail_call) {
16591 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
16598 /* The minimum supported BTF func info size */
16599 #define MIN_BPF_FUNCINFO_SIZE 8
16600 #define MAX_FUNCINFO_REC_SIZE 252
16602 static int check_btf_func_early(struct bpf_verifier_env *env,
16603 const union bpf_attr *attr,
16606 u32 krec_size = sizeof(struct bpf_func_info);
16607 const struct btf_type *type, *func_proto;
16608 u32 i, nfuncs, urec_size, min_size;
16609 struct bpf_func_info *krecord;
16610 struct bpf_prog *prog;
16611 const struct btf *btf;
16612 u32 prev_offset = 0;
16616 nfuncs = attr->func_info_cnt;
16618 if (check_abnormal_return(env))
16623 urec_size = attr->func_info_rec_size;
16624 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
16625 urec_size > MAX_FUNCINFO_REC_SIZE ||
16626 urec_size % sizeof(u32)) {
16627 verbose(env, "invalid func info rec size %u\n", urec_size);
16632 btf = prog->aux->btf;
16634 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
16635 min_size = min_t(u32, krec_size, urec_size);
16637 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
16641 for (i = 0; i < nfuncs; i++) {
16642 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
16644 if (ret == -E2BIG) {
16645 verbose(env, "nonzero tailing record in func info");
16646 /* set the size kernel expects so loader can zero
16647 * out the rest of the record.
16649 if (copy_to_bpfptr_offset(uattr,
16650 offsetof(union bpf_attr, func_info_rec_size),
16651 &min_size, sizeof(min_size)))
16657 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
16662 /* check insn_off */
16665 if (krecord[i].insn_off) {
16667 "nonzero insn_off %u for the first func info record",
16668 krecord[i].insn_off);
16671 } else if (krecord[i].insn_off <= prev_offset) {
16673 "same or smaller insn offset (%u) than previous func info record (%u)",
16674 krecord[i].insn_off, prev_offset);
16678 /* check type_id */
16679 type = btf_type_by_id(btf, krecord[i].type_id);
16680 if (!type || !btf_type_is_func(type)) {
16681 verbose(env, "invalid type id %d in func info",
16682 krecord[i].type_id);
16686 func_proto = btf_type_by_id(btf, type->type);
16687 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
16688 /* btf_func_check() already verified it during BTF load */
16691 prev_offset = krecord[i].insn_off;
16692 bpfptr_add(&urecord, urec_size);
16695 prog->aux->func_info = krecord;
16696 prog->aux->func_info_cnt = nfuncs;
16704 static int check_btf_func(struct bpf_verifier_env *env,
16705 const union bpf_attr *attr,
16708 const struct btf_type *type, *func_proto, *ret_type;
16709 u32 i, nfuncs, urec_size;
16710 struct bpf_func_info *krecord;
16711 struct bpf_func_info_aux *info_aux = NULL;
16712 struct bpf_prog *prog;
16713 const struct btf *btf;
16715 bool scalar_return;
16718 nfuncs = attr->func_info_cnt;
16720 if (check_abnormal_return(env))
16724 if (nfuncs != env->subprog_cnt) {
16725 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
16729 urec_size = attr->func_info_rec_size;
16732 btf = prog->aux->btf;
16734 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
16736 krecord = prog->aux->func_info;
16737 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
16741 for (i = 0; i < nfuncs; i++) {
16742 /* check insn_off */
16745 if (env->subprog_info[i].start != krecord[i].insn_off) {
16746 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
16750 /* Already checked type_id */
16751 type = btf_type_by_id(btf, krecord[i].type_id);
16752 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
16753 /* Already checked func_proto */
16754 func_proto = btf_type_by_id(btf, type->type);
16756 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
16758 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
16759 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
16760 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
16763 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
16764 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
16768 bpfptr_add(&urecord, urec_size);
16771 prog->aux->func_info_aux = info_aux;
16779 static void adjust_btf_func(struct bpf_verifier_env *env)
16781 struct bpf_prog_aux *aux = env->prog->aux;
16784 if (!aux->func_info)
16787 /* func_info is not available for hidden subprogs */
16788 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
16789 aux->func_info[i].insn_off = env->subprog_info[i].start;
16792 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
16793 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
16795 static int check_btf_line(struct bpf_verifier_env *env,
16796 const union bpf_attr *attr,
16799 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
16800 struct bpf_subprog_info *sub;
16801 struct bpf_line_info *linfo;
16802 struct bpf_prog *prog;
16803 const struct btf *btf;
16807 nr_linfo = attr->line_info_cnt;
16810 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
16813 rec_size = attr->line_info_rec_size;
16814 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
16815 rec_size > MAX_LINEINFO_REC_SIZE ||
16816 rec_size & (sizeof(u32) - 1))
16819 /* Need to zero it in case the userspace may
16820 * pass in a smaller bpf_line_info object.
16822 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
16823 GFP_KERNEL | __GFP_NOWARN);
16828 btf = prog->aux->btf;
16831 sub = env->subprog_info;
16832 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
16833 expected_size = sizeof(struct bpf_line_info);
16834 ncopy = min_t(u32, expected_size, rec_size);
16835 for (i = 0; i < nr_linfo; i++) {
16836 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
16838 if (err == -E2BIG) {
16839 verbose(env, "nonzero tailing record in line_info");
16840 if (copy_to_bpfptr_offset(uattr,
16841 offsetof(union bpf_attr, line_info_rec_size),
16842 &expected_size, sizeof(expected_size)))
16848 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
16854 * Check insn_off to ensure
16855 * 1) strictly increasing AND
16856 * 2) bounded by prog->len
16858 * The linfo[0].insn_off == 0 check logically falls into
16859 * the later "missing bpf_line_info for func..." case
16860 * because the first linfo[0].insn_off must be the
16861 * first sub also and the first sub must have
16862 * subprog_info[0].start == 0.
16864 if ((i && linfo[i].insn_off <= prev_offset) ||
16865 linfo[i].insn_off >= prog->len) {
16866 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
16867 i, linfo[i].insn_off, prev_offset,
16873 if (!prog->insnsi[linfo[i].insn_off].code) {
16875 "Invalid insn code at line_info[%u].insn_off\n",
16881 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
16882 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
16883 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
16888 if (s != env->subprog_cnt) {
16889 if (linfo[i].insn_off == sub[s].start) {
16890 sub[s].linfo_idx = i;
16892 } else if (sub[s].start < linfo[i].insn_off) {
16893 verbose(env, "missing bpf_line_info for func#%u\n", s);
16899 prev_offset = linfo[i].insn_off;
16900 bpfptr_add(&ulinfo, rec_size);
16903 if (s != env->subprog_cnt) {
16904 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
16905 env->subprog_cnt - s, s);
16910 prog->aux->linfo = linfo;
16911 prog->aux->nr_linfo = nr_linfo;
16920 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
16921 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
16923 static int check_core_relo(struct bpf_verifier_env *env,
16924 const union bpf_attr *attr,
16927 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
16928 struct bpf_core_relo core_relo = {};
16929 struct bpf_prog *prog = env->prog;
16930 const struct btf *btf = prog->aux->btf;
16931 struct bpf_core_ctx ctx = {
16935 bpfptr_t u_core_relo;
16938 nr_core_relo = attr->core_relo_cnt;
16941 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
16944 rec_size = attr->core_relo_rec_size;
16945 if (rec_size < MIN_CORE_RELO_SIZE ||
16946 rec_size > MAX_CORE_RELO_SIZE ||
16947 rec_size % sizeof(u32))
16950 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
16951 expected_size = sizeof(struct bpf_core_relo);
16952 ncopy = min_t(u32, expected_size, rec_size);
16954 /* Unlike func_info and line_info, copy and apply each CO-RE
16955 * relocation record one at a time.
16957 for (i = 0; i < nr_core_relo; i++) {
16958 /* future proofing when sizeof(bpf_core_relo) changes */
16959 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
16961 if (err == -E2BIG) {
16962 verbose(env, "nonzero tailing record in core_relo");
16963 if (copy_to_bpfptr_offset(uattr,
16964 offsetof(union bpf_attr, core_relo_rec_size),
16965 &expected_size, sizeof(expected_size)))
16971 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16976 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16977 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16978 i, core_relo.insn_off, prog->len);
16983 err = bpf_core_apply(&ctx, &core_relo, i,
16984 &prog->insnsi[core_relo.insn_off / 8]);
16987 bpfptr_add(&u_core_relo, rec_size);
16992 static int check_btf_info_early(struct bpf_verifier_env *env,
16993 const union bpf_attr *attr,
16999 if (!attr->func_info_cnt && !attr->line_info_cnt) {
17000 if (check_abnormal_return(env))
17005 btf = btf_get_by_fd(attr->prog_btf_fd);
17007 return PTR_ERR(btf);
17008 if (btf_is_kernel(btf)) {
17012 env->prog->aux->btf = btf;
17014 err = check_btf_func_early(env, attr, uattr);
17020 static int check_btf_info(struct bpf_verifier_env *env,
17021 const union bpf_attr *attr,
17026 if (!attr->func_info_cnt && !attr->line_info_cnt) {
17027 if (check_abnormal_return(env))
17032 err = check_btf_func(env, attr, uattr);
17036 err = check_btf_line(env, attr, uattr);
17040 err = check_core_relo(env, attr, uattr);
17047 /* check %cur's range satisfies %old's */
17048 static bool range_within(const struct bpf_reg_state *old,
17049 const struct bpf_reg_state *cur)
17051 return old->umin_value <= cur->umin_value &&
17052 old->umax_value >= cur->umax_value &&
17053 old->smin_value <= cur->smin_value &&
17054 old->smax_value >= cur->smax_value &&
17055 old->u32_min_value <= cur->u32_min_value &&
17056 old->u32_max_value >= cur->u32_max_value &&
17057 old->s32_min_value <= cur->s32_min_value &&
17058 old->s32_max_value >= cur->s32_max_value;
17061 /* If in the old state two registers had the same id, then they need to have
17062 * the same id in the new state as well. But that id could be different from
17063 * the old state, so we need to track the mapping from old to new ids.
17064 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
17065 * regs with old id 5 must also have new id 9 for the new state to be safe. But
17066 * regs with a different old id could still have new id 9, we don't care about
17068 * So we look through our idmap to see if this old id has been seen before. If
17069 * so, we require the new id to match; otherwise, we add the id pair to the map.
17071 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
17073 struct bpf_id_pair *map = idmap->map;
17076 /* either both IDs should be set or both should be zero */
17077 if (!!old_id != !!cur_id)
17080 if (old_id == 0) /* cur_id == 0 as well */
17083 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
17085 /* Reached an empty slot; haven't seen this id before */
17086 map[i].old = old_id;
17087 map[i].cur = cur_id;
17090 if (map[i].old == old_id)
17091 return map[i].cur == cur_id;
17092 if (map[i].cur == cur_id)
17095 /* We ran out of idmap slots, which should be impossible */
17100 /* Similar to check_ids(), but allocate a unique temporary ID
17101 * for 'old_id' or 'cur_id' of zero.
17102 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
17104 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
17106 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
17107 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
17109 return check_ids(old_id, cur_id, idmap);
17112 static void clean_func_state(struct bpf_verifier_env *env,
17113 struct bpf_func_state *st)
17115 enum bpf_reg_liveness live;
17118 for (i = 0; i < BPF_REG_FP; i++) {
17119 live = st->regs[i].live;
17120 /* liveness must not touch this register anymore */
17121 st->regs[i].live |= REG_LIVE_DONE;
17122 if (!(live & REG_LIVE_READ))
17123 /* since the register is unused, clear its state
17124 * to make further comparison simpler
17126 __mark_reg_not_init(env, &st->regs[i]);
17129 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
17130 live = st->stack[i].spilled_ptr.live;
17131 /* liveness must not touch this stack slot anymore */
17132 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
17133 if (!(live & REG_LIVE_READ)) {
17134 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
17135 for (j = 0; j < BPF_REG_SIZE; j++)
17136 st->stack[i].slot_type[j] = STACK_INVALID;
17141 static void clean_verifier_state(struct bpf_verifier_env *env,
17142 struct bpf_verifier_state *st)
17146 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
17147 /* all regs in this state in all frames were already marked */
17150 for (i = 0; i <= st->curframe; i++)
17151 clean_func_state(env, st->frame[i]);
17154 /* the parentage chains form a tree.
17155 * the verifier states are added to state lists at given insn and
17156 * pushed into state stack for future exploration.
17157 * when the verifier reaches bpf_exit insn some of the verifer states
17158 * stored in the state lists have their final liveness state already,
17159 * but a lot of states will get revised from liveness point of view when
17160 * the verifier explores other branches.
17163 * 2: if r1 == 100 goto pc+1
17166 * when the verifier reaches exit insn the register r0 in the state list of
17167 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
17168 * of insn 2 and goes exploring further. At the insn 4 it will walk the
17169 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
17171 * Since the verifier pushes the branch states as it sees them while exploring
17172 * the program the condition of walking the branch instruction for the second
17173 * time means that all states below this branch were already explored and
17174 * their final liveness marks are already propagated.
17175 * Hence when the verifier completes the search of state list in is_state_visited()
17176 * we can call this clean_live_states() function to mark all liveness states
17177 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
17178 * will not be used.
17179 * This function also clears the registers and stack for states that !READ
17180 * to simplify state merging.
17182 * Important note here that walking the same branch instruction in the callee
17183 * doesn't meant that the states are DONE. The verifier has to compare
17186 static void clean_live_states(struct bpf_verifier_env *env, int insn,
17187 struct bpf_verifier_state *cur)
17189 struct bpf_verifier_state_list *sl;
17191 sl = *explored_state(env, insn);
17193 if (sl->state.branches)
17195 if (sl->state.insn_idx != insn ||
17196 !same_callsites(&sl->state, cur))
17198 clean_verifier_state(env, &sl->state);
17204 static bool regs_exact(const struct bpf_reg_state *rold,
17205 const struct bpf_reg_state *rcur,
17206 struct bpf_idmap *idmap)
17208 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
17209 check_ids(rold->id, rcur->id, idmap) &&
17210 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
17219 /* Returns true if (rold safe implies rcur safe) */
17220 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
17221 struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
17222 enum exact_level exact)
17224 if (exact == EXACT)
17225 return regs_exact(rold, rcur, idmap);
17227 if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT)
17228 /* explored state didn't use this */
17230 if (rold->type == NOT_INIT) {
17231 if (exact == NOT_EXACT || rcur->type == NOT_INIT)
17232 /* explored state can't have used this */
17236 /* Enforce that register types have to match exactly, including their
17237 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
17240 * One can make a point that using a pointer register as unbounded
17241 * SCALAR would be technically acceptable, but this could lead to
17242 * pointer leaks because scalars are allowed to leak while pointers
17243 * are not. We could make this safe in special cases if root is
17244 * calling us, but it's probably not worth the hassle.
17246 * Also, register types that are *not* MAYBE_NULL could technically be
17247 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
17248 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
17249 * to the same map).
17250 * However, if the old MAYBE_NULL register then got NULL checked,
17251 * doing so could have affected others with the same id, and we can't
17252 * check for that because we lost the id when we converted to
17253 * a non-MAYBE_NULL variant.
17254 * So, as a general rule we don't allow mixing MAYBE_NULL and
17255 * non-MAYBE_NULL registers as well.
17257 if (rold->type != rcur->type)
17260 switch (base_type(rold->type)) {
17262 if (env->explore_alu_limits) {
17263 /* explore_alu_limits disables tnum_in() and range_within()
17264 * logic and requires everything to be strict
17266 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
17267 check_scalar_ids(rold->id, rcur->id, idmap);
17269 if (!rold->precise && exact == NOT_EXACT)
17271 if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
17273 if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
17275 /* Why check_ids() for scalar registers?
17277 * Consider the following BPF code:
17278 * 1: r6 = ... unbound scalar, ID=a ...
17279 * 2: r7 = ... unbound scalar, ID=b ...
17280 * 3: if (r6 > r7) goto +1
17282 * 5: if (r6 > X) goto ...
17283 * 6: ... memory operation using r7 ...
17285 * First verification path is [1-6]:
17286 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
17287 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
17288 * r7 <= X, because r6 and r7 share same id.
17289 * Next verification path is [1-4, 6].
17291 * Instruction (6) would be reached in two states:
17292 * I. r6{.id=b}, r7{.id=b} via path 1-6;
17293 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
17295 * Use check_ids() to distinguish these states.
17297 * Also verify that new value satisfies old value range knowledge.
17299 return range_within(rold, rcur) &&
17300 tnum_in(rold->var_off, rcur->var_off) &&
17301 check_scalar_ids(rold->id, rcur->id, idmap);
17302 case PTR_TO_MAP_KEY:
17303 case PTR_TO_MAP_VALUE:
17306 case PTR_TO_TP_BUFFER:
17307 /* If the new min/max/var_off satisfy the old ones and
17308 * everything else matches, we are OK.
17310 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
17311 range_within(rold, rcur) &&
17312 tnum_in(rold->var_off, rcur->var_off) &&
17313 check_ids(rold->id, rcur->id, idmap) &&
17314 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
17315 case PTR_TO_PACKET_META:
17316 case PTR_TO_PACKET:
17317 /* We must have at least as much range as the old ptr
17318 * did, so that any accesses which were safe before are
17319 * still safe. This is true even if old range < old off,
17320 * since someone could have accessed through (ptr - k), or
17321 * even done ptr -= k in a register, to get a safe access.
17323 if (rold->range > rcur->range)
17325 /* If the offsets don't match, we can't trust our alignment;
17326 * nor can we be sure that we won't fall out of range.
17328 if (rold->off != rcur->off)
17330 /* id relations must be preserved */
17331 if (!check_ids(rold->id, rcur->id, idmap))
17333 /* new val must satisfy old val knowledge */
17334 return range_within(rold, rcur) &&
17335 tnum_in(rold->var_off, rcur->var_off);
17337 /* two stack pointers are equal only if they're pointing to
17338 * the same stack frame, since fp-8 in foo != fp-8 in bar
17340 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
17344 return regs_exact(rold, rcur, idmap);
17348 static struct bpf_reg_state unbound_reg;
17350 static __init int unbound_reg_init(void)
17352 __mark_reg_unknown_imprecise(&unbound_reg);
17353 unbound_reg.live |= REG_LIVE_READ;
17356 late_initcall(unbound_reg_init);
17358 static bool is_stack_all_misc(struct bpf_verifier_env *env,
17359 struct bpf_stack_state *stack)
17363 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
17364 if ((stack->slot_type[i] == STACK_MISC) ||
17365 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
17373 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
17374 struct bpf_stack_state *stack)
17376 if (is_spilled_scalar_reg64(stack))
17377 return &stack->spilled_ptr;
17379 if (is_stack_all_misc(env, stack))
17380 return &unbound_reg;
17385 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
17386 struct bpf_func_state *cur, struct bpf_idmap *idmap,
17387 enum exact_level exact)
17391 /* walk slots of the explored stack and ignore any additional
17392 * slots in the current stack, since explored(safe) state
17395 for (i = 0; i < old->allocated_stack; i++) {
17396 struct bpf_reg_state *old_reg, *cur_reg;
17398 spi = i / BPF_REG_SIZE;
17400 if (exact != NOT_EXACT &&
17401 (i >= cur->allocated_stack ||
17402 old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
17403 cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
17406 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)
17407 && exact == NOT_EXACT) {
17408 i += BPF_REG_SIZE - 1;
17409 /* explored state didn't use this */
17413 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
17416 if (env->allow_uninit_stack &&
17417 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
17420 /* explored stack has more populated slots than current stack
17421 * and these slots were used
17423 if (i >= cur->allocated_stack)
17426 /* 64-bit scalar spill vs all slots MISC and vice versa.
17427 * Load from all slots MISC produces unbound scalar.
17428 * Construct a fake register for such stack and call
17429 * regsafe() to ensure scalar ids are compared.
17431 old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
17432 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
17433 if (old_reg && cur_reg) {
17434 if (!regsafe(env, old_reg, cur_reg, idmap, exact))
17436 i += BPF_REG_SIZE - 1;
17440 /* if old state was safe with misc data in the stack
17441 * it will be safe with zero-initialized stack.
17442 * The opposite is not true
17444 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
17445 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
17447 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
17448 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
17449 /* Ex: old explored (safe) state has STACK_SPILL in
17450 * this stack slot, but current has STACK_MISC ->
17451 * this verifier states are not equivalent,
17452 * return false to continue verification of this path
17455 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
17457 /* Both old and cur are having same slot_type */
17458 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
17460 /* when explored and current stack slot are both storing
17461 * spilled registers, check that stored pointers types
17462 * are the same as well.
17463 * Ex: explored safe path could have stored
17464 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
17465 * but current path has stored:
17466 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
17467 * such verifier states are not equivalent.
17468 * return false to continue verification of this path
17470 if (!regsafe(env, &old->stack[spi].spilled_ptr,
17471 &cur->stack[spi].spilled_ptr, idmap, exact))
17475 old_reg = &old->stack[spi].spilled_ptr;
17476 cur_reg = &cur->stack[spi].spilled_ptr;
17477 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
17478 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
17479 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
17483 old_reg = &old->stack[spi].spilled_ptr;
17484 cur_reg = &cur->stack[spi].spilled_ptr;
17485 /* iter.depth is not compared between states as it
17486 * doesn't matter for correctness and would otherwise
17487 * prevent convergence; we maintain it only to prevent
17488 * infinite loop check triggering, see
17489 * iter_active_depths_differ()
17491 if (old_reg->iter.btf != cur_reg->iter.btf ||
17492 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
17493 old_reg->iter.state != cur_reg->iter.state ||
17494 /* ignore {old_reg,cur_reg}->iter.depth, see above */
17495 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
17500 case STACK_INVALID:
17502 /* Ensure that new unhandled slot types return false by default */
17510 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
17511 struct bpf_idmap *idmap)
17515 if (old->acquired_refs != cur->acquired_refs)
17518 for (i = 0; i < old->acquired_refs; i++) {
17519 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
17526 /* compare two verifier states
17528 * all states stored in state_list are known to be valid, since
17529 * verifier reached 'bpf_exit' instruction through them
17531 * this function is called when verifier exploring different branches of
17532 * execution popped from the state stack. If it sees an old state that has
17533 * more strict register state and more strict stack state then this execution
17534 * branch doesn't need to be explored further, since verifier already
17535 * concluded that more strict state leads to valid finish.
17537 * Therefore two states are equivalent if register state is more conservative
17538 * and explored stack state is more conservative than the current one.
17541 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
17542 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
17544 * In other words if current stack state (one being explored) has more
17545 * valid slots than old one that already passed validation, it means
17546 * the verifier can stop exploring and conclude that current state is valid too
17548 * Similarly with registers. If explored state has register type as invalid
17549 * whereas register type in current state is meaningful, it means that
17550 * the current state will reach 'bpf_exit' instruction safely
17552 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
17553 struct bpf_func_state *cur, enum exact_level exact)
17557 if (old->callback_depth > cur->callback_depth)
17560 for (i = 0; i < MAX_BPF_REG; i++)
17561 if (!regsafe(env, &old->regs[i], &cur->regs[i],
17562 &env->idmap_scratch, exact))
17565 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
17568 if (!refsafe(old, cur, &env->idmap_scratch))
17574 static void reset_idmap_scratch(struct bpf_verifier_env *env)
17576 env->idmap_scratch.tmp_id_gen = env->id_gen;
17577 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
17580 static bool states_equal(struct bpf_verifier_env *env,
17581 struct bpf_verifier_state *old,
17582 struct bpf_verifier_state *cur,
17583 enum exact_level exact)
17587 if (old->curframe != cur->curframe)
17590 reset_idmap_scratch(env);
17592 /* Verification state from speculative execution simulation
17593 * must never prune a non-speculative execution one.
17595 if (old->speculative && !cur->speculative)
17598 if (old->active_lock.ptr != cur->active_lock.ptr)
17601 /* Old and cur active_lock's have to be either both present
17604 if (!!old->active_lock.id != !!cur->active_lock.id)
17607 if (old->active_lock.id &&
17608 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
17611 if (old->active_rcu_lock != cur->active_rcu_lock)
17614 if (old->active_preempt_lock != cur->active_preempt_lock)
17617 if (old->in_sleepable != cur->in_sleepable)
17620 /* for states to be equal callsites have to be the same
17621 * and all frame states need to be equivalent
17623 for (i = 0; i <= old->curframe; i++) {
17624 if (old->frame[i]->callsite != cur->frame[i]->callsite)
17626 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
17632 /* Return 0 if no propagation happened. Return negative error code if error
17633 * happened. Otherwise, return the propagated bit.
17635 static int propagate_liveness_reg(struct bpf_verifier_env *env,
17636 struct bpf_reg_state *reg,
17637 struct bpf_reg_state *parent_reg)
17639 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
17640 u8 flag = reg->live & REG_LIVE_READ;
17643 /* When comes here, read flags of PARENT_REG or REG could be any of
17644 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
17645 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
17647 if (parent_flag == REG_LIVE_READ64 ||
17648 /* Or if there is no read flag from REG. */
17650 /* Or if the read flag from REG is the same as PARENT_REG. */
17651 parent_flag == flag)
17654 err = mark_reg_read(env, reg, parent_reg, flag);
17661 /* A write screens off any subsequent reads; but write marks come from the
17662 * straight-line code between a state and its parent. When we arrive at an
17663 * equivalent state (jump target or such) we didn't arrive by the straight-line
17664 * code, so read marks in the state must propagate to the parent regardless
17665 * of the state's write marks. That's what 'parent == state->parent' comparison
17666 * in mark_reg_read() is for.
17668 static int propagate_liveness(struct bpf_verifier_env *env,
17669 const struct bpf_verifier_state *vstate,
17670 struct bpf_verifier_state *vparent)
17672 struct bpf_reg_state *state_reg, *parent_reg;
17673 struct bpf_func_state *state, *parent;
17674 int i, frame, err = 0;
17676 if (vparent->curframe != vstate->curframe) {
17677 WARN(1, "propagate_live: parent frame %d current frame %d\n",
17678 vparent->curframe, vstate->curframe);
17681 /* Propagate read liveness of registers... */
17682 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
17683 for (frame = 0; frame <= vstate->curframe; frame++) {
17684 parent = vparent->frame[frame];
17685 state = vstate->frame[frame];
17686 parent_reg = parent->regs;
17687 state_reg = state->regs;
17688 /* We don't need to worry about FP liveness, it's read-only */
17689 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
17690 err = propagate_liveness_reg(env, &state_reg[i],
17694 if (err == REG_LIVE_READ64)
17695 mark_insn_zext(env, &parent_reg[i]);
17698 /* Propagate stack slots. */
17699 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
17700 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
17701 parent_reg = &parent->stack[i].spilled_ptr;
17702 state_reg = &state->stack[i].spilled_ptr;
17703 err = propagate_liveness_reg(env, state_reg,
17712 /* find precise scalars in the previous equivalent state and
17713 * propagate them into the current state
17715 static int propagate_precision(struct bpf_verifier_env *env,
17716 const struct bpf_verifier_state *old)
17718 struct bpf_reg_state *state_reg;
17719 struct bpf_func_state *state;
17720 int i, err = 0, fr;
17723 for (fr = old->curframe; fr >= 0; fr--) {
17724 state = old->frame[fr];
17725 state_reg = state->regs;
17727 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
17728 if (state_reg->type != SCALAR_VALUE ||
17729 !state_reg->precise ||
17730 !(state_reg->live & REG_LIVE_READ))
17732 if (env->log.level & BPF_LOG_LEVEL2) {
17734 verbose(env, "frame %d: propagating r%d", fr, i);
17736 verbose(env, ",r%d", i);
17738 bt_set_frame_reg(&env->bt, fr, i);
17742 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17743 if (!is_spilled_reg(&state->stack[i]))
17745 state_reg = &state->stack[i].spilled_ptr;
17746 if (state_reg->type != SCALAR_VALUE ||
17747 !state_reg->precise ||
17748 !(state_reg->live & REG_LIVE_READ))
17750 if (env->log.level & BPF_LOG_LEVEL2) {
17752 verbose(env, "frame %d: propagating fp%d",
17753 fr, (-i - 1) * BPF_REG_SIZE);
17755 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
17757 bt_set_frame_slot(&env->bt, fr, i);
17761 verbose(env, "\n");
17764 err = mark_chain_precision_batch(env);
17771 static bool states_maybe_looping(struct bpf_verifier_state *old,
17772 struct bpf_verifier_state *cur)
17774 struct bpf_func_state *fold, *fcur;
17775 int i, fr = cur->curframe;
17777 if (old->curframe != fr)
17780 fold = old->frame[fr];
17781 fcur = cur->frame[fr];
17782 for (i = 0; i < MAX_BPF_REG; i++)
17783 if (memcmp(&fold->regs[i], &fcur->regs[i],
17784 offsetof(struct bpf_reg_state, parent)))
17789 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
17791 return env->insn_aux_data[insn_idx].is_iter_next;
17794 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
17795 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
17796 * states to match, which otherwise would look like an infinite loop. So while
17797 * iter_next() calls are taken care of, we still need to be careful and
17798 * prevent erroneous and too eager declaration of "ininite loop", when
17799 * iterators are involved.
17801 * Here's a situation in pseudo-BPF assembly form:
17803 * 0: again: ; set up iter_next() call args
17804 * 1: r1 = &it ; <CHECKPOINT HERE>
17805 * 2: call bpf_iter_num_next ; this is iter_next() call
17806 * 3: if r0 == 0 goto done
17807 * 4: ... something useful here ...
17808 * 5: goto again ; another iteration
17811 * 8: call bpf_iter_num_destroy ; clean up iter state
17814 * This is a typical loop. Let's assume that we have a prune point at 1:,
17815 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
17816 * again`, assuming other heuristics don't get in a way).
17818 * When we first time come to 1:, let's say we have some state X. We proceed
17819 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
17820 * Now we come back to validate that forked ACTIVE state. We proceed through
17821 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
17822 * are converging. But the problem is that we don't know that yet, as this
17823 * convergence has to happen at iter_next() call site only. So if nothing is
17824 * done, at 1: verifier will use bounded loop logic and declare infinite
17825 * looping (and would be *technically* correct, if not for iterator's
17826 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
17827 * don't want that. So what we do in process_iter_next_call() when we go on
17828 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
17829 * a different iteration. So when we suspect an infinite loop, we additionally
17830 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
17831 * pretend we are not looping and wait for next iter_next() call.
17833 * This only applies to ACTIVE state. In DRAINED state we don't expect to
17834 * loop, because that would actually mean infinite loop, as DRAINED state is
17835 * "sticky", and so we'll keep returning into the same instruction with the
17836 * same state (at least in one of possible code paths).
17838 * This approach allows to keep infinite loop heuristic even in the face of
17839 * active iterator. E.g., C snippet below is and will be detected as
17840 * inifintely looping:
17842 * struct bpf_iter_num it;
17845 * bpf_iter_num_new(&it, 0, 10);
17846 * while ((p = bpf_iter_num_next(&t))) {
17848 * while (x--) {} // <<-- infinite loop here
17852 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
17854 struct bpf_reg_state *slot, *cur_slot;
17855 struct bpf_func_state *state;
17858 for (fr = old->curframe; fr >= 0; fr--) {
17859 state = old->frame[fr];
17860 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17861 if (state->stack[i].slot_type[0] != STACK_ITER)
17864 slot = &state->stack[i].spilled_ptr;
17865 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
17868 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
17869 if (cur_slot->iter.depth != slot->iter.depth)
17876 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
17878 struct bpf_verifier_state_list *new_sl;
17879 struct bpf_verifier_state_list *sl, **pprev;
17880 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
17881 int i, j, n, err, states_cnt = 0;
17882 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
17883 bool add_new_state = force_new_state;
17886 /* bpf progs typically have pruning point every 4 instructions
17887 * http://vger.kernel.org/bpfconf2019.html#session-1
17888 * Do not add new state for future pruning if the verifier hasn't seen
17889 * at least 2 jumps and at least 8 instructions.
17890 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
17891 * In tests that amounts to up to 50% reduction into total verifier
17892 * memory consumption and 20% verifier time speedup.
17894 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
17895 env->insn_processed - env->prev_insn_processed >= 8)
17896 add_new_state = true;
17898 pprev = explored_state(env, insn_idx);
17901 clean_live_states(env, insn_idx, cur);
17905 if (sl->state.insn_idx != insn_idx)
17908 if (sl->state.branches) {
17909 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
17911 if (frame->in_async_callback_fn &&
17912 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
17913 /* Different async_entry_cnt means that the verifier is
17914 * processing another entry into async callback.
17915 * Seeing the same state is not an indication of infinite
17916 * loop or infinite recursion.
17917 * But finding the same state doesn't mean that it's safe
17918 * to stop processing the current state. The previous state
17919 * hasn't yet reached bpf_exit, since state.branches > 0.
17920 * Checking in_async_callback_fn alone is not enough either.
17921 * Since the verifier still needs to catch infinite loops
17922 * inside async callbacks.
17924 goto skip_inf_loop_check;
17926 /* BPF open-coded iterators loop detection is special.
17927 * states_maybe_looping() logic is too simplistic in detecting
17928 * states that *might* be equivalent, because it doesn't know
17929 * about ID remapping, so don't even perform it.
17930 * See process_iter_next_call() and iter_active_depths_differ()
17931 * for overview of the logic. When current and one of parent
17932 * states are detected as equivalent, it's a good thing: we prove
17933 * convergence and can stop simulating further iterations.
17934 * It's safe to assume that iterator loop will finish, taking into
17935 * account iter_next() contract of eventually returning
17936 * sticky NULL result.
17938 * Note, that states have to be compared exactly in this case because
17939 * read and precision marks might not be finalized inside the loop.
17940 * E.g. as in the program below:
17943 * 2. r6 = bpf_get_prandom_u32()
17944 * 3. while (bpf_iter_num_next(&fp[-8])) {
17945 * 4. if (r6 != 42) {
17947 * 6. r6 = bpf_get_prandom_u32()
17952 * 11. r8 = *(u64 *)(r0 + 0)
17953 * 12. r6 = bpf_get_prandom_u32()
17956 * Here verifier would first visit path 1-3, create a checkpoint at 3
17957 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
17958 * not have read or precision mark for r7 yet, thus inexact states
17959 * comparison would discard current state with r7=-32
17960 * => unsafe memory access at 11 would not be caught.
17962 if (is_iter_next_insn(env, insn_idx)) {
17963 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
17964 struct bpf_func_state *cur_frame;
17965 struct bpf_reg_state *iter_state, *iter_reg;
17968 cur_frame = cur->frame[cur->curframe];
17969 /* btf_check_iter_kfuncs() enforces that
17970 * iter state pointer is always the first arg
17972 iter_reg = &cur_frame->regs[BPF_REG_1];
17973 /* current state is valid due to states_equal(),
17974 * so we can assume valid iter and reg state,
17975 * no need for extra (re-)validations
17977 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
17978 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
17979 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
17980 update_loop_entry(cur, &sl->state);
17984 goto skip_inf_loop_check;
17986 if (is_may_goto_insn_at(env, insn_idx)) {
17987 if (sl->state.may_goto_depth != cur->may_goto_depth &&
17988 states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
17989 update_loop_entry(cur, &sl->state);
17993 if (calls_callback(env, insn_idx)) {
17994 if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
17996 goto skip_inf_loop_check;
17998 /* attempt to detect infinite loop to avoid unnecessary doomed work */
17999 if (states_maybe_looping(&sl->state, cur) &&
18000 states_equal(env, &sl->state, cur, EXACT) &&
18001 !iter_active_depths_differ(&sl->state, cur) &&
18002 sl->state.may_goto_depth == cur->may_goto_depth &&
18003 sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
18004 verbose_linfo(env, insn_idx, "; ");
18005 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
18006 verbose(env, "cur state:");
18007 print_verifier_state(env, cur->frame[cur->curframe], true);
18008 verbose(env, "old state:");
18009 print_verifier_state(env, sl->state.frame[cur->curframe], true);
18012 /* if the verifier is processing a loop, avoid adding new state
18013 * too often, since different loop iterations have distinct
18014 * states and may not help future pruning.
18015 * This threshold shouldn't be too low to make sure that
18016 * a loop with large bound will be rejected quickly.
18017 * The most abusive loop will be:
18019 * if r1 < 1000000 goto pc-2
18020 * 1M insn_procssed limit / 100 == 10k peak states.
18021 * This threshold shouldn't be too high either, since states
18022 * at the end of the loop are likely to be useful in pruning.
18024 skip_inf_loop_check:
18025 if (!force_new_state &&
18026 env->jmps_processed - env->prev_jmps_processed < 20 &&
18027 env->insn_processed - env->prev_insn_processed < 100)
18028 add_new_state = false;
18031 /* If sl->state is a part of a loop and this loop's entry is a part of
18032 * current verification path then states have to be compared exactly.
18033 * 'force_exact' is needed to catch the following case:
18035 * initial Here state 'succ' was processed first,
18036 * | it was eventually tracked to produce a
18037 * V state identical to 'hdr'.
18038 * .---------> hdr All branches from 'succ' had been explored
18039 * | | and thus 'succ' has its .branches == 0.
18041 * | .------... Suppose states 'cur' and 'succ' correspond
18042 * | | | to the same instruction + callsites.
18043 * | V V In such case it is necessary to check
18044 * | ... ... if 'succ' and 'cur' are states_equal().
18045 * | | | If 'succ' and 'cur' are a part of the
18046 * | V V same loop exact flag has to be set.
18047 * | succ <- cur To check if that is the case, verify
18048 * | | if loop entry of 'succ' is in current
18054 * Additional details are in the comment before get_loop_entry().
18056 loop_entry = get_loop_entry(&sl->state);
18057 force_exact = loop_entry && loop_entry->branches > 0;
18058 if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) {
18060 update_loop_entry(cur, loop_entry);
18063 /* reached equivalent register/stack state,
18064 * prune the search.
18065 * Registers read by the continuation are read by us.
18066 * If we have any write marks in env->cur_state, they
18067 * will prevent corresponding reads in the continuation
18068 * from reaching our parent (an explored_state). Our
18069 * own state will get the read marks recorded, but
18070 * they'll be immediately forgotten as we're pruning
18071 * this state and will pop a new one.
18073 err = propagate_liveness(env, &sl->state, cur);
18075 /* if previous state reached the exit with precision and
18076 * current state is equivalent to it (except precision marks)
18077 * the precision needs to be propagated back in
18078 * the current state.
18080 if (is_jmp_point(env, env->insn_idx))
18081 err = err ? : push_jmp_history(env, cur, 0, 0);
18082 err = err ? : propagate_precision(env, &sl->state);
18088 /* when new state is not going to be added do not increase miss count.
18089 * Otherwise several loop iterations will remove the state
18090 * recorded earlier. The goal of these heuristics is to have
18091 * states from some iterations of the loop (some in the beginning
18092 * and some at the end) to help pruning.
18096 /* heuristic to determine whether this state is beneficial
18097 * to keep checking from state equivalence point of view.
18098 * Higher numbers increase max_states_per_insn and verification time,
18099 * but do not meaningfully decrease insn_processed.
18100 * 'n' controls how many times state could miss before eviction.
18101 * Use bigger 'n' for checkpoints because evicting checkpoint states
18102 * too early would hinder iterator convergence.
18104 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
18105 if (sl->miss_cnt > sl->hit_cnt * n + n) {
18106 /* the state is unlikely to be useful. Remove it to
18107 * speed up verification
18110 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
18111 !sl->state.used_as_loop_entry) {
18112 u32 br = sl->state.branches;
18115 "BUG live_done but branches_to_explore %d\n",
18117 free_verifier_state(&sl->state, false);
18119 env->peak_states--;
18121 /* cannot free this state, since parentage chain may
18122 * walk it later. Add it for free_list instead to
18123 * be freed at the end of verification
18125 sl->next = env->free_list;
18126 env->free_list = sl;
18136 if (env->max_states_per_insn < states_cnt)
18137 env->max_states_per_insn = states_cnt;
18139 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
18142 if (!add_new_state)
18145 /* There were no equivalent states, remember the current one.
18146 * Technically the current state is not proven to be safe yet,
18147 * but it will either reach outer most bpf_exit (which means it's safe)
18148 * or it will be rejected. When there are no loops the verifier won't be
18149 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
18150 * again on the way to bpf_exit.
18151 * When looping the sl->state.branches will be > 0 and this state
18152 * will not be considered for equivalence until branches == 0.
18154 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
18157 env->total_states++;
18158 env->peak_states++;
18159 env->prev_jmps_processed = env->jmps_processed;
18160 env->prev_insn_processed = env->insn_processed;
18162 /* forget precise markings we inherited, see __mark_chain_precision */
18163 if (env->bpf_capable)
18164 mark_all_scalars_imprecise(env, cur);
18166 /* add new state to the head of linked list */
18167 new = &new_sl->state;
18168 err = copy_verifier_state(new, cur);
18170 free_verifier_state(new, false);
18174 new->insn_idx = insn_idx;
18175 WARN_ONCE(new->branches != 1,
18176 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
18179 cur->first_insn_idx = insn_idx;
18180 cur->dfs_depth = new->dfs_depth + 1;
18181 clear_jmp_history(cur);
18182 new_sl->next = *explored_state(env, insn_idx);
18183 *explored_state(env, insn_idx) = new_sl;
18184 /* connect new state to parentage chain. Current frame needs all
18185 * registers connected. Only r6 - r9 of the callers are alive (pushed
18186 * to the stack implicitly by JITs) so in callers' frames connect just
18187 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
18188 * the state of the call instruction (with WRITTEN set), and r0 comes
18189 * from callee with its full parentage chain, anyway.
18191 /* clear write marks in current state: the writes we did are not writes
18192 * our child did, so they don't screen off its reads from us.
18193 * (There are no read marks in current state, because reads always mark
18194 * their parent and current state never has children yet. Only
18195 * explored_states can get read marks.)
18197 for (j = 0; j <= cur->curframe; j++) {
18198 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
18199 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
18200 for (i = 0; i < BPF_REG_FP; i++)
18201 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
18204 /* all stack frames are accessible from callee, clear them all */
18205 for (j = 0; j <= cur->curframe; j++) {
18206 struct bpf_func_state *frame = cur->frame[j];
18207 struct bpf_func_state *newframe = new->frame[j];
18209 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
18210 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
18211 frame->stack[i].spilled_ptr.parent =
18212 &newframe->stack[i].spilled_ptr;
18218 /* Return true if it's OK to have the same insn return a different type. */
18219 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
18221 switch (base_type(type)) {
18223 case PTR_TO_SOCKET:
18224 case PTR_TO_SOCK_COMMON:
18225 case PTR_TO_TCP_SOCK:
18226 case PTR_TO_XDP_SOCK:
18227 case PTR_TO_BTF_ID:
18235 /* If an instruction was previously used with particular pointer types, then we
18236 * need to be careful to avoid cases such as the below, where it may be ok
18237 * for one branch accessing the pointer, but not ok for the other branch:
18242 * R1 = some_other_valid_ptr;
18245 * R2 = *(u32 *)(R1 + 0);
18247 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
18249 return src != prev && (!reg_type_mismatch_ok(src) ||
18250 !reg_type_mismatch_ok(prev));
18253 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
18254 bool allow_trust_mismatch)
18256 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
18258 if (*prev_type == NOT_INIT) {
18259 /* Saw a valid insn
18260 * dst_reg = *(u32 *)(src_reg + off)
18261 * save type to validate intersecting paths
18264 } else if (reg_type_mismatch(type, *prev_type)) {
18265 /* Abuser program is trying to use the same insn
18266 * dst_reg = *(u32*) (src_reg + off)
18267 * with different pointer types:
18268 * src_reg == ctx in one branch and
18269 * src_reg == stack|map in some other branch.
18272 if (allow_trust_mismatch &&
18273 base_type(type) == PTR_TO_BTF_ID &&
18274 base_type(*prev_type) == PTR_TO_BTF_ID) {
18276 * Have to support a use case when one path through
18277 * the program yields TRUSTED pointer while another
18278 * is UNTRUSTED. Fallback to UNTRUSTED to generate
18279 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
18281 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
18283 verbose(env, "same insn cannot be used with different pointers\n");
18291 static int do_check(struct bpf_verifier_env *env)
18293 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18294 struct bpf_verifier_state *state = env->cur_state;
18295 struct bpf_insn *insns = env->prog->insnsi;
18296 struct bpf_reg_state *regs;
18297 int insn_cnt = env->prog->len;
18298 bool do_print_state = false;
18299 int prev_insn_idx = -1;
18302 bool exception_exit = false;
18303 struct bpf_insn *insn;
18307 /* reset current history entry on each new instruction */
18308 env->cur_hist_ent = NULL;
18310 env->prev_insn_idx = prev_insn_idx;
18311 if (env->insn_idx >= insn_cnt) {
18312 verbose(env, "invalid insn idx %d insn_cnt %d\n",
18313 env->insn_idx, insn_cnt);
18317 insn = &insns[env->insn_idx];
18318 class = BPF_CLASS(insn->code);
18320 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
18322 "BPF program is too large. Processed %d insn\n",
18323 env->insn_processed);
18327 state->last_insn_idx = env->prev_insn_idx;
18329 if (is_prune_point(env, env->insn_idx)) {
18330 err = is_state_visited(env, env->insn_idx);
18334 /* found equivalent state, can prune the search */
18335 if (env->log.level & BPF_LOG_LEVEL) {
18336 if (do_print_state)
18337 verbose(env, "\nfrom %d to %d%s: safe\n",
18338 env->prev_insn_idx, env->insn_idx,
18339 env->cur_state->speculative ?
18340 " (speculative execution)" : "");
18342 verbose(env, "%d: safe\n", env->insn_idx);
18344 goto process_bpf_exit;
18348 if (is_jmp_point(env, env->insn_idx)) {
18349 err = push_jmp_history(env, state, 0, 0);
18354 if (signal_pending(current))
18357 if (need_resched())
18360 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
18361 verbose(env, "\nfrom %d to %d%s:",
18362 env->prev_insn_idx, env->insn_idx,
18363 env->cur_state->speculative ?
18364 " (speculative execution)" : "");
18365 print_verifier_state(env, state->frame[state->curframe], true);
18366 do_print_state = false;
18369 if (env->log.level & BPF_LOG_LEVEL) {
18370 const struct bpf_insn_cbs cbs = {
18371 .cb_call = disasm_kfunc_name,
18372 .cb_print = verbose,
18373 .private_data = env,
18376 if (verifier_state_scratched(env))
18377 print_insn_state(env, state->frame[state->curframe]);
18379 verbose_linfo(env, env->insn_idx, "; ");
18380 env->prev_log_pos = env->log.end_pos;
18381 verbose(env, "%d: ", env->insn_idx);
18382 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
18383 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
18384 env->prev_log_pos = env->log.end_pos;
18387 if (bpf_prog_is_offloaded(env->prog->aux)) {
18388 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
18389 env->prev_insn_idx);
18394 regs = cur_regs(env);
18395 sanitize_mark_insn_seen(env);
18396 prev_insn_idx = env->insn_idx;
18398 if (class == BPF_ALU || class == BPF_ALU64) {
18399 err = check_alu_op(env, insn);
18403 } else if (class == BPF_LDX) {
18404 enum bpf_reg_type src_reg_type;
18406 /* check for reserved fields is already done */
18408 /* check src operand */
18409 err = check_reg_arg(env, insn->src_reg, SRC_OP);
18413 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
18417 src_reg_type = regs[insn->src_reg].type;
18419 /* check that memory (src_reg + off) is readable,
18420 * the state of dst_reg will be updated by this func
18422 err = check_mem_access(env, env->insn_idx, insn->src_reg,
18423 insn->off, BPF_SIZE(insn->code),
18424 BPF_READ, insn->dst_reg, false,
18425 BPF_MODE(insn->code) == BPF_MEMSX);
18426 err = err ?: save_aux_ptr_type(env, src_reg_type, true);
18427 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx");
18430 } else if (class == BPF_STX) {
18431 enum bpf_reg_type dst_reg_type;
18433 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
18434 err = check_atomic(env, env->insn_idx, insn);
18441 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
18442 verbose(env, "BPF_STX uses reserved fields\n");
18446 /* check src1 operand */
18447 err = check_reg_arg(env, insn->src_reg, SRC_OP);
18450 /* check src2 operand */
18451 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
18455 dst_reg_type = regs[insn->dst_reg].type;
18457 /* check that memory (dst_reg + off) is writeable */
18458 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
18459 insn->off, BPF_SIZE(insn->code),
18460 BPF_WRITE, insn->src_reg, false, false);
18464 err = save_aux_ptr_type(env, dst_reg_type, false);
18467 } else if (class == BPF_ST) {
18468 enum bpf_reg_type dst_reg_type;
18470 if (BPF_MODE(insn->code) != BPF_MEM ||
18471 insn->src_reg != BPF_REG_0) {
18472 verbose(env, "BPF_ST uses reserved fields\n");
18475 /* check src operand */
18476 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
18480 dst_reg_type = regs[insn->dst_reg].type;
18482 /* check that memory (dst_reg + off) is writeable */
18483 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
18484 insn->off, BPF_SIZE(insn->code),
18485 BPF_WRITE, -1, false, false);
18489 err = save_aux_ptr_type(env, dst_reg_type, false);
18492 } else if (class == BPF_JMP || class == BPF_JMP32) {
18493 u8 opcode = BPF_OP(insn->code);
18495 env->jmps_processed++;
18496 if (opcode == BPF_CALL) {
18497 if (BPF_SRC(insn->code) != BPF_K ||
18498 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
18499 && insn->off != 0) ||
18500 (insn->src_reg != BPF_REG_0 &&
18501 insn->src_reg != BPF_PSEUDO_CALL &&
18502 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
18503 insn->dst_reg != BPF_REG_0 ||
18504 class == BPF_JMP32) {
18505 verbose(env, "BPF_CALL uses reserved fields\n");
18509 if (env->cur_state->active_lock.ptr) {
18510 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
18511 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
18512 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
18513 verbose(env, "function calls are not allowed while holding a lock\n");
18517 if (insn->src_reg == BPF_PSEUDO_CALL) {
18518 err = check_func_call(env, insn, &env->insn_idx);
18519 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18520 err = check_kfunc_call(env, insn, &env->insn_idx);
18521 if (!err && is_bpf_throw_kfunc(insn)) {
18522 exception_exit = true;
18523 goto process_bpf_exit_full;
18526 err = check_helper_call(env, insn, &env->insn_idx);
18531 mark_reg_scratched(env, BPF_REG_0);
18532 } else if (opcode == BPF_JA) {
18533 if (BPF_SRC(insn->code) != BPF_K ||
18534 insn->src_reg != BPF_REG_0 ||
18535 insn->dst_reg != BPF_REG_0 ||
18536 (class == BPF_JMP && insn->imm != 0) ||
18537 (class == BPF_JMP32 && insn->off != 0)) {
18538 verbose(env, "BPF_JA uses reserved fields\n");
18542 if (class == BPF_JMP)
18543 env->insn_idx += insn->off + 1;
18545 env->insn_idx += insn->imm + 1;
18548 } else if (opcode == BPF_EXIT) {
18549 if (BPF_SRC(insn->code) != BPF_K ||
18551 insn->src_reg != BPF_REG_0 ||
18552 insn->dst_reg != BPF_REG_0 ||
18553 class == BPF_JMP32) {
18554 verbose(env, "BPF_EXIT uses reserved fields\n");
18557 process_bpf_exit_full:
18558 if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) {
18559 verbose(env, "bpf_spin_unlock is missing\n");
18563 if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) {
18564 verbose(env, "bpf_rcu_read_unlock is missing\n");
18568 if (env->cur_state->active_preempt_lock && !env->cur_state->curframe) {
18569 verbose(env, "%d bpf_preempt_enable%s missing\n",
18570 env->cur_state->active_preempt_lock,
18571 env->cur_state->active_preempt_lock == 1 ? " is" : "(s) are");
18575 /* We must do check_reference_leak here before
18576 * prepare_func_exit to handle the case when
18577 * state->curframe > 0, it may be a callback
18578 * function, for which reference_state must
18579 * match caller reference state when it exits.
18581 err = check_reference_leak(env, exception_exit);
18585 /* The side effect of the prepare_func_exit
18586 * which is being skipped is that it frees
18587 * bpf_func_state. Typically, process_bpf_exit
18588 * will only be hit with outermost exit.
18589 * copy_verifier_state in pop_stack will handle
18590 * freeing of any extra bpf_func_state left over
18591 * from not processing all nested function
18592 * exits. We also skip return code checks as
18593 * they are not needed for exceptional exits.
18595 if (exception_exit)
18596 goto process_bpf_exit;
18598 if (state->curframe) {
18599 /* exit from nested function */
18600 err = prepare_func_exit(env, &env->insn_idx);
18603 do_print_state = true;
18607 err = check_return_code(env, BPF_REG_0, "R0");
18611 mark_verifier_state_scratched(env);
18612 update_branch_counts(env, env->cur_state);
18613 err = pop_stack(env, &prev_insn_idx,
18614 &env->insn_idx, pop_log);
18616 if (err != -ENOENT)
18620 do_print_state = true;
18624 err = check_cond_jmp_op(env, insn, &env->insn_idx);
18628 } else if (class == BPF_LD) {
18629 u8 mode = BPF_MODE(insn->code);
18631 if (mode == BPF_ABS || mode == BPF_IND) {
18632 err = check_ld_abs(env, insn);
18636 } else if (mode == BPF_IMM) {
18637 err = check_ld_imm(env, insn);
18642 sanitize_mark_insn_seen(env);
18644 verbose(env, "invalid BPF_LD mode\n");
18648 verbose(env, "unknown insn class %d\n", class);
18658 static int find_btf_percpu_datasec(struct btf *btf)
18660 const struct btf_type *t;
18665 * Both vmlinux and module each have their own ".data..percpu"
18666 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
18667 * types to look at only module's own BTF types.
18669 n = btf_nr_types(btf);
18670 if (btf_is_module(btf))
18671 i = btf_nr_types(btf_vmlinux);
18675 for(; i < n; i++) {
18676 t = btf_type_by_id(btf, i);
18677 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
18680 tname = btf_name_by_offset(btf, t->name_off);
18681 if (!strcmp(tname, ".data..percpu"))
18688 /* replace pseudo btf_id with kernel symbol address */
18689 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
18690 struct bpf_insn *insn,
18691 struct bpf_insn_aux_data *aux)
18693 const struct btf_var_secinfo *vsi;
18694 const struct btf_type *datasec;
18695 struct btf_mod_pair *btf_mod;
18696 const struct btf_type *t;
18697 const char *sym_name;
18698 bool percpu = false;
18699 u32 type, id = insn->imm;
18703 int i, btf_fd, err;
18705 btf_fd = insn[1].imm;
18707 btf = btf_get_by_fd(btf_fd);
18709 verbose(env, "invalid module BTF object FD specified.\n");
18713 if (!btf_vmlinux) {
18714 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
18721 t = btf_type_by_id(btf, id);
18723 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
18728 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
18729 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
18734 sym_name = btf_name_by_offset(btf, t->name_off);
18735 addr = kallsyms_lookup_name(sym_name);
18737 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
18742 insn[0].imm = (u32)addr;
18743 insn[1].imm = addr >> 32;
18745 if (btf_type_is_func(t)) {
18746 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18747 aux->btf_var.mem_size = 0;
18751 datasec_id = find_btf_percpu_datasec(btf);
18752 if (datasec_id > 0) {
18753 datasec = btf_type_by_id(btf, datasec_id);
18754 for_each_vsi(i, datasec, vsi) {
18755 if (vsi->type == id) {
18763 t = btf_type_skip_modifiers(btf, type, NULL);
18765 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
18766 aux->btf_var.btf = btf;
18767 aux->btf_var.btf_id = type;
18768 } else if (!btf_type_is_struct(t)) {
18769 const struct btf_type *ret;
18773 /* resolve the type size of ksym. */
18774 ret = btf_resolve_size(btf, t, &tsize);
18776 tname = btf_name_by_offset(btf, t->name_off);
18777 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
18778 tname, PTR_ERR(ret));
18782 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18783 aux->btf_var.mem_size = tsize;
18785 aux->btf_var.reg_type = PTR_TO_BTF_ID;
18786 aux->btf_var.btf = btf;
18787 aux->btf_var.btf_id = type;
18790 /* check whether we recorded this BTF (and maybe module) already */
18791 for (i = 0; i < env->used_btf_cnt; i++) {
18792 if (env->used_btfs[i].btf == btf) {
18798 if (env->used_btf_cnt >= MAX_USED_BTFS) {
18803 btf_mod = &env->used_btfs[env->used_btf_cnt];
18804 btf_mod->btf = btf;
18805 btf_mod->module = NULL;
18807 /* if we reference variables from kernel module, bump its refcount */
18808 if (btf_is_module(btf)) {
18809 btf_mod->module = btf_try_get_module(btf);
18810 if (!btf_mod->module) {
18816 env->used_btf_cnt++;
18824 static bool is_tracing_prog_type(enum bpf_prog_type type)
18827 case BPF_PROG_TYPE_KPROBE:
18828 case BPF_PROG_TYPE_TRACEPOINT:
18829 case BPF_PROG_TYPE_PERF_EVENT:
18830 case BPF_PROG_TYPE_RAW_TRACEPOINT:
18831 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
18838 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
18839 struct bpf_map *map,
18840 struct bpf_prog *prog)
18843 enum bpf_prog_type prog_type = resolve_prog_type(prog);
18845 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
18846 btf_record_has_field(map->record, BPF_RB_ROOT)) {
18847 if (is_tracing_prog_type(prog_type)) {
18848 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
18853 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
18854 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
18855 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
18859 if (is_tracing_prog_type(prog_type)) {
18860 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
18865 if (btf_record_has_field(map->record, BPF_TIMER)) {
18866 if (is_tracing_prog_type(prog_type)) {
18867 verbose(env, "tracing progs cannot use bpf_timer yet\n");
18872 if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
18873 if (is_tracing_prog_type(prog_type)) {
18874 verbose(env, "tracing progs cannot use bpf_wq yet\n");
18879 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
18880 !bpf_offload_prog_map_match(prog, map)) {
18881 verbose(env, "offload device mismatch between prog and map\n");
18885 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
18886 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
18890 if (prog->sleepable)
18891 switch (map->map_type) {
18892 case BPF_MAP_TYPE_HASH:
18893 case BPF_MAP_TYPE_LRU_HASH:
18894 case BPF_MAP_TYPE_ARRAY:
18895 case BPF_MAP_TYPE_PERCPU_HASH:
18896 case BPF_MAP_TYPE_PERCPU_ARRAY:
18897 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
18898 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
18899 case BPF_MAP_TYPE_HASH_OF_MAPS:
18900 case BPF_MAP_TYPE_RINGBUF:
18901 case BPF_MAP_TYPE_USER_RINGBUF:
18902 case BPF_MAP_TYPE_INODE_STORAGE:
18903 case BPF_MAP_TYPE_SK_STORAGE:
18904 case BPF_MAP_TYPE_TASK_STORAGE:
18905 case BPF_MAP_TYPE_CGRP_STORAGE:
18906 case BPF_MAP_TYPE_QUEUE:
18907 case BPF_MAP_TYPE_STACK:
18908 case BPF_MAP_TYPE_ARENA:
18912 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
18919 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
18921 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
18922 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
18925 /* Add map behind fd to used maps list, if it's not already there, and return
18926 * its index. Also set *reused to true if this map was already in the list of
18928 * Returns <0 on error, or >= 0 index, on success.
18930 static int add_used_map_from_fd(struct bpf_verifier_env *env, int fd, bool *reused)
18933 struct bpf_map *map;
18936 map = __bpf_map_get(f);
18938 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
18939 return PTR_ERR(map);
18942 /* check whether we recorded this map already */
18943 for (i = 0; i < env->used_map_cnt; i++) {
18944 if (env->used_maps[i] == map) {
18950 if (env->used_map_cnt >= MAX_USED_MAPS) {
18951 verbose(env, "The total number of maps per program has reached the limit of %u\n",
18956 if (env->prog->sleepable)
18957 atomic64_inc(&map->sleepable_refcnt);
18959 /* hold the map. If the program is rejected by verifier,
18960 * the map will be released by release_maps() or it
18961 * will be used by the valid program until it's unloaded
18962 * and all maps are released in bpf_free_used_maps()
18967 env->used_maps[env->used_map_cnt++] = map;
18969 return env->used_map_cnt - 1;
18972 /* find and rewrite pseudo imm in ld_imm64 instructions:
18974 * 1. if it accesses map FD, replace it with actual map pointer.
18975 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
18977 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
18979 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
18981 struct bpf_insn *insn = env->prog->insnsi;
18982 int insn_cnt = env->prog->len;
18985 err = bpf_prog_calc_tag(env->prog);
18989 for (i = 0; i < insn_cnt; i++, insn++) {
18990 if (BPF_CLASS(insn->code) == BPF_LDX &&
18991 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
18993 verbose(env, "BPF_LDX uses reserved fields\n");
18997 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
18998 struct bpf_insn_aux_data *aux;
18999 struct bpf_map *map;
19005 if (i == insn_cnt - 1 || insn[1].code != 0 ||
19006 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
19007 insn[1].off != 0) {
19008 verbose(env, "invalid bpf_ld_imm64 insn\n");
19012 if (insn[0].src_reg == 0)
19013 /* valid generic load 64-bit imm */
19016 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
19017 aux = &env->insn_aux_data[i];
19018 err = check_pseudo_btf_id(env, insn, aux);
19024 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
19025 aux = &env->insn_aux_data[i];
19026 aux->ptr_type = PTR_TO_FUNC;
19030 /* In final convert_pseudo_ld_imm64() step, this is
19031 * converted into regular 64-bit imm load insn.
19033 switch (insn[0].src_reg) {
19034 case BPF_PSEUDO_MAP_VALUE:
19035 case BPF_PSEUDO_MAP_IDX_VALUE:
19037 case BPF_PSEUDO_MAP_FD:
19038 case BPF_PSEUDO_MAP_IDX:
19039 if (insn[1].imm == 0)
19043 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
19047 switch (insn[0].src_reg) {
19048 case BPF_PSEUDO_MAP_IDX_VALUE:
19049 case BPF_PSEUDO_MAP_IDX:
19050 if (bpfptr_is_null(env->fd_array)) {
19051 verbose(env, "fd_idx without fd_array is invalid\n");
19054 if (copy_from_bpfptr_offset(&fd, env->fd_array,
19055 insn[0].imm * sizeof(fd),
19064 map_idx = add_used_map_from_fd(env, fd, &reused);
19067 map = env->used_maps[map_idx];
19069 aux = &env->insn_aux_data[i];
19070 aux->map_index = map_idx;
19072 err = check_map_prog_compatibility(env, map, env->prog);
19076 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
19077 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
19078 addr = (unsigned long)map;
19080 u32 off = insn[1].imm;
19082 if (off >= BPF_MAX_VAR_OFF) {
19083 verbose(env, "direct value offset of %u is not allowed\n", off);
19087 if (!map->ops->map_direct_value_addr) {
19088 verbose(env, "no direct value access support for this map type\n");
19092 err = map->ops->map_direct_value_addr(map, &addr, off);
19094 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
19095 map->value_size, off);
19099 aux->map_off = off;
19103 insn[0].imm = (u32)addr;
19104 insn[1].imm = addr >> 32;
19106 /* proceed with extra checks only if its newly added used map */
19110 if (bpf_map_is_cgroup_storage(map) &&
19111 bpf_cgroup_storage_assign(env->prog->aux, map)) {
19112 verbose(env, "only one cgroup storage of each type is allowed\n");
19115 if (map->map_type == BPF_MAP_TYPE_ARENA) {
19116 if (env->prog->aux->arena) {
19117 verbose(env, "Only one arena per program\n");
19120 if (!env->allow_ptr_leaks || !env->bpf_capable) {
19121 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
19124 if (!env->prog->jit_requested) {
19125 verbose(env, "JIT is required to use arena\n");
19126 return -EOPNOTSUPP;
19128 if (!bpf_jit_supports_arena()) {
19129 verbose(env, "JIT doesn't support arena\n");
19130 return -EOPNOTSUPP;
19132 env->prog->aux->arena = (void *)map;
19133 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
19134 verbose(env, "arena's user address must be set via map_extra or mmap()\n");
19145 /* Basic sanity check before we invest more work here. */
19146 if (!bpf_opcode_in_insntable(insn->code)) {
19147 verbose(env, "unknown opcode %02x\n", insn->code);
19152 /* now all pseudo BPF_LD_IMM64 instructions load valid
19153 * 'struct bpf_map *' into a register instead of user map_fd.
19154 * These pointers will be used later by verifier to validate map access.
19159 /* drop refcnt of maps used by the rejected program */
19160 static void release_maps(struct bpf_verifier_env *env)
19162 __bpf_free_used_maps(env->prog->aux, env->used_maps,
19163 env->used_map_cnt);
19166 /* drop refcnt of maps used by the rejected program */
19167 static void release_btfs(struct bpf_verifier_env *env)
19169 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
19172 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
19173 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
19175 struct bpf_insn *insn = env->prog->insnsi;
19176 int insn_cnt = env->prog->len;
19179 for (i = 0; i < insn_cnt; i++, insn++) {
19180 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
19182 if (insn->src_reg == BPF_PSEUDO_FUNC)
19188 /* single env->prog->insni[off] instruction was replaced with the range
19189 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
19190 * [0, off) and [off, end) to new locations, so the patched range stays zero
19192 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
19193 struct bpf_insn_aux_data *new_data,
19194 struct bpf_prog *new_prog, u32 off, u32 cnt)
19196 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
19197 struct bpf_insn *insn = new_prog->insnsi;
19198 u32 old_seen = old_data[off].seen;
19202 /* aux info at OFF always needs adjustment, no matter fast path
19203 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
19204 * original insn at old prog.
19206 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
19210 prog_len = new_prog->len;
19212 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
19213 memcpy(new_data + off + cnt - 1, old_data + off,
19214 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
19215 for (i = off; i < off + cnt - 1; i++) {
19216 /* Expand insni[off]'s seen count to the patched range. */
19217 new_data[i].seen = old_seen;
19218 new_data[i].zext_dst = insn_has_def32(env, insn + i);
19220 env->insn_aux_data = new_data;
19224 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
19230 /* NOTE: fake 'exit' subprog should be updated as well. */
19231 for (i = 0; i <= env->subprog_cnt; i++) {
19232 if (env->subprog_info[i].start <= off)
19234 env->subprog_info[i].start += len - 1;
19238 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
19240 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
19241 int i, sz = prog->aux->size_poke_tab;
19242 struct bpf_jit_poke_descriptor *desc;
19244 for (i = 0; i < sz; i++) {
19246 if (desc->insn_idx <= off)
19248 desc->insn_idx += len - 1;
19252 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
19253 const struct bpf_insn *patch, u32 len)
19255 struct bpf_prog *new_prog;
19256 struct bpf_insn_aux_data *new_data = NULL;
19259 new_data = vzalloc(array_size(env->prog->len + len - 1,
19260 sizeof(struct bpf_insn_aux_data)));
19265 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
19266 if (IS_ERR(new_prog)) {
19267 if (PTR_ERR(new_prog) == -ERANGE)
19269 "insn %d cannot be patched due to 16-bit range\n",
19270 env->insn_aux_data[off].orig_idx);
19274 adjust_insn_aux_data(env, new_data, new_prog, off, len);
19275 adjust_subprog_starts(env, off, len);
19276 adjust_poke_descs(new_prog, off, len);
19281 * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
19282 * jump offset by 'delta'.
19284 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
19286 struct bpf_insn *insn = prog->insnsi;
19287 u32 insn_cnt = prog->len, i;
19291 for (i = 0; i < insn_cnt; i++, insn++) {
19292 u8 code = insn->code;
19294 if (tgt_idx <= i && i < tgt_idx + delta)
19297 if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
19298 BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
19301 if (insn->code == (BPF_JMP32 | BPF_JA)) {
19302 if (i + 1 + insn->imm != tgt_idx)
19304 if (check_add_overflow(insn->imm, delta, &imm))
19308 if (i + 1 + insn->off != tgt_idx)
19310 if (check_add_overflow(insn->off, delta, &off))
19318 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
19323 /* find first prog starting at or after off (first to remove) */
19324 for (i = 0; i < env->subprog_cnt; i++)
19325 if (env->subprog_info[i].start >= off)
19327 /* find first prog starting at or after off + cnt (first to stay) */
19328 for (j = i; j < env->subprog_cnt; j++)
19329 if (env->subprog_info[j].start >= off + cnt)
19331 /* if j doesn't start exactly at off + cnt, we are just removing
19332 * the front of previous prog
19334 if (env->subprog_info[j].start != off + cnt)
19338 struct bpf_prog_aux *aux = env->prog->aux;
19341 /* move fake 'exit' subprog as well */
19342 move = env->subprog_cnt + 1 - j;
19344 memmove(env->subprog_info + i,
19345 env->subprog_info + j,
19346 sizeof(*env->subprog_info) * move);
19347 env->subprog_cnt -= j - i;
19349 /* remove func_info */
19350 if (aux->func_info) {
19351 move = aux->func_info_cnt - j;
19353 memmove(aux->func_info + i,
19354 aux->func_info + j,
19355 sizeof(*aux->func_info) * move);
19356 aux->func_info_cnt -= j - i;
19357 /* func_info->insn_off is set after all code rewrites,
19358 * in adjust_btf_func() - no need to adjust
19362 /* convert i from "first prog to remove" to "first to adjust" */
19363 if (env->subprog_info[i].start == off)
19367 /* update fake 'exit' subprog as well */
19368 for (; i <= env->subprog_cnt; i++)
19369 env->subprog_info[i].start -= cnt;
19374 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
19377 struct bpf_prog *prog = env->prog;
19378 u32 i, l_off, l_cnt, nr_linfo;
19379 struct bpf_line_info *linfo;
19381 nr_linfo = prog->aux->nr_linfo;
19385 linfo = prog->aux->linfo;
19387 /* find first line info to remove, count lines to be removed */
19388 for (i = 0; i < nr_linfo; i++)
19389 if (linfo[i].insn_off >= off)
19394 for (; i < nr_linfo; i++)
19395 if (linfo[i].insn_off < off + cnt)
19400 /* First live insn doesn't match first live linfo, it needs to "inherit"
19401 * last removed linfo. prog is already modified, so prog->len == off
19402 * means no live instructions after (tail of the program was removed).
19404 if (prog->len != off && l_cnt &&
19405 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
19407 linfo[--i].insn_off = off + cnt;
19410 /* remove the line info which refer to the removed instructions */
19412 memmove(linfo + l_off, linfo + i,
19413 sizeof(*linfo) * (nr_linfo - i));
19415 prog->aux->nr_linfo -= l_cnt;
19416 nr_linfo = prog->aux->nr_linfo;
19419 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
19420 for (i = l_off; i < nr_linfo; i++)
19421 linfo[i].insn_off -= cnt;
19423 /* fix up all subprogs (incl. 'exit') which start >= off */
19424 for (i = 0; i <= env->subprog_cnt; i++)
19425 if (env->subprog_info[i].linfo_idx > l_off) {
19426 /* program may have started in the removed region but
19427 * may not be fully removed
19429 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
19430 env->subprog_info[i].linfo_idx -= l_cnt;
19432 env->subprog_info[i].linfo_idx = l_off;
19438 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
19440 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
19441 unsigned int orig_prog_len = env->prog->len;
19444 if (bpf_prog_is_offloaded(env->prog->aux))
19445 bpf_prog_offload_remove_insns(env, off, cnt);
19447 err = bpf_remove_insns(env->prog, off, cnt);
19451 err = adjust_subprog_starts_after_remove(env, off, cnt);
19455 err = bpf_adj_linfo_after_remove(env, off, cnt);
19459 memmove(aux_data + off, aux_data + off + cnt,
19460 sizeof(*aux_data) * (orig_prog_len - off - cnt));
19465 /* The verifier does more data flow analysis than llvm and will not
19466 * explore branches that are dead at run time. Malicious programs can
19467 * have dead code too. Therefore replace all dead at-run-time code
19470 * Just nops are not optimal, e.g. if they would sit at the end of the
19471 * program and through another bug we would manage to jump there, then
19472 * we'd execute beyond program memory otherwise. Returning exception
19473 * code also wouldn't work since we can have subprogs where the dead
19474 * code could be located.
19476 static void sanitize_dead_code(struct bpf_verifier_env *env)
19478 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
19479 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
19480 struct bpf_insn *insn = env->prog->insnsi;
19481 const int insn_cnt = env->prog->len;
19484 for (i = 0; i < insn_cnt; i++) {
19485 if (aux_data[i].seen)
19487 memcpy(insn + i, &trap, sizeof(trap));
19488 aux_data[i].zext_dst = false;
19492 static bool insn_is_cond_jump(u8 code)
19497 if (BPF_CLASS(code) == BPF_JMP32)
19498 return op != BPF_JA;
19500 if (BPF_CLASS(code) != BPF_JMP)
19503 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
19506 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
19508 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
19509 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
19510 struct bpf_insn *insn = env->prog->insnsi;
19511 const int insn_cnt = env->prog->len;
19514 for (i = 0; i < insn_cnt; i++, insn++) {
19515 if (!insn_is_cond_jump(insn->code))
19518 if (!aux_data[i + 1].seen)
19519 ja.off = insn->off;
19520 else if (!aux_data[i + 1 + insn->off].seen)
19525 if (bpf_prog_is_offloaded(env->prog->aux))
19526 bpf_prog_offload_replace_insn(env, i, &ja);
19528 memcpy(insn, &ja, sizeof(ja));
19532 static int opt_remove_dead_code(struct bpf_verifier_env *env)
19534 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
19535 int insn_cnt = env->prog->len;
19538 for (i = 0; i < insn_cnt; i++) {
19542 while (i + j < insn_cnt && !aux_data[i + j].seen)
19547 err = verifier_remove_insns(env, i, j);
19550 insn_cnt = env->prog->len;
19556 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
19558 static int opt_remove_nops(struct bpf_verifier_env *env)
19560 const struct bpf_insn ja = NOP;
19561 struct bpf_insn *insn = env->prog->insnsi;
19562 int insn_cnt = env->prog->len;
19565 for (i = 0; i < insn_cnt; i++) {
19566 if (memcmp(&insn[i], &ja, sizeof(ja)))
19569 err = verifier_remove_insns(env, i, 1);
19579 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
19580 const union bpf_attr *attr)
19582 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
19583 struct bpf_insn_aux_data *aux = env->insn_aux_data;
19584 int i, patch_len, delta = 0, len = env->prog->len;
19585 struct bpf_insn *insns = env->prog->insnsi;
19586 struct bpf_prog *new_prog;
19589 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
19590 zext_patch[1] = BPF_ZEXT_REG(0);
19591 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
19592 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
19593 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
19594 for (i = 0; i < len; i++) {
19595 int adj_idx = i + delta;
19596 struct bpf_insn insn;
19599 insn = insns[adj_idx];
19600 load_reg = insn_def_regno(&insn);
19601 if (!aux[adj_idx].zext_dst) {
19609 class = BPF_CLASS(code);
19610 if (load_reg == -1)
19613 /* NOTE: arg "reg" (the fourth one) is only used for
19614 * BPF_STX + SRC_OP, so it is safe to pass NULL
19617 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
19618 if (class == BPF_LD &&
19619 BPF_MODE(code) == BPF_IMM)
19624 /* ctx load could be transformed into wider load. */
19625 if (class == BPF_LDX &&
19626 aux[adj_idx].ptr_type == PTR_TO_CTX)
19629 imm_rnd = get_random_u32();
19630 rnd_hi32_patch[0] = insn;
19631 rnd_hi32_patch[1].imm = imm_rnd;
19632 rnd_hi32_patch[3].dst_reg = load_reg;
19633 patch = rnd_hi32_patch;
19635 goto apply_patch_buffer;
19638 /* Add in an zero-extend instruction if a) the JIT has requested
19639 * it or b) it's a CMPXCHG.
19641 * The latter is because: BPF_CMPXCHG always loads a value into
19642 * R0, therefore always zero-extends. However some archs'
19643 * equivalent instruction only does this load when the
19644 * comparison is successful. This detail of CMPXCHG is
19645 * orthogonal to the general zero-extension behaviour of the
19646 * CPU, so it's treated independently of bpf_jit_needs_zext.
19648 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
19651 /* Zero-extension is done by the caller. */
19652 if (bpf_pseudo_kfunc_call(&insn))
19655 if (WARN_ON(load_reg == -1)) {
19656 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
19660 zext_patch[0] = insn;
19661 zext_patch[1].dst_reg = load_reg;
19662 zext_patch[1].src_reg = load_reg;
19663 patch = zext_patch;
19665 apply_patch_buffer:
19666 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
19669 env->prog = new_prog;
19670 insns = new_prog->insnsi;
19671 aux = env->insn_aux_data;
19672 delta += patch_len - 1;
19678 /* convert load instructions that access fields of a context type into a
19679 * sequence of instructions that access fields of the underlying structure:
19680 * struct __sk_buff -> struct sk_buff
19681 * struct bpf_sock_ops -> struct sock
19683 static int convert_ctx_accesses(struct bpf_verifier_env *env)
19685 struct bpf_subprog_info *subprogs = env->subprog_info;
19686 const struct bpf_verifier_ops *ops = env->ops;
19687 int i, cnt, size, ctx_field_size, delta = 0, epilogue_cnt = 0;
19688 const int insn_cnt = env->prog->len;
19689 struct bpf_insn *epilogue_buf = env->epilogue_buf;
19690 struct bpf_insn *insn_buf = env->insn_buf;
19691 struct bpf_insn *insn;
19692 u32 target_size, size_default, off;
19693 struct bpf_prog *new_prog;
19694 enum bpf_access_type type;
19695 bool is_narrower_load;
19696 int epilogue_idx = 0;
19698 if (ops->gen_epilogue) {
19699 epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
19700 -(subprogs[0].stack_depth + 8));
19701 if (epilogue_cnt >= INSN_BUF_SIZE) {
19702 verbose(env, "bpf verifier is misconfigured\n");
19704 } else if (epilogue_cnt) {
19705 /* Save the ARG_PTR_TO_CTX for the epilogue to use */
19707 subprogs[0].stack_depth += 8;
19708 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
19709 -subprogs[0].stack_depth);
19710 insn_buf[cnt++] = env->prog->insnsi[0];
19711 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
19714 env->prog = new_prog;
19719 if (ops->gen_prologue || env->seen_direct_write) {
19720 if (!ops->gen_prologue) {
19721 verbose(env, "bpf verifier is misconfigured\n");
19724 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
19726 if (cnt >= INSN_BUF_SIZE) {
19727 verbose(env, "bpf verifier is misconfigured\n");
19730 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
19734 env->prog = new_prog;
19740 WARN_ON(adjust_jmp_off(env->prog, 0, delta));
19742 if (bpf_prog_is_offloaded(env->prog->aux))
19745 insn = env->prog->insnsi + delta;
19747 for (i = 0; i < insn_cnt; i++, insn++) {
19748 bpf_convert_ctx_access_t convert_ctx_access;
19751 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
19752 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
19753 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
19754 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
19755 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
19756 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
19757 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
19759 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
19760 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
19761 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
19762 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
19763 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
19764 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
19765 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
19766 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
19768 } else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
19769 insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
19770 env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
19771 insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
19772 env->prog->aux->num_exentries++;
19774 } else if (insn->code == (BPF_JMP | BPF_EXIT) &&
19776 i + delta < subprogs[1].start) {
19777 /* Generate epilogue for the main prog */
19778 if (epilogue_idx) {
19779 /* jump back to the earlier generated epilogue */
19780 insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
19783 memcpy(insn_buf, epilogue_buf,
19784 epilogue_cnt * sizeof(*epilogue_buf));
19785 cnt = epilogue_cnt;
19786 /* epilogue_idx cannot be 0. It must have at
19787 * least one ctx ptr saving insn before the
19790 epilogue_idx = i + delta;
19792 goto patch_insn_buf;
19797 if (type == BPF_WRITE &&
19798 env->insn_aux_data[i + delta].sanitize_stack_spill) {
19799 struct bpf_insn patch[] = {
19804 cnt = ARRAY_SIZE(patch);
19805 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
19810 env->prog = new_prog;
19811 insn = new_prog->insnsi + i + delta;
19815 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
19817 if (!ops->convert_ctx_access)
19819 convert_ctx_access = ops->convert_ctx_access;
19821 case PTR_TO_SOCKET:
19822 case PTR_TO_SOCK_COMMON:
19823 convert_ctx_access = bpf_sock_convert_ctx_access;
19825 case PTR_TO_TCP_SOCK:
19826 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
19828 case PTR_TO_XDP_SOCK:
19829 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
19831 case PTR_TO_BTF_ID:
19832 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
19833 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
19834 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
19835 * be said once it is marked PTR_UNTRUSTED, hence we must handle
19836 * any faults for loads into such types. BPF_WRITE is disallowed
19839 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
19840 if (type == BPF_READ) {
19841 if (BPF_MODE(insn->code) == BPF_MEM)
19842 insn->code = BPF_LDX | BPF_PROBE_MEM |
19843 BPF_SIZE((insn)->code);
19845 insn->code = BPF_LDX | BPF_PROBE_MEMSX |
19846 BPF_SIZE((insn)->code);
19847 env->prog->aux->num_exentries++;
19851 if (BPF_MODE(insn->code) == BPF_MEMSX) {
19852 verbose(env, "sign extending loads from arena are not supported yet\n");
19853 return -EOPNOTSUPP;
19855 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
19856 env->prog->aux->num_exentries++;
19862 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
19863 size = BPF_LDST_BYTES(insn);
19864 mode = BPF_MODE(insn->code);
19866 /* If the read access is a narrower load of the field,
19867 * convert to a 4/8-byte load, to minimum program type specific
19868 * convert_ctx_access changes. If conversion is successful,
19869 * we will apply proper mask to the result.
19871 is_narrower_load = size < ctx_field_size;
19872 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
19874 if (is_narrower_load) {
19877 if (type == BPF_WRITE) {
19878 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
19883 if (ctx_field_size == 4)
19885 else if (ctx_field_size == 8)
19886 size_code = BPF_DW;
19888 insn->off = off & ~(size_default - 1);
19889 insn->code = BPF_LDX | BPF_MEM | size_code;
19893 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
19895 if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
19896 (ctx_field_size && !target_size)) {
19897 verbose(env, "bpf verifier is misconfigured\n");
19901 if (is_narrower_load && size < target_size) {
19902 u8 shift = bpf_ctx_narrow_access_offset(
19903 off, size, size_default) * 8;
19904 if (shift && cnt + 1 >= INSN_BUF_SIZE) {
19905 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
19908 if (ctx_field_size <= 4) {
19910 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
19913 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
19914 (1 << size * 8) - 1);
19917 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
19920 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
19921 (1ULL << size * 8) - 1);
19924 if (mode == BPF_MEMSX)
19925 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
19926 insn->dst_reg, insn->dst_reg,
19930 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19936 /* keep walking new program and skip insns we just inserted */
19937 env->prog = new_prog;
19938 insn = new_prog->insnsi + i + delta;
19944 static int jit_subprogs(struct bpf_verifier_env *env)
19946 struct bpf_prog *prog = env->prog, **func, *tmp;
19947 int i, j, subprog_start, subprog_end = 0, len, subprog;
19948 struct bpf_map *map_ptr;
19949 struct bpf_insn *insn;
19950 void *old_bpf_func;
19951 int err, num_exentries;
19953 if (env->subprog_cnt <= 1)
19956 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19957 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
19960 /* Upon error here we cannot fall back to interpreter but
19961 * need a hard reject of the program. Thus -EFAULT is
19962 * propagated in any case.
19964 subprog = find_subprog(env, i + insn->imm + 1);
19966 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
19967 i + insn->imm + 1);
19970 /* temporarily remember subprog id inside insn instead of
19971 * aux_data, since next loop will split up all insns into funcs
19973 insn->off = subprog;
19974 /* remember original imm in case JIT fails and fallback
19975 * to interpreter will be needed
19977 env->insn_aux_data[i].call_imm = insn->imm;
19978 /* point imm to __bpf_call_base+1 from JITs point of view */
19980 if (bpf_pseudo_func(insn)) {
19981 #if defined(MODULES_VADDR)
19982 u64 addr = MODULES_VADDR;
19984 u64 addr = VMALLOC_START;
19986 /* jit (e.g. x86_64) may emit fewer instructions
19987 * if it learns a u32 imm is the same as a u64 imm.
19988 * Set close enough to possible prog address.
19990 insn[0].imm = (u32)addr;
19991 insn[1].imm = addr >> 32;
19995 err = bpf_prog_alloc_jited_linfo(prog);
19997 goto out_undo_insn;
20000 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
20002 goto out_undo_insn;
20004 for (i = 0; i < env->subprog_cnt; i++) {
20005 subprog_start = subprog_end;
20006 subprog_end = env->subprog_info[i + 1].start;
20008 len = subprog_end - subprog_start;
20009 /* bpf_prog_run() doesn't call subprogs directly,
20010 * hence main prog stats include the runtime of subprogs.
20011 * subprogs don't have IDs and not reachable via prog_get_next_id
20012 * func[i]->stats will never be accessed and stays NULL
20014 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
20017 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
20018 len * sizeof(struct bpf_insn));
20019 func[i]->type = prog->type;
20020 func[i]->len = len;
20021 if (bpf_prog_calc_tag(func[i]))
20023 func[i]->is_func = 1;
20024 func[i]->sleepable = prog->sleepable;
20025 func[i]->aux->func_idx = i;
20026 /* Below members will be freed only at prog->aux */
20027 func[i]->aux->btf = prog->aux->btf;
20028 func[i]->aux->func_info = prog->aux->func_info;
20029 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
20030 func[i]->aux->poke_tab = prog->aux->poke_tab;
20031 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
20033 for (j = 0; j < prog->aux->size_poke_tab; j++) {
20034 struct bpf_jit_poke_descriptor *poke;
20036 poke = &prog->aux->poke_tab[j];
20037 if (poke->insn_idx < subprog_end &&
20038 poke->insn_idx >= subprog_start)
20039 poke->aux = func[i]->aux;
20042 func[i]->aux->name[0] = 'F';
20043 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
20044 func[i]->jit_requested = 1;
20045 func[i]->blinding_requested = prog->blinding_requested;
20046 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
20047 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
20048 func[i]->aux->linfo = prog->aux->linfo;
20049 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
20050 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
20051 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
20052 func[i]->aux->arena = prog->aux->arena;
20054 insn = func[i]->insnsi;
20055 for (j = 0; j < func[i]->len; j++, insn++) {
20056 if (BPF_CLASS(insn->code) == BPF_LDX &&
20057 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
20058 BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
20059 BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
20061 if ((BPF_CLASS(insn->code) == BPF_STX ||
20062 BPF_CLASS(insn->code) == BPF_ST) &&
20063 BPF_MODE(insn->code) == BPF_PROBE_MEM32)
20065 if (BPF_CLASS(insn->code) == BPF_STX &&
20066 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
20069 func[i]->aux->num_exentries = num_exentries;
20070 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
20071 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
20073 func[i]->aux->exception_boundary = env->seen_exception;
20074 func[i] = bpf_int_jit_compile(func[i]);
20075 if (!func[i]->jited) {
20082 /* at this point all bpf functions were successfully JITed
20083 * now populate all bpf_calls with correct addresses and
20084 * run last pass of JIT
20086 for (i = 0; i < env->subprog_cnt; i++) {
20087 insn = func[i]->insnsi;
20088 for (j = 0; j < func[i]->len; j++, insn++) {
20089 if (bpf_pseudo_func(insn)) {
20090 subprog = insn->off;
20091 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
20092 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
20095 if (!bpf_pseudo_call(insn))
20097 subprog = insn->off;
20098 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
20101 /* we use the aux data to keep a list of the start addresses
20102 * of the JITed images for each function in the program
20104 * for some architectures, such as powerpc64, the imm field
20105 * might not be large enough to hold the offset of the start
20106 * address of the callee's JITed image from __bpf_call_base
20108 * in such cases, we can lookup the start address of a callee
20109 * by using its subprog id, available from the off field of
20110 * the call instruction, as an index for this list
20112 func[i]->aux->func = func;
20113 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
20114 func[i]->aux->real_func_cnt = env->subprog_cnt;
20116 for (i = 0; i < env->subprog_cnt; i++) {
20117 old_bpf_func = func[i]->bpf_func;
20118 tmp = bpf_int_jit_compile(func[i]);
20119 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
20120 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
20127 /* finally lock prog and jit images for all functions and
20128 * populate kallsysm. Begin at the first subprogram, since
20129 * bpf_prog_load will add the kallsyms for the main program.
20131 for (i = 1; i < env->subprog_cnt; i++) {
20132 err = bpf_prog_lock_ro(func[i]);
20137 for (i = 1; i < env->subprog_cnt; i++)
20138 bpf_prog_kallsyms_add(func[i]);
20140 /* Last step: make now unused interpreter insns from main
20141 * prog consistent for later dump requests, so they can
20142 * later look the same as if they were interpreted only.
20144 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
20145 if (bpf_pseudo_func(insn)) {
20146 insn[0].imm = env->insn_aux_data[i].call_imm;
20147 insn[1].imm = insn->off;
20151 if (!bpf_pseudo_call(insn))
20153 insn->off = env->insn_aux_data[i].call_imm;
20154 subprog = find_subprog(env, i + insn->off + 1);
20155 insn->imm = subprog;
20159 prog->bpf_func = func[0]->bpf_func;
20160 prog->jited_len = func[0]->jited_len;
20161 prog->aux->extable = func[0]->aux->extable;
20162 prog->aux->num_exentries = func[0]->aux->num_exentries;
20163 prog->aux->func = func;
20164 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
20165 prog->aux->real_func_cnt = env->subprog_cnt;
20166 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
20167 prog->aux->exception_boundary = func[0]->aux->exception_boundary;
20168 bpf_prog_jit_attempt_done(prog);
20171 /* We failed JIT'ing, so at this point we need to unregister poke
20172 * descriptors from subprogs, so that kernel is not attempting to
20173 * patch it anymore as we're freeing the subprog JIT memory.
20175 for (i = 0; i < prog->aux->size_poke_tab; i++) {
20176 map_ptr = prog->aux->poke_tab[i].tail_call.map;
20177 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
20179 /* At this point we're guaranteed that poke descriptors are not
20180 * live anymore. We can just unlink its descriptor table as it's
20181 * released with the main prog.
20183 for (i = 0; i < env->subprog_cnt; i++) {
20186 func[i]->aux->poke_tab = NULL;
20187 bpf_jit_free(func[i]);
20191 /* cleanup main prog to be interpreted */
20192 prog->jit_requested = 0;
20193 prog->blinding_requested = 0;
20194 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
20195 if (!bpf_pseudo_call(insn))
20198 insn->imm = env->insn_aux_data[i].call_imm;
20200 bpf_prog_jit_attempt_done(prog);
20204 static int fixup_call_args(struct bpf_verifier_env *env)
20206 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
20207 struct bpf_prog *prog = env->prog;
20208 struct bpf_insn *insn = prog->insnsi;
20209 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
20214 if (env->prog->jit_requested &&
20215 !bpf_prog_is_offloaded(env->prog->aux)) {
20216 err = jit_subprogs(env);
20219 if (err == -EFAULT)
20222 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
20223 if (has_kfunc_call) {
20224 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
20227 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
20228 /* When JIT fails the progs with bpf2bpf calls and tail_calls
20229 * have to be rejected, since interpreter doesn't support them yet.
20231 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
20234 for (i = 0; i < prog->len; i++, insn++) {
20235 if (bpf_pseudo_func(insn)) {
20236 /* When JIT fails the progs with callback calls
20237 * have to be rejected, since interpreter doesn't support them yet.
20239 verbose(env, "callbacks are not allowed in non-JITed programs\n");
20243 if (!bpf_pseudo_call(insn))
20245 depth = get_callee_stack_depth(env, insn, i);
20248 bpf_patch_call_args(insn, depth);
20255 /* replace a generic kfunc with a specialized version if necessary */
20256 static void specialize_kfunc(struct bpf_verifier_env *env,
20257 u32 func_id, u16 offset, unsigned long *addr)
20259 struct bpf_prog *prog = env->prog;
20260 bool seen_direct_write;
20264 if (bpf_dev_bound_kfunc_id(func_id)) {
20265 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
20267 *addr = (unsigned long)xdp_kfunc;
20270 /* fallback to default kfunc when not supported by netdev */
20276 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
20277 seen_direct_write = env->seen_direct_write;
20278 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
20281 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
20283 /* restore env->seen_direct_write to its original value, since
20284 * may_access_direct_pkt_data mutates it
20286 env->seen_direct_write = seen_direct_write;
20290 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
20291 u16 struct_meta_reg,
20292 u16 node_offset_reg,
20293 struct bpf_insn *insn,
20294 struct bpf_insn *insn_buf,
20297 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
20298 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
20300 insn_buf[0] = addr[0];
20301 insn_buf[1] = addr[1];
20302 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
20303 insn_buf[3] = *insn;
20307 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
20308 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
20310 const struct bpf_kfunc_desc *desc;
20313 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
20319 /* insn->imm has the btf func_id. Replace it with an offset relative to
20320 * __bpf_call_base, unless the JIT needs to call functions that are
20321 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
20323 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
20325 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
20330 if (!bpf_jit_supports_far_kfunc_call())
20331 insn->imm = BPF_CALL_IMM(desc->addr);
20334 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
20335 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
20336 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20337 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
20338 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
20340 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
20341 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
20346 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
20347 insn_buf[1] = addr[0];
20348 insn_buf[2] = addr[1];
20349 insn_buf[3] = *insn;
20351 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
20352 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
20353 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
20354 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20355 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
20357 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
20358 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
20363 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
20364 !kptr_struct_meta) {
20365 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
20370 insn_buf[0] = addr[0];
20371 insn_buf[1] = addr[1];
20372 insn_buf[2] = *insn;
20374 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
20375 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
20376 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
20377 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
20378 int struct_meta_reg = BPF_REG_3;
20379 int node_offset_reg = BPF_REG_4;
20381 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
20382 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
20383 struct_meta_reg = BPF_REG_4;
20384 node_offset_reg = BPF_REG_5;
20387 if (!kptr_struct_meta) {
20388 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
20393 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
20394 node_offset_reg, insn, insn_buf, cnt);
20395 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
20396 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
20397 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
20399 } else if (is_bpf_wq_set_callback_impl_kfunc(desc->func_id)) {
20400 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(BPF_REG_4, (long)env->prog->aux) };
20402 insn_buf[0] = ld_addrs[0];
20403 insn_buf[1] = ld_addrs[1];
20404 insn_buf[2] = *insn;
20410 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
20411 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
20413 struct bpf_subprog_info *info = env->subprog_info;
20414 int cnt = env->subprog_cnt;
20415 struct bpf_prog *prog;
20417 /* We only reserve one slot for hidden subprogs in subprog_info. */
20418 if (env->hidden_subprog_cnt) {
20419 verbose(env, "verifier internal error: only one hidden subprog supported\n");
20422 /* We're not patching any existing instruction, just appending the new
20423 * ones for the hidden subprog. Hence all of the adjustment operations
20424 * in bpf_patch_insn_data are no-ops.
20426 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
20430 info[cnt + 1].start = info[cnt].start;
20431 info[cnt].start = prog->len - len + 1;
20432 env->subprog_cnt++;
20433 env->hidden_subprog_cnt++;
20437 /* Do various post-verification rewrites in a single program pass.
20438 * These rewrites simplify JIT and interpreter implementations.
20440 static int do_misc_fixups(struct bpf_verifier_env *env)
20442 struct bpf_prog *prog = env->prog;
20443 enum bpf_attach_type eatype = prog->expected_attach_type;
20444 enum bpf_prog_type prog_type = resolve_prog_type(prog);
20445 struct bpf_insn *insn = prog->insnsi;
20446 const struct bpf_func_proto *fn;
20447 const int insn_cnt = prog->len;
20448 const struct bpf_map_ops *ops;
20449 struct bpf_insn_aux_data *aux;
20450 struct bpf_insn *insn_buf = env->insn_buf;
20451 struct bpf_prog *new_prog;
20452 struct bpf_map *map_ptr;
20453 int i, ret, cnt, delta = 0, cur_subprog = 0;
20454 struct bpf_subprog_info *subprogs = env->subprog_info;
20455 u16 stack_depth = subprogs[cur_subprog].stack_depth;
20456 u16 stack_depth_extra = 0;
20458 if (env->seen_exception && !env->exception_callback_subprog) {
20459 struct bpf_insn patch[] = {
20460 env->prog->insnsi[insn_cnt - 1],
20461 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
20465 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
20469 insn = prog->insnsi;
20471 env->exception_callback_subprog = env->subprog_cnt - 1;
20472 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */
20473 mark_subprog_exc_cb(env, env->exception_callback_subprog);
20476 for (i = 0; i < insn_cnt;) {
20477 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
20478 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
20479 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
20480 /* convert to 32-bit mov that clears upper 32-bit */
20481 insn->code = BPF_ALU | BPF_MOV | BPF_X;
20482 /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
20485 } /* cast from as(0) to as(1) should be handled by JIT */
20489 if (env->insn_aux_data[i + delta].needs_zext)
20490 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
20491 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
20493 /* Make sdiv/smod divide-by-minus-one exceptions impossible. */
20494 if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
20495 insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
20496 insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
20497 insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
20498 insn->off == 1 && insn->imm == -1) {
20499 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
20500 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
20501 struct bpf_insn *patchlet;
20502 struct bpf_insn chk_and_sdiv[] = {
20503 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
20504 BPF_NEG | BPF_K, insn->dst_reg,
20507 struct bpf_insn chk_and_smod[] = {
20508 BPF_MOV32_IMM(insn->dst_reg, 0),
20511 patchlet = isdiv ? chk_and_sdiv : chk_and_smod;
20512 cnt = isdiv ? ARRAY_SIZE(chk_and_sdiv) : ARRAY_SIZE(chk_and_smod);
20514 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
20519 env->prog = prog = new_prog;
20520 insn = new_prog->insnsi + i + delta;
20524 /* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
20525 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
20526 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
20527 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
20528 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
20529 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
20530 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
20531 bool is_sdiv = isdiv && insn->off == 1;
20532 bool is_smod = !isdiv && insn->off == 1;
20533 struct bpf_insn *patchlet;
20534 struct bpf_insn chk_and_div[] = {
20535 /* [R,W]x div 0 -> 0 */
20536 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20537 BPF_JNE | BPF_K, insn->src_reg,
20539 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
20540 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
20543 struct bpf_insn chk_and_mod[] = {
20544 /* [R,W]x mod 0 -> [R,W]x */
20545 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20546 BPF_JEQ | BPF_K, insn->src_reg,
20547 0, 1 + (is64 ? 0 : 1), 0),
20549 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
20550 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
20552 struct bpf_insn chk_and_sdiv[] = {
20553 /* [R,W]x sdiv 0 -> 0
20554 * LLONG_MIN sdiv -1 -> LLONG_MIN
20555 * INT_MIN sdiv -1 -> INT_MIN
20557 BPF_MOV64_REG(BPF_REG_AX, insn->src_reg),
20558 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
20559 BPF_ADD | BPF_K, BPF_REG_AX,
20561 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20562 BPF_JGT | BPF_K, BPF_REG_AX,
20564 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20565 BPF_JEQ | BPF_K, BPF_REG_AX,
20567 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
20568 BPF_MOV | BPF_K, insn->dst_reg,
20570 /* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
20571 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
20572 BPF_NEG | BPF_K, insn->dst_reg,
20574 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
20577 struct bpf_insn chk_and_smod[] = {
20578 /* [R,W]x mod 0 -> [R,W]x */
20579 /* [R,W]x mod -1 -> 0 */
20580 BPF_MOV64_REG(BPF_REG_AX, insn->src_reg),
20581 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
20582 BPF_ADD | BPF_K, BPF_REG_AX,
20584 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20585 BPF_JGT | BPF_K, BPF_REG_AX,
20587 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
20588 BPF_JEQ | BPF_K, BPF_REG_AX,
20589 0, 3 + (is64 ? 0 : 1), 1),
20590 BPF_MOV32_IMM(insn->dst_reg, 0),
20591 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
20593 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
20594 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
20598 patchlet = chk_and_sdiv;
20599 cnt = ARRAY_SIZE(chk_and_sdiv);
20600 } else if (is_smod) {
20601 patchlet = chk_and_smod;
20602 cnt = ARRAY_SIZE(chk_and_smod) - (is64 ? 2 : 0);
20604 patchlet = isdiv ? chk_and_div : chk_and_mod;
20605 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
20606 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
20609 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
20614 env->prog = prog = new_prog;
20615 insn = new_prog->insnsi + i + delta;
20619 /* Make it impossible to de-reference a userspace address */
20620 if (BPF_CLASS(insn->code) == BPF_LDX &&
20621 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
20622 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
20623 struct bpf_insn *patch = &insn_buf[0];
20624 u64 uaddress_limit = bpf_arch_uaddress_limit();
20626 if (!uaddress_limit)
20629 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
20631 *patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
20632 *patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
20633 *patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
20635 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
20636 *patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
20638 cnt = patch - insn_buf;
20639 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20644 env->prog = prog = new_prog;
20645 insn = new_prog->insnsi + i + delta;
20649 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
20650 if (BPF_CLASS(insn->code) == BPF_LD &&
20651 (BPF_MODE(insn->code) == BPF_ABS ||
20652 BPF_MODE(insn->code) == BPF_IND)) {
20653 cnt = env->ops->gen_ld_abs(insn, insn_buf);
20654 if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
20655 verbose(env, "bpf verifier is misconfigured\n");
20659 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20664 env->prog = prog = new_prog;
20665 insn = new_prog->insnsi + i + delta;
20669 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
20670 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
20671 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
20672 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
20673 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
20674 struct bpf_insn *patch = &insn_buf[0];
20675 bool issrc, isneg, isimm;
20678 aux = &env->insn_aux_data[i + delta];
20679 if (!aux->alu_state ||
20680 aux->alu_state == BPF_ALU_NON_POINTER)
20683 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
20684 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
20685 BPF_ALU_SANITIZE_SRC;
20686 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
20688 off_reg = issrc ? insn->src_reg : insn->dst_reg;
20690 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
20693 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
20694 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
20695 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
20696 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
20697 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
20698 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
20699 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
20702 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
20703 insn->src_reg = BPF_REG_AX;
20705 insn->code = insn->code == code_add ?
20706 code_sub : code_add;
20708 if (issrc && isneg && !isimm)
20709 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
20710 cnt = patch - insn_buf;
20712 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20717 env->prog = prog = new_prog;
20718 insn = new_prog->insnsi + i + delta;
20722 if (is_may_goto_insn(insn)) {
20723 int stack_off = -stack_depth - 8;
20725 stack_depth_extra = 8;
20726 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
20727 if (insn->off >= 0)
20728 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
20730 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
20731 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
20732 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
20735 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20740 env->prog = prog = new_prog;
20741 insn = new_prog->insnsi + i + delta;
20745 if (insn->code != (BPF_JMP | BPF_CALL))
20747 if (insn->src_reg == BPF_PSEUDO_CALL)
20749 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
20750 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
20756 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20761 env->prog = prog = new_prog;
20762 insn = new_prog->insnsi + i + delta;
20766 /* Skip inlining the helper call if the JIT does it. */
20767 if (bpf_jit_inlines_helper_call(insn->imm))
20770 if (insn->imm == BPF_FUNC_get_route_realm)
20771 prog->dst_needed = 1;
20772 if (insn->imm == BPF_FUNC_get_prandom_u32)
20773 bpf_user_rnd_init_once();
20774 if (insn->imm == BPF_FUNC_override_return)
20775 prog->kprobe_override = 1;
20776 if (insn->imm == BPF_FUNC_tail_call) {
20777 /* If we tail call into other programs, we
20778 * cannot make any assumptions since they can
20779 * be replaced dynamically during runtime in
20780 * the program array.
20782 prog->cb_access = 1;
20783 if (!allow_tail_call_in_subprogs(env))
20784 prog->aux->stack_depth = MAX_BPF_STACK;
20785 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
20787 /* mark bpf_tail_call as different opcode to avoid
20788 * conditional branch in the interpreter for every normal
20789 * call and to prevent accidental JITing by JIT compiler
20790 * that doesn't support bpf_tail_call yet
20793 insn->code = BPF_JMP | BPF_TAIL_CALL;
20795 aux = &env->insn_aux_data[i + delta];
20796 if (env->bpf_capable && !prog->blinding_requested &&
20797 prog->jit_requested &&
20798 !bpf_map_key_poisoned(aux) &&
20799 !bpf_map_ptr_poisoned(aux) &&
20800 !bpf_map_ptr_unpriv(aux)) {
20801 struct bpf_jit_poke_descriptor desc = {
20802 .reason = BPF_POKE_REASON_TAIL_CALL,
20803 .tail_call.map = aux->map_ptr_state.map_ptr,
20804 .tail_call.key = bpf_map_key_immediate(aux),
20805 .insn_idx = i + delta,
20808 ret = bpf_jit_add_poke_descriptor(prog, &desc);
20810 verbose(env, "adding tail call poke descriptor failed\n");
20814 insn->imm = ret + 1;
20818 if (!bpf_map_ptr_unpriv(aux))
20821 /* instead of changing every JIT dealing with tail_call
20822 * emit two extra insns:
20823 * if (index >= max_entries) goto out;
20824 * index &= array->index_mask;
20825 * to avoid out-of-bounds cpu speculation
20827 if (bpf_map_ptr_poisoned(aux)) {
20828 verbose(env, "tail_call abusing map_ptr\n");
20832 map_ptr = aux->map_ptr_state.map_ptr;
20833 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
20834 map_ptr->max_entries, 2);
20835 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
20836 container_of(map_ptr,
20839 insn_buf[2] = *insn;
20841 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20846 env->prog = prog = new_prog;
20847 insn = new_prog->insnsi + i + delta;
20851 if (insn->imm == BPF_FUNC_timer_set_callback) {
20852 /* The verifier will process callback_fn as many times as necessary
20853 * with different maps and the register states prepared by
20854 * set_timer_callback_state will be accurate.
20856 * The following use case is valid:
20857 * map1 is shared by prog1, prog2, prog3.
20858 * prog1 calls bpf_timer_init for some map1 elements
20859 * prog2 calls bpf_timer_set_callback for some map1 elements.
20860 * Those that were not bpf_timer_init-ed will return -EINVAL.
20861 * prog3 calls bpf_timer_start for some map1 elements.
20862 * Those that were not both bpf_timer_init-ed and
20863 * bpf_timer_set_callback-ed will return -EINVAL.
20865 struct bpf_insn ld_addrs[2] = {
20866 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
20869 insn_buf[0] = ld_addrs[0];
20870 insn_buf[1] = ld_addrs[1];
20871 insn_buf[2] = *insn;
20874 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20879 env->prog = prog = new_prog;
20880 insn = new_prog->insnsi + i + delta;
20881 goto patch_call_imm;
20884 if (is_storage_get_function(insn->imm)) {
20885 if (!in_sleepable(env) ||
20886 env->insn_aux_data[i + delta].storage_get_func_atomic)
20887 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
20889 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
20890 insn_buf[1] = *insn;
20893 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20898 env->prog = prog = new_prog;
20899 insn = new_prog->insnsi + i + delta;
20900 goto patch_call_imm;
20903 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
20904 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
20905 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
20906 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
20908 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
20909 insn_buf[1] = *insn;
20912 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20917 env->prog = prog = new_prog;
20918 insn = new_prog->insnsi + i + delta;
20919 goto patch_call_imm;
20922 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
20923 * and other inlining handlers are currently limited to 64 bit
20926 if (prog->jit_requested && BITS_PER_LONG == 64 &&
20927 (insn->imm == BPF_FUNC_map_lookup_elem ||
20928 insn->imm == BPF_FUNC_map_update_elem ||
20929 insn->imm == BPF_FUNC_map_delete_elem ||
20930 insn->imm == BPF_FUNC_map_push_elem ||
20931 insn->imm == BPF_FUNC_map_pop_elem ||
20932 insn->imm == BPF_FUNC_map_peek_elem ||
20933 insn->imm == BPF_FUNC_redirect_map ||
20934 insn->imm == BPF_FUNC_for_each_map_elem ||
20935 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
20936 aux = &env->insn_aux_data[i + delta];
20937 if (bpf_map_ptr_poisoned(aux))
20938 goto patch_call_imm;
20940 map_ptr = aux->map_ptr_state.map_ptr;
20941 ops = map_ptr->ops;
20942 if (insn->imm == BPF_FUNC_map_lookup_elem &&
20943 ops->map_gen_lookup) {
20944 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
20945 if (cnt == -EOPNOTSUPP)
20946 goto patch_map_ops_generic;
20947 if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
20948 verbose(env, "bpf verifier is misconfigured\n");
20952 new_prog = bpf_patch_insn_data(env, i + delta,
20958 env->prog = prog = new_prog;
20959 insn = new_prog->insnsi + i + delta;
20963 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
20964 (void *(*)(struct bpf_map *map, void *key))NULL));
20965 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
20966 (long (*)(struct bpf_map *map, void *key))NULL));
20967 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
20968 (long (*)(struct bpf_map *map, void *key, void *value,
20970 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
20971 (long (*)(struct bpf_map *map, void *value,
20973 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
20974 (long (*)(struct bpf_map *map, void *value))NULL));
20975 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
20976 (long (*)(struct bpf_map *map, void *value))NULL));
20977 BUILD_BUG_ON(!__same_type(ops->map_redirect,
20978 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
20979 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
20980 (long (*)(struct bpf_map *map,
20981 bpf_callback_t callback_fn,
20982 void *callback_ctx,
20984 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
20985 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
20987 patch_map_ops_generic:
20988 switch (insn->imm) {
20989 case BPF_FUNC_map_lookup_elem:
20990 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
20992 case BPF_FUNC_map_update_elem:
20993 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
20995 case BPF_FUNC_map_delete_elem:
20996 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
20998 case BPF_FUNC_map_push_elem:
20999 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
21001 case BPF_FUNC_map_pop_elem:
21002 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
21004 case BPF_FUNC_map_peek_elem:
21005 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
21007 case BPF_FUNC_redirect_map:
21008 insn->imm = BPF_CALL_IMM(ops->map_redirect);
21010 case BPF_FUNC_for_each_map_elem:
21011 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
21013 case BPF_FUNC_map_lookup_percpu_elem:
21014 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
21018 goto patch_call_imm;
21021 /* Implement bpf_jiffies64 inline. */
21022 if (prog->jit_requested && BITS_PER_LONG == 64 &&
21023 insn->imm == BPF_FUNC_jiffies64) {
21024 struct bpf_insn ld_jiffies_addr[2] = {
21025 BPF_LD_IMM64(BPF_REG_0,
21026 (unsigned long)&jiffies),
21029 insn_buf[0] = ld_jiffies_addr[0];
21030 insn_buf[1] = ld_jiffies_addr[1];
21031 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
21035 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
21041 env->prog = prog = new_prog;
21042 insn = new_prog->insnsi + i + delta;
21046 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
21047 /* Implement bpf_get_smp_processor_id() inline. */
21048 if (insn->imm == BPF_FUNC_get_smp_processor_id &&
21049 verifier_inlines_helper_call(env, insn->imm)) {
21050 /* BPF_FUNC_get_smp_processor_id inlining is an
21051 * optimization, so if pcpu_hot.cpu_number is ever
21052 * changed in some incompatible and hard to support
21053 * way, it's fine to back out this inlining logic
21055 insn_buf[0] = BPF_MOV32_IMM(BPF_REG_0, (u32)(unsigned long)&pcpu_hot.cpu_number);
21056 insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
21057 insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
21060 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21065 env->prog = prog = new_prog;
21066 insn = new_prog->insnsi + i + delta;
21070 /* Implement bpf_get_func_arg inline. */
21071 if (prog_type == BPF_PROG_TYPE_TRACING &&
21072 insn->imm == BPF_FUNC_get_func_arg) {
21073 /* Load nr_args from ctx - 8 */
21074 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
21075 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
21076 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
21077 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
21078 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
21079 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
21080 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
21081 insn_buf[7] = BPF_JMP_A(1);
21082 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
21085 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21090 env->prog = prog = new_prog;
21091 insn = new_prog->insnsi + i + delta;
21095 /* Implement bpf_get_func_ret inline. */
21096 if (prog_type == BPF_PROG_TYPE_TRACING &&
21097 insn->imm == BPF_FUNC_get_func_ret) {
21098 if (eatype == BPF_TRACE_FEXIT ||
21099 eatype == BPF_MODIFY_RETURN) {
21100 /* Load nr_args from ctx - 8 */
21101 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
21102 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
21103 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
21104 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
21105 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
21106 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
21109 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
21113 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21118 env->prog = prog = new_prog;
21119 insn = new_prog->insnsi + i + delta;
21123 /* Implement get_func_arg_cnt inline. */
21124 if (prog_type == BPF_PROG_TYPE_TRACING &&
21125 insn->imm == BPF_FUNC_get_func_arg_cnt) {
21126 /* Load nr_args from ctx - 8 */
21127 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
21129 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
21133 env->prog = prog = new_prog;
21134 insn = new_prog->insnsi + i + delta;
21138 /* Implement bpf_get_func_ip inline. */
21139 if (prog_type == BPF_PROG_TYPE_TRACING &&
21140 insn->imm == BPF_FUNC_get_func_ip) {
21141 /* Load IP address from ctx - 16 */
21142 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
21144 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
21148 env->prog = prog = new_prog;
21149 insn = new_prog->insnsi + i + delta;
21153 /* Implement bpf_get_branch_snapshot inline. */
21154 if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
21155 prog->jit_requested && BITS_PER_LONG == 64 &&
21156 insn->imm == BPF_FUNC_get_branch_snapshot) {
21157 /* We are dealing with the following func protos:
21158 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
21159 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
21161 const u32 br_entry_size = sizeof(struct perf_branch_entry);
21163 /* struct perf_branch_entry is part of UAPI and is
21164 * used as an array element, so extremely unlikely to
21165 * ever grow or shrink
21167 BUILD_BUG_ON(br_entry_size != 24);
21169 /* if (unlikely(flags)) return -EINVAL */
21170 insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
21172 /* Transform size (bytes) into number of entries (cnt = size / 24).
21173 * But to avoid expensive division instruction, we implement
21174 * divide-by-3 through multiplication, followed by further
21175 * division by 8 through 3-bit right shift.
21176 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
21177 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
21179 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
21181 insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
21182 insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
21183 insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
21185 /* call perf_snapshot_branch_stack implementation */
21186 insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
21187 /* if (entry_cnt == 0) return -ENOENT */
21188 insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
21189 /* return entry_cnt * sizeof(struct perf_branch_entry) */
21190 insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
21191 insn_buf[7] = BPF_JMP_A(3);
21192 /* return -EINVAL; */
21193 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
21194 insn_buf[9] = BPF_JMP_A(1);
21195 /* return -ENOENT; */
21196 insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
21199 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21204 env->prog = prog = new_prog;
21205 insn = new_prog->insnsi + i + delta;
21209 /* Implement bpf_kptr_xchg inline */
21210 if (prog->jit_requested && BITS_PER_LONG == 64 &&
21211 insn->imm == BPF_FUNC_kptr_xchg &&
21212 bpf_jit_supports_ptr_xchg()) {
21213 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
21214 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
21217 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21222 env->prog = prog = new_prog;
21223 insn = new_prog->insnsi + i + delta;
21227 fn = env->ops->get_func_proto(insn->imm, env->prog);
21228 /* all functions that have prototype and verifier allowed
21229 * programs to call them, must be real in-kernel functions
21233 "kernel subsystem misconfigured func %s#%d\n",
21234 func_id_name(insn->imm), insn->imm);
21237 insn->imm = fn->func - __bpf_call_base;
21239 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
21240 subprogs[cur_subprog].stack_depth += stack_depth_extra;
21241 subprogs[cur_subprog].stack_extra = stack_depth_extra;
21243 stack_depth = subprogs[cur_subprog].stack_depth;
21244 stack_depth_extra = 0;
21250 env->prog->aux->stack_depth = subprogs[0].stack_depth;
21251 for (i = 0; i < env->subprog_cnt; i++) {
21252 int subprog_start = subprogs[i].start;
21253 int stack_slots = subprogs[i].stack_extra / 8;
21257 if (stack_slots > 1) {
21258 verbose(env, "verifier bug: stack_slots supports may_goto only\n");
21262 /* Add ST insn to subprog prologue to init extra stack */
21263 insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP,
21264 -subprogs[i].stack_depth, BPF_MAX_LOOPS);
21265 /* Copy first actual insn to preserve it */
21266 insn_buf[1] = env->prog->insnsi[subprog_start];
21268 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2);
21271 env->prog = prog = new_prog;
21273 * If may_goto is a first insn of a prog there could be a jmp
21274 * insn that points to it, hence adjust all such jmps to point
21275 * to insn after BPF_ST that inits may_goto count.
21276 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
21278 WARN_ON(adjust_jmp_off(env->prog, subprog_start, 1));
21281 /* Since poke tab is now finalized, publish aux to tracker. */
21282 for (i = 0; i < prog->aux->size_poke_tab; i++) {
21283 map_ptr = prog->aux->poke_tab[i].tail_call.map;
21284 if (!map_ptr->ops->map_poke_track ||
21285 !map_ptr->ops->map_poke_untrack ||
21286 !map_ptr->ops->map_poke_run) {
21287 verbose(env, "bpf verifier is misconfigured\n");
21291 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
21293 verbose(env, "tracking tail call prog failed\n");
21298 sort_kfunc_descs_by_imm_off(env->prog);
21303 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
21306 u32 callback_subprogno,
21309 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
21310 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
21311 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
21312 int reg_loop_max = BPF_REG_6;
21313 int reg_loop_cnt = BPF_REG_7;
21314 int reg_loop_ctx = BPF_REG_8;
21316 struct bpf_insn *insn_buf = env->insn_buf;
21317 struct bpf_prog *new_prog;
21318 u32 callback_start;
21319 u32 call_insn_offset;
21320 s32 callback_offset;
21323 /* This represents an inlined version of bpf_iter.c:bpf_loop,
21324 * be careful to modify this code in sync.
21327 /* Return error and jump to the end of the patch if
21328 * expected number of iterations is too big.
21330 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
21331 insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
21332 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
21333 /* spill R6, R7, R8 to use these as loop vars */
21334 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
21335 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
21336 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
21337 /* initialize loop vars */
21338 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
21339 insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
21340 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
21342 * if reg_loop_cnt >= reg_loop_max skip the loop body
21344 insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
21346 * correct callback offset would be set after patching
21348 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
21349 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
21350 insn_buf[cnt++] = BPF_CALL_REL(0);
21351 /* increment loop counter */
21352 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
21353 /* jump to loop header if callback returned 0 */
21354 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
21355 /* return value of bpf_loop,
21356 * set R0 to the number of iterations
21358 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
21359 /* restore original values of R6, R7, R8 */
21360 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
21361 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
21362 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
21365 new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
21369 /* callback start is known only after patching */
21370 callback_start = env->subprog_info[callback_subprogno].start;
21371 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
21372 call_insn_offset = position + 12;
21373 callback_offset = callback_start - call_insn_offset - 1;
21374 new_prog->insnsi[call_insn_offset].imm = callback_offset;
21379 static bool is_bpf_loop_call(struct bpf_insn *insn)
21381 return insn->code == (BPF_JMP | BPF_CALL) &&
21382 insn->src_reg == 0 &&
21383 insn->imm == BPF_FUNC_loop;
21386 /* For all sub-programs in the program (including main) check
21387 * insn_aux_data to see if there are bpf_loop calls that require
21388 * inlining. If such calls are found the calls are replaced with a
21389 * sequence of instructions produced by `inline_bpf_loop` function and
21390 * subprog stack_depth is increased by the size of 3 registers.
21391 * This stack space is used to spill values of the R6, R7, R8. These
21392 * registers are used to store the loop bound, counter and context
21395 static int optimize_bpf_loop(struct bpf_verifier_env *env)
21397 struct bpf_subprog_info *subprogs = env->subprog_info;
21398 int i, cur_subprog = 0, cnt, delta = 0;
21399 struct bpf_insn *insn = env->prog->insnsi;
21400 int insn_cnt = env->prog->len;
21401 u16 stack_depth = subprogs[cur_subprog].stack_depth;
21402 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
21403 u16 stack_depth_extra = 0;
21405 for (i = 0; i < insn_cnt; i++, insn++) {
21406 struct bpf_loop_inline_state *inline_state =
21407 &env->insn_aux_data[i + delta].loop_inline_state;
21409 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
21410 struct bpf_prog *new_prog;
21412 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
21413 new_prog = inline_bpf_loop(env,
21415 -(stack_depth + stack_depth_extra),
21416 inline_state->callback_subprogno,
21422 env->prog = new_prog;
21423 insn = new_prog->insnsi + i + delta;
21426 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
21427 subprogs[cur_subprog].stack_depth += stack_depth_extra;
21429 stack_depth = subprogs[cur_subprog].stack_depth;
21430 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
21431 stack_depth_extra = 0;
21435 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
21440 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
21441 * adjust subprograms stack depth when possible.
21443 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
21445 struct bpf_subprog_info *subprog = env->subprog_info;
21446 struct bpf_insn_aux_data *aux = env->insn_aux_data;
21447 struct bpf_insn *insn = env->prog->insnsi;
21448 int insn_cnt = env->prog->len;
21450 bool modified = false;
21453 for (i = 0; i < insn_cnt; i++, insn++) {
21454 if (aux[i].fastcall_spills_num > 0) {
21455 spills_num = aux[i].fastcall_spills_num;
21456 /* NOPs would be removed by opt_remove_nops() */
21457 for (j = 1; j <= spills_num; ++j) {
21463 if ((subprog + 1)->start == i + 1) {
21464 if (modified && !subprog->keep_fastcall_stack)
21465 subprog->stack_depth = -subprog->fastcall_stack_off;
21474 static void free_states(struct bpf_verifier_env *env)
21476 struct bpf_verifier_state_list *sl, *sln;
21479 sl = env->free_list;
21482 free_verifier_state(&sl->state, false);
21486 env->free_list = NULL;
21488 if (!env->explored_states)
21491 for (i = 0; i < state_htab_size(env); i++) {
21492 sl = env->explored_states[i];
21496 free_verifier_state(&sl->state, false);
21500 env->explored_states[i] = NULL;
21504 static int do_check_common(struct bpf_verifier_env *env, int subprog)
21506 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
21507 struct bpf_subprog_info *sub = subprog_info(env, subprog);
21508 struct bpf_verifier_state *state;
21509 struct bpf_reg_state *regs;
21512 env->prev_linfo = NULL;
21515 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
21518 state->curframe = 0;
21519 state->speculative = false;
21520 state->branches = 1;
21521 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
21522 if (!state->frame[0]) {
21526 env->cur_state = state;
21527 init_func_state(env, state->frame[0],
21528 BPF_MAIN_FUNC /* callsite */,
21531 state->first_insn_idx = env->subprog_info[subprog].start;
21532 state->last_insn_idx = -1;
21534 regs = state->frame[state->curframe]->regs;
21535 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
21536 const char *sub_name = subprog_name(env, subprog);
21537 struct bpf_subprog_arg_info *arg;
21538 struct bpf_reg_state *reg;
21540 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
21541 ret = btf_prepare_func_args(env, subprog);
21545 if (subprog_is_exc_cb(env, subprog)) {
21546 state->frame[0]->in_exception_callback_fn = true;
21547 /* We have already ensured that the callback returns an integer, just
21548 * like all global subprogs. We need to determine it only has a single
21551 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
21552 verbose(env, "exception cb only supports single integer argument\n");
21557 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
21558 arg = &sub->args[i - BPF_REG_1];
21561 if (arg->arg_type == ARG_PTR_TO_CTX) {
21562 reg->type = PTR_TO_CTX;
21563 mark_reg_known_zero(env, regs, i);
21564 } else if (arg->arg_type == ARG_ANYTHING) {
21565 reg->type = SCALAR_VALUE;
21566 mark_reg_unknown(env, regs, i);
21567 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
21568 /* assume unspecial LOCAL dynptr type */
21569 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
21570 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
21571 reg->type = PTR_TO_MEM;
21572 if (arg->arg_type & PTR_MAYBE_NULL)
21573 reg->type |= PTR_MAYBE_NULL;
21574 mark_reg_known_zero(env, regs, i);
21575 reg->mem_size = arg->mem_size;
21576 reg->id = ++env->id_gen;
21577 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
21578 reg->type = PTR_TO_BTF_ID;
21579 if (arg->arg_type & PTR_MAYBE_NULL)
21580 reg->type |= PTR_MAYBE_NULL;
21581 if (arg->arg_type & PTR_UNTRUSTED)
21582 reg->type |= PTR_UNTRUSTED;
21583 if (arg->arg_type & PTR_TRUSTED)
21584 reg->type |= PTR_TRUSTED;
21585 mark_reg_known_zero(env, regs, i);
21586 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
21587 reg->btf_id = arg->btf_id;
21588 reg->id = ++env->id_gen;
21589 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
21590 /* caller can pass either PTR_TO_ARENA or SCALAR */
21591 mark_reg_unknown(env, regs, i);
21593 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
21594 i - BPF_REG_1, arg->arg_type);
21600 /* if main BPF program has associated BTF info, validate that
21601 * it's matching expected signature, and otherwise mark BTF
21602 * info for main program as unreliable
21604 if (env->prog->aux->func_info_aux) {
21605 ret = btf_prepare_func_args(env, 0);
21606 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
21607 env->prog->aux->func_info_aux[0].unreliable = true;
21610 /* 1st arg to a function */
21611 regs[BPF_REG_1].type = PTR_TO_CTX;
21612 mark_reg_known_zero(env, regs, BPF_REG_1);
21615 ret = do_check(env);
21617 /* check for NULL is necessary, since cur_state can be freed inside
21618 * do_check() under memory pressure.
21620 if (env->cur_state) {
21621 free_verifier_state(env->cur_state, true);
21622 env->cur_state = NULL;
21624 while (!pop_stack(env, NULL, NULL, false));
21625 if (!ret && pop_log)
21626 bpf_vlog_reset(&env->log, 0);
21631 /* Lazily verify all global functions based on their BTF, if they are called
21632 * from main BPF program or any of subprograms transitively.
21633 * BPF global subprogs called from dead code are not validated.
21634 * All callable global functions must pass verification.
21635 * Otherwise the whole program is rejected.
21646 * foo() will be verified first for R1=any_scalar_value. During verification it
21647 * will be assumed that bar() already verified successfully and call to bar()
21648 * from foo() will be checked for type match only. Later bar() will be verified
21649 * independently to check that it's safe for R1=any_scalar_value.
21651 static int do_check_subprogs(struct bpf_verifier_env *env)
21653 struct bpf_prog_aux *aux = env->prog->aux;
21654 struct bpf_func_info_aux *sub_aux;
21655 int i, ret, new_cnt;
21657 if (!aux->func_info)
21660 /* exception callback is presumed to be always called */
21661 if (env->exception_callback_subprog)
21662 subprog_aux(env, env->exception_callback_subprog)->called = true;
21666 for (i = 1; i < env->subprog_cnt; i++) {
21667 if (!subprog_is_global(env, i))
21670 sub_aux = subprog_aux(env, i);
21671 if (!sub_aux->called || sub_aux->verified)
21674 env->insn_idx = env->subprog_info[i].start;
21675 WARN_ON_ONCE(env->insn_idx == 0);
21676 ret = do_check_common(env, i);
21679 } else if (env->log.level & BPF_LOG_LEVEL) {
21680 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
21681 i, subprog_name(env, i));
21684 /* We verified new global subprog, it might have called some
21685 * more global subprogs that we haven't verified yet, so we
21686 * need to do another pass over subprogs to verify those.
21688 sub_aux->verified = true;
21692 /* We can't loop forever as we verify at least one global subprog on
21701 static int do_check_main(struct bpf_verifier_env *env)
21706 ret = do_check_common(env, 0);
21708 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
21713 static void print_verification_stats(struct bpf_verifier_env *env)
21717 if (env->log.level & BPF_LOG_STATS) {
21718 verbose(env, "verification time %lld usec\n",
21719 div_u64(env->verification_time, 1000));
21720 verbose(env, "stack depth ");
21721 for (i = 0; i < env->subprog_cnt; i++) {
21722 u32 depth = env->subprog_info[i].stack_depth;
21724 verbose(env, "%d", depth);
21725 if (i + 1 < env->subprog_cnt)
21728 verbose(env, "\n");
21730 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
21731 "total_states %d peak_states %d mark_read %d\n",
21732 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
21733 env->max_states_per_insn, env->total_states,
21734 env->peak_states, env->longest_mark_read_walk);
21737 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
21739 const struct btf_type *t, *func_proto;
21740 const struct bpf_struct_ops_desc *st_ops_desc;
21741 const struct bpf_struct_ops *st_ops;
21742 const struct btf_member *member;
21743 struct bpf_prog *prog = env->prog;
21744 u32 btf_id, member_idx;
21749 if (!prog->gpl_compatible) {
21750 verbose(env, "struct ops programs must have a GPL compatible license\n");
21754 if (!prog->aux->attach_btf_id)
21757 btf = prog->aux->attach_btf;
21758 if (btf_is_module(btf)) {
21759 /* Make sure st_ops is valid through the lifetime of env */
21760 env->attach_btf_mod = btf_try_get_module(btf);
21761 if (!env->attach_btf_mod) {
21762 verbose(env, "struct_ops module %s is not found\n",
21763 btf_get_name(btf));
21768 btf_id = prog->aux->attach_btf_id;
21769 st_ops_desc = bpf_struct_ops_find(btf, btf_id);
21770 if (!st_ops_desc) {
21771 verbose(env, "attach_btf_id %u is not a supported struct\n",
21775 st_ops = st_ops_desc->st_ops;
21777 t = st_ops_desc->type;
21778 member_idx = prog->expected_attach_type;
21779 if (member_idx >= btf_type_vlen(t)) {
21780 verbose(env, "attach to invalid member idx %u of struct %s\n",
21781 member_idx, st_ops->name);
21785 member = &btf_type_member(t)[member_idx];
21786 mname = btf_name_by_offset(btf, member->name_off);
21787 func_proto = btf_type_resolve_func_ptr(btf, member->type,
21790 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
21791 mname, member_idx, st_ops->name);
21795 err = bpf_struct_ops_supported(st_ops, __btf_member_bit_offset(t, member) / 8);
21797 verbose(env, "attach to unsupported member %s of struct %s\n",
21798 mname, st_ops->name);
21802 if (st_ops->check_member) {
21803 err = st_ops->check_member(t, member, prog);
21806 verbose(env, "attach to unsupported member %s of struct %s\n",
21807 mname, st_ops->name);
21812 /* btf_ctx_access() used this to provide argument type info */
21813 prog->aux->ctx_arg_info =
21814 st_ops_desc->arg_info[member_idx].info;
21815 prog->aux->ctx_arg_info_size =
21816 st_ops_desc->arg_info[member_idx].cnt;
21818 prog->aux->attach_func_proto = func_proto;
21819 prog->aux->attach_func_name = mname;
21820 env->ops = st_ops->verifier_ops;
21824 #define SECURITY_PREFIX "security_"
21826 static int check_attach_modify_return(unsigned long addr, const char *func_name)
21828 if (within_error_injection_list(addr) ||
21829 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
21835 /* list of non-sleepable functions that are otherwise on
21836 * ALLOW_ERROR_INJECTION list
21838 BTF_SET_START(btf_non_sleepable_error_inject)
21839 /* Three functions below can be called from sleepable and non-sleepable context.
21840 * Assume non-sleepable from bpf safety point of view.
21842 BTF_ID(func, __filemap_add_folio)
21843 #ifdef CONFIG_FAIL_PAGE_ALLOC
21844 BTF_ID(func, should_fail_alloc_page)
21846 #ifdef CONFIG_FAILSLAB
21847 BTF_ID(func, should_failslab)
21849 BTF_SET_END(btf_non_sleepable_error_inject)
21851 static int check_non_sleepable_error_inject(u32 btf_id)
21853 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
21856 int bpf_check_attach_target(struct bpf_verifier_log *log,
21857 const struct bpf_prog *prog,
21858 const struct bpf_prog *tgt_prog,
21860 struct bpf_attach_target_info *tgt_info)
21862 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
21863 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
21864 char trace_symbol[KSYM_SYMBOL_LEN];
21865 const char prefix[] = "btf_trace_";
21866 struct bpf_raw_event_map *btp;
21867 int ret = 0, subprog = -1, i;
21868 const struct btf_type *t;
21869 bool conservative = true;
21870 const char *tname, *fname;
21873 struct module *mod = NULL;
21876 bpf_log(log, "Tracing programs must provide btf_id\n");
21879 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
21882 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
21885 t = btf_type_by_id(btf, btf_id);
21887 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
21890 tname = btf_name_by_offset(btf, t->name_off);
21892 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
21896 struct bpf_prog_aux *aux = tgt_prog->aux;
21898 if (bpf_prog_is_dev_bound(prog->aux) &&
21899 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
21900 bpf_log(log, "Target program bound device mismatch");
21904 for (i = 0; i < aux->func_info_cnt; i++)
21905 if (aux->func_info[i].type_id == btf_id) {
21909 if (subprog == -1) {
21910 bpf_log(log, "Subprog %s doesn't exist\n", tname);
21913 if (aux->func && aux->func[subprog]->aux->exception_cb) {
21915 "%s programs cannot attach to exception callback\n",
21916 prog_extension ? "Extension" : "FENTRY/FEXIT");
21919 conservative = aux->func_info_aux[subprog].unreliable;
21920 if (prog_extension) {
21921 if (conservative) {
21923 "Cannot replace static functions\n");
21926 if (!prog->jit_requested) {
21928 "Extension programs should be JITed\n");
21932 if (!tgt_prog->jited) {
21933 bpf_log(log, "Can attach to only JITed progs\n");
21936 if (prog_tracing) {
21937 if (aux->attach_tracing_prog) {
21939 * Target program is an fentry/fexit which is already attached
21940 * to another tracing program. More levels of nesting
21941 * attachment are not allowed.
21943 bpf_log(log, "Cannot nest tracing program attach more than once\n");
21946 } else if (tgt_prog->type == prog->type) {
21948 * To avoid potential call chain cycles, prevent attaching of a
21949 * program extension to another extension. It's ok to attach
21950 * fentry/fexit to extension program.
21952 bpf_log(log, "Cannot recursively attach\n");
21955 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
21957 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
21958 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
21959 /* Program extensions can extend all program types
21960 * except fentry/fexit. The reason is the following.
21961 * The fentry/fexit programs are used for performance
21962 * analysis, stats and can be attached to any program
21963 * type. When extension program is replacing XDP function
21964 * it is necessary to allow performance analysis of all
21965 * functions. Both original XDP program and its program
21966 * extension. Hence attaching fentry/fexit to
21967 * BPF_PROG_TYPE_EXT is allowed. If extending of
21968 * fentry/fexit was allowed it would be possible to create
21969 * long call chain fentry->extension->fentry->extension
21970 * beyond reasonable stack size. Hence extending fentry
21973 bpf_log(log, "Cannot extend fentry/fexit\n");
21977 if (prog_extension) {
21978 bpf_log(log, "Cannot replace kernel functions\n");
21983 switch (prog->expected_attach_type) {
21984 case BPF_TRACE_RAW_TP:
21987 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
21990 if (!btf_type_is_typedef(t)) {
21991 bpf_log(log, "attach_btf_id %u is not a typedef\n",
21995 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
21996 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
22000 tname += sizeof(prefix) - 1;
22002 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument
22003 * names. Thus using bpf_raw_event_map to get argument names.
22005 btp = bpf_get_raw_tracepoint(tname);
22008 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
22010 bpf_put_raw_tracepoint(btp);
22013 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
22015 if (!fname || ret < 0) {
22016 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
22018 t = btf_type_by_id(btf, t->type);
22019 if (!btf_type_is_ptr(t))
22020 /* should never happen in valid vmlinux build */
22023 t = btf_type_by_id(btf, ret);
22024 if (!btf_type_is_func(t))
22025 /* should never happen in valid vmlinux build */
22029 t = btf_type_by_id(btf, t->type);
22030 if (!btf_type_is_func_proto(t))
22031 /* should never happen in valid vmlinux build */
22035 case BPF_TRACE_ITER:
22036 if (!btf_type_is_func(t)) {
22037 bpf_log(log, "attach_btf_id %u is not a function\n",
22041 t = btf_type_by_id(btf, t->type);
22042 if (!btf_type_is_func_proto(t))
22044 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
22049 if (!prog_extension)
22052 case BPF_MODIFY_RETURN:
22054 case BPF_LSM_CGROUP:
22055 case BPF_TRACE_FENTRY:
22056 case BPF_TRACE_FEXIT:
22057 if (!btf_type_is_func(t)) {
22058 bpf_log(log, "attach_btf_id %u is not a function\n",
22062 if (prog_extension &&
22063 btf_check_type_match(log, prog, btf, t))
22065 t = btf_type_by_id(btf, t->type);
22066 if (!btf_type_is_func_proto(t))
22069 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
22070 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
22071 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
22074 if (tgt_prog && conservative)
22077 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
22083 addr = (long) tgt_prog->bpf_func;
22085 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
22087 if (btf_is_module(btf)) {
22088 mod = btf_try_get_module(btf);
22090 addr = find_kallsyms_symbol_value(mod, tname);
22094 addr = kallsyms_lookup_name(tname);
22099 "The address of function %s cannot be found\n",
22105 if (prog->sleepable) {
22107 switch (prog->type) {
22108 case BPF_PROG_TYPE_TRACING:
22110 /* fentry/fexit/fmod_ret progs can be sleepable if they are
22111 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
22113 if (!check_non_sleepable_error_inject(btf_id) &&
22114 within_error_injection_list(addr))
22116 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
22117 * in the fmodret id set with the KF_SLEEPABLE flag.
22120 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
22123 if (flags && (*flags & KF_SLEEPABLE))
22127 case BPF_PROG_TYPE_LSM:
22128 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
22129 * Only some of them are sleepable.
22131 if (bpf_lsm_is_sleepable_hook(btf_id))
22139 bpf_log(log, "%s is not sleepable\n", tname);
22142 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
22145 bpf_log(log, "can't modify return codes of BPF programs\n");
22149 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
22150 !check_attach_modify_return(addr, tname))
22154 bpf_log(log, "%s() is not modifiable\n", tname);
22161 tgt_info->tgt_addr = addr;
22162 tgt_info->tgt_name = tname;
22163 tgt_info->tgt_type = t;
22164 tgt_info->tgt_mod = mod;
22168 BTF_SET_START(btf_id_deny)
22171 BTF_ID(func, migrate_disable)
22172 BTF_ID(func, migrate_enable)
22174 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
22175 BTF_ID(func, rcu_read_unlock_strict)
22177 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
22178 BTF_ID(func, preempt_count_add)
22179 BTF_ID(func, preempt_count_sub)
22181 #ifdef CONFIG_PREEMPT_RCU
22182 BTF_ID(func, __rcu_read_lock)
22183 BTF_ID(func, __rcu_read_unlock)
22185 BTF_SET_END(btf_id_deny)
22187 static bool can_be_sleepable(struct bpf_prog *prog)
22189 if (prog->type == BPF_PROG_TYPE_TRACING) {
22190 switch (prog->expected_attach_type) {
22191 case BPF_TRACE_FENTRY:
22192 case BPF_TRACE_FEXIT:
22193 case BPF_MODIFY_RETURN:
22194 case BPF_TRACE_ITER:
22200 return prog->type == BPF_PROG_TYPE_LSM ||
22201 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
22202 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
22205 static int check_attach_btf_id(struct bpf_verifier_env *env)
22207 struct bpf_prog *prog = env->prog;
22208 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
22209 struct bpf_attach_target_info tgt_info = {};
22210 u32 btf_id = prog->aux->attach_btf_id;
22211 struct bpf_trampoline *tr;
22215 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
22216 if (prog->sleepable)
22217 /* attach_btf_id checked to be zero already */
22219 verbose(env, "Syscall programs can only be sleepable\n");
22223 if (prog->sleepable && !can_be_sleepable(prog)) {
22224 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
22228 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
22229 return check_struct_ops_btf_id(env);
22231 if (prog->type != BPF_PROG_TYPE_TRACING &&
22232 prog->type != BPF_PROG_TYPE_LSM &&
22233 prog->type != BPF_PROG_TYPE_EXT)
22236 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
22240 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
22241 /* to make freplace equivalent to their targets, they need to
22242 * inherit env->ops and expected_attach_type for the rest of the
22245 env->ops = bpf_verifier_ops[tgt_prog->type];
22246 prog->expected_attach_type = tgt_prog->expected_attach_type;
22249 /* store info about the attachment target that will be used later */
22250 prog->aux->attach_func_proto = tgt_info.tgt_type;
22251 prog->aux->attach_func_name = tgt_info.tgt_name;
22252 prog->aux->mod = tgt_info.tgt_mod;
22255 prog->aux->saved_dst_prog_type = tgt_prog->type;
22256 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
22259 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
22260 prog->aux->attach_btf_trace = true;
22262 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
22263 if (!bpf_iter_prog_supported(prog))
22268 if (prog->type == BPF_PROG_TYPE_LSM) {
22269 ret = bpf_lsm_verify_prog(&env->log, prog);
22272 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
22273 btf_id_set_contains(&btf_id_deny, btf_id)) {
22277 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
22278 tr = bpf_trampoline_get(key, &tgt_info);
22282 if (tgt_prog && tgt_prog->aux->tail_call_reachable)
22283 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
22285 prog->aux->dst_trampoline = tr;
22289 struct btf *bpf_get_btf_vmlinux(void)
22291 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
22292 mutex_lock(&bpf_verifier_lock);
22294 btf_vmlinux = btf_parse_vmlinux();
22295 mutex_unlock(&bpf_verifier_lock);
22297 return btf_vmlinux;
22300 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
22302 u64 start_time = ktime_get_ns();
22303 struct bpf_verifier_env *env;
22304 int i, len, ret = -EINVAL, err;
22308 /* no program is valid */
22309 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
22312 /* 'struct bpf_verifier_env' can be global, but since it's not small,
22313 * allocate/free it every time bpf_check() is called
22315 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
22321 len = (*prog)->len;
22322 env->insn_aux_data =
22323 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
22325 if (!env->insn_aux_data)
22327 for (i = 0; i < len; i++)
22328 env->insn_aux_data[i].orig_idx = i;
22330 env->ops = bpf_verifier_ops[env->prog->type];
22331 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
22333 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
22334 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
22335 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
22336 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
22337 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
22339 bpf_get_btf_vmlinux();
22341 /* grab the mutex to protect few globals used by verifier */
22343 mutex_lock(&bpf_verifier_lock);
22345 /* user could have requested verbose verifier output
22346 * and supplied buffer to store the verification trace
22348 ret = bpf_vlog_init(&env->log, attr->log_level,
22349 (char __user *) (unsigned long) attr->log_buf,
22354 mark_verifier_state_clean(env);
22356 if (IS_ERR(btf_vmlinux)) {
22357 /* Either gcc or pahole or kernel are broken. */
22358 verbose(env, "in-kernel BTF is malformed\n");
22359 ret = PTR_ERR(btf_vmlinux);
22360 goto skip_full_check;
22363 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
22364 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
22365 env->strict_alignment = true;
22366 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
22367 env->strict_alignment = false;
22370 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
22371 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
22373 env->explored_states = kvcalloc(state_htab_size(env),
22374 sizeof(struct bpf_verifier_state_list *),
22377 if (!env->explored_states)
22378 goto skip_full_check;
22380 ret = check_btf_info_early(env, attr, uattr);
22382 goto skip_full_check;
22384 ret = add_subprog_and_kfunc(env);
22386 goto skip_full_check;
22388 ret = check_subprogs(env);
22390 goto skip_full_check;
22392 ret = check_btf_info(env, attr, uattr);
22394 goto skip_full_check;
22396 ret = check_attach_btf_id(env);
22398 goto skip_full_check;
22400 ret = resolve_pseudo_ldimm64(env);
22402 goto skip_full_check;
22404 if (bpf_prog_is_offloaded(env->prog->aux)) {
22405 ret = bpf_prog_offload_verifier_prep(env->prog);
22407 goto skip_full_check;
22410 ret = check_cfg(env);
22412 goto skip_full_check;
22414 ret = mark_fastcall_patterns(env);
22416 goto skip_full_check;
22418 ret = do_check_main(env);
22419 ret = ret ?: do_check_subprogs(env);
22421 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
22422 ret = bpf_prog_offload_finalize(env);
22425 kvfree(env->explored_states);
22427 /* might decrease stack depth, keep it before passes that
22428 * allocate additional slots.
22431 ret = remove_fastcall_spills_fills(env);
22434 ret = check_max_stack_depth(env);
22436 /* instruction rewrites happen after this point */
22438 ret = optimize_bpf_loop(env);
22442 opt_hard_wire_dead_code_branches(env);
22444 ret = opt_remove_dead_code(env);
22446 ret = opt_remove_nops(env);
22449 sanitize_dead_code(env);
22453 /* program is valid, convert *(u32*)(ctx + off) accesses */
22454 ret = convert_ctx_accesses(env);
22457 ret = do_misc_fixups(env);
22459 /* do 32-bit optimization after insn patching has done so those patched
22460 * insns could be handled correctly.
22462 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
22463 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
22464 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
22469 ret = fixup_call_args(env);
22471 env->verification_time = ktime_get_ns() - start_time;
22472 print_verification_stats(env);
22473 env->prog->aux->verified_insns = env->insn_processed;
22475 /* preserve original error even if log finalization is successful */
22476 err = bpf_vlog_finalize(&env->log, &log_true_size);
22480 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
22481 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
22482 &log_true_size, sizeof(log_true_size))) {
22484 goto err_release_maps;
22488 goto err_release_maps;
22490 if (env->used_map_cnt) {
22491 /* if program passed verifier, update used_maps in bpf_prog_info */
22492 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
22493 sizeof(env->used_maps[0]),
22496 if (!env->prog->aux->used_maps) {
22498 goto err_release_maps;
22501 memcpy(env->prog->aux->used_maps, env->used_maps,
22502 sizeof(env->used_maps[0]) * env->used_map_cnt);
22503 env->prog->aux->used_map_cnt = env->used_map_cnt;
22505 if (env->used_btf_cnt) {
22506 /* if program passed verifier, update used_btfs in bpf_prog_aux */
22507 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
22508 sizeof(env->used_btfs[0]),
22510 if (!env->prog->aux->used_btfs) {
22512 goto err_release_maps;
22515 memcpy(env->prog->aux->used_btfs, env->used_btfs,
22516 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
22517 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
22519 if (env->used_map_cnt || env->used_btf_cnt) {
22520 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
22521 * bpf_ld_imm64 instructions
22523 convert_pseudo_ld_imm64(env);
22526 adjust_btf_func(env);
22529 if (!env->prog->aux->used_maps)
22530 /* if we didn't copy map pointers into bpf_prog_info, release
22531 * them now. Otherwise free_used_maps() will release them.
22534 if (!env->prog->aux->used_btfs)
22537 /* extension progs temporarily inherit the attach_type of their targets
22538 for verification purposes, so set it back to zero before returning
22540 if (env->prog->type == BPF_PROG_TYPE_EXT)
22541 env->prog->expected_attach_type = 0;
22545 module_put(env->attach_btf_mod);
22548 mutex_unlock(&bpf_verifier_lock);
22549 vfree(env->insn_aux_data);