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>
31 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
32 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
33 [_id] = & _name ## _verifier_ops,
34 #define BPF_MAP_TYPE(_id, _ops)
35 #define BPF_LINK_TYPE(_id, _name)
36 #include <linux/bpf_types.h>
42 /* bpf_check() is a static code analyzer that walks eBPF program
43 * instruction by instruction and updates register/stack state.
44 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
46 * The first pass is depth-first-search to check that the program is a DAG.
47 * It rejects the following programs:
48 * - larger than BPF_MAXINSNS insns
49 * - if loop is present (detected via back-edge)
50 * - unreachable insns exist (shouldn't be a forest. program = one function)
51 * - out of bounds or malformed jumps
52 * The second pass is all possible path descent from the 1st insn.
53 * Since it's analyzing all paths through the program, the length of the
54 * analysis is limited to 64k insn, which may be hit even if total number of
55 * insn is less then 4K, but there are too many branches that change stack/regs.
56 * Number of 'branches to be analyzed' is limited to 1k
58 * On entry to each instruction, each register has a type, and the instruction
59 * changes the types of the registers depending on instruction semantics.
60 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
63 * All registers are 64-bit.
64 * R0 - return register
65 * R1-R5 argument passing registers
66 * R6-R9 callee saved registers
67 * R10 - frame pointer read-only
69 * At the start of BPF program the register R1 contains a pointer to bpf_context
70 * and has type PTR_TO_CTX.
72 * Verifier tracks arithmetic operations on pointers in case:
73 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
74 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
75 * 1st insn copies R10 (which has FRAME_PTR) type into R1
76 * and 2nd arithmetic instruction is pattern matched to recognize
77 * that it wants to construct a pointer to some element within stack.
78 * So after 2nd insn, the register R1 has type PTR_TO_STACK
79 * (and -20 constant is saved for further stack bounds checking).
80 * Meaning that this reg is a pointer to stack plus known immediate constant.
82 * Most of the time the registers have SCALAR_VALUE type, which
83 * means the register has some value, but it's not a valid pointer.
84 * (like pointer plus pointer becomes SCALAR_VALUE type)
86 * When verifier sees load or store instructions the type of base register
87 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
88 * four pointer types recognized by check_mem_access() function.
90 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
91 * and the range of [ptr, ptr + map's value_size) is accessible.
93 * registers used to pass values to function calls are checked against
94 * function argument constraints.
96 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
97 * It means that the register type passed to this function must be
98 * PTR_TO_STACK and it will be used inside the function as
99 * 'pointer to map element key'
101 * For example the argument constraints for bpf_map_lookup_elem():
102 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
103 * .arg1_type = ARG_CONST_MAP_PTR,
104 * .arg2_type = ARG_PTR_TO_MAP_KEY,
106 * ret_type says that this function returns 'pointer to map elem value or null'
107 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
108 * 2nd argument should be a pointer to stack, which will be used inside
109 * the helper function as a pointer to map element key.
111 * On the kernel side the helper function looks like:
112 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
114 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
115 * void *key = (void *) (unsigned long) r2;
118 * here kernel can access 'key' and 'map' pointers safely, knowing that
119 * [key, key + map->key_size) bytes are valid and were initialized on
120 * the stack of eBPF program.
123 * Corresponding eBPF program may look like:
124 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
125 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
126 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
127 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
128 * here verifier looks at prototype of map_lookup_elem() and sees:
129 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
130 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
132 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
133 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
134 * and were initialized prior to this call.
135 * If it's ok, then verifier allows this BPF_CALL insn and looks at
136 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
137 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
138 * returns either pointer to map value or NULL.
140 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
141 * insn, the register holding that pointer in the true branch changes state to
142 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
143 * branch. See check_cond_jmp_op().
145 * After the call R0 is set to return type of the function and registers R1-R5
146 * are set to NOT_INIT to indicate that they are no longer readable.
148 * The following reference types represent a potential reference to a kernel
149 * resource which, after first being allocated, must be checked and freed by
151 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
153 * When the verifier sees a helper call return a reference type, it allocates a
154 * pointer id for the reference and stores it in the current function state.
155 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
156 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
157 * passes through a NULL-check conditional. For the branch wherein the state is
158 * changed to CONST_IMM, the verifier releases the reference.
160 * For each helper function that allocates a reference, such as
161 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
162 * bpf_sk_release(). When a reference type passes into the release function,
163 * the verifier also releases the reference. If any unchecked or unreleased
164 * reference remains at the end of the program, the verifier rejects it.
167 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
168 struct bpf_verifier_stack_elem {
169 /* verifer state is 'st'
170 * before processing instruction 'insn_idx'
171 * and after processing instruction 'prev_insn_idx'
173 struct bpf_verifier_state st;
176 struct bpf_verifier_stack_elem *next;
177 /* length of verifier log at the time this state was pushed on stack */
181 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
182 #define BPF_COMPLEXITY_LIMIT_STATES 64
184 #define BPF_MAP_KEY_POISON (1ULL << 63)
185 #define BPF_MAP_KEY_SEEN (1ULL << 62)
187 #define BPF_MAP_PTR_UNPRIV 1UL
188 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
189 POISON_POINTER_DELTA))
190 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
192 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
193 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
194 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
195 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
196 static int ref_set_non_owning(struct bpf_verifier_env *env,
197 struct bpf_reg_state *reg);
198 static void specialize_kfunc(struct bpf_verifier_env *env,
199 u32 func_id, u16 offset, unsigned long *addr);
200 static bool is_trusted_reg(const struct bpf_reg_state *reg);
202 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
204 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
207 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
209 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
212 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
213 const struct bpf_map *map, bool unpriv)
215 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
216 unpriv |= bpf_map_ptr_unpriv(aux);
217 aux->map_ptr_state = (unsigned long)map |
218 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
221 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
223 return aux->map_key_state & BPF_MAP_KEY_POISON;
226 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
228 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
231 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
233 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
236 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
238 bool poisoned = bpf_map_key_poisoned(aux);
240 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
241 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
244 static bool bpf_helper_call(const struct bpf_insn *insn)
246 return insn->code == (BPF_JMP | BPF_CALL) &&
250 static bool bpf_pseudo_call(const struct bpf_insn *insn)
252 return insn->code == (BPF_JMP | BPF_CALL) &&
253 insn->src_reg == BPF_PSEUDO_CALL;
256 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
258 return insn->code == (BPF_JMP | BPF_CALL) &&
259 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
262 struct bpf_call_arg_meta {
263 struct bpf_map *map_ptr;
280 struct btf_field *kptr_field;
283 struct bpf_kfunc_call_arg_meta {
288 const struct btf_type *func_proto;
289 const char *func_name;
302 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
303 * generally to pass info about user-defined local kptr types to later
306 * Record the local kptr type to be drop'd
307 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
308 * Record the local kptr type to be refcount_incr'd and use
309 * arg_owning_ref to determine whether refcount_acquire should be
317 struct btf_field *field;
320 struct btf_field *field;
323 enum bpf_dynptr_type type;
326 } initialized_dynptr;
334 struct btf *btf_vmlinux;
336 static DEFINE_MUTEX(bpf_verifier_lock);
338 static const struct bpf_line_info *
339 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
341 const struct bpf_line_info *linfo;
342 const struct bpf_prog *prog;
346 nr_linfo = prog->aux->nr_linfo;
348 if (!nr_linfo || insn_off >= prog->len)
351 linfo = prog->aux->linfo;
352 for (i = 1; i < nr_linfo; i++)
353 if (insn_off < linfo[i].insn_off)
356 return &linfo[i - 1];
359 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
361 struct bpf_verifier_env *env = private_data;
364 if (!bpf_verifier_log_needed(&env->log))
368 bpf_verifier_vlog(&env->log, fmt, args);
372 static const char *ltrim(const char *s)
380 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
382 const char *prefix_fmt, ...)
384 const struct bpf_line_info *linfo;
386 if (!bpf_verifier_log_needed(&env->log))
389 linfo = find_linfo(env, insn_off);
390 if (!linfo || linfo == env->prev_linfo)
396 va_start(args, prefix_fmt);
397 bpf_verifier_vlog(&env->log, prefix_fmt, args);
402 ltrim(btf_name_by_offset(env->prog->aux->btf,
405 env->prev_linfo = linfo;
408 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
409 struct bpf_reg_state *reg,
410 struct tnum *range, const char *ctx,
411 const char *reg_name)
415 verbose(env, "At %s the register %s ", ctx, reg_name);
416 if (!tnum_is_unknown(reg->var_off)) {
417 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
418 verbose(env, "has value %s", tn_buf);
420 verbose(env, "has unknown scalar value");
422 tnum_strn(tn_buf, sizeof(tn_buf), *range);
423 verbose(env, " should have been in %s\n", tn_buf);
426 static bool type_is_pkt_pointer(enum bpf_reg_type type)
428 type = base_type(type);
429 return type == PTR_TO_PACKET ||
430 type == PTR_TO_PACKET_META;
433 static bool type_is_sk_pointer(enum bpf_reg_type type)
435 return type == PTR_TO_SOCKET ||
436 type == PTR_TO_SOCK_COMMON ||
437 type == PTR_TO_TCP_SOCK ||
438 type == PTR_TO_XDP_SOCK;
441 static bool type_may_be_null(u32 type)
443 return type & PTR_MAYBE_NULL;
446 static bool reg_not_null(const struct bpf_reg_state *reg)
448 enum bpf_reg_type type;
451 if (type_may_be_null(type))
454 type = base_type(type);
455 return type == PTR_TO_SOCKET ||
456 type == PTR_TO_TCP_SOCK ||
457 type == PTR_TO_MAP_VALUE ||
458 type == PTR_TO_MAP_KEY ||
459 type == PTR_TO_SOCK_COMMON ||
460 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
464 static bool type_is_ptr_alloc_obj(u32 type)
466 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
469 static bool type_is_non_owning_ref(u32 type)
471 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
474 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
476 struct btf_record *rec = NULL;
477 struct btf_struct_meta *meta;
479 if (reg->type == PTR_TO_MAP_VALUE) {
480 rec = reg->map_ptr->record;
481 } else if (type_is_ptr_alloc_obj(reg->type)) {
482 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
489 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
491 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
493 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
496 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
498 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
501 static bool type_is_rdonly_mem(u32 type)
503 return type & MEM_RDONLY;
506 static bool is_acquire_function(enum bpf_func_id func_id,
507 const struct bpf_map *map)
509 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
511 if (func_id == BPF_FUNC_sk_lookup_tcp ||
512 func_id == BPF_FUNC_sk_lookup_udp ||
513 func_id == BPF_FUNC_skc_lookup_tcp ||
514 func_id == BPF_FUNC_ringbuf_reserve ||
515 func_id == BPF_FUNC_kptr_xchg)
518 if (func_id == BPF_FUNC_map_lookup_elem &&
519 (map_type == BPF_MAP_TYPE_SOCKMAP ||
520 map_type == BPF_MAP_TYPE_SOCKHASH))
526 static bool is_ptr_cast_function(enum bpf_func_id func_id)
528 return func_id == BPF_FUNC_tcp_sock ||
529 func_id == BPF_FUNC_sk_fullsock ||
530 func_id == BPF_FUNC_skc_to_tcp_sock ||
531 func_id == BPF_FUNC_skc_to_tcp6_sock ||
532 func_id == BPF_FUNC_skc_to_udp6_sock ||
533 func_id == BPF_FUNC_skc_to_mptcp_sock ||
534 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
535 func_id == BPF_FUNC_skc_to_tcp_request_sock;
538 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
540 return func_id == BPF_FUNC_dynptr_data;
543 static bool is_callback_calling_kfunc(u32 btf_id);
545 static bool is_callback_calling_function(enum bpf_func_id func_id)
547 return func_id == BPF_FUNC_for_each_map_elem ||
548 func_id == BPF_FUNC_timer_set_callback ||
549 func_id == BPF_FUNC_find_vma ||
550 func_id == BPF_FUNC_loop ||
551 func_id == BPF_FUNC_user_ringbuf_drain;
554 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
556 return func_id == BPF_FUNC_timer_set_callback;
559 static bool is_storage_get_function(enum bpf_func_id func_id)
561 return func_id == BPF_FUNC_sk_storage_get ||
562 func_id == BPF_FUNC_inode_storage_get ||
563 func_id == BPF_FUNC_task_storage_get ||
564 func_id == BPF_FUNC_cgrp_storage_get;
567 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
568 const struct bpf_map *map)
570 int ref_obj_uses = 0;
572 if (is_ptr_cast_function(func_id))
574 if (is_acquire_function(func_id, map))
576 if (is_dynptr_ref_function(func_id))
579 return ref_obj_uses > 1;
582 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
584 return BPF_CLASS(insn->code) == BPF_STX &&
585 BPF_MODE(insn->code) == BPF_ATOMIC &&
586 insn->imm == BPF_CMPXCHG;
589 /* string representation of 'enum bpf_reg_type'
591 * Note that reg_type_str() can not appear more than once in a single verbose()
594 static const char *reg_type_str(struct bpf_verifier_env *env,
595 enum bpf_reg_type type)
597 char postfix[16] = {0}, prefix[64] = {0};
598 static const char * const str[] = {
600 [SCALAR_VALUE] = "scalar",
601 [PTR_TO_CTX] = "ctx",
602 [CONST_PTR_TO_MAP] = "map_ptr",
603 [PTR_TO_MAP_VALUE] = "map_value",
604 [PTR_TO_STACK] = "fp",
605 [PTR_TO_PACKET] = "pkt",
606 [PTR_TO_PACKET_META] = "pkt_meta",
607 [PTR_TO_PACKET_END] = "pkt_end",
608 [PTR_TO_FLOW_KEYS] = "flow_keys",
609 [PTR_TO_SOCKET] = "sock",
610 [PTR_TO_SOCK_COMMON] = "sock_common",
611 [PTR_TO_TCP_SOCK] = "tcp_sock",
612 [PTR_TO_TP_BUFFER] = "tp_buffer",
613 [PTR_TO_XDP_SOCK] = "xdp_sock",
614 [PTR_TO_BTF_ID] = "ptr_",
615 [PTR_TO_MEM] = "mem",
616 [PTR_TO_BUF] = "buf",
617 [PTR_TO_FUNC] = "func",
618 [PTR_TO_MAP_KEY] = "map_key",
619 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr",
622 if (type & PTR_MAYBE_NULL) {
623 if (base_type(type) == PTR_TO_BTF_ID)
624 strncpy(postfix, "or_null_", 16);
626 strncpy(postfix, "_or_null", 16);
629 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
630 type & MEM_RDONLY ? "rdonly_" : "",
631 type & MEM_RINGBUF ? "ringbuf_" : "",
632 type & MEM_USER ? "user_" : "",
633 type & MEM_PERCPU ? "percpu_" : "",
634 type & MEM_RCU ? "rcu_" : "",
635 type & PTR_UNTRUSTED ? "untrusted_" : "",
636 type & PTR_TRUSTED ? "trusted_" : ""
639 snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
640 prefix, str[base_type(type)], postfix);
641 return env->tmp_str_buf;
644 static char slot_type_char[] = {
645 [STACK_INVALID] = '?',
649 [STACK_DYNPTR] = 'd',
653 static void print_liveness(struct bpf_verifier_env *env,
654 enum bpf_reg_liveness live)
656 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
658 if (live & REG_LIVE_READ)
660 if (live & REG_LIVE_WRITTEN)
662 if (live & REG_LIVE_DONE)
666 static int __get_spi(s32 off)
668 return (-off - 1) / BPF_REG_SIZE;
671 static struct bpf_func_state *func(struct bpf_verifier_env *env,
672 const struct bpf_reg_state *reg)
674 struct bpf_verifier_state *cur = env->cur_state;
676 return cur->frame[reg->frameno];
679 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
681 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
683 /* We need to check that slots between [spi - nr_slots + 1, spi] are
684 * within [0, allocated_stack).
686 * Please note that the spi grows downwards. For example, a dynptr
687 * takes the size of two stack slots; the first slot will be at
688 * spi and the second slot will be at spi - 1.
690 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
693 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
694 const char *obj_kind, int nr_slots)
698 if (!tnum_is_const(reg->var_off)) {
699 verbose(env, "%s has to be at a constant offset\n", obj_kind);
703 off = reg->off + reg->var_off.value;
704 if (off % BPF_REG_SIZE) {
705 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
709 spi = __get_spi(off);
710 if (spi + 1 < nr_slots) {
711 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
715 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
720 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
722 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
725 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
727 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
730 static const char *btf_type_name(const struct btf *btf, u32 id)
732 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
735 static const char *dynptr_type_str(enum bpf_dynptr_type type)
738 case BPF_DYNPTR_TYPE_LOCAL:
740 case BPF_DYNPTR_TYPE_RINGBUF:
742 case BPF_DYNPTR_TYPE_SKB:
744 case BPF_DYNPTR_TYPE_XDP:
746 case BPF_DYNPTR_TYPE_INVALID:
749 WARN_ONCE(1, "unknown dynptr type %d\n", type);
754 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
756 if (!btf || btf_id == 0)
759 /* we already validated that type is valid and has conforming name */
760 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
763 static const char *iter_state_str(enum bpf_iter_state state)
766 case BPF_ITER_STATE_ACTIVE:
768 case BPF_ITER_STATE_DRAINED:
770 case BPF_ITER_STATE_INVALID:
773 WARN_ONCE(1, "unknown iter state %d\n", state);
778 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
780 env->scratched_regs |= 1U << regno;
783 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
785 env->scratched_stack_slots |= 1ULL << spi;
788 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
790 return (env->scratched_regs >> regno) & 1;
793 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
795 return (env->scratched_stack_slots >> regno) & 1;
798 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
800 return env->scratched_regs || env->scratched_stack_slots;
803 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
805 env->scratched_regs = 0U;
806 env->scratched_stack_slots = 0ULL;
809 /* Used for printing the entire verifier state. */
810 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
812 env->scratched_regs = ~0U;
813 env->scratched_stack_slots = ~0ULL;
816 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
818 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
819 case DYNPTR_TYPE_LOCAL:
820 return BPF_DYNPTR_TYPE_LOCAL;
821 case DYNPTR_TYPE_RINGBUF:
822 return BPF_DYNPTR_TYPE_RINGBUF;
823 case DYNPTR_TYPE_SKB:
824 return BPF_DYNPTR_TYPE_SKB;
825 case DYNPTR_TYPE_XDP:
826 return BPF_DYNPTR_TYPE_XDP;
828 return BPF_DYNPTR_TYPE_INVALID;
832 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
835 case BPF_DYNPTR_TYPE_LOCAL:
836 return DYNPTR_TYPE_LOCAL;
837 case BPF_DYNPTR_TYPE_RINGBUF:
838 return DYNPTR_TYPE_RINGBUF;
839 case BPF_DYNPTR_TYPE_SKB:
840 return DYNPTR_TYPE_SKB;
841 case BPF_DYNPTR_TYPE_XDP:
842 return DYNPTR_TYPE_XDP;
848 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
850 return type == BPF_DYNPTR_TYPE_RINGBUF;
853 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
854 enum bpf_dynptr_type type,
855 bool first_slot, int dynptr_id);
857 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
858 struct bpf_reg_state *reg);
860 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
861 struct bpf_reg_state *sreg1,
862 struct bpf_reg_state *sreg2,
863 enum bpf_dynptr_type type)
865 int id = ++env->id_gen;
867 __mark_dynptr_reg(sreg1, type, true, id);
868 __mark_dynptr_reg(sreg2, type, false, id);
871 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
872 struct bpf_reg_state *reg,
873 enum bpf_dynptr_type type)
875 __mark_dynptr_reg(reg, type, true, ++env->id_gen);
878 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
879 struct bpf_func_state *state, int spi);
881 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
882 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
884 struct bpf_func_state *state = func(env, reg);
885 enum bpf_dynptr_type type;
888 spi = dynptr_get_spi(env, reg);
892 /* We cannot assume both spi and spi - 1 belong to the same dynptr,
893 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
894 * to ensure that for the following example:
897 * So marking spi = 2 should lead to destruction of both d1 and d2. In
898 * case they do belong to same dynptr, second call won't see slot_type
899 * as STACK_DYNPTR and will simply skip destruction.
901 err = destroy_if_dynptr_stack_slot(env, state, spi);
904 err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
908 for (i = 0; i < BPF_REG_SIZE; i++) {
909 state->stack[spi].slot_type[i] = STACK_DYNPTR;
910 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
913 type = arg_to_dynptr_type(arg_type);
914 if (type == BPF_DYNPTR_TYPE_INVALID)
917 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
918 &state->stack[spi - 1].spilled_ptr, type);
920 if (dynptr_type_refcounted(type)) {
921 /* The id is used to track proper releasing */
924 if (clone_ref_obj_id)
925 id = clone_ref_obj_id;
927 id = acquire_reference_state(env, insn_idx);
932 state->stack[spi].spilled_ptr.ref_obj_id = id;
933 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
936 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
937 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
942 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
946 for (i = 0; i < BPF_REG_SIZE; i++) {
947 state->stack[spi].slot_type[i] = STACK_INVALID;
948 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
951 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
952 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
954 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
956 * While we don't allow reading STACK_INVALID, it is still possible to
957 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
958 * helpers or insns can do partial read of that part without failing,
959 * but check_stack_range_initialized, check_stack_read_var_off, and
960 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
961 * the slot conservatively. Hence we need to prevent those liveness
964 * This was not a problem before because STACK_INVALID is only set by
965 * default (where the default reg state has its reg->parent as NULL), or
966 * in clean_live_states after REG_LIVE_DONE (at which point
967 * mark_reg_read won't walk reg->parent chain), but not randomly during
968 * verifier state exploration (like we did above). Hence, for our case
969 * parentage chain will still be live (i.e. reg->parent may be
970 * non-NULL), while earlier reg->parent was NULL, so we need
971 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
972 * done later on reads or by mark_dynptr_read as well to unnecessary
973 * mark registers in verifier state.
975 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
976 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
979 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
981 struct bpf_func_state *state = func(env, reg);
982 int spi, ref_obj_id, i;
984 spi = dynptr_get_spi(env, reg);
988 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
989 invalidate_dynptr(env, state, spi);
993 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
995 /* If the dynptr has a ref_obj_id, then we need to invalidate
998 * 1) Any dynptrs with a matching ref_obj_id (clones)
999 * 2) Any slices derived from this dynptr.
1002 /* Invalidate any slices associated with this dynptr */
1003 WARN_ON_ONCE(release_reference(env, ref_obj_id));
1005 /* Invalidate any dynptr clones */
1006 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1007 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1010 /* it should always be the case that if the ref obj id
1011 * matches then the stack slot also belongs to a
1014 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1015 verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1018 if (state->stack[i].spilled_ptr.dynptr.first_slot)
1019 invalidate_dynptr(env, state, i);
1025 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1026 struct bpf_reg_state *reg);
1028 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1030 if (!env->allow_ptr_leaks)
1031 __mark_reg_not_init(env, reg);
1033 __mark_reg_unknown(env, reg);
1036 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1037 struct bpf_func_state *state, int spi)
1039 struct bpf_func_state *fstate;
1040 struct bpf_reg_state *dreg;
1043 /* We always ensure that STACK_DYNPTR is never set partially,
1044 * hence just checking for slot_type[0] is enough. This is
1045 * different for STACK_SPILL, where it may be only set for
1046 * 1 byte, so code has to use is_spilled_reg.
1048 if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1051 /* Reposition spi to first slot */
1052 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1055 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1056 verbose(env, "cannot overwrite referenced dynptr\n");
1060 mark_stack_slot_scratched(env, spi);
1061 mark_stack_slot_scratched(env, spi - 1);
1063 /* Writing partially to one dynptr stack slot destroys both. */
1064 for (i = 0; i < BPF_REG_SIZE; i++) {
1065 state->stack[spi].slot_type[i] = STACK_INVALID;
1066 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1069 dynptr_id = state->stack[spi].spilled_ptr.id;
1070 /* Invalidate any slices associated with this dynptr */
1071 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1072 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1073 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1075 if (dreg->dynptr_id == dynptr_id)
1076 mark_reg_invalid(env, dreg);
1079 /* Do not release reference state, we are destroying dynptr on stack,
1080 * not using some helper to release it. Just reset register.
1082 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1083 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1085 /* Same reason as unmark_stack_slots_dynptr above */
1086 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1087 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1092 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1096 if (reg->type == CONST_PTR_TO_DYNPTR)
1099 spi = dynptr_get_spi(env, reg);
1101 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1102 * error because this just means the stack state hasn't been updated yet.
1103 * We will do check_mem_access to check and update stack bounds later.
1105 if (spi < 0 && spi != -ERANGE)
1108 /* We don't need to check if the stack slots are marked by previous
1109 * dynptr initializations because we allow overwriting existing unreferenced
1110 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1111 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1112 * touching are completely destructed before we reinitialize them for a new
1113 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1114 * instead of delaying it until the end where the user will get "Unreleased
1120 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1122 struct bpf_func_state *state = func(env, reg);
1125 /* This already represents first slot of initialized bpf_dynptr.
1127 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1128 * check_func_arg_reg_off's logic, so we don't need to check its
1129 * offset and alignment.
1131 if (reg->type == CONST_PTR_TO_DYNPTR)
1134 spi = dynptr_get_spi(env, reg);
1137 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1140 for (i = 0; i < BPF_REG_SIZE; i++) {
1141 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1142 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1149 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1150 enum bpf_arg_type arg_type)
1152 struct bpf_func_state *state = func(env, reg);
1153 enum bpf_dynptr_type dynptr_type;
1156 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1157 if (arg_type == ARG_PTR_TO_DYNPTR)
1160 dynptr_type = arg_to_dynptr_type(arg_type);
1161 if (reg->type == CONST_PTR_TO_DYNPTR) {
1162 return reg->dynptr.type == dynptr_type;
1164 spi = dynptr_get_spi(env, reg);
1167 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1171 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1173 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1174 struct bpf_reg_state *reg, int insn_idx,
1175 struct btf *btf, u32 btf_id, int nr_slots)
1177 struct bpf_func_state *state = func(env, reg);
1180 spi = iter_get_spi(env, reg, nr_slots);
1184 id = acquire_reference_state(env, insn_idx);
1188 for (i = 0; i < nr_slots; i++) {
1189 struct bpf_stack_state *slot = &state->stack[spi - i];
1190 struct bpf_reg_state *st = &slot->spilled_ptr;
1192 __mark_reg_known_zero(st);
1193 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1194 st->live |= REG_LIVE_WRITTEN;
1195 st->ref_obj_id = i == 0 ? id : 0;
1197 st->iter.btf_id = btf_id;
1198 st->iter.state = BPF_ITER_STATE_ACTIVE;
1201 for (j = 0; j < BPF_REG_SIZE; j++)
1202 slot->slot_type[j] = STACK_ITER;
1204 mark_stack_slot_scratched(env, spi - i);
1210 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1211 struct bpf_reg_state *reg, int nr_slots)
1213 struct bpf_func_state *state = func(env, reg);
1216 spi = iter_get_spi(env, reg, nr_slots);
1220 for (i = 0; i < nr_slots; i++) {
1221 struct bpf_stack_state *slot = &state->stack[spi - i];
1222 struct bpf_reg_state *st = &slot->spilled_ptr;
1225 WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1227 __mark_reg_not_init(env, st);
1229 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1230 st->live |= REG_LIVE_WRITTEN;
1232 for (j = 0; j < BPF_REG_SIZE; j++)
1233 slot->slot_type[j] = STACK_INVALID;
1235 mark_stack_slot_scratched(env, spi - i);
1241 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1242 struct bpf_reg_state *reg, int nr_slots)
1244 struct bpf_func_state *state = func(env, reg);
1247 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1248 * will do check_mem_access to check and update stack bounds later, so
1249 * return true for that case.
1251 spi = iter_get_spi(env, reg, nr_slots);
1257 for (i = 0; i < nr_slots; i++) {
1258 struct bpf_stack_state *slot = &state->stack[spi - i];
1260 for (j = 0; j < BPF_REG_SIZE; j++)
1261 if (slot->slot_type[j] == STACK_ITER)
1268 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1269 struct btf *btf, u32 btf_id, int nr_slots)
1271 struct bpf_func_state *state = func(env, reg);
1274 spi = iter_get_spi(env, reg, nr_slots);
1278 for (i = 0; i < nr_slots; i++) {
1279 struct bpf_stack_state *slot = &state->stack[spi - i];
1280 struct bpf_reg_state *st = &slot->spilled_ptr;
1282 /* only main (first) slot has ref_obj_id set */
1283 if (i == 0 && !st->ref_obj_id)
1285 if (i != 0 && st->ref_obj_id)
1287 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1290 for (j = 0; j < BPF_REG_SIZE; j++)
1291 if (slot->slot_type[j] != STACK_ITER)
1298 /* Check if given stack slot is "special":
1299 * - spilled register state (STACK_SPILL);
1300 * - dynptr state (STACK_DYNPTR);
1301 * - iter state (STACK_ITER).
1303 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1305 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1317 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1322 /* The reg state of a pointer or a bounded scalar was saved when
1323 * it was spilled to the stack.
1325 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1327 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1330 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1332 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1333 stack->spilled_ptr.type == SCALAR_VALUE;
1336 static void scrub_spilled_slot(u8 *stype)
1338 if (*stype != STACK_INVALID)
1339 *stype = STACK_MISC;
1342 static void print_verifier_state(struct bpf_verifier_env *env,
1343 const struct bpf_func_state *state,
1346 const struct bpf_reg_state *reg;
1347 enum bpf_reg_type t;
1351 verbose(env, " frame%d:", state->frameno);
1352 for (i = 0; i < MAX_BPF_REG; i++) {
1353 reg = &state->regs[i];
1357 if (!print_all && !reg_scratched(env, i))
1359 verbose(env, " R%d", i);
1360 print_liveness(env, reg->live);
1362 if (t == SCALAR_VALUE && reg->precise)
1364 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1365 tnum_is_const(reg->var_off)) {
1366 /* reg->off should be 0 for SCALAR_VALUE */
1367 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1368 verbose(env, "%lld", reg->var_off.value + reg->off);
1370 const char *sep = "";
1372 verbose(env, "%s", reg_type_str(env, t));
1373 if (base_type(t) == PTR_TO_BTF_ID)
1374 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1377 * _a stands for append, was shortened to avoid multiline statements below.
1378 * This macro is used to output a comma separated list of attributes.
1380 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1383 verbose_a("id=%d", reg->id);
1384 if (reg->ref_obj_id)
1385 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1386 if (type_is_non_owning_ref(reg->type))
1387 verbose_a("%s", "non_own_ref");
1388 if (t != SCALAR_VALUE)
1389 verbose_a("off=%d", reg->off);
1390 if (type_is_pkt_pointer(t))
1391 verbose_a("r=%d", reg->range);
1392 else if (base_type(t) == CONST_PTR_TO_MAP ||
1393 base_type(t) == PTR_TO_MAP_KEY ||
1394 base_type(t) == PTR_TO_MAP_VALUE)
1395 verbose_a("ks=%d,vs=%d",
1396 reg->map_ptr->key_size,
1397 reg->map_ptr->value_size);
1398 if (tnum_is_const(reg->var_off)) {
1399 /* Typically an immediate SCALAR_VALUE, but
1400 * could be a pointer whose offset is too big
1403 verbose_a("imm=%llx", reg->var_off.value);
1405 if (reg->smin_value != reg->umin_value &&
1406 reg->smin_value != S64_MIN)
1407 verbose_a("smin=%lld", (long long)reg->smin_value);
1408 if (reg->smax_value != reg->umax_value &&
1409 reg->smax_value != S64_MAX)
1410 verbose_a("smax=%lld", (long long)reg->smax_value);
1411 if (reg->umin_value != 0)
1412 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1413 if (reg->umax_value != U64_MAX)
1414 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1415 if (!tnum_is_unknown(reg->var_off)) {
1418 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1419 verbose_a("var_off=%s", tn_buf);
1421 if (reg->s32_min_value != reg->smin_value &&
1422 reg->s32_min_value != S32_MIN)
1423 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1424 if (reg->s32_max_value != reg->smax_value &&
1425 reg->s32_max_value != S32_MAX)
1426 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1427 if (reg->u32_min_value != reg->umin_value &&
1428 reg->u32_min_value != U32_MIN)
1429 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1430 if (reg->u32_max_value != reg->umax_value &&
1431 reg->u32_max_value != U32_MAX)
1432 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1439 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1440 char types_buf[BPF_REG_SIZE + 1];
1444 for (j = 0; j < BPF_REG_SIZE; j++) {
1445 if (state->stack[i].slot_type[j] != STACK_INVALID)
1447 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1449 types_buf[BPF_REG_SIZE] = 0;
1452 if (!print_all && !stack_slot_scratched(env, i))
1454 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1456 reg = &state->stack[i].spilled_ptr;
1459 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1460 print_liveness(env, reg->live);
1461 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1462 if (t == SCALAR_VALUE && reg->precise)
1464 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1465 verbose(env, "%lld", reg->var_off.value + reg->off);
1468 i += BPF_DYNPTR_NR_SLOTS - 1;
1469 reg = &state->stack[i].spilled_ptr;
1471 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1472 print_liveness(env, reg->live);
1473 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1474 if (reg->ref_obj_id)
1475 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1478 /* only main slot has ref_obj_id set; skip others */
1479 reg = &state->stack[i].spilled_ptr;
1480 if (!reg->ref_obj_id)
1483 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1484 print_liveness(env, reg->live);
1485 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1486 iter_type_str(reg->iter.btf, reg->iter.btf_id),
1487 reg->ref_obj_id, iter_state_str(reg->iter.state),
1493 reg = &state->stack[i].spilled_ptr;
1495 for (j = 0; j < BPF_REG_SIZE; j++)
1496 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1497 types_buf[BPF_REG_SIZE] = 0;
1499 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1500 print_liveness(env, reg->live);
1501 verbose(env, "=%s", types_buf);
1505 if (state->acquired_refs && state->refs[0].id) {
1506 verbose(env, " refs=%d", state->refs[0].id);
1507 for (i = 1; i < state->acquired_refs; i++)
1508 if (state->refs[i].id)
1509 verbose(env, ",%d", state->refs[i].id);
1511 if (state->in_callback_fn)
1512 verbose(env, " cb");
1513 if (state->in_async_callback_fn)
1514 verbose(env, " async_cb");
1516 mark_verifier_state_clean(env);
1519 static inline u32 vlog_alignment(u32 pos)
1521 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1522 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1525 static void print_insn_state(struct bpf_verifier_env *env,
1526 const struct bpf_func_state *state)
1528 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1529 /* remove new line character */
1530 bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1531 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1533 verbose(env, "%d:", env->insn_idx);
1535 print_verifier_state(env, state, false);
1538 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1539 * small to hold src. This is different from krealloc since we don't want to preserve
1540 * the contents of dst.
1542 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1545 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1551 if (ZERO_OR_NULL_PTR(src))
1554 if (unlikely(check_mul_overflow(n, size, &bytes)))
1557 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1558 dst = krealloc(orig, alloc_bytes, flags);
1564 memcpy(dst, src, bytes);
1566 return dst ? dst : ZERO_SIZE_PTR;
1569 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1570 * small to hold new_n items. new items are zeroed out if the array grows.
1572 * Contrary to krealloc_array, does not free arr if new_n is zero.
1574 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1579 if (!new_n || old_n == new_n)
1582 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1583 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1591 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1594 return arr ? arr : ZERO_SIZE_PTR;
1597 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1599 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1600 sizeof(struct bpf_reference_state), GFP_KERNEL);
1604 dst->acquired_refs = src->acquired_refs;
1608 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1610 size_t n = src->allocated_stack / BPF_REG_SIZE;
1612 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1617 dst->allocated_stack = src->allocated_stack;
1621 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1623 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1624 sizeof(struct bpf_reference_state));
1628 state->acquired_refs = n;
1632 static int grow_stack_state(struct bpf_func_state *state, int size)
1634 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1639 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1643 state->allocated_stack = size;
1647 /* Acquire a pointer id from the env and update the state->refs to include
1648 * this new pointer reference.
1649 * On success, returns a valid pointer id to associate with the register
1650 * On failure, returns a negative errno.
1652 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1654 struct bpf_func_state *state = cur_func(env);
1655 int new_ofs = state->acquired_refs;
1658 err = resize_reference_state(state, state->acquired_refs + 1);
1662 state->refs[new_ofs].id = id;
1663 state->refs[new_ofs].insn_idx = insn_idx;
1664 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1669 /* release function corresponding to acquire_reference_state(). Idempotent. */
1670 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1674 last_idx = state->acquired_refs - 1;
1675 for (i = 0; i < state->acquired_refs; i++) {
1676 if (state->refs[i].id == ptr_id) {
1677 /* Cannot release caller references in callbacks */
1678 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1680 if (last_idx && i != last_idx)
1681 memcpy(&state->refs[i], &state->refs[last_idx],
1682 sizeof(*state->refs));
1683 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1684 state->acquired_refs--;
1691 static void free_func_state(struct bpf_func_state *state)
1696 kfree(state->stack);
1700 static void clear_jmp_history(struct bpf_verifier_state *state)
1702 kfree(state->jmp_history);
1703 state->jmp_history = NULL;
1704 state->jmp_history_cnt = 0;
1707 static void free_verifier_state(struct bpf_verifier_state *state,
1712 for (i = 0; i <= state->curframe; i++) {
1713 free_func_state(state->frame[i]);
1714 state->frame[i] = NULL;
1716 clear_jmp_history(state);
1721 /* copy verifier state from src to dst growing dst stack space
1722 * when necessary to accommodate larger src stack
1724 static int copy_func_state(struct bpf_func_state *dst,
1725 const struct bpf_func_state *src)
1729 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1730 err = copy_reference_state(dst, src);
1733 return copy_stack_state(dst, src);
1736 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1737 const struct bpf_verifier_state *src)
1739 struct bpf_func_state *dst;
1742 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1743 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1745 if (!dst_state->jmp_history)
1747 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1749 /* if dst has more stack frames then src frame, free them */
1750 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1751 free_func_state(dst_state->frame[i]);
1752 dst_state->frame[i] = NULL;
1754 dst_state->speculative = src->speculative;
1755 dst_state->active_rcu_lock = src->active_rcu_lock;
1756 dst_state->curframe = src->curframe;
1757 dst_state->active_lock.ptr = src->active_lock.ptr;
1758 dst_state->active_lock.id = src->active_lock.id;
1759 dst_state->branches = src->branches;
1760 dst_state->parent = src->parent;
1761 dst_state->first_insn_idx = src->first_insn_idx;
1762 dst_state->last_insn_idx = src->last_insn_idx;
1763 for (i = 0; i <= src->curframe; i++) {
1764 dst = dst_state->frame[i];
1766 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1769 dst_state->frame[i] = dst;
1771 err = copy_func_state(dst, src->frame[i]);
1778 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1781 u32 br = --st->branches;
1783 /* WARN_ON(br > 1) technically makes sense here,
1784 * but see comment in push_stack(), hence:
1786 WARN_ONCE((int)br < 0,
1787 "BUG update_branch_counts:branches_to_explore=%d\n",
1795 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1796 int *insn_idx, bool pop_log)
1798 struct bpf_verifier_state *cur = env->cur_state;
1799 struct bpf_verifier_stack_elem *elem, *head = env->head;
1802 if (env->head == NULL)
1806 err = copy_verifier_state(cur, &head->st);
1811 bpf_vlog_reset(&env->log, head->log_pos);
1813 *insn_idx = head->insn_idx;
1815 *prev_insn_idx = head->prev_insn_idx;
1817 free_verifier_state(&head->st, false);
1824 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1825 int insn_idx, int prev_insn_idx,
1828 struct bpf_verifier_state *cur = env->cur_state;
1829 struct bpf_verifier_stack_elem *elem;
1832 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1836 elem->insn_idx = insn_idx;
1837 elem->prev_insn_idx = prev_insn_idx;
1838 elem->next = env->head;
1839 elem->log_pos = env->log.end_pos;
1842 err = copy_verifier_state(&elem->st, cur);
1845 elem->st.speculative |= speculative;
1846 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1847 verbose(env, "The sequence of %d jumps is too complex.\n",
1851 if (elem->st.parent) {
1852 ++elem->st.parent->branches;
1853 /* WARN_ON(branches > 2) technically makes sense here,
1855 * 1. speculative states will bump 'branches' for non-branch
1857 * 2. is_state_visited() heuristics may decide not to create
1858 * a new state for a sequence of branches and all such current
1859 * and cloned states will be pointing to a single parent state
1860 * which might have large 'branches' count.
1865 free_verifier_state(env->cur_state, true);
1866 env->cur_state = NULL;
1867 /* pop all elements and return */
1868 while (!pop_stack(env, NULL, NULL, false));
1872 #define CALLER_SAVED_REGS 6
1873 static const int caller_saved[CALLER_SAVED_REGS] = {
1874 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1877 /* This helper doesn't clear reg->id */
1878 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1880 reg->var_off = tnum_const(imm);
1881 reg->smin_value = (s64)imm;
1882 reg->smax_value = (s64)imm;
1883 reg->umin_value = imm;
1884 reg->umax_value = imm;
1886 reg->s32_min_value = (s32)imm;
1887 reg->s32_max_value = (s32)imm;
1888 reg->u32_min_value = (u32)imm;
1889 reg->u32_max_value = (u32)imm;
1892 /* Mark the unknown part of a register (variable offset or scalar value) as
1893 * known to have the value @imm.
1895 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1897 /* Clear off and union(map_ptr, range) */
1898 memset(((u8 *)reg) + sizeof(reg->type), 0,
1899 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1901 reg->ref_obj_id = 0;
1902 ___mark_reg_known(reg, imm);
1905 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1907 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1908 reg->s32_min_value = (s32)imm;
1909 reg->s32_max_value = (s32)imm;
1910 reg->u32_min_value = (u32)imm;
1911 reg->u32_max_value = (u32)imm;
1914 /* Mark the 'variable offset' part of a register as zero. This should be
1915 * used only on registers holding a pointer type.
1917 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1919 __mark_reg_known(reg, 0);
1922 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1924 __mark_reg_known(reg, 0);
1925 reg->type = SCALAR_VALUE;
1928 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1929 struct bpf_reg_state *regs, u32 regno)
1931 if (WARN_ON(regno >= MAX_BPF_REG)) {
1932 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1933 /* Something bad happened, let's kill all regs */
1934 for (regno = 0; regno < MAX_BPF_REG; regno++)
1935 __mark_reg_not_init(env, regs + regno);
1938 __mark_reg_known_zero(regs + regno);
1941 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1942 bool first_slot, int dynptr_id)
1944 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1945 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1946 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1948 __mark_reg_known_zero(reg);
1949 reg->type = CONST_PTR_TO_DYNPTR;
1950 /* Give each dynptr a unique id to uniquely associate slices to it. */
1951 reg->id = dynptr_id;
1952 reg->dynptr.type = type;
1953 reg->dynptr.first_slot = first_slot;
1956 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1958 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1959 const struct bpf_map *map = reg->map_ptr;
1961 if (map->inner_map_meta) {
1962 reg->type = CONST_PTR_TO_MAP;
1963 reg->map_ptr = map->inner_map_meta;
1964 /* transfer reg's id which is unique for every map_lookup_elem
1965 * as UID of the inner map.
1967 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1968 reg->map_uid = reg->id;
1969 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1970 reg->type = PTR_TO_XDP_SOCK;
1971 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1972 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1973 reg->type = PTR_TO_SOCKET;
1975 reg->type = PTR_TO_MAP_VALUE;
1980 reg->type &= ~PTR_MAYBE_NULL;
1983 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1984 struct btf_field_graph_root *ds_head)
1986 __mark_reg_known_zero(®s[regno]);
1987 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1988 regs[regno].btf = ds_head->btf;
1989 regs[regno].btf_id = ds_head->value_btf_id;
1990 regs[regno].off = ds_head->node_offset;
1993 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1995 return type_is_pkt_pointer(reg->type);
1998 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2000 return reg_is_pkt_pointer(reg) ||
2001 reg->type == PTR_TO_PACKET_END;
2004 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2006 return base_type(reg->type) == PTR_TO_MEM &&
2007 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2010 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2011 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2012 enum bpf_reg_type which)
2014 /* The register can already have a range from prior markings.
2015 * This is fine as long as it hasn't been advanced from its
2018 return reg->type == which &&
2021 tnum_equals_const(reg->var_off, 0);
2024 /* Reset the min/max bounds of a register */
2025 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2027 reg->smin_value = S64_MIN;
2028 reg->smax_value = S64_MAX;
2029 reg->umin_value = 0;
2030 reg->umax_value = U64_MAX;
2032 reg->s32_min_value = S32_MIN;
2033 reg->s32_max_value = S32_MAX;
2034 reg->u32_min_value = 0;
2035 reg->u32_max_value = U32_MAX;
2038 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2040 reg->smin_value = S64_MIN;
2041 reg->smax_value = S64_MAX;
2042 reg->umin_value = 0;
2043 reg->umax_value = U64_MAX;
2046 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2048 reg->s32_min_value = S32_MIN;
2049 reg->s32_max_value = S32_MAX;
2050 reg->u32_min_value = 0;
2051 reg->u32_max_value = U32_MAX;
2054 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2056 struct tnum var32_off = tnum_subreg(reg->var_off);
2058 /* min signed is max(sign bit) | min(other bits) */
2059 reg->s32_min_value = max_t(s32, reg->s32_min_value,
2060 var32_off.value | (var32_off.mask & S32_MIN));
2061 /* max signed is min(sign bit) | max(other bits) */
2062 reg->s32_max_value = min_t(s32, reg->s32_max_value,
2063 var32_off.value | (var32_off.mask & S32_MAX));
2064 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2065 reg->u32_max_value = min(reg->u32_max_value,
2066 (u32)(var32_off.value | var32_off.mask));
2069 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2071 /* min signed is max(sign bit) | min(other bits) */
2072 reg->smin_value = max_t(s64, reg->smin_value,
2073 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2074 /* max signed is min(sign bit) | max(other bits) */
2075 reg->smax_value = min_t(s64, reg->smax_value,
2076 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2077 reg->umin_value = max(reg->umin_value, reg->var_off.value);
2078 reg->umax_value = min(reg->umax_value,
2079 reg->var_off.value | reg->var_off.mask);
2082 static void __update_reg_bounds(struct bpf_reg_state *reg)
2084 __update_reg32_bounds(reg);
2085 __update_reg64_bounds(reg);
2088 /* Uses signed min/max values to inform unsigned, and vice-versa */
2089 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2091 /* Learn sign from signed bounds.
2092 * If we cannot cross the sign boundary, then signed and unsigned bounds
2093 * are the same, so combine. This works even in the negative case, e.g.
2094 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2096 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2097 reg->s32_min_value = reg->u32_min_value =
2098 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2099 reg->s32_max_value = reg->u32_max_value =
2100 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2103 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2104 * boundary, so we must be careful.
2106 if ((s32)reg->u32_max_value >= 0) {
2107 /* Positive. We can't learn anything from the smin, but smax
2108 * is positive, hence safe.
2110 reg->s32_min_value = reg->u32_min_value;
2111 reg->s32_max_value = reg->u32_max_value =
2112 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2113 } else if ((s32)reg->u32_min_value < 0) {
2114 /* Negative. We can't learn anything from the smax, but smin
2115 * is negative, hence safe.
2117 reg->s32_min_value = reg->u32_min_value =
2118 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2119 reg->s32_max_value = reg->u32_max_value;
2123 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2125 /* Learn sign from signed bounds.
2126 * If we cannot cross the sign boundary, then signed and unsigned bounds
2127 * are the same, so combine. This works even in the negative case, e.g.
2128 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2130 if (reg->smin_value >= 0 || reg->smax_value < 0) {
2131 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2133 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2137 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2138 * boundary, so we must be careful.
2140 if ((s64)reg->umax_value >= 0) {
2141 /* Positive. We can't learn anything from the smin, but smax
2142 * is positive, hence safe.
2144 reg->smin_value = reg->umin_value;
2145 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2147 } else if ((s64)reg->umin_value < 0) {
2148 /* Negative. We can't learn anything from the smax, but smin
2149 * is negative, hence safe.
2151 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2153 reg->smax_value = reg->umax_value;
2157 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2159 __reg32_deduce_bounds(reg);
2160 __reg64_deduce_bounds(reg);
2163 /* Attempts to improve var_off based on unsigned min/max information */
2164 static void __reg_bound_offset(struct bpf_reg_state *reg)
2166 struct tnum var64_off = tnum_intersect(reg->var_off,
2167 tnum_range(reg->umin_value,
2169 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2170 tnum_range(reg->u32_min_value,
2171 reg->u32_max_value));
2173 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2176 static void reg_bounds_sync(struct bpf_reg_state *reg)
2178 /* We might have learned new bounds from the var_off. */
2179 __update_reg_bounds(reg);
2180 /* We might have learned something about the sign bit. */
2181 __reg_deduce_bounds(reg);
2182 /* We might have learned some bits from the bounds. */
2183 __reg_bound_offset(reg);
2184 /* Intersecting with the old var_off might have improved our bounds
2185 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2186 * then new var_off is (0; 0x7f...fc) which improves our umax.
2188 __update_reg_bounds(reg);
2191 static bool __reg32_bound_s64(s32 a)
2193 return a >= 0 && a <= S32_MAX;
2196 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2198 reg->umin_value = reg->u32_min_value;
2199 reg->umax_value = reg->u32_max_value;
2201 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2202 * be positive otherwise set to worse case bounds and refine later
2205 if (__reg32_bound_s64(reg->s32_min_value) &&
2206 __reg32_bound_s64(reg->s32_max_value)) {
2207 reg->smin_value = reg->s32_min_value;
2208 reg->smax_value = reg->s32_max_value;
2210 reg->smin_value = 0;
2211 reg->smax_value = U32_MAX;
2215 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2217 /* special case when 64-bit register has upper 32-bit register
2218 * zeroed. Typically happens after zext or <<32, >>32 sequence
2219 * allowing us to use 32-bit bounds directly,
2221 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2222 __reg_assign_32_into_64(reg);
2224 /* Otherwise the best we can do is push lower 32bit known and
2225 * unknown bits into register (var_off set from jmp logic)
2226 * then learn as much as possible from the 64-bit tnum
2227 * known and unknown bits. The previous smin/smax bounds are
2228 * invalid here because of jmp32 compare so mark them unknown
2229 * so they do not impact tnum bounds calculation.
2231 __mark_reg64_unbounded(reg);
2233 reg_bounds_sync(reg);
2236 static bool __reg64_bound_s32(s64 a)
2238 return a >= S32_MIN && a <= S32_MAX;
2241 static bool __reg64_bound_u32(u64 a)
2243 return a >= U32_MIN && a <= U32_MAX;
2246 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2248 __mark_reg32_unbounded(reg);
2249 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2250 reg->s32_min_value = (s32)reg->smin_value;
2251 reg->s32_max_value = (s32)reg->smax_value;
2253 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2254 reg->u32_min_value = (u32)reg->umin_value;
2255 reg->u32_max_value = (u32)reg->umax_value;
2257 reg_bounds_sync(reg);
2260 /* Mark a register as having a completely unknown (scalar) value. */
2261 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2262 struct bpf_reg_state *reg)
2265 * Clear type, off, and union(map_ptr, range) and
2266 * padding between 'type' and union
2268 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2269 reg->type = SCALAR_VALUE;
2271 reg->ref_obj_id = 0;
2272 reg->var_off = tnum_unknown;
2274 reg->precise = !env->bpf_capable;
2275 __mark_reg_unbounded(reg);
2278 static void mark_reg_unknown(struct bpf_verifier_env *env,
2279 struct bpf_reg_state *regs, u32 regno)
2281 if (WARN_ON(regno >= MAX_BPF_REG)) {
2282 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2283 /* Something bad happened, let's kill all regs except FP */
2284 for (regno = 0; regno < BPF_REG_FP; regno++)
2285 __mark_reg_not_init(env, regs + regno);
2288 __mark_reg_unknown(env, regs + regno);
2291 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2292 struct bpf_reg_state *reg)
2294 __mark_reg_unknown(env, reg);
2295 reg->type = NOT_INIT;
2298 static void mark_reg_not_init(struct bpf_verifier_env *env,
2299 struct bpf_reg_state *regs, u32 regno)
2301 if (WARN_ON(regno >= MAX_BPF_REG)) {
2302 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2303 /* Something bad happened, let's kill all regs except FP */
2304 for (regno = 0; regno < BPF_REG_FP; regno++)
2305 __mark_reg_not_init(env, regs + regno);
2308 __mark_reg_not_init(env, regs + regno);
2311 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2312 struct bpf_reg_state *regs, u32 regno,
2313 enum bpf_reg_type reg_type,
2314 struct btf *btf, u32 btf_id,
2315 enum bpf_type_flag flag)
2317 if (reg_type == SCALAR_VALUE) {
2318 mark_reg_unknown(env, regs, regno);
2321 mark_reg_known_zero(env, regs, regno);
2322 regs[regno].type = PTR_TO_BTF_ID | flag;
2323 regs[regno].btf = btf;
2324 regs[regno].btf_id = btf_id;
2327 #define DEF_NOT_SUBREG (0)
2328 static void init_reg_state(struct bpf_verifier_env *env,
2329 struct bpf_func_state *state)
2331 struct bpf_reg_state *regs = state->regs;
2334 for (i = 0; i < MAX_BPF_REG; i++) {
2335 mark_reg_not_init(env, regs, i);
2336 regs[i].live = REG_LIVE_NONE;
2337 regs[i].parent = NULL;
2338 regs[i].subreg_def = DEF_NOT_SUBREG;
2342 regs[BPF_REG_FP].type = PTR_TO_STACK;
2343 mark_reg_known_zero(env, regs, BPF_REG_FP);
2344 regs[BPF_REG_FP].frameno = state->frameno;
2347 #define BPF_MAIN_FUNC (-1)
2348 static void init_func_state(struct bpf_verifier_env *env,
2349 struct bpf_func_state *state,
2350 int callsite, int frameno, int subprogno)
2352 state->callsite = callsite;
2353 state->frameno = frameno;
2354 state->subprogno = subprogno;
2355 state->callback_ret_range = tnum_range(0, 0);
2356 init_reg_state(env, state);
2357 mark_verifier_state_scratched(env);
2360 /* Similar to push_stack(), but for async callbacks */
2361 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2362 int insn_idx, int prev_insn_idx,
2365 struct bpf_verifier_stack_elem *elem;
2366 struct bpf_func_state *frame;
2368 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2372 elem->insn_idx = insn_idx;
2373 elem->prev_insn_idx = prev_insn_idx;
2374 elem->next = env->head;
2375 elem->log_pos = env->log.end_pos;
2378 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2380 "The sequence of %d jumps is too complex for async cb.\n",
2384 /* Unlike push_stack() do not copy_verifier_state().
2385 * The caller state doesn't matter.
2386 * This is async callback. It starts in a fresh stack.
2387 * Initialize it similar to do_check_common().
2389 elem->st.branches = 1;
2390 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2393 init_func_state(env, frame,
2394 BPF_MAIN_FUNC /* callsite */,
2395 0 /* frameno within this callchain */,
2396 subprog /* subprog number within this prog */);
2397 elem->st.frame[0] = frame;
2400 free_verifier_state(env->cur_state, true);
2401 env->cur_state = NULL;
2402 /* pop all elements and return */
2403 while (!pop_stack(env, NULL, NULL, false));
2409 SRC_OP, /* register is used as source operand */
2410 DST_OP, /* register is used as destination operand */
2411 DST_OP_NO_MARK /* same as above, check only, don't mark */
2414 static int cmp_subprogs(const void *a, const void *b)
2416 return ((struct bpf_subprog_info *)a)->start -
2417 ((struct bpf_subprog_info *)b)->start;
2420 static int find_subprog(struct bpf_verifier_env *env, int off)
2422 struct bpf_subprog_info *p;
2424 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2425 sizeof(env->subprog_info[0]), cmp_subprogs);
2428 return p - env->subprog_info;
2432 static int add_subprog(struct bpf_verifier_env *env, int off)
2434 int insn_cnt = env->prog->len;
2437 if (off >= insn_cnt || off < 0) {
2438 verbose(env, "call to invalid destination\n");
2441 ret = find_subprog(env, off);
2444 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2445 verbose(env, "too many subprograms\n");
2448 /* determine subprog starts. The end is one before the next starts */
2449 env->subprog_info[env->subprog_cnt++].start = off;
2450 sort(env->subprog_info, env->subprog_cnt,
2451 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2452 return env->subprog_cnt - 1;
2455 #define MAX_KFUNC_DESCS 256
2456 #define MAX_KFUNC_BTFS 256
2458 struct bpf_kfunc_desc {
2459 struct btf_func_model func_model;
2466 struct bpf_kfunc_btf {
2468 struct module *module;
2472 struct bpf_kfunc_desc_tab {
2473 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2474 * verification. JITs do lookups by bpf_insn, where func_id may not be
2475 * available, therefore at the end of verification do_misc_fixups()
2476 * sorts this by imm and offset.
2478 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2482 struct bpf_kfunc_btf_tab {
2483 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2487 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2489 const struct bpf_kfunc_desc *d0 = a;
2490 const struct bpf_kfunc_desc *d1 = b;
2492 /* func_id is not greater than BTF_MAX_TYPE */
2493 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2496 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2498 const struct bpf_kfunc_btf *d0 = a;
2499 const struct bpf_kfunc_btf *d1 = b;
2501 return d0->offset - d1->offset;
2504 static const struct bpf_kfunc_desc *
2505 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2507 struct bpf_kfunc_desc desc = {
2511 struct bpf_kfunc_desc_tab *tab;
2513 tab = prog->aux->kfunc_tab;
2514 return bsearch(&desc, tab->descs, tab->nr_descs,
2515 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2518 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2519 u16 btf_fd_idx, u8 **func_addr)
2521 const struct bpf_kfunc_desc *desc;
2523 desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2527 *func_addr = (u8 *)desc->addr;
2531 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2534 struct bpf_kfunc_btf kf_btf = { .offset = offset };
2535 struct bpf_kfunc_btf_tab *tab;
2536 struct bpf_kfunc_btf *b;
2541 tab = env->prog->aux->kfunc_btf_tab;
2542 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2543 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2545 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2546 verbose(env, "too many different module BTFs\n");
2547 return ERR_PTR(-E2BIG);
2550 if (bpfptr_is_null(env->fd_array)) {
2551 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2552 return ERR_PTR(-EPROTO);
2555 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2556 offset * sizeof(btf_fd),
2558 return ERR_PTR(-EFAULT);
2560 btf = btf_get_by_fd(btf_fd);
2562 verbose(env, "invalid module BTF fd specified\n");
2566 if (!btf_is_module(btf)) {
2567 verbose(env, "BTF fd for kfunc is not a module BTF\n");
2569 return ERR_PTR(-EINVAL);
2572 mod = btf_try_get_module(btf);
2575 return ERR_PTR(-ENXIO);
2578 b = &tab->descs[tab->nr_descs++];
2583 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2584 kfunc_btf_cmp_by_off, NULL);
2589 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2594 while (tab->nr_descs--) {
2595 module_put(tab->descs[tab->nr_descs].module);
2596 btf_put(tab->descs[tab->nr_descs].btf);
2601 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2605 /* In the future, this can be allowed to increase limit
2606 * of fd index into fd_array, interpreted as u16.
2608 verbose(env, "negative offset disallowed for kernel module function call\n");
2609 return ERR_PTR(-EINVAL);
2612 return __find_kfunc_desc_btf(env, offset);
2614 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2617 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2619 const struct btf_type *func, *func_proto;
2620 struct bpf_kfunc_btf_tab *btf_tab;
2621 struct bpf_kfunc_desc_tab *tab;
2622 struct bpf_prog_aux *prog_aux;
2623 struct bpf_kfunc_desc *desc;
2624 const char *func_name;
2625 struct btf *desc_btf;
2626 unsigned long call_imm;
2630 prog_aux = env->prog->aux;
2631 tab = prog_aux->kfunc_tab;
2632 btf_tab = prog_aux->kfunc_btf_tab;
2635 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2639 if (!env->prog->jit_requested) {
2640 verbose(env, "JIT is required for calling kernel function\n");
2644 if (!bpf_jit_supports_kfunc_call()) {
2645 verbose(env, "JIT does not support calling kernel function\n");
2649 if (!env->prog->gpl_compatible) {
2650 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2654 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2657 prog_aux->kfunc_tab = tab;
2660 /* func_id == 0 is always invalid, but instead of returning an error, be
2661 * conservative and wait until the code elimination pass before returning
2662 * error, so that invalid calls that get pruned out can be in BPF programs
2663 * loaded from userspace. It is also required that offset be untouched
2666 if (!func_id && !offset)
2669 if (!btf_tab && offset) {
2670 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2673 prog_aux->kfunc_btf_tab = btf_tab;
2676 desc_btf = find_kfunc_desc_btf(env, offset);
2677 if (IS_ERR(desc_btf)) {
2678 verbose(env, "failed to find BTF for kernel function\n");
2679 return PTR_ERR(desc_btf);
2682 if (find_kfunc_desc(env->prog, func_id, offset))
2685 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2686 verbose(env, "too many different kernel function calls\n");
2690 func = btf_type_by_id(desc_btf, func_id);
2691 if (!func || !btf_type_is_func(func)) {
2692 verbose(env, "kernel btf_id %u is not a function\n",
2696 func_proto = btf_type_by_id(desc_btf, func->type);
2697 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2698 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2703 func_name = btf_name_by_offset(desc_btf, func->name_off);
2704 addr = kallsyms_lookup_name(func_name);
2706 verbose(env, "cannot find address for kernel function %s\n",
2710 specialize_kfunc(env, func_id, offset, &addr);
2712 if (bpf_jit_supports_far_kfunc_call()) {
2715 call_imm = BPF_CALL_IMM(addr);
2716 /* Check whether the relative offset overflows desc->imm */
2717 if ((unsigned long)(s32)call_imm != call_imm) {
2718 verbose(env, "address of kernel function %s is out of range\n",
2724 if (bpf_dev_bound_kfunc_id(func_id)) {
2725 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2730 desc = &tab->descs[tab->nr_descs++];
2731 desc->func_id = func_id;
2732 desc->imm = call_imm;
2733 desc->offset = offset;
2735 err = btf_distill_func_proto(&env->log, desc_btf,
2736 func_proto, func_name,
2739 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2740 kfunc_desc_cmp_by_id_off, NULL);
2744 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2746 const struct bpf_kfunc_desc *d0 = a;
2747 const struct bpf_kfunc_desc *d1 = b;
2749 if (d0->imm != d1->imm)
2750 return d0->imm < d1->imm ? -1 : 1;
2751 if (d0->offset != d1->offset)
2752 return d0->offset < d1->offset ? -1 : 1;
2756 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2758 struct bpf_kfunc_desc_tab *tab;
2760 tab = prog->aux->kfunc_tab;
2764 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2765 kfunc_desc_cmp_by_imm_off, NULL);
2768 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2770 return !!prog->aux->kfunc_tab;
2773 const struct btf_func_model *
2774 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2775 const struct bpf_insn *insn)
2777 const struct bpf_kfunc_desc desc = {
2779 .offset = insn->off,
2781 const struct bpf_kfunc_desc *res;
2782 struct bpf_kfunc_desc_tab *tab;
2784 tab = prog->aux->kfunc_tab;
2785 res = bsearch(&desc, tab->descs, tab->nr_descs,
2786 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2788 return res ? &res->func_model : NULL;
2791 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2793 struct bpf_subprog_info *subprog = env->subprog_info;
2794 struct bpf_insn *insn = env->prog->insnsi;
2795 int i, ret, insn_cnt = env->prog->len;
2797 /* Add entry function. */
2798 ret = add_subprog(env, 0);
2802 for (i = 0; i < insn_cnt; i++, insn++) {
2803 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2804 !bpf_pseudo_kfunc_call(insn))
2807 if (!env->bpf_capable) {
2808 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2812 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2813 ret = add_subprog(env, i + insn->imm + 1);
2815 ret = add_kfunc_call(env, insn->imm, insn->off);
2821 /* Add a fake 'exit' subprog which could simplify subprog iteration
2822 * logic. 'subprog_cnt' should not be increased.
2824 subprog[env->subprog_cnt].start = insn_cnt;
2826 if (env->log.level & BPF_LOG_LEVEL2)
2827 for (i = 0; i < env->subprog_cnt; i++)
2828 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2833 static int check_subprogs(struct bpf_verifier_env *env)
2835 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2836 struct bpf_subprog_info *subprog = env->subprog_info;
2837 struct bpf_insn *insn = env->prog->insnsi;
2838 int insn_cnt = env->prog->len;
2840 /* now check that all jumps are within the same subprog */
2841 subprog_start = subprog[cur_subprog].start;
2842 subprog_end = subprog[cur_subprog + 1].start;
2843 for (i = 0; i < insn_cnt; i++) {
2844 u8 code = insn[i].code;
2846 if (code == (BPF_JMP | BPF_CALL) &&
2847 insn[i].src_reg == 0 &&
2848 insn[i].imm == BPF_FUNC_tail_call)
2849 subprog[cur_subprog].has_tail_call = true;
2850 if (BPF_CLASS(code) == BPF_LD &&
2851 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2852 subprog[cur_subprog].has_ld_abs = true;
2853 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2855 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2857 off = i + insn[i].off + 1;
2858 if (off < subprog_start || off >= subprog_end) {
2859 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2863 if (i == subprog_end - 1) {
2864 /* to avoid fall-through from one subprog into another
2865 * the last insn of the subprog should be either exit
2866 * or unconditional jump back
2868 if (code != (BPF_JMP | BPF_EXIT) &&
2869 code != (BPF_JMP | BPF_JA)) {
2870 verbose(env, "last insn is not an exit or jmp\n");
2873 subprog_start = subprog_end;
2875 if (cur_subprog < env->subprog_cnt)
2876 subprog_end = subprog[cur_subprog + 1].start;
2882 /* Parentage chain of this register (or stack slot) should take care of all
2883 * issues like callee-saved registers, stack slot allocation time, etc.
2885 static int mark_reg_read(struct bpf_verifier_env *env,
2886 const struct bpf_reg_state *state,
2887 struct bpf_reg_state *parent, u8 flag)
2889 bool writes = parent == state->parent; /* Observe write marks */
2893 /* if read wasn't screened by an earlier write ... */
2894 if (writes && state->live & REG_LIVE_WRITTEN)
2896 if (parent->live & REG_LIVE_DONE) {
2897 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2898 reg_type_str(env, parent->type),
2899 parent->var_off.value, parent->off);
2902 /* The first condition is more likely to be true than the
2903 * second, checked it first.
2905 if ((parent->live & REG_LIVE_READ) == flag ||
2906 parent->live & REG_LIVE_READ64)
2907 /* The parentage chain never changes and
2908 * this parent was already marked as LIVE_READ.
2909 * There is no need to keep walking the chain again and
2910 * keep re-marking all parents as LIVE_READ.
2911 * This case happens when the same register is read
2912 * multiple times without writes into it in-between.
2913 * Also, if parent has the stronger REG_LIVE_READ64 set,
2914 * then no need to set the weak REG_LIVE_READ32.
2917 /* ... then we depend on parent's value */
2918 parent->live |= flag;
2919 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2920 if (flag == REG_LIVE_READ64)
2921 parent->live &= ~REG_LIVE_READ32;
2923 parent = state->parent;
2928 if (env->longest_mark_read_walk < cnt)
2929 env->longest_mark_read_walk = cnt;
2933 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2935 struct bpf_func_state *state = func(env, reg);
2938 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2939 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2942 if (reg->type == CONST_PTR_TO_DYNPTR)
2944 spi = dynptr_get_spi(env, reg);
2947 /* Caller ensures dynptr is valid and initialized, which means spi is in
2948 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2951 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2952 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2955 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2956 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2959 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2960 int spi, int nr_slots)
2962 struct bpf_func_state *state = func(env, reg);
2965 for (i = 0; i < nr_slots; i++) {
2966 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2968 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2972 mark_stack_slot_scratched(env, spi - i);
2978 /* This function is supposed to be used by the following 32-bit optimization
2979 * code only. It returns TRUE if the source or destination register operates
2980 * on 64-bit, otherwise return FALSE.
2982 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2983 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2988 class = BPF_CLASS(code);
2990 if (class == BPF_JMP) {
2991 /* BPF_EXIT for "main" will reach here. Return TRUE
2996 if (op == BPF_CALL) {
2997 /* BPF to BPF call will reach here because of marking
2998 * caller saved clobber with DST_OP_NO_MARK for which we
2999 * don't care the register def because they are anyway
3000 * marked as NOT_INIT already.
3002 if (insn->src_reg == BPF_PSEUDO_CALL)
3004 /* Helper call will reach here because of arg type
3005 * check, conservatively return TRUE.
3014 if (class == BPF_ALU64 || class == BPF_JMP ||
3015 /* BPF_END always use BPF_ALU class. */
3016 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3019 if (class == BPF_ALU || class == BPF_JMP32)
3022 if (class == BPF_LDX) {
3024 return BPF_SIZE(code) == BPF_DW;
3025 /* LDX source must be ptr. */
3029 if (class == BPF_STX) {
3030 /* BPF_STX (including atomic variants) has multiple source
3031 * operands, one of which is a ptr. Check whether the caller is
3034 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3036 return BPF_SIZE(code) == BPF_DW;
3039 if (class == BPF_LD) {
3040 u8 mode = BPF_MODE(code);
3043 if (mode == BPF_IMM)
3046 /* Both LD_IND and LD_ABS return 32-bit data. */
3050 /* Implicit ctx ptr. */
3051 if (regno == BPF_REG_6)
3054 /* Explicit source could be any width. */
3058 if (class == BPF_ST)
3059 /* The only source register for BPF_ST is a ptr. */
3062 /* Conservatively return true at default. */
3066 /* Return the regno defined by the insn, or -1. */
3067 static int insn_def_regno(const struct bpf_insn *insn)
3069 switch (BPF_CLASS(insn->code)) {
3075 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3076 (insn->imm & BPF_FETCH)) {
3077 if (insn->imm == BPF_CMPXCHG)
3080 return insn->src_reg;
3085 return insn->dst_reg;
3089 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3090 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3092 int dst_reg = insn_def_regno(insn);
3097 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3100 static void mark_insn_zext(struct bpf_verifier_env *env,
3101 struct bpf_reg_state *reg)
3103 s32 def_idx = reg->subreg_def;
3105 if (def_idx == DEF_NOT_SUBREG)
3108 env->insn_aux_data[def_idx - 1].zext_dst = true;
3109 /* The dst will be zero extended, so won't be sub-register anymore. */
3110 reg->subreg_def = DEF_NOT_SUBREG;
3113 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3114 enum reg_arg_type t)
3116 struct bpf_verifier_state *vstate = env->cur_state;
3117 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3118 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3119 struct bpf_reg_state *reg, *regs = state->regs;
3122 if (regno >= MAX_BPF_REG) {
3123 verbose(env, "R%d is invalid\n", regno);
3127 mark_reg_scratched(env, regno);
3130 rw64 = is_reg64(env, insn, regno, reg, t);
3132 /* check whether register used as source operand can be read */
3133 if (reg->type == NOT_INIT) {
3134 verbose(env, "R%d !read_ok\n", regno);
3137 /* We don't need to worry about FP liveness because it's read-only */
3138 if (regno == BPF_REG_FP)
3142 mark_insn_zext(env, reg);
3144 return mark_reg_read(env, reg, reg->parent,
3145 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3147 /* check whether register used as dest operand can be written to */
3148 if (regno == BPF_REG_FP) {
3149 verbose(env, "frame pointer is read only\n");
3152 reg->live |= REG_LIVE_WRITTEN;
3153 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3155 mark_reg_unknown(env, regs, regno);
3160 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3162 env->insn_aux_data[idx].jmp_point = true;
3165 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3167 return env->insn_aux_data[insn_idx].jmp_point;
3170 /* for any branch, call, exit record the history of jmps in the given state */
3171 static int push_jmp_history(struct bpf_verifier_env *env,
3172 struct bpf_verifier_state *cur)
3174 u32 cnt = cur->jmp_history_cnt;
3175 struct bpf_idx_pair *p;
3178 if (!is_jmp_point(env, env->insn_idx))
3182 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3183 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3186 p[cnt - 1].idx = env->insn_idx;
3187 p[cnt - 1].prev_idx = env->prev_insn_idx;
3188 cur->jmp_history = p;
3189 cur->jmp_history_cnt = cnt;
3193 /* Backtrack one insn at a time. If idx is not at the top of recorded
3194 * history then previous instruction came from straight line execution.
3196 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3201 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3202 i = st->jmp_history[cnt - 1].prev_idx;
3210 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3212 const struct btf_type *func;
3213 struct btf *desc_btf;
3215 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3218 desc_btf = find_kfunc_desc_btf(data, insn->off);
3219 if (IS_ERR(desc_btf))
3222 func = btf_type_by_id(desc_btf, insn->imm);
3223 return btf_name_by_offset(desc_btf, func->name_off);
3226 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3231 static inline void bt_reset(struct backtrack_state *bt)
3233 struct bpf_verifier_env *env = bt->env;
3235 memset(bt, 0, sizeof(*bt));
3239 static inline u32 bt_empty(struct backtrack_state *bt)
3244 for (i = 0; i <= bt->frame; i++)
3245 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3250 static inline int bt_subprog_enter(struct backtrack_state *bt)
3252 if (bt->frame == MAX_CALL_FRAMES - 1) {
3253 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3254 WARN_ONCE(1, "verifier backtracking bug");
3261 static inline int bt_subprog_exit(struct backtrack_state *bt)
3263 if (bt->frame == 0) {
3264 verbose(bt->env, "BUG subprog exit from frame 0\n");
3265 WARN_ONCE(1, "verifier backtracking bug");
3272 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3274 bt->reg_masks[frame] |= 1 << reg;
3277 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3279 bt->reg_masks[frame] &= ~(1 << reg);
3282 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3284 bt_set_frame_reg(bt, bt->frame, reg);
3287 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3289 bt_clear_frame_reg(bt, bt->frame, reg);
3292 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3294 bt->stack_masks[frame] |= 1ull << slot;
3297 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3299 bt->stack_masks[frame] &= ~(1ull << slot);
3302 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3304 bt_set_frame_slot(bt, bt->frame, slot);
3307 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3309 bt_clear_frame_slot(bt, bt->frame, slot);
3312 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3314 return bt->reg_masks[frame];
3317 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3319 return bt->reg_masks[bt->frame];
3322 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3324 return bt->stack_masks[frame];
3327 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3329 return bt->stack_masks[bt->frame];
3332 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3334 return bt->reg_masks[bt->frame] & (1 << reg);
3337 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3339 return bt->stack_masks[bt->frame] & (1ull << slot);
3342 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3343 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3345 DECLARE_BITMAP(mask, 64);
3351 bitmap_from_u64(mask, reg_mask);
3352 for_each_set_bit(i, mask, 32) {
3353 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3361 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3362 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3364 DECLARE_BITMAP(mask, 64);
3370 bitmap_from_u64(mask, stack_mask);
3371 for_each_set_bit(i, mask, 64) {
3372 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3381 /* For given verifier state backtrack_insn() is called from the last insn to
3382 * the first insn. Its purpose is to compute a bitmask of registers and
3383 * stack slots that needs precision in the parent verifier state.
3385 * @idx is an index of the instruction we are currently processing;
3386 * @subseq_idx is an index of the subsequent instruction that:
3387 * - *would be* executed next, if jump history is viewed in forward order;
3388 * - *was* processed previously during backtracking.
3390 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3391 struct backtrack_state *bt)
3393 const struct bpf_insn_cbs cbs = {
3394 .cb_call = disasm_kfunc_name,
3395 .cb_print = verbose,
3396 .private_data = env,
3398 struct bpf_insn *insn = env->prog->insnsi + idx;
3399 u8 class = BPF_CLASS(insn->code);
3400 u8 opcode = BPF_OP(insn->code);
3401 u8 mode = BPF_MODE(insn->code);
3402 u32 dreg = insn->dst_reg;
3403 u32 sreg = insn->src_reg;
3406 if (insn->code == 0)
3408 if (env->log.level & BPF_LOG_LEVEL2) {
3409 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3410 verbose(env, "mark_precise: frame%d: regs=%s ",
3411 bt->frame, env->tmp_str_buf);
3412 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3413 verbose(env, "stack=%s before ", env->tmp_str_buf);
3414 verbose(env, "%d: ", idx);
3415 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3418 if (class == BPF_ALU || class == BPF_ALU64) {
3419 if (!bt_is_reg_set(bt, dreg))
3421 if (opcode == BPF_MOV) {
3422 if (BPF_SRC(insn->code) == BPF_X) {
3424 * dreg needs precision after this insn
3425 * sreg needs precision before this insn
3427 bt_clear_reg(bt, dreg);
3428 bt_set_reg(bt, sreg);
3431 * dreg needs precision after this insn.
3432 * Corresponding register is already marked
3433 * as precise=true in this verifier state.
3434 * No further markings in parent are necessary
3436 bt_clear_reg(bt, dreg);
3439 if (BPF_SRC(insn->code) == BPF_X) {
3441 * both dreg and sreg need precision
3444 bt_set_reg(bt, sreg);
3446 * dreg still needs precision before this insn
3449 } else if (class == BPF_LDX) {
3450 if (!bt_is_reg_set(bt, dreg))
3452 bt_clear_reg(bt, dreg);
3454 /* scalars can only be spilled into stack w/o losing precision.
3455 * Load from any other memory can be zero extended.
3456 * The desire to keep that precision is already indicated
3457 * by 'precise' mark in corresponding register of this state.
3458 * No further tracking necessary.
3460 if (insn->src_reg != BPF_REG_FP)
3463 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3464 * that [fp - off] slot contains scalar that needs to be
3465 * tracked with precision
3467 spi = (-insn->off - 1) / BPF_REG_SIZE;
3469 verbose(env, "BUG spi %d\n", spi);
3470 WARN_ONCE(1, "verifier backtracking bug");
3473 bt_set_slot(bt, spi);
3474 } else if (class == BPF_STX || class == BPF_ST) {
3475 if (bt_is_reg_set(bt, dreg))
3476 /* stx & st shouldn't be using _scalar_ dst_reg
3477 * to access memory. It means backtracking
3478 * encountered a case of pointer subtraction.
3481 /* scalars can only be spilled into stack */
3482 if (insn->dst_reg != BPF_REG_FP)
3484 spi = (-insn->off - 1) / BPF_REG_SIZE;
3486 verbose(env, "BUG spi %d\n", spi);
3487 WARN_ONCE(1, "verifier backtracking bug");
3490 if (!bt_is_slot_set(bt, spi))
3492 bt_clear_slot(bt, spi);
3493 if (class == BPF_STX)
3494 bt_set_reg(bt, sreg);
3495 } else if (class == BPF_JMP || class == BPF_JMP32) {
3496 if (bpf_pseudo_call(insn)) {
3497 int subprog_insn_idx, subprog;
3499 subprog_insn_idx = idx + insn->imm + 1;
3500 subprog = find_subprog(env, subprog_insn_idx);
3504 if (subprog_is_global(env, subprog)) {
3505 /* check that jump history doesn't have any
3506 * extra instructions from subprog; the next
3507 * instruction after call to global subprog
3508 * should be literally next instruction in
3511 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3512 /* r1-r5 are invalidated after subprog call,
3513 * so for global func call it shouldn't be set
3516 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3517 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3518 WARN_ONCE(1, "verifier backtracking bug");
3521 /* global subprog always sets R0 */
3522 bt_clear_reg(bt, BPF_REG_0);
3525 /* static subprog call instruction, which
3526 * means that we are exiting current subprog,
3527 * so only r1-r5 could be still requested as
3528 * precise, r0 and r6-r10 or any stack slot in
3529 * the current frame should be zero by now
3531 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3532 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3533 WARN_ONCE(1, "verifier backtracking bug");
3536 /* we don't track register spills perfectly,
3537 * so fallback to force-precise instead of failing */
3538 if (bt_stack_mask(bt) != 0)
3540 /* propagate r1-r5 to the caller */
3541 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3542 if (bt_is_reg_set(bt, i)) {
3543 bt_clear_reg(bt, i);
3544 bt_set_frame_reg(bt, bt->frame - 1, i);
3547 if (bt_subprog_exit(bt))
3551 } else if ((bpf_helper_call(insn) &&
3552 is_callback_calling_function(insn->imm) &&
3553 !is_async_callback_calling_function(insn->imm)) ||
3554 (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3555 /* callback-calling helper or kfunc call, which means
3556 * we are exiting from subprog, but unlike the subprog
3557 * call handling above, we shouldn't propagate
3558 * precision of r1-r5 (if any requested), as they are
3559 * not actually arguments passed directly to callback
3562 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3563 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3564 WARN_ONCE(1, "verifier backtracking bug");
3567 if (bt_stack_mask(bt) != 0)
3569 /* clear r1-r5 in callback subprog's mask */
3570 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3571 bt_clear_reg(bt, i);
3572 if (bt_subprog_exit(bt))
3575 } else if (opcode == BPF_CALL) {
3576 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3577 * catch this error later. Make backtracking conservative
3580 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3582 /* regular helper call sets R0 */
3583 bt_clear_reg(bt, BPF_REG_0);
3584 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3585 /* if backtracing was looking for registers R1-R5
3586 * they should have been found already.
3588 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3589 WARN_ONCE(1, "verifier backtracking bug");
3592 } else if (opcode == BPF_EXIT) {
3595 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3596 /* if backtracing was looking for registers R1-R5
3597 * they should have been found already.
3599 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3600 WARN_ONCE(1, "verifier backtracking bug");
3604 /* BPF_EXIT in subprog or callback always returns
3605 * right after the call instruction, so by checking
3606 * whether the instruction at subseq_idx-1 is subprog
3607 * call or not we can distinguish actual exit from
3608 * *subprog* from exit from *callback*. In the former
3609 * case, we need to propagate r0 precision, if
3610 * necessary. In the former we never do that.
3612 r0_precise = subseq_idx - 1 >= 0 &&
3613 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3614 bt_is_reg_set(bt, BPF_REG_0);
3616 bt_clear_reg(bt, BPF_REG_0);
3617 if (bt_subprog_enter(bt))
3621 bt_set_reg(bt, BPF_REG_0);
3622 /* r6-r9 and stack slots will stay set in caller frame
3623 * bitmasks until we return back from callee(s)
3626 } else if (BPF_SRC(insn->code) == BPF_X) {
3627 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3630 * Both dreg and sreg need precision before
3631 * this insn. If only sreg was marked precise
3632 * before it would be equally necessary to
3633 * propagate it to dreg.
3635 bt_set_reg(bt, dreg);
3636 bt_set_reg(bt, sreg);
3637 /* else dreg <cond> K
3638 * Only dreg still needs precision before
3639 * this insn, so for the K-based conditional
3640 * there is nothing new to be marked.
3643 } else if (class == BPF_LD) {
3644 if (!bt_is_reg_set(bt, dreg))
3646 bt_clear_reg(bt, dreg);
3647 /* It's ld_imm64 or ld_abs or ld_ind.
3648 * For ld_imm64 no further tracking of precision
3649 * into parent is necessary
3651 if (mode == BPF_IND || mode == BPF_ABS)
3652 /* to be analyzed */
3658 /* the scalar precision tracking algorithm:
3659 * . at the start all registers have precise=false.
3660 * . scalar ranges are tracked as normal through alu and jmp insns.
3661 * . once precise value of the scalar register is used in:
3662 * . ptr + scalar alu
3663 * . if (scalar cond K|scalar)
3664 * . helper_call(.., scalar, ...) where ARG_CONST is expected
3665 * backtrack through the verifier states and mark all registers and
3666 * stack slots with spilled constants that these scalar regisers
3667 * should be precise.
3668 * . during state pruning two registers (or spilled stack slots)
3669 * are equivalent if both are not precise.
3671 * Note the verifier cannot simply walk register parentage chain,
3672 * since many different registers and stack slots could have been
3673 * used to compute single precise scalar.
3675 * The approach of starting with precise=true for all registers and then
3676 * backtrack to mark a register as not precise when the verifier detects
3677 * that program doesn't care about specific value (e.g., when helper
3678 * takes register as ARG_ANYTHING parameter) is not safe.
3680 * It's ok to walk single parentage chain of the verifier states.
3681 * It's possible that this backtracking will go all the way till 1st insn.
3682 * All other branches will be explored for needing precision later.
3684 * The backtracking needs to deal with cases like:
3685 * 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)
3688 * if r5 > 0x79f goto pc+7
3689 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3692 * call bpf_perf_event_output#25
3693 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3697 * call foo // uses callee's r6 inside to compute r0
3701 * to track above reg_mask/stack_mask needs to be independent for each frame.
3703 * Also if parent's curframe > frame where backtracking started,
3704 * the verifier need to mark registers in both frames, otherwise callees
3705 * may incorrectly prune callers. This is similar to
3706 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3708 * For now backtracking falls back into conservative marking.
3710 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3711 struct bpf_verifier_state *st)
3713 struct bpf_func_state *func;
3714 struct bpf_reg_state *reg;
3717 if (env->log.level & BPF_LOG_LEVEL2) {
3718 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3722 /* big hammer: mark all scalars precise in this path.
3723 * pop_stack may still get !precise scalars.
3724 * We also skip current state and go straight to first parent state,
3725 * because precision markings in current non-checkpointed state are
3726 * not needed. See why in the comment in __mark_chain_precision below.
3728 for (st = st->parent; st; st = st->parent) {
3729 for (i = 0; i <= st->curframe; i++) {
3730 func = st->frame[i];
3731 for (j = 0; j < BPF_REG_FP; j++) {
3732 reg = &func->regs[j];
3733 if (reg->type != SCALAR_VALUE || reg->precise)
3735 reg->precise = true;
3736 if (env->log.level & BPF_LOG_LEVEL2) {
3737 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3741 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3742 if (!is_spilled_reg(&func->stack[j]))
3744 reg = &func->stack[j].spilled_ptr;
3745 if (reg->type != SCALAR_VALUE || reg->precise)
3747 reg->precise = true;
3748 if (env->log.level & BPF_LOG_LEVEL2) {
3749 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3757 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3759 struct bpf_func_state *func;
3760 struct bpf_reg_state *reg;
3763 for (i = 0; i <= st->curframe; i++) {
3764 func = st->frame[i];
3765 for (j = 0; j < BPF_REG_FP; j++) {
3766 reg = &func->regs[j];
3767 if (reg->type != SCALAR_VALUE)
3769 reg->precise = false;
3771 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3772 if (!is_spilled_reg(&func->stack[j]))
3774 reg = &func->stack[j].spilled_ptr;
3775 if (reg->type != SCALAR_VALUE)
3777 reg->precise = false;
3782 static bool idset_contains(struct bpf_idset *s, u32 id)
3786 for (i = 0; i < s->count; ++i)
3787 if (s->ids[i] == id)
3793 static int idset_push(struct bpf_idset *s, u32 id)
3795 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3797 s->ids[s->count++] = id;
3801 static void idset_reset(struct bpf_idset *s)
3806 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3807 * Mark all registers with these IDs as precise.
3809 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3811 struct bpf_idset *precise_ids = &env->idset_scratch;
3812 struct backtrack_state *bt = &env->bt;
3813 struct bpf_func_state *func;
3814 struct bpf_reg_state *reg;
3815 DECLARE_BITMAP(mask, 64);
3818 idset_reset(precise_ids);
3820 for (fr = bt->frame; fr >= 0; fr--) {
3821 func = st->frame[fr];
3823 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3824 for_each_set_bit(i, mask, 32) {
3825 reg = &func->regs[i];
3826 if (!reg->id || reg->type != SCALAR_VALUE)
3828 if (idset_push(precise_ids, reg->id))
3832 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3833 for_each_set_bit(i, mask, 64) {
3834 if (i >= func->allocated_stack / BPF_REG_SIZE)
3836 if (!is_spilled_scalar_reg(&func->stack[i]))
3838 reg = &func->stack[i].spilled_ptr;
3841 if (idset_push(precise_ids, reg->id))
3846 for (fr = 0; fr <= st->curframe; ++fr) {
3847 func = st->frame[fr];
3849 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
3850 reg = &func->regs[i];
3853 if (!idset_contains(precise_ids, reg->id))
3855 bt_set_frame_reg(bt, fr, i);
3857 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
3858 if (!is_spilled_scalar_reg(&func->stack[i]))
3860 reg = &func->stack[i].spilled_ptr;
3863 if (!idset_contains(precise_ids, reg->id))
3865 bt_set_frame_slot(bt, fr, i);
3873 * __mark_chain_precision() backtracks BPF program instruction sequence and
3874 * chain of verifier states making sure that register *regno* (if regno >= 0)
3875 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3876 * SCALARS, as well as any other registers and slots that contribute to
3877 * a tracked state of given registers/stack slots, depending on specific BPF
3878 * assembly instructions (see backtrack_insns() for exact instruction handling
3879 * logic). This backtracking relies on recorded jmp_history and is able to
3880 * traverse entire chain of parent states. This process ends only when all the
3881 * necessary registers/slots and their transitive dependencies are marked as
3884 * One important and subtle aspect is that precise marks *do not matter* in
3885 * the currently verified state (current state). It is important to understand
3886 * why this is the case.
3888 * First, note that current state is the state that is not yet "checkpointed",
3889 * i.e., it is not yet put into env->explored_states, and it has no children
3890 * states as well. It's ephemeral, and can end up either a) being discarded if
3891 * compatible explored state is found at some point or BPF_EXIT instruction is
3892 * reached or b) checkpointed and put into env->explored_states, branching out
3893 * into one or more children states.
3895 * In the former case, precise markings in current state are completely
3896 * ignored by state comparison code (see regsafe() for details). Only
3897 * checkpointed ("old") state precise markings are important, and if old
3898 * state's register/slot is precise, regsafe() assumes current state's
3899 * register/slot as precise and checks value ranges exactly and precisely. If
3900 * states turn out to be compatible, current state's necessary precise
3901 * markings and any required parent states' precise markings are enforced
3902 * after the fact with propagate_precision() logic, after the fact. But it's
3903 * important to realize that in this case, even after marking current state
3904 * registers/slots as precise, we immediately discard current state. So what
3905 * actually matters is any of the precise markings propagated into current
3906 * state's parent states, which are always checkpointed (due to b) case above).
3907 * As such, for scenario a) it doesn't matter if current state has precise
3908 * markings set or not.
3910 * Now, for the scenario b), checkpointing and forking into child(ren)
3911 * state(s). Note that before current state gets to checkpointing step, any
3912 * processed instruction always assumes precise SCALAR register/slot
3913 * knowledge: if precise value or range is useful to prune jump branch, BPF
3914 * verifier takes this opportunity enthusiastically. Similarly, when
3915 * register's value is used to calculate offset or memory address, exact
3916 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3917 * what we mentioned above about state comparison ignoring precise markings
3918 * during state comparison, BPF verifier ignores and also assumes precise
3919 * markings *at will* during instruction verification process. But as verifier
3920 * assumes precision, it also propagates any precision dependencies across
3921 * parent states, which are not yet finalized, so can be further restricted
3922 * based on new knowledge gained from restrictions enforced by their children
3923 * states. This is so that once those parent states are finalized, i.e., when
3924 * they have no more active children state, state comparison logic in
3925 * is_state_visited() would enforce strict and precise SCALAR ranges, if
3926 * required for correctness.
3928 * To build a bit more intuition, note also that once a state is checkpointed,
3929 * the path we took to get to that state is not important. This is crucial
3930 * property for state pruning. When state is checkpointed and finalized at
3931 * some instruction index, it can be correctly and safely used to "short
3932 * circuit" any *compatible* state that reaches exactly the same instruction
3933 * index. I.e., if we jumped to that instruction from a completely different
3934 * code path than original finalized state was derived from, it doesn't
3935 * matter, current state can be discarded because from that instruction
3936 * forward having a compatible state will ensure we will safely reach the
3937 * exit. States describe preconditions for further exploration, but completely
3938 * forget the history of how we got here.
3940 * This also means that even if we needed precise SCALAR range to get to
3941 * finalized state, but from that point forward *that same* SCALAR register is
3942 * never used in a precise context (i.e., it's precise value is not needed for
3943 * correctness), it's correct and safe to mark such register as "imprecise"
3944 * (i.e., precise marking set to false). This is what we rely on when we do
3945 * not set precise marking in current state. If no child state requires
3946 * precision for any given SCALAR register, it's safe to dictate that it can
3947 * be imprecise. If any child state does require this register to be precise,
3948 * we'll mark it precise later retroactively during precise markings
3949 * propagation from child state to parent states.
3951 * Skipping precise marking setting in current state is a mild version of
3952 * relying on the above observation. But we can utilize this property even
3953 * more aggressively by proactively forgetting any precise marking in the
3954 * current state (which we inherited from the parent state), right before we
3955 * checkpoint it and branch off into new child state. This is done by
3956 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3957 * finalized states which help in short circuiting more future states.
3959 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
3961 struct backtrack_state *bt = &env->bt;
3962 struct bpf_verifier_state *st = env->cur_state;
3963 int first_idx = st->first_insn_idx;
3964 int last_idx = env->insn_idx;
3965 int subseq_idx = -1;
3966 struct bpf_func_state *func;
3967 struct bpf_reg_state *reg;
3968 bool skip_first = true;
3971 if (!env->bpf_capable)
3974 /* set frame number from which we are starting to backtrack */
3975 bt_init(bt, env->cur_state->curframe);
3977 /* Do sanity checks against current state of register and/or stack
3978 * slot, but don't set precise flag in current state, as precision
3979 * tracking in the current state is unnecessary.
3981 func = st->frame[bt->frame];
3983 reg = &func->regs[regno];
3984 if (reg->type != SCALAR_VALUE) {
3985 WARN_ONCE(1, "backtracing misuse");
3988 bt_set_reg(bt, regno);
3995 DECLARE_BITMAP(mask, 64);
3996 u32 history = st->jmp_history_cnt;
3998 if (env->log.level & BPF_LOG_LEVEL2) {
3999 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4000 bt->frame, last_idx, first_idx, subseq_idx);
4003 /* If some register with scalar ID is marked as precise,
4004 * make sure that all registers sharing this ID are also precise.
4005 * This is needed to estimate effect of find_equal_scalars().
4006 * Do this at the last instruction of each state,
4007 * bpf_reg_state::id fields are valid for these instructions.
4009 * Allows to track precision in situation like below:
4011 * r2 = unknown value
4015 * r1 = r2 // r1 and r2 now share the same ID
4017 * --- state #1 {r1.id = A, r2.id = A} ---
4019 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4021 * --- state #2 {r1.id = A, r2.id = A} ---
4023 * r3 += r1 // need to mark both r1 and r2
4025 if (mark_precise_scalar_ids(env, st))
4029 /* we are at the entry into subprog, which
4030 * is expected for global funcs, but only if
4031 * requested precise registers are R1-R5
4032 * (which are global func's input arguments)
4034 if (st->curframe == 0 &&
4035 st->frame[0]->subprogno > 0 &&
4036 st->frame[0]->callsite == BPF_MAIN_FUNC &&
4037 bt_stack_mask(bt) == 0 &&
4038 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4039 bitmap_from_u64(mask, bt_reg_mask(bt));
4040 for_each_set_bit(i, mask, 32) {
4041 reg = &st->frame[0]->regs[i];
4042 if (reg->type != SCALAR_VALUE) {
4043 bt_clear_reg(bt, i);
4046 reg->precise = true;
4051 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4052 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4053 WARN_ONCE(1, "verifier backtracking bug");
4057 for (i = last_idx;;) {
4062 err = backtrack_insn(env, i, subseq_idx, bt);
4064 if (err == -ENOTSUPP) {
4065 mark_all_scalars_precise(env, env->cur_state);
4072 /* Found assignment(s) into tracked register in this state.
4073 * Since this state is already marked, just return.
4074 * Nothing to be tracked further in the parent state.
4080 i = get_prev_insn_idx(st, i, &history);
4081 if (i >= env->prog->len) {
4082 /* This can happen if backtracking reached insn 0
4083 * and there are still reg_mask or stack_mask
4085 * It means the backtracking missed the spot where
4086 * particular register was initialized with a constant.
4088 verbose(env, "BUG backtracking idx %d\n", i);
4089 WARN_ONCE(1, "verifier backtracking bug");
4097 for (fr = bt->frame; fr >= 0; fr--) {
4098 func = st->frame[fr];
4099 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4100 for_each_set_bit(i, mask, 32) {
4101 reg = &func->regs[i];
4102 if (reg->type != SCALAR_VALUE) {
4103 bt_clear_frame_reg(bt, fr, i);
4107 bt_clear_frame_reg(bt, fr, i);
4109 reg->precise = true;
4112 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4113 for_each_set_bit(i, mask, 64) {
4114 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4115 /* the sequence of instructions:
4117 * 3: (7b) *(u64 *)(r3 -8) = r0
4118 * 4: (79) r4 = *(u64 *)(r10 -8)
4119 * doesn't contain jmps. It's backtracked
4120 * as a single block.
4121 * During backtracking insn 3 is not recognized as
4122 * stack access, so at the end of backtracking
4123 * stack slot fp-8 is still marked in stack_mask.
4124 * However the parent state may not have accessed
4125 * fp-8 and it's "unallocated" stack space.
4126 * In such case fallback to conservative.
4128 mark_all_scalars_precise(env, env->cur_state);
4133 if (!is_spilled_scalar_reg(&func->stack[i])) {
4134 bt_clear_frame_slot(bt, fr, i);
4137 reg = &func->stack[i].spilled_ptr;
4139 bt_clear_frame_slot(bt, fr, i);
4141 reg->precise = true;
4143 if (env->log.level & BPF_LOG_LEVEL2) {
4144 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4145 bt_frame_reg_mask(bt, fr));
4146 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4147 fr, env->tmp_str_buf);
4148 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4149 bt_frame_stack_mask(bt, fr));
4150 verbose(env, "stack=%s: ", env->tmp_str_buf);
4151 print_verifier_state(env, func, true);
4158 subseq_idx = first_idx;
4159 last_idx = st->last_insn_idx;
4160 first_idx = st->first_insn_idx;
4163 /* if we still have requested precise regs or slots, we missed
4164 * something (e.g., stack access through non-r10 register), so
4165 * fallback to marking all precise
4167 if (!bt_empty(bt)) {
4168 mark_all_scalars_precise(env, env->cur_state);
4175 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4177 return __mark_chain_precision(env, regno);
4180 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4181 * desired reg and stack masks across all relevant frames
4183 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4185 return __mark_chain_precision(env, -1);
4188 static bool is_spillable_regtype(enum bpf_reg_type type)
4190 switch (base_type(type)) {
4191 case PTR_TO_MAP_VALUE:
4195 case PTR_TO_PACKET_META:
4196 case PTR_TO_PACKET_END:
4197 case PTR_TO_FLOW_KEYS:
4198 case CONST_PTR_TO_MAP:
4200 case PTR_TO_SOCK_COMMON:
4201 case PTR_TO_TCP_SOCK:
4202 case PTR_TO_XDP_SOCK:
4207 case PTR_TO_MAP_KEY:
4214 /* Does this register contain a constant zero? */
4215 static bool register_is_null(struct bpf_reg_state *reg)
4217 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4220 static bool register_is_const(struct bpf_reg_state *reg)
4222 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4225 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4227 return tnum_is_unknown(reg->var_off) &&
4228 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4229 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4230 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4231 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4234 static bool register_is_bounded(struct bpf_reg_state *reg)
4236 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4239 static bool __is_pointer_value(bool allow_ptr_leaks,
4240 const struct bpf_reg_state *reg)
4242 if (allow_ptr_leaks)
4245 return reg->type != SCALAR_VALUE;
4248 /* Copy src state preserving dst->parent and dst->live fields */
4249 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4251 struct bpf_reg_state *parent = dst->parent;
4252 enum bpf_reg_liveness live = dst->live;
4255 dst->parent = parent;
4259 static void save_register_state(struct bpf_func_state *state,
4260 int spi, struct bpf_reg_state *reg,
4265 copy_register_state(&state->stack[spi].spilled_ptr, reg);
4266 if (size == BPF_REG_SIZE)
4267 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4269 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4270 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4272 /* size < 8 bytes spill */
4274 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4277 static bool is_bpf_st_mem(struct bpf_insn *insn)
4279 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4282 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4283 * stack boundary and alignment are checked in check_mem_access()
4285 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4286 /* stack frame we're writing to */
4287 struct bpf_func_state *state,
4288 int off, int size, int value_regno,
4291 struct bpf_func_state *cur; /* state of the current function */
4292 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4293 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4294 struct bpf_reg_state *reg = NULL;
4295 u32 dst_reg = insn->dst_reg;
4297 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4300 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4301 * so it's aligned access and [off, off + size) are within stack limits
4303 if (!env->allow_ptr_leaks &&
4304 state->stack[spi].slot_type[0] == STACK_SPILL &&
4305 size != BPF_REG_SIZE) {
4306 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4310 cur = env->cur_state->frame[env->cur_state->curframe];
4311 if (value_regno >= 0)
4312 reg = &cur->regs[value_regno];
4313 if (!env->bypass_spec_v4) {
4314 bool sanitize = reg && is_spillable_regtype(reg->type);
4316 for (i = 0; i < size; i++) {
4317 u8 type = state->stack[spi].slot_type[i];
4319 if (type != STACK_MISC && type != STACK_ZERO) {
4326 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4329 err = destroy_if_dynptr_stack_slot(env, state, spi);
4333 mark_stack_slot_scratched(env, spi);
4334 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4335 !register_is_null(reg) && env->bpf_capable) {
4336 if (dst_reg != BPF_REG_FP) {
4337 /* The backtracking logic can only recognize explicit
4338 * stack slot address like [fp - 8]. Other spill of
4339 * scalar via different register has to be conservative.
4340 * Backtrack from here and mark all registers as precise
4341 * that contributed into 'reg' being a constant.
4343 err = mark_chain_precision(env, value_regno);
4347 save_register_state(state, spi, reg, size);
4348 /* Break the relation on a narrowing spill. */
4349 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4350 state->stack[spi].spilled_ptr.id = 0;
4351 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4352 insn->imm != 0 && env->bpf_capable) {
4353 struct bpf_reg_state fake_reg = {};
4355 __mark_reg_known(&fake_reg, (u32)insn->imm);
4356 fake_reg.type = SCALAR_VALUE;
4357 save_register_state(state, spi, &fake_reg, size);
4358 } else if (reg && is_spillable_regtype(reg->type)) {
4359 /* register containing pointer is being spilled into stack */
4360 if (size != BPF_REG_SIZE) {
4361 verbose_linfo(env, insn_idx, "; ");
4362 verbose(env, "invalid size of register spill\n");
4365 if (state != cur && reg->type == PTR_TO_STACK) {
4366 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4369 save_register_state(state, spi, reg, size);
4371 u8 type = STACK_MISC;
4373 /* regular write of data into stack destroys any spilled ptr */
4374 state->stack[spi].spilled_ptr.type = NOT_INIT;
4375 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4376 if (is_stack_slot_special(&state->stack[spi]))
4377 for (i = 0; i < BPF_REG_SIZE; i++)
4378 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4380 /* only mark the slot as written if all 8 bytes were written
4381 * otherwise read propagation may incorrectly stop too soon
4382 * when stack slots are partially written.
4383 * This heuristic means that read propagation will be
4384 * conservative, since it will add reg_live_read marks
4385 * to stack slots all the way to first state when programs
4386 * writes+reads less than 8 bytes
4388 if (size == BPF_REG_SIZE)
4389 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4391 /* when we zero initialize stack slots mark them as such */
4392 if ((reg && register_is_null(reg)) ||
4393 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4394 /* backtracking doesn't work for STACK_ZERO yet. */
4395 err = mark_chain_precision(env, value_regno);
4401 /* Mark slots affected by this stack write. */
4402 for (i = 0; i < size; i++)
4403 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4409 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4410 * known to contain a variable offset.
4411 * This function checks whether the write is permitted and conservatively
4412 * tracks the effects of the write, considering that each stack slot in the
4413 * dynamic range is potentially written to.
4415 * 'off' includes 'regno->off'.
4416 * 'value_regno' can be -1, meaning that an unknown value is being written to
4419 * Spilled pointers in range are not marked as written because we don't know
4420 * what's going to be actually written. This means that read propagation for
4421 * future reads cannot be terminated by this write.
4423 * For privileged programs, uninitialized stack slots are considered
4424 * initialized by this write (even though we don't know exactly what offsets
4425 * are going to be written to). The idea is that we don't want the verifier to
4426 * reject future reads that access slots written to through variable offsets.
4428 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4429 /* func where register points to */
4430 struct bpf_func_state *state,
4431 int ptr_regno, int off, int size,
4432 int value_regno, int insn_idx)
4434 struct bpf_func_state *cur; /* state of the current function */
4435 int min_off, max_off;
4437 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4438 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4439 bool writing_zero = false;
4440 /* set if the fact that we're writing a zero is used to let any
4441 * stack slots remain STACK_ZERO
4443 bool zero_used = false;
4445 cur = env->cur_state->frame[env->cur_state->curframe];
4446 ptr_reg = &cur->regs[ptr_regno];
4447 min_off = ptr_reg->smin_value + off;
4448 max_off = ptr_reg->smax_value + off + size;
4449 if (value_regno >= 0)
4450 value_reg = &cur->regs[value_regno];
4451 if ((value_reg && register_is_null(value_reg)) ||
4452 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4453 writing_zero = true;
4455 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4459 for (i = min_off; i < max_off; i++) {
4463 err = destroy_if_dynptr_stack_slot(env, state, spi);
4468 /* Variable offset writes destroy any spilled pointers in range. */
4469 for (i = min_off; i < max_off; i++) {
4470 u8 new_type, *stype;
4474 spi = slot / BPF_REG_SIZE;
4475 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4476 mark_stack_slot_scratched(env, spi);
4478 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4479 /* Reject the write if range we may write to has not
4480 * been initialized beforehand. If we didn't reject
4481 * here, the ptr status would be erased below (even
4482 * though not all slots are actually overwritten),
4483 * possibly opening the door to leaks.
4485 * We do however catch STACK_INVALID case below, and
4486 * only allow reading possibly uninitialized memory
4487 * later for CAP_PERFMON, as the write may not happen to
4490 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4495 /* Erase all spilled pointers. */
4496 state->stack[spi].spilled_ptr.type = NOT_INIT;
4498 /* Update the slot type. */
4499 new_type = STACK_MISC;
4500 if (writing_zero && *stype == STACK_ZERO) {
4501 new_type = STACK_ZERO;
4504 /* If the slot is STACK_INVALID, we check whether it's OK to
4505 * pretend that it will be initialized by this write. The slot
4506 * might not actually be written to, and so if we mark it as
4507 * initialized future reads might leak uninitialized memory.
4508 * For privileged programs, we will accept such reads to slots
4509 * that may or may not be written because, if we're reject
4510 * them, the error would be too confusing.
4512 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4513 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4520 /* backtracking doesn't work for STACK_ZERO yet. */
4521 err = mark_chain_precision(env, value_regno);
4528 /* When register 'dst_regno' is assigned some values from stack[min_off,
4529 * max_off), we set the register's type according to the types of the
4530 * respective stack slots. If all the stack values are known to be zeros, then
4531 * so is the destination reg. Otherwise, the register is considered to be
4532 * SCALAR. This function does not deal with register filling; the caller must
4533 * ensure that all spilled registers in the stack range have been marked as
4536 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4537 /* func where src register points to */
4538 struct bpf_func_state *ptr_state,
4539 int min_off, int max_off, int dst_regno)
4541 struct bpf_verifier_state *vstate = env->cur_state;
4542 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4547 for (i = min_off; i < max_off; i++) {
4549 spi = slot / BPF_REG_SIZE;
4550 mark_stack_slot_scratched(env, spi);
4551 stype = ptr_state->stack[spi].slot_type;
4552 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4556 if (zeros == max_off - min_off) {
4557 /* any access_size read into register is zero extended,
4558 * so the whole register == const_zero
4560 __mark_reg_const_zero(&state->regs[dst_regno]);
4561 /* backtracking doesn't support STACK_ZERO yet,
4562 * so mark it precise here, so that later
4563 * backtracking can stop here.
4564 * Backtracking may not need this if this register
4565 * doesn't participate in pointer adjustment.
4566 * Forward propagation of precise flag is not
4567 * necessary either. This mark is only to stop
4568 * backtracking. Any register that contributed
4569 * to const 0 was marked precise before spill.
4571 state->regs[dst_regno].precise = true;
4573 /* have read misc data from the stack */
4574 mark_reg_unknown(env, state->regs, dst_regno);
4576 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4579 /* Read the stack at 'off' and put the results into the register indicated by
4580 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4583 * 'dst_regno' can be -1, meaning that the read value is not going to a
4586 * The access is assumed to be within the current stack bounds.
4588 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4589 /* func where src register points to */
4590 struct bpf_func_state *reg_state,
4591 int off, int size, int dst_regno)
4593 struct bpf_verifier_state *vstate = env->cur_state;
4594 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4595 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4596 struct bpf_reg_state *reg;
4599 stype = reg_state->stack[spi].slot_type;
4600 reg = ®_state->stack[spi].spilled_ptr;
4602 mark_stack_slot_scratched(env, spi);
4604 if (is_spilled_reg(®_state->stack[spi])) {
4607 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4610 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4611 if (reg->type != SCALAR_VALUE) {
4612 verbose_linfo(env, env->insn_idx, "; ");
4613 verbose(env, "invalid size of register fill\n");
4617 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4621 if (!(off % BPF_REG_SIZE) && size == spill_size) {
4622 /* The earlier check_reg_arg() has decided the
4623 * subreg_def for this insn. Save it first.
4625 s32 subreg_def = state->regs[dst_regno].subreg_def;
4627 copy_register_state(&state->regs[dst_regno], reg);
4628 state->regs[dst_regno].subreg_def = subreg_def;
4630 for (i = 0; i < size; i++) {
4631 type = stype[(slot - i) % BPF_REG_SIZE];
4632 if (type == STACK_SPILL)
4634 if (type == STACK_MISC)
4636 if (type == STACK_INVALID && env->allow_uninit_stack)
4638 verbose(env, "invalid read from stack off %d+%d size %d\n",
4642 mark_reg_unknown(env, state->regs, dst_regno);
4644 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4648 if (dst_regno >= 0) {
4649 /* restore register state from stack */
4650 copy_register_state(&state->regs[dst_regno], reg);
4651 /* mark reg as written since spilled pointer state likely
4652 * has its liveness marks cleared by is_state_visited()
4653 * which resets stack/reg liveness for state transitions
4655 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4656 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4657 /* If dst_regno==-1, the caller is asking us whether
4658 * it is acceptable to use this value as a SCALAR_VALUE
4660 * We must not allow unprivileged callers to do that
4661 * with spilled pointers.
4663 verbose(env, "leaking pointer from stack off %d\n",
4667 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4669 for (i = 0; i < size; i++) {
4670 type = stype[(slot - i) % BPF_REG_SIZE];
4671 if (type == STACK_MISC)
4673 if (type == STACK_ZERO)
4675 if (type == STACK_INVALID && env->allow_uninit_stack)
4677 verbose(env, "invalid read from stack off %d+%d size %d\n",
4681 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4683 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4688 enum bpf_access_src {
4689 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
4690 ACCESS_HELPER = 2, /* the access is performed by a helper */
4693 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4694 int regno, int off, int access_size,
4695 bool zero_size_allowed,
4696 enum bpf_access_src type,
4697 struct bpf_call_arg_meta *meta);
4699 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4701 return cur_regs(env) + regno;
4704 /* Read the stack at 'ptr_regno + off' and put the result into the register
4706 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4707 * but not its variable offset.
4708 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4710 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4711 * filling registers (i.e. reads of spilled register cannot be detected when
4712 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4713 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4714 * offset; for a fixed offset check_stack_read_fixed_off should be used
4717 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4718 int ptr_regno, int off, int size, int dst_regno)
4720 /* The state of the source register. */
4721 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4722 struct bpf_func_state *ptr_state = func(env, reg);
4724 int min_off, max_off;
4726 /* Note that we pass a NULL meta, so raw access will not be permitted.
4728 err = check_stack_range_initialized(env, ptr_regno, off, size,
4729 false, ACCESS_DIRECT, NULL);
4733 min_off = reg->smin_value + off;
4734 max_off = reg->smax_value + off;
4735 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4739 /* check_stack_read dispatches to check_stack_read_fixed_off or
4740 * check_stack_read_var_off.
4742 * The caller must ensure that the offset falls within the allocated stack
4745 * 'dst_regno' is a register which will receive the value from the stack. It
4746 * can be -1, meaning that the read value is not going to a register.
4748 static int check_stack_read(struct bpf_verifier_env *env,
4749 int ptr_regno, int off, int size,
4752 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4753 struct bpf_func_state *state = func(env, reg);
4755 /* Some accesses are only permitted with a static offset. */
4756 bool var_off = !tnum_is_const(reg->var_off);
4758 /* The offset is required to be static when reads don't go to a
4759 * register, in order to not leak pointers (see
4760 * check_stack_read_fixed_off).
4762 if (dst_regno < 0 && var_off) {
4765 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4766 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4770 /* Variable offset is prohibited for unprivileged mode for simplicity
4771 * since it requires corresponding support in Spectre masking for stack
4772 * ALU. See also retrieve_ptr_limit(). The check in
4773 * check_stack_access_for_ptr_arithmetic() called by
4774 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4775 * with variable offsets, therefore no check is required here. Further,
4776 * just checking it here would be insufficient as speculative stack
4777 * writes could still lead to unsafe speculative behaviour.
4780 off += reg->var_off.value;
4781 err = check_stack_read_fixed_off(env, state, off, size,
4784 /* Variable offset stack reads need more conservative handling
4785 * than fixed offset ones. Note that dst_regno >= 0 on this
4788 err = check_stack_read_var_off(env, ptr_regno, off, size,
4795 /* check_stack_write dispatches to check_stack_write_fixed_off or
4796 * check_stack_write_var_off.
4798 * 'ptr_regno' is the register used as a pointer into the stack.
4799 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4800 * 'value_regno' is the register whose value we're writing to the stack. It can
4801 * be -1, meaning that we're not writing from a register.
4803 * The caller must ensure that the offset falls within the maximum stack size.
4805 static int check_stack_write(struct bpf_verifier_env *env,
4806 int ptr_regno, int off, int size,
4807 int value_regno, int insn_idx)
4809 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4810 struct bpf_func_state *state = func(env, reg);
4813 if (tnum_is_const(reg->var_off)) {
4814 off += reg->var_off.value;
4815 err = check_stack_write_fixed_off(env, state, off, size,
4816 value_regno, insn_idx);
4818 /* Variable offset stack reads need more conservative handling
4819 * than fixed offset ones.
4821 err = check_stack_write_var_off(env, state,
4822 ptr_regno, off, size,
4823 value_regno, insn_idx);
4828 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4829 int off, int size, enum bpf_access_type type)
4831 struct bpf_reg_state *regs = cur_regs(env);
4832 struct bpf_map *map = regs[regno].map_ptr;
4833 u32 cap = bpf_map_flags_to_cap(map);
4835 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4836 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4837 map->value_size, off, size);
4841 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4842 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4843 map->value_size, off, size);
4850 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4851 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4852 int off, int size, u32 mem_size,
4853 bool zero_size_allowed)
4855 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4856 struct bpf_reg_state *reg;
4858 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4861 reg = &cur_regs(env)[regno];
4862 switch (reg->type) {
4863 case PTR_TO_MAP_KEY:
4864 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4865 mem_size, off, size);
4867 case PTR_TO_MAP_VALUE:
4868 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4869 mem_size, off, size);
4872 case PTR_TO_PACKET_META:
4873 case PTR_TO_PACKET_END:
4874 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4875 off, size, regno, reg->id, off, mem_size);
4879 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4880 mem_size, off, size);
4886 /* check read/write into a memory region with possible variable offset */
4887 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4888 int off, int size, u32 mem_size,
4889 bool zero_size_allowed)
4891 struct bpf_verifier_state *vstate = env->cur_state;
4892 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4893 struct bpf_reg_state *reg = &state->regs[regno];
4896 /* We may have adjusted the register pointing to memory region, so we
4897 * need to try adding each of min_value and max_value to off
4898 * to make sure our theoretical access will be safe.
4900 * The minimum value is only important with signed
4901 * comparisons where we can't assume the floor of a
4902 * value is 0. If we are using signed variables for our
4903 * index'es we need to make sure that whatever we use
4904 * will have a set floor within our range.
4906 if (reg->smin_value < 0 &&
4907 (reg->smin_value == S64_MIN ||
4908 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4909 reg->smin_value + off < 0)) {
4910 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4914 err = __check_mem_access(env, regno, reg->smin_value + off, size,
4915 mem_size, zero_size_allowed);
4917 verbose(env, "R%d min value is outside of the allowed memory range\n",
4922 /* If we haven't set a max value then we need to bail since we can't be
4923 * sure we won't do bad things.
4924 * If reg->umax_value + off could overflow, treat that as unbounded too.
4926 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4927 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4931 err = __check_mem_access(env, regno, reg->umax_value + off, size,
4932 mem_size, zero_size_allowed);
4934 verbose(env, "R%d max value is outside of the allowed memory range\n",
4942 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4943 const struct bpf_reg_state *reg, int regno,
4946 /* Access to this pointer-typed register or passing it to a helper
4947 * is only allowed in its original, unmodified form.
4951 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4952 reg_type_str(env, reg->type), regno, reg->off);
4956 if (!fixed_off_ok && reg->off) {
4957 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4958 reg_type_str(env, reg->type), regno, reg->off);
4962 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4965 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4966 verbose(env, "variable %s access var_off=%s disallowed\n",
4967 reg_type_str(env, reg->type), tn_buf);
4974 int check_ptr_off_reg(struct bpf_verifier_env *env,
4975 const struct bpf_reg_state *reg, int regno)
4977 return __check_ptr_off_reg(env, reg, regno, false);
4980 static int map_kptr_match_type(struct bpf_verifier_env *env,
4981 struct btf_field *kptr_field,
4982 struct bpf_reg_state *reg, u32 regno)
4984 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4985 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4986 const char *reg_name = "";
4988 /* Only unreferenced case accepts untrusted pointers */
4989 if (kptr_field->type == BPF_KPTR_UNREF)
4990 perm_flags |= PTR_UNTRUSTED;
4992 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4995 if (!btf_is_kernel(reg->btf)) {
4996 verbose(env, "R%d must point to kernel BTF\n", regno);
4999 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5000 reg_name = btf_type_name(reg->btf, reg->btf_id);
5002 /* For ref_ptr case, release function check should ensure we get one
5003 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5004 * normal store of unreferenced kptr, we must ensure var_off is zero.
5005 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5006 * reg->off and reg->ref_obj_id are not needed here.
5008 if (__check_ptr_off_reg(env, reg, regno, true))
5011 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
5012 * we also need to take into account the reg->off.
5014 * We want to support cases like:
5022 * v = func(); // PTR_TO_BTF_ID
5023 * val->foo = v; // reg->off is zero, btf and btf_id match type
5024 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5025 * // first member type of struct after comparison fails
5026 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5029 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5030 * is zero. We must also ensure that btf_struct_ids_match does not walk
5031 * the struct to match type against first member of struct, i.e. reject
5032 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5033 * strict mode to true for type match.
5035 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5036 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5037 kptr_field->type == BPF_KPTR_REF))
5041 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5042 reg_type_str(env, reg->type), reg_name);
5043 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5044 if (kptr_field->type == BPF_KPTR_UNREF)
5045 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5052 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5053 * can dereference RCU protected pointers and result is PTR_TRUSTED.
5055 static bool in_rcu_cs(struct bpf_verifier_env *env)
5057 return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
5060 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5061 BTF_SET_START(rcu_protected_types)
5062 BTF_ID(struct, prog_test_ref_kfunc)
5063 BTF_ID(struct, cgroup)
5064 BTF_ID(struct, bpf_cpumask)
5065 BTF_ID(struct, task_struct)
5066 BTF_SET_END(rcu_protected_types)
5068 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5070 if (!btf_is_kernel(btf))
5072 return btf_id_set_contains(&rcu_protected_types, btf_id);
5075 static bool rcu_safe_kptr(const struct btf_field *field)
5077 const struct btf_field_kptr *kptr = &field->kptr;
5079 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5082 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5083 int value_regno, int insn_idx,
5084 struct btf_field *kptr_field)
5086 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5087 int class = BPF_CLASS(insn->code);
5088 struct bpf_reg_state *val_reg;
5090 /* Things we already checked for in check_map_access and caller:
5091 * - Reject cases where variable offset may touch kptr
5092 * - size of access (must be BPF_DW)
5093 * - tnum_is_const(reg->var_off)
5094 * - kptr_field->offset == off + reg->var_off.value
5096 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5097 if (BPF_MODE(insn->code) != BPF_MEM) {
5098 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5102 /* We only allow loading referenced kptr, since it will be marked as
5103 * untrusted, similar to unreferenced kptr.
5105 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5106 verbose(env, "store to referenced kptr disallowed\n");
5110 if (class == BPF_LDX) {
5111 val_reg = reg_state(env, value_regno);
5112 /* We can simply mark the value_regno receiving the pointer
5113 * value from map as PTR_TO_BTF_ID, with the correct type.
5115 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5116 kptr_field->kptr.btf_id,
5117 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5118 PTR_MAYBE_NULL | MEM_RCU :
5119 PTR_MAYBE_NULL | PTR_UNTRUSTED);
5120 /* For mark_ptr_or_null_reg */
5121 val_reg->id = ++env->id_gen;
5122 } else if (class == BPF_STX) {
5123 val_reg = reg_state(env, value_regno);
5124 if (!register_is_null(val_reg) &&
5125 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5127 } else if (class == BPF_ST) {
5129 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5130 kptr_field->offset);
5134 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5140 /* check read/write into a map element with possible variable offset */
5141 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5142 int off, int size, bool zero_size_allowed,
5143 enum bpf_access_src src)
5145 struct bpf_verifier_state *vstate = env->cur_state;
5146 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5147 struct bpf_reg_state *reg = &state->regs[regno];
5148 struct bpf_map *map = reg->map_ptr;
5149 struct btf_record *rec;
5152 err = check_mem_region_access(env, regno, off, size, map->value_size,
5157 if (IS_ERR_OR_NULL(map->record))
5160 for (i = 0; i < rec->cnt; i++) {
5161 struct btf_field *field = &rec->fields[i];
5162 u32 p = field->offset;
5164 /* If any part of a field can be touched by load/store, reject
5165 * this program. To check that [x1, x2) overlaps with [y1, y2),
5166 * it is sufficient to check x1 < y2 && y1 < x2.
5168 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5169 p < reg->umax_value + off + size) {
5170 switch (field->type) {
5171 case BPF_KPTR_UNREF:
5173 if (src != ACCESS_DIRECT) {
5174 verbose(env, "kptr cannot be accessed indirectly by helper\n");
5177 if (!tnum_is_const(reg->var_off)) {
5178 verbose(env, "kptr access cannot have variable offset\n");
5181 if (p != off + reg->var_off.value) {
5182 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5183 p, off + reg->var_off.value);
5186 if (size != bpf_size_to_bytes(BPF_DW)) {
5187 verbose(env, "kptr access size must be BPF_DW\n");
5192 verbose(env, "%s cannot be accessed directly by load/store\n",
5193 btf_field_type_name(field->type));
5201 #define MAX_PACKET_OFF 0xffff
5203 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5204 const struct bpf_call_arg_meta *meta,
5205 enum bpf_access_type t)
5207 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5209 switch (prog_type) {
5210 /* Program types only with direct read access go here! */
5211 case BPF_PROG_TYPE_LWT_IN:
5212 case BPF_PROG_TYPE_LWT_OUT:
5213 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5214 case BPF_PROG_TYPE_SK_REUSEPORT:
5215 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5216 case BPF_PROG_TYPE_CGROUP_SKB:
5221 /* Program types with direct read + write access go here! */
5222 case BPF_PROG_TYPE_SCHED_CLS:
5223 case BPF_PROG_TYPE_SCHED_ACT:
5224 case BPF_PROG_TYPE_XDP:
5225 case BPF_PROG_TYPE_LWT_XMIT:
5226 case BPF_PROG_TYPE_SK_SKB:
5227 case BPF_PROG_TYPE_SK_MSG:
5229 return meta->pkt_access;
5231 env->seen_direct_write = true;
5234 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5236 env->seen_direct_write = true;
5245 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5246 int size, bool zero_size_allowed)
5248 struct bpf_reg_state *regs = cur_regs(env);
5249 struct bpf_reg_state *reg = ®s[regno];
5252 /* We may have added a variable offset to the packet pointer; but any
5253 * reg->range we have comes after that. We are only checking the fixed
5257 /* We don't allow negative numbers, because we aren't tracking enough
5258 * detail to prove they're safe.
5260 if (reg->smin_value < 0) {
5261 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5266 err = reg->range < 0 ? -EINVAL :
5267 __check_mem_access(env, regno, off, size, reg->range,
5270 verbose(env, "R%d offset is outside of the packet\n", regno);
5274 /* __check_mem_access has made sure "off + size - 1" is within u16.
5275 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5276 * otherwise find_good_pkt_pointers would have refused to set range info
5277 * that __check_mem_access would have rejected this pkt access.
5278 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5280 env->prog->aux->max_pkt_offset =
5281 max_t(u32, env->prog->aux->max_pkt_offset,
5282 off + reg->umax_value + size - 1);
5287 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
5288 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5289 enum bpf_access_type t, enum bpf_reg_type *reg_type,
5290 struct btf **btf, u32 *btf_id)
5292 struct bpf_insn_access_aux info = {
5293 .reg_type = *reg_type,
5297 if (env->ops->is_valid_access &&
5298 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5299 /* A non zero info.ctx_field_size indicates that this field is a
5300 * candidate for later verifier transformation to load the whole
5301 * field and then apply a mask when accessed with a narrower
5302 * access than actual ctx access size. A zero info.ctx_field_size
5303 * will only allow for whole field access and rejects any other
5304 * type of narrower access.
5306 *reg_type = info.reg_type;
5308 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5310 *btf_id = info.btf_id;
5312 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5314 /* remember the offset of last byte accessed in ctx */
5315 if (env->prog->aux->max_ctx_offset < off + size)
5316 env->prog->aux->max_ctx_offset = off + size;
5320 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5324 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5327 if (size < 0 || off < 0 ||
5328 (u64)off + size > sizeof(struct bpf_flow_keys)) {
5329 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5336 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5337 u32 regno, int off, int size,
5338 enum bpf_access_type t)
5340 struct bpf_reg_state *regs = cur_regs(env);
5341 struct bpf_reg_state *reg = ®s[regno];
5342 struct bpf_insn_access_aux info = {};
5345 if (reg->smin_value < 0) {
5346 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5351 switch (reg->type) {
5352 case PTR_TO_SOCK_COMMON:
5353 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5356 valid = bpf_sock_is_valid_access(off, size, t, &info);
5358 case PTR_TO_TCP_SOCK:
5359 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5361 case PTR_TO_XDP_SOCK:
5362 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5370 env->insn_aux_data[insn_idx].ctx_field_size =
5371 info.ctx_field_size;
5375 verbose(env, "R%d invalid %s access off=%d size=%d\n",
5376 regno, reg_type_str(env, reg->type), off, size);
5381 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5383 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5386 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5388 const struct bpf_reg_state *reg = reg_state(env, regno);
5390 return reg->type == PTR_TO_CTX;
5393 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5395 const struct bpf_reg_state *reg = reg_state(env, regno);
5397 return type_is_sk_pointer(reg->type);
5400 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5402 const struct bpf_reg_state *reg = reg_state(env, regno);
5404 return type_is_pkt_pointer(reg->type);
5407 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5409 const struct bpf_reg_state *reg = reg_state(env, regno);
5411 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5412 return reg->type == PTR_TO_FLOW_KEYS;
5415 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5417 /* A referenced register is always trusted. */
5418 if (reg->ref_obj_id)
5421 /* If a register is not referenced, it is trusted if it has the
5422 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5423 * other type modifiers may be safe, but we elect to take an opt-in
5424 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5427 * Eventually, we should make PTR_TRUSTED the single source of truth
5428 * for whether a register is trusted.
5430 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5431 !bpf_type_has_unsafe_modifiers(reg->type);
5434 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5436 return reg->type & MEM_RCU;
5439 static void clear_trusted_flags(enum bpf_type_flag *flag)
5441 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5444 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5445 const struct bpf_reg_state *reg,
5446 int off, int size, bool strict)
5448 struct tnum reg_off;
5451 /* Byte size accesses are always allowed. */
5452 if (!strict || size == 1)
5455 /* For platforms that do not have a Kconfig enabling
5456 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5457 * NET_IP_ALIGN is universally set to '2'. And on platforms
5458 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5459 * to this code only in strict mode where we want to emulate
5460 * the NET_IP_ALIGN==2 checking. Therefore use an
5461 * unconditional IP align value of '2'.
5465 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5466 if (!tnum_is_aligned(reg_off, size)) {
5469 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5471 "misaligned packet access off %d+%s+%d+%d size %d\n",
5472 ip_align, tn_buf, reg->off, off, size);
5479 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5480 const struct bpf_reg_state *reg,
5481 const char *pointer_desc,
5482 int off, int size, bool strict)
5484 struct tnum reg_off;
5486 /* Byte size accesses are always allowed. */
5487 if (!strict || size == 1)
5490 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5491 if (!tnum_is_aligned(reg_off, size)) {
5494 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5495 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5496 pointer_desc, tn_buf, reg->off, off, size);
5503 static int check_ptr_alignment(struct bpf_verifier_env *env,
5504 const struct bpf_reg_state *reg, int off,
5505 int size, bool strict_alignment_once)
5507 bool strict = env->strict_alignment || strict_alignment_once;
5508 const char *pointer_desc = "";
5510 switch (reg->type) {
5512 case PTR_TO_PACKET_META:
5513 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5514 * right in front, treat it the very same way.
5516 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5517 case PTR_TO_FLOW_KEYS:
5518 pointer_desc = "flow keys ";
5520 case PTR_TO_MAP_KEY:
5521 pointer_desc = "key ";
5523 case PTR_TO_MAP_VALUE:
5524 pointer_desc = "value ";
5527 pointer_desc = "context ";
5530 pointer_desc = "stack ";
5531 /* The stack spill tracking logic in check_stack_write_fixed_off()
5532 * and check_stack_read_fixed_off() relies on stack accesses being
5538 pointer_desc = "sock ";
5540 case PTR_TO_SOCK_COMMON:
5541 pointer_desc = "sock_common ";
5543 case PTR_TO_TCP_SOCK:
5544 pointer_desc = "tcp_sock ";
5546 case PTR_TO_XDP_SOCK:
5547 pointer_desc = "xdp_sock ";
5552 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5556 static int update_stack_depth(struct bpf_verifier_env *env,
5557 const struct bpf_func_state *func,
5560 u16 stack = env->subprog_info[func->subprogno].stack_depth;
5565 /* update known max for given subprogram */
5566 env->subprog_info[func->subprogno].stack_depth = -off;
5570 /* starting from main bpf function walk all instructions of the function
5571 * and recursively walk all callees that given function can call.
5572 * Ignore jump and exit insns.
5573 * Since recursion is prevented by check_cfg() this algorithm
5574 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5576 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5578 struct bpf_subprog_info *subprog = env->subprog_info;
5579 struct bpf_insn *insn = env->prog->insnsi;
5580 int depth = 0, frame = 0, i, subprog_end;
5581 bool tail_call_reachable = false;
5582 int ret_insn[MAX_CALL_FRAMES];
5583 int ret_prog[MAX_CALL_FRAMES];
5586 i = subprog[idx].start;
5588 /* protect against potential stack overflow that might happen when
5589 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5590 * depth for such case down to 256 so that the worst case scenario
5591 * would result in 8k stack size (32 which is tailcall limit * 256 =
5594 * To get the idea what might happen, see an example:
5595 * func1 -> sub rsp, 128
5596 * subfunc1 -> sub rsp, 256
5597 * tailcall1 -> add rsp, 256
5598 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5599 * subfunc2 -> sub rsp, 64
5600 * subfunc22 -> sub rsp, 128
5601 * tailcall2 -> add rsp, 128
5602 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5604 * tailcall will unwind the current stack frame but it will not get rid
5605 * of caller's stack as shown on the example above.
5607 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5609 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5613 /* round up to 32-bytes, since this is granularity
5614 * of interpreter stack size
5616 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5617 if (depth > MAX_BPF_STACK) {
5618 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5623 subprog_end = subprog[idx + 1].start;
5624 for (; i < subprog_end; i++) {
5625 int next_insn, sidx;
5627 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5629 /* remember insn and function to return to */
5630 ret_insn[frame] = i + 1;
5631 ret_prog[frame] = idx;
5633 /* find the callee */
5634 next_insn = i + insn[i].imm + 1;
5635 sidx = find_subprog(env, next_insn);
5637 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5641 if (subprog[sidx].is_async_cb) {
5642 if (subprog[sidx].has_tail_call) {
5643 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5646 /* async callbacks don't increase bpf prog stack size unless called directly */
5647 if (!bpf_pseudo_call(insn + i))
5653 if (subprog[idx].has_tail_call)
5654 tail_call_reachable = true;
5657 if (frame >= MAX_CALL_FRAMES) {
5658 verbose(env, "the call stack of %d frames is too deep !\n",
5664 /* if tail call got detected across bpf2bpf calls then mark each of the
5665 * currently present subprog frames as tail call reachable subprogs;
5666 * this info will be utilized by JIT so that we will be preserving the
5667 * tail call counter throughout bpf2bpf calls combined with tailcalls
5669 if (tail_call_reachable)
5670 for (j = 0; j < frame; j++)
5671 subprog[ret_prog[j]].tail_call_reachable = true;
5672 if (subprog[0].tail_call_reachable)
5673 env->prog->aux->tail_call_reachable = true;
5675 /* end of for() loop means the last insn of the 'subprog'
5676 * was reached. Doesn't matter whether it was JA or EXIT
5680 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5682 i = ret_insn[frame];
5683 idx = ret_prog[frame];
5687 static int check_max_stack_depth(struct bpf_verifier_env *env)
5689 struct bpf_subprog_info *si = env->subprog_info;
5692 for (int i = 0; i < env->subprog_cnt; i++) {
5693 if (!i || si[i].is_async_cb) {
5694 ret = check_max_stack_depth_subprog(env, i);
5703 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5704 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5705 const struct bpf_insn *insn, int idx)
5707 int start = idx + insn->imm + 1, subprog;
5709 subprog = find_subprog(env, start);
5711 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5715 return env->subprog_info[subprog].stack_depth;
5719 static int __check_buffer_access(struct bpf_verifier_env *env,
5720 const char *buf_info,
5721 const struct bpf_reg_state *reg,
5722 int regno, int off, int size)
5726 "R%d invalid %s buffer access: off=%d, size=%d\n",
5727 regno, buf_info, off, size);
5730 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5733 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5735 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5736 regno, off, tn_buf);
5743 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5744 const struct bpf_reg_state *reg,
5745 int regno, int off, int size)
5749 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5753 if (off + size > env->prog->aux->max_tp_access)
5754 env->prog->aux->max_tp_access = off + size;
5759 static int check_buffer_access(struct bpf_verifier_env *env,
5760 const struct bpf_reg_state *reg,
5761 int regno, int off, int size,
5762 bool zero_size_allowed,
5765 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5768 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5772 if (off + size > *max_access)
5773 *max_access = off + size;
5778 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5779 static void zext_32_to_64(struct bpf_reg_state *reg)
5781 reg->var_off = tnum_subreg(reg->var_off);
5782 __reg_assign_32_into_64(reg);
5785 /* truncate register to smaller size (in bytes)
5786 * must be called with size < BPF_REG_SIZE
5788 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5792 /* clear high bits in bit representation */
5793 reg->var_off = tnum_cast(reg->var_off, size);
5795 /* fix arithmetic bounds */
5796 mask = ((u64)1 << (size * 8)) - 1;
5797 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5798 reg->umin_value &= mask;
5799 reg->umax_value &= mask;
5801 reg->umin_value = 0;
5802 reg->umax_value = mask;
5804 reg->smin_value = reg->umin_value;
5805 reg->smax_value = reg->umax_value;
5807 /* If size is smaller than 32bit register the 32bit register
5808 * values are also truncated so we push 64-bit bounds into
5809 * 32-bit bounds. Above were truncated < 32-bits already.
5813 __reg_combine_64_into_32(reg);
5816 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5818 /* A map is considered read-only if the following condition are true:
5820 * 1) BPF program side cannot change any of the map content. The
5821 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5822 * and was set at map creation time.
5823 * 2) The map value(s) have been initialized from user space by a
5824 * loader and then "frozen", such that no new map update/delete
5825 * operations from syscall side are possible for the rest of
5826 * the map's lifetime from that point onwards.
5827 * 3) Any parallel/pending map update/delete operations from syscall
5828 * side have been completed. Only after that point, it's safe to
5829 * assume that map value(s) are immutable.
5831 return (map->map_flags & BPF_F_RDONLY_PROG) &&
5832 READ_ONCE(map->frozen) &&
5833 !bpf_map_write_active(map);
5836 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
5842 err = map->ops->map_direct_value_addr(map, &addr, off);
5845 ptr = (void *)(long)addr + off;
5849 *val = (u64)*(u8 *)ptr;
5852 *val = (u64)*(u16 *)ptr;
5855 *val = (u64)*(u32 *)ptr;
5866 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
5867 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
5868 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
5871 * Allow list few fields as RCU trusted or full trusted.
5872 * This logic doesn't allow mix tagging and will be removed once GCC supports
5876 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5877 BTF_TYPE_SAFE_RCU(struct task_struct) {
5878 const cpumask_t *cpus_ptr;
5879 struct css_set __rcu *cgroups;
5880 struct task_struct __rcu *real_parent;
5881 struct task_struct *group_leader;
5884 BTF_TYPE_SAFE_RCU(struct cgroup) {
5885 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
5886 struct kernfs_node *kn;
5889 BTF_TYPE_SAFE_RCU(struct css_set) {
5890 struct cgroup *dfl_cgrp;
5893 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
5894 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
5895 struct file __rcu *exe_file;
5898 /* skb->sk, req->sk are not RCU protected, but we mark them as such
5899 * because bpf prog accessible sockets are SOCK_RCU_FREE.
5901 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
5905 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
5909 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5910 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5911 struct seq_file *seq;
5914 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5915 struct bpf_iter_meta *meta;
5916 struct task_struct *task;
5919 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5923 BTF_TYPE_SAFE_TRUSTED(struct file) {
5924 struct inode *f_inode;
5927 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
5928 /* no negative dentry-s in places where bpf can see it */
5929 struct inode *d_inode;
5932 BTF_TYPE_SAFE_TRUSTED(struct socket) {
5936 static bool type_is_rcu(struct bpf_verifier_env *env,
5937 struct bpf_reg_state *reg,
5938 const char *field_name, u32 btf_id)
5940 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5941 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
5942 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5944 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
5947 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
5948 struct bpf_reg_state *reg,
5949 const char *field_name, u32 btf_id)
5951 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
5952 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
5953 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
5955 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
5958 static bool type_is_trusted(struct bpf_verifier_env *env,
5959 struct bpf_reg_state *reg,
5960 const char *field_name, u32 btf_id)
5962 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5963 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5964 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5965 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5966 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
5967 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
5969 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
5972 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5973 struct bpf_reg_state *regs,
5974 int regno, int off, int size,
5975 enum bpf_access_type atype,
5978 struct bpf_reg_state *reg = regs + regno;
5979 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5980 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5981 const char *field_name = NULL;
5982 enum bpf_type_flag flag = 0;
5986 if (!env->allow_ptr_leaks) {
5988 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5992 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5994 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6000 "R%d is ptr_%s invalid negative access: off=%d\n",
6004 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6007 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6009 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6010 regno, tname, off, tn_buf);
6014 if (reg->type & MEM_USER) {
6016 "R%d is ptr_%s access user memory: off=%d\n",
6021 if (reg->type & MEM_PERCPU) {
6023 "R%d is ptr_%s access percpu memory: off=%d\n",
6028 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6029 if (!btf_is_kernel(reg->btf)) {
6030 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6033 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6035 /* Writes are permitted with default btf_struct_access for
6036 * program allocated objects (which always have ref_obj_id > 0),
6037 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6039 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6040 verbose(env, "only read is supported\n");
6044 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6046 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6050 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6056 if (ret != PTR_TO_BTF_ID) {
6059 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6060 /* If this is an untrusted pointer, all pointers formed by walking it
6061 * also inherit the untrusted flag.
6063 flag = PTR_UNTRUSTED;
6065 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6066 /* By default any pointer obtained from walking a trusted pointer is no
6067 * longer trusted, unless the field being accessed has explicitly been
6068 * marked as inheriting its parent's state of trust (either full or RCU).
6070 * 'cgroups' pointer is untrusted if task->cgroups dereference
6071 * happened in a sleepable program outside of bpf_rcu_read_lock()
6072 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6073 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6075 * A regular RCU-protected pointer with __rcu tag can also be deemed
6076 * trusted if we are in an RCU CS. Such pointer can be NULL.
6078 if (type_is_trusted(env, reg, field_name, btf_id)) {
6079 flag |= PTR_TRUSTED;
6080 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6081 if (type_is_rcu(env, reg, field_name, btf_id)) {
6082 /* ignore __rcu tag and mark it MEM_RCU */
6084 } else if (flag & MEM_RCU ||
6085 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6086 /* __rcu tagged pointers can be NULL */
6087 flag |= MEM_RCU | PTR_MAYBE_NULL;
6088 } else if (flag & (MEM_PERCPU | MEM_USER)) {
6091 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6092 clear_trusted_flags(&flag);
6096 * If not in RCU CS or MEM_RCU pointer can be NULL then
6097 * aggressively mark as untrusted otherwise such
6098 * pointers will be plain PTR_TO_BTF_ID without flags
6099 * and will be allowed to be passed into helpers for
6102 flag = PTR_UNTRUSTED;
6105 /* Old compat. Deprecated */
6106 clear_trusted_flags(&flag);
6109 if (atype == BPF_READ && value_regno >= 0)
6110 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6115 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6116 struct bpf_reg_state *regs,
6117 int regno, int off, int size,
6118 enum bpf_access_type atype,
6121 struct bpf_reg_state *reg = regs + regno;
6122 struct bpf_map *map = reg->map_ptr;
6123 struct bpf_reg_state map_reg;
6124 enum bpf_type_flag flag = 0;
6125 const struct btf_type *t;
6131 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6135 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6136 verbose(env, "map_ptr access not supported for map type %d\n",
6141 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6142 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6144 if (!env->allow_ptr_leaks) {
6146 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6152 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6157 if (atype != BPF_READ) {
6158 verbose(env, "only read from %s is supported\n", tname);
6162 /* Simulate access to a PTR_TO_BTF_ID */
6163 memset(&map_reg, 0, sizeof(map_reg));
6164 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6165 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6169 if (value_regno >= 0)
6170 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6175 /* Check that the stack access at the given offset is within bounds. The
6176 * maximum valid offset is -1.
6178 * The minimum valid offset is -MAX_BPF_STACK for writes, and
6179 * -state->allocated_stack for reads.
6181 static int check_stack_slot_within_bounds(int off,
6182 struct bpf_func_state *state,
6183 enum bpf_access_type t)
6188 min_valid_off = -MAX_BPF_STACK;
6190 min_valid_off = -state->allocated_stack;
6192 if (off < min_valid_off || off > -1)
6197 /* Check that the stack access at 'regno + off' falls within the maximum stack
6200 * 'off' includes `regno->offset`, but not its dynamic part (if any).
6202 static int check_stack_access_within_bounds(
6203 struct bpf_verifier_env *env,
6204 int regno, int off, int access_size,
6205 enum bpf_access_src src, enum bpf_access_type type)
6207 struct bpf_reg_state *regs = cur_regs(env);
6208 struct bpf_reg_state *reg = regs + regno;
6209 struct bpf_func_state *state = func(env, reg);
6210 int min_off, max_off;
6214 if (src == ACCESS_HELPER)
6215 /* We don't know if helpers are reading or writing (or both). */
6216 err_extra = " indirect access to";
6217 else if (type == BPF_READ)
6218 err_extra = " read from";
6220 err_extra = " write to";
6222 if (tnum_is_const(reg->var_off)) {
6223 min_off = reg->var_off.value + off;
6224 if (access_size > 0)
6225 max_off = min_off + access_size - 1;
6229 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6230 reg->smin_value <= -BPF_MAX_VAR_OFF) {
6231 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6235 min_off = reg->smin_value + off;
6236 if (access_size > 0)
6237 max_off = reg->smax_value + off + access_size - 1;
6242 err = check_stack_slot_within_bounds(min_off, state, type);
6244 err = check_stack_slot_within_bounds(max_off, state, type);
6247 if (tnum_is_const(reg->var_off)) {
6248 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6249 err_extra, regno, off, access_size);
6253 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6254 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6255 err_extra, regno, tn_buf, access_size);
6261 /* check whether memory at (regno + off) is accessible for t = (read | write)
6262 * if t==write, value_regno is a register which value is stored into memory
6263 * if t==read, value_regno is a register which will receive the value from memory
6264 * if t==write && value_regno==-1, some unknown value is stored into memory
6265 * if t==read && value_regno==-1, don't care what we read from memory
6267 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6268 int off, int bpf_size, enum bpf_access_type t,
6269 int value_regno, bool strict_alignment_once)
6271 struct bpf_reg_state *regs = cur_regs(env);
6272 struct bpf_reg_state *reg = regs + regno;
6273 struct bpf_func_state *state;
6276 size = bpf_size_to_bytes(bpf_size);
6280 /* alignment checks will add in reg->off themselves */
6281 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6285 /* for access checks, reg->off is just part of off */
6288 if (reg->type == PTR_TO_MAP_KEY) {
6289 if (t == BPF_WRITE) {
6290 verbose(env, "write to change key R%d not allowed\n", regno);
6294 err = check_mem_region_access(env, regno, off, size,
6295 reg->map_ptr->key_size, false);
6298 if (value_regno >= 0)
6299 mark_reg_unknown(env, regs, value_regno);
6300 } else if (reg->type == PTR_TO_MAP_VALUE) {
6301 struct btf_field *kptr_field = NULL;
6303 if (t == BPF_WRITE && value_regno >= 0 &&
6304 is_pointer_value(env, value_regno)) {
6305 verbose(env, "R%d leaks addr into map\n", value_regno);
6308 err = check_map_access_type(env, regno, off, size, t);
6311 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6314 if (tnum_is_const(reg->var_off))
6315 kptr_field = btf_record_find(reg->map_ptr->record,
6316 off + reg->var_off.value, BPF_KPTR);
6318 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6319 } else if (t == BPF_READ && value_regno >= 0) {
6320 struct bpf_map *map = reg->map_ptr;
6322 /* if map is read-only, track its contents as scalars */
6323 if (tnum_is_const(reg->var_off) &&
6324 bpf_map_is_rdonly(map) &&
6325 map->ops->map_direct_value_addr) {
6326 int map_off = off + reg->var_off.value;
6329 err = bpf_map_direct_read(map, map_off, size,
6334 regs[value_regno].type = SCALAR_VALUE;
6335 __mark_reg_known(®s[value_regno], val);
6337 mark_reg_unknown(env, regs, value_regno);
6340 } else if (base_type(reg->type) == PTR_TO_MEM) {
6341 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6343 if (type_may_be_null(reg->type)) {
6344 verbose(env, "R%d invalid mem access '%s'\n", regno,
6345 reg_type_str(env, reg->type));
6349 if (t == BPF_WRITE && rdonly_mem) {
6350 verbose(env, "R%d cannot write into %s\n",
6351 regno, reg_type_str(env, reg->type));
6355 if (t == BPF_WRITE && value_regno >= 0 &&
6356 is_pointer_value(env, value_regno)) {
6357 verbose(env, "R%d leaks addr into mem\n", value_regno);
6361 err = check_mem_region_access(env, regno, off, size,
6362 reg->mem_size, false);
6363 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6364 mark_reg_unknown(env, regs, value_regno);
6365 } else if (reg->type == PTR_TO_CTX) {
6366 enum bpf_reg_type reg_type = SCALAR_VALUE;
6367 struct btf *btf = NULL;
6370 if (t == BPF_WRITE && value_regno >= 0 &&
6371 is_pointer_value(env, value_regno)) {
6372 verbose(env, "R%d leaks addr into ctx\n", value_regno);
6376 err = check_ptr_off_reg(env, reg, regno);
6380 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
6383 verbose_linfo(env, insn_idx, "; ");
6384 if (!err && t == BPF_READ && value_regno >= 0) {
6385 /* ctx access returns either a scalar, or a
6386 * PTR_TO_PACKET[_META,_END]. In the latter
6387 * case, we know the offset is zero.
6389 if (reg_type == SCALAR_VALUE) {
6390 mark_reg_unknown(env, regs, value_regno);
6392 mark_reg_known_zero(env, regs,
6394 if (type_may_be_null(reg_type))
6395 regs[value_regno].id = ++env->id_gen;
6396 /* A load of ctx field could have different
6397 * actual load size with the one encoded in the
6398 * insn. When the dst is PTR, it is for sure not
6401 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6402 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6403 regs[value_regno].btf = btf;
6404 regs[value_regno].btf_id = btf_id;
6407 regs[value_regno].type = reg_type;
6410 } else if (reg->type == PTR_TO_STACK) {
6411 /* Basic bounds checks. */
6412 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6416 state = func(env, reg);
6417 err = update_stack_depth(env, state, off);
6422 err = check_stack_read(env, regno, off, size,
6425 err = check_stack_write(env, regno, off, size,
6426 value_regno, insn_idx);
6427 } else if (reg_is_pkt_pointer(reg)) {
6428 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6429 verbose(env, "cannot write into packet\n");
6432 if (t == BPF_WRITE && value_regno >= 0 &&
6433 is_pointer_value(env, value_regno)) {
6434 verbose(env, "R%d leaks addr into packet\n",
6438 err = check_packet_access(env, regno, off, size, false);
6439 if (!err && t == BPF_READ && value_regno >= 0)
6440 mark_reg_unknown(env, regs, value_regno);
6441 } else if (reg->type == PTR_TO_FLOW_KEYS) {
6442 if (t == BPF_WRITE && value_regno >= 0 &&
6443 is_pointer_value(env, value_regno)) {
6444 verbose(env, "R%d leaks addr into flow keys\n",
6449 err = check_flow_keys_access(env, off, size);
6450 if (!err && t == BPF_READ && value_regno >= 0)
6451 mark_reg_unknown(env, regs, value_regno);
6452 } else if (type_is_sk_pointer(reg->type)) {
6453 if (t == BPF_WRITE) {
6454 verbose(env, "R%d cannot write into %s\n",
6455 regno, reg_type_str(env, reg->type));
6458 err = check_sock_access(env, insn_idx, regno, off, size, t);
6459 if (!err && value_regno >= 0)
6460 mark_reg_unknown(env, regs, value_regno);
6461 } else if (reg->type == PTR_TO_TP_BUFFER) {
6462 err = check_tp_buffer_access(env, reg, regno, off, size);
6463 if (!err && t == BPF_READ && value_regno >= 0)
6464 mark_reg_unknown(env, regs, value_regno);
6465 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6466 !type_may_be_null(reg->type)) {
6467 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6469 } else if (reg->type == CONST_PTR_TO_MAP) {
6470 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6472 } else if (base_type(reg->type) == PTR_TO_BUF) {
6473 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6477 if (t == BPF_WRITE) {
6478 verbose(env, "R%d cannot write into %s\n",
6479 regno, reg_type_str(env, reg->type));
6482 max_access = &env->prog->aux->max_rdonly_access;
6484 max_access = &env->prog->aux->max_rdwr_access;
6487 err = check_buffer_access(env, reg, regno, off, size, false,
6490 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6491 mark_reg_unknown(env, regs, value_regno);
6493 verbose(env, "R%d invalid mem access '%s'\n", regno,
6494 reg_type_str(env, reg->type));
6498 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6499 regs[value_regno].type == SCALAR_VALUE) {
6500 /* b/h/w load zero-extends, mark upper bits as known 0 */
6501 coerce_reg_to_size(®s[value_regno], size);
6506 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6511 switch (insn->imm) {
6513 case BPF_ADD | BPF_FETCH:
6515 case BPF_AND | BPF_FETCH:
6517 case BPF_OR | BPF_FETCH:
6519 case BPF_XOR | BPF_FETCH:
6524 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6528 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6529 verbose(env, "invalid atomic operand size\n");
6533 /* check src1 operand */
6534 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6538 /* check src2 operand */
6539 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6543 if (insn->imm == BPF_CMPXCHG) {
6544 /* Check comparison of R0 with memory location */
6545 const u32 aux_reg = BPF_REG_0;
6547 err = check_reg_arg(env, aux_reg, SRC_OP);
6551 if (is_pointer_value(env, aux_reg)) {
6552 verbose(env, "R%d leaks addr into mem\n", aux_reg);
6557 if (is_pointer_value(env, insn->src_reg)) {
6558 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6562 if (is_ctx_reg(env, insn->dst_reg) ||
6563 is_pkt_reg(env, insn->dst_reg) ||
6564 is_flow_key_reg(env, insn->dst_reg) ||
6565 is_sk_reg(env, insn->dst_reg)) {
6566 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6568 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6572 if (insn->imm & BPF_FETCH) {
6573 if (insn->imm == BPF_CMPXCHG)
6574 load_reg = BPF_REG_0;
6576 load_reg = insn->src_reg;
6578 /* check and record load of old value */
6579 err = check_reg_arg(env, load_reg, DST_OP);
6583 /* This instruction accesses a memory location but doesn't
6584 * actually load it into a register.
6589 /* Check whether we can read the memory, with second call for fetch
6590 * case to simulate the register fill.
6592 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6593 BPF_SIZE(insn->code), BPF_READ, -1, true);
6594 if (!err && load_reg >= 0)
6595 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6596 BPF_SIZE(insn->code), BPF_READ, load_reg,
6601 /* Check whether we can write into the same memory. */
6602 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6603 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
6610 /* When register 'regno' is used to read the stack (either directly or through
6611 * a helper function) make sure that it's within stack boundary and, depending
6612 * on the access type, that all elements of the stack are initialized.
6614 * 'off' includes 'regno->off', but not its dynamic part (if any).
6616 * All registers that have been spilled on the stack in the slots within the
6617 * read offsets are marked as read.
6619 static int check_stack_range_initialized(
6620 struct bpf_verifier_env *env, int regno, int off,
6621 int access_size, bool zero_size_allowed,
6622 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6624 struct bpf_reg_state *reg = reg_state(env, regno);
6625 struct bpf_func_state *state = func(env, reg);
6626 int err, min_off, max_off, i, j, slot, spi;
6627 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6628 enum bpf_access_type bounds_check_type;
6629 /* Some accesses can write anything into the stack, others are
6632 bool clobber = false;
6634 if (access_size == 0 && !zero_size_allowed) {
6635 verbose(env, "invalid zero-sized read\n");
6639 if (type == ACCESS_HELPER) {
6640 /* The bounds checks for writes are more permissive than for
6641 * reads. However, if raw_mode is not set, we'll do extra
6644 bounds_check_type = BPF_WRITE;
6647 bounds_check_type = BPF_READ;
6649 err = check_stack_access_within_bounds(env, regno, off, access_size,
6650 type, bounds_check_type);
6655 if (tnum_is_const(reg->var_off)) {
6656 min_off = max_off = reg->var_off.value + off;
6658 /* Variable offset is prohibited for unprivileged mode for
6659 * simplicity since it requires corresponding support in
6660 * Spectre masking for stack ALU.
6661 * See also retrieve_ptr_limit().
6663 if (!env->bypass_spec_v1) {
6666 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6667 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6668 regno, err_extra, tn_buf);
6671 /* Only initialized buffer on stack is allowed to be accessed
6672 * with variable offset. With uninitialized buffer it's hard to
6673 * guarantee that whole memory is marked as initialized on
6674 * helper return since specific bounds are unknown what may
6675 * cause uninitialized stack leaking.
6677 if (meta && meta->raw_mode)
6680 min_off = reg->smin_value + off;
6681 max_off = reg->smax_value + off;
6684 if (meta && meta->raw_mode) {
6685 /* Ensure we won't be overwriting dynptrs when simulating byte
6686 * by byte access in check_helper_call using meta.access_size.
6687 * This would be a problem if we have a helper in the future
6690 * helper(uninit_mem, len, dynptr)
6692 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6693 * may end up writing to dynptr itself when touching memory from
6694 * arg 1. This can be relaxed on a case by case basis for known
6695 * safe cases, but reject due to the possibilitiy of aliasing by
6698 for (i = min_off; i < max_off + access_size; i++) {
6699 int stack_off = -i - 1;
6702 /* raw_mode may write past allocated_stack */
6703 if (state->allocated_stack <= stack_off)
6705 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6706 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6710 meta->access_size = access_size;
6711 meta->regno = regno;
6715 for (i = min_off; i < max_off + access_size; i++) {
6719 spi = slot / BPF_REG_SIZE;
6720 if (state->allocated_stack <= slot)
6722 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6723 if (*stype == STACK_MISC)
6725 if ((*stype == STACK_ZERO) ||
6726 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6728 /* helper can write anything into the stack */
6729 *stype = STACK_MISC;
6734 if (is_spilled_reg(&state->stack[spi]) &&
6735 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6736 env->allow_ptr_leaks)) {
6738 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6739 for (j = 0; j < BPF_REG_SIZE; j++)
6740 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6746 if (tnum_is_const(reg->var_off)) {
6747 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6748 err_extra, regno, min_off, i - min_off, access_size);
6752 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6753 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6754 err_extra, regno, tn_buf, i - min_off, access_size);
6758 /* reading any byte out of 8-byte 'spill_slot' will cause
6759 * the whole slot to be marked as 'read'
6761 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6762 state->stack[spi].spilled_ptr.parent,
6764 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6765 * be sure that whether stack slot is written to or not. Hence,
6766 * we must still conservatively propagate reads upwards even if
6767 * helper may write to the entire memory range.
6770 return update_stack_depth(env, state, min_off);
6773 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6774 int access_size, bool zero_size_allowed,
6775 struct bpf_call_arg_meta *meta)
6777 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6780 switch (base_type(reg->type)) {
6782 case PTR_TO_PACKET_META:
6783 return check_packet_access(env, regno, reg->off, access_size,
6785 case PTR_TO_MAP_KEY:
6786 if (meta && meta->raw_mode) {
6787 verbose(env, "R%d cannot write into %s\n", regno,
6788 reg_type_str(env, reg->type));
6791 return check_mem_region_access(env, regno, reg->off, access_size,
6792 reg->map_ptr->key_size, false);
6793 case PTR_TO_MAP_VALUE:
6794 if (check_map_access_type(env, regno, reg->off, access_size,
6795 meta && meta->raw_mode ? BPF_WRITE :
6798 return check_map_access(env, regno, reg->off, access_size,
6799 zero_size_allowed, ACCESS_HELPER);
6801 if (type_is_rdonly_mem(reg->type)) {
6802 if (meta && meta->raw_mode) {
6803 verbose(env, "R%d cannot write into %s\n", regno,
6804 reg_type_str(env, reg->type));
6808 return check_mem_region_access(env, regno, reg->off,
6809 access_size, reg->mem_size,
6812 if (type_is_rdonly_mem(reg->type)) {
6813 if (meta && meta->raw_mode) {
6814 verbose(env, "R%d cannot write into %s\n", regno,
6815 reg_type_str(env, reg->type));
6819 max_access = &env->prog->aux->max_rdonly_access;
6821 max_access = &env->prog->aux->max_rdwr_access;
6823 return check_buffer_access(env, reg, regno, reg->off,
6824 access_size, zero_size_allowed,
6827 return check_stack_range_initialized(
6829 regno, reg->off, access_size,
6830 zero_size_allowed, ACCESS_HELPER, meta);
6832 return check_ptr_to_btf_access(env, regs, regno, reg->off,
6833 access_size, BPF_READ, -1);
6835 /* in case the function doesn't know how to access the context,
6836 * (because we are in a program of type SYSCALL for example), we
6837 * can not statically check its size.
6838 * Dynamically check it now.
6840 if (!env->ops->convert_ctx_access) {
6841 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6842 int offset = access_size - 1;
6844 /* Allow zero-byte read from PTR_TO_CTX */
6845 if (access_size == 0)
6846 return zero_size_allowed ? 0 : -EACCES;
6848 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
6853 default: /* scalar_value or invalid ptr */
6854 /* Allow zero-byte read from NULL, regardless of pointer type */
6855 if (zero_size_allowed && access_size == 0 &&
6856 register_is_null(reg))
6859 verbose(env, "R%d type=%s ", regno,
6860 reg_type_str(env, reg->type));
6861 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6866 static int check_mem_size_reg(struct bpf_verifier_env *env,
6867 struct bpf_reg_state *reg, u32 regno,
6868 bool zero_size_allowed,
6869 struct bpf_call_arg_meta *meta)
6873 /* This is used to refine r0 return value bounds for helpers
6874 * that enforce this value as an upper bound on return values.
6875 * See do_refine_retval_range() for helpers that can refine
6876 * the return value. C type of helper is u32 so we pull register
6877 * bound from umax_value however, if negative verifier errors
6878 * out. Only upper bounds can be learned because retval is an
6879 * int type and negative retvals are allowed.
6881 meta->msize_max_value = reg->umax_value;
6883 /* The register is SCALAR_VALUE; the access check
6884 * happens using its boundaries.
6886 if (!tnum_is_const(reg->var_off))
6887 /* For unprivileged variable accesses, disable raw
6888 * mode so that the program is required to
6889 * initialize all the memory that the helper could
6890 * just partially fill up.
6894 if (reg->smin_value < 0) {
6895 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6900 if (reg->umin_value == 0) {
6901 err = check_helper_mem_access(env, regno - 1, 0,
6908 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
6909 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6913 err = check_helper_mem_access(env, regno - 1,
6915 zero_size_allowed, meta);
6917 err = mark_chain_precision(env, regno);
6921 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6922 u32 regno, u32 mem_size)
6924 bool may_be_null = type_may_be_null(reg->type);
6925 struct bpf_reg_state saved_reg;
6926 struct bpf_call_arg_meta meta;
6929 if (register_is_null(reg))
6932 memset(&meta, 0, sizeof(meta));
6933 /* Assuming that the register contains a value check if the memory
6934 * access is safe. Temporarily save and restore the register's state as
6935 * the conversion shouldn't be visible to a caller.
6939 mark_ptr_not_null_reg(reg);
6942 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
6943 /* Check access for BPF_WRITE */
6944 meta.raw_mode = true;
6945 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
6953 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6956 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
6957 bool may_be_null = type_may_be_null(mem_reg->type);
6958 struct bpf_reg_state saved_reg;
6959 struct bpf_call_arg_meta meta;
6962 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
6964 memset(&meta, 0, sizeof(meta));
6967 saved_reg = *mem_reg;
6968 mark_ptr_not_null_reg(mem_reg);
6971 err = check_mem_size_reg(env, reg, regno, true, &meta);
6972 /* Check access for BPF_WRITE */
6973 meta.raw_mode = true;
6974 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6977 *mem_reg = saved_reg;
6981 /* Implementation details:
6982 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6983 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6984 * Two bpf_map_lookups (even with the same key) will have different reg->id.
6985 * Two separate bpf_obj_new will also have different reg->id.
6986 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6987 * clears reg->id after value_or_null->value transition, since the verifier only
6988 * cares about the range of access to valid map value pointer and doesn't care
6989 * about actual address of the map element.
6990 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6991 * reg->id > 0 after value_or_null->value transition. By doing so
6992 * two bpf_map_lookups will be considered two different pointers that
6993 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6994 * returned from bpf_obj_new.
6995 * The verifier allows taking only one bpf_spin_lock at a time to avoid
6997 * Since only one bpf_spin_lock is allowed the checks are simpler than
6998 * reg_is_refcounted() logic. The verifier needs to remember only
6999 * one spin_lock instead of array of acquired_refs.
7000 * cur_state->active_lock remembers which map value element or allocated
7001 * object got locked and clears it after bpf_spin_unlock.
7003 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7006 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7007 struct bpf_verifier_state *cur = env->cur_state;
7008 bool is_const = tnum_is_const(reg->var_off);
7009 u64 val = reg->var_off.value;
7010 struct bpf_map *map = NULL;
7011 struct btf *btf = NULL;
7012 struct btf_record *rec;
7016 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7020 if (reg->type == PTR_TO_MAP_VALUE) {
7024 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7032 rec = reg_btf_record(reg);
7033 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7034 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7035 map ? map->name : "kptr");
7038 if (rec->spin_lock_off != val + reg->off) {
7039 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7040 val + reg->off, rec->spin_lock_off);
7044 if (cur->active_lock.ptr) {
7046 "Locking two bpf_spin_locks are not allowed\n");
7050 cur->active_lock.ptr = map;
7052 cur->active_lock.ptr = btf;
7053 cur->active_lock.id = reg->id;
7062 if (!cur->active_lock.ptr) {
7063 verbose(env, "bpf_spin_unlock without taking a lock\n");
7066 if (cur->active_lock.ptr != ptr ||
7067 cur->active_lock.id != reg->id) {
7068 verbose(env, "bpf_spin_unlock of different lock\n");
7072 invalidate_non_owning_refs(env);
7074 cur->active_lock.ptr = NULL;
7075 cur->active_lock.id = 0;
7080 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7081 struct bpf_call_arg_meta *meta)
7083 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7084 bool is_const = tnum_is_const(reg->var_off);
7085 struct bpf_map *map = reg->map_ptr;
7086 u64 val = reg->var_off.value;
7090 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7095 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7099 if (!btf_record_has_field(map->record, BPF_TIMER)) {
7100 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7103 if (map->record->timer_off != val + reg->off) {
7104 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7105 val + reg->off, map->record->timer_off);
7108 if (meta->map_ptr) {
7109 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7112 meta->map_uid = reg->map_uid;
7113 meta->map_ptr = map;
7117 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7118 struct bpf_call_arg_meta *meta)
7120 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7121 struct bpf_map *map_ptr = reg->map_ptr;
7122 struct btf_field *kptr_field;
7125 if (!tnum_is_const(reg->var_off)) {
7127 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7131 if (!map_ptr->btf) {
7132 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7136 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7137 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7141 meta->map_ptr = map_ptr;
7142 kptr_off = reg->off + reg->var_off.value;
7143 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7145 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7148 if (kptr_field->type != BPF_KPTR_REF) {
7149 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7152 meta->kptr_field = kptr_field;
7156 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7157 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7159 * In both cases we deal with the first 8 bytes, but need to mark the next 8
7160 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7161 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7163 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7164 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7165 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7166 * mutate the view of the dynptr and also possibly destroy it. In the latter
7167 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7168 * memory that dynptr points to.
7170 * The verifier will keep track both levels of mutation (bpf_dynptr's in
7171 * reg->type and the memory's in reg->dynptr.type), but there is no support for
7172 * readonly dynptr view yet, hence only the first case is tracked and checked.
7174 * This is consistent with how C applies the const modifier to a struct object,
7175 * where the pointer itself inside bpf_dynptr becomes const but not what it
7178 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7179 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7181 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7182 enum bpf_arg_type arg_type, int clone_ref_obj_id)
7184 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7187 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7188 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7190 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7191 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7195 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
7196 * constructing a mutable bpf_dynptr object.
7198 * Currently, this is only possible with PTR_TO_STACK
7199 * pointing to a region of at least 16 bytes which doesn't
7200 * contain an existing bpf_dynptr.
7202 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7203 * mutated or destroyed. However, the memory it points to
7206 * None - Points to a initialized dynptr that can be mutated and
7207 * destroyed, including mutation of the memory it points
7210 if (arg_type & MEM_UNINIT) {
7213 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7214 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7218 /* we write BPF_DW bits (8 bytes) at a time */
7219 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7220 err = check_mem_access(env, insn_idx, regno,
7221 i, BPF_DW, BPF_WRITE, -1, false);
7226 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7227 } else /* MEM_RDONLY and None case from above */ {
7228 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7229 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7230 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7234 if (!is_dynptr_reg_valid_init(env, reg)) {
7236 "Expected an initialized dynptr as arg #%d\n",
7241 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7242 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7244 "Expected a dynptr of type %s as arg #%d\n",
7245 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7249 err = mark_dynptr_read(env, reg);
7254 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7256 struct bpf_func_state *state = func(env, reg);
7258 return state->stack[spi].spilled_ptr.ref_obj_id;
7261 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7263 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7266 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7268 return meta->kfunc_flags & KF_ITER_NEW;
7271 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7273 return meta->kfunc_flags & KF_ITER_NEXT;
7276 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7278 return meta->kfunc_flags & KF_ITER_DESTROY;
7281 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7283 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7284 * kfunc is iter state pointer
7286 return arg == 0 && is_iter_kfunc(meta);
7289 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7290 struct bpf_kfunc_call_arg_meta *meta)
7292 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7293 const struct btf_type *t;
7294 const struct btf_param *arg;
7295 int spi, err, i, nr_slots;
7298 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7299 arg = &btf_params(meta->func_proto)[0];
7300 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
7301 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
7302 nr_slots = t->size / BPF_REG_SIZE;
7304 if (is_iter_new_kfunc(meta)) {
7305 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7306 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7307 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7308 iter_type_str(meta->btf, btf_id), regno);
7312 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7313 err = check_mem_access(env, insn_idx, regno,
7314 i, BPF_DW, BPF_WRITE, -1, false);
7319 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7323 /* iter_next() or iter_destroy() expect initialized iter state*/
7324 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7325 verbose(env, "expected an initialized iter_%s as arg #%d\n",
7326 iter_type_str(meta->btf, btf_id), regno);
7330 spi = iter_get_spi(env, reg, nr_slots);
7334 err = mark_iter_read(env, reg, spi, nr_slots);
7338 /* remember meta->iter info for process_iter_next_call() */
7339 meta->iter.spi = spi;
7340 meta->iter.frameno = reg->frameno;
7341 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7343 if (is_iter_destroy_kfunc(meta)) {
7344 err = unmark_stack_slots_iter(env, reg, nr_slots);
7353 /* process_iter_next_call() is called when verifier gets to iterator's next
7354 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7355 * to it as just "iter_next()" in comments below.
7357 * BPF verifier relies on a crucial contract for any iter_next()
7358 * implementation: it should *eventually* return NULL, and once that happens
7359 * it should keep returning NULL. That is, once iterator exhausts elements to
7360 * iterate, it should never reset or spuriously return new elements.
7362 * With the assumption of such contract, process_iter_next_call() simulates
7363 * a fork in the verifier state to validate loop logic correctness and safety
7364 * without having to simulate infinite amount of iterations.
7366 * In current state, we first assume that iter_next() returned NULL and
7367 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7368 * conditions we should not form an infinite loop and should eventually reach
7371 * Besides that, we also fork current state and enqueue it for later
7372 * verification. In a forked state we keep iterator state as ACTIVE
7373 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7374 * also bump iteration depth to prevent erroneous infinite loop detection
7375 * later on (see iter_active_depths_differ() comment for details). In this
7376 * state we assume that we'll eventually loop back to another iter_next()
7377 * calls (it could be in exactly same location or in some other instruction,
7378 * it doesn't matter, we don't make any unnecessary assumptions about this,
7379 * everything revolves around iterator state in a stack slot, not which
7380 * instruction is calling iter_next()). When that happens, we either will come
7381 * to iter_next() with equivalent state and can conclude that next iteration
7382 * will proceed in exactly the same way as we just verified, so it's safe to
7383 * assume that loop converges. If not, we'll go on another iteration
7384 * simulation with a different input state, until all possible starting states
7385 * are validated or we reach maximum number of instructions limit.
7387 * This way, we will either exhaustively discover all possible input states
7388 * that iterator loop can start with and eventually will converge, or we'll
7389 * effectively regress into bounded loop simulation logic and either reach
7390 * maximum number of instructions if loop is not provably convergent, or there
7391 * is some statically known limit on number of iterations (e.g., if there is
7392 * an explicit `if n > 100 then break;` statement somewhere in the loop).
7394 * One very subtle but very important aspect is that we *always* simulate NULL
7395 * condition first (as the current state) before we simulate non-NULL case.
7396 * This has to do with intricacies of scalar precision tracking. By simulating
7397 * "exit condition" of iter_next() returning NULL first, we make sure all the
7398 * relevant precision marks *that will be set **after** we exit iterator loop*
7399 * are propagated backwards to common parent state of NULL and non-NULL
7400 * branches. Thanks to that, state equivalence checks done later in forked
7401 * state, when reaching iter_next() for ACTIVE iterator, can assume that
7402 * precision marks are finalized and won't change. Because simulating another
7403 * ACTIVE iterator iteration won't change them (because given same input
7404 * states we'll end up with exactly same output states which we are currently
7405 * comparing; and verification after the loop already propagated back what
7406 * needs to be **additionally** tracked as precise). It's subtle, grok
7407 * precision tracking for more intuitive understanding.
7409 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7410 struct bpf_kfunc_call_arg_meta *meta)
7412 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7413 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7414 struct bpf_reg_state *cur_iter, *queued_iter;
7415 int iter_frameno = meta->iter.frameno;
7416 int iter_spi = meta->iter.spi;
7418 BTF_TYPE_EMIT(struct bpf_iter);
7420 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7422 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7423 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7424 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7425 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7429 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7430 /* branch out active iter state */
7431 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7435 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7436 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7437 queued_iter->iter.depth++;
7439 queued_fr = queued_st->frame[queued_st->curframe];
7440 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7443 /* switch to DRAINED state, but keep the depth unchanged */
7444 /* mark current iter state as drained and assume returned NULL */
7445 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7446 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7451 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7453 return type == ARG_CONST_SIZE ||
7454 type == ARG_CONST_SIZE_OR_ZERO;
7457 static bool arg_type_is_release(enum bpf_arg_type type)
7459 return type & OBJ_RELEASE;
7462 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7464 return base_type(type) == ARG_PTR_TO_DYNPTR;
7467 static int int_ptr_type_to_size(enum bpf_arg_type type)
7469 if (type == ARG_PTR_TO_INT)
7471 else if (type == ARG_PTR_TO_LONG)
7477 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7478 const struct bpf_call_arg_meta *meta,
7479 enum bpf_arg_type *arg_type)
7481 if (!meta->map_ptr) {
7482 /* kernel subsystem misconfigured verifier */
7483 verbose(env, "invalid map_ptr to access map->type\n");
7487 switch (meta->map_ptr->map_type) {
7488 case BPF_MAP_TYPE_SOCKMAP:
7489 case BPF_MAP_TYPE_SOCKHASH:
7490 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7491 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7493 verbose(env, "invalid arg_type for sockmap/sockhash\n");
7497 case BPF_MAP_TYPE_BLOOM_FILTER:
7498 if (meta->func_id == BPF_FUNC_map_peek_elem)
7499 *arg_type = ARG_PTR_TO_MAP_VALUE;
7507 struct bpf_reg_types {
7508 const enum bpf_reg_type types[10];
7512 static const struct bpf_reg_types sock_types = {
7522 static const struct bpf_reg_types btf_id_sock_common_types = {
7529 PTR_TO_BTF_ID | PTR_TRUSTED,
7531 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7535 static const struct bpf_reg_types mem_types = {
7543 PTR_TO_MEM | MEM_RINGBUF,
7545 PTR_TO_BTF_ID | PTR_TRUSTED,
7549 static const struct bpf_reg_types int_ptr_types = {
7559 static const struct bpf_reg_types spin_lock_types = {
7562 PTR_TO_BTF_ID | MEM_ALLOC,
7566 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7567 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7568 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7569 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7570 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7571 static const struct bpf_reg_types btf_ptr_types = {
7574 PTR_TO_BTF_ID | PTR_TRUSTED,
7575 PTR_TO_BTF_ID | MEM_RCU,
7578 static const struct bpf_reg_types percpu_btf_ptr_types = {
7580 PTR_TO_BTF_ID | MEM_PERCPU,
7581 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7584 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7585 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7586 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7587 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7588 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7589 static const struct bpf_reg_types dynptr_types = {
7592 CONST_PTR_TO_DYNPTR,
7596 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7597 [ARG_PTR_TO_MAP_KEY] = &mem_types,
7598 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
7599 [ARG_CONST_SIZE] = &scalar_types,
7600 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
7601 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
7602 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
7603 [ARG_PTR_TO_CTX] = &context_types,
7604 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
7606 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
7608 [ARG_PTR_TO_SOCKET] = &fullsock_types,
7609 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
7610 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
7611 [ARG_PTR_TO_MEM] = &mem_types,
7612 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
7613 [ARG_PTR_TO_INT] = &int_ptr_types,
7614 [ARG_PTR_TO_LONG] = &int_ptr_types,
7615 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
7616 [ARG_PTR_TO_FUNC] = &func_ptr_types,
7617 [ARG_PTR_TO_STACK] = &stack_ptr_types,
7618 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
7619 [ARG_PTR_TO_TIMER] = &timer_types,
7620 [ARG_PTR_TO_KPTR] = &kptr_types,
7621 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
7624 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7625 enum bpf_arg_type arg_type,
7626 const u32 *arg_btf_id,
7627 struct bpf_call_arg_meta *meta)
7629 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7630 enum bpf_reg_type expected, type = reg->type;
7631 const struct bpf_reg_types *compatible;
7634 compatible = compatible_reg_types[base_type(arg_type)];
7636 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7640 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7641 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7643 * Same for MAYBE_NULL:
7645 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7646 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7648 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7650 * Therefore we fold these flags depending on the arg_type before comparison.
7652 if (arg_type & MEM_RDONLY)
7653 type &= ~MEM_RDONLY;
7654 if (arg_type & PTR_MAYBE_NULL)
7655 type &= ~PTR_MAYBE_NULL;
7656 if (base_type(arg_type) == ARG_PTR_TO_MEM)
7657 type &= ~DYNPTR_TYPE_FLAG_MASK;
7659 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
7662 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7663 expected = compatible->types[i];
7664 if (expected == NOT_INIT)
7667 if (type == expected)
7671 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7672 for (j = 0; j + 1 < i; j++)
7673 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7674 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7678 if (base_type(reg->type) != PTR_TO_BTF_ID)
7681 if (compatible == &mem_types) {
7682 if (!(arg_type & MEM_RDONLY)) {
7684 "%s() may write into memory pointed by R%d type=%s\n",
7685 func_id_name(meta->func_id),
7686 regno, reg_type_str(env, reg->type));
7692 switch ((int)reg->type) {
7694 case PTR_TO_BTF_ID | PTR_TRUSTED:
7695 case PTR_TO_BTF_ID | MEM_RCU:
7696 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7697 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7699 /* For bpf_sk_release, it needs to match against first member
7700 * 'struct sock_common', hence make an exception for it. This
7701 * allows bpf_sk_release to work for multiple socket types.
7703 bool strict_type_match = arg_type_is_release(arg_type) &&
7704 meta->func_id != BPF_FUNC_sk_release;
7706 if (type_may_be_null(reg->type) &&
7707 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7708 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7713 if (!compatible->btf_id) {
7714 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7717 arg_btf_id = compatible->btf_id;
7720 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7721 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7724 if (arg_btf_id == BPF_PTR_POISON) {
7725 verbose(env, "verifier internal error:");
7726 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7731 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7732 btf_vmlinux, *arg_btf_id,
7733 strict_type_match)) {
7734 verbose(env, "R%d is of type %s but %s is expected\n",
7735 regno, btf_type_name(reg->btf, reg->btf_id),
7736 btf_type_name(btf_vmlinux, *arg_btf_id));
7742 case PTR_TO_BTF_ID | MEM_ALLOC:
7743 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7744 meta->func_id != BPF_FUNC_kptr_xchg) {
7745 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7748 /* Handled by helper specific checks */
7750 case PTR_TO_BTF_ID | MEM_PERCPU:
7751 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7752 /* Handled by helper specific checks */
7755 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7761 static struct btf_field *
7762 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7764 struct btf_field *field;
7765 struct btf_record *rec;
7767 rec = reg_btf_record(reg);
7771 field = btf_record_find(rec, off, fields);
7778 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7779 const struct bpf_reg_state *reg, int regno,
7780 enum bpf_arg_type arg_type)
7782 u32 type = reg->type;
7784 /* When referenced register is passed to release function, its fixed
7787 * We will check arg_type_is_release reg has ref_obj_id when storing
7788 * meta->release_regno.
7790 if (arg_type_is_release(arg_type)) {
7791 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7792 * may not directly point to the object being released, but to
7793 * dynptr pointing to such object, which might be at some offset
7794 * on the stack. In that case, we simply to fallback to the
7797 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7800 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7801 if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7802 return __check_ptr_off_reg(env, reg, regno, true);
7804 verbose(env, "R%d must have zero offset when passed to release func\n",
7806 verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7807 btf_type_name(reg->btf, reg->btf_id), reg->off);
7811 /* Doing check_ptr_off_reg check for the offset will catch this
7812 * because fixed_off_ok is false, but checking here allows us
7813 * to give the user a better error message.
7816 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7820 return __check_ptr_off_reg(env, reg, regno, false);
7824 /* Pointer types where both fixed and variable offset is explicitly allowed: */
7827 case PTR_TO_PACKET_META:
7828 case PTR_TO_MAP_KEY:
7829 case PTR_TO_MAP_VALUE:
7831 case PTR_TO_MEM | MEM_RDONLY:
7832 case PTR_TO_MEM | MEM_RINGBUF:
7834 case PTR_TO_BUF | MEM_RDONLY:
7837 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
7841 case PTR_TO_BTF_ID | MEM_ALLOC:
7842 case PTR_TO_BTF_ID | PTR_TRUSTED:
7843 case PTR_TO_BTF_ID | MEM_RCU:
7844 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
7845 /* When referenced PTR_TO_BTF_ID is passed to release function,
7846 * its fixed offset must be 0. In the other cases, fixed offset
7847 * can be non-zero. This was already checked above. So pass
7848 * fixed_off_ok as true to allow fixed offset for all other
7849 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
7850 * still need to do checks instead of returning.
7852 return __check_ptr_off_reg(env, reg, regno, true);
7854 return __check_ptr_off_reg(env, reg, regno, false);
7858 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
7859 const struct bpf_func_proto *fn,
7860 struct bpf_reg_state *regs)
7862 struct bpf_reg_state *state = NULL;
7865 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
7866 if (arg_type_is_dynptr(fn->arg_type[i])) {
7868 verbose(env, "verifier internal error: multiple dynptr args\n");
7871 state = ®s[BPF_REG_1 + i];
7875 verbose(env, "verifier internal error: no dynptr arg found\n");
7880 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7882 struct bpf_func_state *state = func(env, reg);
7885 if (reg->type == CONST_PTR_TO_DYNPTR)
7887 spi = dynptr_get_spi(env, reg);
7890 return state->stack[spi].spilled_ptr.id;
7893 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7895 struct bpf_func_state *state = func(env, reg);
7898 if (reg->type == CONST_PTR_TO_DYNPTR)
7899 return reg->ref_obj_id;
7900 spi = dynptr_get_spi(env, reg);
7903 return state->stack[spi].spilled_ptr.ref_obj_id;
7906 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
7907 struct bpf_reg_state *reg)
7909 struct bpf_func_state *state = func(env, reg);
7912 if (reg->type == CONST_PTR_TO_DYNPTR)
7913 return reg->dynptr.type;
7915 spi = __get_spi(reg->off);
7917 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
7918 return BPF_DYNPTR_TYPE_INVALID;
7921 return state->stack[spi].spilled_ptr.dynptr.type;
7924 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
7925 struct bpf_call_arg_meta *meta,
7926 const struct bpf_func_proto *fn,
7929 u32 regno = BPF_REG_1 + arg;
7930 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7931 enum bpf_arg_type arg_type = fn->arg_type[arg];
7932 enum bpf_reg_type type = reg->type;
7933 u32 *arg_btf_id = NULL;
7936 if (arg_type == ARG_DONTCARE)
7939 err = check_reg_arg(env, regno, SRC_OP);
7943 if (arg_type == ARG_ANYTHING) {
7944 if (is_pointer_value(env, regno)) {
7945 verbose(env, "R%d leaks addr into helper function\n",
7952 if (type_is_pkt_pointer(type) &&
7953 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
7954 verbose(env, "helper access to the packet is not allowed\n");
7958 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
7959 err = resolve_map_arg_type(env, meta, &arg_type);
7964 if (register_is_null(reg) && type_may_be_null(arg_type))
7965 /* A NULL register has a SCALAR_VALUE type, so skip
7968 goto skip_type_check;
7970 /* arg_btf_id and arg_size are in a union. */
7971 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
7972 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
7973 arg_btf_id = fn->arg_btf_id[arg];
7975 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
7979 err = check_func_arg_reg_off(env, reg, regno, arg_type);
7984 if (arg_type_is_release(arg_type)) {
7985 if (arg_type_is_dynptr(arg_type)) {
7986 struct bpf_func_state *state = func(env, reg);
7989 /* Only dynptr created on stack can be released, thus
7990 * the get_spi and stack state checks for spilled_ptr
7991 * should only be done before process_dynptr_func for
7994 if (reg->type == PTR_TO_STACK) {
7995 spi = dynptr_get_spi(env, reg);
7996 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
7997 verbose(env, "arg %d is an unacquired reference\n", regno);
8001 verbose(env, "cannot release unowned const bpf_dynptr\n");
8004 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8005 verbose(env, "R%d must be referenced when passed to release function\n",
8009 if (meta->release_regno) {
8010 verbose(env, "verifier internal error: more than one release argument\n");
8013 meta->release_regno = regno;
8016 if (reg->ref_obj_id) {
8017 if (meta->ref_obj_id) {
8018 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8019 regno, reg->ref_obj_id,
8023 meta->ref_obj_id = reg->ref_obj_id;
8026 switch (base_type(arg_type)) {
8027 case ARG_CONST_MAP_PTR:
8028 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8029 if (meta->map_ptr) {
8030 /* Use map_uid (which is unique id of inner map) to reject:
8031 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8032 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8033 * if (inner_map1 && inner_map2) {
8034 * timer = bpf_map_lookup_elem(inner_map1);
8036 * // mismatch would have been allowed
8037 * bpf_timer_init(timer, inner_map2);
8040 * Comparing map_ptr is enough to distinguish normal and outer maps.
8042 if (meta->map_ptr != reg->map_ptr ||
8043 meta->map_uid != reg->map_uid) {
8045 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8046 meta->map_uid, reg->map_uid);
8050 meta->map_ptr = reg->map_ptr;
8051 meta->map_uid = reg->map_uid;
8053 case ARG_PTR_TO_MAP_KEY:
8054 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8055 * check that [key, key + map->key_size) are within
8056 * stack limits and initialized
8058 if (!meta->map_ptr) {
8059 /* in function declaration map_ptr must come before
8060 * map_key, so that it's verified and known before
8061 * we have to check map_key here. Otherwise it means
8062 * that kernel subsystem misconfigured verifier
8064 verbose(env, "invalid map_ptr to access map->key\n");
8067 err = check_helper_mem_access(env, regno,
8068 meta->map_ptr->key_size, false,
8071 case ARG_PTR_TO_MAP_VALUE:
8072 if (type_may_be_null(arg_type) && register_is_null(reg))
8075 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8076 * check [value, value + map->value_size) validity
8078 if (!meta->map_ptr) {
8079 /* kernel subsystem misconfigured verifier */
8080 verbose(env, "invalid map_ptr to access map->value\n");
8083 meta->raw_mode = arg_type & MEM_UNINIT;
8084 err = check_helper_mem_access(env, regno,
8085 meta->map_ptr->value_size, false,
8088 case ARG_PTR_TO_PERCPU_BTF_ID:
8090 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8093 meta->ret_btf = reg->btf;
8094 meta->ret_btf_id = reg->btf_id;
8096 case ARG_PTR_TO_SPIN_LOCK:
8097 if (in_rbtree_lock_required_cb(env)) {
8098 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8101 if (meta->func_id == BPF_FUNC_spin_lock) {
8102 err = process_spin_lock(env, regno, true);
8105 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8106 err = process_spin_lock(env, regno, false);
8110 verbose(env, "verifier internal error\n");
8114 case ARG_PTR_TO_TIMER:
8115 err = process_timer_func(env, regno, meta);
8119 case ARG_PTR_TO_FUNC:
8120 meta->subprogno = reg->subprogno;
8122 case ARG_PTR_TO_MEM:
8123 /* The access to this pointer is only checked when we hit the
8124 * next is_mem_size argument below.
8126 meta->raw_mode = arg_type & MEM_UNINIT;
8127 if (arg_type & MEM_FIXED_SIZE) {
8128 err = check_helper_mem_access(env, regno,
8129 fn->arg_size[arg], false,
8133 case ARG_CONST_SIZE:
8134 err = check_mem_size_reg(env, reg, regno, false, meta);
8136 case ARG_CONST_SIZE_OR_ZERO:
8137 err = check_mem_size_reg(env, reg, regno, true, meta);
8139 case ARG_PTR_TO_DYNPTR:
8140 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8144 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8145 if (!tnum_is_const(reg->var_off)) {
8146 verbose(env, "R%d is not a known constant'\n",
8150 meta->mem_size = reg->var_off.value;
8151 err = mark_chain_precision(env, regno);
8155 case ARG_PTR_TO_INT:
8156 case ARG_PTR_TO_LONG:
8158 int size = int_ptr_type_to_size(arg_type);
8160 err = check_helper_mem_access(env, regno, size, false, meta);
8163 err = check_ptr_alignment(env, reg, 0, size, true);
8166 case ARG_PTR_TO_CONST_STR:
8168 struct bpf_map *map = reg->map_ptr;
8173 if (!bpf_map_is_rdonly(map)) {
8174 verbose(env, "R%d does not point to a readonly map'\n", regno);
8178 if (!tnum_is_const(reg->var_off)) {
8179 verbose(env, "R%d is not a constant address'\n", regno);
8183 if (!map->ops->map_direct_value_addr) {
8184 verbose(env, "no direct value access support for this map type\n");
8188 err = check_map_access(env, regno, reg->off,
8189 map->value_size - reg->off, false,
8194 map_off = reg->off + reg->var_off.value;
8195 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8197 verbose(env, "direct value access on string failed\n");
8201 str_ptr = (char *)(long)(map_addr);
8202 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8203 verbose(env, "string is not zero-terminated\n");
8208 case ARG_PTR_TO_KPTR:
8209 err = process_kptr_func(env, regno, meta);
8218 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8220 enum bpf_attach_type eatype = env->prog->expected_attach_type;
8221 enum bpf_prog_type type = resolve_prog_type(env->prog);
8223 if (func_id != BPF_FUNC_map_update_elem)
8226 /* It's not possible to get access to a locked struct sock in these
8227 * contexts, so updating is safe.
8230 case BPF_PROG_TYPE_TRACING:
8231 if (eatype == BPF_TRACE_ITER)
8234 case BPF_PROG_TYPE_SOCKET_FILTER:
8235 case BPF_PROG_TYPE_SCHED_CLS:
8236 case BPF_PROG_TYPE_SCHED_ACT:
8237 case BPF_PROG_TYPE_XDP:
8238 case BPF_PROG_TYPE_SK_REUSEPORT:
8239 case BPF_PROG_TYPE_FLOW_DISSECTOR:
8240 case BPF_PROG_TYPE_SK_LOOKUP:
8246 verbose(env, "cannot update sockmap in this context\n");
8250 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8252 return env->prog->jit_requested &&
8253 bpf_jit_supports_subprog_tailcalls();
8256 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8257 struct bpf_map *map, int func_id)
8262 /* We need a two way check, first is from map perspective ... */
8263 switch (map->map_type) {
8264 case BPF_MAP_TYPE_PROG_ARRAY:
8265 if (func_id != BPF_FUNC_tail_call)
8268 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8269 if (func_id != BPF_FUNC_perf_event_read &&
8270 func_id != BPF_FUNC_perf_event_output &&
8271 func_id != BPF_FUNC_skb_output &&
8272 func_id != BPF_FUNC_perf_event_read_value &&
8273 func_id != BPF_FUNC_xdp_output)
8276 case BPF_MAP_TYPE_RINGBUF:
8277 if (func_id != BPF_FUNC_ringbuf_output &&
8278 func_id != BPF_FUNC_ringbuf_reserve &&
8279 func_id != BPF_FUNC_ringbuf_query &&
8280 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8281 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8282 func_id != BPF_FUNC_ringbuf_discard_dynptr)
8285 case BPF_MAP_TYPE_USER_RINGBUF:
8286 if (func_id != BPF_FUNC_user_ringbuf_drain)
8289 case BPF_MAP_TYPE_STACK_TRACE:
8290 if (func_id != BPF_FUNC_get_stackid)
8293 case BPF_MAP_TYPE_CGROUP_ARRAY:
8294 if (func_id != BPF_FUNC_skb_under_cgroup &&
8295 func_id != BPF_FUNC_current_task_under_cgroup)
8298 case BPF_MAP_TYPE_CGROUP_STORAGE:
8299 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8300 if (func_id != BPF_FUNC_get_local_storage)
8303 case BPF_MAP_TYPE_DEVMAP:
8304 case BPF_MAP_TYPE_DEVMAP_HASH:
8305 if (func_id != BPF_FUNC_redirect_map &&
8306 func_id != BPF_FUNC_map_lookup_elem)
8309 /* Restrict bpf side of cpumap and xskmap, open when use-cases
8312 case BPF_MAP_TYPE_CPUMAP:
8313 if (func_id != BPF_FUNC_redirect_map)
8316 case BPF_MAP_TYPE_XSKMAP:
8317 if (func_id != BPF_FUNC_redirect_map &&
8318 func_id != BPF_FUNC_map_lookup_elem)
8321 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8322 case BPF_MAP_TYPE_HASH_OF_MAPS:
8323 if (func_id != BPF_FUNC_map_lookup_elem)
8326 case BPF_MAP_TYPE_SOCKMAP:
8327 if (func_id != BPF_FUNC_sk_redirect_map &&
8328 func_id != BPF_FUNC_sock_map_update &&
8329 func_id != BPF_FUNC_map_delete_elem &&
8330 func_id != BPF_FUNC_msg_redirect_map &&
8331 func_id != BPF_FUNC_sk_select_reuseport &&
8332 func_id != BPF_FUNC_map_lookup_elem &&
8333 !may_update_sockmap(env, func_id))
8336 case BPF_MAP_TYPE_SOCKHASH:
8337 if (func_id != BPF_FUNC_sk_redirect_hash &&
8338 func_id != BPF_FUNC_sock_hash_update &&
8339 func_id != BPF_FUNC_map_delete_elem &&
8340 func_id != BPF_FUNC_msg_redirect_hash &&
8341 func_id != BPF_FUNC_sk_select_reuseport &&
8342 func_id != BPF_FUNC_map_lookup_elem &&
8343 !may_update_sockmap(env, func_id))
8346 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8347 if (func_id != BPF_FUNC_sk_select_reuseport)
8350 case BPF_MAP_TYPE_QUEUE:
8351 case BPF_MAP_TYPE_STACK:
8352 if (func_id != BPF_FUNC_map_peek_elem &&
8353 func_id != BPF_FUNC_map_pop_elem &&
8354 func_id != BPF_FUNC_map_push_elem)
8357 case BPF_MAP_TYPE_SK_STORAGE:
8358 if (func_id != BPF_FUNC_sk_storage_get &&
8359 func_id != BPF_FUNC_sk_storage_delete &&
8360 func_id != BPF_FUNC_kptr_xchg)
8363 case BPF_MAP_TYPE_INODE_STORAGE:
8364 if (func_id != BPF_FUNC_inode_storage_get &&
8365 func_id != BPF_FUNC_inode_storage_delete &&
8366 func_id != BPF_FUNC_kptr_xchg)
8369 case BPF_MAP_TYPE_TASK_STORAGE:
8370 if (func_id != BPF_FUNC_task_storage_get &&
8371 func_id != BPF_FUNC_task_storage_delete &&
8372 func_id != BPF_FUNC_kptr_xchg)
8375 case BPF_MAP_TYPE_CGRP_STORAGE:
8376 if (func_id != BPF_FUNC_cgrp_storage_get &&
8377 func_id != BPF_FUNC_cgrp_storage_delete &&
8378 func_id != BPF_FUNC_kptr_xchg)
8381 case BPF_MAP_TYPE_BLOOM_FILTER:
8382 if (func_id != BPF_FUNC_map_peek_elem &&
8383 func_id != BPF_FUNC_map_push_elem)
8390 /* ... and second from the function itself. */
8392 case BPF_FUNC_tail_call:
8393 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8395 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8396 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8400 case BPF_FUNC_perf_event_read:
8401 case BPF_FUNC_perf_event_output:
8402 case BPF_FUNC_perf_event_read_value:
8403 case BPF_FUNC_skb_output:
8404 case BPF_FUNC_xdp_output:
8405 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8408 case BPF_FUNC_ringbuf_output:
8409 case BPF_FUNC_ringbuf_reserve:
8410 case BPF_FUNC_ringbuf_query:
8411 case BPF_FUNC_ringbuf_reserve_dynptr:
8412 case BPF_FUNC_ringbuf_submit_dynptr:
8413 case BPF_FUNC_ringbuf_discard_dynptr:
8414 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8417 case BPF_FUNC_user_ringbuf_drain:
8418 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8421 case BPF_FUNC_get_stackid:
8422 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8425 case BPF_FUNC_current_task_under_cgroup:
8426 case BPF_FUNC_skb_under_cgroup:
8427 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8430 case BPF_FUNC_redirect_map:
8431 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8432 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8433 map->map_type != BPF_MAP_TYPE_CPUMAP &&
8434 map->map_type != BPF_MAP_TYPE_XSKMAP)
8437 case BPF_FUNC_sk_redirect_map:
8438 case BPF_FUNC_msg_redirect_map:
8439 case BPF_FUNC_sock_map_update:
8440 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8443 case BPF_FUNC_sk_redirect_hash:
8444 case BPF_FUNC_msg_redirect_hash:
8445 case BPF_FUNC_sock_hash_update:
8446 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8449 case BPF_FUNC_get_local_storage:
8450 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8451 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8454 case BPF_FUNC_sk_select_reuseport:
8455 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8456 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8457 map->map_type != BPF_MAP_TYPE_SOCKHASH)
8460 case BPF_FUNC_map_pop_elem:
8461 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8462 map->map_type != BPF_MAP_TYPE_STACK)
8465 case BPF_FUNC_map_peek_elem:
8466 case BPF_FUNC_map_push_elem:
8467 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8468 map->map_type != BPF_MAP_TYPE_STACK &&
8469 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8472 case BPF_FUNC_map_lookup_percpu_elem:
8473 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8474 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8475 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8478 case BPF_FUNC_sk_storage_get:
8479 case BPF_FUNC_sk_storage_delete:
8480 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8483 case BPF_FUNC_inode_storage_get:
8484 case BPF_FUNC_inode_storage_delete:
8485 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8488 case BPF_FUNC_task_storage_get:
8489 case BPF_FUNC_task_storage_delete:
8490 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8493 case BPF_FUNC_cgrp_storage_get:
8494 case BPF_FUNC_cgrp_storage_delete:
8495 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8504 verbose(env, "cannot pass map_type %d into func %s#%d\n",
8505 map->map_type, func_id_name(func_id), func_id);
8509 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8513 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8515 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8517 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8519 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8521 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8524 /* We only support one arg being in raw mode at the moment,
8525 * which is sufficient for the helper functions we have
8531 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8533 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8534 bool has_size = fn->arg_size[arg] != 0;
8535 bool is_next_size = false;
8537 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8538 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8540 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8541 return is_next_size;
8543 return has_size == is_next_size || is_next_size == is_fixed;
8546 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8548 /* bpf_xxx(..., buf, len) call will access 'len'
8549 * bytes from memory 'buf'. Both arg types need
8550 * to be paired, so make sure there's no buggy
8551 * helper function specification.
8553 if (arg_type_is_mem_size(fn->arg1_type) ||
8554 check_args_pair_invalid(fn, 0) ||
8555 check_args_pair_invalid(fn, 1) ||
8556 check_args_pair_invalid(fn, 2) ||
8557 check_args_pair_invalid(fn, 3) ||
8558 check_args_pair_invalid(fn, 4))
8564 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8568 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8569 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8570 return !!fn->arg_btf_id[i];
8571 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8572 return fn->arg_btf_id[i] == BPF_PTR_POISON;
8573 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8574 /* arg_btf_id and arg_size are in a union. */
8575 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8576 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8583 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8585 return check_raw_mode_ok(fn) &&
8586 check_arg_pair_ok(fn) &&
8587 check_btf_id_ok(fn) ? 0 : -EINVAL;
8590 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8591 * are now invalid, so turn them into unknown SCALAR_VALUE.
8593 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8594 * since these slices point to packet data.
8596 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8598 struct bpf_func_state *state;
8599 struct bpf_reg_state *reg;
8601 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8602 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8603 mark_reg_invalid(env, reg);
8609 BEYOND_PKT_END = -2,
8612 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8614 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8615 struct bpf_reg_state *reg = &state->regs[regn];
8617 if (reg->type != PTR_TO_PACKET)
8618 /* PTR_TO_PACKET_META is not supported yet */
8621 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8622 * How far beyond pkt_end it goes is unknown.
8623 * if (!range_open) it's the case of pkt >= pkt_end
8624 * if (range_open) it's the case of pkt > pkt_end
8625 * hence this pointer is at least 1 byte bigger than pkt_end
8628 reg->range = BEYOND_PKT_END;
8630 reg->range = AT_PKT_END;
8633 /* The pointer with the specified id has released its reference to kernel
8634 * resources. Identify all copies of the same pointer and clear the reference.
8636 static int release_reference(struct bpf_verifier_env *env,
8639 struct bpf_func_state *state;
8640 struct bpf_reg_state *reg;
8643 err = release_reference_state(cur_func(env), ref_obj_id);
8647 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8648 if (reg->ref_obj_id == ref_obj_id)
8649 mark_reg_invalid(env, reg);
8655 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8657 struct bpf_func_state *unused;
8658 struct bpf_reg_state *reg;
8660 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8661 if (type_is_non_owning_ref(reg->type))
8662 mark_reg_invalid(env, reg);
8666 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8667 struct bpf_reg_state *regs)
8671 /* after the call registers r0 - r5 were scratched */
8672 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8673 mark_reg_not_init(env, regs, caller_saved[i]);
8674 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8678 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8679 struct bpf_func_state *caller,
8680 struct bpf_func_state *callee,
8683 static int set_callee_state(struct bpf_verifier_env *env,
8684 struct bpf_func_state *caller,
8685 struct bpf_func_state *callee, int insn_idx);
8687 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8688 int *insn_idx, int subprog,
8689 set_callee_state_fn set_callee_state_cb)
8691 struct bpf_verifier_state *state = env->cur_state;
8692 struct bpf_func_state *caller, *callee;
8695 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8696 verbose(env, "the call stack of %d frames is too deep\n",
8697 state->curframe + 2);
8701 caller = state->frame[state->curframe];
8702 if (state->frame[state->curframe + 1]) {
8703 verbose(env, "verifier bug. Frame %d already allocated\n",
8704 state->curframe + 1);
8708 err = btf_check_subprog_call(env, subprog, caller->regs);
8711 if (subprog_is_global(env, subprog)) {
8713 verbose(env, "Caller passes invalid args into func#%d\n",
8717 if (env->log.level & BPF_LOG_LEVEL)
8719 "Func#%d is global and valid. Skipping.\n",
8721 clear_caller_saved_regs(env, caller->regs);
8723 /* All global functions return a 64-bit SCALAR_VALUE */
8724 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8725 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8727 /* continue with next insn after call */
8732 /* set_callee_state is used for direct subprog calls, but we are
8733 * interested in validating only BPF helpers that can call subprogs as
8736 if (set_callee_state_cb != set_callee_state) {
8737 if (bpf_pseudo_kfunc_call(insn) &&
8738 !is_callback_calling_kfunc(insn->imm)) {
8739 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8740 func_id_name(insn->imm), insn->imm);
8742 } else if (!bpf_pseudo_kfunc_call(insn) &&
8743 !is_callback_calling_function(insn->imm)) { /* helper */
8744 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8745 func_id_name(insn->imm), insn->imm);
8750 if (insn->code == (BPF_JMP | BPF_CALL) &&
8751 insn->src_reg == 0 &&
8752 insn->imm == BPF_FUNC_timer_set_callback) {
8753 struct bpf_verifier_state *async_cb;
8755 /* there is no real recursion here. timer callbacks are async */
8756 env->subprog_info[subprog].is_async_cb = true;
8757 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8758 *insn_idx, subprog);
8761 callee = async_cb->frame[0];
8762 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8764 /* Convert bpf_timer_set_callback() args into timer callback args */
8765 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8769 clear_caller_saved_regs(env, caller->regs);
8770 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8771 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8772 /* continue with next insn after call */
8776 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8779 state->frame[state->curframe + 1] = callee;
8781 /* callee cannot access r0, r6 - r9 for reading and has to write
8782 * into its own stack before reading from it.
8783 * callee can read/write into caller's stack
8785 init_func_state(env, callee,
8786 /* remember the callsite, it will be used by bpf_exit */
8787 *insn_idx /* callsite */,
8788 state->curframe + 1 /* frameno within this callchain */,
8789 subprog /* subprog number within this prog */);
8791 /* Transfer references to the callee */
8792 err = copy_reference_state(callee, caller);
8796 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8800 clear_caller_saved_regs(env, caller->regs);
8802 /* only increment it after check_reg_arg() finished */
8805 /* and go analyze first insn of the callee */
8806 *insn_idx = env->subprog_info[subprog].start - 1;
8808 if (env->log.level & BPF_LOG_LEVEL) {
8809 verbose(env, "caller:\n");
8810 print_verifier_state(env, caller, true);
8811 verbose(env, "callee:\n");
8812 print_verifier_state(env, callee, true);
8817 free_func_state(callee);
8818 state->frame[state->curframe + 1] = NULL;
8822 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8823 struct bpf_func_state *caller,
8824 struct bpf_func_state *callee)
8826 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8827 * void *callback_ctx, u64 flags);
8828 * callback_fn(struct bpf_map *map, void *key, void *value,
8829 * void *callback_ctx);
8831 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8833 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8834 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8835 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8837 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8838 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8839 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8841 /* pointer to stack or null */
8842 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
8845 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8849 static int set_callee_state(struct bpf_verifier_env *env,
8850 struct bpf_func_state *caller,
8851 struct bpf_func_state *callee, int insn_idx)
8855 /* copy r1 - r5 args that callee can access. The copy includes parent
8856 * pointers, which connects us up to the liveness chain
8858 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
8859 callee->regs[i] = caller->regs[i];
8863 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8866 int subprog, target_insn;
8868 target_insn = *insn_idx + insn->imm + 1;
8869 subprog = find_subprog(env, target_insn);
8871 verbose(env, "verifier bug. No program starts at insn %d\n",
8876 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
8879 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
8880 struct bpf_func_state *caller,
8881 struct bpf_func_state *callee,
8884 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
8885 struct bpf_map *map;
8888 if (bpf_map_ptr_poisoned(insn_aux)) {
8889 verbose(env, "tail_call abusing map_ptr\n");
8893 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
8894 if (!map->ops->map_set_for_each_callback_args ||
8895 !map->ops->map_for_each_callback) {
8896 verbose(env, "callback function not allowed for map\n");
8900 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
8904 callee->in_callback_fn = true;
8905 callee->callback_ret_range = tnum_range(0, 1);
8909 static int set_loop_callback_state(struct bpf_verifier_env *env,
8910 struct bpf_func_state *caller,
8911 struct bpf_func_state *callee,
8914 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
8916 * callback_fn(u32 index, void *callback_ctx);
8918 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
8919 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8922 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8923 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8924 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8926 callee->in_callback_fn = true;
8927 callee->callback_ret_range = tnum_range(0, 1);
8931 static int set_timer_callback_state(struct bpf_verifier_env *env,
8932 struct bpf_func_state *caller,
8933 struct bpf_func_state *callee,
8936 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
8938 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
8939 * callback_fn(struct bpf_map *map, void *key, void *value);
8941 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
8942 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
8943 callee->regs[BPF_REG_1].map_ptr = map_ptr;
8945 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8946 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8947 callee->regs[BPF_REG_2].map_ptr = map_ptr;
8949 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8950 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8951 callee->regs[BPF_REG_3].map_ptr = map_ptr;
8954 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8955 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8956 callee->in_async_callback_fn = true;
8957 callee->callback_ret_range = tnum_range(0, 1);
8961 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
8962 struct bpf_func_state *caller,
8963 struct bpf_func_state *callee,
8966 /* bpf_find_vma(struct task_struct *task, u64 addr,
8967 * void *callback_fn, void *callback_ctx, u64 flags)
8968 * (callback_fn)(struct task_struct *task,
8969 * struct vm_area_struct *vma, void *callback_ctx);
8971 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8973 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
8974 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8975 callee->regs[BPF_REG_2].btf = btf_vmlinux;
8976 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
8978 /* pointer to stack or null */
8979 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
8982 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8983 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8984 callee->in_callback_fn = true;
8985 callee->callback_ret_range = tnum_range(0, 1);
8989 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
8990 struct bpf_func_state *caller,
8991 struct bpf_func_state *callee,
8994 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
8995 * callback_ctx, u64 flags);
8996 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
8998 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
8999 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9000 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9003 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9004 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9005 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9007 callee->in_callback_fn = true;
9008 callee->callback_ret_range = tnum_range(0, 1);
9012 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9013 struct bpf_func_state *caller,
9014 struct bpf_func_state *callee,
9017 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9018 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9020 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9021 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9022 * by this point, so look at 'root'
9024 struct btf_field *field;
9026 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9028 if (!field || !field->graph_root.value_btf_id)
9031 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9032 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9033 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9034 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9036 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9037 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9038 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9039 callee->in_callback_fn = true;
9040 callee->callback_ret_range = tnum_range(0, 1);
9044 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9046 /* Are we currently verifying the callback for a rbtree helper that must
9047 * be called with lock held? If so, no need to complain about unreleased
9050 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9052 struct bpf_verifier_state *state = env->cur_state;
9053 struct bpf_insn *insn = env->prog->insnsi;
9054 struct bpf_func_state *callee;
9057 if (!state->curframe)
9060 callee = state->frame[state->curframe];
9062 if (!callee->in_callback_fn)
9065 kfunc_btf_id = insn[callee->callsite].imm;
9066 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9069 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9071 struct bpf_verifier_state *state = env->cur_state;
9072 struct bpf_func_state *caller, *callee;
9073 struct bpf_reg_state *r0;
9076 callee = state->frame[state->curframe];
9077 r0 = &callee->regs[BPF_REG_0];
9078 if (r0->type == PTR_TO_STACK) {
9079 /* technically it's ok to return caller's stack pointer
9080 * (or caller's caller's pointer) back to the caller,
9081 * since these pointers are valid. Only current stack
9082 * pointer will be invalid as soon as function exits,
9083 * but let's be conservative
9085 verbose(env, "cannot return stack pointer to the caller\n");
9089 caller = state->frame[state->curframe - 1];
9090 if (callee->in_callback_fn) {
9091 /* enforce R0 return value range [0, 1]. */
9092 struct tnum range = callee->callback_ret_range;
9094 if (r0->type != SCALAR_VALUE) {
9095 verbose(env, "R0 not a scalar value\n");
9098 if (!tnum_in(range, r0->var_off)) {
9099 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9103 /* return to the caller whatever r0 had in the callee */
9104 caller->regs[BPF_REG_0] = *r0;
9107 /* callback_fn frame should have released its own additions to parent's
9108 * reference state at this point, or check_reference_leak would
9109 * complain, hence it must be the same as the caller. There is no need
9112 if (!callee->in_callback_fn) {
9113 /* Transfer references to the caller */
9114 err = copy_reference_state(caller, callee);
9119 *insn_idx = callee->callsite + 1;
9120 if (env->log.level & BPF_LOG_LEVEL) {
9121 verbose(env, "returning from callee:\n");
9122 print_verifier_state(env, callee, true);
9123 verbose(env, "to caller at %d:\n", *insn_idx);
9124 print_verifier_state(env, caller, true);
9126 /* clear everything in the callee */
9127 free_func_state(callee);
9128 state->frame[state->curframe--] = NULL;
9132 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9134 struct bpf_call_arg_meta *meta)
9136 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
9138 if (ret_type != RET_INTEGER ||
9139 (func_id != BPF_FUNC_get_stack &&
9140 func_id != BPF_FUNC_get_task_stack &&
9141 func_id != BPF_FUNC_probe_read_str &&
9142 func_id != BPF_FUNC_probe_read_kernel_str &&
9143 func_id != BPF_FUNC_probe_read_user_str))
9146 ret_reg->smax_value = meta->msize_max_value;
9147 ret_reg->s32_max_value = meta->msize_max_value;
9148 ret_reg->smin_value = -MAX_ERRNO;
9149 ret_reg->s32_min_value = -MAX_ERRNO;
9150 reg_bounds_sync(ret_reg);
9154 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9155 int func_id, int insn_idx)
9157 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9158 struct bpf_map *map = meta->map_ptr;
9160 if (func_id != BPF_FUNC_tail_call &&
9161 func_id != BPF_FUNC_map_lookup_elem &&
9162 func_id != BPF_FUNC_map_update_elem &&
9163 func_id != BPF_FUNC_map_delete_elem &&
9164 func_id != BPF_FUNC_map_push_elem &&
9165 func_id != BPF_FUNC_map_pop_elem &&
9166 func_id != BPF_FUNC_map_peek_elem &&
9167 func_id != BPF_FUNC_for_each_map_elem &&
9168 func_id != BPF_FUNC_redirect_map &&
9169 func_id != BPF_FUNC_map_lookup_percpu_elem)
9173 verbose(env, "kernel subsystem misconfigured verifier\n");
9177 /* In case of read-only, some additional restrictions
9178 * need to be applied in order to prevent altering the
9179 * state of the map from program side.
9181 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9182 (func_id == BPF_FUNC_map_delete_elem ||
9183 func_id == BPF_FUNC_map_update_elem ||
9184 func_id == BPF_FUNC_map_push_elem ||
9185 func_id == BPF_FUNC_map_pop_elem)) {
9186 verbose(env, "write into map forbidden\n");
9190 if (!BPF_MAP_PTR(aux->map_ptr_state))
9191 bpf_map_ptr_store(aux, meta->map_ptr,
9192 !meta->map_ptr->bypass_spec_v1);
9193 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9194 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9195 !meta->map_ptr->bypass_spec_v1);
9200 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9201 int func_id, int insn_idx)
9203 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9204 struct bpf_reg_state *regs = cur_regs(env), *reg;
9205 struct bpf_map *map = meta->map_ptr;
9209 if (func_id != BPF_FUNC_tail_call)
9211 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9212 verbose(env, "kernel subsystem misconfigured verifier\n");
9216 reg = ®s[BPF_REG_3];
9217 val = reg->var_off.value;
9218 max = map->max_entries;
9220 if (!(register_is_const(reg) && val < max)) {
9221 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9225 err = mark_chain_precision(env, BPF_REG_3);
9228 if (bpf_map_key_unseen(aux))
9229 bpf_map_key_store(aux, val);
9230 else if (!bpf_map_key_poisoned(aux) &&
9231 bpf_map_key_immediate(aux) != val)
9232 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9236 static int check_reference_leak(struct bpf_verifier_env *env)
9238 struct bpf_func_state *state = cur_func(env);
9239 bool refs_lingering = false;
9242 if (state->frameno && !state->in_callback_fn)
9245 for (i = 0; i < state->acquired_refs; i++) {
9246 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9248 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9249 state->refs[i].id, state->refs[i].insn_idx);
9250 refs_lingering = true;
9252 return refs_lingering ? -EINVAL : 0;
9255 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9256 struct bpf_reg_state *regs)
9258 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
9259 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
9260 struct bpf_map *fmt_map = fmt_reg->map_ptr;
9261 struct bpf_bprintf_data data = {};
9262 int err, fmt_map_off, num_args;
9266 /* data must be an array of u64 */
9267 if (data_len_reg->var_off.value % 8)
9269 num_args = data_len_reg->var_off.value / 8;
9271 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9272 * and map_direct_value_addr is set.
9274 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9275 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9278 verbose(env, "verifier bug\n");
9281 fmt = (char *)(long)fmt_addr + fmt_map_off;
9283 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9284 * can focus on validating the format specifiers.
9286 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9288 verbose(env, "Invalid format string\n");
9293 static int check_get_func_ip(struct bpf_verifier_env *env)
9295 enum bpf_prog_type type = resolve_prog_type(env->prog);
9296 int func_id = BPF_FUNC_get_func_ip;
9298 if (type == BPF_PROG_TYPE_TRACING) {
9299 if (!bpf_prog_has_trampoline(env->prog)) {
9300 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9301 func_id_name(func_id), func_id);
9305 } else if (type == BPF_PROG_TYPE_KPROBE) {
9309 verbose(env, "func %s#%d not supported for program type %d\n",
9310 func_id_name(func_id), func_id, type);
9314 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9316 return &env->insn_aux_data[env->insn_idx];
9319 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9321 struct bpf_reg_state *regs = cur_regs(env);
9322 struct bpf_reg_state *reg = ®s[BPF_REG_4];
9323 bool reg_is_null = register_is_null(reg);
9326 mark_chain_precision(env, BPF_REG_4);
9331 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9333 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9335 if (!state->initialized) {
9336 state->initialized = 1;
9337 state->fit_for_inline = loop_flag_is_zero(env);
9338 state->callback_subprogno = subprogno;
9342 if (!state->fit_for_inline)
9345 state->fit_for_inline = (loop_flag_is_zero(env) &&
9346 state->callback_subprogno == subprogno);
9349 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9352 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9353 const struct bpf_func_proto *fn = NULL;
9354 enum bpf_return_type ret_type;
9355 enum bpf_type_flag ret_flag;
9356 struct bpf_reg_state *regs;
9357 struct bpf_call_arg_meta meta;
9358 int insn_idx = *insn_idx_p;
9360 int i, err, func_id;
9362 /* find function prototype */
9363 func_id = insn->imm;
9364 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9365 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9370 if (env->ops->get_func_proto)
9371 fn = env->ops->get_func_proto(func_id, env->prog);
9373 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9378 /* eBPF programs must be GPL compatible to use GPL-ed functions */
9379 if (!env->prog->gpl_compatible && fn->gpl_only) {
9380 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9384 if (fn->allowed && !fn->allowed(env->prog)) {
9385 verbose(env, "helper call is not allowed in probe\n");
9389 if (!env->prog->aux->sleepable && fn->might_sleep) {
9390 verbose(env, "helper call might sleep in a non-sleepable prog\n");
9394 /* With LD_ABS/IND some JITs save/restore skb from r1. */
9395 changes_data = bpf_helper_changes_pkt_data(fn->func);
9396 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9397 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9398 func_id_name(func_id), func_id);
9402 memset(&meta, 0, sizeof(meta));
9403 meta.pkt_access = fn->pkt_access;
9405 err = check_func_proto(fn, func_id);
9407 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9408 func_id_name(func_id), func_id);
9412 if (env->cur_state->active_rcu_lock) {
9413 if (fn->might_sleep) {
9414 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9415 func_id_name(func_id), func_id);
9419 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9420 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9423 meta.func_id = func_id;
9425 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9426 err = check_func_arg(env, i, &meta, fn, insn_idx);
9431 err = record_func_map(env, &meta, func_id, insn_idx);
9435 err = record_func_key(env, &meta, func_id, insn_idx);
9439 /* Mark slots with STACK_MISC in case of raw mode, stack offset
9440 * is inferred from register state.
9442 for (i = 0; i < meta.access_size; i++) {
9443 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9444 BPF_WRITE, -1, false);
9449 regs = cur_regs(env);
9451 if (meta.release_regno) {
9453 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9454 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9455 * is safe to do directly.
9457 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9458 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9459 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9462 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
9463 } else if (meta.ref_obj_id) {
9464 err = release_reference(env, meta.ref_obj_id);
9465 } else if (register_is_null(®s[meta.release_regno])) {
9466 /* meta.ref_obj_id can only be 0 if register that is meant to be
9467 * released is NULL, which must be > R0.
9472 verbose(env, "func %s#%d reference has not been acquired before\n",
9473 func_id_name(func_id), func_id);
9479 case BPF_FUNC_tail_call:
9480 err = check_reference_leak(env);
9482 verbose(env, "tail_call would lead to reference leak\n");
9486 case BPF_FUNC_get_local_storage:
9487 /* check that flags argument in get_local_storage(map, flags) is 0,
9488 * this is required because get_local_storage() can't return an error.
9490 if (!register_is_null(®s[BPF_REG_2])) {
9491 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9495 case BPF_FUNC_for_each_map_elem:
9496 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9497 set_map_elem_callback_state);
9499 case BPF_FUNC_timer_set_callback:
9500 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9501 set_timer_callback_state);
9503 case BPF_FUNC_find_vma:
9504 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9505 set_find_vma_callback_state);
9507 case BPF_FUNC_snprintf:
9508 err = check_bpf_snprintf_call(env, regs);
9511 update_loop_inline_state(env, meta.subprogno);
9512 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9513 set_loop_callback_state);
9515 case BPF_FUNC_dynptr_from_mem:
9516 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9517 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9518 reg_type_str(env, regs[BPF_REG_1].type));
9522 case BPF_FUNC_set_retval:
9523 if (prog_type == BPF_PROG_TYPE_LSM &&
9524 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9525 if (!env->prog->aux->attach_func_proto->type) {
9526 /* Make sure programs that attach to void
9527 * hooks don't try to modify return value.
9529 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9534 case BPF_FUNC_dynptr_data:
9536 struct bpf_reg_state *reg;
9539 reg = get_dynptr_arg_reg(env, fn, regs);
9544 if (meta.dynptr_id) {
9545 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9548 if (meta.ref_obj_id) {
9549 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9553 id = dynptr_id(env, reg);
9555 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9559 ref_obj_id = dynptr_ref_obj_id(env, reg);
9560 if (ref_obj_id < 0) {
9561 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9565 meta.dynptr_id = id;
9566 meta.ref_obj_id = ref_obj_id;
9570 case BPF_FUNC_dynptr_write:
9572 enum bpf_dynptr_type dynptr_type;
9573 struct bpf_reg_state *reg;
9575 reg = get_dynptr_arg_reg(env, fn, regs);
9579 dynptr_type = dynptr_get_type(env, reg);
9580 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9583 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9584 /* this will trigger clear_all_pkt_pointers(), which will
9585 * invalidate all dynptr slices associated with the skb
9587 changes_data = true;
9591 case BPF_FUNC_user_ringbuf_drain:
9592 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9593 set_user_ringbuf_callback_state);
9600 /* reset caller saved regs */
9601 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9602 mark_reg_not_init(env, regs, caller_saved[i]);
9603 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9606 /* helper call returns 64-bit value. */
9607 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9609 /* update return register (already marked as written above) */
9610 ret_type = fn->ret_type;
9611 ret_flag = type_flag(ret_type);
9613 switch (base_type(ret_type)) {
9615 /* sets type to SCALAR_VALUE */
9616 mark_reg_unknown(env, regs, BPF_REG_0);
9619 regs[BPF_REG_0].type = NOT_INIT;
9621 case RET_PTR_TO_MAP_VALUE:
9622 /* There is no offset yet applied, variable or fixed */
9623 mark_reg_known_zero(env, regs, BPF_REG_0);
9624 /* remember map_ptr, so that check_map_access()
9625 * can check 'value_size' boundary of memory access
9626 * to map element returned from bpf_map_lookup_elem()
9628 if (meta.map_ptr == NULL) {
9630 "kernel subsystem misconfigured verifier\n");
9633 regs[BPF_REG_0].map_ptr = meta.map_ptr;
9634 regs[BPF_REG_0].map_uid = meta.map_uid;
9635 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9636 if (!type_may_be_null(ret_type) &&
9637 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9638 regs[BPF_REG_0].id = ++env->id_gen;
9641 case RET_PTR_TO_SOCKET:
9642 mark_reg_known_zero(env, regs, BPF_REG_0);
9643 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9645 case RET_PTR_TO_SOCK_COMMON:
9646 mark_reg_known_zero(env, regs, BPF_REG_0);
9647 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9649 case RET_PTR_TO_TCP_SOCK:
9650 mark_reg_known_zero(env, regs, BPF_REG_0);
9651 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9653 case RET_PTR_TO_MEM:
9654 mark_reg_known_zero(env, regs, BPF_REG_0);
9655 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9656 regs[BPF_REG_0].mem_size = meta.mem_size;
9658 case RET_PTR_TO_MEM_OR_BTF_ID:
9660 const struct btf_type *t;
9662 mark_reg_known_zero(env, regs, BPF_REG_0);
9663 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9664 if (!btf_type_is_struct(t)) {
9666 const struct btf_type *ret;
9669 /* resolve the type size of ksym. */
9670 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9672 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9673 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9674 tname, PTR_ERR(ret));
9677 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9678 regs[BPF_REG_0].mem_size = tsize;
9680 /* MEM_RDONLY may be carried from ret_flag, but it
9681 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9682 * it will confuse the check of PTR_TO_BTF_ID in
9683 * check_mem_access().
9685 ret_flag &= ~MEM_RDONLY;
9687 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9688 regs[BPF_REG_0].btf = meta.ret_btf;
9689 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9693 case RET_PTR_TO_BTF_ID:
9695 struct btf *ret_btf;
9698 mark_reg_known_zero(env, regs, BPF_REG_0);
9699 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9700 if (func_id == BPF_FUNC_kptr_xchg) {
9701 ret_btf = meta.kptr_field->kptr.btf;
9702 ret_btf_id = meta.kptr_field->kptr.btf_id;
9703 if (!btf_is_kernel(ret_btf))
9704 regs[BPF_REG_0].type |= MEM_ALLOC;
9706 if (fn->ret_btf_id == BPF_PTR_POISON) {
9707 verbose(env, "verifier internal error:");
9708 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9709 func_id_name(func_id));
9712 ret_btf = btf_vmlinux;
9713 ret_btf_id = *fn->ret_btf_id;
9715 if (ret_btf_id == 0) {
9716 verbose(env, "invalid return type %u of func %s#%d\n",
9717 base_type(ret_type), func_id_name(func_id),
9721 regs[BPF_REG_0].btf = ret_btf;
9722 regs[BPF_REG_0].btf_id = ret_btf_id;
9726 verbose(env, "unknown return type %u of func %s#%d\n",
9727 base_type(ret_type), func_id_name(func_id), func_id);
9731 if (type_may_be_null(regs[BPF_REG_0].type))
9732 regs[BPF_REG_0].id = ++env->id_gen;
9734 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9735 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9736 func_id_name(func_id), func_id);
9740 if (is_dynptr_ref_function(func_id))
9741 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9743 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9744 /* For release_reference() */
9745 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9746 } else if (is_acquire_function(func_id, meta.map_ptr)) {
9747 int id = acquire_reference_state(env, insn_idx);
9751 /* For mark_ptr_or_null_reg() */
9752 regs[BPF_REG_0].id = id;
9753 /* For release_reference() */
9754 regs[BPF_REG_0].ref_obj_id = id;
9757 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9759 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9763 if ((func_id == BPF_FUNC_get_stack ||
9764 func_id == BPF_FUNC_get_task_stack) &&
9765 !env->prog->has_callchain_buf) {
9766 const char *err_str;
9768 #ifdef CONFIG_PERF_EVENTS
9769 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9770 err_str = "cannot get callchain buffer for func %s#%d\n";
9773 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9776 verbose(env, err_str, func_id_name(func_id), func_id);
9780 env->prog->has_callchain_buf = true;
9783 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9784 env->prog->call_get_stack = true;
9786 if (func_id == BPF_FUNC_get_func_ip) {
9787 if (check_get_func_ip(env))
9789 env->prog->call_get_func_ip = true;
9793 clear_all_pkt_pointers(env);
9797 /* mark_btf_func_reg_size() is used when the reg size is determined by
9798 * the BTF func_proto's return value size and argument.
9800 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9803 struct bpf_reg_state *reg = &cur_regs(env)[regno];
9805 if (regno == BPF_REG_0) {
9806 /* Function return value */
9807 reg->live |= REG_LIVE_WRITTEN;
9808 reg->subreg_def = reg_size == sizeof(u64) ?
9809 DEF_NOT_SUBREG : env->insn_idx + 1;
9811 /* Function argument */
9812 if (reg_size == sizeof(u64)) {
9813 mark_insn_zext(env, reg);
9814 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9816 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9821 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
9823 return meta->kfunc_flags & KF_ACQUIRE;
9826 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
9828 return meta->kfunc_flags & KF_RELEASE;
9831 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
9833 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
9836 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
9838 return meta->kfunc_flags & KF_SLEEPABLE;
9841 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
9843 return meta->kfunc_flags & KF_DESTRUCTIVE;
9846 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
9848 return meta->kfunc_flags & KF_RCU;
9851 static bool __kfunc_param_match_suffix(const struct btf *btf,
9852 const struct btf_param *arg,
9855 int suffix_len = strlen(suffix), len;
9856 const char *param_name;
9858 /* In the future, this can be ported to use BTF tagging */
9859 param_name = btf_name_by_offset(btf, arg->name_off);
9860 if (str_is_empty(param_name))
9862 len = strlen(param_name);
9863 if (len < suffix_len)
9865 param_name += len - suffix_len;
9866 return !strncmp(param_name, suffix, suffix_len);
9869 static bool is_kfunc_arg_mem_size(const struct btf *btf,
9870 const struct btf_param *arg,
9871 const struct bpf_reg_state *reg)
9873 const struct btf_type *t;
9875 t = btf_type_skip_modifiers(btf, arg->type, NULL);
9876 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9879 return __kfunc_param_match_suffix(btf, arg, "__sz");
9882 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
9883 const struct btf_param *arg,
9884 const struct bpf_reg_state *reg)
9886 const struct btf_type *t;
9888 t = btf_type_skip_modifiers(btf, arg->type, NULL);
9889 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9892 return __kfunc_param_match_suffix(btf, arg, "__szk");
9895 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
9897 return __kfunc_param_match_suffix(btf, arg, "__opt");
9900 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
9902 return __kfunc_param_match_suffix(btf, arg, "__k");
9905 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
9907 return __kfunc_param_match_suffix(btf, arg, "__ign");
9910 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
9912 return __kfunc_param_match_suffix(btf, arg, "__alloc");
9915 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
9917 return __kfunc_param_match_suffix(btf, arg, "__uninit");
9920 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
9922 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
9925 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
9926 const struct btf_param *arg,
9929 int len, target_len = strlen(name);
9930 const char *param_name;
9932 param_name = btf_name_by_offset(btf, arg->name_off);
9933 if (str_is_empty(param_name))
9935 len = strlen(param_name);
9936 if (len != target_len)
9938 if (strcmp(param_name, name))
9946 KF_ARG_LIST_HEAD_ID,
9947 KF_ARG_LIST_NODE_ID,
9952 BTF_ID_LIST(kf_arg_btf_ids)
9953 BTF_ID(struct, bpf_dynptr_kern)
9954 BTF_ID(struct, bpf_list_head)
9955 BTF_ID(struct, bpf_list_node)
9956 BTF_ID(struct, bpf_rb_root)
9957 BTF_ID(struct, bpf_rb_node)
9959 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
9960 const struct btf_param *arg, int type)
9962 const struct btf_type *t;
9965 t = btf_type_skip_modifiers(btf, arg->type, NULL);
9968 if (!btf_type_is_ptr(t))
9970 t = btf_type_skip_modifiers(btf, t->type, &res_id);
9973 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
9976 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
9978 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
9981 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
9983 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
9986 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
9988 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
9991 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
9993 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
9996 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
9998 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10001 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10002 const struct btf_param *arg)
10004 const struct btf_type *t;
10006 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10013 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10014 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10015 const struct btf *btf,
10016 const struct btf_type *t, int rec)
10018 const struct btf_type *member_type;
10019 const struct btf_member *member;
10022 if (!btf_type_is_struct(t))
10025 for_each_member(i, t, member) {
10026 const struct btf_array *array;
10028 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10029 if (btf_type_is_struct(member_type)) {
10031 verbose(env, "max struct nesting depth exceeded\n");
10034 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10038 if (btf_type_is_array(member_type)) {
10039 array = btf_array(member_type);
10040 if (!array->nelems)
10042 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10043 if (!btf_type_is_scalar(member_type))
10047 if (!btf_type_is_scalar(member_type))
10054 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
10056 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
10057 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
10058 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
10062 enum kfunc_ptr_arg_type {
10064 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
10065 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10066 KF_ARG_PTR_TO_DYNPTR,
10067 KF_ARG_PTR_TO_ITER,
10068 KF_ARG_PTR_TO_LIST_HEAD,
10069 KF_ARG_PTR_TO_LIST_NODE,
10070 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
10072 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
10073 KF_ARG_PTR_TO_CALLBACK,
10074 KF_ARG_PTR_TO_RB_ROOT,
10075 KF_ARG_PTR_TO_RB_NODE,
10078 enum special_kfunc_type {
10079 KF_bpf_obj_new_impl,
10080 KF_bpf_obj_drop_impl,
10081 KF_bpf_refcount_acquire_impl,
10082 KF_bpf_list_push_front_impl,
10083 KF_bpf_list_push_back_impl,
10084 KF_bpf_list_pop_front,
10085 KF_bpf_list_pop_back,
10086 KF_bpf_cast_to_kern_ctx,
10087 KF_bpf_rdonly_cast,
10088 KF_bpf_rcu_read_lock,
10089 KF_bpf_rcu_read_unlock,
10090 KF_bpf_rbtree_remove,
10091 KF_bpf_rbtree_add_impl,
10092 KF_bpf_rbtree_first,
10093 KF_bpf_dynptr_from_skb,
10094 KF_bpf_dynptr_from_xdp,
10095 KF_bpf_dynptr_slice,
10096 KF_bpf_dynptr_slice_rdwr,
10097 KF_bpf_dynptr_clone,
10100 BTF_SET_START(special_kfunc_set)
10101 BTF_ID(func, bpf_obj_new_impl)
10102 BTF_ID(func, bpf_obj_drop_impl)
10103 BTF_ID(func, bpf_refcount_acquire_impl)
10104 BTF_ID(func, bpf_list_push_front_impl)
10105 BTF_ID(func, bpf_list_push_back_impl)
10106 BTF_ID(func, bpf_list_pop_front)
10107 BTF_ID(func, bpf_list_pop_back)
10108 BTF_ID(func, bpf_cast_to_kern_ctx)
10109 BTF_ID(func, bpf_rdonly_cast)
10110 BTF_ID(func, bpf_rbtree_remove)
10111 BTF_ID(func, bpf_rbtree_add_impl)
10112 BTF_ID(func, bpf_rbtree_first)
10113 BTF_ID(func, bpf_dynptr_from_skb)
10114 BTF_ID(func, bpf_dynptr_from_xdp)
10115 BTF_ID(func, bpf_dynptr_slice)
10116 BTF_ID(func, bpf_dynptr_slice_rdwr)
10117 BTF_ID(func, bpf_dynptr_clone)
10118 BTF_SET_END(special_kfunc_set)
10120 BTF_ID_LIST(special_kfunc_list)
10121 BTF_ID(func, bpf_obj_new_impl)
10122 BTF_ID(func, bpf_obj_drop_impl)
10123 BTF_ID(func, bpf_refcount_acquire_impl)
10124 BTF_ID(func, bpf_list_push_front_impl)
10125 BTF_ID(func, bpf_list_push_back_impl)
10126 BTF_ID(func, bpf_list_pop_front)
10127 BTF_ID(func, bpf_list_pop_back)
10128 BTF_ID(func, bpf_cast_to_kern_ctx)
10129 BTF_ID(func, bpf_rdonly_cast)
10130 BTF_ID(func, bpf_rcu_read_lock)
10131 BTF_ID(func, bpf_rcu_read_unlock)
10132 BTF_ID(func, bpf_rbtree_remove)
10133 BTF_ID(func, bpf_rbtree_add_impl)
10134 BTF_ID(func, bpf_rbtree_first)
10135 BTF_ID(func, bpf_dynptr_from_skb)
10136 BTF_ID(func, bpf_dynptr_from_xdp)
10137 BTF_ID(func, bpf_dynptr_slice)
10138 BTF_ID(func, bpf_dynptr_slice_rdwr)
10139 BTF_ID(func, bpf_dynptr_clone)
10141 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10143 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10144 meta->arg_owning_ref) {
10148 return meta->kfunc_flags & KF_RET_NULL;
10151 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10153 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10156 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10158 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10161 static enum kfunc_ptr_arg_type
10162 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10163 struct bpf_kfunc_call_arg_meta *meta,
10164 const struct btf_type *t, const struct btf_type *ref_t,
10165 const char *ref_tname, const struct btf_param *args,
10166 int argno, int nargs)
10168 u32 regno = argno + 1;
10169 struct bpf_reg_state *regs = cur_regs(env);
10170 struct bpf_reg_state *reg = ®s[regno];
10171 bool arg_mem_size = false;
10173 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10174 return KF_ARG_PTR_TO_CTX;
10176 /* In this function, we verify the kfunc's BTF as per the argument type,
10177 * leaving the rest of the verification with respect to the register
10178 * type to our caller. When a set of conditions hold in the BTF type of
10179 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10181 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10182 return KF_ARG_PTR_TO_CTX;
10184 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10185 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10187 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10188 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10190 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10191 return KF_ARG_PTR_TO_DYNPTR;
10193 if (is_kfunc_arg_iter(meta, argno))
10194 return KF_ARG_PTR_TO_ITER;
10196 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10197 return KF_ARG_PTR_TO_LIST_HEAD;
10199 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10200 return KF_ARG_PTR_TO_LIST_NODE;
10202 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10203 return KF_ARG_PTR_TO_RB_ROOT;
10205 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10206 return KF_ARG_PTR_TO_RB_NODE;
10208 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10209 if (!btf_type_is_struct(ref_t)) {
10210 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10211 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10214 return KF_ARG_PTR_TO_BTF_ID;
10217 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10218 return KF_ARG_PTR_TO_CALLBACK;
10221 if (argno + 1 < nargs &&
10222 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
10223 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
10224 arg_mem_size = true;
10226 /* This is the catch all argument type of register types supported by
10227 * check_helper_mem_access. However, we only allow when argument type is
10228 * pointer to scalar, or struct composed (recursively) of scalars. When
10229 * arg_mem_size is true, the pointer can be void *.
10231 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10232 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10233 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10234 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10237 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10240 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10241 struct bpf_reg_state *reg,
10242 const struct btf_type *ref_t,
10243 const char *ref_tname, u32 ref_id,
10244 struct bpf_kfunc_call_arg_meta *meta,
10247 const struct btf_type *reg_ref_t;
10248 bool strict_type_match = false;
10249 const struct btf *reg_btf;
10250 const char *reg_ref_tname;
10253 if (base_type(reg->type) == PTR_TO_BTF_ID) {
10254 reg_btf = reg->btf;
10255 reg_ref_id = reg->btf_id;
10257 reg_btf = btf_vmlinux;
10258 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10261 /* Enforce strict type matching for calls to kfuncs that are acquiring
10262 * or releasing a reference, or are no-cast aliases. We do _not_
10263 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10264 * as we want to enable BPF programs to pass types that are bitwise
10265 * equivalent without forcing them to explicitly cast with something
10266 * like bpf_cast_to_kern_ctx().
10268 * For example, say we had a type like the following:
10270 * struct bpf_cpumask {
10271 * cpumask_t cpumask;
10272 * refcount_t usage;
10275 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10276 * to a struct cpumask, so it would be safe to pass a struct
10277 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10279 * The philosophy here is similar to how we allow scalars of different
10280 * types to be passed to kfuncs as long as the size is the same. The
10281 * only difference here is that we're simply allowing
10282 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10285 if (is_kfunc_acquire(meta) ||
10286 (is_kfunc_release(meta) && reg->ref_obj_id) ||
10287 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10288 strict_type_match = true;
10290 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10292 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
10293 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10294 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10295 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10296 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10297 btf_type_str(reg_ref_t), reg_ref_tname);
10303 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10305 struct bpf_verifier_state *state = env->cur_state;
10307 if (!state->active_lock.ptr) {
10308 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10312 if (type_flag(reg->type) & NON_OWN_REF) {
10313 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10317 reg->type |= NON_OWN_REF;
10321 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10323 struct bpf_func_state *state, *unused;
10324 struct bpf_reg_state *reg;
10327 state = cur_func(env);
10330 verbose(env, "verifier internal error: ref_obj_id is zero for "
10331 "owning -> non-owning conversion\n");
10335 for (i = 0; i < state->acquired_refs; i++) {
10336 if (state->refs[i].id != ref_obj_id)
10339 /* Clear ref_obj_id here so release_reference doesn't clobber
10342 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10343 if (reg->ref_obj_id == ref_obj_id) {
10344 reg->ref_obj_id = 0;
10345 ref_set_non_owning(env, reg);
10351 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10355 /* Implementation details:
10357 * Each register points to some region of memory, which we define as an
10358 * allocation. Each allocation may embed a bpf_spin_lock which protects any
10359 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10360 * allocation. The lock and the data it protects are colocated in the same
10363 * Hence, everytime a register holds a pointer value pointing to such
10364 * allocation, the verifier preserves a unique reg->id for it.
10366 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10367 * bpf_spin_lock is called.
10369 * To enable this, lock state in the verifier captures two values:
10370 * active_lock.ptr = Register's type specific pointer
10371 * active_lock.id = A unique ID for each register pointer value
10373 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10374 * supported register types.
10376 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10377 * allocated objects is the reg->btf pointer.
10379 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10380 * can establish the provenance of the map value statically for each distinct
10381 * lookup into such maps. They always contain a single map value hence unique
10382 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10384 * So, in case of global variables, they use array maps with max_entries = 1,
10385 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10386 * into the same map value as max_entries is 1, as described above).
10388 * In case of inner map lookups, the inner map pointer has same map_ptr as the
10389 * outer map pointer (in verifier context), but each lookup into an inner map
10390 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10391 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10392 * will get different reg->id assigned to each lookup, hence different
10395 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10396 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10397 * returned from bpf_obj_new. Each allocation receives a new reg->id.
10399 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10404 switch ((int)reg->type) {
10405 case PTR_TO_MAP_VALUE:
10406 ptr = reg->map_ptr;
10408 case PTR_TO_BTF_ID | MEM_ALLOC:
10412 verbose(env, "verifier internal error: unknown reg type for lock check\n");
10417 if (!env->cur_state->active_lock.ptr)
10419 if (env->cur_state->active_lock.ptr != ptr ||
10420 env->cur_state->active_lock.id != id) {
10421 verbose(env, "held lock and object are not in the same allocation\n");
10427 static bool is_bpf_list_api_kfunc(u32 btf_id)
10429 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10430 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10431 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10432 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10435 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10437 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10438 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10439 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10442 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10444 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10445 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10448 static bool is_callback_calling_kfunc(u32 btf_id)
10450 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10453 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10455 return is_bpf_rbtree_api_kfunc(btf_id);
10458 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10459 enum btf_field_type head_field_type,
10464 switch (head_field_type) {
10465 case BPF_LIST_HEAD:
10466 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10469 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10472 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10473 btf_field_type_name(head_field_type));
10478 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10479 btf_field_type_name(head_field_type));
10483 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10484 enum btf_field_type node_field_type,
10489 switch (node_field_type) {
10490 case BPF_LIST_NODE:
10491 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10492 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10495 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10496 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10499 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10500 btf_field_type_name(node_field_type));
10505 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10506 btf_field_type_name(node_field_type));
10511 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10512 struct bpf_reg_state *reg, u32 regno,
10513 struct bpf_kfunc_call_arg_meta *meta,
10514 enum btf_field_type head_field_type,
10515 struct btf_field **head_field)
10517 const char *head_type_name;
10518 struct btf_field *field;
10519 struct btf_record *rec;
10522 if (meta->btf != btf_vmlinux) {
10523 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10527 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10530 head_type_name = btf_field_type_name(head_field_type);
10531 if (!tnum_is_const(reg->var_off)) {
10533 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10534 regno, head_type_name);
10538 rec = reg_btf_record(reg);
10539 head_off = reg->off + reg->var_off.value;
10540 field = btf_record_find(rec, head_off, head_field_type);
10542 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10546 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10547 if (check_reg_allocation_locked(env, reg)) {
10548 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10549 rec->spin_lock_off, head_type_name);
10554 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10557 *head_field = field;
10561 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10562 struct bpf_reg_state *reg, u32 regno,
10563 struct bpf_kfunc_call_arg_meta *meta)
10565 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10566 &meta->arg_list_head.field);
10569 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10570 struct bpf_reg_state *reg, u32 regno,
10571 struct bpf_kfunc_call_arg_meta *meta)
10573 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10574 &meta->arg_rbtree_root.field);
10578 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10579 struct bpf_reg_state *reg, u32 regno,
10580 struct bpf_kfunc_call_arg_meta *meta,
10581 enum btf_field_type head_field_type,
10582 enum btf_field_type node_field_type,
10583 struct btf_field **node_field)
10585 const char *node_type_name;
10586 const struct btf_type *et, *t;
10587 struct btf_field *field;
10590 if (meta->btf != btf_vmlinux) {
10591 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10595 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10598 node_type_name = btf_field_type_name(node_field_type);
10599 if (!tnum_is_const(reg->var_off)) {
10601 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10602 regno, node_type_name);
10606 node_off = reg->off + reg->var_off.value;
10607 field = reg_find_field_offset(reg, node_off, node_field_type);
10608 if (!field || field->offset != node_off) {
10609 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10613 field = *node_field;
10615 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10616 t = btf_type_by_id(reg->btf, reg->btf_id);
10617 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10618 field->graph_root.value_btf_id, true)) {
10619 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10620 "in struct %s, but arg is at offset=%d in struct %s\n",
10621 btf_field_type_name(head_field_type),
10622 btf_field_type_name(node_field_type),
10623 field->graph_root.node_offset,
10624 btf_name_by_offset(field->graph_root.btf, et->name_off),
10625 node_off, btf_name_by_offset(reg->btf, t->name_off));
10628 meta->arg_btf = reg->btf;
10629 meta->arg_btf_id = reg->btf_id;
10631 if (node_off != field->graph_root.node_offset) {
10632 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10633 node_off, btf_field_type_name(node_field_type),
10634 field->graph_root.node_offset,
10635 btf_name_by_offset(field->graph_root.btf, et->name_off));
10642 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10643 struct bpf_reg_state *reg, u32 regno,
10644 struct bpf_kfunc_call_arg_meta *meta)
10646 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10647 BPF_LIST_HEAD, BPF_LIST_NODE,
10648 &meta->arg_list_head.field);
10651 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10652 struct bpf_reg_state *reg, u32 regno,
10653 struct bpf_kfunc_call_arg_meta *meta)
10655 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10656 BPF_RB_ROOT, BPF_RB_NODE,
10657 &meta->arg_rbtree_root.field);
10660 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10663 const char *func_name = meta->func_name, *ref_tname;
10664 const struct btf *btf = meta->btf;
10665 const struct btf_param *args;
10666 struct btf_record *rec;
10670 args = (const struct btf_param *)(meta->func_proto + 1);
10671 nargs = btf_type_vlen(meta->func_proto);
10672 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10673 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10674 MAX_BPF_FUNC_REG_ARGS);
10678 /* Check that BTF function arguments match actual types that the
10681 for (i = 0; i < nargs; i++) {
10682 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
10683 const struct btf_type *t, *ref_t, *resolve_ret;
10684 enum bpf_arg_type arg_type = ARG_DONTCARE;
10685 u32 regno = i + 1, ref_id, type_size;
10686 bool is_ret_buf_sz = false;
10689 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10691 if (is_kfunc_arg_ignore(btf, &args[i]))
10694 if (btf_type_is_scalar(t)) {
10695 if (reg->type != SCALAR_VALUE) {
10696 verbose(env, "R%d is not a scalar\n", regno);
10700 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10701 if (meta->arg_constant.found) {
10702 verbose(env, "verifier internal error: only one constant argument permitted\n");
10705 if (!tnum_is_const(reg->var_off)) {
10706 verbose(env, "R%d must be a known constant\n", regno);
10709 ret = mark_chain_precision(env, regno);
10712 meta->arg_constant.found = true;
10713 meta->arg_constant.value = reg->var_off.value;
10714 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10715 meta->r0_rdonly = true;
10716 is_ret_buf_sz = true;
10717 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10718 is_ret_buf_sz = true;
10721 if (is_ret_buf_sz) {
10722 if (meta->r0_size) {
10723 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10727 if (!tnum_is_const(reg->var_off)) {
10728 verbose(env, "R%d is not a const\n", regno);
10732 meta->r0_size = reg->var_off.value;
10733 ret = mark_chain_precision(env, regno);
10740 if (!btf_type_is_ptr(t)) {
10741 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10745 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10746 (register_is_null(reg) || type_may_be_null(reg->type))) {
10747 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10751 if (reg->ref_obj_id) {
10752 if (is_kfunc_release(meta) && meta->ref_obj_id) {
10753 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10754 regno, reg->ref_obj_id,
10758 meta->ref_obj_id = reg->ref_obj_id;
10759 if (is_kfunc_release(meta))
10760 meta->release_regno = regno;
10763 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10764 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10766 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10767 if (kf_arg_type < 0)
10768 return kf_arg_type;
10770 switch (kf_arg_type) {
10771 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10772 case KF_ARG_PTR_TO_BTF_ID:
10773 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10776 if (!is_trusted_reg(reg)) {
10777 if (!is_kfunc_rcu(meta)) {
10778 verbose(env, "R%d must be referenced or trusted\n", regno);
10781 if (!is_rcu_reg(reg)) {
10782 verbose(env, "R%d must be a rcu pointer\n", regno);
10788 case KF_ARG_PTR_TO_CTX:
10789 /* Trusted arguments have the same offset checks as release arguments */
10790 arg_type |= OBJ_RELEASE;
10792 case KF_ARG_PTR_TO_DYNPTR:
10793 case KF_ARG_PTR_TO_ITER:
10794 case KF_ARG_PTR_TO_LIST_HEAD:
10795 case KF_ARG_PTR_TO_LIST_NODE:
10796 case KF_ARG_PTR_TO_RB_ROOT:
10797 case KF_ARG_PTR_TO_RB_NODE:
10798 case KF_ARG_PTR_TO_MEM:
10799 case KF_ARG_PTR_TO_MEM_SIZE:
10800 case KF_ARG_PTR_TO_CALLBACK:
10801 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10802 /* Trusted by default */
10809 if (is_kfunc_release(meta) && reg->ref_obj_id)
10810 arg_type |= OBJ_RELEASE;
10811 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10815 switch (kf_arg_type) {
10816 case KF_ARG_PTR_TO_CTX:
10817 if (reg->type != PTR_TO_CTX) {
10818 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10822 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10823 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10826 meta->ret_btf_id = ret;
10829 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10830 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10831 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10834 if (!reg->ref_obj_id) {
10835 verbose(env, "allocated object must be referenced\n");
10838 if (meta->btf == btf_vmlinux &&
10839 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10840 meta->arg_btf = reg->btf;
10841 meta->arg_btf_id = reg->btf_id;
10844 case KF_ARG_PTR_TO_DYNPTR:
10846 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
10847 int clone_ref_obj_id = 0;
10849 if (reg->type != PTR_TO_STACK &&
10850 reg->type != CONST_PTR_TO_DYNPTR) {
10851 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
10855 if (reg->type == CONST_PTR_TO_DYNPTR)
10856 dynptr_arg_type |= MEM_RDONLY;
10858 if (is_kfunc_arg_uninit(btf, &args[i]))
10859 dynptr_arg_type |= MEM_UNINIT;
10861 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
10862 dynptr_arg_type |= DYNPTR_TYPE_SKB;
10863 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
10864 dynptr_arg_type |= DYNPTR_TYPE_XDP;
10865 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
10866 (dynptr_arg_type & MEM_UNINIT)) {
10867 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
10869 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
10870 verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
10874 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
10875 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
10876 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
10877 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
10882 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
10886 if (!(dynptr_arg_type & MEM_UNINIT)) {
10887 int id = dynptr_id(env, reg);
10890 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10893 meta->initialized_dynptr.id = id;
10894 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
10895 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
10900 case KF_ARG_PTR_TO_ITER:
10901 ret = process_iter_arg(env, regno, insn_idx, meta);
10905 case KF_ARG_PTR_TO_LIST_HEAD:
10906 if (reg->type != PTR_TO_MAP_VALUE &&
10907 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10908 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10911 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10912 verbose(env, "allocated object must be referenced\n");
10915 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
10919 case KF_ARG_PTR_TO_RB_ROOT:
10920 if (reg->type != PTR_TO_MAP_VALUE &&
10921 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10922 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10925 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10926 verbose(env, "allocated object must be referenced\n");
10929 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
10933 case KF_ARG_PTR_TO_LIST_NODE:
10934 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10935 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10938 if (!reg->ref_obj_id) {
10939 verbose(env, "allocated object must be referenced\n");
10942 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
10946 case KF_ARG_PTR_TO_RB_NODE:
10947 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
10948 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
10949 verbose(env, "rbtree_remove node input must be non-owning ref\n");
10952 if (in_rbtree_lock_required_cb(env)) {
10953 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
10957 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10958 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10961 if (!reg->ref_obj_id) {
10962 verbose(env, "allocated object must be referenced\n");
10967 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
10971 case KF_ARG_PTR_TO_BTF_ID:
10972 /* Only base_type is checked, further checks are done here */
10973 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
10974 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
10975 !reg2btf_ids[base_type(reg->type)]) {
10976 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
10977 verbose(env, "expected %s or socket\n",
10978 reg_type_str(env, base_type(reg->type) |
10979 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
10982 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
10986 case KF_ARG_PTR_TO_MEM:
10987 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
10988 if (IS_ERR(resolve_ret)) {
10989 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
10990 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
10993 ret = check_mem_reg(env, reg, regno, type_size);
10997 case KF_ARG_PTR_TO_MEM_SIZE:
10999 struct bpf_reg_state *buff_reg = ®s[regno];
11000 const struct btf_param *buff_arg = &args[i];
11001 struct bpf_reg_state *size_reg = ®s[regno + 1];
11002 const struct btf_param *size_arg = &args[i + 1];
11004 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11005 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11007 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11012 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11013 if (meta->arg_constant.found) {
11014 verbose(env, "verifier internal error: only one constant argument permitted\n");
11017 if (!tnum_is_const(size_reg->var_off)) {
11018 verbose(env, "R%d must be a known constant\n", regno + 1);
11021 meta->arg_constant.found = true;
11022 meta->arg_constant.value = size_reg->var_off.value;
11025 /* Skip next '__sz' or '__szk' argument */
11029 case KF_ARG_PTR_TO_CALLBACK:
11030 meta->subprogno = reg->subprogno;
11032 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11033 if (!type_is_ptr_alloc_obj(reg->type)) {
11034 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11037 if (!type_is_non_owning_ref(reg->type))
11038 meta->arg_owning_ref = true;
11040 rec = reg_btf_record(reg);
11042 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11046 if (rec->refcount_off < 0) {
11047 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11050 if (rec->refcount_off >= 0) {
11051 verbose(env, "bpf_refcount_acquire calls are disabled for now\n");
11054 meta->arg_btf = reg->btf;
11055 meta->arg_btf_id = reg->btf_id;
11060 if (is_kfunc_release(meta) && !meta->release_regno) {
11061 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11069 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11070 struct bpf_insn *insn,
11071 struct bpf_kfunc_call_arg_meta *meta,
11072 const char **kfunc_name)
11074 const struct btf_type *func, *func_proto;
11075 u32 func_id, *kfunc_flags;
11076 const char *func_name;
11077 struct btf *desc_btf;
11080 *kfunc_name = NULL;
11085 desc_btf = find_kfunc_desc_btf(env, insn->off);
11086 if (IS_ERR(desc_btf))
11087 return PTR_ERR(desc_btf);
11089 func_id = insn->imm;
11090 func = btf_type_by_id(desc_btf, func_id);
11091 func_name = btf_name_by_offset(desc_btf, func->name_off);
11093 *kfunc_name = func_name;
11094 func_proto = btf_type_by_id(desc_btf, func->type);
11096 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11097 if (!kfunc_flags) {
11101 memset(meta, 0, sizeof(*meta));
11102 meta->btf = desc_btf;
11103 meta->func_id = func_id;
11104 meta->kfunc_flags = *kfunc_flags;
11105 meta->func_proto = func_proto;
11106 meta->func_name = func_name;
11111 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11114 const struct btf_type *t, *ptr_type;
11115 u32 i, nargs, ptr_type_id, release_ref_obj_id;
11116 struct bpf_reg_state *regs = cur_regs(env);
11117 const char *func_name, *ptr_type_name;
11118 bool sleepable, rcu_lock, rcu_unlock;
11119 struct bpf_kfunc_call_arg_meta meta;
11120 struct bpf_insn_aux_data *insn_aux;
11121 int err, insn_idx = *insn_idx_p;
11122 const struct btf_param *args;
11123 const struct btf_type *ret_t;
11124 struct btf *desc_btf;
11126 /* skip for now, but return error when we find this in fixup_kfunc_call */
11130 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11131 if (err == -EACCES && func_name)
11132 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11135 desc_btf = meta.btf;
11136 insn_aux = &env->insn_aux_data[insn_idx];
11138 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11140 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11141 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11145 sleepable = is_kfunc_sleepable(&meta);
11146 if (sleepable && !env->prog->aux->sleepable) {
11147 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11151 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11152 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11154 if (env->cur_state->active_rcu_lock) {
11155 struct bpf_func_state *state;
11156 struct bpf_reg_state *reg;
11159 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11161 } else if (rcu_unlock) {
11162 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11163 if (reg->type & MEM_RCU) {
11164 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11165 reg->type |= PTR_UNTRUSTED;
11168 env->cur_state->active_rcu_lock = false;
11169 } else if (sleepable) {
11170 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11173 } else if (rcu_lock) {
11174 env->cur_state->active_rcu_lock = true;
11175 } else if (rcu_unlock) {
11176 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11180 /* Check the arguments */
11181 err = check_kfunc_args(env, &meta, insn_idx);
11184 /* In case of release function, we get register number of refcounted
11185 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11187 if (meta.release_regno) {
11188 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11190 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11191 func_name, meta.func_id);
11196 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11197 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11198 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11199 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11200 insn_aux->insert_off = regs[BPF_REG_2].off;
11201 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11202 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11204 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11205 func_name, meta.func_id);
11209 err = release_reference(env, release_ref_obj_id);
11211 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11212 func_name, meta.func_id);
11217 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11218 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11219 set_rbtree_add_callback_state);
11221 verbose(env, "kfunc %s#%d failed callback verification\n",
11222 func_name, meta.func_id);
11227 for (i = 0; i < CALLER_SAVED_REGS; i++)
11228 mark_reg_not_init(env, regs, caller_saved[i]);
11230 /* Check return type */
11231 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11233 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11234 /* Only exception is bpf_obj_new_impl */
11235 if (meta.btf != btf_vmlinux ||
11236 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11237 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11238 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11243 if (btf_type_is_scalar(t)) {
11244 mark_reg_unknown(env, regs, BPF_REG_0);
11245 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11246 } else if (btf_type_is_ptr(t)) {
11247 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11249 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11250 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11251 struct btf *ret_btf;
11254 if (unlikely(!bpf_global_ma_set))
11257 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11258 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11262 ret_btf = env->prog->aux->btf;
11263 ret_btf_id = meta.arg_constant.value;
11265 /* This may be NULL due to user not supplying a BTF */
11267 verbose(env, "bpf_obj_new requires prog BTF\n");
11271 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11272 if (!ret_t || !__btf_type_is_struct(ret_t)) {
11273 verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11277 mark_reg_known_zero(env, regs, BPF_REG_0);
11278 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11279 regs[BPF_REG_0].btf = ret_btf;
11280 regs[BPF_REG_0].btf_id = ret_btf_id;
11282 insn_aux->obj_new_size = ret_t->size;
11283 insn_aux->kptr_struct_meta =
11284 btf_find_struct_meta(ret_btf, ret_btf_id);
11285 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11286 mark_reg_known_zero(env, regs, BPF_REG_0);
11287 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11288 regs[BPF_REG_0].btf = meta.arg_btf;
11289 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11291 insn_aux->kptr_struct_meta =
11292 btf_find_struct_meta(meta.arg_btf,
11294 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11295 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11296 struct btf_field *field = meta.arg_list_head.field;
11298 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11299 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11300 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11301 struct btf_field *field = meta.arg_rbtree_root.field;
11303 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11304 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11305 mark_reg_known_zero(env, regs, BPF_REG_0);
11306 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11307 regs[BPF_REG_0].btf = desc_btf;
11308 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11309 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11310 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11311 if (!ret_t || !btf_type_is_struct(ret_t)) {
11313 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11317 mark_reg_known_zero(env, regs, BPF_REG_0);
11318 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11319 regs[BPF_REG_0].btf = desc_btf;
11320 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11321 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11322 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11323 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11325 mark_reg_known_zero(env, regs, BPF_REG_0);
11327 if (!meta.arg_constant.found) {
11328 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11332 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11334 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11335 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11337 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11338 regs[BPF_REG_0].type |= MEM_RDONLY;
11340 /* this will set env->seen_direct_write to true */
11341 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11342 verbose(env, "the prog does not allow writes to packet data\n");
11347 if (!meta.initialized_dynptr.id) {
11348 verbose(env, "verifier internal error: no dynptr id\n");
11351 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11353 /* we don't need to set BPF_REG_0's ref obj id
11354 * because packet slices are not refcounted (see
11355 * dynptr_type_refcounted)
11358 verbose(env, "kernel function %s unhandled dynamic return type\n",
11362 } else if (!__btf_type_is_struct(ptr_type)) {
11363 if (!meta.r0_size) {
11366 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11368 meta.r0_rdonly = true;
11371 if (!meta.r0_size) {
11372 ptr_type_name = btf_name_by_offset(desc_btf,
11373 ptr_type->name_off);
11375 "kernel function %s returns pointer type %s %s is not supported\n",
11377 btf_type_str(ptr_type),
11382 mark_reg_known_zero(env, regs, BPF_REG_0);
11383 regs[BPF_REG_0].type = PTR_TO_MEM;
11384 regs[BPF_REG_0].mem_size = meta.r0_size;
11386 if (meta.r0_rdonly)
11387 regs[BPF_REG_0].type |= MEM_RDONLY;
11389 /* Ensures we don't access the memory after a release_reference() */
11390 if (meta.ref_obj_id)
11391 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11393 mark_reg_known_zero(env, regs, BPF_REG_0);
11394 regs[BPF_REG_0].btf = desc_btf;
11395 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11396 regs[BPF_REG_0].btf_id = ptr_type_id;
11399 if (is_kfunc_ret_null(&meta)) {
11400 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11401 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11402 regs[BPF_REG_0].id = ++env->id_gen;
11404 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11405 if (is_kfunc_acquire(&meta)) {
11406 int id = acquire_reference_state(env, insn_idx);
11410 if (is_kfunc_ret_null(&meta))
11411 regs[BPF_REG_0].id = id;
11412 regs[BPF_REG_0].ref_obj_id = id;
11413 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11414 ref_set_non_owning(env, ®s[BPF_REG_0]);
11417 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
11418 regs[BPF_REG_0].id = ++env->id_gen;
11419 } else if (btf_type_is_void(t)) {
11420 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11421 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11422 insn_aux->kptr_struct_meta =
11423 btf_find_struct_meta(meta.arg_btf,
11429 nargs = btf_type_vlen(meta.func_proto);
11430 args = (const struct btf_param *)(meta.func_proto + 1);
11431 for (i = 0; i < nargs; i++) {
11434 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11435 if (btf_type_is_ptr(t))
11436 mark_btf_func_reg_size(env, regno, sizeof(void *));
11438 /* scalar. ensured by btf_check_kfunc_arg_match() */
11439 mark_btf_func_reg_size(env, regno, t->size);
11442 if (is_iter_next_kfunc(&meta)) {
11443 err = process_iter_next_call(env, insn_idx, &meta);
11451 static bool signed_add_overflows(s64 a, s64 b)
11453 /* Do the add in u64, where overflow is well-defined */
11454 s64 res = (s64)((u64)a + (u64)b);
11461 static bool signed_add32_overflows(s32 a, s32 b)
11463 /* Do the add in u32, where overflow is well-defined */
11464 s32 res = (s32)((u32)a + (u32)b);
11471 static bool signed_sub_overflows(s64 a, s64 b)
11473 /* Do the sub in u64, where overflow is well-defined */
11474 s64 res = (s64)((u64)a - (u64)b);
11481 static bool signed_sub32_overflows(s32 a, s32 b)
11483 /* Do the sub in u32, where overflow is well-defined */
11484 s32 res = (s32)((u32)a - (u32)b);
11491 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11492 const struct bpf_reg_state *reg,
11493 enum bpf_reg_type type)
11495 bool known = tnum_is_const(reg->var_off);
11496 s64 val = reg->var_off.value;
11497 s64 smin = reg->smin_value;
11499 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11500 verbose(env, "math between %s pointer and %lld is not allowed\n",
11501 reg_type_str(env, type), val);
11505 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11506 verbose(env, "%s pointer offset %d is not allowed\n",
11507 reg_type_str(env, type), reg->off);
11511 if (smin == S64_MIN) {
11512 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11513 reg_type_str(env, type));
11517 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11518 verbose(env, "value %lld makes %s pointer be out of bounds\n",
11519 smin, reg_type_str(env, type));
11527 REASON_BOUNDS = -1,
11534 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11535 u32 *alu_limit, bool mask_to_left)
11537 u32 max = 0, ptr_limit = 0;
11539 switch (ptr_reg->type) {
11541 /* Offset 0 is out-of-bounds, but acceptable start for the
11542 * left direction, see BPF_REG_FP. Also, unknown scalar
11543 * offset where we would need to deal with min/max bounds is
11544 * currently prohibited for unprivileged.
11546 max = MAX_BPF_STACK + mask_to_left;
11547 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11549 case PTR_TO_MAP_VALUE:
11550 max = ptr_reg->map_ptr->value_size;
11551 ptr_limit = (mask_to_left ?
11552 ptr_reg->smin_value :
11553 ptr_reg->umax_value) + ptr_reg->off;
11556 return REASON_TYPE;
11559 if (ptr_limit >= max)
11560 return REASON_LIMIT;
11561 *alu_limit = ptr_limit;
11565 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11566 const struct bpf_insn *insn)
11568 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11571 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11572 u32 alu_state, u32 alu_limit)
11574 /* If we arrived here from different branches with different
11575 * state or limits to sanitize, then this won't work.
11577 if (aux->alu_state &&
11578 (aux->alu_state != alu_state ||
11579 aux->alu_limit != alu_limit))
11580 return REASON_PATHS;
11582 /* Corresponding fixup done in do_misc_fixups(). */
11583 aux->alu_state = alu_state;
11584 aux->alu_limit = alu_limit;
11588 static int sanitize_val_alu(struct bpf_verifier_env *env,
11589 struct bpf_insn *insn)
11591 struct bpf_insn_aux_data *aux = cur_aux(env);
11593 if (can_skip_alu_sanitation(env, insn))
11596 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11599 static bool sanitize_needed(u8 opcode)
11601 return opcode == BPF_ADD || opcode == BPF_SUB;
11604 struct bpf_sanitize_info {
11605 struct bpf_insn_aux_data aux;
11609 static struct bpf_verifier_state *
11610 sanitize_speculative_path(struct bpf_verifier_env *env,
11611 const struct bpf_insn *insn,
11612 u32 next_idx, u32 curr_idx)
11614 struct bpf_verifier_state *branch;
11615 struct bpf_reg_state *regs;
11617 branch = push_stack(env, next_idx, curr_idx, true);
11618 if (branch && insn) {
11619 regs = branch->frame[branch->curframe]->regs;
11620 if (BPF_SRC(insn->code) == BPF_K) {
11621 mark_reg_unknown(env, regs, insn->dst_reg);
11622 } else if (BPF_SRC(insn->code) == BPF_X) {
11623 mark_reg_unknown(env, regs, insn->dst_reg);
11624 mark_reg_unknown(env, regs, insn->src_reg);
11630 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11631 struct bpf_insn *insn,
11632 const struct bpf_reg_state *ptr_reg,
11633 const struct bpf_reg_state *off_reg,
11634 struct bpf_reg_state *dst_reg,
11635 struct bpf_sanitize_info *info,
11636 const bool commit_window)
11638 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11639 struct bpf_verifier_state *vstate = env->cur_state;
11640 bool off_is_imm = tnum_is_const(off_reg->var_off);
11641 bool off_is_neg = off_reg->smin_value < 0;
11642 bool ptr_is_dst_reg = ptr_reg == dst_reg;
11643 u8 opcode = BPF_OP(insn->code);
11644 u32 alu_state, alu_limit;
11645 struct bpf_reg_state tmp;
11649 if (can_skip_alu_sanitation(env, insn))
11652 /* We already marked aux for masking from non-speculative
11653 * paths, thus we got here in the first place. We only care
11654 * to explore bad access from here.
11656 if (vstate->speculative)
11659 if (!commit_window) {
11660 if (!tnum_is_const(off_reg->var_off) &&
11661 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11662 return REASON_BOUNDS;
11664 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
11665 (opcode == BPF_SUB && !off_is_neg);
11668 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11672 if (commit_window) {
11673 /* In commit phase we narrow the masking window based on
11674 * the observed pointer move after the simulated operation.
11676 alu_state = info->aux.alu_state;
11677 alu_limit = abs(info->aux.alu_limit - alu_limit);
11679 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11680 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11681 alu_state |= ptr_is_dst_reg ?
11682 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11684 /* Limit pruning on unknown scalars to enable deep search for
11685 * potential masking differences from other program paths.
11688 env->explore_alu_limits = true;
11691 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11695 /* If we're in commit phase, we're done here given we already
11696 * pushed the truncated dst_reg into the speculative verification
11699 * Also, when register is a known constant, we rewrite register-based
11700 * operation to immediate-based, and thus do not need masking (and as
11701 * a consequence, do not need to simulate the zero-truncation either).
11703 if (commit_window || off_is_imm)
11706 /* Simulate and find potential out-of-bounds access under
11707 * speculative execution from truncation as a result of
11708 * masking when off was not within expected range. If off
11709 * sits in dst, then we temporarily need to move ptr there
11710 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11711 * for cases where we use K-based arithmetic in one direction
11712 * and truncated reg-based in the other in order to explore
11715 if (!ptr_is_dst_reg) {
11717 copy_register_state(dst_reg, ptr_reg);
11719 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11721 if (!ptr_is_dst_reg && ret)
11723 return !ret ? REASON_STACK : 0;
11726 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11728 struct bpf_verifier_state *vstate = env->cur_state;
11730 /* If we simulate paths under speculation, we don't update the
11731 * insn as 'seen' such that when we verify unreachable paths in
11732 * the non-speculative domain, sanitize_dead_code() can still
11733 * rewrite/sanitize them.
11735 if (!vstate->speculative)
11736 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11739 static int sanitize_err(struct bpf_verifier_env *env,
11740 const struct bpf_insn *insn, int reason,
11741 const struct bpf_reg_state *off_reg,
11742 const struct bpf_reg_state *dst_reg)
11744 static const char *err = "pointer arithmetic with it prohibited for !root";
11745 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11746 u32 dst = insn->dst_reg, src = insn->src_reg;
11749 case REASON_BOUNDS:
11750 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11751 off_reg == dst_reg ? dst : src, err);
11754 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11755 off_reg == dst_reg ? src : dst, err);
11758 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11762 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11766 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11770 verbose(env, "verifier internal error: unknown reason (%d)\n",
11778 /* check that stack access falls within stack limits and that 'reg' doesn't
11779 * have a variable offset.
11781 * Variable offset is prohibited for unprivileged mode for simplicity since it
11782 * requires corresponding support in Spectre masking for stack ALU. See also
11783 * retrieve_ptr_limit().
11786 * 'off' includes 'reg->off'.
11788 static int check_stack_access_for_ptr_arithmetic(
11789 struct bpf_verifier_env *env,
11791 const struct bpf_reg_state *reg,
11794 if (!tnum_is_const(reg->var_off)) {
11797 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11798 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11799 regno, tn_buf, off);
11803 if (off >= 0 || off < -MAX_BPF_STACK) {
11804 verbose(env, "R%d stack pointer arithmetic goes out of range, "
11805 "prohibited for !root; off=%d\n", regno, off);
11812 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11813 const struct bpf_insn *insn,
11814 const struct bpf_reg_state *dst_reg)
11816 u32 dst = insn->dst_reg;
11818 /* For unprivileged we require that resulting offset must be in bounds
11819 * in order to be able to sanitize access later on.
11821 if (env->bypass_spec_v1)
11824 switch (dst_reg->type) {
11826 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11827 dst_reg->off + dst_reg->var_off.value))
11830 case PTR_TO_MAP_VALUE:
11831 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
11832 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
11833 "prohibited for !root\n", dst);
11844 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
11845 * Caller should also handle BPF_MOV case separately.
11846 * If we return -EACCES, caller may want to try again treating pointer as a
11847 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
11849 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
11850 struct bpf_insn *insn,
11851 const struct bpf_reg_state *ptr_reg,
11852 const struct bpf_reg_state *off_reg)
11854 struct bpf_verifier_state *vstate = env->cur_state;
11855 struct bpf_func_state *state = vstate->frame[vstate->curframe];
11856 struct bpf_reg_state *regs = state->regs, *dst_reg;
11857 bool known = tnum_is_const(off_reg->var_off);
11858 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
11859 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
11860 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
11861 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
11862 struct bpf_sanitize_info info = {};
11863 u8 opcode = BPF_OP(insn->code);
11864 u32 dst = insn->dst_reg;
11867 dst_reg = ®s[dst];
11869 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
11870 smin_val > smax_val || umin_val > umax_val) {
11871 /* Taint dst register if offset had invalid bounds derived from
11872 * e.g. dead branches.
11874 __mark_reg_unknown(env, dst_reg);
11878 if (BPF_CLASS(insn->code) != BPF_ALU64) {
11879 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
11880 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11881 __mark_reg_unknown(env, dst_reg);
11886 "R%d 32-bit pointer arithmetic prohibited\n",
11891 if (ptr_reg->type & PTR_MAYBE_NULL) {
11892 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
11893 dst, reg_type_str(env, ptr_reg->type));
11897 switch (base_type(ptr_reg->type)) {
11898 case CONST_PTR_TO_MAP:
11899 /* smin_val represents the known value */
11900 if (known && smin_val == 0 && opcode == BPF_ADD)
11903 case PTR_TO_PACKET_END:
11904 case PTR_TO_SOCKET:
11905 case PTR_TO_SOCK_COMMON:
11906 case PTR_TO_TCP_SOCK:
11907 case PTR_TO_XDP_SOCK:
11908 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
11909 dst, reg_type_str(env, ptr_reg->type));
11915 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
11916 * The id may be overwritten later if we create a new variable offset.
11918 dst_reg->type = ptr_reg->type;
11919 dst_reg->id = ptr_reg->id;
11921 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
11922 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
11925 /* pointer types do not carry 32-bit bounds at the moment. */
11926 __mark_reg32_unbounded(dst_reg);
11928 if (sanitize_needed(opcode)) {
11929 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
11932 return sanitize_err(env, insn, ret, off_reg, dst_reg);
11937 /* We can take a fixed offset as long as it doesn't overflow
11938 * the s32 'off' field
11940 if (known && (ptr_reg->off + smin_val ==
11941 (s64)(s32)(ptr_reg->off + smin_val))) {
11942 /* pointer += K. Accumulate it into fixed offset */
11943 dst_reg->smin_value = smin_ptr;
11944 dst_reg->smax_value = smax_ptr;
11945 dst_reg->umin_value = umin_ptr;
11946 dst_reg->umax_value = umax_ptr;
11947 dst_reg->var_off = ptr_reg->var_off;
11948 dst_reg->off = ptr_reg->off + smin_val;
11949 dst_reg->raw = ptr_reg->raw;
11952 /* A new variable offset is created. Note that off_reg->off
11953 * == 0, since it's a scalar.
11954 * dst_reg gets the pointer type and since some positive
11955 * integer value was added to the pointer, give it a new 'id'
11956 * if it's a PTR_TO_PACKET.
11957 * this creates a new 'base' pointer, off_reg (variable) gets
11958 * added into the variable offset, and we copy the fixed offset
11961 if (signed_add_overflows(smin_ptr, smin_val) ||
11962 signed_add_overflows(smax_ptr, smax_val)) {
11963 dst_reg->smin_value = S64_MIN;
11964 dst_reg->smax_value = S64_MAX;
11966 dst_reg->smin_value = smin_ptr + smin_val;
11967 dst_reg->smax_value = smax_ptr + smax_val;
11969 if (umin_ptr + umin_val < umin_ptr ||
11970 umax_ptr + umax_val < umax_ptr) {
11971 dst_reg->umin_value = 0;
11972 dst_reg->umax_value = U64_MAX;
11974 dst_reg->umin_value = umin_ptr + umin_val;
11975 dst_reg->umax_value = umax_ptr + umax_val;
11977 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
11978 dst_reg->off = ptr_reg->off;
11979 dst_reg->raw = ptr_reg->raw;
11980 if (reg_is_pkt_pointer(ptr_reg)) {
11981 dst_reg->id = ++env->id_gen;
11982 /* something was added to pkt_ptr, set range to zero */
11983 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11987 if (dst_reg == off_reg) {
11988 /* scalar -= pointer. Creates an unknown scalar */
11989 verbose(env, "R%d tried to subtract pointer from scalar\n",
11993 /* We don't allow subtraction from FP, because (according to
11994 * test_verifier.c test "invalid fp arithmetic", JITs might not
11995 * be able to deal with it.
11997 if (ptr_reg->type == PTR_TO_STACK) {
11998 verbose(env, "R%d subtraction from stack pointer prohibited\n",
12002 if (known && (ptr_reg->off - smin_val ==
12003 (s64)(s32)(ptr_reg->off - smin_val))) {
12004 /* pointer -= K. Subtract it from fixed offset */
12005 dst_reg->smin_value = smin_ptr;
12006 dst_reg->smax_value = smax_ptr;
12007 dst_reg->umin_value = umin_ptr;
12008 dst_reg->umax_value = umax_ptr;
12009 dst_reg->var_off = ptr_reg->var_off;
12010 dst_reg->id = ptr_reg->id;
12011 dst_reg->off = ptr_reg->off - smin_val;
12012 dst_reg->raw = ptr_reg->raw;
12015 /* A new variable offset is created. If the subtrahend is known
12016 * nonnegative, then any reg->range we had before is still good.
12018 if (signed_sub_overflows(smin_ptr, smax_val) ||
12019 signed_sub_overflows(smax_ptr, smin_val)) {
12020 /* Overflow possible, we know nothing */
12021 dst_reg->smin_value = S64_MIN;
12022 dst_reg->smax_value = S64_MAX;
12024 dst_reg->smin_value = smin_ptr - smax_val;
12025 dst_reg->smax_value = smax_ptr - smin_val;
12027 if (umin_ptr < umax_val) {
12028 /* Overflow possible, we know nothing */
12029 dst_reg->umin_value = 0;
12030 dst_reg->umax_value = U64_MAX;
12032 /* Cannot overflow (as long as bounds are consistent) */
12033 dst_reg->umin_value = umin_ptr - umax_val;
12034 dst_reg->umax_value = umax_ptr - umin_val;
12036 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12037 dst_reg->off = ptr_reg->off;
12038 dst_reg->raw = ptr_reg->raw;
12039 if (reg_is_pkt_pointer(ptr_reg)) {
12040 dst_reg->id = ++env->id_gen;
12041 /* something was added to pkt_ptr, set range to zero */
12043 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12049 /* bitwise ops on pointers are troublesome, prohibit. */
12050 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12051 dst, bpf_alu_string[opcode >> 4]);
12054 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12055 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12056 dst, bpf_alu_string[opcode >> 4]);
12060 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12062 reg_bounds_sync(dst_reg);
12063 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12065 if (sanitize_needed(opcode)) {
12066 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12069 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12075 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12076 struct bpf_reg_state *src_reg)
12078 s32 smin_val = src_reg->s32_min_value;
12079 s32 smax_val = src_reg->s32_max_value;
12080 u32 umin_val = src_reg->u32_min_value;
12081 u32 umax_val = src_reg->u32_max_value;
12083 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12084 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12085 dst_reg->s32_min_value = S32_MIN;
12086 dst_reg->s32_max_value = S32_MAX;
12088 dst_reg->s32_min_value += smin_val;
12089 dst_reg->s32_max_value += smax_val;
12091 if (dst_reg->u32_min_value + umin_val < umin_val ||
12092 dst_reg->u32_max_value + umax_val < umax_val) {
12093 dst_reg->u32_min_value = 0;
12094 dst_reg->u32_max_value = U32_MAX;
12096 dst_reg->u32_min_value += umin_val;
12097 dst_reg->u32_max_value += umax_val;
12101 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12102 struct bpf_reg_state *src_reg)
12104 s64 smin_val = src_reg->smin_value;
12105 s64 smax_val = src_reg->smax_value;
12106 u64 umin_val = src_reg->umin_value;
12107 u64 umax_val = src_reg->umax_value;
12109 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12110 signed_add_overflows(dst_reg->smax_value, smax_val)) {
12111 dst_reg->smin_value = S64_MIN;
12112 dst_reg->smax_value = S64_MAX;
12114 dst_reg->smin_value += smin_val;
12115 dst_reg->smax_value += smax_val;
12117 if (dst_reg->umin_value + umin_val < umin_val ||
12118 dst_reg->umax_value + umax_val < umax_val) {
12119 dst_reg->umin_value = 0;
12120 dst_reg->umax_value = U64_MAX;
12122 dst_reg->umin_value += umin_val;
12123 dst_reg->umax_value += umax_val;
12127 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12128 struct bpf_reg_state *src_reg)
12130 s32 smin_val = src_reg->s32_min_value;
12131 s32 smax_val = src_reg->s32_max_value;
12132 u32 umin_val = src_reg->u32_min_value;
12133 u32 umax_val = src_reg->u32_max_value;
12135 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12136 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12137 /* Overflow possible, we know nothing */
12138 dst_reg->s32_min_value = S32_MIN;
12139 dst_reg->s32_max_value = S32_MAX;
12141 dst_reg->s32_min_value -= smax_val;
12142 dst_reg->s32_max_value -= smin_val;
12144 if (dst_reg->u32_min_value < umax_val) {
12145 /* Overflow possible, we know nothing */
12146 dst_reg->u32_min_value = 0;
12147 dst_reg->u32_max_value = U32_MAX;
12149 /* Cannot overflow (as long as bounds are consistent) */
12150 dst_reg->u32_min_value -= umax_val;
12151 dst_reg->u32_max_value -= umin_val;
12155 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12156 struct bpf_reg_state *src_reg)
12158 s64 smin_val = src_reg->smin_value;
12159 s64 smax_val = src_reg->smax_value;
12160 u64 umin_val = src_reg->umin_value;
12161 u64 umax_val = src_reg->umax_value;
12163 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12164 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12165 /* Overflow possible, we know nothing */
12166 dst_reg->smin_value = S64_MIN;
12167 dst_reg->smax_value = S64_MAX;
12169 dst_reg->smin_value -= smax_val;
12170 dst_reg->smax_value -= smin_val;
12172 if (dst_reg->umin_value < umax_val) {
12173 /* Overflow possible, we know nothing */
12174 dst_reg->umin_value = 0;
12175 dst_reg->umax_value = U64_MAX;
12177 /* Cannot overflow (as long as bounds are consistent) */
12178 dst_reg->umin_value -= umax_val;
12179 dst_reg->umax_value -= umin_val;
12183 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12184 struct bpf_reg_state *src_reg)
12186 s32 smin_val = src_reg->s32_min_value;
12187 u32 umin_val = src_reg->u32_min_value;
12188 u32 umax_val = src_reg->u32_max_value;
12190 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12191 /* Ain't nobody got time to multiply that sign */
12192 __mark_reg32_unbounded(dst_reg);
12195 /* Both values are positive, so we can work with unsigned and
12196 * copy the result to signed (unless it exceeds S32_MAX).
12198 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12199 /* Potential overflow, we know nothing */
12200 __mark_reg32_unbounded(dst_reg);
12203 dst_reg->u32_min_value *= umin_val;
12204 dst_reg->u32_max_value *= umax_val;
12205 if (dst_reg->u32_max_value > S32_MAX) {
12206 /* Overflow possible, we know nothing */
12207 dst_reg->s32_min_value = S32_MIN;
12208 dst_reg->s32_max_value = S32_MAX;
12210 dst_reg->s32_min_value = dst_reg->u32_min_value;
12211 dst_reg->s32_max_value = dst_reg->u32_max_value;
12215 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12216 struct bpf_reg_state *src_reg)
12218 s64 smin_val = src_reg->smin_value;
12219 u64 umin_val = src_reg->umin_value;
12220 u64 umax_val = src_reg->umax_value;
12222 if (smin_val < 0 || dst_reg->smin_value < 0) {
12223 /* Ain't nobody got time to multiply that sign */
12224 __mark_reg64_unbounded(dst_reg);
12227 /* Both values are positive, so we can work with unsigned and
12228 * copy the result to signed (unless it exceeds S64_MAX).
12230 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12231 /* Potential overflow, we know nothing */
12232 __mark_reg64_unbounded(dst_reg);
12235 dst_reg->umin_value *= umin_val;
12236 dst_reg->umax_value *= umax_val;
12237 if (dst_reg->umax_value > S64_MAX) {
12238 /* Overflow possible, we know nothing */
12239 dst_reg->smin_value = S64_MIN;
12240 dst_reg->smax_value = S64_MAX;
12242 dst_reg->smin_value = dst_reg->umin_value;
12243 dst_reg->smax_value = dst_reg->umax_value;
12247 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12248 struct bpf_reg_state *src_reg)
12250 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12251 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12252 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12253 s32 smin_val = src_reg->s32_min_value;
12254 u32 umax_val = src_reg->u32_max_value;
12256 if (src_known && dst_known) {
12257 __mark_reg32_known(dst_reg, var32_off.value);
12261 /* We get our minimum from the var_off, since that's inherently
12262 * bitwise. Our maximum is the minimum of the operands' maxima.
12264 dst_reg->u32_min_value = var32_off.value;
12265 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12266 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12267 /* Lose signed bounds when ANDing negative numbers,
12268 * ain't nobody got time for that.
12270 dst_reg->s32_min_value = S32_MIN;
12271 dst_reg->s32_max_value = S32_MAX;
12273 /* ANDing two positives gives a positive, so safe to
12274 * cast result into s64.
12276 dst_reg->s32_min_value = dst_reg->u32_min_value;
12277 dst_reg->s32_max_value = dst_reg->u32_max_value;
12281 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12282 struct bpf_reg_state *src_reg)
12284 bool src_known = tnum_is_const(src_reg->var_off);
12285 bool dst_known = tnum_is_const(dst_reg->var_off);
12286 s64 smin_val = src_reg->smin_value;
12287 u64 umax_val = src_reg->umax_value;
12289 if (src_known && dst_known) {
12290 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12294 /* We get our minimum from the var_off, since that's inherently
12295 * bitwise. Our maximum is the minimum of the operands' maxima.
12297 dst_reg->umin_value = dst_reg->var_off.value;
12298 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12299 if (dst_reg->smin_value < 0 || smin_val < 0) {
12300 /* Lose signed bounds when ANDing negative numbers,
12301 * ain't nobody got time for that.
12303 dst_reg->smin_value = S64_MIN;
12304 dst_reg->smax_value = S64_MAX;
12306 /* ANDing two positives gives a positive, so safe to
12307 * cast result into s64.
12309 dst_reg->smin_value = dst_reg->umin_value;
12310 dst_reg->smax_value = dst_reg->umax_value;
12312 /* We may learn something more from the var_off */
12313 __update_reg_bounds(dst_reg);
12316 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12317 struct bpf_reg_state *src_reg)
12319 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12320 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12321 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12322 s32 smin_val = src_reg->s32_min_value;
12323 u32 umin_val = src_reg->u32_min_value;
12325 if (src_known && dst_known) {
12326 __mark_reg32_known(dst_reg, var32_off.value);
12330 /* We get our maximum from the var_off, and our minimum is the
12331 * maximum of the operands' minima
12333 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12334 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12335 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12336 /* Lose signed bounds when ORing negative numbers,
12337 * ain't nobody got time for that.
12339 dst_reg->s32_min_value = S32_MIN;
12340 dst_reg->s32_max_value = S32_MAX;
12342 /* ORing two positives gives a positive, so safe to
12343 * cast result into s64.
12345 dst_reg->s32_min_value = dst_reg->u32_min_value;
12346 dst_reg->s32_max_value = dst_reg->u32_max_value;
12350 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12351 struct bpf_reg_state *src_reg)
12353 bool src_known = tnum_is_const(src_reg->var_off);
12354 bool dst_known = tnum_is_const(dst_reg->var_off);
12355 s64 smin_val = src_reg->smin_value;
12356 u64 umin_val = src_reg->umin_value;
12358 if (src_known && dst_known) {
12359 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12363 /* We get our maximum from the var_off, and our minimum is the
12364 * maximum of the operands' minima
12366 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12367 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12368 if (dst_reg->smin_value < 0 || smin_val < 0) {
12369 /* Lose signed bounds when ORing negative numbers,
12370 * ain't nobody got time for that.
12372 dst_reg->smin_value = S64_MIN;
12373 dst_reg->smax_value = S64_MAX;
12375 /* ORing two positives gives a positive, so safe to
12376 * cast result into s64.
12378 dst_reg->smin_value = dst_reg->umin_value;
12379 dst_reg->smax_value = dst_reg->umax_value;
12381 /* We may learn something more from the var_off */
12382 __update_reg_bounds(dst_reg);
12385 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12386 struct bpf_reg_state *src_reg)
12388 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12389 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12390 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12391 s32 smin_val = src_reg->s32_min_value;
12393 if (src_known && dst_known) {
12394 __mark_reg32_known(dst_reg, var32_off.value);
12398 /* We get both minimum and maximum from the var32_off. */
12399 dst_reg->u32_min_value = var32_off.value;
12400 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12402 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12403 /* XORing two positive sign numbers gives a positive,
12404 * so safe to cast u32 result into s32.
12406 dst_reg->s32_min_value = dst_reg->u32_min_value;
12407 dst_reg->s32_max_value = dst_reg->u32_max_value;
12409 dst_reg->s32_min_value = S32_MIN;
12410 dst_reg->s32_max_value = S32_MAX;
12414 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12415 struct bpf_reg_state *src_reg)
12417 bool src_known = tnum_is_const(src_reg->var_off);
12418 bool dst_known = tnum_is_const(dst_reg->var_off);
12419 s64 smin_val = src_reg->smin_value;
12421 if (src_known && dst_known) {
12422 /* dst_reg->var_off.value has been updated earlier */
12423 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12427 /* We get both minimum and maximum from the var_off. */
12428 dst_reg->umin_value = dst_reg->var_off.value;
12429 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12431 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12432 /* XORing two positive sign numbers gives a positive,
12433 * so safe to cast u64 result into s64.
12435 dst_reg->smin_value = dst_reg->umin_value;
12436 dst_reg->smax_value = dst_reg->umax_value;
12438 dst_reg->smin_value = S64_MIN;
12439 dst_reg->smax_value = S64_MAX;
12442 __update_reg_bounds(dst_reg);
12445 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12446 u64 umin_val, u64 umax_val)
12448 /* We lose all sign bit information (except what we can pick
12451 dst_reg->s32_min_value = S32_MIN;
12452 dst_reg->s32_max_value = S32_MAX;
12453 /* If we might shift our top bit out, then we know nothing */
12454 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12455 dst_reg->u32_min_value = 0;
12456 dst_reg->u32_max_value = U32_MAX;
12458 dst_reg->u32_min_value <<= umin_val;
12459 dst_reg->u32_max_value <<= umax_val;
12463 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12464 struct bpf_reg_state *src_reg)
12466 u32 umax_val = src_reg->u32_max_value;
12467 u32 umin_val = src_reg->u32_min_value;
12468 /* u32 alu operation will zext upper bits */
12469 struct tnum subreg = tnum_subreg(dst_reg->var_off);
12471 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12472 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12473 /* Not required but being careful mark reg64 bounds as unknown so
12474 * that we are forced to pick them up from tnum and zext later and
12475 * if some path skips this step we are still safe.
12477 __mark_reg64_unbounded(dst_reg);
12478 __update_reg32_bounds(dst_reg);
12481 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12482 u64 umin_val, u64 umax_val)
12484 /* Special case <<32 because it is a common compiler pattern to sign
12485 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12486 * positive we know this shift will also be positive so we can track
12487 * bounds correctly. Otherwise we lose all sign bit information except
12488 * what we can pick up from var_off. Perhaps we can generalize this
12489 * later to shifts of any length.
12491 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12492 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12494 dst_reg->smax_value = S64_MAX;
12496 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12497 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12499 dst_reg->smin_value = S64_MIN;
12501 /* If we might shift our top bit out, then we know nothing */
12502 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12503 dst_reg->umin_value = 0;
12504 dst_reg->umax_value = U64_MAX;
12506 dst_reg->umin_value <<= umin_val;
12507 dst_reg->umax_value <<= umax_val;
12511 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12512 struct bpf_reg_state *src_reg)
12514 u64 umax_val = src_reg->umax_value;
12515 u64 umin_val = src_reg->umin_value;
12517 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
12518 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12519 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12521 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12522 /* We may learn something more from the var_off */
12523 __update_reg_bounds(dst_reg);
12526 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12527 struct bpf_reg_state *src_reg)
12529 struct tnum subreg = tnum_subreg(dst_reg->var_off);
12530 u32 umax_val = src_reg->u32_max_value;
12531 u32 umin_val = src_reg->u32_min_value;
12533 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12534 * be negative, then either:
12535 * 1) src_reg might be zero, so the sign bit of the result is
12536 * unknown, so we lose our signed bounds
12537 * 2) it's known negative, thus the unsigned bounds capture the
12539 * 3) the signed bounds cross zero, so they tell us nothing
12541 * If the value in dst_reg is known nonnegative, then again the
12542 * unsigned bounds capture the signed bounds.
12543 * Thus, in all cases it suffices to blow away our signed bounds
12544 * and rely on inferring new ones from the unsigned bounds and
12545 * var_off of the result.
12547 dst_reg->s32_min_value = S32_MIN;
12548 dst_reg->s32_max_value = S32_MAX;
12550 dst_reg->var_off = tnum_rshift(subreg, umin_val);
12551 dst_reg->u32_min_value >>= umax_val;
12552 dst_reg->u32_max_value >>= umin_val;
12554 __mark_reg64_unbounded(dst_reg);
12555 __update_reg32_bounds(dst_reg);
12558 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12559 struct bpf_reg_state *src_reg)
12561 u64 umax_val = src_reg->umax_value;
12562 u64 umin_val = src_reg->umin_value;
12564 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12565 * be negative, then either:
12566 * 1) src_reg might be zero, so the sign bit of the result is
12567 * unknown, so we lose our signed bounds
12568 * 2) it's known negative, thus the unsigned bounds capture the
12570 * 3) the signed bounds cross zero, so they tell us nothing
12572 * If the value in dst_reg is known nonnegative, then again the
12573 * unsigned bounds capture the signed bounds.
12574 * Thus, in all cases it suffices to blow away our signed bounds
12575 * and rely on inferring new ones from the unsigned bounds and
12576 * var_off of the result.
12578 dst_reg->smin_value = S64_MIN;
12579 dst_reg->smax_value = S64_MAX;
12580 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12581 dst_reg->umin_value >>= umax_val;
12582 dst_reg->umax_value >>= umin_val;
12584 /* Its not easy to operate on alu32 bounds here because it depends
12585 * on bits being shifted in. Take easy way out and mark unbounded
12586 * so we can recalculate later from tnum.
12588 __mark_reg32_unbounded(dst_reg);
12589 __update_reg_bounds(dst_reg);
12592 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12593 struct bpf_reg_state *src_reg)
12595 u64 umin_val = src_reg->u32_min_value;
12597 /* Upon reaching here, src_known is true and
12598 * umax_val is equal to umin_val.
12600 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12601 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12603 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12605 /* blow away the dst_reg umin_value/umax_value and rely on
12606 * dst_reg var_off to refine the result.
12608 dst_reg->u32_min_value = 0;
12609 dst_reg->u32_max_value = U32_MAX;
12611 __mark_reg64_unbounded(dst_reg);
12612 __update_reg32_bounds(dst_reg);
12615 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12616 struct bpf_reg_state *src_reg)
12618 u64 umin_val = src_reg->umin_value;
12620 /* Upon reaching here, src_known is true and umax_val is equal
12623 dst_reg->smin_value >>= umin_val;
12624 dst_reg->smax_value >>= umin_val;
12626 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12628 /* blow away the dst_reg umin_value/umax_value and rely on
12629 * dst_reg var_off to refine the result.
12631 dst_reg->umin_value = 0;
12632 dst_reg->umax_value = U64_MAX;
12634 /* Its not easy to operate on alu32 bounds here because it depends
12635 * on bits being shifted in from upper 32-bits. Take easy way out
12636 * and mark unbounded so we can recalculate later from tnum.
12638 __mark_reg32_unbounded(dst_reg);
12639 __update_reg_bounds(dst_reg);
12642 /* WARNING: This function does calculations on 64-bit values, but the actual
12643 * execution may occur on 32-bit values. Therefore, things like bitshifts
12644 * need extra checks in the 32-bit case.
12646 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12647 struct bpf_insn *insn,
12648 struct bpf_reg_state *dst_reg,
12649 struct bpf_reg_state src_reg)
12651 struct bpf_reg_state *regs = cur_regs(env);
12652 u8 opcode = BPF_OP(insn->code);
12654 s64 smin_val, smax_val;
12655 u64 umin_val, umax_val;
12656 s32 s32_min_val, s32_max_val;
12657 u32 u32_min_val, u32_max_val;
12658 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12659 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12662 smin_val = src_reg.smin_value;
12663 smax_val = src_reg.smax_value;
12664 umin_val = src_reg.umin_value;
12665 umax_val = src_reg.umax_value;
12667 s32_min_val = src_reg.s32_min_value;
12668 s32_max_val = src_reg.s32_max_value;
12669 u32_min_val = src_reg.u32_min_value;
12670 u32_max_val = src_reg.u32_max_value;
12673 src_known = tnum_subreg_is_const(src_reg.var_off);
12675 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12676 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12677 /* Taint dst register if offset had invalid bounds
12678 * derived from e.g. dead branches.
12680 __mark_reg_unknown(env, dst_reg);
12684 src_known = tnum_is_const(src_reg.var_off);
12686 (smin_val != smax_val || umin_val != umax_val)) ||
12687 smin_val > smax_val || umin_val > umax_val) {
12688 /* Taint dst register if offset had invalid bounds
12689 * derived from e.g. dead branches.
12691 __mark_reg_unknown(env, dst_reg);
12697 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12698 __mark_reg_unknown(env, dst_reg);
12702 if (sanitize_needed(opcode)) {
12703 ret = sanitize_val_alu(env, insn);
12705 return sanitize_err(env, insn, ret, NULL, NULL);
12708 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12709 * There are two classes of instructions: The first class we track both
12710 * alu32 and alu64 sign/unsigned bounds independently this provides the
12711 * greatest amount of precision when alu operations are mixed with jmp32
12712 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12713 * and BPF_OR. This is possible because these ops have fairly easy to
12714 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12715 * See alu32 verifier tests for examples. The second class of
12716 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12717 * with regards to tracking sign/unsigned bounds because the bits may
12718 * cross subreg boundaries in the alu64 case. When this happens we mark
12719 * the reg unbounded in the subreg bound space and use the resulting
12720 * tnum to calculate an approximation of the sign/unsigned bounds.
12724 scalar32_min_max_add(dst_reg, &src_reg);
12725 scalar_min_max_add(dst_reg, &src_reg);
12726 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12729 scalar32_min_max_sub(dst_reg, &src_reg);
12730 scalar_min_max_sub(dst_reg, &src_reg);
12731 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12734 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12735 scalar32_min_max_mul(dst_reg, &src_reg);
12736 scalar_min_max_mul(dst_reg, &src_reg);
12739 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12740 scalar32_min_max_and(dst_reg, &src_reg);
12741 scalar_min_max_and(dst_reg, &src_reg);
12744 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12745 scalar32_min_max_or(dst_reg, &src_reg);
12746 scalar_min_max_or(dst_reg, &src_reg);
12749 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12750 scalar32_min_max_xor(dst_reg, &src_reg);
12751 scalar_min_max_xor(dst_reg, &src_reg);
12754 if (umax_val >= insn_bitness) {
12755 /* Shifts greater than 31 or 63 are undefined.
12756 * This includes shifts by a negative number.
12758 mark_reg_unknown(env, regs, insn->dst_reg);
12762 scalar32_min_max_lsh(dst_reg, &src_reg);
12764 scalar_min_max_lsh(dst_reg, &src_reg);
12767 if (umax_val >= insn_bitness) {
12768 /* Shifts greater than 31 or 63 are undefined.
12769 * This includes shifts by a negative number.
12771 mark_reg_unknown(env, regs, insn->dst_reg);
12775 scalar32_min_max_rsh(dst_reg, &src_reg);
12777 scalar_min_max_rsh(dst_reg, &src_reg);
12780 if (umax_val >= insn_bitness) {
12781 /* Shifts greater than 31 or 63 are undefined.
12782 * This includes shifts by a negative number.
12784 mark_reg_unknown(env, regs, insn->dst_reg);
12788 scalar32_min_max_arsh(dst_reg, &src_reg);
12790 scalar_min_max_arsh(dst_reg, &src_reg);
12793 mark_reg_unknown(env, regs, insn->dst_reg);
12797 /* ALU32 ops are zero extended into 64bit register */
12799 zext_32_to_64(dst_reg);
12800 reg_bounds_sync(dst_reg);
12804 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12807 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12808 struct bpf_insn *insn)
12810 struct bpf_verifier_state *vstate = env->cur_state;
12811 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12812 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12813 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12814 u8 opcode = BPF_OP(insn->code);
12817 dst_reg = ®s[insn->dst_reg];
12819 if (dst_reg->type != SCALAR_VALUE)
12822 /* Make sure ID is cleared otherwise dst_reg min/max could be
12823 * incorrectly propagated into other registers by find_equal_scalars()
12826 if (BPF_SRC(insn->code) == BPF_X) {
12827 src_reg = ®s[insn->src_reg];
12828 if (src_reg->type != SCALAR_VALUE) {
12829 if (dst_reg->type != SCALAR_VALUE) {
12830 /* Combining two pointers by any ALU op yields
12831 * an arbitrary scalar. Disallow all math except
12832 * pointer subtraction
12834 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12835 mark_reg_unknown(env, regs, insn->dst_reg);
12838 verbose(env, "R%d pointer %s pointer prohibited\n",
12840 bpf_alu_string[opcode >> 4]);
12843 /* scalar += pointer
12844 * This is legal, but we have to reverse our
12845 * src/dest handling in computing the range
12847 err = mark_chain_precision(env, insn->dst_reg);
12850 return adjust_ptr_min_max_vals(env, insn,
12853 } else if (ptr_reg) {
12854 /* pointer += scalar */
12855 err = mark_chain_precision(env, insn->src_reg);
12858 return adjust_ptr_min_max_vals(env, insn,
12860 } else if (dst_reg->precise) {
12861 /* if dst_reg is precise, src_reg should be precise as well */
12862 err = mark_chain_precision(env, insn->src_reg);
12867 /* Pretend the src is a reg with a known value, since we only
12868 * need to be able to read from this state.
12870 off_reg.type = SCALAR_VALUE;
12871 __mark_reg_known(&off_reg, insn->imm);
12872 src_reg = &off_reg;
12873 if (ptr_reg) /* pointer += K */
12874 return adjust_ptr_min_max_vals(env, insn,
12878 /* Got here implies adding two SCALAR_VALUEs */
12879 if (WARN_ON_ONCE(ptr_reg)) {
12880 print_verifier_state(env, state, true);
12881 verbose(env, "verifier internal error: unexpected ptr_reg\n");
12884 if (WARN_ON(!src_reg)) {
12885 print_verifier_state(env, state, true);
12886 verbose(env, "verifier internal error: no src_reg\n");
12889 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
12892 /* check validity of 32-bit and 64-bit arithmetic operations */
12893 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
12895 struct bpf_reg_state *regs = cur_regs(env);
12896 u8 opcode = BPF_OP(insn->code);
12899 if (opcode == BPF_END || opcode == BPF_NEG) {
12900 if (opcode == BPF_NEG) {
12901 if (BPF_SRC(insn->code) != BPF_K ||
12902 insn->src_reg != BPF_REG_0 ||
12903 insn->off != 0 || insn->imm != 0) {
12904 verbose(env, "BPF_NEG uses reserved fields\n");
12908 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
12909 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
12910 BPF_CLASS(insn->code) == BPF_ALU64) {
12911 verbose(env, "BPF_END uses reserved fields\n");
12916 /* check src operand */
12917 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12921 if (is_pointer_value(env, insn->dst_reg)) {
12922 verbose(env, "R%d pointer arithmetic prohibited\n",
12927 /* check dest operand */
12928 err = check_reg_arg(env, insn->dst_reg, DST_OP);
12932 } else if (opcode == BPF_MOV) {
12934 if (BPF_SRC(insn->code) == BPF_X) {
12935 if (insn->imm != 0 || insn->off != 0) {
12936 verbose(env, "BPF_MOV uses reserved fields\n");
12940 /* check src operand */
12941 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12945 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12946 verbose(env, "BPF_MOV uses reserved fields\n");
12951 /* check dest operand, mark as required later */
12952 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12956 if (BPF_SRC(insn->code) == BPF_X) {
12957 struct bpf_reg_state *src_reg = regs + insn->src_reg;
12958 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
12959 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
12960 !tnum_is_const(src_reg->var_off);
12962 if (BPF_CLASS(insn->code) == BPF_ALU64) {
12964 * copy register state to dest reg
12967 /* Assign src and dst registers the same ID
12968 * that will be used by find_equal_scalars()
12969 * to propagate min/max range.
12971 src_reg->id = ++env->id_gen;
12972 copy_register_state(dst_reg, src_reg);
12973 dst_reg->live |= REG_LIVE_WRITTEN;
12974 dst_reg->subreg_def = DEF_NOT_SUBREG;
12976 /* R1 = (u32) R2 */
12977 if (is_pointer_value(env, insn->src_reg)) {
12979 "R%d partial copy of pointer\n",
12982 } else if (src_reg->type == SCALAR_VALUE) {
12983 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
12985 if (is_src_reg_u32 && need_id)
12986 src_reg->id = ++env->id_gen;
12987 copy_register_state(dst_reg, src_reg);
12988 /* Make sure ID is cleared if src_reg is not in u32 range otherwise
12989 * dst_reg min/max could be incorrectly
12990 * propagated into src_reg by find_equal_scalars()
12992 if (!is_src_reg_u32)
12994 dst_reg->live |= REG_LIVE_WRITTEN;
12995 dst_reg->subreg_def = env->insn_idx + 1;
12997 mark_reg_unknown(env, regs,
13000 zext_32_to_64(dst_reg);
13001 reg_bounds_sync(dst_reg);
13005 * remember the value we stored into this reg
13007 /* clear any state __mark_reg_known doesn't set */
13008 mark_reg_unknown(env, regs, insn->dst_reg);
13009 regs[insn->dst_reg].type = SCALAR_VALUE;
13010 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13011 __mark_reg_known(regs + insn->dst_reg,
13014 __mark_reg_known(regs + insn->dst_reg,
13019 } else if (opcode > BPF_END) {
13020 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13023 } else { /* all other ALU ops: and, sub, xor, add, ... */
13025 if (BPF_SRC(insn->code) == BPF_X) {
13026 if (insn->imm != 0 || insn->off != 0) {
13027 verbose(env, "BPF_ALU uses reserved fields\n");
13030 /* check src1 operand */
13031 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13035 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13036 verbose(env, "BPF_ALU uses reserved fields\n");
13041 /* check src2 operand */
13042 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13046 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13047 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13048 verbose(env, "div by zero\n");
13052 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13053 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13054 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13056 if (insn->imm < 0 || insn->imm >= size) {
13057 verbose(env, "invalid shift %d\n", insn->imm);
13062 /* check dest operand */
13063 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13067 return adjust_reg_min_max_vals(env, insn);
13073 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13074 struct bpf_reg_state *dst_reg,
13075 enum bpf_reg_type type,
13076 bool range_right_open)
13078 struct bpf_func_state *state;
13079 struct bpf_reg_state *reg;
13082 if (dst_reg->off < 0 ||
13083 (dst_reg->off == 0 && range_right_open))
13084 /* This doesn't give us any range */
13087 if (dst_reg->umax_value > MAX_PACKET_OFF ||
13088 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13089 /* Risk of overflow. For instance, ptr + (1<<63) may be less
13090 * than pkt_end, but that's because it's also less than pkt.
13094 new_range = dst_reg->off;
13095 if (range_right_open)
13098 /* Examples for register markings:
13100 * pkt_data in dst register:
13104 * if (r2 > pkt_end) goto <handle exception>
13109 * if (r2 < pkt_end) goto <access okay>
13110 * <handle exception>
13113 * r2 == dst_reg, pkt_end == src_reg
13114 * r2=pkt(id=n,off=8,r=0)
13115 * r3=pkt(id=n,off=0,r=0)
13117 * pkt_data in src register:
13121 * if (pkt_end >= r2) goto <access okay>
13122 * <handle exception>
13126 * if (pkt_end <= r2) goto <handle exception>
13130 * pkt_end == dst_reg, r2 == src_reg
13131 * r2=pkt(id=n,off=8,r=0)
13132 * r3=pkt(id=n,off=0,r=0)
13134 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13135 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13136 * and [r3, r3 + 8-1) respectively is safe to access depending on
13140 /* If our ids match, then we must have the same max_value. And we
13141 * don't care about the other reg's fixed offset, since if it's too big
13142 * the range won't allow anything.
13143 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13145 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13146 if (reg->type == type && reg->id == dst_reg->id)
13147 /* keep the maximum range already checked */
13148 reg->range = max(reg->range, new_range);
13152 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13154 struct tnum subreg = tnum_subreg(reg->var_off);
13155 s32 sval = (s32)val;
13159 if (tnum_is_const(subreg))
13160 return !!tnum_equals_const(subreg, val);
13161 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13165 if (tnum_is_const(subreg))
13166 return !tnum_equals_const(subreg, val);
13167 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13171 if ((~subreg.mask & subreg.value) & val)
13173 if (!((subreg.mask | subreg.value) & val))
13177 if (reg->u32_min_value > val)
13179 else if (reg->u32_max_value <= val)
13183 if (reg->s32_min_value > sval)
13185 else if (reg->s32_max_value <= sval)
13189 if (reg->u32_max_value < val)
13191 else if (reg->u32_min_value >= val)
13195 if (reg->s32_max_value < sval)
13197 else if (reg->s32_min_value >= sval)
13201 if (reg->u32_min_value >= val)
13203 else if (reg->u32_max_value < val)
13207 if (reg->s32_min_value >= sval)
13209 else if (reg->s32_max_value < sval)
13213 if (reg->u32_max_value <= val)
13215 else if (reg->u32_min_value > val)
13219 if (reg->s32_max_value <= sval)
13221 else if (reg->s32_min_value > sval)
13230 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13232 s64 sval = (s64)val;
13236 if (tnum_is_const(reg->var_off))
13237 return !!tnum_equals_const(reg->var_off, val);
13238 else if (val < reg->umin_value || val > reg->umax_value)
13242 if (tnum_is_const(reg->var_off))
13243 return !tnum_equals_const(reg->var_off, val);
13244 else if (val < reg->umin_value || val > reg->umax_value)
13248 if ((~reg->var_off.mask & reg->var_off.value) & val)
13250 if (!((reg->var_off.mask | reg->var_off.value) & val))
13254 if (reg->umin_value > val)
13256 else if (reg->umax_value <= val)
13260 if (reg->smin_value > sval)
13262 else if (reg->smax_value <= sval)
13266 if (reg->umax_value < val)
13268 else if (reg->umin_value >= val)
13272 if (reg->smax_value < sval)
13274 else if (reg->smin_value >= sval)
13278 if (reg->umin_value >= val)
13280 else if (reg->umax_value < val)
13284 if (reg->smin_value >= sval)
13286 else if (reg->smax_value < sval)
13290 if (reg->umax_value <= val)
13292 else if (reg->umin_value > val)
13296 if (reg->smax_value <= sval)
13298 else if (reg->smin_value > sval)
13306 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13308 * 1 - branch will be taken and "goto target" will be executed
13309 * 0 - branch will not be taken and fall-through to next insn
13310 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13313 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13316 if (__is_pointer_value(false, reg)) {
13317 if (!reg_not_null(reg))
13320 /* If pointer is valid tests against zero will fail so we can
13321 * use this to direct branch taken.
13337 return is_branch32_taken(reg, val, opcode);
13338 return is_branch64_taken(reg, val, opcode);
13341 static int flip_opcode(u32 opcode)
13343 /* How can we transform "a <op> b" into "b <op> a"? */
13344 static const u8 opcode_flip[16] = {
13345 /* these stay the same */
13346 [BPF_JEQ >> 4] = BPF_JEQ,
13347 [BPF_JNE >> 4] = BPF_JNE,
13348 [BPF_JSET >> 4] = BPF_JSET,
13349 /* these swap "lesser" and "greater" (L and G in the opcodes) */
13350 [BPF_JGE >> 4] = BPF_JLE,
13351 [BPF_JGT >> 4] = BPF_JLT,
13352 [BPF_JLE >> 4] = BPF_JGE,
13353 [BPF_JLT >> 4] = BPF_JGT,
13354 [BPF_JSGE >> 4] = BPF_JSLE,
13355 [BPF_JSGT >> 4] = BPF_JSLT,
13356 [BPF_JSLE >> 4] = BPF_JSGE,
13357 [BPF_JSLT >> 4] = BPF_JSGT
13359 return opcode_flip[opcode >> 4];
13362 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13363 struct bpf_reg_state *src_reg,
13366 struct bpf_reg_state *pkt;
13368 if (src_reg->type == PTR_TO_PACKET_END) {
13370 } else if (dst_reg->type == PTR_TO_PACKET_END) {
13372 opcode = flip_opcode(opcode);
13377 if (pkt->range >= 0)
13382 /* pkt <= pkt_end */
13385 /* pkt > pkt_end */
13386 if (pkt->range == BEYOND_PKT_END)
13387 /* pkt has at last one extra byte beyond pkt_end */
13388 return opcode == BPF_JGT;
13391 /* pkt < pkt_end */
13394 /* pkt >= pkt_end */
13395 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13396 return opcode == BPF_JGE;
13402 /* Adjusts the register min/max values in the case that the dst_reg is the
13403 * variable register that we are working on, and src_reg is a constant or we're
13404 * simply doing a BPF_K check.
13405 * In JEQ/JNE cases we also adjust the var_off values.
13407 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13408 struct bpf_reg_state *false_reg,
13409 u64 val, u32 val32,
13410 u8 opcode, bool is_jmp32)
13412 struct tnum false_32off = tnum_subreg(false_reg->var_off);
13413 struct tnum false_64off = false_reg->var_off;
13414 struct tnum true_32off = tnum_subreg(true_reg->var_off);
13415 struct tnum true_64off = true_reg->var_off;
13416 s64 sval = (s64)val;
13417 s32 sval32 = (s32)val32;
13419 /* If the dst_reg is a pointer, we can't learn anything about its
13420 * variable offset from the compare (unless src_reg were a pointer into
13421 * the same object, but we don't bother with that.
13422 * Since false_reg and true_reg have the same type by construction, we
13423 * only need to check one of them for pointerness.
13425 if (__is_pointer_value(false, false_reg))
13429 /* JEQ/JNE comparison doesn't change the register equivalence.
13432 * if (r1 == 42) goto label;
13434 * label: // here both r1 and r2 are known to be 42.
13436 * Hence when marking register as known preserve it's ID.
13440 __mark_reg32_known(true_reg, val32);
13441 true_32off = tnum_subreg(true_reg->var_off);
13443 ___mark_reg_known(true_reg, val);
13444 true_64off = true_reg->var_off;
13449 __mark_reg32_known(false_reg, val32);
13450 false_32off = tnum_subreg(false_reg->var_off);
13452 ___mark_reg_known(false_reg, val);
13453 false_64off = false_reg->var_off;
13458 false_32off = tnum_and(false_32off, tnum_const(~val32));
13459 if (is_power_of_2(val32))
13460 true_32off = tnum_or(true_32off,
13461 tnum_const(val32));
13463 false_64off = tnum_and(false_64off, tnum_const(~val));
13464 if (is_power_of_2(val))
13465 true_64off = tnum_or(true_64off,
13473 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
13474 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13476 false_reg->u32_max_value = min(false_reg->u32_max_value,
13478 true_reg->u32_min_value = max(true_reg->u32_min_value,
13481 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
13482 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13484 false_reg->umax_value = min(false_reg->umax_value, false_umax);
13485 true_reg->umin_value = max(true_reg->umin_value, true_umin);
13493 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
13494 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13496 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13497 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13499 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
13500 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13502 false_reg->smax_value = min(false_reg->smax_value, false_smax);
13503 true_reg->smin_value = max(true_reg->smin_value, true_smin);
13511 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
13512 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13514 false_reg->u32_min_value = max(false_reg->u32_min_value,
13516 true_reg->u32_max_value = min(true_reg->u32_max_value,
13519 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
13520 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13522 false_reg->umin_value = max(false_reg->umin_value, false_umin);
13523 true_reg->umax_value = min(true_reg->umax_value, true_umax);
13531 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
13532 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13534 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13535 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13537 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
13538 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13540 false_reg->smin_value = max(false_reg->smin_value, false_smin);
13541 true_reg->smax_value = min(true_reg->smax_value, true_smax);
13550 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13551 tnum_subreg(false_32off));
13552 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13553 tnum_subreg(true_32off));
13554 __reg_combine_32_into_64(false_reg);
13555 __reg_combine_32_into_64(true_reg);
13557 false_reg->var_off = false_64off;
13558 true_reg->var_off = true_64off;
13559 __reg_combine_64_into_32(false_reg);
13560 __reg_combine_64_into_32(true_reg);
13564 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13565 * the variable reg.
13567 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13568 struct bpf_reg_state *false_reg,
13569 u64 val, u32 val32,
13570 u8 opcode, bool is_jmp32)
13572 opcode = flip_opcode(opcode);
13573 /* This uses zero as "not present in table"; luckily the zero opcode,
13574 * BPF_JA, can't get here.
13577 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13580 /* Regs are known to be equal, so intersect their min/max/var_off */
13581 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13582 struct bpf_reg_state *dst_reg)
13584 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13585 dst_reg->umin_value);
13586 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13587 dst_reg->umax_value);
13588 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13589 dst_reg->smin_value);
13590 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13591 dst_reg->smax_value);
13592 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13594 reg_bounds_sync(src_reg);
13595 reg_bounds_sync(dst_reg);
13598 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13599 struct bpf_reg_state *true_dst,
13600 struct bpf_reg_state *false_src,
13601 struct bpf_reg_state *false_dst,
13606 __reg_combine_min_max(true_src, true_dst);
13609 __reg_combine_min_max(false_src, false_dst);
13614 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13615 struct bpf_reg_state *reg, u32 id,
13618 if (type_may_be_null(reg->type) && reg->id == id &&
13619 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13620 /* Old offset (both fixed and variable parts) should have been
13621 * known-zero, because we don't allow pointer arithmetic on
13622 * pointers that might be NULL. If we see this happening, don't
13623 * convert the register.
13625 * But in some cases, some helpers that return local kptrs
13626 * advance offset for the returned pointer. In those cases, it
13627 * is fine to expect to see reg->off.
13629 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13631 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13632 WARN_ON_ONCE(reg->off))
13636 reg->type = SCALAR_VALUE;
13637 /* We don't need id and ref_obj_id from this point
13638 * onwards anymore, thus we should better reset it,
13639 * so that state pruning has chances to take effect.
13642 reg->ref_obj_id = 0;
13647 mark_ptr_not_null_reg(reg);
13649 if (!reg_may_point_to_spin_lock(reg)) {
13650 /* For not-NULL ptr, reg->ref_obj_id will be reset
13651 * in release_reference().
13653 * reg->id is still used by spin_lock ptr. Other
13654 * than spin_lock ptr type, reg->id can be reset.
13661 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13662 * be folded together at some point.
13664 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13667 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13668 struct bpf_reg_state *regs = state->regs, *reg;
13669 u32 ref_obj_id = regs[regno].ref_obj_id;
13670 u32 id = regs[regno].id;
13672 if (ref_obj_id && ref_obj_id == id && is_null)
13673 /* regs[regno] is in the " == NULL" branch.
13674 * No one could have freed the reference state before
13675 * doing the NULL check.
13677 WARN_ON_ONCE(release_reference_state(state, id));
13679 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13680 mark_ptr_or_null_reg(state, reg, id, is_null);
13684 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13685 struct bpf_reg_state *dst_reg,
13686 struct bpf_reg_state *src_reg,
13687 struct bpf_verifier_state *this_branch,
13688 struct bpf_verifier_state *other_branch)
13690 if (BPF_SRC(insn->code) != BPF_X)
13693 /* Pointers are always 64-bit. */
13694 if (BPF_CLASS(insn->code) == BPF_JMP32)
13697 switch (BPF_OP(insn->code)) {
13699 if ((dst_reg->type == PTR_TO_PACKET &&
13700 src_reg->type == PTR_TO_PACKET_END) ||
13701 (dst_reg->type == PTR_TO_PACKET_META &&
13702 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13703 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13704 find_good_pkt_pointers(this_branch, dst_reg,
13705 dst_reg->type, false);
13706 mark_pkt_end(other_branch, insn->dst_reg, true);
13707 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13708 src_reg->type == PTR_TO_PACKET) ||
13709 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13710 src_reg->type == PTR_TO_PACKET_META)) {
13711 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13712 find_good_pkt_pointers(other_branch, src_reg,
13713 src_reg->type, true);
13714 mark_pkt_end(this_branch, insn->src_reg, false);
13720 if ((dst_reg->type == PTR_TO_PACKET &&
13721 src_reg->type == PTR_TO_PACKET_END) ||
13722 (dst_reg->type == PTR_TO_PACKET_META &&
13723 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13724 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13725 find_good_pkt_pointers(other_branch, dst_reg,
13726 dst_reg->type, true);
13727 mark_pkt_end(this_branch, insn->dst_reg, false);
13728 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13729 src_reg->type == PTR_TO_PACKET) ||
13730 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13731 src_reg->type == PTR_TO_PACKET_META)) {
13732 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13733 find_good_pkt_pointers(this_branch, src_reg,
13734 src_reg->type, false);
13735 mark_pkt_end(other_branch, insn->src_reg, true);
13741 if ((dst_reg->type == PTR_TO_PACKET &&
13742 src_reg->type == PTR_TO_PACKET_END) ||
13743 (dst_reg->type == PTR_TO_PACKET_META &&
13744 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13745 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13746 find_good_pkt_pointers(this_branch, dst_reg,
13747 dst_reg->type, true);
13748 mark_pkt_end(other_branch, insn->dst_reg, false);
13749 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13750 src_reg->type == PTR_TO_PACKET) ||
13751 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13752 src_reg->type == PTR_TO_PACKET_META)) {
13753 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13754 find_good_pkt_pointers(other_branch, src_reg,
13755 src_reg->type, false);
13756 mark_pkt_end(this_branch, insn->src_reg, true);
13762 if ((dst_reg->type == PTR_TO_PACKET &&
13763 src_reg->type == PTR_TO_PACKET_END) ||
13764 (dst_reg->type == PTR_TO_PACKET_META &&
13765 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13766 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13767 find_good_pkt_pointers(other_branch, dst_reg,
13768 dst_reg->type, false);
13769 mark_pkt_end(this_branch, insn->dst_reg, true);
13770 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13771 src_reg->type == PTR_TO_PACKET) ||
13772 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13773 src_reg->type == PTR_TO_PACKET_META)) {
13774 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13775 find_good_pkt_pointers(this_branch, src_reg,
13776 src_reg->type, true);
13777 mark_pkt_end(other_branch, insn->src_reg, false);
13789 static void find_equal_scalars(struct bpf_verifier_state *vstate,
13790 struct bpf_reg_state *known_reg)
13792 struct bpf_func_state *state;
13793 struct bpf_reg_state *reg;
13795 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13796 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
13797 copy_register_state(reg, known_reg);
13801 static int check_cond_jmp_op(struct bpf_verifier_env *env,
13802 struct bpf_insn *insn, int *insn_idx)
13804 struct bpf_verifier_state *this_branch = env->cur_state;
13805 struct bpf_verifier_state *other_branch;
13806 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
13807 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
13808 struct bpf_reg_state *eq_branch_regs;
13809 u8 opcode = BPF_OP(insn->code);
13814 /* Only conditional jumps are expected to reach here. */
13815 if (opcode == BPF_JA || opcode > BPF_JSLE) {
13816 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
13820 if (BPF_SRC(insn->code) == BPF_X) {
13821 if (insn->imm != 0) {
13822 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13826 /* check src1 operand */
13827 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13831 if (is_pointer_value(env, insn->src_reg)) {
13832 verbose(env, "R%d pointer comparison prohibited\n",
13836 src_reg = ®s[insn->src_reg];
13838 if (insn->src_reg != BPF_REG_0) {
13839 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13844 /* check src2 operand */
13845 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13849 dst_reg = ®s[insn->dst_reg];
13850 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
13852 if (BPF_SRC(insn->code) == BPF_K) {
13853 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
13854 } else if (src_reg->type == SCALAR_VALUE &&
13855 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
13856 pred = is_branch_taken(dst_reg,
13857 tnum_subreg(src_reg->var_off).value,
13860 } else if (src_reg->type == SCALAR_VALUE &&
13861 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
13862 pred = is_branch_taken(dst_reg,
13863 src_reg->var_off.value,
13866 } else if (dst_reg->type == SCALAR_VALUE &&
13867 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
13868 pred = is_branch_taken(src_reg,
13869 tnum_subreg(dst_reg->var_off).value,
13870 flip_opcode(opcode),
13872 } else if (dst_reg->type == SCALAR_VALUE &&
13873 !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
13874 pred = is_branch_taken(src_reg,
13875 dst_reg->var_off.value,
13876 flip_opcode(opcode),
13878 } else if (reg_is_pkt_pointer_any(dst_reg) &&
13879 reg_is_pkt_pointer_any(src_reg) &&
13881 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
13885 /* If we get here with a dst_reg pointer type it is because
13886 * above is_branch_taken() special cased the 0 comparison.
13888 if (!__is_pointer_value(false, dst_reg))
13889 err = mark_chain_precision(env, insn->dst_reg);
13890 if (BPF_SRC(insn->code) == BPF_X && !err &&
13891 !__is_pointer_value(false, src_reg))
13892 err = mark_chain_precision(env, insn->src_reg);
13898 /* Only follow the goto, ignore fall-through. If needed, push
13899 * the fall-through branch for simulation under speculative
13902 if (!env->bypass_spec_v1 &&
13903 !sanitize_speculative_path(env, insn, *insn_idx + 1,
13906 *insn_idx += insn->off;
13908 } else if (pred == 0) {
13909 /* Only follow the fall-through branch, since that's where the
13910 * program will go. If needed, push the goto branch for
13911 * simulation under speculative execution.
13913 if (!env->bypass_spec_v1 &&
13914 !sanitize_speculative_path(env, insn,
13915 *insn_idx + insn->off + 1,
13921 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
13925 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
13927 /* detect if we are comparing against a constant value so we can adjust
13928 * our min/max values for our dst register.
13929 * this is only legit if both are scalars (or pointers to the same
13930 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
13931 * because otherwise the different base pointers mean the offsets aren't
13934 if (BPF_SRC(insn->code) == BPF_X) {
13935 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
13937 if (dst_reg->type == SCALAR_VALUE &&
13938 src_reg->type == SCALAR_VALUE) {
13939 if (tnum_is_const(src_reg->var_off) ||
13941 tnum_is_const(tnum_subreg(src_reg->var_off))))
13942 reg_set_min_max(&other_branch_regs[insn->dst_reg],
13944 src_reg->var_off.value,
13945 tnum_subreg(src_reg->var_off).value,
13947 else if (tnum_is_const(dst_reg->var_off) ||
13949 tnum_is_const(tnum_subreg(dst_reg->var_off))))
13950 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
13952 dst_reg->var_off.value,
13953 tnum_subreg(dst_reg->var_off).value,
13955 else if (!is_jmp32 &&
13956 (opcode == BPF_JEQ || opcode == BPF_JNE))
13957 /* Comparing for equality, we can combine knowledge */
13958 reg_combine_min_max(&other_branch_regs[insn->src_reg],
13959 &other_branch_regs[insn->dst_reg],
13960 src_reg, dst_reg, opcode);
13962 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
13963 find_equal_scalars(this_branch, src_reg);
13964 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
13968 } else if (dst_reg->type == SCALAR_VALUE) {
13969 reg_set_min_max(&other_branch_regs[insn->dst_reg],
13970 dst_reg, insn->imm, (u32)insn->imm,
13974 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
13975 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
13976 find_equal_scalars(this_branch, dst_reg);
13977 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
13980 /* if one pointer register is compared to another pointer
13981 * register check if PTR_MAYBE_NULL could be lifted.
13982 * E.g. register A - maybe null
13983 * register B - not null
13984 * for JNE A, B, ... - A is not null in the false branch;
13985 * for JEQ A, B, ... - A is not null in the true branch.
13987 * Since PTR_TO_BTF_ID points to a kernel struct that does
13988 * not need to be null checked by the BPF program, i.e.,
13989 * could be null even without PTR_MAYBE_NULL marking, so
13990 * only propagate nullness when neither reg is that type.
13992 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
13993 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
13994 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
13995 base_type(src_reg->type) != PTR_TO_BTF_ID &&
13996 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
13997 eq_branch_regs = NULL;
14000 eq_branch_regs = other_branch_regs;
14003 eq_branch_regs = regs;
14009 if (eq_branch_regs) {
14010 if (type_may_be_null(src_reg->type))
14011 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14013 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14017 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14018 * NOTE: these optimizations below are related with pointer comparison
14019 * which will never be JMP32.
14021 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14022 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14023 type_may_be_null(dst_reg->type)) {
14024 /* Mark all identical registers in each branch as either
14025 * safe or unknown depending R == 0 or R != 0 conditional.
14027 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14028 opcode == BPF_JNE);
14029 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14030 opcode == BPF_JEQ);
14031 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
14032 this_branch, other_branch) &&
14033 is_pointer_value(env, insn->dst_reg)) {
14034 verbose(env, "R%d pointer comparison prohibited\n",
14038 if (env->log.level & BPF_LOG_LEVEL)
14039 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14043 /* verify BPF_LD_IMM64 instruction */
14044 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14046 struct bpf_insn_aux_data *aux = cur_aux(env);
14047 struct bpf_reg_state *regs = cur_regs(env);
14048 struct bpf_reg_state *dst_reg;
14049 struct bpf_map *map;
14052 if (BPF_SIZE(insn->code) != BPF_DW) {
14053 verbose(env, "invalid BPF_LD_IMM insn\n");
14056 if (insn->off != 0) {
14057 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14061 err = check_reg_arg(env, insn->dst_reg, DST_OP);
14065 dst_reg = ®s[insn->dst_reg];
14066 if (insn->src_reg == 0) {
14067 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14069 dst_reg->type = SCALAR_VALUE;
14070 __mark_reg_known(®s[insn->dst_reg], imm);
14074 /* All special src_reg cases are listed below. From this point onwards
14075 * we either succeed and assign a corresponding dst_reg->type after
14076 * zeroing the offset, or fail and reject the program.
14078 mark_reg_known_zero(env, regs, insn->dst_reg);
14080 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14081 dst_reg->type = aux->btf_var.reg_type;
14082 switch (base_type(dst_reg->type)) {
14084 dst_reg->mem_size = aux->btf_var.mem_size;
14086 case PTR_TO_BTF_ID:
14087 dst_reg->btf = aux->btf_var.btf;
14088 dst_reg->btf_id = aux->btf_var.btf_id;
14091 verbose(env, "bpf verifier is misconfigured\n");
14097 if (insn->src_reg == BPF_PSEUDO_FUNC) {
14098 struct bpf_prog_aux *aux = env->prog->aux;
14099 u32 subprogno = find_subprog(env,
14100 env->insn_idx + insn->imm + 1);
14102 if (!aux->func_info) {
14103 verbose(env, "missing btf func_info\n");
14106 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14107 verbose(env, "callback function not static\n");
14111 dst_reg->type = PTR_TO_FUNC;
14112 dst_reg->subprogno = subprogno;
14116 map = env->used_maps[aux->map_index];
14117 dst_reg->map_ptr = map;
14119 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14120 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14121 dst_reg->type = PTR_TO_MAP_VALUE;
14122 dst_reg->off = aux->map_off;
14123 WARN_ON_ONCE(map->max_entries != 1);
14124 /* We want reg->id to be same (0) as map_value is not distinct */
14125 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14126 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14127 dst_reg->type = CONST_PTR_TO_MAP;
14129 verbose(env, "bpf verifier is misconfigured\n");
14136 static bool may_access_skb(enum bpf_prog_type type)
14139 case BPF_PROG_TYPE_SOCKET_FILTER:
14140 case BPF_PROG_TYPE_SCHED_CLS:
14141 case BPF_PROG_TYPE_SCHED_ACT:
14148 /* verify safety of LD_ABS|LD_IND instructions:
14149 * - they can only appear in the programs where ctx == skb
14150 * - since they are wrappers of function calls, they scratch R1-R5 registers,
14151 * preserve R6-R9, and store return value into R0
14154 * ctx == skb == R6 == CTX
14157 * SRC == any register
14158 * IMM == 32-bit immediate
14161 * R0 - 8/16/32-bit skb data converted to cpu endianness
14163 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14165 struct bpf_reg_state *regs = cur_regs(env);
14166 static const int ctx_reg = BPF_REG_6;
14167 u8 mode = BPF_MODE(insn->code);
14170 if (!may_access_skb(resolve_prog_type(env->prog))) {
14171 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14175 if (!env->ops->gen_ld_abs) {
14176 verbose(env, "bpf verifier is misconfigured\n");
14180 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14181 BPF_SIZE(insn->code) == BPF_DW ||
14182 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14183 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14187 /* check whether implicit source operand (register R6) is readable */
14188 err = check_reg_arg(env, ctx_reg, SRC_OP);
14192 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14193 * gen_ld_abs() may terminate the program at runtime, leading to
14196 err = check_reference_leak(env);
14198 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14202 if (env->cur_state->active_lock.ptr) {
14203 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14207 if (env->cur_state->active_rcu_lock) {
14208 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14212 if (regs[ctx_reg].type != PTR_TO_CTX) {
14214 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14218 if (mode == BPF_IND) {
14219 /* check explicit source operand */
14220 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14225 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
14229 /* reset caller saved regs to unreadable */
14230 for (i = 0; i < CALLER_SAVED_REGS; i++) {
14231 mark_reg_not_init(env, regs, caller_saved[i]);
14232 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14235 /* mark destination R0 register as readable, since it contains
14236 * the value fetched from the packet.
14237 * Already marked as written above.
14239 mark_reg_unknown(env, regs, BPF_REG_0);
14240 /* ld_abs load up to 32-bit skb data. */
14241 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14245 static int check_return_code(struct bpf_verifier_env *env)
14247 struct tnum enforce_attach_type_range = tnum_unknown;
14248 const struct bpf_prog *prog = env->prog;
14249 struct bpf_reg_state *reg;
14250 struct tnum range = tnum_range(0, 1);
14251 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14253 struct bpf_func_state *frame = env->cur_state->frame[0];
14254 const bool is_subprog = frame->subprogno;
14256 /* LSM and struct_ops func-ptr's return type could be "void" */
14258 switch (prog_type) {
14259 case BPF_PROG_TYPE_LSM:
14260 if (prog->expected_attach_type == BPF_LSM_CGROUP)
14261 /* See below, can be 0 or 0-1 depending on hook. */
14264 case BPF_PROG_TYPE_STRUCT_OPS:
14265 if (!prog->aux->attach_func_proto->type)
14273 /* eBPF calling convention is such that R0 is used
14274 * to return the value from eBPF program.
14275 * Make sure that it's readable at this time
14276 * of bpf_exit, which means that program wrote
14277 * something into it earlier
14279 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14283 if (is_pointer_value(env, BPF_REG_0)) {
14284 verbose(env, "R0 leaks addr as return value\n");
14288 reg = cur_regs(env) + BPF_REG_0;
14290 if (frame->in_async_callback_fn) {
14291 /* enforce return zero from async callbacks like timer */
14292 if (reg->type != SCALAR_VALUE) {
14293 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14294 reg_type_str(env, reg->type));
14298 if (!tnum_in(tnum_const(0), reg->var_off)) {
14299 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
14306 if (reg->type != SCALAR_VALUE) {
14307 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14308 reg_type_str(env, reg->type));
14314 switch (prog_type) {
14315 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14316 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14317 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14318 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14319 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14320 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14321 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14322 range = tnum_range(1, 1);
14323 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14324 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14325 range = tnum_range(0, 3);
14327 case BPF_PROG_TYPE_CGROUP_SKB:
14328 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14329 range = tnum_range(0, 3);
14330 enforce_attach_type_range = tnum_range(2, 3);
14333 case BPF_PROG_TYPE_CGROUP_SOCK:
14334 case BPF_PROG_TYPE_SOCK_OPS:
14335 case BPF_PROG_TYPE_CGROUP_DEVICE:
14336 case BPF_PROG_TYPE_CGROUP_SYSCTL:
14337 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14339 case BPF_PROG_TYPE_RAW_TRACEPOINT:
14340 if (!env->prog->aux->attach_btf_id)
14342 range = tnum_const(0);
14344 case BPF_PROG_TYPE_TRACING:
14345 switch (env->prog->expected_attach_type) {
14346 case BPF_TRACE_FENTRY:
14347 case BPF_TRACE_FEXIT:
14348 range = tnum_const(0);
14350 case BPF_TRACE_RAW_TP:
14351 case BPF_MODIFY_RETURN:
14353 case BPF_TRACE_ITER:
14359 case BPF_PROG_TYPE_SK_LOOKUP:
14360 range = tnum_range(SK_DROP, SK_PASS);
14363 case BPF_PROG_TYPE_LSM:
14364 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14365 /* Regular BPF_PROG_TYPE_LSM programs can return
14370 if (!env->prog->aux->attach_func_proto->type) {
14371 /* Make sure programs that attach to void
14372 * hooks don't try to modify return value.
14374 range = tnum_range(1, 1);
14378 case BPF_PROG_TYPE_NETFILTER:
14379 range = tnum_range(NF_DROP, NF_ACCEPT);
14381 case BPF_PROG_TYPE_EXT:
14382 /* freplace program can return anything as its return value
14383 * depends on the to-be-replaced kernel func or bpf program.
14389 if (reg->type != SCALAR_VALUE) {
14390 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14391 reg_type_str(env, reg->type));
14395 if (!tnum_in(range, reg->var_off)) {
14396 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14397 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14398 prog_type == BPF_PROG_TYPE_LSM &&
14399 !prog->aux->attach_func_proto->type)
14400 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14404 if (!tnum_is_unknown(enforce_attach_type_range) &&
14405 tnum_in(enforce_attach_type_range, reg->var_off))
14406 env->prog->enforce_expected_attach_type = 1;
14410 /* non-recursive DFS pseudo code
14411 * 1 procedure DFS-iterative(G,v):
14412 * 2 label v as discovered
14413 * 3 let S be a stack
14415 * 5 while S is not empty
14417 * 7 if t is what we're looking for:
14419 * 9 for all edges e in G.adjacentEdges(t) do
14420 * 10 if edge e is already labelled
14421 * 11 continue with the next edge
14422 * 12 w <- G.adjacentVertex(t,e)
14423 * 13 if vertex w is not discovered and not explored
14424 * 14 label e as tree-edge
14425 * 15 label w as discovered
14428 * 18 else if vertex w is discovered
14429 * 19 label e as back-edge
14431 * 21 // vertex w is explored
14432 * 22 label e as forward- or cross-edge
14433 * 23 label t as explored
14437 * 0x10 - discovered
14438 * 0x11 - discovered and fall-through edge labelled
14439 * 0x12 - discovered and fall-through and branch edges labelled
14450 static u32 state_htab_size(struct bpf_verifier_env *env)
14452 return env->prog->len;
14455 static struct bpf_verifier_state_list **explored_state(
14456 struct bpf_verifier_env *env,
14459 struct bpf_verifier_state *cur = env->cur_state;
14460 struct bpf_func_state *state = cur->frame[cur->curframe];
14462 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14465 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14467 env->insn_aux_data[idx].prune_point = true;
14470 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14472 return env->insn_aux_data[insn_idx].prune_point;
14475 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14477 env->insn_aux_data[idx].force_checkpoint = true;
14480 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14482 return env->insn_aux_data[insn_idx].force_checkpoint;
14487 DONE_EXPLORING = 0,
14488 KEEP_EXPLORING = 1,
14491 /* t, w, e - match pseudo-code above:
14492 * t - index of current instruction
14493 * w - next instruction
14496 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14499 int *insn_stack = env->cfg.insn_stack;
14500 int *insn_state = env->cfg.insn_state;
14502 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14503 return DONE_EXPLORING;
14505 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14506 return DONE_EXPLORING;
14508 if (w < 0 || w >= env->prog->len) {
14509 verbose_linfo(env, t, "%d: ", t);
14510 verbose(env, "jump out of range from insn %d to %d\n", t, w);
14515 /* mark branch target for state pruning */
14516 mark_prune_point(env, w);
14517 mark_jmp_point(env, w);
14520 if (insn_state[w] == 0) {
14522 insn_state[t] = DISCOVERED | e;
14523 insn_state[w] = DISCOVERED;
14524 if (env->cfg.cur_stack >= env->prog->len)
14526 insn_stack[env->cfg.cur_stack++] = w;
14527 return KEEP_EXPLORING;
14528 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14529 if (loop_ok && env->bpf_capable)
14530 return DONE_EXPLORING;
14531 verbose_linfo(env, t, "%d: ", t);
14532 verbose_linfo(env, w, "%d: ", w);
14533 verbose(env, "back-edge from insn %d to %d\n", t, w);
14535 } else if (insn_state[w] == EXPLORED) {
14536 /* forward- or cross-edge */
14537 insn_state[t] = DISCOVERED | e;
14539 verbose(env, "insn state internal bug\n");
14542 return DONE_EXPLORING;
14545 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14546 struct bpf_verifier_env *env,
14551 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14555 mark_prune_point(env, t + 1);
14556 /* when we exit from subprog, we need to record non-linear history */
14557 mark_jmp_point(env, t + 1);
14559 if (visit_callee) {
14560 mark_prune_point(env, t);
14561 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14562 /* It's ok to allow recursion from CFG point of
14563 * view. __check_func_call() will do the actual
14566 bpf_pseudo_func(insns + t));
14571 /* Visits the instruction at index t and returns one of the following:
14572 * < 0 - an error occurred
14573 * DONE_EXPLORING - the instruction was fully explored
14574 * KEEP_EXPLORING - there is still work to be done before it is fully explored
14576 static int visit_insn(int t, struct bpf_verifier_env *env)
14578 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14581 if (bpf_pseudo_func(insn))
14582 return visit_func_call_insn(t, insns, env, true);
14584 /* All non-branch instructions have a single fall-through edge. */
14585 if (BPF_CLASS(insn->code) != BPF_JMP &&
14586 BPF_CLASS(insn->code) != BPF_JMP32)
14587 return push_insn(t, t + 1, FALLTHROUGH, env, false);
14589 switch (BPF_OP(insn->code)) {
14591 return DONE_EXPLORING;
14594 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14595 /* Mark this call insn as a prune point to trigger
14596 * is_state_visited() check before call itself is
14597 * processed by __check_func_call(). Otherwise new
14598 * async state will be pushed for further exploration.
14600 mark_prune_point(env, t);
14601 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14602 struct bpf_kfunc_call_arg_meta meta;
14604 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14605 if (ret == 0 && is_iter_next_kfunc(&meta)) {
14606 mark_prune_point(env, t);
14607 /* Checking and saving state checkpoints at iter_next() call
14608 * is crucial for fast convergence of open-coded iterator loop
14609 * logic, so we need to force it. If we don't do that,
14610 * is_state_visited() might skip saving a checkpoint, causing
14611 * unnecessarily long sequence of not checkpointed
14612 * instructions and jumps, leading to exhaustion of jump
14613 * history buffer, and potentially other undesired outcomes.
14614 * It is expected that with correct open-coded iterators
14615 * convergence will happen quickly, so we don't run a risk of
14616 * exhausting memory.
14618 mark_force_checkpoint(env, t);
14621 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14624 if (BPF_SRC(insn->code) != BPF_K)
14627 /* unconditional jump with single edge */
14628 ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
14633 mark_prune_point(env, t + insn->off + 1);
14634 mark_jmp_point(env, t + insn->off + 1);
14639 /* conditional jump with two edges */
14640 mark_prune_point(env, t);
14642 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14646 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14650 /* non-recursive depth-first-search to detect loops in BPF program
14651 * loop == back-edge in directed graph
14653 static int check_cfg(struct bpf_verifier_env *env)
14655 int insn_cnt = env->prog->len;
14656 int *insn_stack, *insn_state;
14660 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14664 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14666 kvfree(insn_state);
14670 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14671 insn_stack[0] = 0; /* 0 is the first instruction */
14672 env->cfg.cur_stack = 1;
14674 while (env->cfg.cur_stack > 0) {
14675 int t = insn_stack[env->cfg.cur_stack - 1];
14677 ret = visit_insn(t, env);
14679 case DONE_EXPLORING:
14680 insn_state[t] = EXPLORED;
14681 env->cfg.cur_stack--;
14683 case KEEP_EXPLORING:
14687 verbose(env, "visit_insn internal bug\n");
14694 if (env->cfg.cur_stack < 0) {
14695 verbose(env, "pop stack internal bug\n");
14700 for (i = 0; i < insn_cnt; i++) {
14701 if (insn_state[i] != EXPLORED) {
14702 verbose(env, "unreachable insn %d\n", i);
14707 ret = 0; /* cfg looks good */
14710 kvfree(insn_state);
14711 kvfree(insn_stack);
14712 env->cfg.insn_state = env->cfg.insn_stack = NULL;
14716 static int check_abnormal_return(struct bpf_verifier_env *env)
14720 for (i = 1; i < env->subprog_cnt; i++) {
14721 if (env->subprog_info[i].has_ld_abs) {
14722 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14725 if (env->subprog_info[i].has_tail_call) {
14726 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14733 /* The minimum supported BTF func info size */
14734 #define MIN_BPF_FUNCINFO_SIZE 8
14735 #define MAX_FUNCINFO_REC_SIZE 252
14737 static int check_btf_func(struct bpf_verifier_env *env,
14738 const union bpf_attr *attr,
14741 const struct btf_type *type, *func_proto, *ret_type;
14742 u32 i, nfuncs, urec_size, min_size;
14743 u32 krec_size = sizeof(struct bpf_func_info);
14744 struct bpf_func_info *krecord;
14745 struct bpf_func_info_aux *info_aux = NULL;
14746 struct bpf_prog *prog;
14747 const struct btf *btf;
14749 u32 prev_offset = 0;
14750 bool scalar_return;
14753 nfuncs = attr->func_info_cnt;
14755 if (check_abnormal_return(env))
14760 if (nfuncs != env->subprog_cnt) {
14761 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14765 urec_size = attr->func_info_rec_size;
14766 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14767 urec_size > MAX_FUNCINFO_REC_SIZE ||
14768 urec_size % sizeof(u32)) {
14769 verbose(env, "invalid func info rec size %u\n", urec_size);
14774 btf = prog->aux->btf;
14776 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
14777 min_size = min_t(u32, krec_size, urec_size);
14779 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
14782 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
14786 for (i = 0; i < nfuncs; i++) {
14787 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
14789 if (ret == -E2BIG) {
14790 verbose(env, "nonzero tailing record in func info");
14791 /* set the size kernel expects so loader can zero
14792 * out the rest of the record.
14794 if (copy_to_bpfptr_offset(uattr,
14795 offsetof(union bpf_attr, func_info_rec_size),
14796 &min_size, sizeof(min_size)))
14802 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
14807 /* check insn_off */
14810 if (krecord[i].insn_off) {
14812 "nonzero insn_off %u for the first func info record",
14813 krecord[i].insn_off);
14816 } else if (krecord[i].insn_off <= prev_offset) {
14818 "same or smaller insn offset (%u) than previous func info record (%u)",
14819 krecord[i].insn_off, prev_offset);
14823 if (env->subprog_info[i].start != krecord[i].insn_off) {
14824 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
14828 /* check type_id */
14829 type = btf_type_by_id(btf, krecord[i].type_id);
14830 if (!type || !btf_type_is_func(type)) {
14831 verbose(env, "invalid type id %d in func info",
14832 krecord[i].type_id);
14835 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
14837 func_proto = btf_type_by_id(btf, type->type);
14838 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
14839 /* btf_func_check() already verified it during BTF load */
14841 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
14843 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
14844 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
14845 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
14848 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
14849 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
14853 prev_offset = krecord[i].insn_off;
14854 bpfptr_add(&urecord, urec_size);
14857 prog->aux->func_info = krecord;
14858 prog->aux->func_info_cnt = nfuncs;
14859 prog->aux->func_info_aux = info_aux;
14868 static void adjust_btf_func(struct bpf_verifier_env *env)
14870 struct bpf_prog_aux *aux = env->prog->aux;
14873 if (!aux->func_info)
14876 for (i = 0; i < env->subprog_cnt; i++)
14877 aux->func_info[i].insn_off = env->subprog_info[i].start;
14880 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
14881 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
14883 static int check_btf_line(struct bpf_verifier_env *env,
14884 const union bpf_attr *attr,
14887 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
14888 struct bpf_subprog_info *sub;
14889 struct bpf_line_info *linfo;
14890 struct bpf_prog *prog;
14891 const struct btf *btf;
14895 nr_linfo = attr->line_info_cnt;
14898 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
14901 rec_size = attr->line_info_rec_size;
14902 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
14903 rec_size > MAX_LINEINFO_REC_SIZE ||
14904 rec_size & (sizeof(u32) - 1))
14907 /* Need to zero it in case the userspace may
14908 * pass in a smaller bpf_line_info object.
14910 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
14911 GFP_KERNEL | __GFP_NOWARN);
14916 btf = prog->aux->btf;
14919 sub = env->subprog_info;
14920 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
14921 expected_size = sizeof(struct bpf_line_info);
14922 ncopy = min_t(u32, expected_size, rec_size);
14923 for (i = 0; i < nr_linfo; i++) {
14924 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
14926 if (err == -E2BIG) {
14927 verbose(env, "nonzero tailing record in line_info");
14928 if (copy_to_bpfptr_offset(uattr,
14929 offsetof(union bpf_attr, line_info_rec_size),
14930 &expected_size, sizeof(expected_size)))
14936 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
14942 * Check insn_off to ensure
14943 * 1) strictly increasing AND
14944 * 2) bounded by prog->len
14946 * The linfo[0].insn_off == 0 check logically falls into
14947 * the later "missing bpf_line_info for func..." case
14948 * because the first linfo[0].insn_off must be the
14949 * first sub also and the first sub must have
14950 * subprog_info[0].start == 0.
14952 if ((i && linfo[i].insn_off <= prev_offset) ||
14953 linfo[i].insn_off >= prog->len) {
14954 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
14955 i, linfo[i].insn_off, prev_offset,
14961 if (!prog->insnsi[linfo[i].insn_off].code) {
14963 "Invalid insn code at line_info[%u].insn_off\n",
14969 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
14970 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
14971 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
14976 if (s != env->subprog_cnt) {
14977 if (linfo[i].insn_off == sub[s].start) {
14978 sub[s].linfo_idx = i;
14980 } else if (sub[s].start < linfo[i].insn_off) {
14981 verbose(env, "missing bpf_line_info for func#%u\n", s);
14987 prev_offset = linfo[i].insn_off;
14988 bpfptr_add(&ulinfo, rec_size);
14991 if (s != env->subprog_cnt) {
14992 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
14993 env->subprog_cnt - s, s);
14998 prog->aux->linfo = linfo;
14999 prog->aux->nr_linfo = nr_linfo;
15008 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
15009 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
15011 static int check_core_relo(struct bpf_verifier_env *env,
15012 const union bpf_attr *attr,
15015 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15016 struct bpf_core_relo core_relo = {};
15017 struct bpf_prog *prog = env->prog;
15018 const struct btf *btf = prog->aux->btf;
15019 struct bpf_core_ctx ctx = {
15023 bpfptr_t u_core_relo;
15026 nr_core_relo = attr->core_relo_cnt;
15029 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15032 rec_size = attr->core_relo_rec_size;
15033 if (rec_size < MIN_CORE_RELO_SIZE ||
15034 rec_size > MAX_CORE_RELO_SIZE ||
15035 rec_size % sizeof(u32))
15038 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15039 expected_size = sizeof(struct bpf_core_relo);
15040 ncopy = min_t(u32, expected_size, rec_size);
15042 /* Unlike func_info and line_info, copy and apply each CO-RE
15043 * relocation record one at a time.
15045 for (i = 0; i < nr_core_relo; i++) {
15046 /* future proofing when sizeof(bpf_core_relo) changes */
15047 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15049 if (err == -E2BIG) {
15050 verbose(env, "nonzero tailing record in core_relo");
15051 if (copy_to_bpfptr_offset(uattr,
15052 offsetof(union bpf_attr, core_relo_rec_size),
15053 &expected_size, sizeof(expected_size)))
15059 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15064 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15065 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15066 i, core_relo.insn_off, prog->len);
15071 err = bpf_core_apply(&ctx, &core_relo, i,
15072 &prog->insnsi[core_relo.insn_off / 8]);
15075 bpfptr_add(&u_core_relo, rec_size);
15080 static int check_btf_info(struct bpf_verifier_env *env,
15081 const union bpf_attr *attr,
15087 if (!attr->func_info_cnt && !attr->line_info_cnt) {
15088 if (check_abnormal_return(env))
15093 btf = btf_get_by_fd(attr->prog_btf_fd);
15095 return PTR_ERR(btf);
15096 if (btf_is_kernel(btf)) {
15100 env->prog->aux->btf = btf;
15102 err = check_btf_func(env, attr, uattr);
15106 err = check_btf_line(env, attr, uattr);
15110 err = check_core_relo(env, attr, uattr);
15117 /* check %cur's range satisfies %old's */
15118 static bool range_within(struct bpf_reg_state *old,
15119 struct bpf_reg_state *cur)
15121 return old->umin_value <= cur->umin_value &&
15122 old->umax_value >= cur->umax_value &&
15123 old->smin_value <= cur->smin_value &&
15124 old->smax_value >= cur->smax_value &&
15125 old->u32_min_value <= cur->u32_min_value &&
15126 old->u32_max_value >= cur->u32_max_value &&
15127 old->s32_min_value <= cur->s32_min_value &&
15128 old->s32_max_value >= cur->s32_max_value;
15131 /* If in the old state two registers had the same id, then they need to have
15132 * the same id in the new state as well. But that id could be different from
15133 * the old state, so we need to track the mapping from old to new ids.
15134 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15135 * regs with old id 5 must also have new id 9 for the new state to be safe. But
15136 * regs with a different old id could still have new id 9, we don't care about
15138 * So we look through our idmap to see if this old id has been seen before. If
15139 * so, we require the new id to match; otherwise, we add the id pair to the map.
15141 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15143 struct bpf_id_pair *map = idmap->map;
15146 /* either both IDs should be set or both should be zero */
15147 if (!!old_id != !!cur_id)
15150 if (old_id == 0) /* cur_id == 0 as well */
15153 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15155 /* Reached an empty slot; haven't seen this id before */
15156 map[i].old = old_id;
15157 map[i].cur = cur_id;
15160 if (map[i].old == old_id)
15161 return map[i].cur == cur_id;
15162 if (map[i].cur == cur_id)
15165 /* We ran out of idmap slots, which should be impossible */
15170 /* Similar to check_ids(), but allocate a unique temporary ID
15171 * for 'old_id' or 'cur_id' of zero.
15172 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15174 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15176 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15177 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15179 return check_ids(old_id, cur_id, idmap);
15182 static void clean_func_state(struct bpf_verifier_env *env,
15183 struct bpf_func_state *st)
15185 enum bpf_reg_liveness live;
15188 for (i = 0; i < BPF_REG_FP; i++) {
15189 live = st->regs[i].live;
15190 /* liveness must not touch this register anymore */
15191 st->regs[i].live |= REG_LIVE_DONE;
15192 if (!(live & REG_LIVE_READ))
15193 /* since the register is unused, clear its state
15194 * to make further comparison simpler
15196 __mark_reg_not_init(env, &st->regs[i]);
15199 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15200 live = st->stack[i].spilled_ptr.live;
15201 /* liveness must not touch this stack slot anymore */
15202 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15203 if (!(live & REG_LIVE_READ)) {
15204 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15205 for (j = 0; j < BPF_REG_SIZE; j++)
15206 st->stack[i].slot_type[j] = STACK_INVALID;
15211 static void clean_verifier_state(struct bpf_verifier_env *env,
15212 struct bpf_verifier_state *st)
15216 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15217 /* all regs in this state in all frames were already marked */
15220 for (i = 0; i <= st->curframe; i++)
15221 clean_func_state(env, st->frame[i]);
15224 /* the parentage chains form a tree.
15225 * the verifier states are added to state lists at given insn and
15226 * pushed into state stack for future exploration.
15227 * when the verifier reaches bpf_exit insn some of the verifer states
15228 * stored in the state lists have their final liveness state already,
15229 * but a lot of states will get revised from liveness point of view when
15230 * the verifier explores other branches.
15233 * 2: if r1 == 100 goto pc+1
15236 * when the verifier reaches exit insn the register r0 in the state list of
15237 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15238 * of insn 2 and goes exploring further. At the insn 4 it will walk the
15239 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15241 * Since the verifier pushes the branch states as it sees them while exploring
15242 * the program the condition of walking the branch instruction for the second
15243 * time means that all states below this branch were already explored and
15244 * their final liveness marks are already propagated.
15245 * Hence when the verifier completes the search of state list in is_state_visited()
15246 * we can call this clean_live_states() function to mark all liveness states
15247 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15248 * will not be used.
15249 * This function also clears the registers and stack for states that !READ
15250 * to simplify state merging.
15252 * Important note here that walking the same branch instruction in the callee
15253 * doesn't meant that the states are DONE. The verifier has to compare
15256 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15257 struct bpf_verifier_state *cur)
15259 struct bpf_verifier_state_list *sl;
15262 sl = *explored_state(env, insn);
15264 if (sl->state.branches)
15266 if (sl->state.insn_idx != insn ||
15267 sl->state.curframe != cur->curframe)
15269 for (i = 0; i <= cur->curframe; i++)
15270 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15272 clean_verifier_state(env, &sl->state);
15278 static bool regs_exact(const struct bpf_reg_state *rold,
15279 const struct bpf_reg_state *rcur,
15280 struct bpf_idmap *idmap)
15282 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15283 check_ids(rold->id, rcur->id, idmap) &&
15284 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15287 /* Returns true if (rold safe implies rcur safe) */
15288 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15289 struct bpf_reg_state *rcur, struct bpf_idmap *idmap)
15291 if (!(rold->live & REG_LIVE_READ))
15292 /* explored state didn't use this */
15294 if (rold->type == NOT_INIT)
15295 /* explored state can't have used this */
15297 if (rcur->type == NOT_INIT)
15300 /* Enforce that register types have to match exactly, including their
15301 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15304 * One can make a point that using a pointer register as unbounded
15305 * SCALAR would be technically acceptable, but this could lead to
15306 * pointer leaks because scalars are allowed to leak while pointers
15307 * are not. We could make this safe in special cases if root is
15308 * calling us, but it's probably not worth the hassle.
15310 * Also, register types that are *not* MAYBE_NULL could technically be
15311 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15312 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15313 * to the same map).
15314 * However, if the old MAYBE_NULL register then got NULL checked,
15315 * doing so could have affected others with the same id, and we can't
15316 * check for that because we lost the id when we converted to
15317 * a non-MAYBE_NULL variant.
15318 * So, as a general rule we don't allow mixing MAYBE_NULL and
15319 * non-MAYBE_NULL registers as well.
15321 if (rold->type != rcur->type)
15324 switch (base_type(rold->type)) {
15326 if (env->explore_alu_limits) {
15327 /* explore_alu_limits disables tnum_in() and range_within()
15328 * logic and requires everything to be strict
15330 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15331 check_scalar_ids(rold->id, rcur->id, idmap);
15333 if (!rold->precise)
15335 /* Why check_ids() for scalar registers?
15337 * Consider the following BPF code:
15338 * 1: r6 = ... unbound scalar, ID=a ...
15339 * 2: r7 = ... unbound scalar, ID=b ...
15340 * 3: if (r6 > r7) goto +1
15342 * 5: if (r6 > X) goto ...
15343 * 6: ... memory operation using r7 ...
15345 * First verification path is [1-6]:
15346 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15347 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15348 * r7 <= X, because r6 and r7 share same id.
15349 * Next verification path is [1-4, 6].
15351 * Instruction (6) would be reached in two states:
15352 * I. r6{.id=b}, r7{.id=b} via path 1-6;
15353 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15355 * Use check_ids() to distinguish these states.
15357 * Also verify that new value satisfies old value range knowledge.
15359 return range_within(rold, rcur) &&
15360 tnum_in(rold->var_off, rcur->var_off) &&
15361 check_scalar_ids(rold->id, rcur->id, idmap);
15362 case PTR_TO_MAP_KEY:
15363 case PTR_TO_MAP_VALUE:
15366 case PTR_TO_TP_BUFFER:
15367 /* If the new min/max/var_off satisfy the old ones and
15368 * everything else matches, we are OK.
15370 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15371 range_within(rold, rcur) &&
15372 tnum_in(rold->var_off, rcur->var_off) &&
15373 check_ids(rold->id, rcur->id, idmap) &&
15374 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15375 case PTR_TO_PACKET_META:
15376 case PTR_TO_PACKET:
15377 /* We must have at least as much range as the old ptr
15378 * did, so that any accesses which were safe before are
15379 * still safe. This is true even if old range < old off,
15380 * since someone could have accessed through (ptr - k), or
15381 * even done ptr -= k in a register, to get a safe access.
15383 if (rold->range > rcur->range)
15385 /* If the offsets don't match, we can't trust our alignment;
15386 * nor can we be sure that we won't fall out of range.
15388 if (rold->off != rcur->off)
15390 /* id relations must be preserved */
15391 if (!check_ids(rold->id, rcur->id, idmap))
15393 /* new val must satisfy old val knowledge */
15394 return range_within(rold, rcur) &&
15395 tnum_in(rold->var_off, rcur->var_off);
15397 /* two stack pointers are equal only if they're pointing to
15398 * the same stack frame, since fp-8 in foo != fp-8 in bar
15400 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15402 return regs_exact(rold, rcur, idmap);
15406 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15407 struct bpf_func_state *cur, struct bpf_idmap *idmap)
15411 /* walk slots of the explored stack and ignore any additional
15412 * slots in the current stack, since explored(safe) state
15415 for (i = 0; i < old->allocated_stack; i++) {
15416 struct bpf_reg_state *old_reg, *cur_reg;
15418 spi = i / BPF_REG_SIZE;
15420 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15421 i += BPF_REG_SIZE - 1;
15422 /* explored state didn't use this */
15426 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15429 if (env->allow_uninit_stack &&
15430 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15433 /* explored stack has more populated slots than current stack
15434 * and these slots were used
15436 if (i >= cur->allocated_stack)
15439 /* if old state was safe with misc data in the stack
15440 * it will be safe with zero-initialized stack.
15441 * The opposite is not true
15443 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15444 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15446 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15447 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15448 /* Ex: old explored (safe) state has STACK_SPILL in
15449 * this stack slot, but current has STACK_MISC ->
15450 * this verifier states are not equivalent,
15451 * return false to continue verification of this path
15454 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15456 /* Both old and cur are having same slot_type */
15457 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15459 /* when explored and current stack slot are both storing
15460 * spilled registers, check that stored pointers types
15461 * are the same as well.
15462 * Ex: explored safe path could have stored
15463 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15464 * but current path has stored:
15465 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15466 * such verifier states are not equivalent.
15467 * return false to continue verification of this path
15469 if (!regsafe(env, &old->stack[spi].spilled_ptr,
15470 &cur->stack[spi].spilled_ptr, idmap))
15474 old_reg = &old->stack[spi].spilled_ptr;
15475 cur_reg = &cur->stack[spi].spilled_ptr;
15476 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15477 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15478 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15482 old_reg = &old->stack[spi].spilled_ptr;
15483 cur_reg = &cur->stack[spi].spilled_ptr;
15484 /* iter.depth is not compared between states as it
15485 * doesn't matter for correctness and would otherwise
15486 * prevent convergence; we maintain it only to prevent
15487 * infinite loop check triggering, see
15488 * iter_active_depths_differ()
15490 if (old_reg->iter.btf != cur_reg->iter.btf ||
15491 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15492 old_reg->iter.state != cur_reg->iter.state ||
15493 /* ignore {old_reg,cur_reg}->iter.depth, see above */
15494 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15499 case STACK_INVALID:
15501 /* Ensure that new unhandled slot types return false by default */
15509 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15510 struct bpf_idmap *idmap)
15514 if (old->acquired_refs != cur->acquired_refs)
15517 for (i = 0; i < old->acquired_refs; i++) {
15518 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15525 /* compare two verifier states
15527 * all states stored in state_list are known to be valid, since
15528 * verifier reached 'bpf_exit' instruction through them
15530 * this function is called when verifier exploring different branches of
15531 * execution popped from the state stack. If it sees an old state that has
15532 * more strict register state and more strict stack state then this execution
15533 * branch doesn't need to be explored further, since verifier already
15534 * concluded that more strict state leads to valid finish.
15536 * Therefore two states are equivalent if register state is more conservative
15537 * and explored stack state is more conservative than the current one.
15540 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15541 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15543 * In other words if current stack state (one being explored) has more
15544 * valid slots than old one that already passed validation, it means
15545 * the verifier can stop exploring and conclude that current state is valid too
15547 * Similarly with registers. If explored state has register type as invalid
15548 * whereas register type in current state is meaningful, it means that
15549 * the current state will reach 'bpf_exit' instruction safely
15551 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15552 struct bpf_func_state *cur)
15556 for (i = 0; i < MAX_BPF_REG; i++)
15557 if (!regsafe(env, &old->regs[i], &cur->regs[i],
15558 &env->idmap_scratch))
15561 if (!stacksafe(env, old, cur, &env->idmap_scratch))
15564 if (!refsafe(old, cur, &env->idmap_scratch))
15570 static bool states_equal(struct bpf_verifier_env *env,
15571 struct bpf_verifier_state *old,
15572 struct bpf_verifier_state *cur)
15576 if (old->curframe != cur->curframe)
15579 env->idmap_scratch.tmp_id_gen = env->id_gen;
15580 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
15582 /* Verification state from speculative execution simulation
15583 * must never prune a non-speculative execution one.
15585 if (old->speculative && !cur->speculative)
15588 if (old->active_lock.ptr != cur->active_lock.ptr)
15591 /* Old and cur active_lock's have to be either both present
15594 if (!!old->active_lock.id != !!cur->active_lock.id)
15597 if (old->active_lock.id &&
15598 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
15601 if (old->active_rcu_lock != cur->active_rcu_lock)
15604 /* for states to be equal callsites have to be the same
15605 * and all frame states need to be equivalent
15607 for (i = 0; i <= old->curframe; i++) {
15608 if (old->frame[i]->callsite != cur->frame[i]->callsite)
15610 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15616 /* Return 0 if no propagation happened. Return negative error code if error
15617 * happened. Otherwise, return the propagated bit.
15619 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15620 struct bpf_reg_state *reg,
15621 struct bpf_reg_state *parent_reg)
15623 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15624 u8 flag = reg->live & REG_LIVE_READ;
15627 /* When comes here, read flags of PARENT_REG or REG could be any of
15628 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15629 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15631 if (parent_flag == REG_LIVE_READ64 ||
15632 /* Or if there is no read flag from REG. */
15634 /* Or if the read flag from REG is the same as PARENT_REG. */
15635 parent_flag == flag)
15638 err = mark_reg_read(env, reg, parent_reg, flag);
15645 /* A write screens off any subsequent reads; but write marks come from the
15646 * straight-line code between a state and its parent. When we arrive at an
15647 * equivalent state (jump target or such) we didn't arrive by the straight-line
15648 * code, so read marks in the state must propagate to the parent regardless
15649 * of the state's write marks. That's what 'parent == state->parent' comparison
15650 * in mark_reg_read() is for.
15652 static int propagate_liveness(struct bpf_verifier_env *env,
15653 const struct bpf_verifier_state *vstate,
15654 struct bpf_verifier_state *vparent)
15656 struct bpf_reg_state *state_reg, *parent_reg;
15657 struct bpf_func_state *state, *parent;
15658 int i, frame, err = 0;
15660 if (vparent->curframe != vstate->curframe) {
15661 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15662 vparent->curframe, vstate->curframe);
15665 /* Propagate read liveness of registers... */
15666 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15667 for (frame = 0; frame <= vstate->curframe; frame++) {
15668 parent = vparent->frame[frame];
15669 state = vstate->frame[frame];
15670 parent_reg = parent->regs;
15671 state_reg = state->regs;
15672 /* We don't need to worry about FP liveness, it's read-only */
15673 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15674 err = propagate_liveness_reg(env, &state_reg[i],
15678 if (err == REG_LIVE_READ64)
15679 mark_insn_zext(env, &parent_reg[i]);
15682 /* Propagate stack slots. */
15683 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15684 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15685 parent_reg = &parent->stack[i].spilled_ptr;
15686 state_reg = &state->stack[i].spilled_ptr;
15687 err = propagate_liveness_reg(env, state_reg,
15696 /* find precise scalars in the previous equivalent state and
15697 * propagate them into the current state
15699 static int propagate_precision(struct bpf_verifier_env *env,
15700 const struct bpf_verifier_state *old)
15702 struct bpf_reg_state *state_reg;
15703 struct bpf_func_state *state;
15704 int i, err = 0, fr;
15707 for (fr = old->curframe; fr >= 0; fr--) {
15708 state = old->frame[fr];
15709 state_reg = state->regs;
15711 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15712 if (state_reg->type != SCALAR_VALUE ||
15713 !state_reg->precise ||
15714 !(state_reg->live & REG_LIVE_READ))
15716 if (env->log.level & BPF_LOG_LEVEL2) {
15718 verbose(env, "frame %d: propagating r%d", fr, i);
15720 verbose(env, ",r%d", i);
15722 bt_set_frame_reg(&env->bt, fr, i);
15726 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15727 if (!is_spilled_reg(&state->stack[i]))
15729 state_reg = &state->stack[i].spilled_ptr;
15730 if (state_reg->type != SCALAR_VALUE ||
15731 !state_reg->precise ||
15732 !(state_reg->live & REG_LIVE_READ))
15734 if (env->log.level & BPF_LOG_LEVEL2) {
15736 verbose(env, "frame %d: propagating fp%d",
15737 fr, (-i - 1) * BPF_REG_SIZE);
15739 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15741 bt_set_frame_slot(&env->bt, fr, i);
15745 verbose(env, "\n");
15748 err = mark_chain_precision_batch(env);
15755 static bool states_maybe_looping(struct bpf_verifier_state *old,
15756 struct bpf_verifier_state *cur)
15758 struct bpf_func_state *fold, *fcur;
15759 int i, fr = cur->curframe;
15761 if (old->curframe != fr)
15764 fold = old->frame[fr];
15765 fcur = cur->frame[fr];
15766 for (i = 0; i < MAX_BPF_REG; i++)
15767 if (memcmp(&fold->regs[i], &fcur->regs[i],
15768 offsetof(struct bpf_reg_state, parent)))
15773 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15775 return env->insn_aux_data[insn_idx].is_iter_next;
15778 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
15779 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15780 * states to match, which otherwise would look like an infinite loop. So while
15781 * iter_next() calls are taken care of, we still need to be careful and
15782 * prevent erroneous and too eager declaration of "ininite loop", when
15783 * iterators are involved.
15785 * Here's a situation in pseudo-BPF assembly form:
15787 * 0: again: ; set up iter_next() call args
15788 * 1: r1 = &it ; <CHECKPOINT HERE>
15789 * 2: call bpf_iter_num_next ; this is iter_next() call
15790 * 3: if r0 == 0 goto done
15791 * 4: ... something useful here ...
15792 * 5: goto again ; another iteration
15795 * 8: call bpf_iter_num_destroy ; clean up iter state
15798 * This is a typical loop. Let's assume that we have a prune point at 1:,
15799 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
15800 * again`, assuming other heuristics don't get in a way).
15802 * When we first time come to 1:, let's say we have some state X. We proceed
15803 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
15804 * Now we come back to validate that forked ACTIVE state. We proceed through
15805 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
15806 * are converging. But the problem is that we don't know that yet, as this
15807 * convergence has to happen at iter_next() call site only. So if nothing is
15808 * done, at 1: verifier will use bounded loop logic and declare infinite
15809 * looping (and would be *technically* correct, if not for iterator's
15810 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
15811 * don't want that. So what we do in process_iter_next_call() when we go on
15812 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
15813 * a different iteration. So when we suspect an infinite loop, we additionally
15814 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
15815 * pretend we are not looping and wait for next iter_next() call.
15817 * This only applies to ACTIVE state. In DRAINED state we don't expect to
15818 * loop, because that would actually mean infinite loop, as DRAINED state is
15819 * "sticky", and so we'll keep returning into the same instruction with the
15820 * same state (at least in one of possible code paths).
15822 * This approach allows to keep infinite loop heuristic even in the face of
15823 * active iterator. E.g., C snippet below is and will be detected as
15824 * inifintely looping:
15826 * struct bpf_iter_num it;
15829 * bpf_iter_num_new(&it, 0, 10);
15830 * while ((p = bpf_iter_num_next(&t))) {
15832 * while (x--) {} // <<-- infinite loop here
15836 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
15838 struct bpf_reg_state *slot, *cur_slot;
15839 struct bpf_func_state *state;
15842 for (fr = old->curframe; fr >= 0; fr--) {
15843 state = old->frame[fr];
15844 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15845 if (state->stack[i].slot_type[0] != STACK_ITER)
15848 slot = &state->stack[i].spilled_ptr;
15849 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
15852 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
15853 if (cur_slot->iter.depth != slot->iter.depth)
15860 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
15862 struct bpf_verifier_state_list *new_sl;
15863 struct bpf_verifier_state_list *sl, **pprev;
15864 struct bpf_verifier_state *cur = env->cur_state, *new;
15865 int i, j, err, states_cnt = 0;
15866 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
15867 bool add_new_state = force_new_state;
15869 /* bpf progs typically have pruning point every 4 instructions
15870 * http://vger.kernel.org/bpfconf2019.html#session-1
15871 * Do not add new state for future pruning if the verifier hasn't seen
15872 * at least 2 jumps and at least 8 instructions.
15873 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
15874 * In tests that amounts to up to 50% reduction into total verifier
15875 * memory consumption and 20% verifier time speedup.
15877 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
15878 env->insn_processed - env->prev_insn_processed >= 8)
15879 add_new_state = true;
15881 pprev = explored_state(env, insn_idx);
15884 clean_live_states(env, insn_idx, cur);
15888 if (sl->state.insn_idx != insn_idx)
15891 if (sl->state.branches) {
15892 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
15894 if (frame->in_async_callback_fn &&
15895 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
15896 /* Different async_entry_cnt means that the verifier is
15897 * processing another entry into async callback.
15898 * Seeing the same state is not an indication of infinite
15899 * loop or infinite recursion.
15900 * But finding the same state doesn't mean that it's safe
15901 * to stop processing the current state. The previous state
15902 * hasn't yet reached bpf_exit, since state.branches > 0.
15903 * Checking in_async_callback_fn alone is not enough either.
15904 * Since the verifier still needs to catch infinite loops
15905 * inside async callbacks.
15907 goto skip_inf_loop_check;
15909 /* BPF open-coded iterators loop detection is special.
15910 * states_maybe_looping() logic is too simplistic in detecting
15911 * states that *might* be equivalent, because it doesn't know
15912 * about ID remapping, so don't even perform it.
15913 * See process_iter_next_call() and iter_active_depths_differ()
15914 * for overview of the logic. When current and one of parent
15915 * states are detected as equivalent, it's a good thing: we prove
15916 * convergence and can stop simulating further iterations.
15917 * It's safe to assume that iterator loop will finish, taking into
15918 * account iter_next() contract of eventually returning
15919 * sticky NULL result.
15921 if (is_iter_next_insn(env, insn_idx)) {
15922 if (states_equal(env, &sl->state, cur)) {
15923 struct bpf_func_state *cur_frame;
15924 struct bpf_reg_state *iter_state, *iter_reg;
15927 cur_frame = cur->frame[cur->curframe];
15928 /* btf_check_iter_kfuncs() enforces that
15929 * iter state pointer is always the first arg
15931 iter_reg = &cur_frame->regs[BPF_REG_1];
15932 /* current state is valid due to states_equal(),
15933 * so we can assume valid iter and reg state,
15934 * no need for extra (re-)validations
15936 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
15937 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
15938 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
15941 goto skip_inf_loop_check;
15943 /* attempt to detect infinite loop to avoid unnecessary doomed work */
15944 if (states_maybe_looping(&sl->state, cur) &&
15945 states_equal(env, &sl->state, cur) &&
15946 !iter_active_depths_differ(&sl->state, cur)) {
15947 verbose_linfo(env, insn_idx, "; ");
15948 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
15951 /* if the verifier is processing a loop, avoid adding new state
15952 * too often, since different loop iterations have distinct
15953 * states and may not help future pruning.
15954 * This threshold shouldn't be too low to make sure that
15955 * a loop with large bound will be rejected quickly.
15956 * The most abusive loop will be:
15958 * if r1 < 1000000 goto pc-2
15959 * 1M insn_procssed limit / 100 == 10k peak states.
15960 * This threshold shouldn't be too high either, since states
15961 * at the end of the loop are likely to be useful in pruning.
15963 skip_inf_loop_check:
15964 if (!force_new_state &&
15965 env->jmps_processed - env->prev_jmps_processed < 20 &&
15966 env->insn_processed - env->prev_insn_processed < 100)
15967 add_new_state = false;
15970 if (states_equal(env, &sl->state, cur)) {
15973 /* reached equivalent register/stack state,
15974 * prune the search.
15975 * Registers read by the continuation are read by us.
15976 * If we have any write marks in env->cur_state, they
15977 * will prevent corresponding reads in the continuation
15978 * from reaching our parent (an explored_state). Our
15979 * own state will get the read marks recorded, but
15980 * they'll be immediately forgotten as we're pruning
15981 * this state and will pop a new one.
15983 err = propagate_liveness(env, &sl->state, cur);
15985 /* if previous state reached the exit with precision and
15986 * current state is equivalent to it (except precsion marks)
15987 * the precision needs to be propagated back in
15988 * the current state.
15990 err = err ? : push_jmp_history(env, cur);
15991 err = err ? : propagate_precision(env, &sl->state);
15997 /* when new state is not going to be added do not increase miss count.
15998 * Otherwise several loop iterations will remove the state
15999 * recorded earlier. The goal of these heuristics is to have
16000 * states from some iterations of the loop (some in the beginning
16001 * and some at the end) to help pruning.
16005 /* heuristic to determine whether this state is beneficial
16006 * to keep checking from state equivalence point of view.
16007 * Higher numbers increase max_states_per_insn and verification time,
16008 * but do not meaningfully decrease insn_processed.
16010 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
16011 /* the state is unlikely to be useful. Remove it to
16012 * speed up verification
16015 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
16016 u32 br = sl->state.branches;
16019 "BUG live_done but branches_to_explore %d\n",
16021 free_verifier_state(&sl->state, false);
16023 env->peak_states--;
16025 /* cannot free this state, since parentage chain may
16026 * walk it later. Add it for free_list instead to
16027 * be freed at the end of verification
16029 sl->next = env->free_list;
16030 env->free_list = sl;
16040 if (env->max_states_per_insn < states_cnt)
16041 env->max_states_per_insn = states_cnt;
16043 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16046 if (!add_new_state)
16049 /* There were no equivalent states, remember the current one.
16050 * Technically the current state is not proven to be safe yet,
16051 * but it will either reach outer most bpf_exit (which means it's safe)
16052 * or it will be rejected. When there are no loops the verifier won't be
16053 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16054 * again on the way to bpf_exit.
16055 * When looping the sl->state.branches will be > 0 and this state
16056 * will not be considered for equivalence until branches == 0.
16058 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16061 env->total_states++;
16062 env->peak_states++;
16063 env->prev_jmps_processed = env->jmps_processed;
16064 env->prev_insn_processed = env->insn_processed;
16066 /* forget precise markings we inherited, see __mark_chain_precision */
16067 if (env->bpf_capable)
16068 mark_all_scalars_imprecise(env, cur);
16070 /* add new state to the head of linked list */
16071 new = &new_sl->state;
16072 err = copy_verifier_state(new, cur);
16074 free_verifier_state(new, false);
16078 new->insn_idx = insn_idx;
16079 WARN_ONCE(new->branches != 1,
16080 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16083 cur->first_insn_idx = insn_idx;
16084 clear_jmp_history(cur);
16085 new_sl->next = *explored_state(env, insn_idx);
16086 *explored_state(env, insn_idx) = new_sl;
16087 /* connect new state to parentage chain. Current frame needs all
16088 * registers connected. Only r6 - r9 of the callers are alive (pushed
16089 * to the stack implicitly by JITs) so in callers' frames connect just
16090 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16091 * the state of the call instruction (with WRITTEN set), and r0 comes
16092 * from callee with its full parentage chain, anyway.
16094 /* clear write marks in current state: the writes we did are not writes
16095 * our child did, so they don't screen off its reads from us.
16096 * (There are no read marks in current state, because reads always mark
16097 * their parent and current state never has children yet. Only
16098 * explored_states can get read marks.)
16100 for (j = 0; j <= cur->curframe; j++) {
16101 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16102 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16103 for (i = 0; i < BPF_REG_FP; i++)
16104 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16107 /* all stack frames are accessible from callee, clear them all */
16108 for (j = 0; j <= cur->curframe; j++) {
16109 struct bpf_func_state *frame = cur->frame[j];
16110 struct bpf_func_state *newframe = new->frame[j];
16112 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16113 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16114 frame->stack[i].spilled_ptr.parent =
16115 &newframe->stack[i].spilled_ptr;
16121 /* Return true if it's OK to have the same insn return a different type. */
16122 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16124 switch (base_type(type)) {
16126 case PTR_TO_SOCKET:
16127 case PTR_TO_SOCK_COMMON:
16128 case PTR_TO_TCP_SOCK:
16129 case PTR_TO_XDP_SOCK:
16130 case PTR_TO_BTF_ID:
16137 /* If an instruction was previously used with particular pointer types, then we
16138 * need to be careful to avoid cases such as the below, where it may be ok
16139 * for one branch accessing the pointer, but not ok for the other branch:
16144 * R1 = some_other_valid_ptr;
16147 * R2 = *(u32 *)(R1 + 0);
16149 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16151 return src != prev && (!reg_type_mismatch_ok(src) ||
16152 !reg_type_mismatch_ok(prev));
16155 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16156 bool allow_trust_missmatch)
16158 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16160 if (*prev_type == NOT_INIT) {
16161 /* Saw a valid insn
16162 * dst_reg = *(u32 *)(src_reg + off)
16163 * save type to validate intersecting paths
16166 } else if (reg_type_mismatch(type, *prev_type)) {
16167 /* Abuser program is trying to use the same insn
16168 * dst_reg = *(u32*) (src_reg + off)
16169 * with different pointer types:
16170 * src_reg == ctx in one branch and
16171 * src_reg == stack|map in some other branch.
16174 if (allow_trust_missmatch &&
16175 base_type(type) == PTR_TO_BTF_ID &&
16176 base_type(*prev_type) == PTR_TO_BTF_ID) {
16178 * Have to support a use case when one path through
16179 * the program yields TRUSTED pointer while another
16180 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16183 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16185 verbose(env, "same insn cannot be used with different pointers\n");
16193 static int do_check(struct bpf_verifier_env *env)
16195 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16196 struct bpf_verifier_state *state = env->cur_state;
16197 struct bpf_insn *insns = env->prog->insnsi;
16198 struct bpf_reg_state *regs;
16199 int insn_cnt = env->prog->len;
16200 bool do_print_state = false;
16201 int prev_insn_idx = -1;
16204 struct bpf_insn *insn;
16208 env->prev_insn_idx = prev_insn_idx;
16209 if (env->insn_idx >= insn_cnt) {
16210 verbose(env, "invalid insn idx %d insn_cnt %d\n",
16211 env->insn_idx, insn_cnt);
16215 insn = &insns[env->insn_idx];
16216 class = BPF_CLASS(insn->code);
16218 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16220 "BPF program is too large. Processed %d insn\n",
16221 env->insn_processed);
16225 state->last_insn_idx = env->prev_insn_idx;
16227 if (is_prune_point(env, env->insn_idx)) {
16228 err = is_state_visited(env, env->insn_idx);
16232 /* found equivalent state, can prune the search */
16233 if (env->log.level & BPF_LOG_LEVEL) {
16234 if (do_print_state)
16235 verbose(env, "\nfrom %d to %d%s: safe\n",
16236 env->prev_insn_idx, env->insn_idx,
16237 env->cur_state->speculative ?
16238 " (speculative execution)" : "");
16240 verbose(env, "%d: safe\n", env->insn_idx);
16242 goto process_bpf_exit;
16246 if (is_jmp_point(env, env->insn_idx)) {
16247 err = push_jmp_history(env, state);
16252 if (signal_pending(current))
16255 if (need_resched())
16258 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16259 verbose(env, "\nfrom %d to %d%s:",
16260 env->prev_insn_idx, env->insn_idx,
16261 env->cur_state->speculative ?
16262 " (speculative execution)" : "");
16263 print_verifier_state(env, state->frame[state->curframe], true);
16264 do_print_state = false;
16267 if (env->log.level & BPF_LOG_LEVEL) {
16268 const struct bpf_insn_cbs cbs = {
16269 .cb_call = disasm_kfunc_name,
16270 .cb_print = verbose,
16271 .private_data = env,
16274 if (verifier_state_scratched(env))
16275 print_insn_state(env, state->frame[state->curframe]);
16277 verbose_linfo(env, env->insn_idx, "; ");
16278 env->prev_log_pos = env->log.end_pos;
16279 verbose(env, "%d: ", env->insn_idx);
16280 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16281 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16282 env->prev_log_pos = env->log.end_pos;
16285 if (bpf_prog_is_offloaded(env->prog->aux)) {
16286 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16287 env->prev_insn_idx);
16292 regs = cur_regs(env);
16293 sanitize_mark_insn_seen(env);
16294 prev_insn_idx = env->insn_idx;
16296 if (class == BPF_ALU || class == BPF_ALU64) {
16297 err = check_alu_op(env, insn);
16301 } else if (class == BPF_LDX) {
16302 enum bpf_reg_type src_reg_type;
16304 /* check for reserved fields is already done */
16306 /* check src operand */
16307 err = check_reg_arg(env, insn->src_reg, SRC_OP);
16311 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16315 src_reg_type = regs[insn->src_reg].type;
16317 /* check that memory (src_reg + off) is readable,
16318 * the state of dst_reg will be updated by this func
16320 err = check_mem_access(env, env->insn_idx, insn->src_reg,
16321 insn->off, BPF_SIZE(insn->code),
16322 BPF_READ, insn->dst_reg, false);
16326 err = save_aux_ptr_type(env, src_reg_type, true);
16329 } else if (class == BPF_STX) {
16330 enum bpf_reg_type dst_reg_type;
16332 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16333 err = check_atomic(env, env->insn_idx, insn);
16340 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16341 verbose(env, "BPF_STX uses reserved fields\n");
16345 /* check src1 operand */
16346 err = check_reg_arg(env, insn->src_reg, SRC_OP);
16349 /* check src2 operand */
16350 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16354 dst_reg_type = regs[insn->dst_reg].type;
16356 /* check that memory (dst_reg + off) is writeable */
16357 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16358 insn->off, BPF_SIZE(insn->code),
16359 BPF_WRITE, insn->src_reg, false);
16363 err = save_aux_ptr_type(env, dst_reg_type, false);
16366 } else if (class == BPF_ST) {
16367 enum bpf_reg_type dst_reg_type;
16369 if (BPF_MODE(insn->code) != BPF_MEM ||
16370 insn->src_reg != BPF_REG_0) {
16371 verbose(env, "BPF_ST uses reserved fields\n");
16374 /* check src operand */
16375 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16379 dst_reg_type = regs[insn->dst_reg].type;
16381 /* check that memory (dst_reg + off) is writeable */
16382 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16383 insn->off, BPF_SIZE(insn->code),
16384 BPF_WRITE, -1, false);
16388 err = save_aux_ptr_type(env, dst_reg_type, false);
16391 } else if (class == BPF_JMP || class == BPF_JMP32) {
16392 u8 opcode = BPF_OP(insn->code);
16394 env->jmps_processed++;
16395 if (opcode == BPF_CALL) {
16396 if (BPF_SRC(insn->code) != BPF_K ||
16397 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16398 && insn->off != 0) ||
16399 (insn->src_reg != BPF_REG_0 &&
16400 insn->src_reg != BPF_PSEUDO_CALL &&
16401 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16402 insn->dst_reg != BPF_REG_0 ||
16403 class == BPF_JMP32) {
16404 verbose(env, "BPF_CALL uses reserved fields\n");
16408 if (env->cur_state->active_lock.ptr) {
16409 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16410 (insn->src_reg == BPF_PSEUDO_CALL) ||
16411 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16412 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16413 verbose(env, "function calls are not allowed while holding a lock\n");
16417 if (insn->src_reg == BPF_PSEUDO_CALL)
16418 err = check_func_call(env, insn, &env->insn_idx);
16419 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16420 err = check_kfunc_call(env, insn, &env->insn_idx);
16422 err = check_helper_call(env, insn, &env->insn_idx);
16426 mark_reg_scratched(env, BPF_REG_0);
16427 } else if (opcode == BPF_JA) {
16428 if (BPF_SRC(insn->code) != BPF_K ||
16430 insn->src_reg != BPF_REG_0 ||
16431 insn->dst_reg != BPF_REG_0 ||
16432 class == BPF_JMP32) {
16433 verbose(env, "BPF_JA uses reserved fields\n");
16437 env->insn_idx += insn->off + 1;
16440 } else if (opcode == BPF_EXIT) {
16441 if (BPF_SRC(insn->code) != BPF_K ||
16443 insn->src_reg != BPF_REG_0 ||
16444 insn->dst_reg != BPF_REG_0 ||
16445 class == BPF_JMP32) {
16446 verbose(env, "BPF_EXIT uses reserved fields\n");
16450 if (env->cur_state->active_lock.ptr &&
16451 !in_rbtree_lock_required_cb(env)) {
16452 verbose(env, "bpf_spin_unlock is missing\n");
16456 if (env->cur_state->active_rcu_lock) {
16457 verbose(env, "bpf_rcu_read_unlock is missing\n");
16461 /* We must do check_reference_leak here before
16462 * prepare_func_exit to handle the case when
16463 * state->curframe > 0, it may be a callback
16464 * function, for which reference_state must
16465 * match caller reference state when it exits.
16467 err = check_reference_leak(env);
16471 if (state->curframe) {
16472 /* exit from nested function */
16473 err = prepare_func_exit(env, &env->insn_idx);
16476 do_print_state = true;
16480 err = check_return_code(env);
16484 mark_verifier_state_scratched(env);
16485 update_branch_counts(env, env->cur_state);
16486 err = pop_stack(env, &prev_insn_idx,
16487 &env->insn_idx, pop_log);
16489 if (err != -ENOENT)
16493 do_print_state = true;
16497 err = check_cond_jmp_op(env, insn, &env->insn_idx);
16501 } else if (class == BPF_LD) {
16502 u8 mode = BPF_MODE(insn->code);
16504 if (mode == BPF_ABS || mode == BPF_IND) {
16505 err = check_ld_abs(env, insn);
16509 } else if (mode == BPF_IMM) {
16510 err = check_ld_imm(env, insn);
16515 sanitize_mark_insn_seen(env);
16517 verbose(env, "invalid BPF_LD mode\n");
16521 verbose(env, "unknown insn class %d\n", class);
16531 static int find_btf_percpu_datasec(struct btf *btf)
16533 const struct btf_type *t;
16538 * Both vmlinux and module each have their own ".data..percpu"
16539 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16540 * types to look at only module's own BTF types.
16542 n = btf_nr_types(btf);
16543 if (btf_is_module(btf))
16544 i = btf_nr_types(btf_vmlinux);
16548 for(; i < n; i++) {
16549 t = btf_type_by_id(btf, i);
16550 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16553 tname = btf_name_by_offset(btf, t->name_off);
16554 if (!strcmp(tname, ".data..percpu"))
16561 /* replace pseudo btf_id with kernel symbol address */
16562 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16563 struct bpf_insn *insn,
16564 struct bpf_insn_aux_data *aux)
16566 const struct btf_var_secinfo *vsi;
16567 const struct btf_type *datasec;
16568 struct btf_mod_pair *btf_mod;
16569 const struct btf_type *t;
16570 const char *sym_name;
16571 bool percpu = false;
16572 u32 type, id = insn->imm;
16576 int i, btf_fd, err;
16578 btf_fd = insn[1].imm;
16580 btf = btf_get_by_fd(btf_fd);
16582 verbose(env, "invalid module BTF object FD specified.\n");
16586 if (!btf_vmlinux) {
16587 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16594 t = btf_type_by_id(btf, id);
16596 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16601 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16602 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16607 sym_name = btf_name_by_offset(btf, t->name_off);
16608 addr = kallsyms_lookup_name(sym_name);
16610 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16615 insn[0].imm = (u32)addr;
16616 insn[1].imm = addr >> 32;
16618 if (btf_type_is_func(t)) {
16619 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16620 aux->btf_var.mem_size = 0;
16624 datasec_id = find_btf_percpu_datasec(btf);
16625 if (datasec_id > 0) {
16626 datasec = btf_type_by_id(btf, datasec_id);
16627 for_each_vsi(i, datasec, vsi) {
16628 if (vsi->type == id) {
16636 t = btf_type_skip_modifiers(btf, type, NULL);
16638 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16639 aux->btf_var.btf = btf;
16640 aux->btf_var.btf_id = type;
16641 } else if (!btf_type_is_struct(t)) {
16642 const struct btf_type *ret;
16646 /* resolve the type size of ksym. */
16647 ret = btf_resolve_size(btf, t, &tsize);
16649 tname = btf_name_by_offset(btf, t->name_off);
16650 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16651 tname, PTR_ERR(ret));
16655 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16656 aux->btf_var.mem_size = tsize;
16658 aux->btf_var.reg_type = PTR_TO_BTF_ID;
16659 aux->btf_var.btf = btf;
16660 aux->btf_var.btf_id = type;
16663 /* check whether we recorded this BTF (and maybe module) already */
16664 for (i = 0; i < env->used_btf_cnt; i++) {
16665 if (env->used_btfs[i].btf == btf) {
16671 if (env->used_btf_cnt >= MAX_USED_BTFS) {
16676 btf_mod = &env->used_btfs[env->used_btf_cnt];
16677 btf_mod->btf = btf;
16678 btf_mod->module = NULL;
16680 /* if we reference variables from kernel module, bump its refcount */
16681 if (btf_is_module(btf)) {
16682 btf_mod->module = btf_try_get_module(btf);
16683 if (!btf_mod->module) {
16689 env->used_btf_cnt++;
16697 static bool is_tracing_prog_type(enum bpf_prog_type type)
16700 case BPF_PROG_TYPE_KPROBE:
16701 case BPF_PROG_TYPE_TRACEPOINT:
16702 case BPF_PROG_TYPE_PERF_EVENT:
16703 case BPF_PROG_TYPE_RAW_TRACEPOINT:
16704 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16711 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16712 struct bpf_map *map,
16713 struct bpf_prog *prog)
16716 enum bpf_prog_type prog_type = resolve_prog_type(prog);
16718 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16719 btf_record_has_field(map->record, BPF_RB_ROOT)) {
16720 if (is_tracing_prog_type(prog_type)) {
16721 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16726 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16727 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16728 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16732 if (is_tracing_prog_type(prog_type)) {
16733 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16737 if (prog->aux->sleepable) {
16738 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16743 if (btf_record_has_field(map->record, BPF_TIMER)) {
16744 if (is_tracing_prog_type(prog_type)) {
16745 verbose(env, "tracing progs cannot use bpf_timer yet\n");
16750 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16751 !bpf_offload_prog_map_match(prog, map)) {
16752 verbose(env, "offload device mismatch between prog and map\n");
16756 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16757 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16761 if (prog->aux->sleepable)
16762 switch (map->map_type) {
16763 case BPF_MAP_TYPE_HASH:
16764 case BPF_MAP_TYPE_LRU_HASH:
16765 case BPF_MAP_TYPE_ARRAY:
16766 case BPF_MAP_TYPE_PERCPU_HASH:
16767 case BPF_MAP_TYPE_PERCPU_ARRAY:
16768 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16769 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16770 case BPF_MAP_TYPE_HASH_OF_MAPS:
16771 case BPF_MAP_TYPE_RINGBUF:
16772 case BPF_MAP_TYPE_USER_RINGBUF:
16773 case BPF_MAP_TYPE_INODE_STORAGE:
16774 case BPF_MAP_TYPE_SK_STORAGE:
16775 case BPF_MAP_TYPE_TASK_STORAGE:
16776 case BPF_MAP_TYPE_CGRP_STORAGE:
16780 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
16787 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
16789 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
16790 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
16793 /* find and rewrite pseudo imm in ld_imm64 instructions:
16795 * 1. if it accesses map FD, replace it with actual map pointer.
16796 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
16798 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
16800 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
16802 struct bpf_insn *insn = env->prog->insnsi;
16803 int insn_cnt = env->prog->len;
16806 err = bpf_prog_calc_tag(env->prog);
16810 for (i = 0; i < insn_cnt; i++, insn++) {
16811 if (BPF_CLASS(insn->code) == BPF_LDX &&
16812 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
16813 verbose(env, "BPF_LDX uses reserved fields\n");
16817 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
16818 struct bpf_insn_aux_data *aux;
16819 struct bpf_map *map;
16824 if (i == insn_cnt - 1 || insn[1].code != 0 ||
16825 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
16826 insn[1].off != 0) {
16827 verbose(env, "invalid bpf_ld_imm64 insn\n");
16831 if (insn[0].src_reg == 0)
16832 /* valid generic load 64-bit imm */
16835 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
16836 aux = &env->insn_aux_data[i];
16837 err = check_pseudo_btf_id(env, insn, aux);
16843 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
16844 aux = &env->insn_aux_data[i];
16845 aux->ptr_type = PTR_TO_FUNC;
16849 /* In final convert_pseudo_ld_imm64() step, this is
16850 * converted into regular 64-bit imm load insn.
16852 switch (insn[0].src_reg) {
16853 case BPF_PSEUDO_MAP_VALUE:
16854 case BPF_PSEUDO_MAP_IDX_VALUE:
16856 case BPF_PSEUDO_MAP_FD:
16857 case BPF_PSEUDO_MAP_IDX:
16858 if (insn[1].imm == 0)
16862 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
16866 switch (insn[0].src_reg) {
16867 case BPF_PSEUDO_MAP_IDX_VALUE:
16868 case BPF_PSEUDO_MAP_IDX:
16869 if (bpfptr_is_null(env->fd_array)) {
16870 verbose(env, "fd_idx without fd_array is invalid\n");
16873 if (copy_from_bpfptr_offset(&fd, env->fd_array,
16874 insn[0].imm * sizeof(fd),
16884 map = __bpf_map_get(f);
16886 verbose(env, "fd %d is not pointing to valid bpf_map\n",
16888 return PTR_ERR(map);
16891 err = check_map_prog_compatibility(env, map, env->prog);
16897 aux = &env->insn_aux_data[i];
16898 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
16899 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
16900 addr = (unsigned long)map;
16902 u32 off = insn[1].imm;
16904 if (off >= BPF_MAX_VAR_OFF) {
16905 verbose(env, "direct value offset of %u is not allowed\n", off);
16910 if (!map->ops->map_direct_value_addr) {
16911 verbose(env, "no direct value access support for this map type\n");
16916 err = map->ops->map_direct_value_addr(map, &addr, off);
16918 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
16919 map->value_size, off);
16924 aux->map_off = off;
16928 insn[0].imm = (u32)addr;
16929 insn[1].imm = addr >> 32;
16931 /* check whether we recorded this map already */
16932 for (j = 0; j < env->used_map_cnt; j++) {
16933 if (env->used_maps[j] == map) {
16934 aux->map_index = j;
16940 if (env->used_map_cnt >= MAX_USED_MAPS) {
16945 /* hold the map. If the program is rejected by verifier,
16946 * the map will be released by release_maps() or it
16947 * will be used by the valid program until it's unloaded
16948 * and all maps are released in free_used_maps()
16952 aux->map_index = env->used_map_cnt;
16953 env->used_maps[env->used_map_cnt++] = map;
16955 if (bpf_map_is_cgroup_storage(map) &&
16956 bpf_cgroup_storage_assign(env->prog->aux, map)) {
16957 verbose(env, "only one cgroup storage of each type is allowed\n");
16969 /* Basic sanity check before we invest more work here. */
16970 if (!bpf_opcode_in_insntable(insn->code)) {
16971 verbose(env, "unknown opcode %02x\n", insn->code);
16976 /* now all pseudo BPF_LD_IMM64 instructions load valid
16977 * 'struct bpf_map *' into a register instead of user map_fd.
16978 * These pointers will be used later by verifier to validate map access.
16983 /* drop refcnt of maps used by the rejected program */
16984 static void release_maps(struct bpf_verifier_env *env)
16986 __bpf_free_used_maps(env->prog->aux, env->used_maps,
16987 env->used_map_cnt);
16990 /* drop refcnt of maps used by the rejected program */
16991 static void release_btfs(struct bpf_verifier_env *env)
16993 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
16994 env->used_btf_cnt);
16997 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
16998 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17000 struct bpf_insn *insn = env->prog->insnsi;
17001 int insn_cnt = env->prog->len;
17004 for (i = 0; i < insn_cnt; i++, insn++) {
17005 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17007 if (insn->src_reg == BPF_PSEUDO_FUNC)
17013 /* single env->prog->insni[off] instruction was replaced with the range
17014 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
17015 * [0, off) and [off, end) to new locations, so the patched range stays zero
17017 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17018 struct bpf_insn_aux_data *new_data,
17019 struct bpf_prog *new_prog, u32 off, u32 cnt)
17021 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17022 struct bpf_insn *insn = new_prog->insnsi;
17023 u32 old_seen = old_data[off].seen;
17027 /* aux info at OFF always needs adjustment, no matter fast path
17028 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17029 * original insn at old prog.
17031 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17035 prog_len = new_prog->len;
17037 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17038 memcpy(new_data + off + cnt - 1, old_data + off,
17039 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17040 for (i = off; i < off + cnt - 1; i++) {
17041 /* Expand insni[off]'s seen count to the patched range. */
17042 new_data[i].seen = old_seen;
17043 new_data[i].zext_dst = insn_has_def32(env, insn + i);
17045 env->insn_aux_data = new_data;
17049 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17055 /* NOTE: fake 'exit' subprog should be updated as well. */
17056 for (i = 0; i <= env->subprog_cnt; i++) {
17057 if (env->subprog_info[i].start <= off)
17059 env->subprog_info[i].start += len - 1;
17063 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17065 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17066 int i, sz = prog->aux->size_poke_tab;
17067 struct bpf_jit_poke_descriptor *desc;
17069 for (i = 0; i < sz; i++) {
17071 if (desc->insn_idx <= off)
17073 desc->insn_idx += len - 1;
17077 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17078 const struct bpf_insn *patch, u32 len)
17080 struct bpf_prog *new_prog;
17081 struct bpf_insn_aux_data *new_data = NULL;
17084 new_data = vzalloc(array_size(env->prog->len + len - 1,
17085 sizeof(struct bpf_insn_aux_data)));
17090 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17091 if (IS_ERR(new_prog)) {
17092 if (PTR_ERR(new_prog) == -ERANGE)
17094 "insn %d cannot be patched due to 16-bit range\n",
17095 env->insn_aux_data[off].orig_idx);
17099 adjust_insn_aux_data(env, new_data, new_prog, off, len);
17100 adjust_subprog_starts(env, off, len);
17101 adjust_poke_descs(new_prog, off, len);
17105 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17110 /* find first prog starting at or after off (first to remove) */
17111 for (i = 0; i < env->subprog_cnt; i++)
17112 if (env->subprog_info[i].start >= off)
17114 /* find first prog starting at or after off + cnt (first to stay) */
17115 for (j = i; j < env->subprog_cnt; j++)
17116 if (env->subprog_info[j].start >= off + cnt)
17118 /* if j doesn't start exactly at off + cnt, we are just removing
17119 * the front of previous prog
17121 if (env->subprog_info[j].start != off + cnt)
17125 struct bpf_prog_aux *aux = env->prog->aux;
17128 /* move fake 'exit' subprog as well */
17129 move = env->subprog_cnt + 1 - j;
17131 memmove(env->subprog_info + i,
17132 env->subprog_info + j,
17133 sizeof(*env->subprog_info) * move);
17134 env->subprog_cnt -= j - i;
17136 /* remove func_info */
17137 if (aux->func_info) {
17138 move = aux->func_info_cnt - j;
17140 memmove(aux->func_info + i,
17141 aux->func_info + j,
17142 sizeof(*aux->func_info) * move);
17143 aux->func_info_cnt -= j - i;
17144 /* func_info->insn_off is set after all code rewrites,
17145 * in adjust_btf_func() - no need to adjust
17149 /* convert i from "first prog to remove" to "first to adjust" */
17150 if (env->subprog_info[i].start == off)
17154 /* update fake 'exit' subprog as well */
17155 for (; i <= env->subprog_cnt; i++)
17156 env->subprog_info[i].start -= cnt;
17161 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17164 struct bpf_prog *prog = env->prog;
17165 u32 i, l_off, l_cnt, nr_linfo;
17166 struct bpf_line_info *linfo;
17168 nr_linfo = prog->aux->nr_linfo;
17172 linfo = prog->aux->linfo;
17174 /* find first line info to remove, count lines to be removed */
17175 for (i = 0; i < nr_linfo; i++)
17176 if (linfo[i].insn_off >= off)
17181 for (; i < nr_linfo; i++)
17182 if (linfo[i].insn_off < off + cnt)
17187 /* First live insn doesn't match first live linfo, it needs to "inherit"
17188 * last removed linfo. prog is already modified, so prog->len == off
17189 * means no live instructions after (tail of the program was removed).
17191 if (prog->len != off && l_cnt &&
17192 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17194 linfo[--i].insn_off = off + cnt;
17197 /* remove the line info which refer to the removed instructions */
17199 memmove(linfo + l_off, linfo + i,
17200 sizeof(*linfo) * (nr_linfo - i));
17202 prog->aux->nr_linfo -= l_cnt;
17203 nr_linfo = prog->aux->nr_linfo;
17206 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
17207 for (i = l_off; i < nr_linfo; i++)
17208 linfo[i].insn_off -= cnt;
17210 /* fix up all subprogs (incl. 'exit') which start >= off */
17211 for (i = 0; i <= env->subprog_cnt; i++)
17212 if (env->subprog_info[i].linfo_idx > l_off) {
17213 /* program may have started in the removed region but
17214 * may not be fully removed
17216 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17217 env->subprog_info[i].linfo_idx -= l_cnt;
17219 env->subprog_info[i].linfo_idx = l_off;
17225 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17227 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17228 unsigned int orig_prog_len = env->prog->len;
17231 if (bpf_prog_is_offloaded(env->prog->aux))
17232 bpf_prog_offload_remove_insns(env, off, cnt);
17234 err = bpf_remove_insns(env->prog, off, cnt);
17238 err = adjust_subprog_starts_after_remove(env, off, cnt);
17242 err = bpf_adj_linfo_after_remove(env, off, cnt);
17246 memmove(aux_data + off, aux_data + off + cnt,
17247 sizeof(*aux_data) * (orig_prog_len - off - cnt));
17252 /* The verifier does more data flow analysis than llvm and will not
17253 * explore branches that are dead at run time. Malicious programs can
17254 * have dead code too. Therefore replace all dead at-run-time code
17257 * Just nops are not optimal, e.g. if they would sit at the end of the
17258 * program and through another bug we would manage to jump there, then
17259 * we'd execute beyond program memory otherwise. Returning exception
17260 * code also wouldn't work since we can have subprogs where the dead
17261 * code could be located.
17263 static void sanitize_dead_code(struct bpf_verifier_env *env)
17265 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17266 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17267 struct bpf_insn *insn = env->prog->insnsi;
17268 const int insn_cnt = env->prog->len;
17271 for (i = 0; i < insn_cnt; i++) {
17272 if (aux_data[i].seen)
17274 memcpy(insn + i, &trap, sizeof(trap));
17275 aux_data[i].zext_dst = false;
17279 static bool insn_is_cond_jump(u8 code)
17283 if (BPF_CLASS(code) == BPF_JMP32)
17286 if (BPF_CLASS(code) != BPF_JMP)
17290 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17293 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17295 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17296 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17297 struct bpf_insn *insn = env->prog->insnsi;
17298 const int insn_cnt = env->prog->len;
17301 for (i = 0; i < insn_cnt; i++, insn++) {
17302 if (!insn_is_cond_jump(insn->code))
17305 if (!aux_data[i + 1].seen)
17306 ja.off = insn->off;
17307 else if (!aux_data[i + 1 + insn->off].seen)
17312 if (bpf_prog_is_offloaded(env->prog->aux))
17313 bpf_prog_offload_replace_insn(env, i, &ja);
17315 memcpy(insn, &ja, sizeof(ja));
17319 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17321 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17322 int insn_cnt = env->prog->len;
17325 for (i = 0; i < insn_cnt; i++) {
17329 while (i + j < insn_cnt && !aux_data[i + j].seen)
17334 err = verifier_remove_insns(env, i, j);
17337 insn_cnt = env->prog->len;
17343 static int opt_remove_nops(struct bpf_verifier_env *env)
17345 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17346 struct bpf_insn *insn = env->prog->insnsi;
17347 int insn_cnt = env->prog->len;
17350 for (i = 0; i < insn_cnt; i++) {
17351 if (memcmp(&insn[i], &ja, sizeof(ja)))
17354 err = verifier_remove_insns(env, i, 1);
17364 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17365 const union bpf_attr *attr)
17367 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17368 struct bpf_insn_aux_data *aux = env->insn_aux_data;
17369 int i, patch_len, delta = 0, len = env->prog->len;
17370 struct bpf_insn *insns = env->prog->insnsi;
17371 struct bpf_prog *new_prog;
17374 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17375 zext_patch[1] = BPF_ZEXT_REG(0);
17376 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17377 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17378 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17379 for (i = 0; i < len; i++) {
17380 int adj_idx = i + delta;
17381 struct bpf_insn insn;
17384 insn = insns[adj_idx];
17385 load_reg = insn_def_regno(&insn);
17386 if (!aux[adj_idx].zext_dst) {
17394 class = BPF_CLASS(code);
17395 if (load_reg == -1)
17398 /* NOTE: arg "reg" (the fourth one) is only used for
17399 * BPF_STX + SRC_OP, so it is safe to pass NULL
17402 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17403 if (class == BPF_LD &&
17404 BPF_MODE(code) == BPF_IMM)
17409 /* ctx load could be transformed into wider load. */
17410 if (class == BPF_LDX &&
17411 aux[adj_idx].ptr_type == PTR_TO_CTX)
17414 imm_rnd = get_random_u32();
17415 rnd_hi32_patch[0] = insn;
17416 rnd_hi32_patch[1].imm = imm_rnd;
17417 rnd_hi32_patch[3].dst_reg = load_reg;
17418 patch = rnd_hi32_patch;
17420 goto apply_patch_buffer;
17423 /* Add in an zero-extend instruction if a) the JIT has requested
17424 * it or b) it's a CMPXCHG.
17426 * The latter is because: BPF_CMPXCHG always loads a value into
17427 * R0, therefore always zero-extends. However some archs'
17428 * equivalent instruction only does this load when the
17429 * comparison is successful. This detail of CMPXCHG is
17430 * orthogonal to the general zero-extension behaviour of the
17431 * CPU, so it's treated independently of bpf_jit_needs_zext.
17433 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17436 /* Zero-extension is done by the caller. */
17437 if (bpf_pseudo_kfunc_call(&insn))
17440 if (WARN_ON(load_reg == -1)) {
17441 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17445 zext_patch[0] = insn;
17446 zext_patch[1].dst_reg = load_reg;
17447 zext_patch[1].src_reg = load_reg;
17448 patch = zext_patch;
17450 apply_patch_buffer:
17451 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17454 env->prog = new_prog;
17455 insns = new_prog->insnsi;
17456 aux = env->insn_aux_data;
17457 delta += patch_len - 1;
17463 /* convert load instructions that access fields of a context type into a
17464 * sequence of instructions that access fields of the underlying structure:
17465 * struct __sk_buff -> struct sk_buff
17466 * struct bpf_sock_ops -> struct sock
17468 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17470 const struct bpf_verifier_ops *ops = env->ops;
17471 int i, cnt, size, ctx_field_size, delta = 0;
17472 const int insn_cnt = env->prog->len;
17473 struct bpf_insn insn_buf[16], *insn;
17474 u32 target_size, size_default, off;
17475 struct bpf_prog *new_prog;
17476 enum bpf_access_type type;
17477 bool is_narrower_load;
17479 if (ops->gen_prologue || env->seen_direct_write) {
17480 if (!ops->gen_prologue) {
17481 verbose(env, "bpf verifier is misconfigured\n");
17484 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17486 if (cnt >= ARRAY_SIZE(insn_buf)) {
17487 verbose(env, "bpf verifier is misconfigured\n");
17490 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17494 env->prog = new_prog;
17499 if (bpf_prog_is_offloaded(env->prog->aux))
17502 insn = env->prog->insnsi + delta;
17504 for (i = 0; i < insn_cnt; i++, insn++) {
17505 bpf_convert_ctx_access_t convert_ctx_access;
17507 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17508 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17509 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17510 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
17512 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17513 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17514 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17515 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17516 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17517 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17518 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17519 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17525 if (type == BPF_WRITE &&
17526 env->insn_aux_data[i + delta].sanitize_stack_spill) {
17527 struct bpf_insn patch[] = {
17532 cnt = ARRAY_SIZE(patch);
17533 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17538 env->prog = new_prog;
17539 insn = new_prog->insnsi + i + delta;
17543 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17545 if (!ops->convert_ctx_access)
17547 convert_ctx_access = ops->convert_ctx_access;
17549 case PTR_TO_SOCKET:
17550 case PTR_TO_SOCK_COMMON:
17551 convert_ctx_access = bpf_sock_convert_ctx_access;
17553 case PTR_TO_TCP_SOCK:
17554 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17556 case PTR_TO_XDP_SOCK:
17557 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17559 case PTR_TO_BTF_ID:
17560 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17561 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17562 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17563 * be said once it is marked PTR_UNTRUSTED, hence we must handle
17564 * any faults for loads into such types. BPF_WRITE is disallowed
17567 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17568 if (type == BPF_READ) {
17569 insn->code = BPF_LDX | BPF_PROBE_MEM |
17570 BPF_SIZE((insn)->code);
17571 env->prog->aux->num_exentries++;
17578 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17579 size = BPF_LDST_BYTES(insn);
17581 /* If the read access is a narrower load of the field,
17582 * convert to a 4/8-byte load, to minimum program type specific
17583 * convert_ctx_access changes. If conversion is successful,
17584 * we will apply proper mask to the result.
17586 is_narrower_load = size < ctx_field_size;
17587 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17589 if (is_narrower_load) {
17592 if (type == BPF_WRITE) {
17593 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17598 if (ctx_field_size == 4)
17600 else if (ctx_field_size == 8)
17601 size_code = BPF_DW;
17603 insn->off = off & ~(size_default - 1);
17604 insn->code = BPF_LDX | BPF_MEM | size_code;
17608 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17610 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17611 (ctx_field_size && !target_size)) {
17612 verbose(env, "bpf verifier is misconfigured\n");
17616 if (is_narrower_load && size < target_size) {
17617 u8 shift = bpf_ctx_narrow_access_offset(
17618 off, size, size_default) * 8;
17619 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17620 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17623 if (ctx_field_size <= 4) {
17625 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17628 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17629 (1 << size * 8) - 1);
17632 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17635 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17636 (1ULL << size * 8) - 1);
17640 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17646 /* keep walking new program and skip insns we just inserted */
17647 env->prog = new_prog;
17648 insn = new_prog->insnsi + i + delta;
17654 static int jit_subprogs(struct bpf_verifier_env *env)
17656 struct bpf_prog *prog = env->prog, **func, *tmp;
17657 int i, j, subprog_start, subprog_end = 0, len, subprog;
17658 struct bpf_map *map_ptr;
17659 struct bpf_insn *insn;
17660 void *old_bpf_func;
17661 int err, num_exentries;
17663 if (env->subprog_cnt <= 1)
17666 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17667 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17670 /* Upon error here we cannot fall back to interpreter but
17671 * need a hard reject of the program. Thus -EFAULT is
17672 * propagated in any case.
17674 subprog = find_subprog(env, i + insn->imm + 1);
17676 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17677 i + insn->imm + 1);
17680 /* temporarily remember subprog id inside insn instead of
17681 * aux_data, since next loop will split up all insns into funcs
17683 insn->off = subprog;
17684 /* remember original imm in case JIT fails and fallback
17685 * to interpreter will be needed
17687 env->insn_aux_data[i].call_imm = insn->imm;
17688 /* point imm to __bpf_call_base+1 from JITs point of view */
17690 if (bpf_pseudo_func(insn))
17691 /* jit (e.g. x86_64) may emit fewer instructions
17692 * if it learns a u32 imm is the same as a u64 imm.
17693 * Force a non zero here.
17698 err = bpf_prog_alloc_jited_linfo(prog);
17700 goto out_undo_insn;
17703 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17705 goto out_undo_insn;
17707 for (i = 0; i < env->subprog_cnt; i++) {
17708 subprog_start = subprog_end;
17709 subprog_end = env->subprog_info[i + 1].start;
17711 len = subprog_end - subprog_start;
17712 /* bpf_prog_run() doesn't call subprogs directly,
17713 * hence main prog stats include the runtime of subprogs.
17714 * subprogs don't have IDs and not reachable via prog_get_next_id
17715 * func[i]->stats will never be accessed and stays NULL
17717 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17720 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17721 len * sizeof(struct bpf_insn));
17722 func[i]->type = prog->type;
17723 func[i]->len = len;
17724 if (bpf_prog_calc_tag(func[i]))
17726 func[i]->is_func = 1;
17727 func[i]->aux->func_idx = i;
17728 /* Below members will be freed only at prog->aux */
17729 func[i]->aux->btf = prog->aux->btf;
17730 func[i]->aux->func_info = prog->aux->func_info;
17731 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17732 func[i]->aux->poke_tab = prog->aux->poke_tab;
17733 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17735 for (j = 0; j < prog->aux->size_poke_tab; j++) {
17736 struct bpf_jit_poke_descriptor *poke;
17738 poke = &prog->aux->poke_tab[j];
17739 if (poke->insn_idx < subprog_end &&
17740 poke->insn_idx >= subprog_start)
17741 poke->aux = func[i]->aux;
17744 func[i]->aux->name[0] = 'F';
17745 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17746 func[i]->jit_requested = 1;
17747 func[i]->blinding_requested = prog->blinding_requested;
17748 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17749 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17750 func[i]->aux->linfo = prog->aux->linfo;
17751 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17752 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17753 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17755 insn = func[i]->insnsi;
17756 for (j = 0; j < func[i]->len; j++, insn++) {
17757 if (BPF_CLASS(insn->code) == BPF_LDX &&
17758 BPF_MODE(insn->code) == BPF_PROBE_MEM)
17761 func[i]->aux->num_exentries = num_exentries;
17762 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
17763 func[i] = bpf_int_jit_compile(func[i]);
17764 if (!func[i]->jited) {
17771 /* at this point all bpf functions were successfully JITed
17772 * now populate all bpf_calls with correct addresses and
17773 * run last pass of JIT
17775 for (i = 0; i < env->subprog_cnt; i++) {
17776 insn = func[i]->insnsi;
17777 for (j = 0; j < func[i]->len; j++, insn++) {
17778 if (bpf_pseudo_func(insn)) {
17779 subprog = insn->off;
17780 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
17781 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
17784 if (!bpf_pseudo_call(insn))
17786 subprog = insn->off;
17787 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
17790 /* we use the aux data to keep a list of the start addresses
17791 * of the JITed images for each function in the program
17793 * for some architectures, such as powerpc64, the imm field
17794 * might not be large enough to hold the offset of the start
17795 * address of the callee's JITed image from __bpf_call_base
17797 * in such cases, we can lookup the start address of a callee
17798 * by using its subprog id, available from the off field of
17799 * the call instruction, as an index for this list
17801 func[i]->aux->func = func;
17802 func[i]->aux->func_cnt = env->subprog_cnt;
17804 for (i = 0; i < env->subprog_cnt; i++) {
17805 old_bpf_func = func[i]->bpf_func;
17806 tmp = bpf_int_jit_compile(func[i]);
17807 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
17808 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
17815 /* finally lock prog and jit images for all functions and
17816 * populate kallsysm. Begin at the first subprogram, since
17817 * bpf_prog_load will add the kallsyms for the main program.
17819 for (i = 1; i < env->subprog_cnt; i++) {
17820 bpf_prog_lock_ro(func[i]);
17821 bpf_prog_kallsyms_add(func[i]);
17824 /* Last step: make now unused interpreter insns from main
17825 * prog consistent for later dump requests, so they can
17826 * later look the same as if they were interpreted only.
17828 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17829 if (bpf_pseudo_func(insn)) {
17830 insn[0].imm = env->insn_aux_data[i].call_imm;
17831 insn[1].imm = insn->off;
17835 if (!bpf_pseudo_call(insn))
17837 insn->off = env->insn_aux_data[i].call_imm;
17838 subprog = find_subprog(env, i + insn->off + 1);
17839 insn->imm = subprog;
17843 prog->bpf_func = func[0]->bpf_func;
17844 prog->jited_len = func[0]->jited_len;
17845 prog->aux->extable = func[0]->aux->extable;
17846 prog->aux->num_exentries = func[0]->aux->num_exentries;
17847 prog->aux->func = func;
17848 prog->aux->func_cnt = env->subprog_cnt;
17849 bpf_prog_jit_attempt_done(prog);
17852 /* We failed JIT'ing, so at this point we need to unregister poke
17853 * descriptors from subprogs, so that kernel is not attempting to
17854 * patch it anymore as we're freeing the subprog JIT memory.
17856 for (i = 0; i < prog->aux->size_poke_tab; i++) {
17857 map_ptr = prog->aux->poke_tab[i].tail_call.map;
17858 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
17860 /* At this point we're guaranteed that poke descriptors are not
17861 * live anymore. We can just unlink its descriptor table as it's
17862 * released with the main prog.
17864 for (i = 0; i < env->subprog_cnt; i++) {
17867 func[i]->aux->poke_tab = NULL;
17868 bpf_jit_free(func[i]);
17872 /* cleanup main prog to be interpreted */
17873 prog->jit_requested = 0;
17874 prog->blinding_requested = 0;
17875 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17876 if (!bpf_pseudo_call(insn))
17879 insn->imm = env->insn_aux_data[i].call_imm;
17881 bpf_prog_jit_attempt_done(prog);
17885 static int fixup_call_args(struct bpf_verifier_env *env)
17887 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17888 struct bpf_prog *prog = env->prog;
17889 struct bpf_insn *insn = prog->insnsi;
17890 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
17895 if (env->prog->jit_requested &&
17896 !bpf_prog_is_offloaded(env->prog->aux)) {
17897 err = jit_subprogs(env);
17900 if (err == -EFAULT)
17903 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17904 if (has_kfunc_call) {
17905 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
17908 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
17909 /* When JIT fails the progs with bpf2bpf calls and tail_calls
17910 * have to be rejected, since interpreter doesn't support them yet.
17912 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
17915 for (i = 0; i < prog->len; i++, insn++) {
17916 if (bpf_pseudo_func(insn)) {
17917 /* When JIT fails the progs with callback calls
17918 * have to be rejected, since interpreter doesn't support them yet.
17920 verbose(env, "callbacks are not allowed in non-JITed programs\n");
17924 if (!bpf_pseudo_call(insn))
17926 depth = get_callee_stack_depth(env, insn, i);
17929 bpf_patch_call_args(insn, depth);
17936 /* replace a generic kfunc with a specialized version if necessary */
17937 static void specialize_kfunc(struct bpf_verifier_env *env,
17938 u32 func_id, u16 offset, unsigned long *addr)
17940 struct bpf_prog *prog = env->prog;
17941 bool seen_direct_write;
17945 if (bpf_dev_bound_kfunc_id(func_id)) {
17946 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
17948 *addr = (unsigned long)xdp_kfunc;
17951 /* fallback to default kfunc when not supported by netdev */
17957 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
17958 seen_direct_write = env->seen_direct_write;
17959 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
17962 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
17964 /* restore env->seen_direct_write to its original value, since
17965 * may_access_direct_pkt_data mutates it
17967 env->seen_direct_write = seen_direct_write;
17971 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
17972 u16 struct_meta_reg,
17973 u16 node_offset_reg,
17974 struct bpf_insn *insn,
17975 struct bpf_insn *insn_buf,
17978 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
17979 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
17981 insn_buf[0] = addr[0];
17982 insn_buf[1] = addr[1];
17983 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
17984 insn_buf[3] = *insn;
17988 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
17989 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
17991 const struct bpf_kfunc_desc *desc;
17994 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18000 /* insn->imm has the btf func_id. Replace it with an offset relative to
18001 * __bpf_call_base, unless the JIT needs to call functions that are
18002 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18004 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18006 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18011 if (!bpf_jit_supports_far_kfunc_call())
18012 insn->imm = BPF_CALL_IMM(desc->addr);
18015 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18016 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18017 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18018 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18020 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18021 insn_buf[1] = addr[0];
18022 insn_buf[2] = addr[1];
18023 insn_buf[3] = *insn;
18025 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18026 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18027 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18028 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18030 insn_buf[0] = addr[0];
18031 insn_buf[1] = addr[1];
18032 insn_buf[2] = *insn;
18034 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18035 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18036 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18037 int struct_meta_reg = BPF_REG_3;
18038 int node_offset_reg = BPF_REG_4;
18040 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18041 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18042 struct_meta_reg = BPF_REG_4;
18043 node_offset_reg = BPF_REG_5;
18046 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18047 node_offset_reg, insn, insn_buf, cnt);
18048 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18049 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18050 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18056 /* Do various post-verification rewrites in a single program pass.
18057 * These rewrites simplify JIT and interpreter implementations.
18059 static int do_misc_fixups(struct bpf_verifier_env *env)
18061 struct bpf_prog *prog = env->prog;
18062 enum bpf_attach_type eatype = prog->expected_attach_type;
18063 enum bpf_prog_type prog_type = resolve_prog_type(prog);
18064 struct bpf_insn *insn = prog->insnsi;
18065 const struct bpf_func_proto *fn;
18066 const int insn_cnt = prog->len;
18067 const struct bpf_map_ops *ops;
18068 struct bpf_insn_aux_data *aux;
18069 struct bpf_insn insn_buf[16];
18070 struct bpf_prog *new_prog;
18071 struct bpf_map *map_ptr;
18072 int i, ret, cnt, delta = 0;
18074 for (i = 0; i < insn_cnt; i++, insn++) {
18075 /* Make divide-by-zero exceptions impossible. */
18076 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18077 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18078 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18079 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18080 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18081 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18082 struct bpf_insn *patchlet;
18083 struct bpf_insn chk_and_div[] = {
18084 /* [R,W]x div 0 -> 0 */
18085 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18086 BPF_JNE | BPF_K, insn->src_reg,
18088 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18089 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18092 struct bpf_insn chk_and_mod[] = {
18093 /* [R,W]x mod 0 -> [R,W]x */
18094 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18095 BPF_JEQ | BPF_K, insn->src_reg,
18096 0, 1 + (is64 ? 0 : 1), 0),
18098 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18099 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18102 patchlet = isdiv ? chk_and_div : chk_and_mod;
18103 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18104 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18106 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18111 env->prog = prog = new_prog;
18112 insn = new_prog->insnsi + i + delta;
18116 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18117 if (BPF_CLASS(insn->code) == BPF_LD &&
18118 (BPF_MODE(insn->code) == BPF_ABS ||
18119 BPF_MODE(insn->code) == BPF_IND)) {
18120 cnt = env->ops->gen_ld_abs(insn, insn_buf);
18121 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18122 verbose(env, "bpf verifier is misconfigured\n");
18126 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18131 env->prog = prog = new_prog;
18132 insn = new_prog->insnsi + i + delta;
18136 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
18137 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18138 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18139 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18140 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18141 struct bpf_insn *patch = &insn_buf[0];
18142 bool issrc, isneg, isimm;
18145 aux = &env->insn_aux_data[i + delta];
18146 if (!aux->alu_state ||
18147 aux->alu_state == BPF_ALU_NON_POINTER)
18150 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18151 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18152 BPF_ALU_SANITIZE_SRC;
18153 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18155 off_reg = issrc ? insn->src_reg : insn->dst_reg;
18157 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18160 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18161 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18162 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18163 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18164 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18165 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18166 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18169 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18170 insn->src_reg = BPF_REG_AX;
18172 insn->code = insn->code == code_add ?
18173 code_sub : code_add;
18175 if (issrc && isneg && !isimm)
18176 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18177 cnt = patch - insn_buf;
18179 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18184 env->prog = prog = new_prog;
18185 insn = new_prog->insnsi + i + delta;
18189 if (insn->code != (BPF_JMP | BPF_CALL))
18191 if (insn->src_reg == BPF_PSEUDO_CALL)
18193 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18194 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18200 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18205 env->prog = prog = new_prog;
18206 insn = new_prog->insnsi + i + delta;
18210 if (insn->imm == BPF_FUNC_get_route_realm)
18211 prog->dst_needed = 1;
18212 if (insn->imm == BPF_FUNC_get_prandom_u32)
18213 bpf_user_rnd_init_once();
18214 if (insn->imm == BPF_FUNC_override_return)
18215 prog->kprobe_override = 1;
18216 if (insn->imm == BPF_FUNC_tail_call) {
18217 /* If we tail call into other programs, we
18218 * cannot make any assumptions since they can
18219 * be replaced dynamically during runtime in
18220 * the program array.
18222 prog->cb_access = 1;
18223 if (!allow_tail_call_in_subprogs(env))
18224 prog->aux->stack_depth = MAX_BPF_STACK;
18225 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18227 /* mark bpf_tail_call as different opcode to avoid
18228 * conditional branch in the interpreter for every normal
18229 * call and to prevent accidental JITing by JIT compiler
18230 * that doesn't support bpf_tail_call yet
18233 insn->code = BPF_JMP | BPF_TAIL_CALL;
18235 aux = &env->insn_aux_data[i + delta];
18236 if (env->bpf_capable && !prog->blinding_requested &&
18237 prog->jit_requested &&
18238 !bpf_map_key_poisoned(aux) &&
18239 !bpf_map_ptr_poisoned(aux) &&
18240 !bpf_map_ptr_unpriv(aux)) {
18241 struct bpf_jit_poke_descriptor desc = {
18242 .reason = BPF_POKE_REASON_TAIL_CALL,
18243 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18244 .tail_call.key = bpf_map_key_immediate(aux),
18245 .insn_idx = i + delta,
18248 ret = bpf_jit_add_poke_descriptor(prog, &desc);
18250 verbose(env, "adding tail call poke descriptor failed\n");
18254 insn->imm = ret + 1;
18258 if (!bpf_map_ptr_unpriv(aux))
18261 /* instead of changing every JIT dealing with tail_call
18262 * emit two extra insns:
18263 * if (index >= max_entries) goto out;
18264 * index &= array->index_mask;
18265 * to avoid out-of-bounds cpu speculation
18267 if (bpf_map_ptr_poisoned(aux)) {
18268 verbose(env, "tail_call abusing map_ptr\n");
18272 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18273 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18274 map_ptr->max_entries, 2);
18275 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18276 container_of(map_ptr,
18279 insn_buf[2] = *insn;
18281 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18286 env->prog = prog = new_prog;
18287 insn = new_prog->insnsi + i + delta;
18291 if (insn->imm == BPF_FUNC_timer_set_callback) {
18292 /* The verifier will process callback_fn as many times as necessary
18293 * with different maps and the register states prepared by
18294 * set_timer_callback_state will be accurate.
18296 * The following use case is valid:
18297 * map1 is shared by prog1, prog2, prog3.
18298 * prog1 calls bpf_timer_init for some map1 elements
18299 * prog2 calls bpf_timer_set_callback for some map1 elements.
18300 * Those that were not bpf_timer_init-ed will return -EINVAL.
18301 * prog3 calls bpf_timer_start for some map1 elements.
18302 * Those that were not both bpf_timer_init-ed and
18303 * bpf_timer_set_callback-ed will return -EINVAL.
18305 struct bpf_insn ld_addrs[2] = {
18306 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18309 insn_buf[0] = ld_addrs[0];
18310 insn_buf[1] = ld_addrs[1];
18311 insn_buf[2] = *insn;
18314 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18319 env->prog = prog = new_prog;
18320 insn = new_prog->insnsi + i + delta;
18321 goto patch_call_imm;
18324 if (is_storage_get_function(insn->imm)) {
18325 if (!env->prog->aux->sleepable ||
18326 env->insn_aux_data[i + delta].storage_get_func_atomic)
18327 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18329 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18330 insn_buf[1] = *insn;
18333 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18338 env->prog = prog = new_prog;
18339 insn = new_prog->insnsi + i + delta;
18340 goto patch_call_imm;
18343 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18344 * and other inlining handlers are currently limited to 64 bit
18347 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18348 (insn->imm == BPF_FUNC_map_lookup_elem ||
18349 insn->imm == BPF_FUNC_map_update_elem ||
18350 insn->imm == BPF_FUNC_map_delete_elem ||
18351 insn->imm == BPF_FUNC_map_push_elem ||
18352 insn->imm == BPF_FUNC_map_pop_elem ||
18353 insn->imm == BPF_FUNC_map_peek_elem ||
18354 insn->imm == BPF_FUNC_redirect_map ||
18355 insn->imm == BPF_FUNC_for_each_map_elem ||
18356 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18357 aux = &env->insn_aux_data[i + delta];
18358 if (bpf_map_ptr_poisoned(aux))
18359 goto patch_call_imm;
18361 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18362 ops = map_ptr->ops;
18363 if (insn->imm == BPF_FUNC_map_lookup_elem &&
18364 ops->map_gen_lookup) {
18365 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18366 if (cnt == -EOPNOTSUPP)
18367 goto patch_map_ops_generic;
18368 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18369 verbose(env, "bpf verifier is misconfigured\n");
18373 new_prog = bpf_patch_insn_data(env, i + delta,
18379 env->prog = prog = new_prog;
18380 insn = new_prog->insnsi + i + delta;
18384 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18385 (void *(*)(struct bpf_map *map, void *key))NULL));
18386 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18387 (long (*)(struct bpf_map *map, void *key))NULL));
18388 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18389 (long (*)(struct bpf_map *map, void *key, void *value,
18391 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18392 (long (*)(struct bpf_map *map, void *value,
18394 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18395 (long (*)(struct bpf_map *map, void *value))NULL));
18396 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18397 (long (*)(struct bpf_map *map, void *value))NULL));
18398 BUILD_BUG_ON(!__same_type(ops->map_redirect,
18399 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18400 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18401 (long (*)(struct bpf_map *map,
18402 bpf_callback_t callback_fn,
18403 void *callback_ctx,
18405 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18406 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18408 patch_map_ops_generic:
18409 switch (insn->imm) {
18410 case BPF_FUNC_map_lookup_elem:
18411 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18413 case BPF_FUNC_map_update_elem:
18414 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18416 case BPF_FUNC_map_delete_elem:
18417 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18419 case BPF_FUNC_map_push_elem:
18420 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18422 case BPF_FUNC_map_pop_elem:
18423 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18425 case BPF_FUNC_map_peek_elem:
18426 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18428 case BPF_FUNC_redirect_map:
18429 insn->imm = BPF_CALL_IMM(ops->map_redirect);
18431 case BPF_FUNC_for_each_map_elem:
18432 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18434 case BPF_FUNC_map_lookup_percpu_elem:
18435 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18439 goto patch_call_imm;
18442 /* Implement bpf_jiffies64 inline. */
18443 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18444 insn->imm == BPF_FUNC_jiffies64) {
18445 struct bpf_insn ld_jiffies_addr[2] = {
18446 BPF_LD_IMM64(BPF_REG_0,
18447 (unsigned long)&jiffies),
18450 insn_buf[0] = ld_jiffies_addr[0];
18451 insn_buf[1] = ld_jiffies_addr[1];
18452 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18456 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18462 env->prog = prog = new_prog;
18463 insn = new_prog->insnsi + i + delta;
18467 /* Implement bpf_get_func_arg inline. */
18468 if (prog_type == BPF_PROG_TYPE_TRACING &&
18469 insn->imm == BPF_FUNC_get_func_arg) {
18470 /* Load nr_args from ctx - 8 */
18471 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18472 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18473 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18474 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18475 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18476 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18477 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18478 insn_buf[7] = BPF_JMP_A(1);
18479 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18482 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18487 env->prog = prog = new_prog;
18488 insn = new_prog->insnsi + i + delta;
18492 /* Implement bpf_get_func_ret inline. */
18493 if (prog_type == BPF_PROG_TYPE_TRACING &&
18494 insn->imm == BPF_FUNC_get_func_ret) {
18495 if (eatype == BPF_TRACE_FEXIT ||
18496 eatype == BPF_MODIFY_RETURN) {
18497 /* Load nr_args from ctx - 8 */
18498 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18499 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18500 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18501 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18502 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18503 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18506 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18510 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18515 env->prog = prog = new_prog;
18516 insn = new_prog->insnsi + i + delta;
18520 /* Implement get_func_arg_cnt inline. */
18521 if (prog_type == BPF_PROG_TYPE_TRACING &&
18522 insn->imm == BPF_FUNC_get_func_arg_cnt) {
18523 /* Load nr_args from ctx - 8 */
18524 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18526 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18530 env->prog = prog = new_prog;
18531 insn = new_prog->insnsi + i + delta;
18535 /* Implement bpf_get_func_ip inline. */
18536 if (prog_type == BPF_PROG_TYPE_TRACING &&
18537 insn->imm == BPF_FUNC_get_func_ip) {
18538 /* Load IP address from ctx - 16 */
18539 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18541 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18545 env->prog = prog = new_prog;
18546 insn = new_prog->insnsi + i + delta;
18551 fn = env->ops->get_func_proto(insn->imm, env->prog);
18552 /* all functions that have prototype and verifier allowed
18553 * programs to call them, must be real in-kernel functions
18557 "kernel subsystem misconfigured func %s#%d\n",
18558 func_id_name(insn->imm), insn->imm);
18561 insn->imm = fn->func - __bpf_call_base;
18564 /* Since poke tab is now finalized, publish aux to tracker. */
18565 for (i = 0; i < prog->aux->size_poke_tab; i++) {
18566 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18567 if (!map_ptr->ops->map_poke_track ||
18568 !map_ptr->ops->map_poke_untrack ||
18569 !map_ptr->ops->map_poke_run) {
18570 verbose(env, "bpf verifier is misconfigured\n");
18574 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18576 verbose(env, "tracking tail call prog failed\n");
18581 sort_kfunc_descs_by_imm_off(env->prog);
18586 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18589 u32 callback_subprogno,
18592 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18593 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18594 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18595 int reg_loop_max = BPF_REG_6;
18596 int reg_loop_cnt = BPF_REG_7;
18597 int reg_loop_ctx = BPF_REG_8;
18599 struct bpf_prog *new_prog;
18600 u32 callback_start;
18601 u32 call_insn_offset;
18602 s32 callback_offset;
18604 /* This represents an inlined version of bpf_iter.c:bpf_loop,
18605 * be careful to modify this code in sync.
18607 struct bpf_insn insn_buf[] = {
18608 /* Return error and jump to the end of the patch if
18609 * expected number of iterations is too big.
18611 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18612 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18613 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18614 /* spill R6, R7, R8 to use these as loop vars */
18615 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18616 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18617 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18618 /* initialize loop vars */
18619 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18620 BPF_MOV32_IMM(reg_loop_cnt, 0),
18621 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18623 * if reg_loop_cnt >= reg_loop_max skip the loop body
18625 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18627 * correct callback offset would be set after patching
18629 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18630 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18632 /* increment loop counter */
18633 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18634 /* jump to loop header if callback returned 0 */
18635 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18636 /* return value of bpf_loop,
18637 * set R0 to the number of iterations
18639 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18640 /* restore original values of R6, R7, R8 */
18641 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18642 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18643 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18646 *cnt = ARRAY_SIZE(insn_buf);
18647 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18651 /* callback start is known only after patching */
18652 callback_start = env->subprog_info[callback_subprogno].start;
18653 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18654 call_insn_offset = position + 12;
18655 callback_offset = callback_start - call_insn_offset - 1;
18656 new_prog->insnsi[call_insn_offset].imm = callback_offset;
18661 static bool is_bpf_loop_call(struct bpf_insn *insn)
18663 return insn->code == (BPF_JMP | BPF_CALL) &&
18664 insn->src_reg == 0 &&
18665 insn->imm == BPF_FUNC_loop;
18668 /* For all sub-programs in the program (including main) check
18669 * insn_aux_data to see if there are bpf_loop calls that require
18670 * inlining. If such calls are found the calls are replaced with a
18671 * sequence of instructions produced by `inline_bpf_loop` function and
18672 * subprog stack_depth is increased by the size of 3 registers.
18673 * This stack space is used to spill values of the R6, R7, R8. These
18674 * registers are used to store the loop bound, counter and context
18677 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18679 struct bpf_subprog_info *subprogs = env->subprog_info;
18680 int i, cur_subprog = 0, cnt, delta = 0;
18681 struct bpf_insn *insn = env->prog->insnsi;
18682 int insn_cnt = env->prog->len;
18683 u16 stack_depth = subprogs[cur_subprog].stack_depth;
18684 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18685 u16 stack_depth_extra = 0;
18687 for (i = 0; i < insn_cnt; i++, insn++) {
18688 struct bpf_loop_inline_state *inline_state =
18689 &env->insn_aux_data[i + delta].loop_inline_state;
18691 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18692 struct bpf_prog *new_prog;
18694 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18695 new_prog = inline_bpf_loop(env,
18697 -(stack_depth + stack_depth_extra),
18698 inline_state->callback_subprogno,
18704 env->prog = new_prog;
18705 insn = new_prog->insnsi + i + delta;
18708 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18709 subprogs[cur_subprog].stack_depth += stack_depth_extra;
18711 stack_depth = subprogs[cur_subprog].stack_depth;
18712 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18713 stack_depth_extra = 0;
18717 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18722 static void free_states(struct bpf_verifier_env *env)
18724 struct bpf_verifier_state_list *sl, *sln;
18727 sl = env->free_list;
18730 free_verifier_state(&sl->state, false);
18734 env->free_list = NULL;
18736 if (!env->explored_states)
18739 for (i = 0; i < state_htab_size(env); i++) {
18740 sl = env->explored_states[i];
18744 free_verifier_state(&sl->state, false);
18748 env->explored_states[i] = NULL;
18752 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18754 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18755 struct bpf_verifier_state *state;
18756 struct bpf_reg_state *regs;
18759 env->prev_linfo = NULL;
18762 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18765 state->curframe = 0;
18766 state->speculative = false;
18767 state->branches = 1;
18768 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18769 if (!state->frame[0]) {
18773 env->cur_state = state;
18774 init_func_state(env, state->frame[0],
18775 BPF_MAIN_FUNC /* callsite */,
18778 state->first_insn_idx = env->subprog_info[subprog].start;
18779 state->last_insn_idx = -1;
18781 regs = state->frame[state->curframe]->regs;
18782 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
18783 ret = btf_prepare_func_args(env, subprog, regs);
18786 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
18787 if (regs[i].type == PTR_TO_CTX)
18788 mark_reg_known_zero(env, regs, i);
18789 else if (regs[i].type == SCALAR_VALUE)
18790 mark_reg_unknown(env, regs, i);
18791 else if (base_type(regs[i].type) == PTR_TO_MEM) {
18792 const u32 mem_size = regs[i].mem_size;
18794 mark_reg_known_zero(env, regs, i);
18795 regs[i].mem_size = mem_size;
18796 regs[i].id = ++env->id_gen;
18800 /* 1st arg to a function */
18801 regs[BPF_REG_1].type = PTR_TO_CTX;
18802 mark_reg_known_zero(env, regs, BPF_REG_1);
18803 ret = btf_check_subprog_arg_match(env, subprog, regs);
18804 if (ret == -EFAULT)
18805 /* unlikely verifier bug. abort.
18806 * ret == 0 and ret < 0 are sadly acceptable for
18807 * main() function due to backward compatibility.
18808 * Like socket filter program may be written as:
18809 * int bpf_prog(struct pt_regs *ctx)
18810 * and never dereference that ctx in the program.
18811 * 'struct pt_regs' is a type mismatch for socket
18812 * filter that should be using 'struct __sk_buff'.
18817 ret = do_check(env);
18819 /* check for NULL is necessary, since cur_state can be freed inside
18820 * do_check() under memory pressure.
18822 if (env->cur_state) {
18823 free_verifier_state(env->cur_state, true);
18824 env->cur_state = NULL;
18826 while (!pop_stack(env, NULL, NULL, false));
18827 if (!ret && pop_log)
18828 bpf_vlog_reset(&env->log, 0);
18833 /* Verify all global functions in a BPF program one by one based on their BTF.
18834 * All global functions must pass verification. Otherwise the whole program is rejected.
18845 * foo() will be verified first for R1=any_scalar_value. During verification it
18846 * will be assumed that bar() already verified successfully and call to bar()
18847 * from foo() will be checked for type match only. Later bar() will be verified
18848 * independently to check that it's safe for R1=any_scalar_value.
18850 static int do_check_subprogs(struct bpf_verifier_env *env)
18852 struct bpf_prog_aux *aux = env->prog->aux;
18855 if (!aux->func_info)
18858 for (i = 1; i < env->subprog_cnt; i++) {
18859 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
18861 env->insn_idx = env->subprog_info[i].start;
18862 WARN_ON_ONCE(env->insn_idx == 0);
18863 ret = do_check_common(env, i);
18866 } else if (env->log.level & BPF_LOG_LEVEL) {
18868 "Func#%d is safe for any args that match its prototype\n",
18875 static int do_check_main(struct bpf_verifier_env *env)
18880 ret = do_check_common(env, 0);
18882 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18887 static void print_verification_stats(struct bpf_verifier_env *env)
18891 if (env->log.level & BPF_LOG_STATS) {
18892 verbose(env, "verification time %lld usec\n",
18893 div_u64(env->verification_time, 1000));
18894 verbose(env, "stack depth ");
18895 for (i = 0; i < env->subprog_cnt; i++) {
18896 u32 depth = env->subprog_info[i].stack_depth;
18898 verbose(env, "%d", depth);
18899 if (i + 1 < env->subprog_cnt)
18902 verbose(env, "\n");
18904 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
18905 "total_states %d peak_states %d mark_read %d\n",
18906 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
18907 env->max_states_per_insn, env->total_states,
18908 env->peak_states, env->longest_mark_read_walk);
18911 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
18913 const struct btf_type *t, *func_proto;
18914 const struct bpf_struct_ops *st_ops;
18915 const struct btf_member *member;
18916 struct bpf_prog *prog = env->prog;
18917 u32 btf_id, member_idx;
18920 if (!prog->gpl_compatible) {
18921 verbose(env, "struct ops programs must have a GPL compatible license\n");
18925 btf_id = prog->aux->attach_btf_id;
18926 st_ops = bpf_struct_ops_find(btf_id);
18928 verbose(env, "attach_btf_id %u is not a supported struct\n",
18934 member_idx = prog->expected_attach_type;
18935 if (member_idx >= btf_type_vlen(t)) {
18936 verbose(env, "attach to invalid member idx %u of struct %s\n",
18937 member_idx, st_ops->name);
18941 member = &btf_type_member(t)[member_idx];
18942 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
18943 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
18946 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
18947 mname, member_idx, st_ops->name);
18951 if (st_ops->check_member) {
18952 int err = st_ops->check_member(t, member, prog);
18955 verbose(env, "attach to unsupported member %s of struct %s\n",
18956 mname, st_ops->name);
18961 prog->aux->attach_func_proto = func_proto;
18962 prog->aux->attach_func_name = mname;
18963 env->ops = st_ops->verifier_ops;
18967 #define SECURITY_PREFIX "security_"
18969 static int check_attach_modify_return(unsigned long addr, const char *func_name)
18971 if (within_error_injection_list(addr) ||
18972 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
18978 /* list of non-sleepable functions that are otherwise on
18979 * ALLOW_ERROR_INJECTION list
18981 BTF_SET_START(btf_non_sleepable_error_inject)
18982 /* Three functions below can be called from sleepable and non-sleepable context.
18983 * Assume non-sleepable from bpf safety point of view.
18985 BTF_ID(func, __filemap_add_folio)
18986 BTF_ID(func, should_fail_alloc_page)
18987 BTF_ID(func, should_failslab)
18988 BTF_SET_END(btf_non_sleepable_error_inject)
18990 static int check_non_sleepable_error_inject(u32 btf_id)
18992 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
18995 int bpf_check_attach_target(struct bpf_verifier_log *log,
18996 const struct bpf_prog *prog,
18997 const struct bpf_prog *tgt_prog,
18999 struct bpf_attach_target_info *tgt_info)
19001 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19002 const char prefix[] = "btf_trace_";
19003 int ret = 0, subprog = -1, i;
19004 const struct btf_type *t;
19005 bool conservative = true;
19009 struct module *mod = NULL;
19012 bpf_log(log, "Tracing programs must provide btf_id\n");
19015 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19018 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19021 t = btf_type_by_id(btf, btf_id);
19023 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19026 tname = btf_name_by_offset(btf, t->name_off);
19028 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19032 struct bpf_prog_aux *aux = tgt_prog->aux;
19034 if (bpf_prog_is_dev_bound(prog->aux) &&
19035 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19036 bpf_log(log, "Target program bound device mismatch");
19040 for (i = 0; i < aux->func_info_cnt; i++)
19041 if (aux->func_info[i].type_id == btf_id) {
19045 if (subprog == -1) {
19046 bpf_log(log, "Subprog %s doesn't exist\n", tname);
19049 conservative = aux->func_info_aux[subprog].unreliable;
19050 if (prog_extension) {
19051 if (conservative) {
19053 "Cannot replace static functions\n");
19056 if (!prog->jit_requested) {
19058 "Extension programs should be JITed\n");
19062 if (!tgt_prog->jited) {
19063 bpf_log(log, "Can attach to only JITed progs\n");
19066 if (tgt_prog->type == prog->type) {
19067 /* Cannot fentry/fexit another fentry/fexit program.
19068 * Cannot attach program extension to another extension.
19069 * It's ok to attach fentry/fexit to extension program.
19071 bpf_log(log, "Cannot recursively attach\n");
19074 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19076 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19077 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19078 /* Program extensions can extend all program types
19079 * except fentry/fexit. The reason is the following.
19080 * The fentry/fexit programs are used for performance
19081 * analysis, stats and can be attached to any program
19082 * type except themselves. When extension program is
19083 * replacing XDP function it is necessary to allow
19084 * performance analysis of all functions. Both original
19085 * XDP program and its program extension. Hence
19086 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19087 * allowed. If extending of fentry/fexit was allowed it
19088 * would be possible to create long call chain
19089 * fentry->extension->fentry->extension beyond
19090 * reasonable stack size. Hence extending fentry is not
19093 bpf_log(log, "Cannot extend fentry/fexit\n");
19097 if (prog_extension) {
19098 bpf_log(log, "Cannot replace kernel functions\n");
19103 switch (prog->expected_attach_type) {
19104 case BPF_TRACE_RAW_TP:
19107 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19110 if (!btf_type_is_typedef(t)) {
19111 bpf_log(log, "attach_btf_id %u is not a typedef\n",
19115 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19116 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19120 tname += sizeof(prefix) - 1;
19121 t = btf_type_by_id(btf, t->type);
19122 if (!btf_type_is_ptr(t))
19123 /* should never happen in valid vmlinux build */
19125 t = btf_type_by_id(btf, t->type);
19126 if (!btf_type_is_func_proto(t))
19127 /* should never happen in valid vmlinux build */
19131 case BPF_TRACE_ITER:
19132 if (!btf_type_is_func(t)) {
19133 bpf_log(log, "attach_btf_id %u is not a function\n",
19137 t = btf_type_by_id(btf, t->type);
19138 if (!btf_type_is_func_proto(t))
19140 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19145 if (!prog_extension)
19148 case BPF_MODIFY_RETURN:
19150 case BPF_LSM_CGROUP:
19151 case BPF_TRACE_FENTRY:
19152 case BPF_TRACE_FEXIT:
19153 if (!btf_type_is_func(t)) {
19154 bpf_log(log, "attach_btf_id %u is not a function\n",
19158 if (prog_extension &&
19159 btf_check_type_match(log, prog, btf, t))
19161 t = btf_type_by_id(btf, t->type);
19162 if (!btf_type_is_func_proto(t))
19165 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19166 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19167 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19170 if (tgt_prog && conservative)
19173 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19179 addr = (long) tgt_prog->bpf_func;
19181 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19183 if (btf_is_module(btf)) {
19184 mod = btf_try_get_module(btf);
19186 addr = find_kallsyms_symbol_value(mod, tname);
19190 addr = kallsyms_lookup_name(tname);
19195 "The address of function %s cannot be found\n",
19201 if (prog->aux->sleepable) {
19203 switch (prog->type) {
19204 case BPF_PROG_TYPE_TRACING:
19206 /* fentry/fexit/fmod_ret progs can be sleepable if they are
19207 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19209 if (!check_non_sleepable_error_inject(btf_id) &&
19210 within_error_injection_list(addr))
19212 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
19213 * in the fmodret id set with the KF_SLEEPABLE flag.
19216 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19219 if (flags && (*flags & KF_SLEEPABLE))
19223 case BPF_PROG_TYPE_LSM:
19224 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
19225 * Only some of them are sleepable.
19227 if (bpf_lsm_is_sleepable_hook(btf_id))
19235 bpf_log(log, "%s is not sleepable\n", tname);
19238 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19241 bpf_log(log, "can't modify return codes of BPF programs\n");
19245 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19246 !check_attach_modify_return(addr, tname))
19250 bpf_log(log, "%s() is not modifiable\n", tname);
19257 tgt_info->tgt_addr = addr;
19258 tgt_info->tgt_name = tname;
19259 tgt_info->tgt_type = t;
19260 tgt_info->tgt_mod = mod;
19264 BTF_SET_START(btf_id_deny)
19267 BTF_ID(func, migrate_disable)
19268 BTF_ID(func, migrate_enable)
19270 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19271 BTF_ID(func, rcu_read_unlock_strict)
19273 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19274 BTF_ID(func, preempt_count_add)
19275 BTF_ID(func, preempt_count_sub)
19277 #ifdef CONFIG_PREEMPT_RCU
19278 BTF_ID(func, __rcu_read_lock)
19279 BTF_ID(func, __rcu_read_unlock)
19281 BTF_SET_END(btf_id_deny)
19283 static bool can_be_sleepable(struct bpf_prog *prog)
19285 if (prog->type == BPF_PROG_TYPE_TRACING) {
19286 switch (prog->expected_attach_type) {
19287 case BPF_TRACE_FENTRY:
19288 case BPF_TRACE_FEXIT:
19289 case BPF_MODIFY_RETURN:
19290 case BPF_TRACE_ITER:
19296 return prog->type == BPF_PROG_TYPE_LSM ||
19297 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19298 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19301 static int check_attach_btf_id(struct bpf_verifier_env *env)
19303 struct bpf_prog *prog = env->prog;
19304 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19305 struct bpf_attach_target_info tgt_info = {};
19306 u32 btf_id = prog->aux->attach_btf_id;
19307 struct bpf_trampoline *tr;
19311 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19312 if (prog->aux->sleepable)
19313 /* attach_btf_id checked to be zero already */
19315 verbose(env, "Syscall programs can only be sleepable\n");
19319 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19320 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19324 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19325 return check_struct_ops_btf_id(env);
19327 if (prog->type != BPF_PROG_TYPE_TRACING &&
19328 prog->type != BPF_PROG_TYPE_LSM &&
19329 prog->type != BPF_PROG_TYPE_EXT)
19332 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19336 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19337 /* to make freplace equivalent to their targets, they need to
19338 * inherit env->ops and expected_attach_type for the rest of the
19341 env->ops = bpf_verifier_ops[tgt_prog->type];
19342 prog->expected_attach_type = tgt_prog->expected_attach_type;
19345 /* store info about the attachment target that will be used later */
19346 prog->aux->attach_func_proto = tgt_info.tgt_type;
19347 prog->aux->attach_func_name = tgt_info.tgt_name;
19348 prog->aux->mod = tgt_info.tgt_mod;
19351 prog->aux->saved_dst_prog_type = tgt_prog->type;
19352 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19355 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19356 prog->aux->attach_btf_trace = true;
19358 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19359 if (!bpf_iter_prog_supported(prog))
19364 if (prog->type == BPF_PROG_TYPE_LSM) {
19365 ret = bpf_lsm_verify_prog(&env->log, prog);
19368 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
19369 btf_id_set_contains(&btf_id_deny, btf_id)) {
19373 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19374 tr = bpf_trampoline_get(key, &tgt_info);
19378 prog->aux->dst_trampoline = tr;
19382 struct btf *bpf_get_btf_vmlinux(void)
19384 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19385 mutex_lock(&bpf_verifier_lock);
19387 btf_vmlinux = btf_parse_vmlinux();
19388 mutex_unlock(&bpf_verifier_lock);
19390 return btf_vmlinux;
19393 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19395 u64 start_time = ktime_get_ns();
19396 struct bpf_verifier_env *env;
19397 int i, len, ret = -EINVAL, err;
19401 /* no program is valid */
19402 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19405 /* 'struct bpf_verifier_env' can be global, but since it's not small,
19406 * allocate/free it every time bpf_check() is called
19408 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19414 len = (*prog)->len;
19415 env->insn_aux_data =
19416 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19418 if (!env->insn_aux_data)
19420 for (i = 0; i < len; i++)
19421 env->insn_aux_data[i].orig_idx = i;
19423 env->ops = bpf_verifier_ops[env->prog->type];
19424 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19425 is_priv = bpf_capable();
19427 bpf_get_btf_vmlinux();
19429 /* grab the mutex to protect few globals used by verifier */
19431 mutex_lock(&bpf_verifier_lock);
19433 /* user could have requested verbose verifier output
19434 * and supplied buffer to store the verification trace
19436 ret = bpf_vlog_init(&env->log, attr->log_level,
19437 (char __user *) (unsigned long) attr->log_buf,
19442 mark_verifier_state_clean(env);
19444 if (IS_ERR(btf_vmlinux)) {
19445 /* Either gcc or pahole or kernel are broken. */
19446 verbose(env, "in-kernel BTF is malformed\n");
19447 ret = PTR_ERR(btf_vmlinux);
19448 goto skip_full_check;
19451 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19452 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19453 env->strict_alignment = true;
19454 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19455 env->strict_alignment = false;
19457 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19458 env->allow_uninit_stack = bpf_allow_uninit_stack();
19459 env->bypass_spec_v1 = bpf_bypass_spec_v1();
19460 env->bypass_spec_v4 = bpf_bypass_spec_v4();
19461 env->bpf_capable = bpf_capable();
19464 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19466 env->explored_states = kvcalloc(state_htab_size(env),
19467 sizeof(struct bpf_verifier_state_list *),
19470 if (!env->explored_states)
19471 goto skip_full_check;
19473 ret = add_subprog_and_kfunc(env);
19475 goto skip_full_check;
19477 ret = check_subprogs(env);
19479 goto skip_full_check;
19481 ret = check_btf_info(env, attr, uattr);
19483 goto skip_full_check;
19485 ret = check_attach_btf_id(env);
19487 goto skip_full_check;
19489 ret = resolve_pseudo_ldimm64(env);
19491 goto skip_full_check;
19493 if (bpf_prog_is_offloaded(env->prog->aux)) {
19494 ret = bpf_prog_offload_verifier_prep(env->prog);
19496 goto skip_full_check;
19499 ret = check_cfg(env);
19501 goto skip_full_check;
19503 ret = do_check_subprogs(env);
19504 ret = ret ?: do_check_main(env);
19506 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19507 ret = bpf_prog_offload_finalize(env);
19510 kvfree(env->explored_states);
19513 ret = check_max_stack_depth(env);
19515 /* instruction rewrites happen after this point */
19517 ret = optimize_bpf_loop(env);
19521 opt_hard_wire_dead_code_branches(env);
19523 ret = opt_remove_dead_code(env);
19525 ret = opt_remove_nops(env);
19528 sanitize_dead_code(env);
19532 /* program is valid, convert *(u32*)(ctx + off) accesses */
19533 ret = convert_ctx_accesses(env);
19536 ret = do_misc_fixups(env);
19538 /* do 32-bit optimization after insn patching has done so those patched
19539 * insns could be handled correctly.
19541 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19542 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19543 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19548 ret = fixup_call_args(env);
19550 env->verification_time = ktime_get_ns() - start_time;
19551 print_verification_stats(env);
19552 env->prog->aux->verified_insns = env->insn_processed;
19554 /* preserve original error even if log finalization is successful */
19555 err = bpf_vlog_finalize(&env->log, &log_true_size);
19559 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19560 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19561 &log_true_size, sizeof(log_true_size))) {
19563 goto err_release_maps;
19567 goto err_release_maps;
19569 if (env->used_map_cnt) {
19570 /* if program passed verifier, update used_maps in bpf_prog_info */
19571 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19572 sizeof(env->used_maps[0]),
19575 if (!env->prog->aux->used_maps) {
19577 goto err_release_maps;
19580 memcpy(env->prog->aux->used_maps, env->used_maps,
19581 sizeof(env->used_maps[0]) * env->used_map_cnt);
19582 env->prog->aux->used_map_cnt = env->used_map_cnt;
19584 if (env->used_btf_cnt) {
19585 /* if program passed verifier, update used_btfs in bpf_prog_aux */
19586 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19587 sizeof(env->used_btfs[0]),
19589 if (!env->prog->aux->used_btfs) {
19591 goto err_release_maps;
19594 memcpy(env->prog->aux->used_btfs, env->used_btfs,
19595 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19596 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19598 if (env->used_map_cnt || env->used_btf_cnt) {
19599 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
19600 * bpf_ld_imm64 instructions
19602 convert_pseudo_ld_imm64(env);
19605 adjust_btf_func(env);
19608 if (!env->prog->aux->used_maps)
19609 /* if we didn't copy map pointers into bpf_prog_info, release
19610 * them now. Otherwise free_used_maps() will release them.
19613 if (!env->prog->aux->used_btfs)
19616 /* extension progs temporarily inherit the attach_type of their targets
19617 for verification purposes, so set it back to zero before returning
19619 if (env->prog->type == BPF_PROG_TYPE_EXT)
19620 env->prog->expected_attach_type = 0;
19625 mutex_unlock(&bpf_verifier_lock);
19626 vfree(env->insn_aux_data);