1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3 * Copyright (c) 2016 Facebook
4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
32 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
33 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
34 [_id] = & _name ## _verifier_ops,
35 #define BPF_MAP_TYPE(_id, _ops)
36 #define BPF_LINK_TYPE(_id, _name)
37 #include <linux/bpf_types.h>
43 /* bpf_check() is a static code analyzer that walks eBPF program
44 * instruction by instruction and updates register/stack state.
45 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
47 * The first pass is depth-first-search to check that the program is a DAG.
48 * It rejects the following programs:
49 * - larger than BPF_MAXINSNS insns
50 * - if loop is present (detected via back-edge)
51 * - unreachable insns exist (shouldn't be a forest. program = one function)
52 * - out of bounds or malformed jumps
53 * The second pass is all possible path descent from the 1st insn.
54 * Since it's analyzing all paths through the program, the length of the
55 * analysis is limited to 64k insn, which may be hit even if total number of
56 * insn is less then 4K, but there are too many branches that change stack/regs.
57 * Number of 'branches to be analyzed' is limited to 1k
59 * On entry to each instruction, each register has a type, and the instruction
60 * changes the types of the registers depending on instruction semantics.
61 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
64 * All registers are 64-bit.
65 * R0 - return register
66 * R1-R5 argument passing registers
67 * R6-R9 callee saved registers
68 * R10 - frame pointer read-only
70 * At the start of BPF program the register R1 contains a pointer to bpf_context
71 * and has type PTR_TO_CTX.
73 * Verifier tracks arithmetic operations on pointers in case:
74 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
75 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
76 * 1st insn copies R10 (which has FRAME_PTR) type into R1
77 * and 2nd arithmetic instruction is pattern matched to recognize
78 * that it wants to construct a pointer to some element within stack.
79 * So after 2nd insn, the register R1 has type PTR_TO_STACK
80 * (and -20 constant is saved for further stack bounds checking).
81 * Meaning that this reg is a pointer to stack plus known immediate constant.
83 * Most of the time the registers have SCALAR_VALUE type, which
84 * means the register has some value, but it's not a valid pointer.
85 * (like pointer plus pointer becomes SCALAR_VALUE type)
87 * When verifier sees load or store instructions the type of base register
88 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
89 * four pointer types recognized by check_mem_access() function.
91 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
92 * and the range of [ptr, ptr + map's value_size) is accessible.
94 * registers used to pass values to function calls are checked against
95 * function argument constraints.
97 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
98 * It means that the register type passed to this function must be
99 * PTR_TO_STACK and it will be used inside the function as
100 * 'pointer to map element key'
102 * For example the argument constraints for bpf_map_lookup_elem():
103 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
104 * .arg1_type = ARG_CONST_MAP_PTR,
105 * .arg2_type = ARG_PTR_TO_MAP_KEY,
107 * ret_type says that this function returns 'pointer to map elem value or null'
108 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
109 * 2nd argument should be a pointer to stack, which will be used inside
110 * the helper function as a pointer to map element key.
112 * On the kernel side the helper function looks like:
113 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
115 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
116 * void *key = (void *) (unsigned long) r2;
119 * here kernel can access 'key' and 'map' pointers safely, knowing that
120 * [key, key + map->key_size) bytes are valid and were initialized on
121 * the stack of eBPF program.
124 * Corresponding eBPF program may look like:
125 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
126 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
127 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
128 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
129 * here verifier looks at prototype of map_lookup_elem() and sees:
130 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
131 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
133 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
134 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
135 * and were initialized prior to this call.
136 * If it's ok, then verifier allows this BPF_CALL insn and looks at
137 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
138 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
139 * returns either pointer to map value or NULL.
141 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
142 * insn, the register holding that pointer in the true branch changes state to
143 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
144 * branch. See check_cond_jmp_op().
146 * After the call R0 is set to return type of the function and registers R1-R5
147 * are set to NOT_INIT to indicate that they are no longer readable.
149 * The following reference types represent a potential reference to a kernel
150 * resource which, after first being allocated, must be checked and freed by
152 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
154 * When the verifier sees a helper call return a reference type, it allocates a
155 * pointer id for the reference and stores it in the current function state.
156 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
157 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
158 * passes through a NULL-check conditional. For the branch wherein the state is
159 * changed to CONST_IMM, the verifier releases the reference.
161 * For each helper function that allocates a reference, such as
162 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
163 * bpf_sk_release(). When a reference type passes into the release function,
164 * the verifier also releases the reference. If any unchecked or unreleased
165 * reference remains at the end of the program, the verifier rejects it.
168 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
169 struct bpf_verifier_stack_elem {
170 /* verifer state is 'st'
171 * before processing instruction 'insn_idx'
172 * and after processing instruction 'prev_insn_idx'
174 struct bpf_verifier_state st;
177 struct bpf_verifier_stack_elem *next;
178 /* length of verifier log at the time this state was pushed on stack */
182 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
183 #define BPF_COMPLEXITY_LIMIT_STATES 64
185 #define BPF_MAP_KEY_POISON (1ULL << 63)
186 #define BPF_MAP_KEY_SEEN (1ULL << 62)
188 #define BPF_MAP_PTR_UNPRIV 1UL
189 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
190 POISON_POINTER_DELTA))
191 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
193 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
194 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
195 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
196 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
197 static int ref_set_non_owning(struct bpf_verifier_env *env,
198 struct bpf_reg_state *reg);
199 static void specialize_kfunc(struct bpf_verifier_env *env,
200 u32 func_id, u16 offset, unsigned long *addr);
201 static bool is_trusted_reg(const struct bpf_reg_state *reg);
203 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
205 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
208 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
210 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
213 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
214 const struct bpf_map *map, bool unpriv)
216 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
217 unpriv |= bpf_map_ptr_unpriv(aux);
218 aux->map_ptr_state = (unsigned long)map |
219 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
222 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
224 return aux->map_key_state & BPF_MAP_KEY_POISON;
227 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
229 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
232 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
234 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
237 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
239 bool poisoned = bpf_map_key_poisoned(aux);
241 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
242 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
245 static bool bpf_helper_call(const struct bpf_insn *insn)
247 return insn->code == (BPF_JMP | BPF_CALL) &&
251 static bool bpf_pseudo_call(const struct bpf_insn *insn)
253 return insn->code == (BPF_JMP | BPF_CALL) &&
254 insn->src_reg == BPF_PSEUDO_CALL;
257 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
259 return insn->code == (BPF_JMP | BPF_CALL) &&
260 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
263 struct bpf_call_arg_meta {
264 struct bpf_map *map_ptr;
281 struct btf_field *kptr_field;
284 struct bpf_kfunc_call_arg_meta {
289 const struct btf_type *func_proto;
290 const char *func_name;
303 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
304 * generally to pass info about user-defined local kptr types to later
307 * Record the local kptr type to be drop'd
308 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
309 * Record the local kptr type to be refcount_incr'd and use
310 * arg_owning_ref to determine whether refcount_acquire should be
318 struct btf_field *field;
321 struct btf_field *field;
324 enum bpf_dynptr_type type;
327 } initialized_dynptr;
335 struct btf *btf_vmlinux;
337 static DEFINE_MUTEX(bpf_verifier_lock);
339 static const struct bpf_line_info *
340 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
342 const struct bpf_line_info *linfo;
343 const struct bpf_prog *prog;
347 nr_linfo = prog->aux->nr_linfo;
349 if (!nr_linfo || insn_off >= prog->len)
352 linfo = prog->aux->linfo;
353 for (i = 1; i < nr_linfo; i++)
354 if (insn_off < linfo[i].insn_off)
357 return &linfo[i - 1];
360 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
362 struct bpf_verifier_env *env = private_data;
365 if (!bpf_verifier_log_needed(&env->log))
369 bpf_verifier_vlog(&env->log, fmt, args);
373 static const char *ltrim(const char *s)
381 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
383 const char *prefix_fmt, ...)
385 const struct bpf_line_info *linfo;
387 if (!bpf_verifier_log_needed(&env->log))
390 linfo = find_linfo(env, insn_off);
391 if (!linfo || linfo == env->prev_linfo)
397 va_start(args, prefix_fmt);
398 bpf_verifier_vlog(&env->log, prefix_fmt, args);
403 ltrim(btf_name_by_offset(env->prog->aux->btf,
406 env->prev_linfo = linfo;
409 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
410 struct bpf_reg_state *reg,
411 struct tnum *range, const char *ctx,
412 const char *reg_name)
416 verbose(env, "At %s the register %s ", ctx, reg_name);
417 if (!tnum_is_unknown(reg->var_off)) {
418 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
419 verbose(env, "has value %s", tn_buf);
421 verbose(env, "has unknown scalar value");
423 tnum_strn(tn_buf, sizeof(tn_buf), *range);
424 verbose(env, " should have been in %s\n", tn_buf);
427 static bool type_is_pkt_pointer(enum bpf_reg_type type)
429 type = base_type(type);
430 return type == PTR_TO_PACKET ||
431 type == PTR_TO_PACKET_META;
434 static bool type_is_sk_pointer(enum bpf_reg_type type)
436 return type == PTR_TO_SOCKET ||
437 type == PTR_TO_SOCK_COMMON ||
438 type == PTR_TO_TCP_SOCK ||
439 type == PTR_TO_XDP_SOCK;
442 static bool type_may_be_null(u32 type)
444 return type & PTR_MAYBE_NULL;
447 static bool reg_not_null(const struct bpf_reg_state *reg)
449 enum bpf_reg_type type;
452 if (type_may_be_null(type))
455 type = base_type(type);
456 return type == PTR_TO_SOCKET ||
457 type == PTR_TO_TCP_SOCK ||
458 type == PTR_TO_MAP_VALUE ||
459 type == PTR_TO_MAP_KEY ||
460 type == PTR_TO_SOCK_COMMON ||
461 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
465 static bool type_is_ptr_alloc_obj(u32 type)
467 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
470 static bool type_is_non_owning_ref(u32 type)
472 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
475 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
477 struct btf_record *rec = NULL;
478 struct btf_struct_meta *meta;
480 if (reg->type == PTR_TO_MAP_VALUE) {
481 rec = reg->map_ptr->record;
482 } else if (type_is_ptr_alloc_obj(reg->type)) {
483 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
490 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
492 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
494 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
497 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
499 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
502 static bool type_is_rdonly_mem(u32 type)
504 return type & MEM_RDONLY;
507 static bool is_acquire_function(enum bpf_func_id func_id,
508 const struct bpf_map *map)
510 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
512 if (func_id == BPF_FUNC_sk_lookup_tcp ||
513 func_id == BPF_FUNC_sk_lookup_udp ||
514 func_id == BPF_FUNC_skc_lookup_tcp ||
515 func_id == BPF_FUNC_ringbuf_reserve ||
516 func_id == BPF_FUNC_kptr_xchg)
519 if (func_id == BPF_FUNC_map_lookup_elem &&
520 (map_type == BPF_MAP_TYPE_SOCKMAP ||
521 map_type == BPF_MAP_TYPE_SOCKHASH))
527 static bool is_ptr_cast_function(enum bpf_func_id func_id)
529 return func_id == BPF_FUNC_tcp_sock ||
530 func_id == BPF_FUNC_sk_fullsock ||
531 func_id == BPF_FUNC_skc_to_tcp_sock ||
532 func_id == BPF_FUNC_skc_to_tcp6_sock ||
533 func_id == BPF_FUNC_skc_to_udp6_sock ||
534 func_id == BPF_FUNC_skc_to_mptcp_sock ||
535 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
536 func_id == BPF_FUNC_skc_to_tcp_request_sock;
539 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
541 return func_id == BPF_FUNC_dynptr_data;
544 static bool is_callback_calling_kfunc(u32 btf_id);
546 static bool is_callback_calling_function(enum bpf_func_id func_id)
548 return func_id == BPF_FUNC_for_each_map_elem ||
549 func_id == BPF_FUNC_timer_set_callback ||
550 func_id == BPF_FUNC_find_vma ||
551 func_id == BPF_FUNC_loop ||
552 func_id == BPF_FUNC_user_ringbuf_drain;
555 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
557 return func_id == BPF_FUNC_timer_set_callback;
560 static bool is_storage_get_function(enum bpf_func_id func_id)
562 return func_id == BPF_FUNC_sk_storage_get ||
563 func_id == BPF_FUNC_inode_storage_get ||
564 func_id == BPF_FUNC_task_storage_get ||
565 func_id == BPF_FUNC_cgrp_storage_get;
568 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
569 const struct bpf_map *map)
571 int ref_obj_uses = 0;
573 if (is_ptr_cast_function(func_id))
575 if (is_acquire_function(func_id, map))
577 if (is_dynptr_ref_function(func_id))
580 return ref_obj_uses > 1;
583 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
585 return BPF_CLASS(insn->code) == BPF_STX &&
586 BPF_MODE(insn->code) == BPF_ATOMIC &&
587 insn->imm == BPF_CMPXCHG;
590 /* string representation of 'enum bpf_reg_type'
592 * Note that reg_type_str() can not appear more than once in a single verbose()
595 static const char *reg_type_str(struct bpf_verifier_env *env,
596 enum bpf_reg_type type)
598 char postfix[16] = {0}, prefix[64] = {0};
599 static const char * const str[] = {
601 [SCALAR_VALUE] = "scalar",
602 [PTR_TO_CTX] = "ctx",
603 [CONST_PTR_TO_MAP] = "map_ptr",
604 [PTR_TO_MAP_VALUE] = "map_value",
605 [PTR_TO_STACK] = "fp",
606 [PTR_TO_PACKET] = "pkt",
607 [PTR_TO_PACKET_META] = "pkt_meta",
608 [PTR_TO_PACKET_END] = "pkt_end",
609 [PTR_TO_FLOW_KEYS] = "flow_keys",
610 [PTR_TO_SOCKET] = "sock",
611 [PTR_TO_SOCK_COMMON] = "sock_common",
612 [PTR_TO_TCP_SOCK] = "tcp_sock",
613 [PTR_TO_TP_BUFFER] = "tp_buffer",
614 [PTR_TO_XDP_SOCK] = "xdp_sock",
615 [PTR_TO_BTF_ID] = "ptr_",
616 [PTR_TO_MEM] = "mem",
617 [PTR_TO_BUF] = "buf",
618 [PTR_TO_FUNC] = "func",
619 [PTR_TO_MAP_KEY] = "map_key",
620 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr",
623 if (type & PTR_MAYBE_NULL) {
624 if (base_type(type) == PTR_TO_BTF_ID)
625 strncpy(postfix, "or_null_", 16);
627 strncpy(postfix, "_or_null", 16);
630 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
631 type & MEM_RDONLY ? "rdonly_" : "",
632 type & MEM_RINGBUF ? "ringbuf_" : "",
633 type & MEM_USER ? "user_" : "",
634 type & MEM_PERCPU ? "percpu_" : "",
635 type & MEM_RCU ? "rcu_" : "",
636 type & PTR_UNTRUSTED ? "untrusted_" : "",
637 type & PTR_TRUSTED ? "trusted_" : ""
640 snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
641 prefix, str[base_type(type)], postfix);
642 return env->tmp_str_buf;
645 static char slot_type_char[] = {
646 [STACK_INVALID] = '?',
650 [STACK_DYNPTR] = 'd',
654 static void print_liveness(struct bpf_verifier_env *env,
655 enum bpf_reg_liveness live)
657 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
659 if (live & REG_LIVE_READ)
661 if (live & REG_LIVE_WRITTEN)
663 if (live & REG_LIVE_DONE)
667 static int __get_spi(s32 off)
669 return (-off - 1) / BPF_REG_SIZE;
672 static struct bpf_func_state *func(struct bpf_verifier_env *env,
673 const struct bpf_reg_state *reg)
675 struct bpf_verifier_state *cur = env->cur_state;
677 return cur->frame[reg->frameno];
680 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
682 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
684 /* We need to check that slots between [spi - nr_slots + 1, spi] are
685 * within [0, allocated_stack).
687 * Please note that the spi grows downwards. For example, a dynptr
688 * takes the size of two stack slots; the first slot will be at
689 * spi and the second slot will be at spi - 1.
691 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
694 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
695 const char *obj_kind, int nr_slots)
699 if (!tnum_is_const(reg->var_off)) {
700 verbose(env, "%s has to be at a constant offset\n", obj_kind);
704 off = reg->off + reg->var_off.value;
705 if (off % BPF_REG_SIZE) {
706 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
710 spi = __get_spi(off);
711 if (spi + 1 < nr_slots) {
712 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
716 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
721 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
723 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
726 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
728 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
731 static const char *btf_type_name(const struct btf *btf, u32 id)
733 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
736 static const char *dynptr_type_str(enum bpf_dynptr_type type)
739 case BPF_DYNPTR_TYPE_LOCAL:
741 case BPF_DYNPTR_TYPE_RINGBUF:
743 case BPF_DYNPTR_TYPE_SKB:
745 case BPF_DYNPTR_TYPE_XDP:
747 case BPF_DYNPTR_TYPE_INVALID:
750 WARN_ONCE(1, "unknown dynptr type %d\n", type);
755 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
757 if (!btf || btf_id == 0)
760 /* we already validated that type is valid and has conforming name */
761 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
764 static const char *iter_state_str(enum bpf_iter_state state)
767 case BPF_ITER_STATE_ACTIVE:
769 case BPF_ITER_STATE_DRAINED:
771 case BPF_ITER_STATE_INVALID:
774 WARN_ONCE(1, "unknown iter state %d\n", state);
779 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
781 env->scratched_regs |= 1U << regno;
784 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
786 env->scratched_stack_slots |= 1ULL << spi;
789 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
791 return (env->scratched_regs >> regno) & 1;
794 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
796 return (env->scratched_stack_slots >> regno) & 1;
799 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
801 return env->scratched_regs || env->scratched_stack_slots;
804 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
806 env->scratched_regs = 0U;
807 env->scratched_stack_slots = 0ULL;
810 /* Used for printing the entire verifier state. */
811 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
813 env->scratched_regs = ~0U;
814 env->scratched_stack_slots = ~0ULL;
817 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
819 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
820 case DYNPTR_TYPE_LOCAL:
821 return BPF_DYNPTR_TYPE_LOCAL;
822 case DYNPTR_TYPE_RINGBUF:
823 return BPF_DYNPTR_TYPE_RINGBUF;
824 case DYNPTR_TYPE_SKB:
825 return BPF_DYNPTR_TYPE_SKB;
826 case DYNPTR_TYPE_XDP:
827 return BPF_DYNPTR_TYPE_XDP;
829 return BPF_DYNPTR_TYPE_INVALID;
833 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
836 case BPF_DYNPTR_TYPE_LOCAL:
837 return DYNPTR_TYPE_LOCAL;
838 case BPF_DYNPTR_TYPE_RINGBUF:
839 return DYNPTR_TYPE_RINGBUF;
840 case BPF_DYNPTR_TYPE_SKB:
841 return DYNPTR_TYPE_SKB;
842 case BPF_DYNPTR_TYPE_XDP:
843 return DYNPTR_TYPE_XDP;
849 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
851 return type == BPF_DYNPTR_TYPE_RINGBUF;
854 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
855 enum bpf_dynptr_type type,
856 bool first_slot, int dynptr_id);
858 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
859 struct bpf_reg_state *reg);
861 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
862 struct bpf_reg_state *sreg1,
863 struct bpf_reg_state *sreg2,
864 enum bpf_dynptr_type type)
866 int id = ++env->id_gen;
868 __mark_dynptr_reg(sreg1, type, true, id);
869 __mark_dynptr_reg(sreg2, type, false, id);
872 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
873 struct bpf_reg_state *reg,
874 enum bpf_dynptr_type type)
876 __mark_dynptr_reg(reg, type, true, ++env->id_gen);
879 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
880 struct bpf_func_state *state, int spi);
882 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
883 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
885 struct bpf_func_state *state = func(env, reg);
886 enum bpf_dynptr_type type;
889 spi = dynptr_get_spi(env, reg);
893 /* We cannot assume both spi and spi - 1 belong to the same dynptr,
894 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
895 * to ensure that for the following example:
898 * So marking spi = 2 should lead to destruction of both d1 and d2. In
899 * case they do belong to same dynptr, second call won't see slot_type
900 * as STACK_DYNPTR and will simply skip destruction.
902 err = destroy_if_dynptr_stack_slot(env, state, spi);
905 err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
909 for (i = 0; i < BPF_REG_SIZE; i++) {
910 state->stack[spi].slot_type[i] = STACK_DYNPTR;
911 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
914 type = arg_to_dynptr_type(arg_type);
915 if (type == BPF_DYNPTR_TYPE_INVALID)
918 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
919 &state->stack[spi - 1].spilled_ptr, type);
921 if (dynptr_type_refcounted(type)) {
922 /* The id is used to track proper releasing */
925 if (clone_ref_obj_id)
926 id = clone_ref_obj_id;
928 id = acquire_reference_state(env, insn_idx);
933 state->stack[spi].spilled_ptr.ref_obj_id = id;
934 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
937 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
938 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
943 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
947 for (i = 0; i < BPF_REG_SIZE; i++) {
948 state->stack[spi].slot_type[i] = STACK_INVALID;
949 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
952 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
953 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
955 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
957 * While we don't allow reading STACK_INVALID, it is still possible to
958 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
959 * helpers or insns can do partial read of that part without failing,
960 * but check_stack_range_initialized, check_stack_read_var_off, and
961 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
962 * the slot conservatively. Hence we need to prevent those liveness
965 * This was not a problem before because STACK_INVALID is only set by
966 * default (where the default reg state has its reg->parent as NULL), or
967 * in clean_live_states after REG_LIVE_DONE (at which point
968 * mark_reg_read won't walk reg->parent chain), but not randomly during
969 * verifier state exploration (like we did above). Hence, for our case
970 * parentage chain will still be live (i.e. reg->parent may be
971 * non-NULL), while earlier reg->parent was NULL, so we need
972 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
973 * done later on reads or by mark_dynptr_read as well to unnecessary
974 * mark registers in verifier state.
976 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
977 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
980 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
982 struct bpf_func_state *state = func(env, reg);
983 int spi, ref_obj_id, i;
985 spi = dynptr_get_spi(env, reg);
989 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
990 invalidate_dynptr(env, state, spi);
994 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
996 /* If the dynptr has a ref_obj_id, then we need to invalidate
999 * 1) Any dynptrs with a matching ref_obj_id (clones)
1000 * 2) Any slices derived from this dynptr.
1003 /* Invalidate any slices associated with this dynptr */
1004 WARN_ON_ONCE(release_reference(env, ref_obj_id));
1006 /* Invalidate any dynptr clones */
1007 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1008 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1011 /* it should always be the case that if the ref obj id
1012 * matches then the stack slot also belongs to a
1015 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1016 verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1019 if (state->stack[i].spilled_ptr.dynptr.first_slot)
1020 invalidate_dynptr(env, state, i);
1026 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1027 struct bpf_reg_state *reg);
1029 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1031 if (!env->allow_ptr_leaks)
1032 __mark_reg_not_init(env, reg);
1034 __mark_reg_unknown(env, reg);
1037 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1038 struct bpf_func_state *state, int spi)
1040 struct bpf_func_state *fstate;
1041 struct bpf_reg_state *dreg;
1044 /* We always ensure that STACK_DYNPTR is never set partially,
1045 * hence just checking for slot_type[0] is enough. This is
1046 * different for STACK_SPILL, where it may be only set for
1047 * 1 byte, so code has to use is_spilled_reg.
1049 if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1052 /* Reposition spi to first slot */
1053 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1056 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1057 verbose(env, "cannot overwrite referenced dynptr\n");
1061 mark_stack_slot_scratched(env, spi);
1062 mark_stack_slot_scratched(env, spi - 1);
1064 /* Writing partially to one dynptr stack slot destroys both. */
1065 for (i = 0; i < BPF_REG_SIZE; i++) {
1066 state->stack[spi].slot_type[i] = STACK_INVALID;
1067 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1070 dynptr_id = state->stack[spi].spilled_ptr.id;
1071 /* Invalidate any slices associated with this dynptr */
1072 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1073 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1074 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1076 if (dreg->dynptr_id == dynptr_id)
1077 mark_reg_invalid(env, dreg);
1080 /* Do not release reference state, we are destroying dynptr on stack,
1081 * not using some helper to release it. Just reset register.
1083 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1084 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1086 /* Same reason as unmark_stack_slots_dynptr above */
1087 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1088 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1093 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1097 if (reg->type == CONST_PTR_TO_DYNPTR)
1100 spi = dynptr_get_spi(env, reg);
1102 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1103 * error because this just means the stack state hasn't been updated yet.
1104 * We will do check_mem_access to check and update stack bounds later.
1106 if (spi < 0 && spi != -ERANGE)
1109 /* We don't need to check if the stack slots are marked by previous
1110 * dynptr initializations because we allow overwriting existing unreferenced
1111 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1112 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1113 * touching are completely destructed before we reinitialize them for a new
1114 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1115 * instead of delaying it until the end where the user will get "Unreleased
1121 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1123 struct bpf_func_state *state = func(env, reg);
1126 /* This already represents first slot of initialized bpf_dynptr.
1128 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1129 * check_func_arg_reg_off's logic, so we don't need to check its
1130 * offset and alignment.
1132 if (reg->type == CONST_PTR_TO_DYNPTR)
1135 spi = dynptr_get_spi(env, reg);
1138 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1141 for (i = 0; i < BPF_REG_SIZE; i++) {
1142 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1143 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1150 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1151 enum bpf_arg_type arg_type)
1153 struct bpf_func_state *state = func(env, reg);
1154 enum bpf_dynptr_type dynptr_type;
1157 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1158 if (arg_type == ARG_PTR_TO_DYNPTR)
1161 dynptr_type = arg_to_dynptr_type(arg_type);
1162 if (reg->type == CONST_PTR_TO_DYNPTR) {
1163 return reg->dynptr.type == dynptr_type;
1165 spi = dynptr_get_spi(env, reg);
1168 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1172 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1174 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1175 struct bpf_reg_state *reg, int insn_idx,
1176 struct btf *btf, u32 btf_id, int nr_slots)
1178 struct bpf_func_state *state = func(env, reg);
1181 spi = iter_get_spi(env, reg, nr_slots);
1185 id = acquire_reference_state(env, insn_idx);
1189 for (i = 0; i < nr_slots; i++) {
1190 struct bpf_stack_state *slot = &state->stack[spi - i];
1191 struct bpf_reg_state *st = &slot->spilled_ptr;
1193 __mark_reg_known_zero(st);
1194 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1195 st->live |= REG_LIVE_WRITTEN;
1196 st->ref_obj_id = i == 0 ? id : 0;
1198 st->iter.btf_id = btf_id;
1199 st->iter.state = BPF_ITER_STATE_ACTIVE;
1202 for (j = 0; j < BPF_REG_SIZE; j++)
1203 slot->slot_type[j] = STACK_ITER;
1205 mark_stack_slot_scratched(env, spi - i);
1211 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1212 struct bpf_reg_state *reg, int nr_slots)
1214 struct bpf_func_state *state = func(env, reg);
1217 spi = iter_get_spi(env, reg, nr_slots);
1221 for (i = 0; i < nr_slots; i++) {
1222 struct bpf_stack_state *slot = &state->stack[spi - i];
1223 struct bpf_reg_state *st = &slot->spilled_ptr;
1226 WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1228 __mark_reg_not_init(env, st);
1230 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1231 st->live |= REG_LIVE_WRITTEN;
1233 for (j = 0; j < BPF_REG_SIZE; j++)
1234 slot->slot_type[j] = STACK_INVALID;
1236 mark_stack_slot_scratched(env, spi - i);
1242 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1243 struct bpf_reg_state *reg, int nr_slots)
1245 struct bpf_func_state *state = func(env, reg);
1248 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1249 * will do check_mem_access to check and update stack bounds later, so
1250 * return true for that case.
1252 spi = iter_get_spi(env, reg, nr_slots);
1258 for (i = 0; i < nr_slots; i++) {
1259 struct bpf_stack_state *slot = &state->stack[spi - i];
1261 for (j = 0; j < BPF_REG_SIZE; j++)
1262 if (slot->slot_type[j] == STACK_ITER)
1269 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1270 struct btf *btf, u32 btf_id, int nr_slots)
1272 struct bpf_func_state *state = func(env, reg);
1275 spi = iter_get_spi(env, reg, nr_slots);
1279 for (i = 0; i < nr_slots; i++) {
1280 struct bpf_stack_state *slot = &state->stack[spi - i];
1281 struct bpf_reg_state *st = &slot->spilled_ptr;
1283 /* only main (first) slot has ref_obj_id set */
1284 if (i == 0 && !st->ref_obj_id)
1286 if (i != 0 && st->ref_obj_id)
1288 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1291 for (j = 0; j < BPF_REG_SIZE; j++)
1292 if (slot->slot_type[j] != STACK_ITER)
1299 /* Check if given stack slot is "special":
1300 * - spilled register state (STACK_SPILL);
1301 * - dynptr state (STACK_DYNPTR);
1302 * - iter state (STACK_ITER).
1304 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1306 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1318 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1323 /* The reg state of a pointer or a bounded scalar was saved when
1324 * it was spilled to the stack.
1326 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1328 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1331 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1333 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1334 stack->spilled_ptr.type == SCALAR_VALUE;
1337 static void scrub_spilled_slot(u8 *stype)
1339 if (*stype != STACK_INVALID)
1340 *stype = STACK_MISC;
1343 static void print_verifier_state(struct bpf_verifier_env *env,
1344 const struct bpf_func_state *state,
1347 const struct bpf_reg_state *reg;
1348 enum bpf_reg_type t;
1352 verbose(env, " frame%d:", state->frameno);
1353 for (i = 0; i < MAX_BPF_REG; i++) {
1354 reg = &state->regs[i];
1358 if (!print_all && !reg_scratched(env, i))
1360 verbose(env, " R%d", i);
1361 print_liveness(env, reg->live);
1363 if (t == SCALAR_VALUE && reg->precise)
1365 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1366 tnum_is_const(reg->var_off)) {
1367 /* reg->off should be 0 for SCALAR_VALUE */
1368 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1369 verbose(env, "%lld", reg->var_off.value + reg->off);
1371 const char *sep = "";
1373 verbose(env, "%s", reg_type_str(env, t));
1374 if (base_type(t) == PTR_TO_BTF_ID)
1375 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1378 * _a stands for append, was shortened to avoid multiline statements below.
1379 * This macro is used to output a comma separated list of attributes.
1381 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1384 verbose_a("id=%d", reg->id);
1385 if (reg->ref_obj_id)
1386 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1387 if (type_is_non_owning_ref(reg->type))
1388 verbose_a("%s", "non_own_ref");
1389 if (t != SCALAR_VALUE)
1390 verbose_a("off=%d", reg->off);
1391 if (type_is_pkt_pointer(t))
1392 verbose_a("r=%d", reg->range);
1393 else if (base_type(t) == CONST_PTR_TO_MAP ||
1394 base_type(t) == PTR_TO_MAP_KEY ||
1395 base_type(t) == PTR_TO_MAP_VALUE)
1396 verbose_a("ks=%d,vs=%d",
1397 reg->map_ptr->key_size,
1398 reg->map_ptr->value_size);
1399 if (tnum_is_const(reg->var_off)) {
1400 /* Typically an immediate SCALAR_VALUE, but
1401 * could be a pointer whose offset is too big
1404 verbose_a("imm=%llx", reg->var_off.value);
1406 if (reg->smin_value != reg->umin_value &&
1407 reg->smin_value != S64_MIN)
1408 verbose_a("smin=%lld", (long long)reg->smin_value);
1409 if (reg->smax_value != reg->umax_value &&
1410 reg->smax_value != S64_MAX)
1411 verbose_a("smax=%lld", (long long)reg->smax_value);
1412 if (reg->umin_value != 0)
1413 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1414 if (reg->umax_value != U64_MAX)
1415 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1416 if (!tnum_is_unknown(reg->var_off)) {
1419 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1420 verbose_a("var_off=%s", tn_buf);
1422 if (reg->s32_min_value != reg->smin_value &&
1423 reg->s32_min_value != S32_MIN)
1424 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1425 if (reg->s32_max_value != reg->smax_value &&
1426 reg->s32_max_value != S32_MAX)
1427 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1428 if (reg->u32_min_value != reg->umin_value &&
1429 reg->u32_min_value != U32_MIN)
1430 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1431 if (reg->u32_max_value != reg->umax_value &&
1432 reg->u32_max_value != U32_MAX)
1433 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1440 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1441 char types_buf[BPF_REG_SIZE + 1];
1445 for (j = 0; j < BPF_REG_SIZE; j++) {
1446 if (state->stack[i].slot_type[j] != STACK_INVALID)
1448 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1450 types_buf[BPF_REG_SIZE] = 0;
1453 if (!print_all && !stack_slot_scratched(env, i))
1455 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1457 reg = &state->stack[i].spilled_ptr;
1460 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1461 print_liveness(env, reg->live);
1462 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1463 if (t == SCALAR_VALUE && reg->precise)
1465 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1466 verbose(env, "%lld", reg->var_off.value + reg->off);
1469 i += BPF_DYNPTR_NR_SLOTS - 1;
1470 reg = &state->stack[i].spilled_ptr;
1472 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1473 print_liveness(env, reg->live);
1474 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1475 if (reg->ref_obj_id)
1476 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1479 /* only main slot has ref_obj_id set; skip others */
1480 reg = &state->stack[i].spilled_ptr;
1481 if (!reg->ref_obj_id)
1484 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1485 print_liveness(env, reg->live);
1486 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1487 iter_type_str(reg->iter.btf, reg->iter.btf_id),
1488 reg->ref_obj_id, iter_state_str(reg->iter.state),
1494 reg = &state->stack[i].spilled_ptr;
1496 for (j = 0; j < BPF_REG_SIZE; j++)
1497 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1498 types_buf[BPF_REG_SIZE] = 0;
1500 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1501 print_liveness(env, reg->live);
1502 verbose(env, "=%s", types_buf);
1506 if (state->acquired_refs && state->refs[0].id) {
1507 verbose(env, " refs=%d", state->refs[0].id);
1508 for (i = 1; i < state->acquired_refs; i++)
1509 if (state->refs[i].id)
1510 verbose(env, ",%d", state->refs[i].id);
1512 if (state->in_callback_fn)
1513 verbose(env, " cb");
1514 if (state->in_async_callback_fn)
1515 verbose(env, " async_cb");
1517 mark_verifier_state_clean(env);
1520 static inline u32 vlog_alignment(u32 pos)
1522 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1523 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1526 static void print_insn_state(struct bpf_verifier_env *env,
1527 const struct bpf_func_state *state)
1529 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1530 /* remove new line character */
1531 bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1532 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1534 verbose(env, "%d:", env->insn_idx);
1536 print_verifier_state(env, state, false);
1539 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1540 * small to hold src. This is different from krealloc since we don't want to preserve
1541 * the contents of dst.
1543 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1546 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1552 if (ZERO_OR_NULL_PTR(src))
1555 if (unlikely(check_mul_overflow(n, size, &bytes)))
1558 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1559 dst = krealloc(orig, alloc_bytes, flags);
1565 memcpy(dst, src, bytes);
1567 return dst ? dst : ZERO_SIZE_PTR;
1570 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1571 * small to hold new_n items. new items are zeroed out if the array grows.
1573 * Contrary to krealloc_array, does not free arr if new_n is zero.
1575 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1580 if (!new_n || old_n == new_n)
1583 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1584 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1592 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1595 return arr ? arr : ZERO_SIZE_PTR;
1598 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1600 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1601 sizeof(struct bpf_reference_state), GFP_KERNEL);
1605 dst->acquired_refs = src->acquired_refs;
1609 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1611 size_t n = src->allocated_stack / BPF_REG_SIZE;
1613 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1618 dst->allocated_stack = src->allocated_stack;
1622 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1624 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1625 sizeof(struct bpf_reference_state));
1629 state->acquired_refs = n;
1633 static int grow_stack_state(struct bpf_func_state *state, int size)
1635 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1640 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1644 state->allocated_stack = size;
1648 /* Acquire a pointer id from the env and update the state->refs to include
1649 * this new pointer reference.
1650 * On success, returns a valid pointer id to associate with the register
1651 * On failure, returns a negative errno.
1653 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1655 struct bpf_func_state *state = cur_func(env);
1656 int new_ofs = state->acquired_refs;
1659 err = resize_reference_state(state, state->acquired_refs + 1);
1663 state->refs[new_ofs].id = id;
1664 state->refs[new_ofs].insn_idx = insn_idx;
1665 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1670 /* release function corresponding to acquire_reference_state(). Idempotent. */
1671 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1675 last_idx = state->acquired_refs - 1;
1676 for (i = 0; i < state->acquired_refs; i++) {
1677 if (state->refs[i].id == ptr_id) {
1678 /* Cannot release caller references in callbacks */
1679 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1681 if (last_idx && i != last_idx)
1682 memcpy(&state->refs[i], &state->refs[last_idx],
1683 sizeof(*state->refs));
1684 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1685 state->acquired_refs--;
1692 static void free_func_state(struct bpf_func_state *state)
1697 kfree(state->stack);
1701 static void clear_jmp_history(struct bpf_verifier_state *state)
1703 kfree(state->jmp_history);
1704 state->jmp_history = NULL;
1705 state->jmp_history_cnt = 0;
1708 static void free_verifier_state(struct bpf_verifier_state *state,
1713 for (i = 0; i <= state->curframe; i++) {
1714 free_func_state(state->frame[i]);
1715 state->frame[i] = NULL;
1717 clear_jmp_history(state);
1722 /* copy verifier state from src to dst growing dst stack space
1723 * when necessary to accommodate larger src stack
1725 static int copy_func_state(struct bpf_func_state *dst,
1726 const struct bpf_func_state *src)
1730 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1731 err = copy_reference_state(dst, src);
1734 return copy_stack_state(dst, src);
1737 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1738 const struct bpf_verifier_state *src)
1740 struct bpf_func_state *dst;
1743 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1744 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1746 if (!dst_state->jmp_history)
1748 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1750 /* if dst has more stack frames then src frame, free them */
1751 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1752 free_func_state(dst_state->frame[i]);
1753 dst_state->frame[i] = NULL;
1755 dst_state->speculative = src->speculative;
1756 dst_state->active_rcu_lock = src->active_rcu_lock;
1757 dst_state->curframe = src->curframe;
1758 dst_state->active_lock.ptr = src->active_lock.ptr;
1759 dst_state->active_lock.id = src->active_lock.id;
1760 dst_state->branches = src->branches;
1761 dst_state->parent = src->parent;
1762 dst_state->first_insn_idx = src->first_insn_idx;
1763 dst_state->last_insn_idx = src->last_insn_idx;
1764 for (i = 0; i <= src->curframe; i++) {
1765 dst = dst_state->frame[i];
1767 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1770 dst_state->frame[i] = dst;
1772 err = copy_func_state(dst, src->frame[i]);
1779 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1782 u32 br = --st->branches;
1784 /* WARN_ON(br > 1) technically makes sense here,
1785 * but see comment in push_stack(), hence:
1787 WARN_ONCE((int)br < 0,
1788 "BUG update_branch_counts:branches_to_explore=%d\n",
1796 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1797 int *insn_idx, bool pop_log)
1799 struct bpf_verifier_state *cur = env->cur_state;
1800 struct bpf_verifier_stack_elem *elem, *head = env->head;
1803 if (env->head == NULL)
1807 err = copy_verifier_state(cur, &head->st);
1812 bpf_vlog_reset(&env->log, head->log_pos);
1814 *insn_idx = head->insn_idx;
1816 *prev_insn_idx = head->prev_insn_idx;
1818 free_verifier_state(&head->st, false);
1825 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1826 int insn_idx, int prev_insn_idx,
1829 struct bpf_verifier_state *cur = env->cur_state;
1830 struct bpf_verifier_stack_elem *elem;
1833 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1837 elem->insn_idx = insn_idx;
1838 elem->prev_insn_idx = prev_insn_idx;
1839 elem->next = env->head;
1840 elem->log_pos = env->log.end_pos;
1843 err = copy_verifier_state(&elem->st, cur);
1846 elem->st.speculative |= speculative;
1847 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1848 verbose(env, "The sequence of %d jumps is too complex.\n",
1852 if (elem->st.parent) {
1853 ++elem->st.parent->branches;
1854 /* WARN_ON(branches > 2) technically makes sense here,
1856 * 1. speculative states will bump 'branches' for non-branch
1858 * 2. is_state_visited() heuristics may decide not to create
1859 * a new state for a sequence of branches and all such current
1860 * and cloned states will be pointing to a single parent state
1861 * which might have large 'branches' count.
1866 free_verifier_state(env->cur_state, true);
1867 env->cur_state = NULL;
1868 /* pop all elements and return */
1869 while (!pop_stack(env, NULL, NULL, false));
1873 #define CALLER_SAVED_REGS 6
1874 static const int caller_saved[CALLER_SAVED_REGS] = {
1875 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1878 /* This helper doesn't clear reg->id */
1879 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1881 reg->var_off = tnum_const(imm);
1882 reg->smin_value = (s64)imm;
1883 reg->smax_value = (s64)imm;
1884 reg->umin_value = imm;
1885 reg->umax_value = imm;
1887 reg->s32_min_value = (s32)imm;
1888 reg->s32_max_value = (s32)imm;
1889 reg->u32_min_value = (u32)imm;
1890 reg->u32_max_value = (u32)imm;
1893 /* Mark the unknown part of a register (variable offset or scalar value) as
1894 * known to have the value @imm.
1896 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1898 /* Clear off and union(map_ptr, range) */
1899 memset(((u8 *)reg) + sizeof(reg->type), 0,
1900 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1902 reg->ref_obj_id = 0;
1903 ___mark_reg_known(reg, imm);
1906 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1908 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1909 reg->s32_min_value = (s32)imm;
1910 reg->s32_max_value = (s32)imm;
1911 reg->u32_min_value = (u32)imm;
1912 reg->u32_max_value = (u32)imm;
1915 /* Mark the 'variable offset' part of a register as zero. This should be
1916 * used only on registers holding a pointer type.
1918 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1920 __mark_reg_known(reg, 0);
1923 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1925 __mark_reg_known(reg, 0);
1926 reg->type = SCALAR_VALUE;
1929 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1930 struct bpf_reg_state *regs, u32 regno)
1932 if (WARN_ON(regno >= MAX_BPF_REG)) {
1933 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1934 /* Something bad happened, let's kill all regs */
1935 for (regno = 0; regno < MAX_BPF_REG; regno++)
1936 __mark_reg_not_init(env, regs + regno);
1939 __mark_reg_known_zero(regs + regno);
1942 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1943 bool first_slot, int dynptr_id)
1945 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1946 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1947 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1949 __mark_reg_known_zero(reg);
1950 reg->type = CONST_PTR_TO_DYNPTR;
1951 /* Give each dynptr a unique id to uniquely associate slices to it. */
1952 reg->id = dynptr_id;
1953 reg->dynptr.type = type;
1954 reg->dynptr.first_slot = first_slot;
1957 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1959 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1960 const struct bpf_map *map = reg->map_ptr;
1962 if (map->inner_map_meta) {
1963 reg->type = CONST_PTR_TO_MAP;
1964 reg->map_ptr = map->inner_map_meta;
1965 /* transfer reg's id which is unique for every map_lookup_elem
1966 * as UID of the inner map.
1968 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1969 reg->map_uid = reg->id;
1970 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1971 reg->type = PTR_TO_XDP_SOCK;
1972 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1973 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1974 reg->type = PTR_TO_SOCKET;
1976 reg->type = PTR_TO_MAP_VALUE;
1981 reg->type &= ~PTR_MAYBE_NULL;
1984 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1985 struct btf_field_graph_root *ds_head)
1987 __mark_reg_known_zero(®s[regno]);
1988 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1989 regs[regno].btf = ds_head->btf;
1990 regs[regno].btf_id = ds_head->value_btf_id;
1991 regs[regno].off = ds_head->node_offset;
1994 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1996 return type_is_pkt_pointer(reg->type);
1999 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2001 return reg_is_pkt_pointer(reg) ||
2002 reg->type == PTR_TO_PACKET_END;
2005 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2007 return base_type(reg->type) == PTR_TO_MEM &&
2008 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2011 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2012 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2013 enum bpf_reg_type which)
2015 /* The register can already have a range from prior markings.
2016 * This is fine as long as it hasn't been advanced from its
2019 return reg->type == which &&
2022 tnum_equals_const(reg->var_off, 0);
2025 /* Reset the min/max bounds of a register */
2026 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2028 reg->smin_value = S64_MIN;
2029 reg->smax_value = S64_MAX;
2030 reg->umin_value = 0;
2031 reg->umax_value = U64_MAX;
2033 reg->s32_min_value = S32_MIN;
2034 reg->s32_max_value = S32_MAX;
2035 reg->u32_min_value = 0;
2036 reg->u32_max_value = U32_MAX;
2039 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2041 reg->smin_value = S64_MIN;
2042 reg->smax_value = S64_MAX;
2043 reg->umin_value = 0;
2044 reg->umax_value = U64_MAX;
2047 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2049 reg->s32_min_value = S32_MIN;
2050 reg->s32_max_value = S32_MAX;
2051 reg->u32_min_value = 0;
2052 reg->u32_max_value = U32_MAX;
2055 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2057 struct tnum var32_off = tnum_subreg(reg->var_off);
2059 /* min signed is max(sign bit) | min(other bits) */
2060 reg->s32_min_value = max_t(s32, reg->s32_min_value,
2061 var32_off.value | (var32_off.mask & S32_MIN));
2062 /* max signed is min(sign bit) | max(other bits) */
2063 reg->s32_max_value = min_t(s32, reg->s32_max_value,
2064 var32_off.value | (var32_off.mask & S32_MAX));
2065 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2066 reg->u32_max_value = min(reg->u32_max_value,
2067 (u32)(var32_off.value | var32_off.mask));
2070 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2072 /* min signed is max(sign bit) | min(other bits) */
2073 reg->smin_value = max_t(s64, reg->smin_value,
2074 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2075 /* max signed is min(sign bit) | max(other bits) */
2076 reg->smax_value = min_t(s64, reg->smax_value,
2077 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2078 reg->umin_value = max(reg->umin_value, reg->var_off.value);
2079 reg->umax_value = min(reg->umax_value,
2080 reg->var_off.value | reg->var_off.mask);
2083 static void __update_reg_bounds(struct bpf_reg_state *reg)
2085 __update_reg32_bounds(reg);
2086 __update_reg64_bounds(reg);
2089 /* Uses signed min/max values to inform unsigned, and vice-versa */
2090 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2092 /* Learn sign from signed bounds.
2093 * If we cannot cross the sign boundary, then signed and unsigned bounds
2094 * are the same, so combine. This works even in the negative case, e.g.
2095 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2097 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2098 reg->s32_min_value = reg->u32_min_value =
2099 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2100 reg->s32_max_value = reg->u32_max_value =
2101 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2104 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2105 * boundary, so we must be careful.
2107 if ((s32)reg->u32_max_value >= 0) {
2108 /* Positive. We can't learn anything from the smin, but smax
2109 * is positive, hence safe.
2111 reg->s32_min_value = reg->u32_min_value;
2112 reg->s32_max_value = reg->u32_max_value =
2113 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2114 } else if ((s32)reg->u32_min_value < 0) {
2115 /* Negative. We can't learn anything from the smax, but smin
2116 * is negative, hence safe.
2118 reg->s32_min_value = reg->u32_min_value =
2119 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2120 reg->s32_max_value = reg->u32_max_value;
2124 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2126 /* Learn sign from signed bounds.
2127 * If we cannot cross the sign boundary, then signed and unsigned bounds
2128 * are the same, so combine. This works even in the negative case, e.g.
2129 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2131 if (reg->smin_value >= 0 || reg->smax_value < 0) {
2132 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2134 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2138 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2139 * boundary, so we must be careful.
2141 if ((s64)reg->umax_value >= 0) {
2142 /* Positive. We can't learn anything from the smin, but smax
2143 * is positive, hence safe.
2145 reg->smin_value = reg->umin_value;
2146 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2148 } else if ((s64)reg->umin_value < 0) {
2149 /* Negative. We can't learn anything from the smax, but smin
2150 * is negative, hence safe.
2152 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2154 reg->smax_value = reg->umax_value;
2158 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2160 __reg32_deduce_bounds(reg);
2161 __reg64_deduce_bounds(reg);
2164 /* Attempts to improve var_off based on unsigned min/max information */
2165 static void __reg_bound_offset(struct bpf_reg_state *reg)
2167 struct tnum var64_off = tnum_intersect(reg->var_off,
2168 tnum_range(reg->umin_value,
2170 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2171 tnum_range(reg->u32_min_value,
2172 reg->u32_max_value));
2174 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2177 static void reg_bounds_sync(struct bpf_reg_state *reg)
2179 /* We might have learned new bounds from the var_off. */
2180 __update_reg_bounds(reg);
2181 /* We might have learned something about the sign bit. */
2182 __reg_deduce_bounds(reg);
2183 /* We might have learned some bits from the bounds. */
2184 __reg_bound_offset(reg);
2185 /* Intersecting with the old var_off might have improved our bounds
2186 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2187 * then new var_off is (0; 0x7f...fc) which improves our umax.
2189 __update_reg_bounds(reg);
2192 static bool __reg32_bound_s64(s32 a)
2194 return a >= 0 && a <= S32_MAX;
2197 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2199 reg->umin_value = reg->u32_min_value;
2200 reg->umax_value = reg->u32_max_value;
2202 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2203 * be positive otherwise set to worse case bounds and refine later
2206 if (__reg32_bound_s64(reg->s32_min_value) &&
2207 __reg32_bound_s64(reg->s32_max_value)) {
2208 reg->smin_value = reg->s32_min_value;
2209 reg->smax_value = reg->s32_max_value;
2211 reg->smin_value = 0;
2212 reg->smax_value = U32_MAX;
2216 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2218 /* special case when 64-bit register has upper 32-bit register
2219 * zeroed. Typically happens after zext or <<32, >>32 sequence
2220 * allowing us to use 32-bit bounds directly,
2222 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2223 __reg_assign_32_into_64(reg);
2225 /* Otherwise the best we can do is push lower 32bit known and
2226 * unknown bits into register (var_off set from jmp logic)
2227 * then learn as much as possible from the 64-bit tnum
2228 * known and unknown bits. The previous smin/smax bounds are
2229 * invalid here because of jmp32 compare so mark them unknown
2230 * so they do not impact tnum bounds calculation.
2232 __mark_reg64_unbounded(reg);
2234 reg_bounds_sync(reg);
2237 static bool __reg64_bound_s32(s64 a)
2239 return a >= S32_MIN && a <= S32_MAX;
2242 static bool __reg64_bound_u32(u64 a)
2244 return a >= U32_MIN && a <= U32_MAX;
2247 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2249 __mark_reg32_unbounded(reg);
2250 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2251 reg->s32_min_value = (s32)reg->smin_value;
2252 reg->s32_max_value = (s32)reg->smax_value;
2254 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2255 reg->u32_min_value = (u32)reg->umin_value;
2256 reg->u32_max_value = (u32)reg->umax_value;
2258 reg_bounds_sync(reg);
2261 /* Mark a register as having a completely unknown (scalar) value. */
2262 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2263 struct bpf_reg_state *reg)
2266 * Clear type, off, and union(map_ptr, range) and
2267 * padding between 'type' and union
2269 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2270 reg->type = SCALAR_VALUE;
2272 reg->ref_obj_id = 0;
2273 reg->var_off = tnum_unknown;
2275 reg->precise = !env->bpf_capable;
2276 __mark_reg_unbounded(reg);
2279 static void mark_reg_unknown(struct bpf_verifier_env *env,
2280 struct bpf_reg_state *regs, u32 regno)
2282 if (WARN_ON(regno >= MAX_BPF_REG)) {
2283 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2284 /* Something bad happened, let's kill all regs except FP */
2285 for (regno = 0; regno < BPF_REG_FP; regno++)
2286 __mark_reg_not_init(env, regs + regno);
2289 __mark_reg_unknown(env, regs + regno);
2292 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2293 struct bpf_reg_state *reg)
2295 __mark_reg_unknown(env, reg);
2296 reg->type = NOT_INIT;
2299 static void mark_reg_not_init(struct bpf_verifier_env *env,
2300 struct bpf_reg_state *regs, u32 regno)
2302 if (WARN_ON(regno >= MAX_BPF_REG)) {
2303 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2304 /* Something bad happened, let's kill all regs except FP */
2305 for (regno = 0; regno < BPF_REG_FP; regno++)
2306 __mark_reg_not_init(env, regs + regno);
2309 __mark_reg_not_init(env, regs + regno);
2312 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2313 struct bpf_reg_state *regs, u32 regno,
2314 enum bpf_reg_type reg_type,
2315 struct btf *btf, u32 btf_id,
2316 enum bpf_type_flag flag)
2318 if (reg_type == SCALAR_VALUE) {
2319 mark_reg_unknown(env, regs, regno);
2322 mark_reg_known_zero(env, regs, regno);
2323 regs[regno].type = PTR_TO_BTF_ID | flag;
2324 regs[regno].btf = btf;
2325 regs[regno].btf_id = btf_id;
2328 #define DEF_NOT_SUBREG (0)
2329 static void init_reg_state(struct bpf_verifier_env *env,
2330 struct bpf_func_state *state)
2332 struct bpf_reg_state *regs = state->regs;
2335 for (i = 0; i < MAX_BPF_REG; i++) {
2336 mark_reg_not_init(env, regs, i);
2337 regs[i].live = REG_LIVE_NONE;
2338 regs[i].parent = NULL;
2339 regs[i].subreg_def = DEF_NOT_SUBREG;
2343 regs[BPF_REG_FP].type = PTR_TO_STACK;
2344 mark_reg_known_zero(env, regs, BPF_REG_FP);
2345 regs[BPF_REG_FP].frameno = state->frameno;
2348 #define BPF_MAIN_FUNC (-1)
2349 static void init_func_state(struct bpf_verifier_env *env,
2350 struct bpf_func_state *state,
2351 int callsite, int frameno, int subprogno)
2353 state->callsite = callsite;
2354 state->frameno = frameno;
2355 state->subprogno = subprogno;
2356 state->callback_ret_range = tnum_range(0, 0);
2357 init_reg_state(env, state);
2358 mark_verifier_state_scratched(env);
2361 /* Similar to push_stack(), but for async callbacks */
2362 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2363 int insn_idx, int prev_insn_idx,
2366 struct bpf_verifier_stack_elem *elem;
2367 struct bpf_func_state *frame;
2369 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2373 elem->insn_idx = insn_idx;
2374 elem->prev_insn_idx = prev_insn_idx;
2375 elem->next = env->head;
2376 elem->log_pos = env->log.end_pos;
2379 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2381 "The sequence of %d jumps is too complex for async cb.\n",
2385 /* Unlike push_stack() do not copy_verifier_state().
2386 * The caller state doesn't matter.
2387 * This is async callback. It starts in a fresh stack.
2388 * Initialize it similar to do_check_common().
2390 elem->st.branches = 1;
2391 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2394 init_func_state(env, frame,
2395 BPF_MAIN_FUNC /* callsite */,
2396 0 /* frameno within this callchain */,
2397 subprog /* subprog number within this prog */);
2398 elem->st.frame[0] = frame;
2401 free_verifier_state(env->cur_state, true);
2402 env->cur_state = NULL;
2403 /* pop all elements and return */
2404 while (!pop_stack(env, NULL, NULL, false));
2410 SRC_OP, /* register is used as source operand */
2411 DST_OP, /* register is used as destination operand */
2412 DST_OP_NO_MARK /* same as above, check only, don't mark */
2415 static int cmp_subprogs(const void *a, const void *b)
2417 return ((struct bpf_subprog_info *)a)->start -
2418 ((struct bpf_subprog_info *)b)->start;
2421 static int find_subprog(struct bpf_verifier_env *env, int off)
2423 struct bpf_subprog_info *p;
2425 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2426 sizeof(env->subprog_info[0]), cmp_subprogs);
2429 return p - env->subprog_info;
2433 static int add_subprog(struct bpf_verifier_env *env, int off)
2435 int insn_cnt = env->prog->len;
2438 if (off >= insn_cnt || off < 0) {
2439 verbose(env, "call to invalid destination\n");
2442 ret = find_subprog(env, off);
2445 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2446 verbose(env, "too many subprograms\n");
2449 /* determine subprog starts. The end is one before the next starts */
2450 env->subprog_info[env->subprog_cnt++].start = off;
2451 sort(env->subprog_info, env->subprog_cnt,
2452 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2453 return env->subprog_cnt - 1;
2456 #define MAX_KFUNC_DESCS 256
2457 #define MAX_KFUNC_BTFS 256
2459 struct bpf_kfunc_desc {
2460 struct btf_func_model func_model;
2467 struct bpf_kfunc_btf {
2469 struct module *module;
2473 struct bpf_kfunc_desc_tab {
2474 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2475 * verification. JITs do lookups by bpf_insn, where func_id may not be
2476 * available, therefore at the end of verification do_misc_fixups()
2477 * sorts this by imm and offset.
2479 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2483 struct bpf_kfunc_btf_tab {
2484 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2488 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2490 const struct bpf_kfunc_desc *d0 = a;
2491 const struct bpf_kfunc_desc *d1 = b;
2493 /* func_id is not greater than BTF_MAX_TYPE */
2494 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2497 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2499 const struct bpf_kfunc_btf *d0 = a;
2500 const struct bpf_kfunc_btf *d1 = b;
2502 return d0->offset - d1->offset;
2505 static const struct bpf_kfunc_desc *
2506 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2508 struct bpf_kfunc_desc desc = {
2512 struct bpf_kfunc_desc_tab *tab;
2514 tab = prog->aux->kfunc_tab;
2515 return bsearch(&desc, tab->descs, tab->nr_descs,
2516 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2519 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2520 u16 btf_fd_idx, u8 **func_addr)
2522 const struct bpf_kfunc_desc *desc;
2524 desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2528 *func_addr = (u8 *)desc->addr;
2532 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2535 struct bpf_kfunc_btf kf_btf = { .offset = offset };
2536 struct bpf_kfunc_btf_tab *tab;
2537 struct bpf_kfunc_btf *b;
2542 tab = env->prog->aux->kfunc_btf_tab;
2543 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2544 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2546 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2547 verbose(env, "too many different module BTFs\n");
2548 return ERR_PTR(-E2BIG);
2551 if (bpfptr_is_null(env->fd_array)) {
2552 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2553 return ERR_PTR(-EPROTO);
2556 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2557 offset * sizeof(btf_fd),
2559 return ERR_PTR(-EFAULT);
2561 btf = btf_get_by_fd(btf_fd);
2563 verbose(env, "invalid module BTF fd specified\n");
2567 if (!btf_is_module(btf)) {
2568 verbose(env, "BTF fd for kfunc is not a module BTF\n");
2570 return ERR_PTR(-EINVAL);
2573 mod = btf_try_get_module(btf);
2576 return ERR_PTR(-ENXIO);
2579 b = &tab->descs[tab->nr_descs++];
2584 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2585 kfunc_btf_cmp_by_off, NULL);
2590 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2595 while (tab->nr_descs--) {
2596 module_put(tab->descs[tab->nr_descs].module);
2597 btf_put(tab->descs[tab->nr_descs].btf);
2602 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2606 /* In the future, this can be allowed to increase limit
2607 * of fd index into fd_array, interpreted as u16.
2609 verbose(env, "negative offset disallowed for kernel module function call\n");
2610 return ERR_PTR(-EINVAL);
2613 return __find_kfunc_desc_btf(env, offset);
2615 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2618 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2620 const struct btf_type *func, *func_proto;
2621 struct bpf_kfunc_btf_tab *btf_tab;
2622 struct bpf_kfunc_desc_tab *tab;
2623 struct bpf_prog_aux *prog_aux;
2624 struct bpf_kfunc_desc *desc;
2625 const char *func_name;
2626 struct btf *desc_btf;
2627 unsigned long call_imm;
2631 prog_aux = env->prog->aux;
2632 tab = prog_aux->kfunc_tab;
2633 btf_tab = prog_aux->kfunc_btf_tab;
2636 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2640 if (!env->prog->jit_requested) {
2641 verbose(env, "JIT is required for calling kernel function\n");
2645 if (!bpf_jit_supports_kfunc_call()) {
2646 verbose(env, "JIT does not support calling kernel function\n");
2650 if (!env->prog->gpl_compatible) {
2651 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2655 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2658 prog_aux->kfunc_tab = tab;
2661 /* func_id == 0 is always invalid, but instead of returning an error, be
2662 * conservative and wait until the code elimination pass before returning
2663 * error, so that invalid calls that get pruned out can be in BPF programs
2664 * loaded from userspace. It is also required that offset be untouched
2667 if (!func_id && !offset)
2670 if (!btf_tab && offset) {
2671 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2674 prog_aux->kfunc_btf_tab = btf_tab;
2677 desc_btf = find_kfunc_desc_btf(env, offset);
2678 if (IS_ERR(desc_btf)) {
2679 verbose(env, "failed to find BTF for kernel function\n");
2680 return PTR_ERR(desc_btf);
2683 if (find_kfunc_desc(env->prog, func_id, offset))
2686 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2687 verbose(env, "too many different kernel function calls\n");
2691 func = btf_type_by_id(desc_btf, func_id);
2692 if (!func || !btf_type_is_func(func)) {
2693 verbose(env, "kernel btf_id %u is not a function\n",
2697 func_proto = btf_type_by_id(desc_btf, func->type);
2698 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2699 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2704 func_name = btf_name_by_offset(desc_btf, func->name_off);
2705 addr = kallsyms_lookup_name(func_name);
2707 verbose(env, "cannot find address for kernel function %s\n",
2711 specialize_kfunc(env, func_id, offset, &addr);
2713 if (bpf_jit_supports_far_kfunc_call()) {
2716 call_imm = BPF_CALL_IMM(addr);
2717 /* Check whether the relative offset overflows desc->imm */
2718 if ((unsigned long)(s32)call_imm != call_imm) {
2719 verbose(env, "address of kernel function %s is out of range\n",
2725 if (bpf_dev_bound_kfunc_id(func_id)) {
2726 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2731 desc = &tab->descs[tab->nr_descs++];
2732 desc->func_id = func_id;
2733 desc->imm = call_imm;
2734 desc->offset = offset;
2736 err = btf_distill_func_proto(&env->log, desc_btf,
2737 func_proto, func_name,
2740 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2741 kfunc_desc_cmp_by_id_off, NULL);
2745 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2747 const struct bpf_kfunc_desc *d0 = a;
2748 const struct bpf_kfunc_desc *d1 = b;
2750 if (d0->imm != d1->imm)
2751 return d0->imm < d1->imm ? -1 : 1;
2752 if (d0->offset != d1->offset)
2753 return d0->offset < d1->offset ? -1 : 1;
2757 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2759 struct bpf_kfunc_desc_tab *tab;
2761 tab = prog->aux->kfunc_tab;
2765 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2766 kfunc_desc_cmp_by_imm_off, NULL);
2769 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2771 return !!prog->aux->kfunc_tab;
2774 const struct btf_func_model *
2775 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2776 const struct bpf_insn *insn)
2778 const struct bpf_kfunc_desc desc = {
2780 .offset = insn->off,
2782 const struct bpf_kfunc_desc *res;
2783 struct bpf_kfunc_desc_tab *tab;
2785 tab = prog->aux->kfunc_tab;
2786 res = bsearch(&desc, tab->descs, tab->nr_descs,
2787 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2789 return res ? &res->func_model : NULL;
2792 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2794 struct bpf_subprog_info *subprog = env->subprog_info;
2795 struct bpf_insn *insn = env->prog->insnsi;
2796 int i, ret, insn_cnt = env->prog->len;
2798 /* Add entry function. */
2799 ret = add_subprog(env, 0);
2803 for (i = 0; i < insn_cnt; i++, insn++) {
2804 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2805 !bpf_pseudo_kfunc_call(insn))
2808 if (!env->bpf_capable) {
2809 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2813 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2814 ret = add_subprog(env, i + insn->imm + 1);
2816 ret = add_kfunc_call(env, insn->imm, insn->off);
2822 /* Add a fake 'exit' subprog which could simplify subprog iteration
2823 * logic. 'subprog_cnt' should not be increased.
2825 subprog[env->subprog_cnt].start = insn_cnt;
2827 if (env->log.level & BPF_LOG_LEVEL2)
2828 for (i = 0; i < env->subprog_cnt; i++)
2829 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2834 static int check_subprogs(struct bpf_verifier_env *env)
2836 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2837 struct bpf_subprog_info *subprog = env->subprog_info;
2838 struct bpf_insn *insn = env->prog->insnsi;
2839 int insn_cnt = env->prog->len;
2841 /* now check that all jumps are within the same subprog */
2842 subprog_start = subprog[cur_subprog].start;
2843 subprog_end = subprog[cur_subprog + 1].start;
2844 for (i = 0; i < insn_cnt; i++) {
2845 u8 code = insn[i].code;
2847 if (code == (BPF_JMP | BPF_CALL) &&
2848 insn[i].src_reg == 0 &&
2849 insn[i].imm == BPF_FUNC_tail_call)
2850 subprog[cur_subprog].has_tail_call = true;
2851 if (BPF_CLASS(code) == BPF_LD &&
2852 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2853 subprog[cur_subprog].has_ld_abs = true;
2854 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2856 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2858 off = i + insn[i].off + 1;
2859 if (off < subprog_start || off >= subprog_end) {
2860 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2864 if (i == subprog_end - 1) {
2865 /* to avoid fall-through from one subprog into another
2866 * the last insn of the subprog should be either exit
2867 * or unconditional jump back
2869 if (code != (BPF_JMP | BPF_EXIT) &&
2870 code != (BPF_JMP | BPF_JA)) {
2871 verbose(env, "last insn is not an exit or jmp\n");
2874 subprog_start = subprog_end;
2876 if (cur_subprog < env->subprog_cnt)
2877 subprog_end = subprog[cur_subprog + 1].start;
2883 /* Parentage chain of this register (or stack slot) should take care of all
2884 * issues like callee-saved registers, stack slot allocation time, etc.
2886 static int mark_reg_read(struct bpf_verifier_env *env,
2887 const struct bpf_reg_state *state,
2888 struct bpf_reg_state *parent, u8 flag)
2890 bool writes = parent == state->parent; /* Observe write marks */
2894 /* if read wasn't screened by an earlier write ... */
2895 if (writes && state->live & REG_LIVE_WRITTEN)
2897 if (parent->live & REG_LIVE_DONE) {
2898 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2899 reg_type_str(env, parent->type),
2900 parent->var_off.value, parent->off);
2903 /* The first condition is more likely to be true than the
2904 * second, checked it first.
2906 if ((parent->live & REG_LIVE_READ) == flag ||
2907 parent->live & REG_LIVE_READ64)
2908 /* The parentage chain never changes and
2909 * this parent was already marked as LIVE_READ.
2910 * There is no need to keep walking the chain again and
2911 * keep re-marking all parents as LIVE_READ.
2912 * This case happens when the same register is read
2913 * multiple times without writes into it in-between.
2914 * Also, if parent has the stronger REG_LIVE_READ64 set,
2915 * then no need to set the weak REG_LIVE_READ32.
2918 /* ... then we depend on parent's value */
2919 parent->live |= flag;
2920 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2921 if (flag == REG_LIVE_READ64)
2922 parent->live &= ~REG_LIVE_READ32;
2924 parent = state->parent;
2929 if (env->longest_mark_read_walk < cnt)
2930 env->longest_mark_read_walk = cnt;
2934 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2936 struct bpf_func_state *state = func(env, reg);
2939 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2940 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2943 if (reg->type == CONST_PTR_TO_DYNPTR)
2945 spi = dynptr_get_spi(env, reg);
2948 /* Caller ensures dynptr is valid and initialized, which means spi is in
2949 * bounds and spi is the first dynptr slot. Simply mark stack slot as
2952 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2953 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2956 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2957 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2960 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2961 int spi, int nr_slots)
2963 struct bpf_func_state *state = func(env, reg);
2966 for (i = 0; i < nr_slots; i++) {
2967 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2969 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2973 mark_stack_slot_scratched(env, spi - i);
2979 /* This function is supposed to be used by the following 32-bit optimization
2980 * code only. It returns TRUE if the source or destination register operates
2981 * on 64-bit, otherwise return FALSE.
2983 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2984 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2989 class = BPF_CLASS(code);
2991 if (class == BPF_JMP) {
2992 /* BPF_EXIT for "main" will reach here. Return TRUE
2997 if (op == BPF_CALL) {
2998 /* BPF to BPF call will reach here because of marking
2999 * caller saved clobber with DST_OP_NO_MARK for which we
3000 * don't care the register def because they are anyway
3001 * marked as NOT_INIT already.
3003 if (insn->src_reg == BPF_PSEUDO_CALL)
3005 /* Helper call will reach here because of arg type
3006 * check, conservatively return TRUE.
3015 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3018 if (class == BPF_ALU64 || class == BPF_JMP ||
3019 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3022 if (class == BPF_ALU || class == BPF_JMP32)
3025 if (class == BPF_LDX) {
3027 return BPF_SIZE(code) == BPF_DW;
3028 /* LDX source must be ptr. */
3032 if (class == BPF_STX) {
3033 /* BPF_STX (including atomic variants) has multiple source
3034 * operands, one of which is a ptr. Check whether the caller is
3037 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3039 return BPF_SIZE(code) == BPF_DW;
3042 if (class == BPF_LD) {
3043 u8 mode = BPF_MODE(code);
3046 if (mode == BPF_IMM)
3049 /* Both LD_IND and LD_ABS return 32-bit data. */
3053 /* Implicit ctx ptr. */
3054 if (regno == BPF_REG_6)
3057 /* Explicit source could be any width. */
3061 if (class == BPF_ST)
3062 /* The only source register for BPF_ST is a ptr. */
3065 /* Conservatively return true at default. */
3069 /* Return the regno defined by the insn, or -1. */
3070 static int insn_def_regno(const struct bpf_insn *insn)
3072 switch (BPF_CLASS(insn->code)) {
3078 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3079 (insn->imm & BPF_FETCH)) {
3080 if (insn->imm == BPF_CMPXCHG)
3083 return insn->src_reg;
3088 return insn->dst_reg;
3092 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3093 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3095 int dst_reg = insn_def_regno(insn);
3100 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3103 static void mark_insn_zext(struct bpf_verifier_env *env,
3104 struct bpf_reg_state *reg)
3106 s32 def_idx = reg->subreg_def;
3108 if (def_idx == DEF_NOT_SUBREG)
3111 env->insn_aux_data[def_idx - 1].zext_dst = true;
3112 /* The dst will be zero extended, so won't be sub-register anymore. */
3113 reg->subreg_def = DEF_NOT_SUBREG;
3116 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3117 enum reg_arg_type t)
3119 struct bpf_verifier_state *vstate = env->cur_state;
3120 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3121 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3122 struct bpf_reg_state *reg, *regs = state->regs;
3125 if (regno >= MAX_BPF_REG) {
3126 verbose(env, "R%d is invalid\n", regno);
3130 mark_reg_scratched(env, regno);
3133 rw64 = is_reg64(env, insn, regno, reg, t);
3135 /* check whether register used as source operand can be read */
3136 if (reg->type == NOT_INIT) {
3137 verbose(env, "R%d !read_ok\n", regno);
3140 /* We don't need to worry about FP liveness because it's read-only */
3141 if (regno == BPF_REG_FP)
3145 mark_insn_zext(env, reg);
3147 return mark_reg_read(env, reg, reg->parent,
3148 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3150 /* check whether register used as dest operand can be written to */
3151 if (regno == BPF_REG_FP) {
3152 verbose(env, "frame pointer is read only\n");
3155 reg->live |= REG_LIVE_WRITTEN;
3156 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3158 mark_reg_unknown(env, regs, regno);
3163 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3165 env->insn_aux_data[idx].jmp_point = true;
3168 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3170 return env->insn_aux_data[insn_idx].jmp_point;
3173 /* for any branch, call, exit record the history of jmps in the given state */
3174 static int push_jmp_history(struct bpf_verifier_env *env,
3175 struct bpf_verifier_state *cur)
3177 u32 cnt = cur->jmp_history_cnt;
3178 struct bpf_idx_pair *p;
3181 if (!is_jmp_point(env, env->insn_idx))
3185 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3186 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3189 p[cnt - 1].idx = env->insn_idx;
3190 p[cnt - 1].prev_idx = env->prev_insn_idx;
3191 cur->jmp_history = p;
3192 cur->jmp_history_cnt = cnt;
3196 /* Backtrack one insn at a time. If idx is not at the top of recorded
3197 * history then previous instruction came from straight line execution.
3199 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3204 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3205 i = st->jmp_history[cnt - 1].prev_idx;
3213 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3215 const struct btf_type *func;
3216 struct btf *desc_btf;
3218 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3221 desc_btf = find_kfunc_desc_btf(data, insn->off);
3222 if (IS_ERR(desc_btf))
3225 func = btf_type_by_id(desc_btf, insn->imm);
3226 return btf_name_by_offset(desc_btf, func->name_off);
3229 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3234 static inline void bt_reset(struct backtrack_state *bt)
3236 struct bpf_verifier_env *env = bt->env;
3238 memset(bt, 0, sizeof(*bt));
3242 static inline u32 bt_empty(struct backtrack_state *bt)
3247 for (i = 0; i <= bt->frame; i++)
3248 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3253 static inline int bt_subprog_enter(struct backtrack_state *bt)
3255 if (bt->frame == MAX_CALL_FRAMES - 1) {
3256 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3257 WARN_ONCE(1, "verifier backtracking bug");
3264 static inline int bt_subprog_exit(struct backtrack_state *bt)
3266 if (bt->frame == 0) {
3267 verbose(bt->env, "BUG subprog exit from frame 0\n");
3268 WARN_ONCE(1, "verifier backtracking bug");
3275 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3277 bt->reg_masks[frame] |= 1 << reg;
3280 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3282 bt->reg_masks[frame] &= ~(1 << reg);
3285 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3287 bt_set_frame_reg(bt, bt->frame, reg);
3290 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3292 bt_clear_frame_reg(bt, bt->frame, reg);
3295 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3297 bt->stack_masks[frame] |= 1ull << slot;
3300 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3302 bt->stack_masks[frame] &= ~(1ull << slot);
3305 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3307 bt_set_frame_slot(bt, bt->frame, slot);
3310 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3312 bt_clear_frame_slot(bt, bt->frame, slot);
3315 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3317 return bt->reg_masks[frame];
3320 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3322 return bt->reg_masks[bt->frame];
3325 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3327 return bt->stack_masks[frame];
3330 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3332 return bt->stack_masks[bt->frame];
3335 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3337 return bt->reg_masks[bt->frame] & (1 << reg);
3340 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3342 return bt->stack_masks[bt->frame] & (1ull << slot);
3345 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3346 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3348 DECLARE_BITMAP(mask, 64);
3354 bitmap_from_u64(mask, reg_mask);
3355 for_each_set_bit(i, mask, 32) {
3356 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3364 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3365 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3367 DECLARE_BITMAP(mask, 64);
3373 bitmap_from_u64(mask, stack_mask);
3374 for_each_set_bit(i, mask, 64) {
3375 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3384 /* For given verifier state backtrack_insn() is called from the last insn to
3385 * the first insn. Its purpose is to compute a bitmask of registers and
3386 * stack slots that needs precision in the parent verifier state.
3388 * @idx is an index of the instruction we are currently processing;
3389 * @subseq_idx is an index of the subsequent instruction that:
3390 * - *would be* executed next, if jump history is viewed in forward order;
3391 * - *was* processed previously during backtracking.
3393 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3394 struct backtrack_state *bt)
3396 const struct bpf_insn_cbs cbs = {
3397 .cb_call = disasm_kfunc_name,
3398 .cb_print = verbose,
3399 .private_data = env,
3401 struct bpf_insn *insn = env->prog->insnsi + idx;
3402 u8 class = BPF_CLASS(insn->code);
3403 u8 opcode = BPF_OP(insn->code);
3404 u8 mode = BPF_MODE(insn->code);
3405 u32 dreg = insn->dst_reg;
3406 u32 sreg = insn->src_reg;
3409 if (insn->code == 0)
3411 if (env->log.level & BPF_LOG_LEVEL2) {
3412 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3413 verbose(env, "mark_precise: frame%d: regs=%s ",
3414 bt->frame, env->tmp_str_buf);
3415 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3416 verbose(env, "stack=%s before ", env->tmp_str_buf);
3417 verbose(env, "%d: ", idx);
3418 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3421 if (class == BPF_ALU || class == BPF_ALU64) {
3422 if (!bt_is_reg_set(bt, dreg))
3424 if (opcode == BPF_MOV) {
3425 if (BPF_SRC(insn->code) == BPF_X) {
3426 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3427 * dreg needs precision after this insn
3428 * sreg needs precision before this insn
3430 bt_clear_reg(bt, dreg);
3431 bt_set_reg(bt, sreg);
3434 * dreg needs precision after this insn.
3435 * Corresponding register is already marked
3436 * as precise=true in this verifier state.
3437 * No further markings in parent are necessary
3439 bt_clear_reg(bt, dreg);
3442 if (BPF_SRC(insn->code) == BPF_X) {
3444 * both dreg and sreg need precision
3447 bt_set_reg(bt, sreg);
3449 * dreg still needs precision before this insn
3452 } else if (class == BPF_LDX) {
3453 if (!bt_is_reg_set(bt, dreg))
3455 bt_clear_reg(bt, dreg);
3457 /* scalars can only be spilled into stack w/o losing precision.
3458 * Load from any other memory can be zero extended.
3459 * The desire to keep that precision is already indicated
3460 * by 'precise' mark in corresponding register of this state.
3461 * No further tracking necessary.
3463 if (insn->src_reg != BPF_REG_FP)
3466 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3467 * that [fp - off] slot contains scalar that needs to be
3468 * tracked with precision
3470 spi = (-insn->off - 1) / BPF_REG_SIZE;
3472 verbose(env, "BUG spi %d\n", spi);
3473 WARN_ONCE(1, "verifier backtracking bug");
3476 bt_set_slot(bt, spi);
3477 } else if (class == BPF_STX || class == BPF_ST) {
3478 if (bt_is_reg_set(bt, dreg))
3479 /* stx & st shouldn't be using _scalar_ dst_reg
3480 * to access memory. It means backtracking
3481 * encountered a case of pointer subtraction.
3484 /* scalars can only be spilled into stack */
3485 if (insn->dst_reg != BPF_REG_FP)
3487 spi = (-insn->off - 1) / BPF_REG_SIZE;
3489 verbose(env, "BUG spi %d\n", spi);
3490 WARN_ONCE(1, "verifier backtracking bug");
3493 if (!bt_is_slot_set(bt, spi))
3495 bt_clear_slot(bt, spi);
3496 if (class == BPF_STX)
3497 bt_set_reg(bt, sreg);
3498 } else if (class == BPF_JMP || class == BPF_JMP32) {
3499 if (bpf_pseudo_call(insn)) {
3500 int subprog_insn_idx, subprog;
3502 subprog_insn_idx = idx + insn->imm + 1;
3503 subprog = find_subprog(env, subprog_insn_idx);
3507 if (subprog_is_global(env, subprog)) {
3508 /* check that jump history doesn't have any
3509 * extra instructions from subprog; the next
3510 * instruction after call to global subprog
3511 * should be literally next instruction in
3514 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3515 /* r1-r5 are invalidated after subprog call,
3516 * so for global func call it shouldn't be set
3519 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3520 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3521 WARN_ONCE(1, "verifier backtracking bug");
3524 /* global subprog always sets R0 */
3525 bt_clear_reg(bt, BPF_REG_0);
3528 /* static subprog call instruction, which
3529 * means that we are exiting current subprog,
3530 * so only r1-r5 could be still requested as
3531 * precise, r0 and r6-r10 or any stack slot in
3532 * the current frame should be zero by now
3534 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3535 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3536 WARN_ONCE(1, "verifier backtracking bug");
3539 /* we don't track register spills perfectly,
3540 * so fallback to force-precise instead of failing */
3541 if (bt_stack_mask(bt) != 0)
3543 /* propagate r1-r5 to the caller */
3544 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3545 if (bt_is_reg_set(bt, i)) {
3546 bt_clear_reg(bt, i);
3547 bt_set_frame_reg(bt, bt->frame - 1, i);
3550 if (bt_subprog_exit(bt))
3554 } else if ((bpf_helper_call(insn) &&
3555 is_callback_calling_function(insn->imm) &&
3556 !is_async_callback_calling_function(insn->imm)) ||
3557 (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3558 /* callback-calling helper or kfunc call, which means
3559 * we are exiting from subprog, but unlike the subprog
3560 * call handling above, we shouldn't propagate
3561 * precision of r1-r5 (if any requested), as they are
3562 * not actually arguments passed directly to callback
3565 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3566 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3567 WARN_ONCE(1, "verifier backtracking bug");
3570 if (bt_stack_mask(bt) != 0)
3572 /* clear r1-r5 in callback subprog's mask */
3573 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3574 bt_clear_reg(bt, i);
3575 if (bt_subprog_exit(bt))
3578 } else if (opcode == BPF_CALL) {
3579 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3580 * catch this error later. Make backtracking conservative
3583 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3585 /* regular helper call sets R0 */
3586 bt_clear_reg(bt, BPF_REG_0);
3587 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3588 /* if backtracing was looking for registers R1-R5
3589 * they should have been found already.
3591 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3592 WARN_ONCE(1, "verifier backtracking bug");
3595 } else if (opcode == BPF_EXIT) {
3598 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3599 /* if backtracing was looking for registers R1-R5
3600 * they should have been found already.
3602 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3603 WARN_ONCE(1, "verifier backtracking bug");
3607 /* BPF_EXIT in subprog or callback always returns
3608 * right after the call instruction, so by checking
3609 * whether the instruction at subseq_idx-1 is subprog
3610 * call or not we can distinguish actual exit from
3611 * *subprog* from exit from *callback*. In the former
3612 * case, we need to propagate r0 precision, if
3613 * necessary. In the former we never do that.
3615 r0_precise = subseq_idx - 1 >= 0 &&
3616 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3617 bt_is_reg_set(bt, BPF_REG_0);
3619 bt_clear_reg(bt, BPF_REG_0);
3620 if (bt_subprog_enter(bt))
3624 bt_set_reg(bt, BPF_REG_0);
3625 /* r6-r9 and stack slots will stay set in caller frame
3626 * bitmasks until we return back from callee(s)
3629 } else if (BPF_SRC(insn->code) == BPF_X) {
3630 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3633 * Both dreg and sreg need precision before
3634 * this insn. If only sreg was marked precise
3635 * before it would be equally necessary to
3636 * propagate it to dreg.
3638 bt_set_reg(bt, dreg);
3639 bt_set_reg(bt, sreg);
3640 /* else dreg <cond> K
3641 * Only dreg still needs precision before
3642 * this insn, so for the K-based conditional
3643 * there is nothing new to be marked.
3646 } else if (class == BPF_LD) {
3647 if (!bt_is_reg_set(bt, dreg))
3649 bt_clear_reg(bt, dreg);
3650 /* It's ld_imm64 or ld_abs or ld_ind.
3651 * For ld_imm64 no further tracking of precision
3652 * into parent is necessary
3654 if (mode == BPF_IND || mode == BPF_ABS)
3655 /* to be analyzed */
3661 /* the scalar precision tracking algorithm:
3662 * . at the start all registers have precise=false.
3663 * . scalar ranges are tracked as normal through alu and jmp insns.
3664 * . once precise value of the scalar register is used in:
3665 * . ptr + scalar alu
3666 * . if (scalar cond K|scalar)
3667 * . helper_call(.., scalar, ...) where ARG_CONST is expected
3668 * backtrack through the verifier states and mark all registers and
3669 * stack slots with spilled constants that these scalar regisers
3670 * should be precise.
3671 * . during state pruning two registers (or spilled stack slots)
3672 * are equivalent if both are not precise.
3674 * Note the verifier cannot simply walk register parentage chain,
3675 * since many different registers and stack slots could have been
3676 * used to compute single precise scalar.
3678 * The approach of starting with precise=true for all registers and then
3679 * backtrack to mark a register as not precise when the verifier detects
3680 * that program doesn't care about specific value (e.g., when helper
3681 * takes register as ARG_ANYTHING parameter) is not safe.
3683 * It's ok to walk single parentage chain of the verifier states.
3684 * It's possible that this backtracking will go all the way till 1st insn.
3685 * All other branches will be explored for needing precision later.
3687 * The backtracking needs to deal with cases like:
3688 * 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)
3691 * if r5 > 0x79f goto pc+7
3692 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3695 * call bpf_perf_event_output#25
3696 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3700 * call foo // uses callee's r6 inside to compute r0
3704 * to track above reg_mask/stack_mask needs to be independent for each frame.
3706 * Also if parent's curframe > frame where backtracking started,
3707 * the verifier need to mark registers in both frames, otherwise callees
3708 * may incorrectly prune callers. This is similar to
3709 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3711 * For now backtracking falls back into conservative marking.
3713 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3714 struct bpf_verifier_state *st)
3716 struct bpf_func_state *func;
3717 struct bpf_reg_state *reg;
3720 if (env->log.level & BPF_LOG_LEVEL2) {
3721 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3725 /* big hammer: mark all scalars precise in this path.
3726 * pop_stack may still get !precise scalars.
3727 * We also skip current state and go straight to first parent state,
3728 * because precision markings in current non-checkpointed state are
3729 * not needed. See why in the comment in __mark_chain_precision below.
3731 for (st = st->parent; st; st = st->parent) {
3732 for (i = 0; i <= st->curframe; i++) {
3733 func = st->frame[i];
3734 for (j = 0; j < BPF_REG_FP; j++) {
3735 reg = &func->regs[j];
3736 if (reg->type != SCALAR_VALUE || reg->precise)
3738 reg->precise = true;
3739 if (env->log.level & BPF_LOG_LEVEL2) {
3740 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3744 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3745 if (!is_spilled_reg(&func->stack[j]))
3747 reg = &func->stack[j].spilled_ptr;
3748 if (reg->type != SCALAR_VALUE || reg->precise)
3750 reg->precise = true;
3751 if (env->log.level & BPF_LOG_LEVEL2) {
3752 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3760 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3762 struct bpf_func_state *func;
3763 struct bpf_reg_state *reg;
3766 for (i = 0; i <= st->curframe; i++) {
3767 func = st->frame[i];
3768 for (j = 0; j < BPF_REG_FP; j++) {
3769 reg = &func->regs[j];
3770 if (reg->type != SCALAR_VALUE)
3772 reg->precise = false;
3774 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3775 if (!is_spilled_reg(&func->stack[j]))
3777 reg = &func->stack[j].spilled_ptr;
3778 if (reg->type != SCALAR_VALUE)
3780 reg->precise = false;
3785 static bool idset_contains(struct bpf_idset *s, u32 id)
3789 for (i = 0; i < s->count; ++i)
3790 if (s->ids[i] == id)
3796 static int idset_push(struct bpf_idset *s, u32 id)
3798 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3800 s->ids[s->count++] = id;
3804 static void idset_reset(struct bpf_idset *s)
3809 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3810 * Mark all registers with these IDs as precise.
3812 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3814 struct bpf_idset *precise_ids = &env->idset_scratch;
3815 struct backtrack_state *bt = &env->bt;
3816 struct bpf_func_state *func;
3817 struct bpf_reg_state *reg;
3818 DECLARE_BITMAP(mask, 64);
3821 idset_reset(precise_ids);
3823 for (fr = bt->frame; fr >= 0; fr--) {
3824 func = st->frame[fr];
3826 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3827 for_each_set_bit(i, mask, 32) {
3828 reg = &func->regs[i];
3829 if (!reg->id || reg->type != SCALAR_VALUE)
3831 if (idset_push(precise_ids, reg->id))
3835 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3836 for_each_set_bit(i, mask, 64) {
3837 if (i >= func->allocated_stack / BPF_REG_SIZE)
3839 if (!is_spilled_scalar_reg(&func->stack[i]))
3841 reg = &func->stack[i].spilled_ptr;
3844 if (idset_push(precise_ids, reg->id))
3849 for (fr = 0; fr <= st->curframe; ++fr) {
3850 func = st->frame[fr];
3852 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
3853 reg = &func->regs[i];
3856 if (!idset_contains(precise_ids, reg->id))
3858 bt_set_frame_reg(bt, fr, i);
3860 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
3861 if (!is_spilled_scalar_reg(&func->stack[i]))
3863 reg = &func->stack[i].spilled_ptr;
3866 if (!idset_contains(precise_ids, reg->id))
3868 bt_set_frame_slot(bt, fr, i);
3876 * __mark_chain_precision() backtracks BPF program instruction sequence and
3877 * chain of verifier states making sure that register *regno* (if regno >= 0)
3878 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3879 * SCALARS, as well as any other registers and slots that contribute to
3880 * a tracked state of given registers/stack slots, depending on specific BPF
3881 * assembly instructions (see backtrack_insns() for exact instruction handling
3882 * logic). This backtracking relies on recorded jmp_history and is able to
3883 * traverse entire chain of parent states. This process ends only when all the
3884 * necessary registers/slots and their transitive dependencies are marked as
3887 * One important and subtle aspect is that precise marks *do not matter* in
3888 * the currently verified state (current state). It is important to understand
3889 * why this is the case.
3891 * First, note that current state is the state that is not yet "checkpointed",
3892 * i.e., it is not yet put into env->explored_states, and it has no children
3893 * states as well. It's ephemeral, and can end up either a) being discarded if
3894 * compatible explored state is found at some point or BPF_EXIT instruction is
3895 * reached or b) checkpointed and put into env->explored_states, branching out
3896 * into one or more children states.
3898 * In the former case, precise markings in current state are completely
3899 * ignored by state comparison code (see regsafe() for details). Only
3900 * checkpointed ("old") state precise markings are important, and if old
3901 * state's register/slot is precise, regsafe() assumes current state's
3902 * register/slot as precise and checks value ranges exactly and precisely. If
3903 * states turn out to be compatible, current state's necessary precise
3904 * markings and any required parent states' precise markings are enforced
3905 * after the fact with propagate_precision() logic, after the fact. But it's
3906 * important to realize that in this case, even after marking current state
3907 * registers/slots as precise, we immediately discard current state. So what
3908 * actually matters is any of the precise markings propagated into current
3909 * state's parent states, which are always checkpointed (due to b) case above).
3910 * As such, for scenario a) it doesn't matter if current state has precise
3911 * markings set or not.
3913 * Now, for the scenario b), checkpointing and forking into child(ren)
3914 * state(s). Note that before current state gets to checkpointing step, any
3915 * processed instruction always assumes precise SCALAR register/slot
3916 * knowledge: if precise value or range is useful to prune jump branch, BPF
3917 * verifier takes this opportunity enthusiastically. Similarly, when
3918 * register's value is used to calculate offset or memory address, exact
3919 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3920 * what we mentioned above about state comparison ignoring precise markings
3921 * during state comparison, BPF verifier ignores and also assumes precise
3922 * markings *at will* during instruction verification process. But as verifier
3923 * assumes precision, it also propagates any precision dependencies across
3924 * parent states, which are not yet finalized, so can be further restricted
3925 * based on new knowledge gained from restrictions enforced by their children
3926 * states. This is so that once those parent states are finalized, i.e., when
3927 * they have no more active children state, state comparison logic in
3928 * is_state_visited() would enforce strict and precise SCALAR ranges, if
3929 * required for correctness.
3931 * To build a bit more intuition, note also that once a state is checkpointed,
3932 * the path we took to get to that state is not important. This is crucial
3933 * property for state pruning. When state is checkpointed and finalized at
3934 * some instruction index, it can be correctly and safely used to "short
3935 * circuit" any *compatible* state that reaches exactly the same instruction
3936 * index. I.e., if we jumped to that instruction from a completely different
3937 * code path than original finalized state was derived from, it doesn't
3938 * matter, current state can be discarded because from that instruction
3939 * forward having a compatible state will ensure we will safely reach the
3940 * exit. States describe preconditions for further exploration, but completely
3941 * forget the history of how we got here.
3943 * This also means that even if we needed precise SCALAR range to get to
3944 * finalized state, but from that point forward *that same* SCALAR register is
3945 * never used in a precise context (i.e., it's precise value is not needed for
3946 * correctness), it's correct and safe to mark such register as "imprecise"
3947 * (i.e., precise marking set to false). This is what we rely on when we do
3948 * not set precise marking in current state. If no child state requires
3949 * precision for any given SCALAR register, it's safe to dictate that it can
3950 * be imprecise. If any child state does require this register to be precise,
3951 * we'll mark it precise later retroactively during precise markings
3952 * propagation from child state to parent states.
3954 * Skipping precise marking setting in current state is a mild version of
3955 * relying on the above observation. But we can utilize this property even
3956 * more aggressively by proactively forgetting any precise marking in the
3957 * current state (which we inherited from the parent state), right before we
3958 * checkpoint it and branch off into new child state. This is done by
3959 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3960 * finalized states which help in short circuiting more future states.
3962 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
3964 struct backtrack_state *bt = &env->bt;
3965 struct bpf_verifier_state *st = env->cur_state;
3966 int first_idx = st->first_insn_idx;
3967 int last_idx = env->insn_idx;
3968 int subseq_idx = -1;
3969 struct bpf_func_state *func;
3970 struct bpf_reg_state *reg;
3971 bool skip_first = true;
3974 if (!env->bpf_capable)
3977 /* set frame number from which we are starting to backtrack */
3978 bt_init(bt, env->cur_state->curframe);
3980 /* Do sanity checks against current state of register and/or stack
3981 * slot, but don't set precise flag in current state, as precision
3982 * tracking in the current state is unnecessary.
3984 func = st->frame[bt->frame];
3986 reg = &func->regs[regno];
3987 if (reg->type != SCALAR_VALUE) {
3988 WARN_ONCE(1, "backtracing misuse");
3991 bt_set_reg(bt, regno);
3998 DECLARE_BITMAP(mask, 64);
3999 u32 history = st->jmp_history_cnt;
4001 if (env->log.level & BPF_LOG_LEVEL2) {
4002 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4003 bt->frame, last_idx, first_idx, subseq_idx);
4006 /* If some register with scalar ID is marked as precise,
4007 * make sure that all registers sharing this ID are also precise.
4008 * This is needed to estimate effect of find_equal_scalars().
4009 * Do this at the last instruction of each state,
4010 * bpf_reg_state::id fields are valid for these instructions.
4012 * Allows to track precision in situation like below:
4014 * r2 = unknown value
4018 * r1 = r2 // r1 and r2 now share the same ID
4020 * --- state #1 {r1.id = A, r2.id = A} ---
4022 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4024 * --- state #2 {r1.id = A, r2.id = A} ---
4026 * r3 += r1 // need to mark both r1 and r2
4028 if (mark_precise_scalar_ids(env, st))
4032 /* we are at the entry into subprog, which
4033 * is expected for global funcs, but only if
4034 * requested precise registers are R1-R5
4035 * (which are global func's input arguments)
4037 if (st->curframe == 0 &&
4038 st->frame[0]->subprogno > 0 &&
4039 st->frame[0]->callsite == BPF_MAIN_FUNC &&
4040 bt_stack_mask(bt) == 0 &&
4041 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4042 bitmap_from_u64(mask, bt_reg_mask(bt));
4043 for_each_set_bit(i, mask, 32) {
4044 reg = &st->frame[0]->regs[i];
4045 if (reg->type != SCALAR_VALUE) {
4046 bt_clear_reg(bt, i);
4049 reg->precise = true;
4054 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4055 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4056 WARN_ONCE(1, "verifier backtracking bug");
4060 for (i = last_idx;;) {
4065 err = backtrack_insn(env, i, subseq_idx, bt);
4067 if (err == -ENOTSUPP) {
4068 mark_all_scalars_precise(env, env->cur_state);
4075 /* Found assignment(s) into tracked register in this state.
4076 * Since this state is already marked, just return.
4077 * Nothing to be tracked further in the parent state.
4083 i = get_prev_insn_idx(st, i, &history);
4084 if (i >= env->prog->len) {
4085 /* This can happen if backtracking reached insn 0
4086 * and there are still reg_mask or stack_mask
4088 * It means the backtracking missed the spot where
4089 * particular register was initialized with a constant.
4091 verbose(env, "BUG backtracking idx %d\n", i);
4092 WARN_ONCE(1, "verifier backtracking bug");
4100 for (fr = bt->frame; fr >= 0; fr--) {
4101 func = st->frame[fr];
4102 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4103 for_each_set_bit(i, mask, 32) {
4104 reg = &func->regs[i];
4105 if (reg->type != SCALAR_VALUE) {
4106 bt_clear_frame_reg(bt, fr, i);
4110 bt_clear_frame_reg(bt, fr, i);
4112 reg->precise = true;
4115 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4116 for_each_set_bit(i, mask, 64) {
4117 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4118 /* the sequence of instructions:
4120 * 3: (7b) *(u64 *)(r3 -8) = r0
4121 * 4: (79) r4 = *(u64 *)(r10 -8)
4122 * doesn't contain jmps. It's backtracked
4123 * as a single block.
4124 * During backtracking insn 3 is not recognized as
4125 * stack access, so at the end of backtracking
4126 * stack slot fp-8 is still marked in stack_mask.
4127 * However the parent state may not have accessed
4128 * fp-8 and it's "unallocated" stack space.
4129 * In such case fallback to conservative.
4131 mark_all_scalars_precise(env, env->cur_state);
4136 if (!is_spilled_scalar_reg(&func->stack[i])) {
4137 bt_clear_frame_slot(bt, fr, i);
4140 reg = &func->stack[i].spilled_ptr;
4142 bt_clear_frame_slot(bt, fr, i);
4144 reg->precise = true;
4146 if (env->log.level & BPF_LOG_LEVEL2) {
4147 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4148 bt_frame_reg_mask(bt, fr));
4149 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4150 fr, env->tmp_str_buf);
4151 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4152 bt_frame_stack_mask(bt, fr));
4153 verbose(env, "stack=%s: ", env->tmp_str_buf);
4154 print_verifier_state(env, func, true);
4161 subseq_idx = first_idx;
4162 last_idx = st->last_insn_idx;
4163 first_idx = st->first_insn_idx;
4166 /* if we still have requested precise regs or slots, we missed
4167 * something (e.g., stack access through non-r10 register), so
4168 * fallback to marking all precise
4170 if (!bt_empty(bt)) {
4171 mark_all_scalars_precise(env, env->cur_state);
4178 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4180 return __mark_chain_precision(env, regno);
4183 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4184 * desired reg and stack masks across all relevant frames
4186 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4188 return __mark_chain_precision(env, -1);
4191 static bool is_spillable_regtype(enum bpf_reg_type type)
4193 switch (base_type(type)) {
4194 case PTR_TO_MAP_VALUE:
4198 case PTR_TO_PACKET_META:
4199 case PTR_TO_PACKET_END:
4200 case PTR_TO_FLOW_KEYS:
4201 case CONST_PTR_TO_MAP:
4203 case PTR_TO_SOCK_COMMON:
4204 case PTR_TO_TCP_SOCK:
4205 case PTR_TO_XDP_SOCK:
4210 case PTR_TO_MAP_KEY:
4217 /* Does this register contain a constant zero? */
4218 static bool register_is_null(struct bpf_reg_state *reg)
4220 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4223 static bool register_is_const(struct bpf_reg_state *reg)
4225 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4228 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4230 return tnum_is_unknown(reg->var_off) &&
4231 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4232 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4233 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4234 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4237 static bool register_is_bounded(struct bpf_reg_state *reg)
4239 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4242 static bool __is_pointer_value(bool allow_ptr_leaks,
4243 const struct bpf_reg_state *reg)
4245 if (allow_ptr_leaks)
4248 return reg->type != SCALAR_VALUE;
4251 /* Copy src state preserving dst->parent and dst->live fields */
4252 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4254 struct bpf_reg_state *parent = dst->parent;
4255 enum bpf_reg_liveness live = dst->live;
4258 dst->parent = parent;
4262 static void save_register_state(struct bpf_func_state *state,
4263 int spi, struct bpf_reg_state *reg,
4268 copy_register_state(&state->stack[spi].spilled_ptr, reg);
4269 if (size == BPF_REG_SIZE)
4270 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4272 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4273 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4275 /* size < 8 bytes spill */
4277 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4280 static bool is_bpf_st_mem(struct bpf_insn *insn)
4282 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4285 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4286 * stack boundary and alignment are checked in check_mem_access()
4288 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4289 /* stack frame we're writing to */
4290 struct bpf_func_state *state,
4291 int off, int size, int value_regno,
4294 struct bpf_func_state *cur; /* state of the current function */
4295 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4296 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4297 struct bpf_reg_state *reg = NULL;
4298 u32 dst_reg = insn->dst_reg;
4300 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4303 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4304 * so it's aligned access and [off, off + size) are within stack limits
4306 if (!env->allow_ptr_leaks &&
4307 state->stack[spi].slot_type[0] == STACK_SPILL &&
4308 size != BPF_REG_SIZE) {
4309 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4313 cur = env->cur_state->frame[env->cur_state->curframe];
4314 if (value_regno >= 0)
4315 reg = &cur->regs[value_regno];
4316 if (!env->bypass_spec_v4) {
4317 bool sanitize = reg && is_spillable_regtype(reg->type);
4319 for (i = 0; i < size; i++) {
4320 u8 type = state->stack[spi].slot_type[i];
4322 if (type != STACK_MISC && type != STACK_ZERO) {
4329 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4332 err = destroy_if_dynptr_stack_slot(env, state, spi);
4336 mark_stack_slot_scratched(env, spi);
4337 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4338 !register_is_null(reg) && env->bpf_capable) {
4339 if (dst_reg != BPF_REG_FP) {
4340 /* The backtracking logic can only recognize explicit
4341 * stack slot address like [fp - 8]. Other spill of
4342 * scalar via different register has to be conservative.
4343 * Backtrack from here and mark all registers as precise
4344 * that contributed into 'reg' being a constant.
4346 err = mark_chain_precision(env, value_regno);
4350 save_register_state(state, spi, reg, size);
4351 /* Break the relation on a narrowing spill. */
4352 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4353 state->stack[spi].spilled_ptr.id = 0;
4354 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4355 insn->imm != 0 && env->bpf_capable) {
4356 struct bpf_reg_state fake_reg = {};
4358 __mark_reg_known(&fake_reg, (u32)insn->imm);
4359 fake_reg.type = SCALAR_VALUE;
4360 save_register_state(state, spi, &fake_reg, size);
4361 } else if (reg && is_spillable_regtype(reg->type)) {
4362 /* register containing pointer is being spilled into stack */
4363 if (size != BPF_REG_SIZE) {
4364 verbose_linfo(env, insn_idx, "; ");
4365 verbose(env, "invalid size of register spill\n");
4368 if (state != cur && reg->type == PTR_TO_STACK) {
4369 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4372 save_register_state(state, spi, reg, size);
4374 u8 type = STACK_MISC;
4376 /* regular write of data into stack destroys any spilled ptr */
4377 state->stack[spi].spilled_ptr.type = NOT_INIT;
4378 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4379 if (is_stack_slot_special(&state->stack[spi]))
4380 for (i = 0; i < BPF_REG_SIZE; i++)
4381 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4383 /* only mark the slot as written if all 8 bytes were written
4384 * otherwise read propagation may incorrectly stop too soon
4385 * when stack slots are partially written.
4386 * This heuristic means that read propagation will be
4387 * conservative, since it will add reg_live_read marks
4388 * to stack slots all the way to first state when programs
4389 * writes+reads less than 8 bytes
4391 if (size == BPF_REG_SIZE)
4392 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4394 /* when we zero initialize stack slots mark them as such */
4395 if ((reg && register_is_null(reg)) ||
4396 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4397 /* backtracking doesn't work for STACK_ZERO yet. */
4398 err = mark_chain_precision(env, value_regno);
4404 /* Mark slots affected by this stack write. */
4405 for (i = 0; i < size; i++)
4406 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4412 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4413 * known to contain a variable offset.
4414 * This function checks whether the write is permitted and conservatively
4415 * tracks the effects of the write, considering that each stack slot in the
4416 * dynamic range is potentially written to.
4418 * 'off' includes 'regno->off'.
4419 * 'value_regno' can be -1, meaning that an unknown value is being written to
4422 * Spilled pointers in range are not marked as written because we don't know
4423 * what's going to be actually written. This means that read propagation for
4424 * future reads cannot be terminated by this write.
4426 * For privileged programs, uninitialized stack slots are considered
4427 * initialized by this write (even though we don't know exactly what offsets
4428 * are going to be written to). The idea is that we don't want the verifier to
4429 * reject future reads that access slots written to through variable offsets.
4431 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4432 /* func where register points to */
4433 struct bpf_func_state *state,
4434 int ptr_regno, int off, int size,
4435 int value_regno, int insn_idx)
4437 struct bpf_func_state *cur; /* state of the current function */
4438 int min_off, max_off;
4440 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4441 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4442 bool writing_zero = false;
4443 /* set if the fact that we're writing a zero is used to let any
4444 * stack slots remain STACK_ZERO
4446 bool zero_used = false;
4448 cur = env->cur_state->frame[env->cur_state->curframe];
4449 ptr_reg = &cur->regs[ptr_regno];
4450 min_off = ptr_reg->smin_value + off;
4451 max_off = ptr_reg->smax_value + off + size;
4452 if (value_regno >= 0)
4453 value_reg = &cur->regs[value_regno];
4454 if ((value_reg && register_is_null(value_reg)) ||
4455 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4456 writing_zero = true;
4458 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4462 for (i = min_off; i < max_off; i++) {
4466 err = destroy_if_dynptr_stack_slot(env, state, spi);
4471 /* Variable offset writes destroy any spilled pointers in range. */
4472 for (i = min_off; i < max_off; i++) {
4473 u8 new_type, *stype;
4477 spi = slot / BPF_REG_SIZE;
4478 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4479 mark_stack_slot_scratched(env, spi);
4481 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4482 /* Reject the write if range we may write to has not
4483 * been initialized beforehand. If we didn't reject
4484 * here, the ptr status would be erased below (even
4485 * though not all slots are actually overwritten),
4486 * possibly opening the door to leaks.
4488 * We do however catch STACK_INVALID case below, and
4489 * only allow reading possibly uninitialized memory
4490 * later for CAP_PERFMON, as the write may not happen to
4493 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4498 /* Erase all spilled pointers. */
4499 state->stack[spi].spilled_ptr.type = NOT_INIT;
4501 /* Update the slot type. */
4502 new_type = STACK_MISC;
4503 if (writing_zero && *stype == STACK_ZERO) {
4504 new_type = STACK_ZERO;
4507 /* If the slot is STACK_INVALID, we check whether it's OK to
4508 * pretend that it will be initialized by this write. The slot
4509 * might not actually be written to, and so if we mark it as
4510 * initialized future reads might leak uninitialized memory.
4511 * For privileged programs, we will accept such reads to slots
4512 * that may or may not be written because, if we're reject
4513 * them, the error would be too confusing.
4515 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4516 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4523 /* backtracking doesn't work for STACK_ZERO yet. */
4524 err = mark_chain_precision(env, value_regno);
4531 /* When register 'dst_regno' is assigned some values from stack[min_off,
4532 * max_off), we set the register's type according to the types of the
4533 * respective stack slots. If all the stack values are known to be zeros, then
4534 * so is the destination reg. Otherwise, the register is considered to be
4535 * SCALAR. This function does not deal with register filling; the caller must
4536 * ensure that all spilled registers in the stack range have been marked as
4539 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4540 /* func where src register points to */
4541 struct bpf_func_state *ptr_state,
4542 int min_off, int max_off, int dst_regno)
4544 struct bpf_verifier_state *vstate = env->cur_state;
4545 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4550 for (i = min_off; i < max_off; i++) {
4552 spi = slot / BPF_REG_SIZE;
4553 mark_stack_slot_scratched(env, spi);
4554 stype = ptr_state->stack[spi].slot_type;
4555 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4559 if (zeros == max_off - min_off) {
4560 /* any access_size read into register is zero extended,
4561 * so the whole register == const_zero
4563 __mark_reg_const_zero(&state->regs[dst_regno]);
4564 /* backtracking doesn't support STACK_ZERO yet,
4565 * so mark it precise here, so that later
4566 * backtracking can stop here.
4567 * Backtracking may not need this if this register
4568 * doesn't participate in pointer adjustment.
4569 * Forward propagation of precise flag is not
4570 * necessary either. This mark is only to stop
4571 * backtracking. Any register that contributed
4572 * to const 0 was marked precise before spill.
4574 state->regs[dst_regno].precise = true;
4576 /* have read misc data from the stack */
4577 mark_reg_unknown(env, state->regs, dst_regno);
4579 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4582 /* Read the stack at 'off' and put the results into the register indicated by
4583 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4586 * 'dst_regno' can be -1, meaning that the read value is not going to a
4589 * The access is assumed to be within the current stack bounds.
4591 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4592 /* func where src register points to */
4593 struct bpf_func_state *reg_state,
4594 int off, int size, int dst_regno)
4596 struct bpf_verifier_state *vstate = env->cur_state;
4597 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4598 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4599 struct bpf_reg_state *reg;
4602 stype = reg_state->stack[spi].slot_type;
4603 reg = ®_state->stack[spi].spilled_ptr;
4605 mark_stack_slot_scratched(env, spi);
4607 if (is_spilled_reg(®_state->stack[spi])) {
4610 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4613 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4614 if (reg->type != SCALAR_VALUE) {
4615 verbose_linfo(env, env->insn_idx, "; ");
4616 verbose(env, "invalid size of register fill\n");
4620 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4624 if (!(off % BPF_REG_SIZE) && size == spill_size) {
4625 /* The earlier check_reg_arg() has decided the
4626 * subreg_def for this insn. Save it first.
4628 s32 subreg_def = state->regs[dst_regno].subreg_def;
4630 copy_register_state(&state->regs[dst_regno], reg);
4631 state->regs[dst_regno].subreg_def = subreg_def;
4633 for (i = 0; i < size; i++) {
4634 type = stype[(slot - i) % BPF_REG_SIZE];
4635 if (type == STACK_SPILL)
4637 if (type == STACK_MISC)
4639 if (type == STACK_INVALID && env->allow_uninit_stack)
4641 verbose(env, "invalid read from stack off %d+%d size %d\n",
4645 mark_reg_unknown(env, state->regs, dst_regno);
4647 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4651 if (dst_regno >= 0) {
4652 /* restore register state from stack */
4653 copy_register_state(&state->regs[dst_regno], reg);
4654 /* mark reg as written since spilled pointer state likely
4655 * has its liveness marks cleared by is_state_visited()
4656 * which resets stack/reg liveness for state transitions
4658 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4659 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4660 /* If dst_regno==-1, the caller is asking us whether
4661 * it is acceptable to use this value as a SCALAR_VALUE
4663 * We must not allow unprivileged callers to do that
4664 * with spilled pointers.
4666 verbose(env, "leaking pointer from stack off %d\n",
4670 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4672 for (i = 0; i < size; i++) {
4673 type = stype[(slot - i) % BPF_REG_SIZE];
4674 if (type == STACK_MISC)
4676 if (type == STACK_ZERO)
4678 if (type == STACK_INVALID && env->allow_uninit_stack)
4680 verbose(env, "invalid read from stack off %d+%d size %d\n",
4684 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4686 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4691 enum bpf_access_src {
4692 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
4693 ACCESS_HELPER = 2, /* the access is performed by a helper */
4696 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4697 int regno, int off, int access_size,
4698 bool zero_size_allowed,
4699 enum bpf_access_src type,
4700 struct bpf_call_arg_meta *meta);
4702 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4704 return cur_regs(env) + regno;
4707 /* Read the stack at 'ptr_regno + off' and put the result into the register
4709 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4710 * but not its variable offset.
4711 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4713 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4714 * filling registers (i.e. reads of spilled register cannot be detected when
4715 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4716 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4717 * offset; for a fixed offset check_stack_read_fixed_off should be used
4720 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4721 int ptr_regno, int off, int size, int dst_regno)
4723 /* The state of the source register. */
4724 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4725 struct bpf_func_state *ptr_state = func(env, reg);
4727 int min_off, max_off;
4729 /* Note that we pass a NULL meta, so raw access will not be permitted.
4731 err = check_stack_range_initialized(env, ptr_regno, off, size,
4732 false, ACCESS_DIRECT, NULL);
4736 min_off = reg->smin_value + off;
4737 max_off = reg->smax_value + off;
4738 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4742 /* check_stack_read dispatches to check_stack_read_fixed_off or
4743 * check_stack_read_var_off.
4745 * The caller must ensure that the offset falls within the allocated stack
4748 * 'dst_regno' is a register which will receive the value from the stack. It
4749 * can be -1, meaning that the read value is not going to a register.
4751 static int check_stack_read(struct bpf_verifier_env *env,
4752 int ptr_regno, int off, int size,
4755 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4756 struct bpf_func_state *state = func(env, reg);
4758 /* Some accesses are only permitted with a static offset. */
4759 bool var_off = !tnum_is_const(reg->var_off);
4761 /* The offset is required to be static when reads don't go to a
4762 * register, in order to not leak pointers (see
4763 * check_stack_read_fixed_off).
4765 if (dst_regno < 0 && var_off) {
4768 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4769 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4773 /* Variable offset is prohibited for unprivileged mode for simplicity
4774 * since it requires corresponding support in Spectre masking for stack
4775 * ALU. See also retrieve_ptr_limit(). The check in
4776 * check_stack_access_for_ptr_arithmetic() called by
4777 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4778 * with variable offsets, therefore no check is required here. Further,
4779 * just checking it here would be insufficient as speculative stack
4780 * writes could still lead to unsafe speculative behaviour.
4783 off += reg->var_off.value;
4784 err = check_stack_read_fixed_off(env, state, off, size,
4787 /* Variable offset stack reads need more conservative handling
4788 * than fixed offset ones. Note that dst_regno >= 0 on this
4791 err = check_stack_read_var_off(env, ptr_regno, off, size,
4798 /* check_stack_write dispatches to check_stack_write_fixed_off or
4799 * check_stack_write_var_off.
4801 * 'ptr_regno' is the register used as a pointer into the stack.
4802 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4803 * 'value_regno' is the register whose value we're writing to the stack. It can
4804 * be -1, meaning that we're not writing from a register.
4806 * The caller must ensure that the offset falls within the maximum stack size.
4808 static int check_stack_write(struct bpf_verifier_env *env,
4809 int ptr_regno, int off, int size,
4810 int value_regno, int insn_idx)
4812 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4813 struct bpf_func_state *state = func(env, reg);
4816 if (tnum_is_const(reg->var_off)) {
4817 off += reg->var_off.value;
4818 err = check_stack_write_fixed_off(env, state, off, size,
4819 value_regno, insn_idx);
4821 /* Variable offset stack reads need more conservative handling
4822 * than fixed offset ones.
4824 err = check_stack_write_var_off(env, state,
4825 ptr_regno, off, size,
4826 value_regno, insn_idx);
4831 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4832 int off, int size, enum bpf_access_type type)
4834 struct bpf_reg_state *regs = cur_regs(env);
4835 struct bpf_map *map = regs[regno].map_ptr;
4836 u32 cap = bpf_map_flags_to_cap(map);
4838 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4839 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4840 map->value_size, off, size);
4844 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4845 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4846 map->value_size, off, size);
4853 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4854 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4855 int off, int size, u32 mem_size,
4856 bool zero_size_allowed)
4858 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4859 struct bpf_reg_state *reg;
4861 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4864 reg = &cur_regs(env)[regno];
4865 switch (reg->type) {
4866 case PTR_TO_MAP_KEY:
4867 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4868 mem_size, off, size);
4870 case PTR_TO_MAP_VALUE:
4871 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4872 mem_size, off, size);
4875 case PTR_TO_PACKET_META:
4876 case PTR_TO_PACKET_END:
4877 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4878 off, size, regno, reg->id, off, mem_size);
4882 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4883 mem_size, off, size);
4889 /* check read/write into a memory region with possible variable offset */
4890 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4891 int off, int size, u32 mem_size,
4892 bool zero_size_allowed)
4894 struct bpf_verifier_state *vstate = env->cur_state;
4895 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4896 struct bpf_reg_state *reg = &state->regs[regno];
4899 /* We may have adjusted the register pointing to memory region, so we
4900 * need to try adding each of min_value and max_value to off
4901 * to make sure our theoretical access will be safe.
4903 * The minimum value is only important with signed
4904 * comparisons where we can't assume the floor of a
4905 * value is 0. If we are using signed variables for our
4906 * index'es we need to make sure that whatever we use
4907 * will have a set floor within our range.
4909 if (reg->smin_value < 0 &&
4910 (reg->smin_value == S64_MIN ||
4911 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4912 reg->smin_value + off < 0)) {
4913 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4917 err = __check_mem_access(env, regno, reg->smin_value + off, size,
4918 mem_size, zero_size_allowed);
4920 verbose(env, "R%d min value is outside of the allowed memory range\n",
4925 /* If we haven't set a max value then we need to bail since we can't be
4926 * sure we won't do bad things.
4927 * If reg->umax_value + off could overflow, treat that as unbounded too.
4929 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4930 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4934 err = __check_mem_access(env, regno, reg->umax_value + off, size,
4935 mem_size, zero_size_allowed);
4937 verbose(env, "R%d max value is outside of the allowed memory range\n",
4945 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4946 const struct bpf_reg_state *reg, int regno,
4949 /* Access to this pointer-typed register or passing it to a helper
4950 * is only allowed in its original, unmodified form.
4954 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4955 reg_type_str(env, reg->type), regno, reg->off);
4959 if (!fixed_off_ok && reg->off) {
4960 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4961 reg_type_str(env, reg->type), regno, reg->off);
4965 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4968 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4969 verbose(env, "variable %s access var_off=%s disallowed\n",
4970 reg_type_str(env, reg->type), tn_buf);
4977 int check_ptr_off_reg(struct bpf_verifier_env *env,
4978 const struct bpf_reg_state *reg, int regno)
4980 return __check_ptr_off_reg(env, reg, regno, false);
4983 static int map_kptr_match_type(struct bpf_verifier_env *env,
4984 struct btf_field *kptr_field,
4985 struct bpf_reg_state *reg, u32 regno)
4987 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4988 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4989 const char *reg_name = "";
4991 /* Only unreferenced case accepts untrusted pointers */
4992 if (kptr_field->type == BPF_KPTR_UNREF)
4993 perm_flags |= PTR_UNTRUSTED;
4995 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4998 if (!btf_is_kernel(reg->btf)) {
4999 verbose(env, "R%d must point to kernel BTF\n", regno);
5002 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5003 reg_name = btf_type_name(reg->btf, reg->btf_id);
5005 /* For ref_ptr case, release function check should ensure we get one
5006 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5007 * normal store of unreferenced kptr, we must ensure var_off is zero.
5008 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5009 * reg->off and reg->ref_obj_id are not needed here.
5011 if (__check_ptr_off_reg(env, reg, regno, true))
5014 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
5015 * we also need to take into account the reg->off.
5017 * We want to support cases like:
5025 * v = func(); // PTR_TO_BTF_ID
5026 * val->foo = v; // reg->off is zero, btf and btf_id match type
5027 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5028 * // first member type of struct after comparison fails
5029 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5032 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5033 * is zero. We must also ensure that btf_struct_ids_match does not walk
5034 * the struct to match type against first member of struct, i.e. reject
5035 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5036 * strict mode to true for type match.
5038 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5039 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5040 kptr_field->type == BPF_KPTR_REF))
5044 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5045 reg_type_str(env, reg->type), reg_name);
5046 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5047 if (kptr_field->type == BPF_KPTR_UNREF)
5048 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5055 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5056 * can dereference RCU protected pointers and result is PTR_TRUSTED.
5058 static bool in_rcu_cs(struct bpf_verifier_env *env)
5060 return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
5063 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5064 BTF_SET_START(rcu_protected_types)
5065 BTF_ID(struct, prog_test_ref_kfunc)
5066 BTF_ID(struct, cgroup)
5067 BTF_ID(struct, bpf_cpumask)
5068 BTF_ID(struct, task_struct)
5069 BTF_SET_END(rcu_protected_types)
5071 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5073 if (!btf_is_kernel(btf))
5075 return btf_id_set_contains(&rcu_protected_types, btf_id);
5078 static bool rcu_safe_kptr(const struct btf_field *field)
5080 const struct btf_field_kptr *kptr = &field->kptr;
5082 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5085 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5086 int value_regno, int insn_idx,
5087 struct btf_field *kptr_field)
5089 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5090 int class = BPF_CLASS(insn->code);
5091 struct bpf_reg_state *val_reg;
5093 /* Things we already checked for in check_map_access and caller:
5094 * - Reject cases where variable offset may touch kptr
5095 * - size of access (must be BPF_DW)
5096 * - tnum_is_const(reg->var_off)
5097 * - kptr_field->offset == off + reg->var_off.value
5099 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5100 if (BPF_MODE(insn->code) != BPF_MEM) {
5101 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5105 /* We only allow loading referenced kptr, since it will be marked as
5106 * untrusted, similar to unreferenced kptr.
5108 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5109 verbose(env, "store to referenced kptr disallowed\n");
5113 if (class == BPF_LDX) {
5114 val_reg = reg_state(env, value_regno);
5115 /* We can simply mark the value_regno receiving the pointer
5116 * value from map as PTR_TO_BTF_ID, with the correct type.
5118 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5119 kptr_field->kptr.btf_id,
5120 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5121 PTR_MAYBE_NULL | MEM_RCU :
5122 PTR_MAYBE_NULL | PTR_UNTRUSTED);
5123 /* For mark_ptr_or_null_reg */
5124 val_reg->id = ++env->id_gen;
5125 } else if (class == BPF_STX) {
5126 val_reg = reg_state(env, value_regno);
5127 if (!register_is_null(val_reg) &&
5128 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5130 } else if (class == BPF_ST) {
5132 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5133 kptr_field->offset);
5137 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5143 /* check read/write into a map element with possible variable offset */
5144 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5145 int off, int size, bool zero_size_allowed,
5146 enum bpf_access_src src)
5148 struct bpf_verifier_state *vstate = env->cur_state;
5149 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5150 struct bpf_reg_state *reg = &state->regs[regno];
5151 struct bpf_map *map = reg->map_ptr;
5152 struct btf_record *rec;
5155 err = check_mem_region_access(env, regno, off, size, map->value_size,
5160 if (IS_ERR_OR_NULL(map->record))
5163 for (i = 0; i < rec->cnt; i++) {
5164 struct btf_field *field = &rec->fields[i];
5165 u32 p = field->offset;
5167 /* If any part of a field can be touched by load/store, reject
5168 * this program. To check that [x1, x2) overlaps with [y1, y2),
5169 * it is sufficient to check x1 < y2 && y1 < x2.
5171 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5172 p < reg->umax_value + off + size) {
5173 switch (field->type) {
5174 case BPF_KPTR_UNREF:
5176 if (src != ACCESS_DIRECT) {
5177 verbose(env, "kptr cannot be accessed indirectly by helper\n");
5180 if (!tnum_is_const(reg->var_off)) {
5181 verbose(env, "kptr access cannot have variable offset\n");
5184 if (p != off + reg->var_off.value) {
5185 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5186 p, off + reg->var_off.value);
5189 if (size != bpf_size_to_bytes(BPF_DW)) {
5190 verbose(env, "kptr access size must be BPF_DW\n");
5195 verbose(env, "%s cannot be accessed directly by load/store\n",
5196 btf_field_type_name(field->type));
5204 #define MAX_PACKET_OFF 0xffff
5206 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5207 const struct bpf_call_arg_meta *meta,
5208 enum bpf_access_type t)
5210 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5212 switch (prog_type) {
5213 /* Program types only with direct read access go here! */
5214 case BPF_PROG_TYPE_LWT_IN:
5215 case BPF_PROG_TYPE_LWT_OUT:
5216 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5217 case BPF_PROG_TYPE_SK_REUSEPORT:
5218 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5219 case BPF_PROG_TYPE_CGROUP_SKB:
5224 /* Program types with direct read + write access go here! */
5225 case BPF_PROG_TYPE_SCHED_CLS:
5226 case BPF_PROG_TYPE_SCHED_ACT:
5227 case BPF_PROG_TYPE_XDP:
5228 case BPF_PROG_TYPE_LWT_XMIT:
5229 case BPF_PROG_TYPE_SK_SKB:
5230 case BPF_PROG_TYPE_SK_MSG:
5232 return meta->pkt_access;
5234 env->seen_direct_write = true;
5237 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5239 env->seen_direct_write = true;
5248 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5249 int size, bool zero_size_allowed)
5251 struct bpf_reg_state *regs = cur_regs(env);
5252 struct bpf_reg_state *reg = ®s[regno];
5255 /* We may have added a variable offset to the packet pointer; but any
5256 * reg->range we have comes after that. We are only checking the fixed
5260 /* We don't allow negative numbers, because we aren't tracking enough
5261 * detail to prove they're safe.
5263 if (reg->smin_value < 0) {
5264 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5269 err = reg->range < 0 ? -EINVAL :
5270 __check_mem_access(env, regno, off, size, reg->range,
5273 verbose(env, "R%d offset is outside of the packet\n", regno);
5277 /* __check_mem_access has made sure "off + size - 1" is within u16.
5278 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5279 * otherwise find_good_pkt_pointers would have refused to set range info
5280 * that __check_mem_access would have rejected this pkt access.
5281 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5283 env->prog->aux->max_pkt_offset =
5284 max_t(u32, env->prog->aux->max_pkt_offset,
5285 off + reg->umax_value + size - 1);
5290 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
5291 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5292 enum bpf_access_type t, enum bpf_reg_type *reg_type,
5293 struct btf **btf, u32 *btf_id)
5295 struct bpf_insn_access_aux info = {
5296 .reg_type = *reg_type,
5300 if (env->ops->is_valid_access &&
5301 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5302 /* A non zero info.ctx_field_size indicates that this field is a
5303 * candidate for later verifier transformation to load the whole
5304 * field and then apply a mask when accessed with a narrower
5305 * access than actual ctx access size. A zero info.ctx_field_size
5306 * will only allow for whole field access and rejects any other
5307 * type of narrower access.
5309 *reg_type = info.reg_type;
5311 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5313 *btf_id = info.btf_id;
5315 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5317 /* remember the offset of last byte accessed in ctx */
5318 if (env->prog->aux->max_ctx_offset < off + size)
5319 env->prog->aux->max_ctx_offset = off + size;
5323 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5327 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5330 if (size < 0 || off < 0 ||
5331 (u64)off + size > sizeof(struct bpf_flow_keys)) {
5332 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5339 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5340 u32 regno, int off, int size,
5341 enum bpf_access_type t)
5343 struct bpf_reg_state *regs = cur_regs(env);
5344 struct bpf_reg_state *reg = ®s[regno];
5345 struct bpf_insn_access_aux info = {};
5348 if (reg->smin_value < 0) {
5349 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5354 switch (reg->type) {
5355 case PTR_TO_SOCK_COMMON:
5356 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5359 valid = bpf_sock_is_valid_access(off, size, t, &info);
5361 case PTR_TO_TCP_SOCK:
5362 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5364 case PTR_TO_XDP_SOCK:
5365 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5373 env->insn_aux_data[insn_idx].ctx_field_size =
5374 info.ctx_field_size;
5378 verbose(env, "R%d invalid %s access off=%d size=%d\n",
5379 regno, reg_type_str(env, reg->type), off, size);
5384 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5386 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5389 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5391 const struct bpf_reg_state *reg = reg_state(env, regno);
5393 return reg->type == PTR_TO_CTX;
5396 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5398 const struct bpf_reg_state *reg = reg_state(env, regno);
5400 return type_is_sk_pointer(reg->type);
5403 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5405 const struct bpf_reg_state *reg = reg_state(env, regno);
5407 return type_is_pkt_pointer(reg->type);
5410 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5412 const struct bpf_reg_state *reg = reg_state(env, regno);
5414 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5415 return reg->type == PTR_TO_FLOW_KEYS;
5418 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5420 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5421 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5422 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5424 [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5427 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5429 /* A referenced register is always trusted. */
5430 if (reg->ref_obj_id)
5433 /* Types listed in the reg2btf_ids are always trusted */
5434 if (reg2btf_ids[base_type(reg->type)])
5437 /* If a register is not referenced, it is trusted if it has the
5438 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5439 * other type modifiers may be safe, but we elect to take an opt-in
5440 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5443 * Eventually, we should make PTR_TRUSTED the single source of truth
5444 * for whether a register is trusted.
5446 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5447 !bpf_type_has_unsafe_modifiers(reg->type);
5450 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5452 return reg->type & MEM_RCU;
5455 static void clear_trusted_flags(enum bpf_type_flag *flag)
5457 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5460 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5461 const struct bpf_reg_state *reg,
5462 int off, int size, bool strict)
5464 struct tnum reg_off;
5467 /* Byte size accesses are always allowed. */
5468 if (!strict || size == 1)
5471 /* For platforms that do not have a Kconfig enabling
5472 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5473 * NET_IP_ALIGN is universally set to '2'. And on platforms
5474 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5475 * to this code only in strict mode where we want to emulate
5476 * the NET_IP_ALIGN==2 checking. Therefore use an
5477 * unconditional IP align value of '2'.
5481 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5482 if (!tnum_is_aligned(reg_off, size)) {
5485 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5487 "misaligned packet access off %d+%s+%d+%d size %d\n",
5488 ip_align, tn_buf, reg->off, off, size);
5495 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5496 const struct bpf_reg_state *reg,
5497 const char *pointer_desc,
5498 int off, int size, bool strict)
5500 struct tnum reg_off;
5502 /* Byte size accesses are always allowed. */
5503 if (!strict || size == 1)
5506 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5507 if (!tnum_is_aligned(reg_off, size)) {
5510 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5511 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5512 pointer_desc, tn_buf, reg->off, off, size);
5519 static int check_ptr_alignment(struct bpf_verifier_env *env,
5520 const struct bpf_reg_state *reg, int off,
5521 int size, bool strict_alignment_once)
5523 bool strict = env->strict_alignment || strict_alignment_once;
5524 const char *pointer_desc = "";
5526 switch (reg->type) {
5528 case PTR_TO_PACKET_META:
5529 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5530 * right in front, treat it the very same way.
5532 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5533 case PTR_TO_FLOW_KEYS:
5534 pointer_desc = "flow keys ";
5536 case PTR_TO_MAP_KEY:
5537 pointer_desc = "key ";
5539 case PTR_TO_MAP_VALUE:
5540 pointer_desc = "value ";
5543 pointer_desc = "context ";
5546 pointer_desc = "stack ";
5547 /* The stack spill tracking logic in check_stack_write_fixed_off()
5548 * and check_stack_read_fixed_off() relies on stack accesses being
5554 pointer_desc = "sock ";
5556 case PTR_TO_SOCK_COMMON:
5557 pointer_desc = "sock_common ";
5559 case PTR_TO_TCP_SOCK:
5560 pointer_desc = "tcp_sock ";
5562 case PTR_TO_XDP_SOCK:
5563 pointer_desc = "xdp_sock ";
5568 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5572 static int update_stack_depth(struct bpf_verifier_env *env,
5573 const struct bpf_func_state *func,
5576 u16 stack = env->subprog_info[func->subprogno].stack_depth;
5581 /* update known max for given subprogram */
5582 env->subprog_info[func->subprogno].stack_depth = -off;
5586 /* starting from main bpf function walk all instructions of the function
5587 * and recursively walk all callees that given function can call.
5588 * Ignore jump and exit insns.
5589 * Since recursion is prevented by check_cfg() this algorithm
5590 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5592 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5594 struct bpf_subprog_info *subprog = env->subprog_info;
5595 struct bpf_insn *insn = env->prog->insnsi;
5596 int depth = 0, frame = 0, i, subprog_end;
5597 bool tail_call_reachable = false;
5598 int ret_insn[MAX_CALL_FRAMES];
5599 int ret_prog[MAX_CALL_FRAMES];
5602 i = subprog[idx].start;
5604 /* protect against potential stack overflow that might happen when
5605 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5606 * depth for such case down to 256 so that the worst case scenario
5607 * would result in 8k stack size (32 which is tailcall limit * 256 =
5610 * To get the idea what might happen, see an example:
5611 * func1 -> sub rsp, 128
5612 * subfunc1 -> sub rsp, 256
5613 * tailcall1 -> add rsp, 256
5614 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5615 * subfunc2 -> sub rsp, 64
5616 * subfunc22 -> sub rsp, 128
5617 * tailcall2 -> add rsp, 128
5618 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5620 * tailcall will unwind the current stack frame but it will not get rid
5621 * of caller's stack as shown on the example above.
5623 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5625 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5629 /* round up to 32-bytes, since this is granularity
5630 * of interpreter stack size
5632 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5633 if (depth > MAX_BPF_STACK) {
5634 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5639 subprog_end = subprog[idx + 1].start;
5640 for (; i < subprog_end; i++) {
5641 int next_insn, sidx;
5643 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5645 /* remember insn and function to return to */
5646 ret_insn[frame] = i + 1;
5647 ret_prog[frame] = idx;
5649 /* find the callee */
5650 next_insn = i + insn[i].imm + 1;
5651 sidx = find_subprog(env, next_insn);
5653 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5657 if (subprog[sidx].is_async_cb) {
5658 if (subprog[sidx].has_tail_call) {
5659 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5662 /* async callbacks don't increase bpf prog stack size unless called directly */
5663 if (!bpf_pseudo_call(insn + i))
5669 if (subprog[idx].has_tail_call)
5670 tail_call_reachable = true;
5673 if (frame >= MAX_CALL_FRAMES) {
5674 verbose(env, "the call stack of %d frames is too deep !\n",
5680 /* if tail call got detected across bpf2bpf calls then mark each of the
5681 * currently present subprog frames as tail call reachable subprogs;
5682 * this info will be utilized by JIT so that we will be preserving the
5683 * tail call counter throughout bpf2bpf calls combined with tailcalls
5685 if (tail_call_reachable)
5686 for (j = 0; j < frame; j++)
5687 subprog[ret_prog[j]].tail_call_reachable = true;
5688 if (subprog[0].tail_call_reachable)
5689 env->prog->aux->tail_call_reachable = true;
5691 /* end of for() loop means the last insn of the 'subprog'
5692 * was reached. Doesn't matter whether it was JA or EXIT
5696 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5698 i = ret_insn[frame];
5699 idx = ret_prog[frame];
5703 static int check_max_stack_depth(struct bpf_verifier_env *env)
5705 struct bpf_subprog_info *si = env->subprog_info;
5708 for (int i = 0; i < env->subprog_cnt; i++) {
5709 if (!i || si[i].is_async_cb) {
5710 ret = check_max_stack_depth_subprog(env, i);
5719 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5720 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5721 const struct bpf_insn *insn, int idx)
5723 int start = idx + insn->imm + 1, subprog;
5725 subprog = find_subprog(env, start);
5727 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5731 return env->subprog_info[subprog].stack_depth;
5735 static int __check_buffer_access(struct bpf_verifier_env *env,
5736 const char *buf_info,
5737 const struct bpf_reg_state *reg,
5738 int regno, int off, int size)
5742 "R%d invalid %s buffer access: off=%d, size=%d\n",
5743 regno, buf_info, off, size);
5746 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5749 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5751 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5752 regno, off, tn_buf);
5759 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5760 const struct bpf_reg_state *reg,
5761 int regno, int off, int size)
5765 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5769 if (off + size > env->prog->aux->max_tp_access)
5770 env->prog->aux->max_tp_access = off + size;
5775 static int check_buffer_access(struct bpf_verifier_env *env,
5776 const struct bpf_reg_state *reg,
5777 int regno, int off, int size,
5778 bool zero_size_allowed,
5781 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5784 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5788 if (off + size > *max_access)
5789 *max_access = off + size;
5794 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5795 static void zext_32_to_64(struct bpf_reg_state *reg)
5797 reg->var_off = tnum_subreg(reg->var_off);
5798 __reg_assign_32_into_64(reg);
5801 /* truncate register to smaller size (in bytes)
5802 * must be called with size < BPF_REG_SIZE
5804 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5808 /* clear high bits in bit representation */
5809 reg->var_off = tnum_cast(reg->var_off, size);
5811 /* fix arithmetic bounds */
5812 mask = ((u64)1 << (size * 8)) - 1;
5813 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5814 reg->umin_value &= mask;
5815 reg->umax_value &= mask;
5817 reg->umin_value = 0;
5818 reg->umax_value = mask;
5820 reg->smin_value = reg->umin_value;
5821 reg->smax_value = reg->umax_value;
5823 /* If size is smaller than 32bit register the 32bit register
5824 * values are also truncated so we push 64-bit bounds into
5825 * 32-bit bounds. Above were truncated < 32-bits already.
5829 __reg_combine_64_into_32(reg);
5832 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
5835 reg->smin_value = reg->s32_min_value = S8_MIN;
5836 reg->smax_value = reg->s32_max_value = S8_MAX;
5837 } else if (size == 2) {
5838 reg->smin_value = reg->s32_min_value = S16_MIN;
5839 reg->smax_value = reg->s32_max_value = S16_MAX;
5842 reg->smin_value = reg->s32_min_value = S32_MIN;
5843 reg->smax_value = reg->s32_max_value = S32_MAX;
5845 reg->umin_value = reg->u32_min_value = 0;
5846 reg->umax_value = U64_MAX;
5847 reg->u32_max_value = U32_MAX;
5848 reg->var_off = tnum_unknown;
5851 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
5853 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
5854 u64 top_smax_value, top_smin_value;
5855 u64 num_bits = size * 8;
5857 if (tnum_is_const(reg->var_off)) {
5858 u64_cval = reg->var_off.value;
5860 reg->var_off = tnum_const((s8)u64_cval);
5862 reg->var_off = tnum_const((s16)u64_cval);
5865 reg->var_off = tnum_const((s32)u64_cval);
5867 u64_cval = reg->var_off.value;
5868 reg->smax_value = reg->smin_value = u64_cval;
5869 reg->umax_value = reg->umin_value = u64_cval;
5870 reg->s32_max_value = reg->s32_min_value = u64_cval;
5871 reg->u32_max_value = reg->u32_min_value = u64_cval;
5875 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
5876 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
5878 if (top_smax_value != top_smin_value)
5881 /* find the s64_min and s64_min after sign extension */
5883 init_s64_max = (s8)reg->smax_value;
5884 init_s64_min = (s8)reg->smin_value;
5885 } else if (size == 2) {
5886 init_s64_max = (s16)reg->smax_value;
5887 init_s64_min = (s16)reg->smin_value;
5889 init_s64_max = (s32)reg->smax_value;
5890 init_s64_min = (s32)reg->smin_value;
5893 s64_max = max(init_s64_max, init_s64_min);
5894 s64_min = min(init_s64_max, init_s64_min);
5896 /* both of s64_max/s64_min positive or negative */
5897 if (s64_max >= 0 == s64_min >= 0) {
5898 reg->smin_value = reg->s32_min_value = s64_min;
5899 reg->smax_value = reg->s32_max_value = s64_max;
5900 reg->umin_value = reg->u32_min_value = s64_min;
5901 reg->umax_value = reg->u32_max_value = s64_max;
5902 reg->var_off = tnum_range(s64_min, s64_max);
5907 set_sext64_default_val(reg, size);
5910 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
5913 reg->s32_min_value = S8_MIN;
5914 reg->s32_max_value = S8_MAX;
5917 reg->s32_min_value = S16_MIN;
5918 reg->s32_max_value = S16_MAX;
5920 reg->u32_min_value = 0;
5921 reg->u32_max_value = U32_MAX;
5924 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
5926 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
5927 u32 top_smax_value, top_smin_value;
5928 u32 num_bits = size * 8;
5930 if (tnum_is_const(reg->var_off)) {
5931 u32_val = reg->var_off.value;
5933 reg->var_off = tnum_const((s8)u32_val);
5935 reg->var_off = tnum_const((s16)u32_val);
5937 u32_val = reg->var_off.value;
5938 reg->s32_min_value = reg->s32_max_value = u32_val;
5939 reg->u32_min_value = reg->u32_max_value = u32_val;
5943 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
5944 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
5946 if (top_smax_value != top_smin_value)
5949 /* find the s32_min and s32_min after sign extension */
5951 init_s32_max = (s8)reg->s32_max_value;
5952 init_s32_min = (s8)reg->s32_min_value;
5955 init_s32_max = (s16)reg->s32_max_value;
5956 init_s32_min = (s16)reg->s32_min_value;
5958 s32_max = max(init_s32_max, init_s32_min);
5959 s32_min = min(init_s32_max, init_s32_min);
5961 if (s32_min >= 0 == s32_max >= 0) {
5962 reg->s32_min_value = s32_min;
5963 reg->s32_max_value = s32_max;
5964 reg->u32_min_value = (u32)s32_min;
5965 reg->u32_max_value = (u32)s32_max;
5970 set_sext32_default_val(reg, size);
5973 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5975 /* A map is considered read-only if the following condition are true:
5977 * 1) BPF program side cannot change any of the map content. The
5978 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5979 * and was set at map creation time.
5980 * 2) The map value(s) have been initialized from user space by a
5981 * loader and then "frozen", such that no new map update/delete
5982 * operations from syscall side are possible for the rest of
5983 * the map's lifetime from that point onwards.
5984 * 3) Any parallel/pending map update/delete operations from syscall
5985 * side have been completed. Only after that point, it's safe to
5986 * assume that map value(s) are immutable.
5988 return (map->map_flags & BPF_F_RDONLY_PROG) &&
5989 READ_ONCE(map->frozen) &&
5990 !bpf_map_write_active(map);
5993 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6000 err = map->ops->map_direct_value_addr(map, &addr, off);
6003 ptr = (void *)(long)addr + off;
6007 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6010 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6013 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6024 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
6025 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
6026 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
6029 * Allow list few fields as RCU trusted or full trusted.
6030 * This logic doesn't allow mix tagging and will be removed once GCC supports
6034 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6035 BTF_TYPE_SAFE_RCU(struct task_struct) {
6036 const cpumask_t *cpus_ptr;
6037 struct css_set __rcu *cgroups;
6038 struct task_struct __rcu *real_parent;
6039 struct task_struct *group_leader;
6042 BTF_TYPE_SAFE_RCU(struct cgroup) {
6043 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6044 struct kernfs_node *kn;
6047 BTF_TYPE_SAFE_RCU(struct css_set) {
6048 struct cgroup *dfl_cgrp;
6051 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6052 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6053 struct file __rcu *exe_file;
6056 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6057 * because bpf prog accessible sockets are SOCK_RCU_FREE.
6059 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6063 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6067 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6068 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6069 struct seq_file *seq;
6072 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6073 struct bpf_iter_meta *meta;
6074 struct task_struct *task;
6077 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6081 BTF_TYPE_SAFE_TRUSTED(struct file) {
6082 struct inode *f_inode;
6085 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6086 /* no negative dentry-s in places where bpf can see it */
6087 struct inode *d_inode;
6090 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6094 static bool type_is_rcu(struct bpf_verifier_env *env,
6095 struct bpf_reg_state *reg,
6096 const char *field_name, u32 btf_id)
6098 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6099 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6100 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6102 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6105 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6106 struct bpf_reg_state *reg,
6107 const char *field_name, u32 btf_id)
6109 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6110 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6111 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6113 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6116 static bool type_is_trusted(struct bpf_verifier_env *env,
6117 struct bpf_reg_state *reg,
6118 const char *field_name, u32 btf_id)
6120 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6121 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6122 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6123 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6124 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6125 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6127 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6130 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6131 struct bpf_reg_state *regs,
6132 int regno, int off, int size,
6133 enum bpf_access_type atype,
6136 struct bpf_reg_state *reg = regs + regno;
6137 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6138 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6139 const char *field_name = NULL;
6140 enum bpf_type_flag flag = 0;
6144 if (!env->allow_ptr_leaks) {
6146 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6150 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6152 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6158 "R%d is ptr_%s invalid negative access: off=%d\n",
6162 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6165 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6167 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6168 regno, tname, off, tn_buf);
6172 if (reg->type & MEM_USER) {
6174 "R%d is ptr_%s access user memory: off=%d\n",
6179 if (reg->type & MEM_PERCPU) {
6181 "R%d is ptr_%s access percpu memory: off=%d\n",
6186 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6187 if (!btf_is_kernel(reg->btf)) {
6188 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6191 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6193 /* Writes are permitted with default btf_struct_access for
6194 * program allocated objects (which always have ref_obj_id > 0),
6195 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6197 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6198 verbose(env, "only read is supported\n");
6202 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6204 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6208 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6214 if (ret != PTR_TO_BTF_ID) {
6217 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6218 /* If this is an untrusted pointer, all pointers formed by walking it
6219 * also inherit the untrusted flag.
6221 flag = PTR_UNTRUSTED;
6223 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6224 /* By default any pointer obtained from walking a trusted pointer is no
6225 * longer trusted, unless the field being accessed has explicitly been
6226 * marked as inheriting its parent's state of trust (either full or RCU).
6228 * 'cgroups' pointer is untrusted if task->cgroups dereference
6229 * happened in a sleepable program outside of bpf_rcu_read_lock()
6230 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6231 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6233 * A regular RCU-protected pointer with __rcu tag can also be deemed
6234 * trusted if we are in an RCU CS. Such pointer can be NULL.
6236 if (type_is_trusted(env, reg, field_name, btf_id)) {
6237 flag |= PTR_TRUSTED;
6238 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6239 if (type_is_rcu(env, reg, field_name, btf_id)) {
6240 /* ignore __rcu tag and mark it MEM_RCU */
6242 } else if (flag & MEM_RCU ||
6243 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6244 /* __rcu tagged pointers can be NULL */
6245 flag |= MEM_RCU | PTR_MAYBE_NULL;
6247 /* We always trust them */
6248 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6249 flag & PTR_UNTRUSTED)
6250 flag &= ~PTR_UNTRUSTED;
6251 } else if (flag & (MEM_PERCPU | MEM_USER)) {
6254 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6255 clear_trusted_flags(&flag);
6259 * If not in RCU CS or MEM_RCU pointer can be NULL then
6260 * aggressively mark as untrusted otherwise such
6261 * pointers will be plain PTR_TO_BTF_ID without flags
6262 * and will be allowed to be passed into helpers for
6265 flag = PTR_UNTRUSTED;
6268 /* Old compat. Deprecated */
6269 clear_trusted_flags(&flag);
6272 if (atype == BPF_READ && value_regno >= 0)
6273 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6278 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6279 struct bpf_reg_state *regs,
6280 int regno, int off, int size,
6281 enum bpf_access_type atype,
6284 struct bpf_reg_state *reg = regs + regno;
6285 struct bpf_map *map = reg->map_ptr;
6286 struct bpf_reg_state map_reg;
6287 enum bpf_type_flag flag = 0;
6288 const struct btf_type *t;
6294 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6298 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6299 verbose(env, "map_ptr access not supported for map type %d\n",
6304 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6305 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6307 if (!env->allow_ptr_leaks) {
6309 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6315 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6320 if (atype != BPF_READ) {
6321 verbose(env, "only read from %s is supported\n", tname);
6325 /* Simulate access to a PTR_TO_BTF_ID */
6326 memset(&map_reg, 0, sizeof(map_reg));
6327 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6328 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6332 if (value_regno >= 0)
6333 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6338 /* Check that the stack access at the given offset is within bounds. The
6339 * maximum valid offset is -1.
6341 * The minimum valid offset is -MAX_BPF_STACK for writes, and
6342 * -state->allocated_stack for reads.
6344 static int check_stack_slot_within_bounds(int off,
6345 struct bpf_func_state *state,
6346 enum bpf_access_type t)
6351 min_valid_off = -MAX_BPF_STACK;
6353 min_valid_off = -state->allocated_stack;
6355 if (off < min_valid_off || off > -1)
6360 /* Check that the stack access at 'regno + off' falls within the maximum stack
6363 * 'off' includes `regno->offset`, but not its dynamic part (if any).
6365 static int check_stack_access_within_bounds(
6366 struct bpf_verifier_env *env,
6367 int regno, int off, int access_size,
6368 enum bpf_access_src src, enum bpf_access_type type)
6370 struct bpf_reg_state *regs = cur_regs(env);
6371 struct bpf_reg_state *reg = regs + regno;
6372 struct bpf_func_state *state = func(env, reg);
6373 int min_off, max_off;
6377 if (src == ACCESS_HELPER)
6378 /* We don't know if helpers are reading or writing (or both). */
6379 err_extra = " indirect access to";
6380 else if (type == BPF_READ)
6381 err_extra = " read from";
6383 err_extra = " write to";
6385 if (tnum_is_const(reg->var_off)) {
6386 min_off = reg->var_off.value + off;
6387 if (access_size > 0)
6388 max_off = min_off + access_size - 1;
6392 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6393 reg->smin_value <= -BPF_MAX_VAR_OFF) {
6394 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6398 min_off = reg->smin_value + off;
6399 if (access_size > 0)
6400 max_off = reg->smax_value + off + access_size - 1;
6405 err = check_stack_slot_within_bounds(min_off, state, type);
6407 err = check_stack_slot_within_bounds(max_off, state, type);
6410 if (tnum_is_const(reg->var_off)) {
6411 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6412 err_extra, regno, off, access_size);
6416 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6417 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6418 err_extra, regno, tn_buf, access_size);
6424 /* check whether memory at (regno + off) is accessible for t = (read | write)
6425 * if t==write, value_regno is a register which value is stored into memory
6426 * if t==read, value_regno is a register which will receive the value from memory
6427 * if t==write && value_regno==-1, some unknown value is stored into memory
6428 * if t==read && value_regno==-1, don't care what we read from memory
6430 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6431 int off, int bpf_size, enum bpf_access_type t,
6432 int value_regno, bool strict_alignment_once, bool is_ldsx)
6434 struct bpf_reg_state *regs = cur_regs(env);
6435 struct bpf_reg_state *reg = regs + regno;
6436 struct bpf_func_state *state;
6439 size = bpf_size_to_bytes(bpf_size);
6443 /* alignment checks will add in reg->off themselves */
6444 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6448 /* for access checks, reg->off is just part of off */
6451 if (reg->type == PTR_TO_MAP_KEY) {
6452 if (t == BPF_WRITE) {
6453 verbose(env, "write to change key R%d not allowed\n", regno);
6457 err = check_mem_region_access(env, regno, off, size,
6458 reg->map_ptr->key_size, false);
6461 if (value_regno >= 0)
6462 mark_reg_unknown(env, regs, value_regno);
6463 } else if (reg->type == PTR_TO_MAP_VALUE) {
6464 struct btf_field *kptr_field = NULL;
6466 if (t == BPF_WRITE && value_regno >= 0 &&
6467 is_pointer_value(env, value_regno)) {
6468 verbose(env, "R%d leaks addr into map\n", value_regno);
6471 err = check_map_access_type(env, regno, off, size, t);
6474 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6477 if (tnum_is_const(reg->var_off))
6478 kptr_field = btf_record_find(reg->map_ptr->record,
6479 off + reg->var_off.value, BPF_KPTR);
6481 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6482 } else if (t == BPF_READ && value_regno >= 0) {
6483 struct bpf_map *map = reg->map_ptr;
6485 /* if map is read-only, track its contents as scalars */
6486 if (tnum_is_const(reg->var_off) &&
6487 bpf_map_is_rdonly(map) &&
6488 map->ops->map_direct_value_addr) {
6489 int map_off = off + reg->var_off.value;
6492 err = bpf_map_direct_read(map, map_off, size,
6497 regs[value_regno].type = SCALAR_VALUE;
6498 __mark_reg_known(®s[value_regno], val);
6500 mark_reg_unknown(env, regs, value_regno);
6503 } else if (base_type(reg->type) == PTR_TO_MEM) {
6504 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6506 if (type_may_be_null(reg->type)) {
6507 verbose(env, "R%d invalid mem access '%s'\n", regno,
6508 reg_type_str(env, reg->type));
6512 if (t == BPF_WRITE && rdonly_mem) {
6513 verbose(env, "R%d cannot write into %s\n",
6514 regno, reg_type_str(env, reg->type));
6518 if (t == BPF_WRITE && value_regno >= 0 &&
6519 is_pointer_value(env, value_regno)) {
6520 verbose(env, "R%d leaks addr into mem\n", value_regno);
6524 err = check_mem_region_access(env, regno, off, size,
6525 reg->mem_size, false);
6526 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6527 mark_reg_unknown(env, regs, value_regno);
6528 } else if (reg->type == PTR_TO_CTX) {
6529 enum bpf_reg_type reg_type = SCALAR_VALUE;
6530 struct btf *btf = NULL;
6533 if (t == BPF_WRITE && value_regno >= 0 &&
6534 is_pointer_value(env, value_regno)) {
6535 verbose(env, "R%d leaks addr into ctx\n", value_regno);
6539 err = check_ptr_off_reg(env, reg, regno);
6543 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
6546 verbose_linfo(env, insn_idx, "; ");
6547 if (!err && t == BPF_READ && value_regno >= 0) {
6548 /* ctx access returns either a scalar, or a
6549 * PTR_TO_PACKET[_META,_END]. In the latter
6550 * case, we know the offset is zero.
6552 if (reg_type == SCALAR_VALUE) {
6553 mark_reg_unknown(env, regs, value_regno);
6555 mark_reg_known_zero(env, regs,
6557 if (type_may_be_null(reg_type))
6558 regs[value_regno].id = ++env->id_gen;
6559 /* A load of ctx field could have different
6560 * actual load size with the one encoded in the
6561 * insn. When the dst is PTR, it is for sure not
6564 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6565 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6566 regs[value_regno].btf = btf;
6567 regs[value_regno].btf_id = btf_id;
6570 regs[value_regno].type = reg_type;
6573 } else if (reg->type == PTR_TO_STACK) {
6574 /* Basic bounds checks. */
6575 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6579 state = func(env, reg);
6580 err = update_stack_depth(env, state, off);
6585 err = check_stack_read(env, regno, off, size,
6588 err = check_stack_write(env, regno, off, size,
6589 value_regno, insn_idx);
6590 } else if (reg_is_pkt_pointer(reg)) {
6591 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6592 verbose(env, "cannot write into packet\n");
6595 if (t == BPF_WRITE && value_regno >= 0 &&
6596 is_pointer_value(env, value_regno)) {
6597 verbose(env, "R%d leaks addr into packet\n",
6601 err = check_packet_access(env, regno, off, size, false);
6602 if (!err && t == BPF_READ && value_regno >= 0)
6603 mark_reg_unknown(env, regs, value_regno);
6604 } else if (reg->type == PTR_TO_FLOW_KEYS) {
6605 if (t == BPF_WRITE && value_regno >= 0 &&
6606 is_pointer_value(env, value_regno)) {
6607 verbose(env, "R%d leaks addr into flow keys\n",
6612 err = check_flow_keys_access(env, off, size);
6613 if (!err && t == BPF_READ && value_regno >= 0)
6614 mark_reg_unknown(env, regs, value_regno);
6615 } else if (type_is_sk_pointer(reg->type)) {
6616 if (t == BPF_WRITE) {
6617 verbose(env, "R%d cannot write into %s\n",
6618 regno, reg_type_str(env, reg->type));
6621 err = check_sock_access(env, insn_idx, regno, off, size, t);
6622 if (!err && value_regno >= 0)
6623 mark_reg_unknown(env, regs, value_regno);
6624 } else if (reg->type == PTR_TO_TP_BUFFER) {
6625 err = check_tp_buffer_access(env, reg, regno, off, size);
6626 if (!err && t == BPF_READ && value_regno >= 0)
6627 mark_reg_unknown(env, regs, value_regno);
6628 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6629 !type_may_be_null(reg->type)) {
6630 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6632 } else if (reg->type == CONST_PTR_TO_MAP) {
6633 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6635 } else if (base_type(reg->type) == PTR_TO_BUF) {
6636 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6640 if (t == BPF_WRITE) {
6641 verbose(env, "R%d cannot write into %s\n",
6642 regno, reg_type_str(env, reg->type));
6645 max_access = &env->prog->aux->max_rdonly_access;
6647 max_access = &env->prog->aux->max_rdwr_access;
6650 err = check_buffer_access(env, reg, regno, off, size, false,
6653 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6654 mark_reg_unknown(env, regs, value_regno);
6656 verbose(env, "R%d invalid mem access '%s'\n", regno,
6657 reg_type_str(env, reg->type));
6661 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6662 regs[value_regno].type == SCALAR_VALUE) {
6664 /* b/h/w load zero-extends, mark upper bits as known 0 */
6665 coerce_reg_to_size(®s[value_regno], size);
6667 coerce_reg_to_size_sx(®s[value_regno], size);
6672 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6677 switch (insn->imm) {
6679 case BPF_ADD | BPF_FETCH:
6681 case BPF_AND | BPF_FETCH:
6683 case BPF_OR | BPF_FETCH:
6685 case BPF_XOR | BPF_FETCH:
6690 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6694 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6695 verbose(env, "invalid atomic operand size\n");
6699 /* check src1 operand */
6700 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6704 /* check src2 operand */
6705 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6709 if (insn->imm == BPF_CMPXCHG) {
6710 /* Check comparison of R0 with memory location */
6711 const u32 aux_reg = BPF_REG_0;
6713 err = check_reg_arg(env, aux_reg, SRC_OP);
6717 if (is_pointer_value(env, aux_reg)) {
6718 verbose(env, "R%d leaks addr into mem\n", aux_reg);
6723 if (is_pointer_value(env, insn->src_reg)) {
6724 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6728 if (is_ctx_reg(env, insn->dst_reg) ||
6729 is_pkt_reg(env, insn->dst_reg) ||
6730 is_flow_key_reg(env, insn->dst_reg) ||
6731 is_sk_reg(env, insn->dst_reg)) {
6732 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6734 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6738 if (insn->imm & BPF_FETCH) {
6739 if (insn->imm == BPF_CMPXCHG)
6740 load_reg = BPF_REG_0;
6742 load_reg = insn->src_reg;
6744 /* check and record load of old value */
6745 err = check_reg_arg(env, load_reg, DST_OP);
6749 /* This instruction accesses a memory location but doesn't
6750 * actually load it into a register.
6755 /* Check whether we can read the memory, with second call for fetch
6756 * case to simulate the register fill.
6758 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6759 BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6760 if (!err && load_reg >= 0)
6761 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6762 BPF_SIZE(insn->code), BPF_READ, load_reg,
6767 /* Check whether we can write into the same memory. */
6768 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6769 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6776 /* When register 'regno' is used to read the stack (either directly or through
6777 * a helper function) make sure that it's within stack boundary and, depending
6778 * on the access type, that all elements of the stack are initialized.
6780 * 'off' includes 'regno->off', but not its dynamic part (if any).
6782 * All registers that have been spilled on the stack in the slots within the
6783 * read offsets are marked as read.
6785 static int check_stack_range_initialized(
6786 struct bpf_verifier_env *env, int regno, int off,
6787 int access_size, bool zero_size_allowed,
6788 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6790 struct bpf_reg_state *reg = reg_state(env, regno);
6791 struct bpf_func_state *state = func(env, reg);
6792 int err, min_off, max_off, i, j, slot, spi;
6793 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6794 enum bpf_access_type bounds_check_type;
6795 /* Some accesses can write anything into the stack, others are
6798 bool clobber = false;
6800 if (access_size == 0 && !zero_size_allowed) {
6801 verbose(env, "invalid zero-sized read\n");
6805 if (type == ACCESS_HELPER) {
6806 /* The bounds checks for writes are more permissive than for
6807 * reads. However, if raw_mode is not set, we'll do extra
6810 bounds_check_type = BPF_WRITE;
6813 bounds_check_type = BPF_READ;
6815 err = check_stack_access_within_bounds(env, regno, off, access_size,
6816 type, bounds_check_type);
6821 if (tnum_is_const(reg->var_off)) {
6822 min_off = max_off = reg->var_off.value + off;
6824 /* Variable offset is prohibited for unprivileged mode for
6825 * simplicity since it requires corresponding support in
6826 * Spectre masking for stack ALU.
6827 * See also retrieve_ptr_limit().
6829 if (!env->bypass_spec_v1) {
6832 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6833 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6834 regno, err_extra, tn_buf);
6837 /* Only initialized buffer on stack is allowed to be accessed
6838 * with variable offset. With uninitialized buffer it's hard to
6839 * guarantee that whole memory is marked as initialized on
6840 * helper return since specific bounds are unknown what may
6841 * cause uninitialized stack leaking.
6843 if (meta && meta->raw_mode)
6846 min_off = reg->smin_value + off;
6847 max_off = reg->smax_value + off;
6850 if (meta && meta->raw_mode) {
6851 /* Ensure we won't be overwriting dynptrs when simulating byte
6852 * by byte access in check_helper_call using meta.access_size.
6853 * This would be a problem if we have a helper in the future
6856 * helper(uninit_mem, len, dynptr)
6858 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6859 * may end up writing to dynptr itself when touching memory from
6860 * arg 1. This can be relaxed on a case by case basis for known
6861 * safe cases, but reject due to the possibilitiy of aliasing by
6864 for (i = min_off; i < max_off + access_size; i++) {
6865 int stack_off = -i - 1;
6868 /* raw_mode may write past allocated_stack */
6869 if (state->allocated_stack <= stack_off)
6871 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6872 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6876 meta->access_size = access_size;
6877 meta->regno = regno;
6881 for (i = min_off; i < max_off + access_size; i++) {
6885 spi = slot / BPF_REG_SIZE;
6886 if (state->allocated_stack <= slot)
6888 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6889 if (*stype == STACK_MISC)
6891 if ((*stype == STACK_ZERO) ||
6892 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6894 /* helper can write anything into the stack */
6895 *stype = STACK_MISC;
6900 if (is_spilled_reg(&state->stack[spi]) &&
6901 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6902 env->allow_ptr_leaks)) {
6904 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6905 for (j = 0; j < BPF_REG_SIZE; j++)
6906 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6912 if (tnum_is_const(reg->var_off)) {
6913 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6914 err_extra, regno, min_off, i - min_off, access_size);
6918 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6919 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6920 err_extra, regno, tn_buf, i - min_off, access_size);
6924 /* reading any byte out of 8-byte 'spill_slot' will cause
6925 * the whole slot to be marked as 'read'
6927 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6928 state->stack[spi].spilled_ptr.parent,
6930 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6931 * be sure that whether stack slot is written to or not. Hence,
6932 * we must still conservatively propagate reads upwards even if
6933 * helper may write to the entire memory range.
6936 return update_stack_depth(env, state, min_off);
6939 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6940 int access_size, bool zero_size_allowed,
6941 struct bpf_call_arg_meta *meta)
6943 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6946 switch (base_type(reg->type)) {
6948 case PTR_TO_PACKET_META:
6949 return check_packet_access(env, regno, reg->off, access_size,
6951 case PTR_TO_MAP_KEY:
6952 if (meta && meta->raw_mode) {
6953 verbose(env, "R%d cannot write into %s\n", regno,
6954 reg_type_str(env, reg->type));
6957 return check_mem_region_access(env, regno, reg->off, access_size,
6958 reg->map_ptr->key_size, false);
6959 case PTR_TO_MAP_VALUE:
6960 if (check_map_access_type(env, regno, reg->off, access_size,
6961 meta && meta->raw_mode ? BPF_WRITE :
6964 return check_map_access(env, regno, reg->off, access_size,
6965 zero_size_allowed, ACCESS_HELPER);
6967 if (type_is_rdonly_mem(reg->type)) {
6968 if (meta && meta->raw_mode) {
6969 verbose(env, "R%d cannot write into %s\n", regno,
6970 reg_type_str(env, reg->type));
6974 return check_mem_region_access(env, regno, reg->off,
6975 access_size, reg->mem_size,
6978 if (type_is_rdonly_mem(reg->type)) {
6979 if (meta && meta->raw_mode) {
6980 verbose(env, "R%d cannot write into %s\n", regno,
6981 reg_type_str(env, reg->type));
6985 max_access = &env->prog->aux->max_rdonly_access;
6987 max_access = &env->prog->aux->max_rdwr_access;
6989 return check_buffer_access(env, reg, regno, reg->off,
6990 access_size, zero_size_allowed,
6993 return check_stack_range_initialized(
6995 regno, reg->off, access_size,
6996 zero_size_allowed, ACCESS_HELPER, meta);
6998 return check_ptr_to_btf_access(env, regs, regno, reg->off,
6999 access_size, BPF_READ, -1);
7001 /* in case the function doesn't know how to access the context,
7002 * (because we are in a program of type SYSCALL for example), we
7003 * can not statically check its size.
7004 * Dynamically check it now.
7006 if (!env->ops->convert_ctx_access) {
7007 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7008 int offset = access_size - 1;
7010 /* Allow zero-byte read from PTR_TO_CTX */
7011 if (access_size == 0)
7012 return zero_size_allowed ? 0 : -EACCES;
7014 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7015 atype, -1, false, false);
7019 default: /* scalar_value or invalid ptr */
7020 /* Allow zero-byte read from NULL, regardless of pointer type */
7021 if (zero_size_allowed && access_size == 0 &&
7022 register_is_null(reg))
7025 verbose(env, "R%d type=%s ", regno,
7026 reg_type_str(env, reg->type));
7027 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7032 static int check_mem_size_reg(struct bpf_verifier_env *env,
7033 struct bpf_reg_state *reg, u32 regno,
7034 bool zero_size_allowed,
7035 struct bpf_call_arg_meta *meta)
7039 /* This is used to refine r0 return value bounds for helpers
7040 * that enforce this value as an upper bound on return values.
7041 * See do_refine_retval_range() for helpers that can refine
7042 * the return value. C type of helper is u32 so we pull register
7043 * bound from umax_value however, if negative verifier errors
7044 * out. Only upper bounds can be learned because retval is an
7045 * int type and negative retvals are allowed.
7047 meta->msize_max_value = reg->umax_value;
7049 /* The register is SCALAR_VALUE; the access check
7050 * happens using its boundaries.
7052 if (!tnum_is_const(reg->var_off))
7053 /* For unprivileged variable accesses, disable raw
7054 * mode so that the program is required to
7055 * initialize all the memory that the helper could
7056 * just partially fill up.
7060 if (reg->smin_value < 0) {
7061 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7066 if (reg->umin_value == 0) {
7067 err = check_helper_mem_access(env, regno - 1, 0,
7074 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7075 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7079 err = check_helper_mem_access(env, regno - 1,
7081 zero_size_allowed, meta);
7083 err = mark_chain_precision(env, regno);
7087 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7088 u32 regno, u32 mem_size)
7090 bool may_be_null = type_may_be_null(reg->type);
7091 struct bpf_reg_state saved_reg;
7092 struct bpf_call_arg_meta meta;
7095 if (register_is_null(reg))
7098 memset(&meta, 0, sizeof(meta));
7099 /* Assuming that the register contains a value check if the memory
7100 * access is safe. Temporarily save and restore the register's state as
7101 * the conversion shouldn't be visible to a caller.
7105 mark_ptr_not_null_reg(reg);
7108 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7109 /* Check access for BPF_WRITE */
7110 meta.raw_mode = true;
7111 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7119 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7122 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7123 bool may_be_null = type_may_be_null(mem_reg->type);
7124 struct bpf_reg_state saved_reg;
7125 struct bpf_call_arg_meta meta;
7128 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7130 memset(&meta, 0, sizeof(meta));
7133 saved_reg = *mem_reg;
7134 mark_ptr_not_null_reg(mem_reg);
7137 err = check_mem_size_reg(env, reg, regno, true, &meta);
7138 /* Check access for BPF_WRITE */
7139 meta.raw_mode = true;
7140 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7143 *mem_reg = saved_reg;
7147 /* Implementation details:
7148 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7149 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7150 * Two bpf_map_lookups (even with the same key) will have different reg->id.
7151 * Two separate bpf_obj_new will also have different reg->id.
7152 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7153 * clears reg->id after value_or_null->value transition, since the verifier only
7154 * cares about the range of access to valid map value pointer and doesn't care
7155 * about actual address of the map element.
7156 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7157 * reg->id > 0 after value_or_null->value transition. By doing so
7158 * two bpf_map_lookups will be considered two different pointers that
7159 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7160 * returned from bpf_obj_new.
7161 * The verifier allows taking only one bpf_spin_lock at a time to avoid
7163 * Since only one bpf_spin_lock is allowed the checks are simpler than
7164 * reg_is_refcounted() logic. The verifier needs to remember only
7165 * one spin_lock instead of array of acquired_refs.
7166 * cur_state->active_lock remembers which map value element or allocated
7167 * object got locked and clears it after bpf_spin_unlock.
7169 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7172 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7173 struct bpf_verifier_state *cur = env->cur_state;
7174 bool is_const = tnum_is_const(reg->var_off);
7175 u64 val = reg->var_off.value;
7176 struct bpf_map *map = NULL;
7177 struct btf *btf = NULL;
7178 struct btf_record *rec;
7182 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7186 if (reg->type == PTR_TO_MAP_VALUE) {
7190 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7198 rec = reg_btf_record(reg);
7199 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7200 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7201 map ? map->name : "kptr");
7204 if (rec->spin_lock_off != val + reg->off) {
7205 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7206 val + reg->off, rec->spin_lock_off);
7210 if (cur->active_lock.ptr) {
7212 "Locking two bpf_spin_locks are not allowed\n");
7216 cur->active_lock.ptr = map;
7218 cur->active_lock.ptr = btf;
7219 cur->active_lock.id = reg->id;
7228 if (!cur->active_lock.ptr) {
7229 verbose(env, "bpf_spin_unlock without taking a lock\n");
7232 if (cur->active_lock.ptr != ptr ||
7233 cur->active_lock.id != reg->id) {
7234 verbose(env, "bpf_spin_unlock of different lock\n");
7238 invalidate_non_owning_refs(env);
7240 cur->active_lock.ptr = NULL;
7241 cur->active_lock.id = 0;
7246 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7247 struct bpf_call_arg_meta *meta)
7249 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7250 bool is_const = tnum_is_const(reg->var_off);
7251 struct bpf_map *map = reg->map_ptr;
7252 u64 val = reg->var_off.value;
7256 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7261 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7265 if (!btf_record_has_field(map->record, BPF_TIMER)) {
7266 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7269 if (map->record->timer_off != val + reg->off) {
7270 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7271 val + reg->off, map->record->timer_off);
7274 if (meta->map_ptr) {
7275 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7278 meta->map_uid = reg->map_uid;
7279 meta->map_ptr = map;
7283 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7284 struct bpf_call_arg_meta *meta)
7286 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7287 struct bpf_map *map_ptr = reg->map_ptr;
7288 struct btf_field *kptr_field;
7291 if (!tnum_is_const(reg->var_off)) {
7293 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7297 if (!map_ptr->btf) {
7298 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7302 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7303 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7307 meta->map_ptr = map_ptr;
7308 kptr_off = reg->off + reg->var_off.value;
7309 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7311 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7314 if (kptr_field->type != BPF_KPTR_REF) {
7315 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7318 meta->kptr_field = kptr_field;
7322 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7323 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7325 * In both cases we deal with the first 8 bytes, but need to mark the next 8
7326 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7327 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7329 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7330 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7331 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7332 * mutate the view of the dynptr and also possibly destroy it. In the latter
7333 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7334 * memory that dynptr points to.
7336 * The verifier will keep track both levels of mutation (bpf_dynptr's in
7337 * reg->type and the memory's in reg->dynptr.type), but there is no support for
7338 * readonly dynptr view yet, hence only the first case is tracked and checked.
7340 * This is consistent with how C applies the const modifier to a struct object,
7341 * where the pointer itself inside bpf_dynptr becomes const but not what it
7344 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7345 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7347 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7348 enum bpf_arg_type arg_type, int clone_ref_obj_id)
7350 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7353 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7354 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7356 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7357 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7361 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
7362 * constructing a mutable bpf_dynptr object.
7364 * Currently, this is only possible with PTR_TO_STACK
7365 * pointing to a region of at least 16 bytes which doesn't
7366 * contain an existing bpf_dynptr.
7368 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7369 * mutated or destroyed. However, the memory it points to
7372 * None - Points to a initialized dynptr that can be mutated and
7373 * destroyed, including mutation of the memory it points
7376 if (arg_type & MEM_UNINIT) {
7379 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7380 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7384 /* we write BPF_DW bits (8 bytes) at a time */
7385 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7386 err = check_mem_access(env, insn_idx, regno,
7387 i, BPF_DW, BPF_WRITE, -1, false, false);
7392 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7393 } else /* MEM_RDONLY and None case from above */ {
7394 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7395 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7396 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7400 if (!is_dynptr_reg_valid_init(env, reg)) {
7402 "Expected an initialized dynptr as arg #%d\n",
7407 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7408 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7410 "Expected a dynptr of type %s as arg #%d\n",
7411 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7415 err = mark_dynptr_read(env, reg);
7420 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7422 struct bpf_func_state *state = func(env, reg);
7424 return state->stack[spi].spilled_ptr.ref_obj_id;
7427 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7429 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7432 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7434 return meta->kfunc_flags & KF_ITER_NEW;
7437 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7439 return meta->kfunc_flags & KF_ITER_NEXT;
7442 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7444 return meta->kfunc_flags & KF_ITER_DESTROY;
7447 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7449 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7450 * kfunc is iter state pointer
7452 return arg == 0 && is_iter_kfunc(meta);
7455 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7456 struct bpf_kfunc_call_arg_meta *meta)
7458 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7459 const struct btf_type *t;
7460 const struct btf_param *arg;
7461 int spi, err, i, nr_slots;
7464 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7465 arg = &btf_params(meta->func_proto)[0];
7466 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
7467 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
7468 nr_slots = t->size / BPF_REG_SIZE;
7470 if (is_iter_new_kfunc(meta)) {
7471 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7472 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7473 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7474 iter_type_str(meta->btf, btf_id), regno);
7478 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7479 err = check_mem_access(env, insn_idx, regno,
7480 i, BPF_DW, BPF_WRITE, -1, false, false);
7485 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7489 /* iter_next() or iter_destroy() expect initialized iter state*/
7490 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7491 verbose(env, "expected an initialized iter_%s as arg #%d\n",
7492 iter_type_str(meta->btf, btf_id), regno);
7496 spi = iter_get_spi(env, reg, nr_slots);
7500 err = mark_iter_read(env, reg, spi, nr_slots);
7504 /* remember meta->iter info for process_iter_next_call() */
7505 meta->iter.spi = spi;
7506 meta->iter.frameno = reg->frameno;
7507 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7509 if (is_iter_destroy_kfunc(meta)) {
7510 err = unmark_stack_slots_iter(env, reg, nr_slots);
7519 /* process_iter_next_call() is called when verifier gets to iterator's next
7520 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7521 * to it as just "iter_next()" in comments below.
7523 * BPF verifier relies on a crucial contract for any iter_next()
7524 * implementation: it should *eventually* return NULL, and once that happens
7525 * it should keep returning NULL. That is, once iterator exhausts elements to
7526 * iterate, it should never reset or spuriously return new elements.
7528 * With the assumption of such contract, process_iter_next_call() simulates
7529 * a fork in the verifier state to validate loop logic correctness and safety
7530 * without having to simulate infinite amount of iterations.
7532 * In current state, we first assume that iter_next() returned NULL and
7533 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7534 * conditions we should not form an infinite loop and should eventually reach
7537 * Besides that, we also fork current state and enqueue it for later
7538 * verification. In a forked state we keep iterator state as ACTIVE
7539 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7540 * also bump iteration depth to prevent erroneous infinite loop detection
7541 * later on (see iter_active_depths_differ() comment for details). In this
7542 * state we assume that we'll eventually loop back to another iter_next()
7543 * calls (it could be in exactly same location or in some other instruction,
7544 * it doesn't matter, we don't make any unnecessary assumptions about this,
7545 * everything revolves around iterator state in a stack slot, not which
7546 * instruction is calling iter_next()). When that happens, we either will come
7547 * to iter_next() with equivalent state and can conclude that next iteration
7548 * will proceed in exactly the same way as we just verified, so it's safe to
7549 * assume that loop converges. If not, we'll go on another iteration
7550 * simulation with a different input state, until all possible starting states
7551 * are validated or we reach maximum number of instructions limit.
7553 * This way, we will either exhaustively discover all possible input states
7554 * that iterator loop can start with and eventually will converge, or we'll
7555 * effectively regress into bounded loop simulation logic and either reach
7556 * maximum number of instructions if loop is not provably convergent, or there
7557 * is some statically known limit on number of iterations (e.g., if there is
7558 * an explicit `if n > 100 then break;` statement somewhere in the loop).
7560 * One very subtle but very important aspect is that we *always* simulate NULL
7561 * condition first (as the current state) before we simulate non-NULL case.
7562 * This has to do with intricacies of scalar precision tracking. By simulating
7563 * "exit condition" of iter_next() returning NULL first, we make sure all the
7564 * relevant precision marks *that will be set **after** we exit iterator loop*
7565 * are propagated backwards to common parent state of NULL and non-NULL
7566 * branches. Thanks to that, state equivalence checks done later in forked
7567 * state, when reaching iter_next() for ACTIVE iterator, can assume that
7568 * precision marks are finalized and won't change. Because simulating another
7569 * ACTIVE iterator iteration won't change them (because given same input
7570 * states we'll end up with exactly same output states which we are currently
7571 * comparing; and verification after the loop already propagated back what
7572 * needs to be **additionally** tracked as precise). It's subtle, grok
7573 * precision tracking for more intuitive understanding.
7575 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7576 struct bpf_kfunc_call_arg_meta *meta)
7578 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7579 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7580 struct bpf_reg_state *cur_iter, *queued_iter;
7581 int iter_frameno = meta->iter.frameno;
7582 int iter_spi = meta->iter.spi;
7584 BTF_TYPE_EMIT(struct bpf_iter);
7586 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7588 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7589 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7590 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7591 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7595 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7596 /* branch out active iter state */
7597 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7601 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7602 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7603 queued_iter->iter.depth++;
7605 queued_fr = queued_st->frame[queued_st->curframe];
7606 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7609 /* switch to DRAINED state, but keep the depth unchanged */
7610 /* mark current iter state as drained and assume returned NULL */
7611 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7612 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7617 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7619 return type == ARG_CONST_SIZE ||
7620 type == ARG_CONST_SIZE_OR_ZERO;
7623 static bool arg_type_is_release(enum bpf_arg_type type)
7625 return type & OBJ_RELEASE;
7628 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7630 return base_type(type) == ARG_PTR_TO_DYNPTR;
7633 static int int_ptr_type_to_size(enum bpf_arg_type type)
7635 if (type == ARG_PTR_TO_INT)
7637 else if (type == ARG_PTR_TO_LONG)
7643 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7644 const struct bpf_call_arg_meta *meta,
7645 enum bpf_arg_type *arg_type)
7647 if (!meta->map_ptr) {
7648 /* kernel subsystem misconfigured verifier */
7649 verbose(env, "invalid map_ptr to access map->type\n");
7653 switch (meta->map_ptr->map_type) {
7654 case BPF_MAP_TYPE_SOCKMAP:
7655 case BPF_MAP_TYPE_SOCKHASH:
7656 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7657 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7659 verbose(env, "invalid arg_type for sockmap/sockhash\n");
7663 case BPF_MAP_TYPE_BLOOM_FILTER:
7664 if (meta->func_id == BPF_FUNC_map_peek_elem)
7665 *arg_type = ARG_PTR_TO_MAP_VALUE;
7673 struct bpf_reg_types {
7674 const enum bpf_reg_type types[10];
7678 static const struct bpf_reg_types sock_types = {
7688 static const struct bpf_reg_types btf_id_sock_common_types = {
7695 PTR_TO_BTF_ID | PTR_TRUSTED,
7697 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7701 static const struct bpf_reg_types mem_types = {
7709 PTR_TO_MEM | MEM_RINGBUF,
7711 PTR_TO_BTF_ID | PTR_TRUSTED,
7715 static const struct bpf_reg_types int_ptr_types = {
7725 static const struct bpf_reg_types spin_lock_types = {
7728 PTR_TO_BTF_ID | MEM_ALLOC,
7732 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7733 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7734 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7735 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7736 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7737 static const struct bpf_reg_types btf_ptr_types = {
7740 PTR_TO_BTF_ID | PTR_TRUSTED,
7741 PTR_TO_BTF_ID | MEM_RCU,
7744 static const struct bpf_reg_types percpu_btf_ptr_types = {
7746 PTR_TO_BTF_ID | MEM_PERCPU,
7747 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7750 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7751 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7752 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7753 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7754 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7755 static const struct bpf_reg_types dynptr_types = {
7758 CONST_PTR_TO_DYNPTR,
7762 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7763 [ARG_PTR_TO_MAP_KEY] = &mem_types,
7764 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
7765 [ARG_CONST_SIZE] = &scalar_types,
7766 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
7767 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
7768 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
7769 [ARG_PTR_TO_CTX] = &context_types,
7770 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
7772 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
7774 [ARG_PTR_TO_SOCKET] = &fullsock_types,
7775 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
7776 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
7777 [ARG_PTR_TO_MEM] = &mem_types,
7778 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
7779 [ARG_PTR_TO_INT] = &int_ptr_types,
7780 [ARG_PTR_TO_LONG] = &int_ptr_types,
7781 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
7782 [ARG_PTR_TO_FUNC] = &func_ptr_types,
7783 [ARG_PTR_TO_STACK] = &stack_ptr_types,
7784 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
7785 [ARG_PTR_TO_TIMER] = &timer_types,
7786 [ARG_PTR_TO_KPTR] = &kptr_types,
7787 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
7790 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7791 enum bpf_arg_type arg_type,
7792 const u32 *arg_btf_id,
7793 struct bpf_call_arg_meta *meta)
7795 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7796 enum bpf_reg_type expected, type = reg->type;
7797 const struct bpf_reg_types *compatible;
7800 compatible = compatible_reg_types[base_type(arg_type)];
7802 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7806 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7807 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7809 * Same for MAYBE_NULL:
7811 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7812 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7814 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7816 * Therefore we fold these flags depending on the arg_type before comparison.
7818 if (arg_type & MEM_RDONLY)
7819 type &= ~MEM_RDONLY;
7820 if (arg_type & PTR_MAYBE_NULL)
7821 type &= ~PTR_MAYBE_NULL;
7822 if (base_type(arg_type) == ARG_PTR_TO_MEM)
7823 type &= ~DYNPTR_TYPE_FLAG_MASK;
7825 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
7828 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7829 expected = compatible->types[i];
7830 if (expected == NOT_INIT)
7833 if (type == expected)
7837 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7838 for (j = 0; j + 1 < i; j++)
7839 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7840 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7844 if (base_type(reg->type) != PTR_TO_BTF_ID)
7847 if (compatible == &mem_types) {
7848 if (!(arg_type & MEM_RDONLY)) {
7850 "%s() may write into memory pointed by R%d type=%s\n",
7851 func_id_name(meta->func_id),
7852 regno, reg_type_str(env, reg->type));
7858 switch ((int)reg->type) {
7860 case PTR_TO_BTF_ID | PTR_TRUSTED:
7861 case PTR_TO_BTF_ID | MEM_RCU:
7862 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7863 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7865 /* For bpf_sk_release, it needs to match against first member
7866 * 'struct sock_common', hence make an exception for it. This
7867 * allows bpf_sk_release to work for multiple socket types.
7869 bool strict_type_match = arg_type_is_release(arg_type) &&
7870 meta->func_id != BPF_FUNC_sk_release;
7872 if (type_may_be_null(reg->type) &&
7873 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7874 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7879 if (!compatible->btf_id) {
7880 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7883 arg_btf_id = compatible->btf_id;
7886 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7887 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7890 if (arg_btf_id == BPF_PTR_POISON) {
7891 verbose(env, "verifier internal error:");
7892 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7897 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7898 btf_vmlinux, *arg_btf_id,
7899 strict_type_match)) {
7900 verbose(env, "R%d is of type %s but %s is expected\n",
7901 regno, btf_type_name(reg->btf, reg->btf_id),
7902 btf_type_name(btf_vmlinux, *arg_btf_id));
7908 case PTR_TO_BTF_ID | MEM_ALLOC:
7909 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7910 meta->func_id != BPF_FUNC_kptr_xchg) {
7911 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7914 /* Handled by helper specific checks */
7916 case PTR_TO_BTF_ID | MEM_PERCPU:
7917 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7918 /* Handled by helper specific checks */
7921 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7927 static struct btf_field *
7928 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7930 struct btf_field *field;
7931 struct btf_record *rec;
7933 rec = reg_btf_record(reg);
7937 field = btf_record_find(rec, off, fields);
7944 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7945 const struct bpf_reg_state *reg, int regno,
7946 enum bpf_arg_type arg_type)
7948 u32 type = reg->type;
7950 /* When referenced register is passed to release function, its fixed
7953 * We will check arg_type_is_release reg has ref_obj_id when storing
7954 * meta->release_regno.
7956 if (arg_type_is_release(arg_type)) {
7957 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7958 * may not directly point to the object being released, but to
7959 * dynptr pointing to such object, which might be at some offset
7960 * on the stack. In that case, we simply to fallback to the
7963 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7966 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7967 if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7968 return __check_ptr_off_reg(env, reg, regno, true);
7970 verbose(env, "R%d must have zero offset when passed to release func\n",
7972 verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7973 btf_type_name(reg->btf, reg->btf_id), reg->off);
7977 /* Doing check_ptr_off_reg check for the offset will catch this
7978 * because fixed_off_ok is false, but checking here allows us
7979 * to give the user a better error message.
7982 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7986 return __check_ptr_off_reg(env, reg, regno, false);
7990 /* Pointer types where both fixed and variable offset is explicitly allowed: */
7993 case PTR_TO_PACKET_META:
7994 case PTR_TO_MAP_KEY:
7995 case PTR_TO_MAP_VALUE:
7997 case PTR_TO_MEM | MEM_RDONLY:
7998 case PTR_TO_MEM | MEM_RINGBUF:
8000 case PTR_TO_BUF | MEM_RDONLY:
8003 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8007 case PTR_TO_BTF_ID | MEM_ALLOC:
8008 case PTR_TO_BTF_ID | PTR_TRUSTED:
8009 case PTR_TO_BTF_ID | MEM_RCU:
8010 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8011 /* When referenced PTR_TO_BTF_ID is passed to release function,
8012 * its fixed offset must be 0. In the other cases, fixed offset
8013 * can be non-zero. This was already checked above. So pass
8014 * fixed_off_ok as true to allow fixed offset for all other
8015 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8016 * still need to do checks instead of returning.
8018 return __check_ptr_off_reg(env, reg, regno, true);
8020 return __check_ptr_off_reg(env, reg, regno, false);
8024 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8025 const struct bpf_func_proto *fn,
8026 struct bpf_reg_state *regs)
8028 struct bpf_reg_state *state = NULL;
8031 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8032 if (arg_type_is_dynptr(fn->arg_type[i])) {
8034 verbose(env, "verifier internal error: multiple dynptr args\n");
8037 state = ®s[BPF_REG_1 + i];
8041 verbose(env, "verifier internal error: no dynptr arg found\n");
8046 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8048 struct bpf_func_state *state = func(env, reg);
8051 if (reg->type == CONST_PTR_TO_DYNPTR)
8053 spi = dynptr_get_spi(env, reg);
8056 return state->stack[spi].spilled_ptr.id;
8059 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8061 struct bpf_func_state *state = func(env, reg);
8064 if (reg->type == CONST_PTR_TO_DYNPTR)
8065 return reg->ref_obj_id;
8066 spi = dynptr_get_spi(env, reg);
8069 return state->stack[spi].spilled_ptr.ref_obj_id;
8072 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8073 struct bpf_reg_state *reg)
8075 struct bpf_func_state *state = func(env, reg);
8078 if (reg->type == CONST_PTR_TO_DYNPTR)
8079 return reg->dynptr.type;
8081 spi = __get_spi(reg->off);
8083 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8084 return BPF_DYNPTR_TYPE_INVALID;
8087 return state->stack[spi].spilled_ptr.dynptr.type;
8090 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8091 struct bpf_call_arg_meta *meta,
8092 const struct bpf_func_proto *fn,
8095 u32 regno = BPF_REG_1 + arg;
8096 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8097 enum bpf_arg_type arg_type = fn->arg_type[arg];
8098 enum bpf_reg_type type = reg->type;
8099 u32 *arg_btf_id = NULL;
8102 if (arg_type == ARG_DONTCARE)
8105 err = check_reg_arg(env, regno, SRC_OP);
8109 if (arg_type == ARG_ANYTHING) {
8110 if (is_pointer_value(env, regno)) {
8111 verbose(env, "R%d leaks addr into helper function\n",
8118 if (type_is_pkt_pointer(type) &&
8119 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8120 verbose(env, "helper access to the packet is not allowed\n");
8124 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8125 err = resolve_map_arg_type(env, meta, &arg_type);
8130 if (register_is_null(reg) && type_may_be_null(arg_type))
8131 /* A NULL register has a SCALAR_VALUE type, so skip
8134 goto skip_type_check;
8136 /* arg_btf_id and arg_size are in a union. */
8137 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8138 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8139 arg_btf_id = fn->arg_btf_id[arg];
8141 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8145 err = check_func_arg_reg_off(env, reg, regno, arg_type);
8150 if (arg_type_is_release(arg_type)) {
8151 if (arg_type_is_dynptr(arg_type)) {
8152 struct bpf_func_state *state = func(env, reg);
8155 /* Only dynptr created on stack can be released, thus
8156 * the get_spi and stack state checks for spilled_ptr
8157 * should only be done before process_dynptr_func for
8160 if (reg->type == PTR_TO_STACK) {
8161 spi = dynptr_get_spi(env, reg);
8162 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8163 verbose(env, "arg %d is an unacquired reference\n", regno);
8167 verbose(env, "cannot release unowned const bpf_dynptr\n");
8170 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8171 verbose(env, "R%d must be referenced when passed to release function\n",
8175 if (meta->release_regno) {
8176 verbose(env, "verifier internal error: more than one release argument\n");
8179 meta->release_regno = regno;
8182 if (reg->ref_obj_id) {
8183 if (meta->ref_obj_id) {
8184 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8185 regno, reg->ref_obj_id,
8189 meta->ref_obj_id = reg->ref_obj_id;
8192 switch (base_type(arg_type)) {
8193 case ARG_CONST_MAP_PTR:
8194 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8195 if (meta->map_ptr) {
8196 /* Use map_uid (which is unique id of inner map) to reject:
8197 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8198 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8199 * if (inner_map1 && inner_map2) {
8200 * timer = bpf_map_lookup_elem(inner_map1);
8202 * // mismatch would have been allowed
8203 * bpf_timer_init(timer, inner_map2);
8206 * Comparing map_ptr is enough to distinguish normal and outer maps.
8208 if (meta->map_ptr != reg->map_ptr ||
8209 meta->map_uid != reg->map_uid) {
8211 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8212 meta->map_uid, reg->map_uid);
8216 meta->map_ptr = reg->map_ptr;
8217 meta->map_uid = reg->map_uid;
8219 case ARG_PTR_TO_MAP_KEY:
8220 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8221 * check that [key, key + map->key_size) are within
8222 * stack limits and initialized
8224 if (!meta->map_ptr) {
8225 /* in function declaration map_ptr must come before
8226 * map_key, so that it's verified and known before
8227 * we have to check map_key here. Otherwise it means
8228 * that kernel subsystem misconfigured verifier
8230 verbose(env, "invalid map_ptr to access map->key\n");
8233 err = check_helper_mem_access(env, regno,
8234 meta->map_ptr->key_size, false,
8237 case ARG_PTR_TO_MAP_VALUE:
8238 if (type_may_be_null(arg_type) && register_is_null(reg))
8241 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8242 * check [value, value + map->value_size) validity
8244 if (!meta->map_ptr) {
8245 /* kernel subsystem misconfigured verifier */
8246 verbose(env, "invalid map_ptr to access map->value\n");
8249 meta->raw_mode = arg_type & MEM_UNINIT;
8250 err = check_helper_mem_access(env, regno,
8251 meta->map_ptr->value_size, false,
8254 case ARG_PTR_TO_PERCPU_BTF_ID:
8256 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8259 meta->ret_btf = reg->btf;
8260 meta->ret_btf_id = reg->btf_id;
8262 case ARG_PTR_TO_SPIN_LOCK:
8263 if (in_rbtree_lock_required_cb(env)) {
8264 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8267 if (meta->func_id == BPF_FUNC_spin_lock) {
8268 err = process_spin_lock(env, regno, true);
8271 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8272 err = process_spin_lock(env, regno, false);
8276 verbose(env, "verifier internal error\n");
8280 case ARG_PTR_TO_TIMER:
8281 err = process_timer_func(env, regno, meta);
8285 case ARG_PTR_TO_FUNC:
8286 meta->subprogno = reg->subprogno;
8288 case ARG_PTR_TO_MEM:
8289 /* The access to this pointer is only checked when we hit the
8290 * next is_mem_size argument below.
8292 meta->raw_mode = arg_type & MEM_UNINIT;
8293 if (arg_type & MEM_FIXED_SIZE) {
8294 err = check_helper_mem_access(env, regno,
8295 fn->arg_size[arg], false,
8299 case ARG_CONST_SIZE:
8300 err = check_mem_size_reg(env, reg, regno, false, meta);
8302 case ARG_CONST_SIZE_OR_ZERO:
8303 err = check_mem_size_reg(env, reg, regno, true, meta);
8305 case ARG_PTR_TO_DYNPTR:
8306 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8310 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8311 if (!tnum_is_const(reg->var_off)) {
8312 verbose(env, "R%d is not a known constant'\n",
8316 meta->mem_size = reg->var_off.value;
8317 err = mark_chain_precision(env, regno);
8321 case ARG_PTR_TO_INT:
8322 case ARG_PTR_TO_LONG:
8324 int size = int_ptr_type_to_size(arg_type);
8326 err = check_helper_mem_access(env, regno, size, false, meta);
8329 err = check_ptr_alignment(env, reg, 0, size, true);
8332 case ARG_PTR_TO_CONST_STR:
8334 struct bpf_map *map = reg->map_ptr;
8339 if (!bpf_map_is_rdonly(map)) {
8340 verbose(env, "R%d does not point to a readonly map'\n", regno);
8344 if (!tnum_is_const(reg->var_off)) {
8345 verbose(env, "R%d is not a constant address'\n", regno);
8349 if (!map->ops->map_direct_value_addr) {
8350 verbose(env, "no direct value access support for this map type\n");
8354 err = check_map_access(env, regno, reg->off,
8355 map->value_size - reg->off, false,
8360 map_off = reg->off + reg->var_off.value;
8361 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8363 verbose(env, "direct value access on string failed\n");
8367 str_ptr = (char *)(long)(map_addr);
8368 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8369 verbose(env, "string is not zero-terminated\n");
8374 case ARG_PTR_TO_KPTR:
8375 err = process_kptr_func(env, regno, meta);
8384 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8386 enum bpf_attach_type eatype = env->prog->expected_attach_type;
8387 enum bpf_prog_type type = resolve_prog_type(env->prog);
8389 if (func_id != BPF_FUNC_map_update_elem)
8392 /* It's not possible to get access to a locked struct sock in these
8393 * contexts, so updating is safe.
8396 case BPF_PROG_TYPE_TRACING:
8397 if (eatype == BPF_TRACE_ITER)
8400 case BPF_PROG_TYPE_SOCKET_FILTER:
8401 case BPF_PROG_TYPE_SCHED_CLS:
8402 case BPF_PROG_TYPE_SCHED_ACT:
8403 case BPF_PROG_TYPE_XDP:
8404 case BPF_PROG_TYPE_SK_REUSEPORT:
8405 case BPF_PROG_TYPE_FLOW_DISSECTOR:
8406 case BPF_PROG_TYPE_SK_LOOKUP:
8412 verbose(env, "cannot update sockmap in this context\n");
8416 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8418 return env->prog->jit_requested &&
8419 bpf_jit_supports_subprog_tailcalls();
8422 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8423 struct bpf_map *map, int func_id)
8428 /* We need a two way check, first is from map perspective ... */
8429 switch (map->map_type) {
8430 case BPF_MAP_TYPE_PROG_ARRAY:
8431 if (func_id != BPF_FUNC_tail_call)
8434 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8435 if (func_id != BPF_FUNC_perf_event_read &&
8436 func_id != BPF_FUNC_perf_event_output &&
8437 func_id != BPF_FUNC_skb_output &&
8438 func_id != BPF_FUNC_perf_event_read_value &&
8439 func_id != BPF_FUNC_xdp_output)
8442 case BPF_MAP_TYPE_RINGBUF:
8443 if (func_id != BPF_FUNC_ringbuf_output &&
8444 func_id != BPF_FUNC_ringbuf_reserve &&
8445 func_id != BPF_FUNC_ringbuf_query &&
8446 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8447 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8448 func_id != BPF_FUNC_ringbuf_discard_dynptr)
8451 case BPF_MAP_TYPE_USER_RINGBUF:
8452 if (func_id != BPF_FUNC_user_ringbuf_drain)
8455 case BPF_MAP_TYPE_STACK_TRACE:
8456 if (func_id != BPF_FUNC_get_stackid)
8459 case BPF_MAP_TYPE_CGROUP_ARRAY:
8460 if (func_id != BPF_FUNC_skb_under_cgroup &&
8461 func_id != BPF_FUNC_current_task_under_cgroup)
8464 case BPF_MAP_TYPE_CGROUP_STORAGE:
8465 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8466 if (func_id != BPF_FUNC_get_local_storage)
8469 case BPF_MAP_TYPE_DEVMAP:
8470 case BPF_MAP_TYPE_DEVMAP_HASH:
8471 if (func_id != BPF_FUNC_redirect_map &&
8472 func_id != BPF_FUNC_map_lookup_elem)
8475 /* Restrict bpf side of cpumap and xskmap, open when use-cases
8478 case BPF_MAP_TYPE_CPUMAP:
8479 if (func_id != BPF_FUNC_redirect_map)
8482 case BPF_MAP_TYPE_XSKMAP:
8483 if (func_id != BPF_FUNC_redirect_map &&
8484 func_id != BPF_FUNC_map_lookup_elem)
8487 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8488 case BPF_MAP_TYPE_HASH_OF_MAPS:
8489 if (func_id != BPF_FUNC_map_lookup_elem)
8492 case BPF_MAP_TYPE_SOCKMAP:
8493 if (func_id != BPF_FUNC_sk_redirect_map &&
8494 func_id != BPF_FUNC_sock_map_update &&
8495 func_id != BPF_FUNC_map_delete_elem &&
8496 func_id != BPF_FUNC_msg_redirect_map &&
8497 func_id != BPF_FUNC_sk_select_reuseport &&
8498 func_id != BPF_FUNC_map_lookup_elem &&
8499 !may_update_sockmap(env, func_id))
8502 case BPF_MAP_TYPE_SOCKHASH:
8503 if (func_id != BPF_FUNC_sk_redirect_hash &&
8504 func_id != BPF_FUNC_sock_hash_update &&
8505 func_id != BPF_FUNC_map_delete_elem &&
8506 func_id != BPF_FUNC_msg_redirect_hash &&
8507 func_id != BPF_FUNC_sk_select_reuseport &&
8508 func_id != BPF_FUNC_map_lookup_elem &&
8509 !may_update_sockmap(env, func_id))
8512 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8513 if (func_id != BPF_FUNC_sk_select_reuseport)
8516 case BPF_MAP_TYPE_QUEUE:
8517 case BPF_MAP_TYPE_STACK:
8518 if (func_id != BPF_FUNC_map_peek_elem &&
8519 func_id != BPF_FUNC_map_pop_elem &&
8520 func_id != BPF_FUNC_map_push_elem)
8523 case BPF_MAP_TYPE_SK_STORAGE:
8524 if (func_id != BPF_FUNC_sk_storage_get &&
8525 func_id != BPF_FUNC_sk_storage_delete &&
8526 func_id != BPF_FUNC_kptr_xchg)
8529 case BPF_MAP_TYPE_INODE_STORAGE:
8530 if (func_id != BPF_FUNC_inode_storage_get &&
8531 func_id != BPF_FUNC_inode_storage_delete &&
8532 func_id != BPF_FUNC_kptr_xchg)
8535 case BPF_MAP_TYPE_TASK_STORAGE:
8536 if (func_id != BPF_FUNC_task_storage_get &&
8537 func_id != BPF_FUNC_task_storage_delete &&
8538 func_id != BPF_FUNC_kptr_xchg)
8541 case BPF_MAP_TYPE_CGRP_STORAGE:
8542 if (func_id != BPF_FUNC_cgrp_storage_get &&
8543 func_id != BPF_FUNC_cgrp_storage_delete &&
8544 func_id != BPF_FUNC_kptr_xchg)
8547 case BPF_MAP_TYPE_BLOOM_FILTER:
8548 if (func_id != BPF_FUNC_map_peek_elem &&
8549 func_id != BPF_FUNC_map_push_elem)
8556 /* ... and second from the function itself. */
8558 case BPF_FUNC_tail_call:
8559 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8561 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8562 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8566 case BPF_FUNC_perf_event_read:
8567 case BPF_FUNC_perf_event_output:
8568 case BPF_FUNC_perf_event_read_value:
8569 case BPF_FUNC_skb_output:
8570 case BPF_FUNC_xdp_output:
8571 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8574 case BPF_FUNC_ringbuf_output:
8575 case BPF_FUNC_ringbuf_reserve:
8576 case BPF_FUNC_ringbuf_query:
8577 case BPF_FUNC_ringbuf_reserve_dynptr:
8578 case BPF_FUNC_ringbuf_submit_dynptr:
8579 case BPF_FUNC_ringbuf_discard_dynptr:
8580 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8583 case BPF_FUNC_user_ringbuf_drain:
8584 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8587 case BPF_FUNC_get_stackid:
8588 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8591 case BPF_FUNC_current_task_under_cgroup:
8592 case BPF_FUNC_skb_under_cgroup:
8593 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8596 case BPF_FUNC_redirect_map:
8597 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8598 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8599 map->map_type != BPF_MAP_TYPE_CPUMAP &&
8600 map->map_type != BPF_MAP_TYPE_XSKMAP)
8603 case BPF_FUNC_sk_redirect_map:
8604 case BPF_FUNC_msg_redirect_map:
8605 case BPF_FUNC_sock_map_update:
8606 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8609 case BPF_FUNC_sk_redirect_hash:
8610 case BPF_FUNC_msg_redirect_hash:
8611 case BPF_FUNC_sock_hash_update:
8612 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8615 case BPF_FUNC_get_local_storage:
8616 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8617 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8620 case BPF_FUNC_sk_select_reuseport:
8621 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8622 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8623 map->map_type != BPF_MAP_TYPE_SOCKHASH)
8626 case BPF_FUNC_map_pop_elem:
8627 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8628 map->map_type != BPF_MAP_TYPE_STACK)
8631 case BPF_FUNC_map_peek_elem:
8632 case BPF_FUNC_map_push_elem:
8633 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8634 map->map_type != BPF_MAP_TYPE_STACK &&
8635 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8638 case BPF_FUNC_map_lookup_percpu_elem:
8639 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8640 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8641 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8644 case BPF_FUNC_sk_storage_get:
8645 case BPF_FUNC_sk_storage_delete:
8646 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8649 case BPF_FUNC_inode_storage_get:
8650 case BPF_FUNC_inode_storage_delete:
8651 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8654 case BPF_FUNC_task_storage_get:
8655 case BPF_FUNC_task_storage_delete:
8656 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8659 case BPF_FUNC_cgrp_storage_get:
8660 case BPF_FUNC_cgrp_storage_delete:
8661 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8670 verbose(env, "cannot pass map_type %d into func %s#%d\n",
8671 map->map_type, func_id_name(func_id), func_id);
8675 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8679 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8681 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8683 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8685 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8687 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8690 /* We only support one arg being in raw mode at the moment,
8691 * which is sufficient for the helper functions we have
8697 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8699 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8700 bool has_size = fn->arg_size[arg] != 0;
8701 bool is_next_size = false;
8703 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8704 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8706 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8707 return is_next_size;
8709 return has_size == is_next_size || is_next_size == is_fixed;
8712 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8714 /* bpf_xxx(..., buf, len) call will access 'len'
8715 * bytes from memory 'buf'. Both arg types need
8716 * to be paired, so make sure there's no buggy
8717 * helper function specification.
8719 if (arg_type_is_mem_size(fn->arg1_type) ||
8720 check_args_pair_invalid(fn, 0) ||
8721 check_args_pair_invalid(fn, 1) ||
8722 check_args_pair_invalid(fn, 2) ||
8723 check_args_pair_invalid(fn, 3) ||
8724 check_args_pair_invalid(fn, 4))
8730 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8734 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8735 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8736 return !!fn->arg_btf_id[i];
8737 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8738 return fn->arg_btf_id[i] == BPF_PTR_POISON;
8739 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8740 /* arg_btf_id and arg_size are in a union. */
8741 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8742 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8749 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8751 return check_raw_mode_ok(fn) &&
8752 check_arg_pair_ok(fn) &&
8753 check_btf_id_ok(fn) ? 0 : -EINVAL;
8756 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8757 * are now invalid, so turn them into unknown SCALAR_VALUE.
8759 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8760 * since these slices point to packet data.
8762 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8764 struct bpf_func_state *state;
8765 struct bpf_reg_state *reg;
8767 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8768 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8769 mark_reg_invalid(env, reg);
8775 BEYOND_PKT_END = -2,
8778 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8780 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8781 struct bpf_reg_state *reg = &state->regs[regn];
8783 if (reg->type != PTR_TO_PACKET)
8784 /* PTR_TO_PACKET_META is not supported yet */
8787 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8788 * How far beyond pkt_end it goes is unknown.
8789 * if (!range_open) it's the case of pkt >= pkt_end
8790 * if (range_open) it's the case of pkt > pkt_end
8791 * hence this pointer is at least 1 byte bigger than pkt_end
8794 reg->range = BEYOND_PKT_END;
8796 reg->range = AT_PKT_END;
8799 /* The pointer with the specified id has released its reference to kernel
8800 * resources. Identify all copies of the same pointer and clear the reference.
8802 static int release_reference(struct bpf_verifier_env *env,
8805 struct bpf_func_state *state;
8806 struct bpf_reg_state *reg;
8809 err = release_reference_state(cur_func(env), ref_obj_id);
8813 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8814 if (reg->ref_obj_id == ref_obj_id)
8815 mark_reg_invalid(env, reg);
8821 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8823 struct bpf_func_state *unused;
8824 struct bpf_reg_state *reg;
8826 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8827 if (type_is_non_owning_ref(reg->type))
8828 mark_reg_invalid(env, reg);
8832 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8833 struct bpf_reg_state *regs)
8837 /* after the call registers r0 - r5 were scratched */
8838 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8839 mark_reg_not_init(env, regs, caller_saved[i]);
8840 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8844 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8845 struct bpf_func_state *caller,
8846 struct bpf_func_state *callee,
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);
8853 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8854 int *insn_idx, int subprog,
8855 set_callee_state_fn set_callee_state_cb)
8857 struct bpf_verifier_state *state = env->cur_state;
8858 struct bpf_func_state *caller, *callee;
8861 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8862 verbose(env, "the call stack of %d frames is too deep\n",
8863 state->curframe + 2);
8867 caller = state->frame[state->curframe];
8868 if (state->frame[state->curframe + 1]) {
8869 verbose(env, "verifier bug. Frame %d already allocated\n",
8870 state->curframe + 1);
8874 err = btf_check_subprog_call(env, subprog, caller->regs);
8877 if (subprog_is_global(env, subprog)) {
8879 verbose(env, "Caller passes invalid args into func#%d\n",
8883 if (env->log.level & BPF_LOG_LEVEL)
8885 "Func#%d is global and valid. Skipping.\n",
8887 clear_caller_saved_regs(env, caller->regs);
8889 /* All global functions return a 64-bit SCALAR_VALUE */
8890 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8891 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8893 /* continue with next insn after call */
8898 /* set_callee_state is used for direct subprog calls, but we are
8899 * interested in validating only BPF helpers that can call subprogs as
8902 if (set_callee_state_cb != set_callee_state) {
8903 if (bpf_pseudo_kfunc_call(insn) &&
8904 !is_callback_calling_kfunc(insn->imm)) {
8905 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8906 func_id_name(insn->imm), insn->imm);
8908 } else if (!bpf_pseudo_kfunc_call(insn) &&
8909 !is_callback_calling_function(insn->imm)) { /* helper */
8910 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8911 func_id_name(insn->imm), insn->imm);
8916 if (insn->code == (BPF_JMP | BPF_CALL) &&
8917 insn->src_reg == 0 &&
8918 insn->imm == BPF_FUNC_timer_set_callback) {
8919 struct bpf_verifier_state *async_cb;
8921 /* there is no real recursion here. timer callbacks are async */
8922 env->subprog_info[subprog].is_async_cb = true;
8923 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8924 *insn_idx, subprog);
8927 callee = async_cb->frame[0];
8928 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8930 /* Convert bpf_timer_set_callback() args into timer callback args */
8931 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8935 clear_caller_saved_regs(env, caller->regs);
8936 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8937 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8938 /* continue with next insn after call */
8942 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8945 state->frame[state->curframe + 1] = callee;
8947 /* callee cannot access r0, r6 - r9 for reading and has to write
8948 * into its own stack before reading from it.
8949 * callee can read/write into caller's stack
8951 init_func_state(env, callee,
8952 /* remember the callsite, it will be used by bpf_exit */
8953 *insn_idx /* callsite */,
8954 state->curframe + 1 /* frameno within this callchain */,
8955 subprog /* subprog number within this prog */);
8957 /* Transfer references to the callee */
8958 err = copy_reference_state(callee, caller);
8962 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8966 clear_caller_saved_regs(env, caller->regs);
8968 /* only increment it after check_reg_arg() finished */
8971 /* and go analyze first insn of the callee */
8972 *insn_idx = env->subprog_info[subprog].start - 1;
8974 if (env->log.level & BPF_LOG_LEVEL) {
8975 verbose(env, "caller:\n");
8976 print_verifier_state(env, caller, true);
8977 verbose(env, "callee:\n");
8978 print_verifier_state(env, callee, true);
8983 free_func_state(callee);
8984 state->frame[state->curframe + 1] = NULL;
8988 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8989 struct bpf_func_state *caller,
8990 struct bpf_func_state *callee)
8992 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8993 * void *callback_ctx, u64 flags);
8994 * callback_fn(struct bpf_map *map, void *key, void *value,
8995 * void *callback_ctx);
8997 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8999 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9000 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9001 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9003 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9004 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9005 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9007 /* pointer to stack or null */
9008 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9011 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9015 static int set_callee_state(struct bpf_verifier_env *env,
9016 struct bpf_func_state *caller,
9017 struct bpf_func_state *callee, int insn_idx)
9021 /* copy r1 - r5 args that callee can access. The copy includes parent
9022 * pointers, which connects us up to the liveness chain
9024 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9025 callee->regs[i] = caller->regs[i];
9029 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9032 int subprog, target_insn;
9034 target_insn = *insn_idx + insn->imm + 1;
9035 subprog = find_subprog(env, target_insn);
9037 verbose(env, "verifier bug. No program starts at insn %d\n",
9042 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
9045 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9046 struct bpf_func_state *caller,
9047 struct bpf_func_state *callee,
9050 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9051 struct bpf_map *map;
9054 if (bpf_map_ptr_poisoned(insn_aux)) {
9055 verbose(env, "tail_call abusing map_ptr\n");
9059 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9060 if (!map->ops->map_set_for_each_callback_args ||
9061 !map->ops->map_for_each_callback) {
9062 verbose(env, "callback function not allowed for map\n");
9066 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9070 callee->in_callback_fn = true;
9071 callee->callback_ret_range = tnum_range(0, 1);
9075 static int set_loop_callback_state(struct bpf_verifier_env *env,
9076 struct bpf_func_state *caller,
9077 struct bpf_func_state *callee,
9080 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9082 * callback_fn(u32 index, void *callback_ctx);
9084 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9085 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9088 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9089 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9090 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9092 callee->in_callback_fn = true;
9093 callee->callback_ret_range = tnum_range(0, 1);
9097 static int set_timer_callback_state(struct bpf_verifier_env *env,
9098 struct bpf_func_state *caller,
9099 struct bpf_func_state *callee,
9102 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9104 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9105 * callback_fn(struct bpf_map *map, void *key, void *value);
9107 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9108 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9109 callee->regs[BPF_REG_1].map_ptr = map_ptr;
9111 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9112 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9113 callee->regs[BPF_REG_2].map_ptr = map_ptr;
9115 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9116 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9117 callee->regs[BPF_REG_3].map_ptr = map_ptr;
9120 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9121 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9122 callee->in_async_callback_fn = true;
9123 callee->callback_ret_range = tnum_range(0, 1);
9127 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9128 struct bpf_func_state *caller,
9129 struct bpf_func_state *callee,
9132 /* bpf_find_vma(struct task_struct *task, u64 addr,
9133 * void *callback_fn, void *callback_ctx, u64 flags)
9134 * (callback_fn)(struct task_struct *task,
9135 * struct vm_area_struct *vma, void *callback_ctx);
9137 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9139 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9140 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9141 callee->regs[BPF_REG_2].btf = btf_vmlinux;
9142 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9144 /* pointer to stack or null */
9145 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9148 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9149 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9150 callee->in_callback_fn = true;
9151 callee->callback_ret_range = tnum_range(0, 1);
9155 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9156 struct bpf_func_state *caller,
9157 struct bpf_func_state *callee,
9160 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9161 * callback_ctx, u64 flags);
9162 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9164 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9165 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9166 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9169 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9170 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9171 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9173 callee->in_callback_fn = true;
9174 callee->callback_ret_range = tnum_range(0, 1);
9178 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9179 struct bpf_func_state *caller,
9180 struct bpf_func_state *callee,
9183 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9184 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9186 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9187 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9188 * by this point, so look at 'root'
9190 struct btf_field *field;
9192 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9194 if (!field || !field->graph_root.value_btf_id)
9197 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9198 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9199 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9200 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9202 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9203 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9204 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9205 callee->in_callback_fn = true;
9206 callee->callback_ret_range = tnum_range(0, 1);
9210 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9212 /* Are we currently verifying the callback for a rbtree helper that must
9213 * be called with lock held? If so, no need to complain about unreleased
9216 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9218 struct bpf_verifier_state *state = env->cur_state;
9219 struct bpf_insn *insn = env->prog->insnsi;
9220 struct bpf_func_state *callee;
9223 if (!state->curframe)
9226 callee = state->frame[state->curframe];
9228 if (!callee->in_callback_fn)
9231 kfunc_btf_id = insn[callee->callsite].imm;
9232 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9235 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9237 struct bpf_verifier_state *state = env->cur_state;
9238 struct bpf_func_state *caller, *callee;
9239 struct bpf_reg_state *r0;
9242 callee = state->frame[state->curframe];
9243 r0 = &callee->regs[BPF_REG_0];
9244 if (r0->type == PTR_TO_STACK) {
9245 /* technically it's ok to return caller's stack pointer
9246 * (or caller's caller's pointer) back to the caller,
9247 * since these pointers are valid. Only current stack
9248 * pointer will be invalid as soon as function exits,
9249 * but let's be conservative
9251 verbose(env, "cannot return stack pointer to the caller\n");
9255 caller = state->frame[state->curframe - 1];
9256 if (callee->in_callback_fn) {
9257 /* enforce R0 return value range [0, 1]. */
9258 struct tnum range = callee->callback_ret_range;
9260 if (r0->type != SCALAR_VALUE) {
9261 verbose(env, "R0 not a scalar value\n");
9264 if (!tnum_in(range, r0->var_off)) {
9265 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9269 /* return to the caller whatever r0 had in the callee */
9270 caller->regs[BPF_REG_0] = *r0;
9273 /* callback_fn frame should have released its own additions to parent's
9274 * reference state at this point, or check_reference_leak would
9275 * complain, hence it must be the same as the caller. There is no need
9278 if (!callee->in_callback_fn) {
9279 /* Transfer references to the caller */
9280 err = copy_reference_state(caller, callee);
9285 *insn_idx = callee->callsite + 1;
9286 if (env->log.level & BPF_LOG_LEVEL) {
9287 verbose(env, "returning from callee:\n");
9288 print_verifier_state(env, callee, true);
9289 verbose(env, "to caller at %d:\n", *insn_idx);
9290 print_verifier_state(env, caller, true);
9292 /* clear everything in the callee */
9293 free_func_state(callee);
9294 state->frame[state->curframe--] = NULL;
9298 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9300 struct bpf_call_arg_meta *meta)
9302 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
9304 if (ret_type != RET_INTEGER)
9308 case BPF_FUNC_get_stack:
9309 case BPF_FUNC_get_task_stack:
9310 case BPF_FUNC_probe_read_str:
9311 case BPF_FUNC_probe_read_kernel_str:
9312 case BPF_FUNC_probe_read_user_str:
9313 ret_reg->smax_value = meta->msize_max_value;
9314 ret_reg->s32_max_value = meta->msize_max_value;
9315 ret_reg->smin_value = -MAX_ERRNO;
9316 ret_reg->s32_min_value = -MAX_ERRNO;
9317 reg_bounds_sync(ret_reg);
9319 case BPF_FUNC_get_smp_processor_id:
9320 ret_reg->umax_value = nr_cpu_ids - 1;
9321 ret_reg->u32_max_value = nr_cpu_ids - 1;
9322 ret_reg->smax_value = nr_cpu_ids - 1;
9323 ret_reg->s32_max_value = nr_cpu_ids - 1;
9324 ret_reg->umin_value = 0;
9325 ret_reg->u32_min_value = 0;
9326 ret_reg->smin_value = 0;
9327 ret_reg->s32_min_value = 0;
9328 reg_bounds_sync(ret_reg);
9334 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9335 int func_id, int insn_idx)
9337 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9338 struct bpf_map *map = meta->map_ptr;
9340 if (func_id != BPF_FUNC_tail_call &&
9341 func_id != BPF_FUNC_map_lookup_elem &&
9342 func_id != BPF_FUNC_map_update_elem &&
9343 func_id != BPF_FUNC_map_delete_elem &&
9344 func_id != BPF_FUNC_map_push_elem &&
9345 func_id != BPF_FUNC_map_pop_elem &&
9346 func_id != BPF_FUNC_map_peek_elem &&
9347 func_id != BPF_FUNC_for_each_map_elem &&
9348 func_id != BPF_FUNC_redirect_map &&
9349 func_id != BPF_FUNC_map_lookup_percpu_elem)
9353 verbose(env, "kernel subsystem misconfigured verifier\n");
9357 /* In case of read-only, some additional restrictions
9358 * need to be applied in order to prevent altering the
9359 * state of the map from program side.
9361 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9362 (func_id == BPF_FUNC_map_delete_elem ||
9363 func_id == BPF_FUNC_map_update_elem ||
9364 func_id == BPF_FUNC_map_push_elem ||
9365 func_id == BPF_FUNC_map_pop_elem)) {
9366 verbose(env, "write into map forbidden\n");
9370 if (!BPF_MAP_PTR(aux->map_ptr_state))
9371 bpf_map_ptr_store(aux, meta->map_ptr,
9372 !meta->map_ptr->bypass_spec_v1);
9373 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9374 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9375 !meta->map_ptr->bypass_spec_v1);
9380 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9381 int func_id, int insn_idx)
9383 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9384 struct bpf_reg_state *regs = cur_regs(env), *reg;
9385 struct bpf_map *map = meta->map_ptr;
9389 if (func_id != BPF_FUNC_tail_call)
9391 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9392 verbose(env, "kernel subsystem misconfigured verifier\n");
9396 reg = ®s[BPF_REG_3];
9397 val = reg->var_off.value;
9398 max = map->max_entries;
9400 if (!(register_is_const(reg) && val < max)) {
9401 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9405 err = mark_chain_precision(env, BPF_REG_3);
9408 if (bpf_map_key_unseen(aux))
9409 bpf_map_key_store(aux, val);
9410 else if (!bpf_map_key_poisoned(aux) &&
9411 bpf_map_key_immediate(aux) != val)
9412 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9416 static int check_reference_leak(struct bpf_verifier_env *env)
9418 struct bpf_func_state *state = cur_func(env);
9419 bool refs_lingering = false;
9422 if (state->frameno && !state->in_callback_fn)
9425 for (i = 0; i < state->acquired_refs; i++) {
9426 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9428 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9429 state->refs[i].id, state->refs[i].insn_idx);
9430 refs_lingering = true;
9432 return refs_lingering ? -EINVAL : 0;
9435 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9436 struct bpf_reg_state *regs)
9438 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
9439 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
9440 struct bpf_map *fmt_map = fmt_reg->map_ptr;
9441 struct bpf_bprintf_data data = {};
9442 int err, fmt_map_off, num_args;
9446 /* data must be an array of u64 */
9447 if (data_len_reg->var_off.value % 8)
9449 num_args = data_len_reg->var_off.value / 8;
9451 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9452 * and map_direct_value_addr is set.
9454 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9455 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9458 verbose(env, "verifier bug\n");
9461 fmt = (char *)(long)fmt_addr + fmt_map_off;
9463 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9464 * can focus on validating the format specifiers.
9466 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9468 verbose(env, "Invalid format string\n");
9473 static int check_get_func_ip(struct bpf_verifier_env *env)
9475 enum bpf_prog_type type = resolve_prog_type(env->prog);
9476 int func_id = BPF_FUNC_get_func_ip;
9478 if (type == BPF_PROG_TYPE_TRACING) {
9479 if (!bpf_prog_has_trampoline(env->prog)) {
9480 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9481 func_id_name(func_id), func_id);
9485 } else if (type == BPF_PROG_TYPE_KPROBE) {
9489 verbose(env, "func %s#%d not supported for program type %d\n",
9490 func_id_name(func_id), func_id, type);
9494 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9496 return &env->insn_aux_data[env->insn_idx];
9499 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9501 struct bpf_reg_state *regs = cur_regs(env);
9502 struct bpf_reg_state *reg = ®s[BPF_REG_4];
9503 bool reg_is_null = register_is_null(reg);
9506 mark_chain_precision(env, BPF_REG_4);
9511 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9513 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9515 if (!state->initialized) {
9516 state->initialized = 1;
9517 state->fit_for_inline = loop_flag_is_zero(env);
9518 state->callback_subprogno = subprogno;
9522 if (!state->fit_for_inline)
9525 state->fit_for_inline = (loop_flag_is_zero(env) &&
9526 state->callback_subprogno == subprogno);
9529 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9532 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9533 const struct bpf_func_proto *fn = NULL;
9534 enum bpf_return_type ret_type;
9535 enum bpf_type_flag ret_flag;
9536 struct bpf_reg_state *regs;
9537 struct bpf_call_arg_meta meta;
9538 int insn_idx = *insn_idx_p;
9540 int i, err, func_id;
9542 /* find function prototype */
9543 func_id = insn->imm;
9544 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9545 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9550 if (env->ops->get_func_proto)
9551 fn = env->ops->get_func_proto(func_id, env->prog);
9553 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9558 /* eBPF programs must be GPL compatible to use GPL-ed functions */
9559 if (!env->prog->gpl_compatible && fn->gpl_only) {
9560 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9564 if (fn->allowed && !fn->allowed(env->prog)) {
9565 verbose(env, "helper call is not allowed in probe\n");
9569 if (!env->prog->aux->sleepable && fn->might_sleep) {
9570 verbose(env, "helper call might sleep in a non-sleepable prog\n");
9574 /* With LD_ABS/IND some JITs save/restore skb from r1. */
9575 changes_data = bpf_helper_changes_pkt_data(fn->func);
9576 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9577 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9578 func_id_name(func_id), func_id);
9582 memset(&meta, 0, sizeof(meta));
9583 meta.pkt_access = fn->pkt_access;
9585 err = check_func_proto(fn, func_id);
9587 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9588 func_id_name(func_id), func_id);
9592 if (env->cur_state->active_rcu_lock) {
9593 if (fn->might_sleep) {
9594 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9595 func_id_name(func_id), func_id);
9599 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9600 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9603 meta.func_id = func_id;
9605 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9606 err = check_func_arg(env, i, &meta, fn, insn_idx);
9611 err = record_func_map(env, &meta, func_id, insn_idx);
9615 err = record_func_key(env, &meta, func_id, insn_idx);
9619 /* Mark slots with STACK_MISC in case of raw mode, stack offset
9620 * is inferred from register state.
9622 for (i = 0; i < meta.access_size; i++) {
9623 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9624 BPF_WRITE, -1, false, false);
9629 regs = cur_regs(env);
9631 if (meta.release_regno) {
9633 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9634 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9635 * is safe to do directly.
9637 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9638 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9639 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9642 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
9643 } else if (meta.ref_obj_id) {
9644 err = release_reference(env, meta.ref_obj_id);
9645 } else if (register_is_null(®s[meta.release_regno])) {
9646 /* meta.ref_obj_id can only be 0 if register that is meant to be
9647 * released is NULL, which must be > R0.
9652 verbose(env, "func %s#%d reference has not been acquired before\n",
9653 func_id_name(func_id), func_id);
9659 case BPF_FUNC_tail_call:
9660 err = check_reference_leak(env);
9662 verbose(env, "tail_call would lead to reference leak\n");
9666 case BPF_FUNC_get_local_storage:
9667 /* check that flags argument in get_local_storage(map, flags) is 0,
9668 * this is required because get_local_storage() can't return an error.
9670 if (!register_is_null(®s[BPF_REG_2])) {
9671 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9675 case BPF_FUNC_for_each_map_elem:
9676 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9677 set_map_elem_callback_state);
9679 case BPF_FUNC_timer_set_callback:
9680 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9681 set_timer_callback_state);
9683 case BPF_FUNC_find_vma:
9684 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9685 set_find_vma_callback_state);
9687 case BPF_FUNC_snprintf:
9688 err = check_bpf_snprintf_call(env, regs);
9691 update_loop_inline_state(env, meta.subprogno);
9692 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9693 set_loop_callback_state);
9695 case BPF_FUNC_dynptr_from_mem:
9696 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9697 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9698 reg_type_str(env, regs[BPF_REG_1].type));
9702 case BPF_FUNC_set_retval:
9703 if (prog_type == BPF_PROG_TYPE_LSM &&
9704 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9705 if (!env->prog->aux->attach_func_proto->type) {
9706 /* Make sure programs that attach to void
9707 * hooks don't try to modify return value.
9709 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9714 case BPF_FUNC_dynptr_data:
9716 struct bpf_reg_state *reg;
9719 reg = get_dynptr_arg_reg(env, fn, regs);
9724 if (meta.dynptr_id) {
9725 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9728 if (meta.ref_obj_id) {
9729 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9733 id = dynptr_id(env, reg);
9735 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9739 ref_obj_id = dynptr_ref_obj_id(env, reg);
9740 if (ref_obj_id < 0) {
9741 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9745 meta.dynptr_id = id;
9746 meta.ref_obj_id = ref_obj_id;
9750 case BPF_FUNC_dynptr_write:
9752 enum bpf_dynptr_type dynptr_type;
9753 struct bpf_reg_state *reg;
9755 reg = get_dynptr_arg_reg(env, fn, regs);
9759 dynptr_type = dynptr_get_type(env, reg);
9760 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9763 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9764 /* this will trigger clear_all_pkt_pointers(), which will
9765 * invalidate all dynptr slices associated with the skb
9767 changes_data = true;
9771 case BPF_FUNC_user_ringbuf_drain:
9772 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9773 set_user_ringbuf_callback_state);
9780 /* reset caller saved regs */
9781 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9782 mark_reg_not_init(env, regs, caller_saved[i]);
9783 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9786 /* helper call returns 64-bit value. */
9787 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9789 /* update return register (already marked as written above) */
9790 ret_type = fn->ret_type;
9791 ret_flag = type_flag(ret_type);
9793 switch (base_type(ret_type)) {
9795 /* sets type to SCALAR_VALUE */
9796 mark_reg_unknown(env, regs, BPF_REG_0);
9799 regs[BPF_REG_0].type = NOT_INIT;
9801 case RET_PTR_TO_MAP_VALUE:
9802 /* There is no offset yet applied, variable or fixed */
9803 mark_reg_known_zero(env, regs, BPF_REG_0);
9804 /* remember map_ptr, so that check_map_access()
9805 * can check 'value_size' boundary of memory access
9806 * to map element returned from bpf_map_lookup_elem()
9808 if (meta.map_ptr == NULL) {
9810 "kernel subsystem misconfigured verifier\n");
9813 regs[BPF_REG_0].map_ptr = meta.map_ptr;
9814 regs[BPF_REG_0].map_uid = meta.map_uid;
9815 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9816 if (!type_may_be_null(ret_type) &&
9817 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9818 regs[BPF_REG_0].id = ++env->id_gen;
9821 case RET_PTR_TO_SOCKET:
9822 mark_reg_known_zero(env, regs, BPF_REG_0);
9823 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9825 case RET_PTR_TO_SOCK_COMMON:
9826 mark_reg_known_zero(env, regs, BPF_REG_0);
9827 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9829 case RET_PTR_TO_TCP_SOCK:
9830 mark_reg_known_zero(env, regs, BPF_REG_0);
9831 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9833 case RET_PTR_TO_MEM:
9834 mark_reg_known_zero(env, regs, BPF_REG_0);
9835 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9836 regs[BPF_REG_0].mem_size = meta.mem_size;
9838 case RET_PTR_TO_MEM_OR_BTF_ID:
9840 const struct btf_type *t;
9842 mark_reg_known_zero(env, regs, BPF_REG_0);
9843 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9844 if (!btf_type_is_struct(t)) {
9846 const struct btf_type *ret;
9849 /* resolve the type size of ksym. */
9850 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9852 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9853 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9854 tname, PTR_ERR(ret));
9857 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9858 regs[BPF_REG_0].mem_size = tsize;
9860 /* MEM_RDONLY may be carried from ret_flag, but it
9861 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9862 * it will confuse the check of PTR_TO_BTF_ID in
9863 * check_mem_access().
9865 ret_flag &= ~MEM_RDONLY;
9867 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9868 regs[BPF_REG_0].btf = meta.ret_btf;
9869 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9873 case RET_PTR_TO_BTF_ID:
9875 struct btf *ret_btf;
9878 mark_reg_known_zero(env, regs, BPF_REG_0);
9879 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9880 if (func_id == BPF_FUNC_kptr_xchg) {
9881 ret_btf = meta.kptr_field->kptr.btf;
9882 ret_btf_id = meta.kptr_field->kptr.btf_id;
9883 if (!btf_is_kernel(ret_btf))
9884 regs[BPF_REG_0].type |= MEM_ALLOC;
9886 if (fn->ret_btf_id == BPF_PTR_POISON) {
9887 verbose(env, "verifier internal error:");
9888 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9889 func_id_name(func_id));
9892 ret_btf = btf_vmlinux;
9893 ret_btf_id = *fn->ret_btf_id;
9895 if (ret_btf_id == 0) {
9896 verbose(env, "invalid return type %u of func %s#%d\n",
9897 base_type(ret_type), func_id_name(func_id),
9901 regs[BPF_REG_0].btf = ret_btf;
9902 regs[BPF_REG_0].btf_id = ret_btf_id;
9906 verbose(env, "unknown return type %u of func %s#%d\n",
9907 base_type(ret_type), func_id_name(func_id), func_id);
9911 if (type_may_be_null(regs[BPF_REG_0].type))
9912 regs[BPF_REG_0].id = ++env->id_gen;
9914 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9915 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9916 func_id_name(func_id), func_id);
9920 if (is_dynptr_ref_function(func_id))
9921 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9923 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9924 /* For release_reference() */
9925 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9926 } else if (is_acquire_function(func_id, meta.map_ptr)) {
9927 int id = acquire_reference_state(env, insn_idx);
9931 /* For mark_ptr_or_null_reg() */
9932 regs[BPF_REG_0].id = id;
9933 /* For release_reference() */
9934 regs[BPF_REG_0].ref_obj_id = id;
9937 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9939 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9943 if ((func_id == BPF_FUNC_get_stack ||
9944 func_id == BPF_FUNC_get_task_stack) &&
9945 !env->prog->has_callchain_buf) {
9946 const char *err_str;
9948 #ifdef CONFIG_PERF_EVENTS
9949 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9950 err_str = "cannot get callchain buffer for func %s#%d\n";
9953 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9956 verbose(env, err_str, func_id_name(func_id), func_id);
9960 env->prog->has_callchain_buf = true;
9963 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9964 env->prog->call_get_stack = true;
9966 if (func_id == BPF_FUNC_get_func_ip) {
9967 if (check_get_func_ip(env))
9969 env->prog->call_get_func_ip = true;
9973 clear_all_pkt_pointers(env);
9977 /* mark_btf_func_reg_size() is used when the reg size is determined by
9978 * the BTF func_proto's return value size and argument.
9980 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9983 struct bpf_reg_state *reg = &cur_regs(env)[regno];
9985 if (regno == BPF_REG_0) {
9986 /* Function return value */
9987 reg->live |= REG_LIVE_WRITTEN;
9988 reg->subreg_def = reg_size == sizeof(u64) ?
9989 DEF_NOT_SUBREG : env->insn_idx + 1;
9991 /* Function argument */
9992 if (reg_size == sizeof(u64)) {
9993 mark_insn_zext(env, reg);
9994 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9996 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10001 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10003 return meta->kfunc_flags & KF_ACQUIRE;
10006 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10008 return meta->kfunc_flags & KF_RELEASE;
10011 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10013 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10016 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10018 return meta->kfunc_flags & KF_SLEEPABLE;
10021 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10023 return meta->kfunc_flags & KF_DESTRUCTIVE;
10026 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10028 return meta->kfunc_flags & KF_RCU;
10031 static bool __kfunc_param_match_suffix(const struct btf *btf,
10032 const struct btf_param *arg,
10033 const char *suffix)
10035 int suffix_len = strlen(suffix), len;
10036 const char *param_name;
10038 /* In the future, this can be ported to use BTF tagging */
10039 param_name = btf_name_by_offset(btf, arg->name_off);
10040 if (str_is_empty(param_name))
10042 len = strlen(param_name);
10043 if (len < suffix_len)
10045 param_name += len - suffix_len;
10046 return !strncmp(param_name, suffix, suffix_len);
10049 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10050 const struct btf_param *arg,
10051 const struct bpf_reg_state *reg)
10053 const struct btf_type *t;
10055 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10056 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10059 return __kfunc_param_match_suffix(btf, arg, "__sz");
10062 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10063 const struct btf_param *arg,
10064 const struct bpf_reg_state *reg)
10066 const struct btf_type *t;
10068 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10069 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10072 return __kfunc_param_match_suffix(btf, arg, "__szk");
10075 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10077 return __kfunc_param_match_suffix(btf, arg, "__opt");
10080 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10082 return __kfunc_param_match_suffix(btf, arg, "__k");
10085 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10087 return __kfunc_param_match_suffix(btf, arg, "__ign");
10090 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10092 return __kfunc_param_match_suffix(btf, arg, "__alloc");
10095 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10097 return __kfunc_param_match_suffix(btf, arg, "__uninit");
10100 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10102 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10105 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10106 const struct btf_param *arg,
10109 int len, target_len = strlen(name);
10110 const char *param_name;
10112 param_name = btf_name_by_offset(btf, arg->name_off);
10113 if (str_is_empty(param_name))
10115 len = strlen(param_name);
10116 if (len != target_len)
10118 if (strcmp(param_name, name))
10126 KF_ARG_LIST_HEAD_ID,
10127 KF_ARG_LIST_NODE_ID,
10132 BTF_ID_LIST(kf_arg_btf_ids)
10133 BTF_ID(struct, bpf_dynptr_kern)
10134 BTF_ID(struct, bpf_list_head)
10135 BTF_ID(struct, bpf_list_node)
10136 BTF_ID(struct, bpf_rb_root)
10137 BTF_ID(struct, bpf_rb_node)
10139 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10140 const struct btf_param *arg, int type)
10142 const struct btf_type *t;
10145 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10148 if (!btf_type_is_ptr(t))
10150 t = btf_type_skip_modifiers(btf, t->type, &res_id);
10153 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10156 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10158 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10161 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10163 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10166 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10168 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10171 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10173 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10176 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10178 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10181 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10182 const struct btf_param *arg)
10184 const struct btf_type *t;
10186 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10193 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10194 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10195 const struct btf *btf,
10196 const struct btf_type *t, int rec)
10198 const struct btf_type *member_type;
10199 const struct btf_member *member;
10202 if (!btf_type_is_struct(t))
10205 for_each_member(i, t, member) {
10206 const struct btf_array *array;
10208 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10209 if (btf_type_is_struct(member_type)) {
10211 verbose(env, "max struct nesting depth exceeded\n");
10214 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10218 if (btf_type_is_array(member_type)) {
10219 array = btf_array(member_type);
10220 if (!array->nelems)
10222 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10223 if (!btf_type_is_scalar(member_type))
10227 if (!btf_type_is_scalar(member_type))
10233 enum kfunc_ptr_arg_type {
10235 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
10236 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10237 KF_ARG_PTR_TO_DYNPTR,
10238 KF_ARG_PTR_TO_ITER,
10239 KF_ARG_PTR_TO_LIST_HEAD,
10240 KF_ARG_PTR_TO_LIST_NODE,
10241 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
10243 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
10244 KF_ARG_PTR_TO_CALLBACK,
10245 KF_ARG_PTR_TO_RB_ROOT,
10246 KF_ARG_PTR_TO_RB_NODE,
10249 enum special_kfunc_type {
10250 KF_bpf_obj_new_impl,
10251 KF_bpf_obj_drop_impl,
10252 KF_bpf_refcount_acquire_impl,
10253 KF_bpf_list_push_front_impl,
10254 KF_bpf_list_push_back_impl,
10255 KF_bpf_list_pop_front,
10256 KF_bpf_list_pop_back,
10257 KF_bpf_cast_to_kern_ctx,
10258 KF_bpf_rdonly_cast,
10259 KF_bpf_rcu_read_lock,
10260 KF_bpf_rcu_read_unlock,
10261 KF_bpf_rbtree_remove,
10262 KF_bpf_rbtree_add_impl,
10263 KF_bpf_rbtree_first,
10264 KF_bpf_dynptr_from_skb,
10265 KF_bpf_dynptr_from_xdp,
10266 KF_bpf_dynptr_slice,
10267 KF_bpf_dynptr_slice_rdwr,
10268 KF_bpf_dynptr_clone,
10271 BTF_SET_START(special_kfunc_set)
10272 BTF_ID(func, bpf_obj_new_impl)
10273 BTF_ID(func, bpf_obj_drop_impl)
10274 BTF_ID(func, bpf_refcount_acquire_impl)
10275 BTF_ID(func, bpf_list_push_front_impl)
10276 BTF_ID(func, bpf_list_push_back_impl)
10277 BTF_ID(func, bpf_list_pop_front)
10278 BTF_ID(func, bpf_list_pop_back)
10279 BTF_ID(func, bpf_cast_to_kern_ctx)
10280 BTF_ID(func, bpf_rdonly_cast)
10281 BTF_ID(func, bpf_rbtree_remove)
10282 BTF_ID(func, bpf_rbtree_add_impl)
10283 BTF_ID(func, bpf_rbtree_first)
10284 BTF_ID(func, bpf_dynptr_from_skb)
10285 BTF_ID(func, bpf_dynptr_from_xdp)
10286 BTF_ID(func, bpf_dynptr_slice)
10287 BTF_ID(func, bpf_dynptr_slice_rdwr)
10288 BTF_ID(func, bpf_dynptr_clone)
10289 BTF_SET_END(special_kfunc_set)
10291 BTF_ID_LIST(special_kfunc_list)
10292 BTF_ID(func, bpf_obj_new_impl)
10293 BTF_ID(func, bpf_obj_drop_impl)
10294 BTF_ID(func, bpf_refcount_acquire_impl)
10295 BTF_ID(func, bpf_list_push_front_impl)
10296 BTF_ID(func, bpf_list_push_back_impl)
10297 BTF_ID(func, bpf_list_pop_front)
10298 BTF_ID(func, bpf_list_pop_back)
10299 BTF_ID(func, bpf_cast_to_kern_ctx)
10300 BTF_ID(func, bpf_rdonly_cast)
10301 BTF_ID(func, bpf_rcu_read_lock)
10302 BTF_ID(func, bpf_rcu_read_unlock)
10303 BTF_ID(func, bpf_rbtree_remove)
10304 BTF_ID(func, bpf_rbtree_add_impl)
10305 BTF_ID(func, bpf_rbtree_first)
10306 BTF_ID(func, bpf_dynptr_from_skb)
10307 BTF_ID(func, bpf_dynptr_from_xdp)
10308 BTF_ID(func, bpf_dynptr_slice)
10309 BTF_ID(func, bpf_dynptr_slice_rdwr)
10310 BTF_ID(func, bpf_dynptr_clone)
10312 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10314 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10315 meta->arg_owning_ref) {
10319 return meta->kfunc_flags & KF_RET_NULL;
10322 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10324 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10327 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10329 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10332 static enum kfunc_ptr_arg_type
10333 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10334 struct bpf_kfunc_call_arg_meta *meta,
10335 const struct btf_type *t, const struct btf_type *ref_t,
10336 const char *ref_tname, const struct btf_param *args,
10337 int argno, int nargs)
10339 u32 regno = argno + 1;
10340 struct bpf_reg_state *regs = cur_regs(env);
10341 struct bpf_reg_state *reg = ®s[regno];
10342 bool arg_mem_size = false;
10344 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10345 return KF_ARG_PTR_TO_CTX;
10347 /* In this function, we verify the kfunc's BTF as per the argument type,
10348 * leaving the rest of the verification with respect to the register
10349 * type to our caller. When a set of conditions hold in the BTF type of
10350 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10352 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10353 return KF_ARG_PTR_TO_CTX;
10355 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10356 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10358 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10359 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10361 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10362 return KF_ARG_PTR_TO_DYNPTR;
10364 if (is_kfunc_arg_iter(meta, argno))
10365 return KF_ARG_PTR_TO_ITER;
10367 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10368 return KF_ARG_PTR_TO_LIST_HEAD;
10370 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10371 return KF_ARG_PTR_TO_LIST_NODE;
10373 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10374 return KF_ARG_PTR_TO_RB_ROOT;
10376 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10377 return KF_ARG_PTR_TO_RB_NODE;
10379 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10380 if (!btf_type_is_struct(ref_t)) {
10381 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10382 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10385 return KF_ARG_PTR_TO_BTF_ID;
10388 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10389 return KF_ARG_PTR_TO_CALLBACK;
10392 if (argno + 1 < nargs &&
10393 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
10394 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
10395 arg_mem_size = true;
10397 /* This is the catch all argument type of register types supported by
10398 * check_helper_mem_access. However, we only allow when argument type is
10399 * pointer to scalar, or struct composed (recursively) of scalars. When
10400 * arg_mem_size is true, the pointer can be void *.
10402 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10403 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10404 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10405 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10408 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10411 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10412 struct bpf_reg_state *reg,
10413 const struct btf_type *ref_t,
10414 const char *ref_tname, u32 ref_id,
10415 struct bpf_kfunc_call_arg_meta *meta,
10418 const struct btf_type *reg_ref_t;
10419 bool strict_type_match = false;
10420 const struct btf *reg_btf;
10421 const char *reg_ref_tname;
10424 if (base_type(reg->type) == PTR_TO_BTF_ID) {
10425 reg_btf = reg->btf;
10426 reg_ref_id = reg->btf_id;
10428 reg_btf = btf_vmlinux;
10429 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10432 /* Enforce strict type matching for calls to kfuncs that are acquiring
10433 * or releasing a reference, or are no-cast aliases. We do _not_
10434 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10435 * as we want to enable BPF programs to pass types that are bitwise
10436 * equivalent without forcing them to explicitly cast with something
10437 * like bpf_cast_to_kern_ctx().
10439 * For example, say we had a type like the following:
10441 * struct bpf_cpumask {
10442 * cpumask_t cpumask;
10443 * refcount_t usage;
10446 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10447 * to a struct cpumask, so it would be safe to pass a struct
10448 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10450 * The philosophy here is similar to how we allow scalars of different
10451 * types to be passed to kfuncs as long as the size is the same. The
10452 * only difference here is that we're simply allowing
10453 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10456 if (is_kfunc_acquire(meta) ||
10457 (is_kfunc_release(meta) && reg->ref_obj_id) ||
10458 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10459 strict_type_match = true;
10461 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10463 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
10464 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10465 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10466 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10467 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10468 btf_type_str(reg_ref_t), reg_ref_tname);
10474 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10476 struct bpf_verifier_state *state = env->cur_state;
10478 if (!state->active_lock.ptr) {
10479 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10483 if (type_flag(reg->type) & NON_OWN_REF) {
10484 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10488 reg->type |= NON_OWN_REF;
10492 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10494 struct bpf_func_state *state, *unused;
10495 struct bpf_reg_state *reg;
10498 state = cur_func(env);
10501 verbose(env, "verifier internal error: ref_obj_id is zero for "
10502 "owning -> non-owning conversion\n");
10506 for (i = 0; i < state->acquired_refs; i++) {
10507 if (state->refs[i].id != ref_obj_id)
10510 /* Clear ref_obj_id here so release_reference doesn't clobber
10513 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10514 if (reg->ref_obj_id == ref_obj_id) {
10515 reg->ref_obj_id = 0;
10516 ref_set_non_owning(env, reg);
10522 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10526 /* Implementation details:
10528 * Each register points to some region of memory, which we define as an
10529 * allocation. Each allocation may embed a bpf_spin_lock which protects any
10530 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10531 * allocation. The lock and the data it protects are colocated in the same
10534 * Hence, everytime a register holds a pointer value pointing to such
10535 * allocation, the verifier preserves a unique reg->id for it.
10537 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10538 * bpf_spin_lock is called.
10540 * To enable this, lock state in the verifier captures two values:
10541 * active_lock.ptr = Register's type specific pointer
10542 * active_lock.id = A unique ID for each register pointer value
10544 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10545 * supported register types.
10547 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10548 * allocated objects is the reg->btf pointer.
10550 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10551 * can establish the provenance of the map value statically for each distinct
10552 * lookup into such maps. They always contain a single map value hence unique
10553 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10555 * So, in case of global variables, they use array maps with max_entries = 1,
10556 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10557 * into the same map value as max_entries is 1, as described above).
10559 * In case of inner map lookups, the inner map pointer has same map_ptr as the
10560 * outer map pointer (in verifier context), but each lookup into an inner map
10561 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10562 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10563 * will get different reg->id assigned to each lookup, hence different
10566 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10567 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10568 * returned from bpf_obj_new. Each allocation receives a new reg->id.
10570 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10575 switch ((int)reg->type) {
10576 case PTR_TO_MAP_VALUE:
10577 ptr = reg->map_ptr;
10579 case PTR_TO_BTF_ID | MEM_ALLOC:
10583 verbose(env, "verifier internal error: unknown reg type for lock check\n");
10588 if (!env->cur_state->active_lock.ptr)
10590 if (env->cur_state->active_lock.ptr != ptr ||
10591 env->cur_state->active_lock.id != id) {
10592 verbose(env, "held lock and object are not in the same allocation\n");
10598 static bool is_bpf_list_api_kfunc(u32 btf_id)
10600 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10601 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10602 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10603 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10606 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10608 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10609 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10610 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10613 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10615 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10616 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10619 static bool is_callback_calling_kfunc(u32 btf_id)
10621 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10624 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10626 return is_bpf_rbtree_api_kfunc(btf_id);
10629 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10630 enum btf_field_type head_field_type,
10635 switch (head_field_type) {
10636 case BPF_LIST_HEAD:
10637 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10640 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10643 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10644 btf_field_type_name(head_field_type));
10649 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10650 btf_field_type_name(head_field_type));
10654 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10655 enum btf_field_type node_field_type,
10660 switch (node_field_type) {
10661 case BPF_LIST_NODE:
10662 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10663 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10666 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10667 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10670 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10671 btf_field_type_name(node_field_type));
10676 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10677 btf_field_type_name(node_field_type));
10682 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10683 struct bpf_reg_state *reg, u32 regno,
10684 struct bpf_kfunc_call_arg_meta *meta,
10685 enum btf_field_type head_field_type,
10686 struct btf_field **head_field)
10688 const char *head_type_name;
10689 struct btf_field *field;
10690 struct btf_record *rec;
10693 if (meta->btf != btf_vmlinux) {
10694 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10698 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10701 head_type_name = btf_field_type_name(head_field_type);
10702 if (!tnum_is_const(reg->var_off)) {
10704 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10705 regno, head_type_name);
10709 rec = reg_btf_record(reg);
10710 head_off = reg->off + reg->var_off.value;
10711 field = btf_record_find(rec, head_off, head_field_type);
10713 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10717 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10718 if (check_reg_allocation_locked(env, reg)) {
10719 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10720 rec->spin_lock_off, head_type_name);
10725 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10728 *head_field = field;
10732 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10733 struct bpf_reg_state *reg, u32 regno,
10734 struct bpf_kfunc_call_arg_meta *meta)
10736 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10737 &meta->arg_list_head.field);
10740 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10741 struct bpf_reg_state *reg, u32 regno,
10742 struct bpf_kfunc_call_arg_meta *meta)
10744 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10745 &meta->arg_rbtree_root.field);
10749 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10750 struct bpf_reg_state *reg, u32 regno,
10751 struct bpf_kfunc_call_arg_meta *meta,
10752 enum btf_field_type head_field_type,
10753 enum btf_field_type node_field_type,
10754 struct btf_field **node_field)
10756 const char *node_type_name;
10757 const struct btf_type *et, *t;
10758 struct btf_field *field;
10761 if (meta->btf != btf_vmlinux) {
10762 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10766 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10769 node_type_name = btf_field_type_name(node_field_type);
10770 if (!tnum_is_const(reg->var_off)) {
10772 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10773 regno, node_type_name);
10777 node_off = reg->off + reg->var_off.value;
10778 field = reg_find_field_offset(reg, node_off, node_field_type);
10779 if (!field || field->offset != node_off) {
10780 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10784 field = *node_field;
10786 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10787 t = btf_type_by_id(reg->btf, reg->btf_id);
10788 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10789 field->graph_root.value_btf_id, true)) {
10790 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10791 "in struct %s, but arg is at offset=%d in struct %s\n",
10792 btf_field_type_name(head_field_type),
10793 btf_field_type_name(node_field_type),
10794 field->graph_root.node_offset,
10795 btf_name_by_offset(field->graph_root.btf, et->name_off),
10796 node_off, btf_name_by_offset(reg->btf, t->name_off));
10799 meta->arg_btf = reg->btf;
10800 meta->arg_btf_id = reg->btf_id;
10802 if (node_off != field->graph_root.node_offset) {
10803 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10804 node_off, btf_field_type_name(node_field_type),
10805 field->graph_root.node_offset,
10806 btf_name_by_offset(field->graph_root.btf, et->name_off));
10813 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10814 struct bpf_reg_state *reg, u32 regno,
10815 struct bpf_kfunc_call_arg_meta *meta)
10817 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10818 BPF_LIST_HEAD, BPF_LIST_NODE,
10819 &meta->arg_list_head.field);
10822 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10823 struct bpf_reg_state *reg, u32 regno,
10824 struct bpf_kfunc_call_arg_meta *meta)
10826 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10827 BPF_RB_ROOT, BPF_RB_NODE,
10828 &meta->arg_rbtree_root.field);
10831 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10834 const char *func_name = meta->func_name, *ref_tname;
10835 const struct btf *btf = meta->btf;
10836 const struct btf_param *args;
10837 struct btf_record *rec;
10841 args = (const struct btf_param *)(meta->func_proto + 1);
10842 nargs = btf_type_vlen(meta->func_proto);
10843 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10844 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10845 MAX_BPF_FUNC_REG_ARGS);
10849 /* Check that BTF function arguments match actual types that the
10852 for (i = 0; i < nargs; i++) {
10853 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
10854 const struct btf_type *t, *ref_t, *resolve_ret;
10855 enum bpf_arg_type arg_type = ARG_DONTCARE;
10856 u32 regno = i + 1, ref_id, type_size;
10857 bool is_ret_buf_sz = false;
10860 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10862 if (is_kfunc_arg_ignore(btf, &args[i]))
10865 if (btf_type_is_scalar(t)) {
10866 if (reg->type != SCALAR_VALUE) {
10867 verbose(env, "R%d is not a scalar\n", regno);
10871 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10872 if (meta->arg_constant.found) {
10873 verbose(env, "verifier internal error: only one constant argument permitted\n");
10876 if (!tnum_is_const(reg->var_off)) {
10877 verbose(env, "R%d must be a known constant\n", regno);
10880 ret = mark_chain_precision(env, regno);
10883 meta->arg_constant.found = true;
10884 meta->arg_constant.value = reg->var_off.value;
10885 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10886 meta->r0_rdonly = true;
10887 is_ret_buf_sz = true;
10888 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10889 is_ret_buf_sz = true;
10892 if (is_ret_buf_sz) {
10893 if (meta->r0_size) {
10894 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10898 if (!tnum_is_const(reg->var_off)) {
10899 verbose(env, "R%d is not a const\n", regno);
10903 meta->r0_size = reg->var_off.value;
10904 ret = mark_chain_precision(env, regno);
10911 if (!btf_type_is_ptr(t)) {
10912 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10916 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10917 (register_is_null(reg) || type_may_be_null(reg->type))) {
10918 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10922 if (reg->ref_obj_id) {
10923 if (is_kfunc_release(meta) && meta->ref_obj_id) {
10924 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10925 regno, reg->ref_obj_id,
10929 meta->ref_obj_id = reg->ref_obj_id;
10930 if (is_kfunc_release(meta))
10931 meta->release_regno = regno;
10934 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10935 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10937 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10938 if (kf_arg_type < 0)
10939 return kf_arg_type;
10941 switch (kf_arg_type) {
10942 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10943 case KF_ARG_PTR_TO_BTF_ID:
10944 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10947 if (!is_trusted_reg(reg)) {
10948 if (!is_kfunc_rcu(meta)) {
10949 verbose(env, "R%d must be referenced or trusted\n", regno);
10952 if (!is_rcu_reg(reg)) {
10953 verbose(env, "R%d must be a rcu pointer\n", regno);
10959 case KF_ARG_PTR_TO_CTX:
10960 /* Trusted arguments have the same offset checks as release arguments */
10961 arg_type |= OBJ_RELEASE;
10963 case KF_ARG_PTR_TO_DYNPTR:
10964 case KF_ARG_PTR_TO_ITER:
10965 case KF_ARG_PTR_TO_LIST_HEAD:
10966 case KF_ARG_PTR_TO_LIST_NODE:
10967 case KF_ARG_PTR_TO_RB_ROOT:
10968 case KF_ARG_PTR_TO_RB_NODE:
10969 case KF_ARG_PTR_TO_MEM:
10970 case KF_ARG_PTR_TO_MEM_SIZE:
10971 case KF_ARG_PTR_TO_CALLBACK:
10972 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10973 /* Trusted by default */
10980 if (is_kfunc_release(meta) && reg->ref_obj_id)
10981 arg_type |= OBJ_RELEASE;
10982 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10986 switch (kf_arg_type) {
10987 case KF_ARG_PTR_TO_CTX:
10988 if (reg->type != PTR_TO_CTX) {
10989 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10993 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10994 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10997 meta->ret_btf_id = ret;
11000 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11001 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11002 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11005 if (!reg->ref_obj_id) {
11006 verbose(env, "allocated object must be referenced\n");
11009 if (meta->btf == btf_vmlinux &&
11010 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11011 meta->arg_btf = reg->btf;
11012 meta->arg_btf_id = reg->btf_id;
11015 case KF_ARG_PTR_TO_DYNPTR:
11017 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11018 int clone_ref_obj_id = 0;
11020 if (reg->type != PTR_TO_STACK &&
11021 reg->type != CONST_PTR_TO_DYNPTR) {
11022 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11026 if (reg->type == CONST_PTR_TO_DYNPTR)
11027 dynptr_arg_type |= MEM_RDONLY;
11029 if (is_kfunc_arg_uninit(btf, &args[i]))
11030 dynptr_arg_type |= MEM_UNINIT;
11032 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11033 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11034 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11035 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11036 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11037 (dynptr_arg_type & MEM_UNINIT)) {
11038 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11040 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11041 verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11045 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11046 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11047 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11048 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11053 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11057 if (!(dynptr_arg_type & MEM_UNINIT)) {
11058 int id = dynptr_id(env, reg);
11061 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11064 meta->initialized_dynptr.id = id;
11065 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11066 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11071 case KF_ARG_PTR_TO_ITER:
11072 ret = process_iter_arg(env, regno, insn_idx, meta);
11076 case KF_ARG_PTR_TO_LIST_HEAD:
11077 if (reg->type != PTR_TO_MAP_VALUE &&
11078 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11079 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11082 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11083 verbose(env, "allocated object must be referenced\n");
11086 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11090 case KF_ARG_PTR_TO_RB_ROOT:
11091 if (reg->type != PTR_TO_MAP_VALUE &&
11092 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11093 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11096 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11097 verbose(env, "allocated object must be referenced\n");
11100 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11104 case KF_ARG_PTR_TO_LIST_NODE:
11105 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11106 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11109 if (!reg->ref_obj_id) {
11110 verbose(env, "allocated object must be referenced\n");
11113 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11117 case KF_ARG_PTR_TO_RB_NODE:
11118 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11119 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11120 verbose(env, "rbtree_remove node input must be non-owning ref\n");
11123 if (in_rbtree_lock_required_cb(env)) {
11124 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11128 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11129 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11132 if (!reg->ref_obj_id) {
11133 verbose(env, "allocated object must be referenced\n");
11138 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11142 case KF_ARG_PTR_TO_BTF_ID:
11143 /* Only base_type is checked, further checks are done here */
11144 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11145 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11146 !reg2btf_ids[base_type(reg->type)]) {
11147 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11148 verbose(env, "expected %s or socket\n",
11149 reg_type_str(env, base_type(reg->type) |
11150 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11153 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11157 case KF_ARG_PTR_TO_MEM:
11158 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11159 if (IS_ERR(resolve_ret)) {
11160 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11161 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11164 ret = check_mem_reg(env, reg, regno, type_size);
11168 case KF_ARG_PTR_TO_MEM_SIZE:
11170 struct bpf_reg_state *buff_reg = ®s[regno];
11171 const struct btf_param *buff_arg = &args[i];
11172 struct bpf_reg_state *size_reg = ®s[regno + 1];
11173 const struct btf_param *size_arg = &args[i + 1];
11175 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11176 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11178 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11183 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11184 if (meta->arg_constant.found) {
11185 verbose(env, "verifier internal error: only one constant argument permitted\n");
11188 if (!tnum_is_const(size_reg->var_off)) {
11189 verbose(env, "R%d must be a known constant\n", regno + 1);
11192 meta->arg_constant.found = true;
11193 meta->arg_constant.value = size_reg->var_off.value;
11196 /* Skip next '__sz' or '__szk' argument */
11200 case KF_ARG_PTR_TO_CALLBACK:
11201 meta->subprogno = reg->subprogno;
11203 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11204 if (!type_is_ptr_alloc_obj(reg->type)) {
11205 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11208 if (!type_is_non_owning_ref(reg->type))
11209 meta->arg_owning_ref = true;
11211 rec = reg_btf_record(reg);
11213 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11217 if (rec->refcount_off < 0) {
11218 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11221 if (rec->refcount_off >= 0) {
11222 verbose(env, "bpf_refcount_acquire calls are disabled for now\n");
11225 meta->arg_btf = reg->btf;
11226 meta->arg_btf_id = reg->btf_id;
11231 if (is_kfunc_release(meta) && !meta->release_regno) {
11232 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11240 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11241 struct bpf_insn *insn,
11242 struct bpf_kfunc_call_arg_meta *meta,
11243 const char **kfunc_name)
11245 const struct btf_type *func, *func_proto;
11246 u32 func_id, *kfunc_flags;
11247 const char *func_name;
11248 struct btf *desc_btf;
11251 *kfunc_name = NULL;
11256 desc_btf = find_kfunc_desc_btf(env, insn->off);
11257 if (IS_ERR(desc_btf))
11258 return PTR_ERR(desc_btf);
11260 func_id = insn->imm;
11261 func = btf_type_by_id(desc_btf, func_id);
11262 func_name = btf_name_by_offset(desc_btf, func->name_off);
11264 *kfunc_name = func_name;
11265 func_proto = btf_type_by_id(desc_btf, func->type);
11267 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11268 if (!kfunc_flags) {
11272 memset(meta, 0, sizeof(*meta));
11273 meta->btf = desc_btf;
11274 meta->func_id = func_id;
11275 meta->kfunc_flags = *kfunc_flags;
11276 meta->func_proto = func_proto;
11277 meta->func_name = func_name;
11282 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11285 const struct btf_type *t, *ptr_type;
11286 u32 i, nargs, ptr_type_id, release_ref_obj_id;
11287 struct bpf_reg_state *regs = cur_regs(env);
11288 const char *func_name, *ptr_type_name;
11289 bool sleepable, rcu_lock, rcu_unlock;
11290 struct bpf_kfunc_call_arg_meta meta;
11291 struct bpf_insn_aux_data *insn_aux;
11292 int err, insn_idx = *insn_idx_p;
11293 const struct btf_param *args;
11294 const struct btf_type *ret_t;
11295 struct btf *desc_btf;
11297 /* skip for now, but return error when we find this in fixup_kfunc_call */
11301 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11302 if (err == -EACCES && func_name)
11303 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11306 desc_btf = meta.btf;
11307 insn_aux = &env->insn_aux_data[insn_idx];
11309 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11311 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11312 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11316 sleepable = is_kfunc_sleepable(&meta);
11317 if (sleepable && !env->prog->aux->sleepable) {
11318 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11322 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11323 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11325 if (env->cur_state->active_rcu_lock) {
11326 struct bpf_func_state *state;
11327 struct bpf_reg_state *reg;
11330 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11332 } else if (rcu_unlock) {
11333 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11334 if (reg->type & MEM_RCU) {
11335 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11336 reg->type |= PTR_UNTRUSTED;
11339 env->cur_state->active_rcu_lock = false;
11340 } else if (sleepable) {
11341 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11344 } else if (rcu_lock) {
11345 env->cur_state->active_rcu_lock = true;
11346 } else if (rcu_unlock) {
11347 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11351 /* Check the arguments */
11352 err = check_kfunc_args(env, &meta, insn_idx);
11355 /* In case of release function, we get register number of refcounted
11356 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11358 if (meta.release_regno) {
11359 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11361 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11362 func_name, meta.func_id);
11367 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11368 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11369 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11370 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11371 insn_aux->insert_off = regs[BPF_REG_2].off;
11372 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11373 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11375 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11376 func_name, meta.func_id);
11380 err = release_reference(env, release_ref_obj_id);
11382 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11383 func_name, meta.func_id);
11388 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11389 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11390 set_rbtree_add_callback_state);
11392 verbose(env, "kfunc %s#%d failed callback verification\n",
11393 func_name, meta.func_id);
11398 for (i = 0; i < CALLER_SAVED_REGS; i++)
11399 mark_reg_not_init(env, regs, caller_saved[i]);
11401 /* Check return type */
11402 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11404 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11405 /* Only exception is bpf_obj_new_impl */
11406 if (meta.btf != btf_vmlinux ||
11407 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11408 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11409 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11414 if (btf_type_is_scalar(t)) {
11415 mark_reg_unknown(env, regs, BPF_REG_0);
11416 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11417 } else if (btf_type_is_ptr(t)) {
11418 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
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_new_impl]) {
11422 struct btf *ret_btf;
11425 if (unlikely(!bpf_global_ma_set))
11428 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11429 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11433 ret_btf = env->prog->aux->btf;
11434 ret_btf_id = meta.arg_constant.value;
11436 /* This may be NULL due to user not supplying a BTF */
11438 verbose(env, "bpf_obj_new requires prog BTF\n");
11442 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11443 if (!ret_t || !__btf_type_is_struct(ret_t)) {
11444 verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11448 mark_reg_known_zero(env, regs, BPF_REG_0);
11449 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11450 regs[BPF_REG_0].btf = ret_btf;
11451 regs[BPF_REG_0].btf_id = ret_btf_id;
11453 insn_aux->obj_new_size = ret_t->size;
11454 insn_aux->kptr_struct_meta =
11455 btf_find_struct_meta(ret_btf, ret_btf_id);
11456 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11457 mark_reg_known_zero(env, regs, BPF_REG_0);
11458 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11459 regs[BPF_REG_0].btf = meta.arg_btf;
11460 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11462 insn_aux->kptr_struct_meta =
11463 btf_find_struct_meta(meta.arg_btf,
11465 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11466 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11467 struct btf_field *field = meta.arg_list_head.field;
11469 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11470 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11471 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11472 struct btf_field *field = meta.arg_rbtree_root.field;
11474 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11475 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11476 mark_reg_known_zero(env, regs, BPF_REG_0);
11477 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11478 regs[BPF_REG_0].btf = desc_btf;
11479 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11480 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11481 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11482 if (!ret_t || !btf_type_is_struct(ret_t)) {
11484 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11488 mark_reg_known_zero(env, regs, BPF_REG_0);
11489 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11490 regs[BPF_REG_0].btf = desc_btf;
11491 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11492 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11493 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11494 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11496 mark_reg_known_zero(env, regs, BPF_REG_0);
11498 if (!meta.arg_constant.found) {
11499 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11503 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11505 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11506 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11508 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11509 regs[BPF_REG_0].type |= MEM_RDONLY;
11511 /* this will set env->seen_direct_write to true */
11512 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11513 verbose(env, "the prog does not allow writes to packet data\n");
11518 if (!meta.initialized_dynptr.id) {
11519 verbose(env, "verifier internal error: no dynptr id\n");
11522 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11524 /* we don't need to set BPF_REG_0's ref obj id
11525 * because packet slices are not refcounted (see
11526 * dynptr_type_refcounted)
11529 verbose(env, "kernel function %s unhandled dynamic return type\n",
11533 } else if (!__btf_type_is_struct(ptr_type)) {
11534 if (!meta.r0_size) {
11537 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11539 meta.r0_rdonly = true;
11542 if (!meta.r0_size) {
11543 ptr_type_name = btf_name_by_offset(desc_btf,
11544 ptr_type->name_off);
11546 "kernel function %s returns pointer type %s %s is not supported\n",
11548 btf_type_str(ptr_type),
11553 mark_reg_known_zero(env, regs, BPF_REG_0);
11554 regs[BPF_REG_0].type = PTR_TO_MEM;
11555 regs[BPF_REG_0].mem_size = meta.r0_size;
11557 if (meta.r0_rdonly)
11558 regs[BPF_REG_0].type |= MEM_RDONLY;
11560 /* Ensures we don't access the memory after a release_reference() */
11561 if (meta.ref_obj_id)
11562 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11564 mark_reg_known_zero(env, regs, BPF_REG_0);
11565 regs[BPF_REG_0].btf = desc_btf;
11566 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11567 regs[BPF_REG_0].btf_id = ptr_type_id;
11570 if (is_kfunc_ret_null(&meta)) {
11571 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11572 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11573 regs[BPF_REG_0].id = ++env->id_gen;
11575 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11576 if (is_kfunc_acquire(&meta)) {
11577 int id = acquire_reference_state(env, insn_idx);
11581 if (is_kfunc_ret_null(&meta))
11582 regs[BPF_REG_0].id = id;
11583 regs[BPF_REG_0].ref_obj_id = id;
11584 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11585 ref_set_non_owning(env, ®s[BPF_REG_0]);
11588 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
11589 regs[BPF_REG_0].id = ++env->id_gen;
11590 } else if (btf_type_is_void(t)) {
11591 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11592 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11593 insn_aux->kptr_struct_meta =
11594 btf_find_struct_meta(meta.arg_btf,
11600 nargs = btf_type_vlen(meta.func_proto);
11601 args = (const struct btf_param *)(meta.func_proto + 1);
11602 for (i = 0; i < nargs; i++) {
11605 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11606 if (btf_type_is_ptr(t))
11607 mark_btf_func_reg_size(env, regno, sizeof(void *));
11609 /* scalar. ensured by btf_check_kfunc_arg_match() */
11610 mark_btf_func_reg_size(env, regno, t->size);
11613 if (is_iter_next_kfunc(&meta)) {
11614 err = process_iter_next_call(env, insn_idx, &meta);
11622 static bool signed_add_overflows(s64 a, s64 b)
11624 /* Do the add in u64, where overflow is well-defined */
11625 s64 res = (s64)((u64)a + (u64)b);
11632 static bool signed_add32_overflows(s32 a, s32 b)
11634 /* Do the add in u32, where overflow is well-defined */
11635 s32 res = (s32)((u32)a + (u32)b);
11642 static bool signed_sub_overflows(s64 a, s64 b)
11644 /* Do the sub in u64, where overflow is well-defined */
11645 s64 res = (s64)((u64)a - (u64)b);
11652 static bool signed_sub32_overflows(s32 a, s32 b)
11654 /* Do the sub in u32, where overflow is well-defined */
11655 s32 res = (s32)((u32)a - (u32)b);
11662 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11663 const struct bpf_reg_state *reg,
11664 enum bpf_reg_type type)
11666 bool known = tnum_is_const(reg->var_off);
11667 s64 val = reg->var_off.value;
11668 s64 smin = reg->smin_value;
11670 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11671 verbose(env, "math between %s pointer and %lld is not allowed\n",
11672 reg_type_str(env, type), val);
11676 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11677 verbose(env, "%s pointer offset %d is not allowed\n",
11678 reg_type_str(env, type), reg->off);
11682 if (smin == S64_MIN) {
11683 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11684 reg_type_str(env, type));
11688 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11689 verbose(env, "value %lld makes %s pointer be out of bounds\n",
11690 smin, reg_type_str(env, type));
11698 REASON_BOUNDS = -1,
11705 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11706 u32 *alu_limit, bool mask_to_left)
11708 u32 max = 0, ptr_limit = 0;
11710 switch (ptr_reg->type) {
11712 /* Offset 0 is out-of-bounds, but acceptable start for the
11713 * left direction, see BPF_REG_FP. Also, unknown scalar
11714 * offset where we would need to deal with min/max bounds is
11715 * currently prohibited for unprivileged.
11717 max = MAX_BPF_STACK + mask_to_left;
11718 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11720 case PTR_TO_MAP_VALUE:
11721 max = ptr_reg->map_ptr->value_size;
11722 ptr_limit = (mask_to_left ?
11723 ptr_reg->smin_value :
11724 ptr_reg->umax_value) + ptr_reg->off;
11727 return REASON_TYPE;
11730 if (ptr_limit >= max)
11731 return REASON_LIMIT;
11732 *alu_limit = ptr_limit;
11736 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11737 const struct bpf_insn *insn)
11739 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11742 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11743 u32 alu_state, u32 alu_limit)
11745 /* If we arrived here from different branches with different
11746 * state or limits to sanitize, then this won't work.
11748 if (aux->alu_state &&
11749 (aux->alu_state != alu_state ||
11750 aux->alu_limit != alu_limit))
11751 return REASON_PATHS;
11753 /* Corresponding fixup done in do_misc_fixups(). */
11754 aux->alu_state = alu_state;
11755 aux->alu_limit = alu_limit;
11759 static int sanitize_val_alu(struct bpf_verifier_env *env,
11760 struct bpf_insn *insn)
11762 struct bpf_insn_aux_data *aux = cur_aux(env);
11764 if (can_skip_alu_sanitation(env, insn))
11767 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11770 static bool sanitize_needed(u8 opcode)
11772 return opcode == BPF_ADD || opcode == BPF_SUB;
11775 struct bpf_sanitize_info {
11776 struct bpf_insn_aux_data aux;
11780 static struct bpf_verifier_state *
11781 sanitize_speculative_path(struct bpf_verifier_env *env,
11782 const struct bpf_insn *insn,
11783 u32 next_idx, u32 curr_idx)
11785 struct bpf_verifier_state *branch;
11786 struct bpf_reg_state *regs;
11788 branch = push_stack(env, next_idx, curr_idx, true);
11789 if (branch && insn) {
11790 regs = branch->frame[branch->curframe]->regs;
11791 if (BPF_SRC(insn->code) == BPF_K) {
11792 mark_reg_unknown(env, regs, insn->dst_reg);
11793 } else if (BPF_SRC(insn->code) == BPF_X) {
11794 mark_reg_unknown(env, regs, insn->dst_reg);
11795 mark_reg_unknown(env, regs, insn->src_reg);
11801 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11802 struct bpf_insn *insn,
11803 const struct bpf_reg_state *ptr_reg,
11804 const struct bpf_reg_state *off_reg,
11805 struct bpf_reg_state *dst_reg,
11806 struct bpf_sanitize_info *info,
11807 const bool commit_window)
11809 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11810 struct bpf_verifier_state *vstate = env->cur_state;
11811 bool off_is_imm = tnum_is_const(off_reg->var_off);
11812 bool off_is_neg = off_reg->smin_value < 0;
11813 bool ptr_is_dst_reg = ptr_reg == dst_reg;
11814 u8 opcode = BPF_OP(insn->code);
11815 u32 alu_state, alu_limit;
11816 struct bpf_reg_state tmp;
11820 if (can_skip_alu_sanitation(env, insn))
11823 /* We already marked aux for masking from non-speculative
11824 * paths, thus we got here in the first place. We only care
11825 * to explore bad access from here.
11827 if (vstate->speculative)
11830 if (!commit_window) {
11831 if (!tnum_is_const(off_reg->var_off) &&
11832 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11833 return REASON_BOUNDS;
11835 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
11836 (opcode == BPF_SUB && !off_is_neg);
11839 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11843 if (commit_window) {
11844 /* In commit phase we narrow the masking window based on
11845 * the observed pointer move after the simulated operation.
11847 alu_state = info->aux.alu_state;
11848 alu_limit = abs(info->aux.alu_limit - alu_limit);
11850 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11851 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11852 alu_state |= ptr_is_dst_reg ?
11853 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11855 /* Limit pruning on unknown scalars to enable deep search for
11856 * potential masking differences from other program paths.
11859 env->explore_alu_limits = true;
11862 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11866 /* If we're in commit phase, we're done here given we already
11867 * pushed the truncated dst_reg into the speculative verification
11870 * Also, when register is a known constant, we rewrite register-based
11871 * operation to immediate-based, and thus do not need masking (and as
11872 * a consequence, do not need to simulate the zero-truncation either).
11874 if (commit_window || off_is_imm)
11877 /* Simulate and find potential out-of-bounds access under
11878 * speculative execution from truncation as a result of
11879 * masking when off was not within expected range. If off
11880 * sits in dst, then we temporarily need to move ptr there
11881 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11882 * for cases where we use K-based arithmetic in one direction
11883 * and truncated reg-based in the other in order to explore
11886 if (!ptr_is_dst_reg) {
11888 copy_register_state(dst_reg, ptr_reg);
11890 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11892 if (!ptr_is_dst_reg && ret)
11894 return !ret ? REASON_STACK : 0;
11897 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11899 struct bpf_verifier_state *vstate = env->cur_state;
11901 /* If we simulate paths under speculation, we don't update the
11902 * insn as 'seen' such that when we verify unreachable paths in
11903 * the non-speculative domain, sanitize_dead_code() can still
11904 * rewrite/sanitize them.
11906 if (!vstate->speculative)
11907 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11910 static int sanitize_err(struct bpf_verifier_env *env,
11911 const struct bpf_insn *insn, int reason,
11912 const struct bpf_reg_state *off_reg,
11913 const struct bpf_reg_state *dst_reg)
11915 static const char *err = "pointer arithmetic with it prohibited for !root";
11916 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11917 u32 dst = insn->dst_reg, src = insn->src_reg;
11920 case REASON_BOUNDS:
11921 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11922 off_reg == dst_reg ? dst : src, err);
11925 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11926 off_reg == dst_reg ? src : dst, err);
11929 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11933 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11937 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11941 verbose(env, "verifier internal error: unknown reason (%d)\n",
11949 /* check that stack access falls within stack limits and that 'reg' doesn't
11950 * have a variable offset.
11952 * Variable offset is prohibited for unprivileged mode for simplicity since it
11953 * requires corresponding support in Spectre masking for stack ALU. See also
11954 * retrieve_ptr_limit().
11957 * 'off' includes 'reg->off'.
11959 static int check_stack_access_for_ptr_arithmetic(
11960 struct bpf_verifier_env *env,
11962 const struct bpf_reg_state *reg,
11965 if (!tnum_is_const(reg->var_off)) {
11968 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11969 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11970 regno, tn_buf, off);
11974 if (off >= 0 || off < -MAX_BPF_STACK) {
11975 verbose(env, "R%d stack pointer arithmetic goes out of range, "
11976 "prohibited for !root; off=%d\n", regno, off);
11983 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11984 const struct bpf_insn *insn,
11985 const struct bpf_reg_state *dst_reg)
11987 u32 dst = insn->dst_reg;
11989 /* For unprivileged we require that resulting offset must be in bounds
11990 * in order to be able to sanitize access later on.
11992 if (env->bypass_spec_v1)
11995 switch (dst_reg->type) {
11997 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11998 dst_reg->off + dst_reg->var_off.value))
12001 case PTR_TO_MAP_VALUE:
12002 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12003 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12004 "prohibited for !root\n", dst);
12015 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12016 * Caller should also handle BPF_MOV case separately.
12017 * If we return -EACCES, caller may want to try again treating pointer as a
12018 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
12020 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12021 struct bpf_insn *insn,
12022 const struct bpf_reg_state *ptr_reg,
12023 const struct bpf_reg_state *off_reg)
12025 struct bpf_verifier_state *vstate = env->cur_state;
12026 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12027 struct bpf_reg_state *regs = state->regs, *dst_reg;
12028 bool known = tnum_is_const(off_reg->var_off);
12029 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12030 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12031 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12032 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12033 struct bpf_sanitize_info info = {};
12034 u8 opcode = BPF_OP(insn->code);
12035 u32 dst = insn->dst_reg;
12038 dst_reg = ®s[dst];
12040 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12041 smin_val > smax_val || umin_val > umax_val) {
12042 /* Taint dst register if offset had invalid bounds derived from
12043 * e.g. dead branches.
12045 __mark_reg_unknown(env, dst_reg);
12049 if (BPF_CLASS(insn->code) != BPF_ALU64) {
12050 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12051 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12052 __mark_reg_unknown(env, dst_reg);
12057 "R%d 32-bit pointer arithmetic prohibited\n",
12062 if (ptr_reg->type & PTR_MAYBE_NULL) {
12063 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12064 dst, reg_type_str(env, ptr_reg->type));
12068 switch (base_type(ptr_reg->type)) {
12069 case CONST_PTR_TO_MAP:
12070 /* smin_val represents the known value */
12071 if (known && smin_val == 0 && opcode == BPF_ADD)
12074 case PTR_TO_PACKET_END:
12075 case PTR_TO_SOCKET:
12076 case PTR_TO_SOCK_COMMON:
12077 case PTR_TO_TCP_SOCK:
12078 case PTR_TO_XDP_SOCK:
12079 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12080 dst, reg_type_str(env, ptr_reg->type));
12086 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12087 * The id may be overwritten later if we create a new variable offset.
12089 dst_reg->type = ptr_reg->type;
12090 dst_reg->id = ptr_reg->id;
12092 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12093 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12096 /* pointer types do not carry 32-bit bounds at the moment. */
12097 __mark_reg32_unbounded(dst_reg);
12099 if (sanitize_needed(opcode)) {
12100 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12103 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12108 /* We can take a fixed offset as long as it doesn't overflow
12109 * the s32 'off' field
12111 if (known && (ptr_reg->off + smin_val ==
12112 (s64)(s32)(ptr_reg->off + smin_val))) {
12113 /* pointer += K. Accumulate it into fixed offset */
12114 dst_reg->smin_value = smin_ptr;
12115 dst_reg->smax_value = smax_ptr;
12116 dst_reg->umin_value = umin_ptr;
12117 dst_reg->umax_value = umax_ptr;
12118 dst_reg->var_off = ptr_reg->var_off;
12119 dst_reg->off = ptr_reg->off + smin_val;
12120 dst_reg->raw = ptr_reg->raw;
12123 /* A new variable offset is created. Note that off_reg->off
12124 * == 0, since it's a scalar.
12125 * dst_reg gets the pointer type and since some positive
12126 * integer value was added to the pointer, give it a new 'id'
12127 * if it's a PTR_TO_PACKET.
12128 * this creates a new 'base' pointer, off_reg (variable) gets
12129 * added into the variable offset, and we copy the fixed offset
12132 if (signed_add_overflows(smin_ptr, smin_val) ||
12133 signed_add_overflows(smax_ptr, smax_val)) {
12134 dst_reg->smin_value = S64_MIN;
12135 dst_reg->smax_value = S64_MAX;
12137 dst_reg->smin_value = smin_ptr + smin_val;
12138 dst_reg->smax_value = smax_ptr + smax_val;
12140 if (umin_ptr + umin_val < umin_ptr ||
12141 umax_ptr + umax_val < umax_ptr) {
12142 dst_reg->umin_value = 0;
12143 dst_reg->umax_value = U64_MAX;
12145 dst_reg->umin_value = umin_ptr + umin_val;
12146 dst_reg->umax_value = umax_ptr + umax_val;
12148 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12149 dst_reg->off = ptr_reg->off;
12150 dst_reg->raw = ptr_reg->raw;
12151 if (reg_is_pkt_pointer(ptr_reg)) {
12152 dst_reg->id = ++env->id_gen;
12153 /* something was added to pkt_ptr, set range to zero */
12154 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12158 if (dst_reg == off_reg) {
12159 /* scalar -= pointer. Creates an unknown scalar */
12160 verbose(env, "R%d tried to subtract pointer from scalar\n",
12164 /* We don't allow subtraction from FP, because (according to
12165 * test_verifier.c test "invalid fp arithmetic", JITs might not
12166 * be able to deal with it.
12168 if (ptr_reg->type == PTR_TO_STACK) {
12169 verbose(env, "R%d subtraction from stack pointer prohibited\n",
12173 if (known && (ptr_reg->off - smin_val ==
12174 (s64)(s32)(ptr_reg->off - smin_val))) {
12175 /* pointer -= K. Subtract it from fixed offset */
12176 dst_reg->smin_value = smin_ptr;
12177 dst_reg->smax_value = smax_ptr;
12178 dst_reg->umin_value = umin_ptr;
12179 dst_reg->umax_value = umax_ptr;
12180 dst_reg->var_off = ptr_reg->var_off;
12181 dst_reg->id = ptr_reg->id;
12182 dst_reg->off = ptr_reg->off - smin_val;
12183 dst_reg->raw = ptr_reg->raw;
12186 /* A new variable offset is created. If the subtrahend is known
12187 * nonnegative, then any reg->range we had before is still good.
12189 if (signed_sub_overflows(smin_ptr, smax_val) ||
12190 signed_sub_overflows(smax_ptr, smin_val)) {
12191 /* Overflow possible, we know nothing */
12192 dst_reg->smin_value = S64_MIN;
12193 dst_reg->smax_value = S64_MAX;
12195 dst_reg->smin_value = smin_ptr - smax_val;
12196 dst_reg->smax_value = smax_ptr - smin_val;
12198 if (umin_ptr < umax_val) {
12199 /* Overflow possible, we know nothing */
12200 dst_reg->umin_value = 0;
12201 dst_reg->umax_value = U64_MAX;
12203 /* Cannot overflow (as long as bounds are consistent) */
12204 dst_reg->umin_value = umin_ptr - umax_val;
12205 dst_reg->umax_value = umax_ptr - umin_val;
12207 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12208 dst_reg->off = ptr_reg->off;
12209 dst_reg->raw = ptr_reg->raw;
12210 if (reg_is_pkt_pointer(ptr_reg)) {
12211 dst_reg->id = ++env->id_gen;
12212 /* something was added to pkt_ptr, set range to zero */
12214 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12220 /* bitwise ops on pointers are troublesome, prohibit. */
12221 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12222 dst, bpf_alu_string[opcode >> 4]);
12225 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12226 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12227 dst, bpf_alu_string[opcode >> 4]);
12231 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12233 reg_bounds_sync(dst_reg);
12234 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12236 if (sanitize_needed(opcode)) {
12237 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12240 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12246 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12247 struct bpf_reg_state *src_reg)
12249 s32 smin_val = src_reg->s32_min_value;
12250 s32 smax_val = src_reg->s32_max_value;
12251 u32 umin_val = src_reg->u32_min_value;
12252 u32 umax_val = src_reg->u32_max_value;
12254 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12255 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12256 dst_reg->s32_min_value = S32_MIN;
12257 dst_reg->s32_max_value = S32_MAX;
12259 dst_reg->s32_min_value += smin_val;
12260 dst_reg->s32_max_value += smax_val;
12262 if (dst_reg->u32_min_value + umin_val < umin_val ||
12263 dst_reg->u32_max_value + umax_val < umax_val) {
12264 dst_reg->u32_min_value = 0;
12265 dst_reg->u32_max_value = U32_MAX;
12267 dst_reg->u32_min_value += umin_val;
12268 dst_reg->u32_max_value += umax_val;
12272 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12273 struct bpf_reg_state *src_reg)
12275 s64 smin_val = src_reg->smin_value;
12276 s64 smax_val = src_reg->smax_value;
12277 u64 umin_val = src_reg->umin_value;
12278 u64 umax_val = src_reg->umax_value;
12280 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12281 signed_add_overflows(dst_reg->smax_value, smax_val)) {
12282 dst_reg->smin_value = S64_MIN;
12283 dst_reg->smax_value = S64_MAX;
12285 dst_reg->smin_value += smin_val;
12286 dst_reg->smax_value += smax_val;
12288 if (dst_reg->umin_value + umin_val < umin_val ||
12289 dst_reg->umax_value + umax_val < umax_val) {
12290 dst_reg->umin_value = 0;
12291 dst_reg->umax_value = U64_MAX;
12293 dst_reg->umin_value += umin_val;
12294 dst_reg->umax_value += umax_val;
12298 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12299 struct bpf_reg_state *src_reg)
12301 s32 smin_val = src_reg->s32_min_value;
12302 s32 smax_val = src_reg->s32_max_value;
12303 u32 umin_val = src_reg->u32_min_value;
12304 u32 umax_val = src_reg->u32_max_value;
12306 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12307 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12308 /* Overflow possible, we know nothing */
12309 dst_reg->s32_min_value = S32_MIN;
12310 dst_reg->s32_max_value = S32_MAX;
12312 dst_reg->s32_min_value -= smax_val;
12313 dst_reg->s32_max_value -= smin_val;
12315 if (dst_reg->u32_min_value < umax_val) {
12316 /* Overflow possible, we know nothing */
12317 dst_reg->u32_min_value = 0;
12318 dst_reg->u32_max_value = U32_MAX;
12320 /* Cannot overflow (as long as bounds are consistent) */
12321 dst_reg->u32_min_value -= umax_val;
12322 dst_reg->u32_max_value -= umin_val;
12326 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12327 struct bpf_reg_state *src_reg)
12329 s64 smin_val = src_reg->smin_value;
12330 s64 smax_val = src_reg->smax_value;
12331 u64 umin_val = src_reg->umin_value;
12332 u64 umax_val = src_reg->umax_value;
12334 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12335 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12336 /* Overflow possible, we know nothing */
12337 dst_reg->smin_value = S64_MIN;
12338 dst_reg->smax_value = S64_MAX;
12340 dst_reg->smin_value -= smax_val;
12341 dst_reg->smax_value -= smin_val;
12343 if (dst_reg->umin_value < umax_val) {
12344 /* Overflow possible, we know nothing */
12345 dst_reg->umin_value = 0;
12346 dst_reg->umax_value = U64_MAX;
12348 /* Cannot overflow (as long as bounds are consistent) */
12349 dst_reg->umin_value -= umax_val;
12350 dst_reg->umax_value -= umin_val;
12354 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12355 struct bpf_reg_state *src_reg)
12357 s32 smin_val = src_reg->s32_min_value;
12358 u32 umin_val = src_reg->u32_min_value;
12359 u32 umax_val = src_reg->u32_max_value;
12361 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12362 /* Ain't nobody got time to multiply that sign */
12363 __mark_reg32_unbounded(dst_reg);
12366 /* Both values are positive, so we can work with unsigned and
12367 * copy the result to signed (unless it exceeds S32_MAX).
12369 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12370 /* Potential overflow, we know nothing */
12371 __mark_reg32_unbounded(dst_reg);
12374 dst_reg->u32_min_value *= umin_val;
12375 dst_reg->u32_max_value *= umax_val;
12376 if (dst_reg->u32_max_value > S32_MAX) {
12377 /* Overflow possible, we know nothing */
12378 dst_reg->s32_min_value = S32_MIN;
12379 dst_reg->s32_max_value = S32_MAX;
12381 dst_reg->s32_min_value = dst_reg->u32_min_value;
12382 dst_reg->s32_max_value = dst_reg->u32_max_value;
12386 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12387 struct bpf_reg_state *src_reg)
12389 s64 smin_val = src_reg->smin_value;
12390 u64 umin_val = src_reg->umin_value;
12391 u64 umax_val = src_reg->umax_value;
12393 if (smin_val < 0 || dst_reg->smin_value < 0) {
12394 /* Ain't nobody got time to multiply that sign */
12395 __mark_reg64_unbounded(dst_reg);
12398 /* Both values are positive, so we can work with unsigned and
12399 * copy the result to signed (unless it exceeds S64_MAX).
12401 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12402 /* Potential overflow, we know nothing */
12403 __mark_reg64_unbounded(dst_reg);
12406 dst_reg->umin_value *= umin_val;
12407 dst_reg->umax_value *= umax_val;
12408 if (dst_reg->umax_value > S64_MAX) {
12409 /* Overflow possible, we know nothing */
12410 dst_reg->smin_value = S64_MIN;
12411 dst_reg->smax_value = S64_MAX;
12413 dst_reg->smin_value = dst_reg->umin_value;
12414 dst_reg->smax_value = dst_reg->umax_value;
12418 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12419 struct bpf_reg_state *src_reg)
12421 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12422 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12423 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12424 s32 smin_val = src_reg->s32_min_value;
12425 u32 umax_val = src_reg->u32_max_value;
12427 if (src_known && dst_known) {
12428 __mark_reg32_known(dst_reg, var32_off.value);
12432 /* We get our minimum from the var_off, since that's inherently
12433 * bitwise. Our maximum is the minimum of the operands' maxima.
12435 dst_reg->u32_min_value = var32_off.value;
12436 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12437 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12438 /* Lose signed bounds when ANDing negative numbers,
12439 * ain't nobody got time for that.
12441 dst_reg->s32_min_value = S32_MIN;
12442 dst_reg->s32_max_value = S32_MAX;
12444 /* ANDing two positives gives a positive, so safe to
12445 * cast result into s64.
12447 dst_reg->s32_min_value = dst_reg->u32_min_value;
12448 dst_reg->s32_max_value = dst_reg->u32_max_value;
12452 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12453 struct bpf_reg_state *src_reg)
12455 bool src_known = tnum_is_const(src_reg->var_off);
12456 bool dst_known = tnum_is_const(dst_reg->var_off);
12457 s64 smin_val = src_reg->smin_value;
12458 u64 umax_val = src_reg->umax_value;
12460 if (src_known && dst_known) {
12461 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12465 /* We get our minimum from the var_off, since that's inherently
12466 * bitwise. Our maximum is the minimum of the operands' maxima.
12468 dst_reg->umin_value = dst_reg->var_off.value;
12469 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12470 if (dst_reg->smin_value < 0 || smin_val < 0) {
12471 /* Lose signed bounds when ANDing negative numbers,
12472 * ain't nobody got time for that.
12474 dst_reg->smin_value = S64_MIN;
12475 dst_reg->smax_value = S64_MAX;
12477 /* ANDing two positives gives a positive, so safe to
12478 * cast result into s64.
12480 dst_reg->smin_value = dst_reg->umin_value;
12481 dst_reg->smax_value = dst_reg->umax_value;
12483 /* We may learn something more from the var_off */
12484 __update_reg_bounds(dst_reg);
12487 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12488 struct bpf_reg_state *src_reg)
12490 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12491 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12492 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12493 s32 smin_val = src_reg->s32_min_value;
12494 u32 umin_val = src_reg->u32_min_value;
12496 if (src_known && dst_known) {
12497 __mark_reg32_known(dst_reg, var32_off.value);
12501 /* We get our maximum from the var_off, and our minimum is the
12502 * maximum of the operands' minima
12504 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12505 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12506 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12507 /* Lose signed bounds when ORing negative numbers,
12508 * ain't nobody got time for that.
12510 dst_reg->s32_min_value = S32_MIN;
12511 dst_reg->s32_max_value = S32_MAX;
12513 /* ORing two positives gives a positive, so safe to
12514 * cast result into s64.
12516 dst_reg->s32_min_value = dst_reg->u32_min_value;
12517 dst_reg->s32_max_value = dst_reg->u32_max_value;
12521 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12522 struct bpf_reg_state *src_reg)
12524 bool src_known = tnum_is_const(src_reg->var_off);
12525 bool dst_known = tnum_is_const(dst_reg->var_off);
12526 s64 smin_val = src_reg->smin_value;
12527 u64 umin_val = src_reg->umin_value;
12529 if (src_known && dst_known) {
12530 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12534 /* We get our maximum from the var_off, and our minimum is the
12535 * maximum of the operands' minima
12537 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12538 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12539 if (dst_reg->smin_value < 0 || smin_val < 0) {
12540 /* Lose signed bounds when ORing negative numbers,
12541 * ain't nobody got time for that.
12543 dst_reg->smin_value = S64_MIN;
12544 dst_reg->smax_value = S64_MAX;
12546 /* ORing two positives gives a positive, so safe to
12547 * cast result into s64.
12549 dst_reg->smin_value = dst_reg->umin_value;
12550 dst_reg->smax_value = dst_reg->umax_value;
12552 /* We may learn something more from the var_off */
12553 __update_reg_bounds(dst_reg);
12556 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12557 struct bpf_reg_state *src_reg)
12559 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12560 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12561 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12562 s32 smin_val = src_reg->s32_min_value;
12564 if (src_known && dst_known) {
12565 __mark_reg32_known(dst_reg, var32_off.value);
12569 /* We get both minimum and maximum from the var32_off. */
12570 dst_reg->u32_min_value = var32_off.value;
12571 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12573 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12574 /* XORing two positive sign numbers gives a positive,
12575 * so safe to cast u32 result into s32.
12577 dst_reg->s32_min_value = dst_reg->u32_min_value;
12578 dst_reg->s32_max_value = dst_reg->u32_max_value;
12580 dst_reg->s32_min_value = S32_MIN;
12581 dst_reg->s32_max_value = S32_MAX;
12585 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12586 struct bpf_reg_state *src_reg)
12588 bool src_known = tnum_is_const(src_reg->var_off);
12589 bool dst_known = tnum_is_const(dst_reg->var_off);
12590 s64 smin_val = src_reg->smin_value;
12592 if (src_known && dst_known) {
12593 /* dst_reg->var_off.value has been updated earlier */
12594 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12598 /* We get both minimum and maximum from the var_off. */
12599 dst_reg->umin_value = dst_reg->var_off.value;
12600 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12602 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12603 /* XORing two positive sign numbers gives a positive,
12604 * so safe to cast u64 result into s64.
12606 dst_reg->smin_value = dst_reg->umin_value;
12607 dst_reg->smax_value = dst_reg->umax_value;
12609 dst_reg->smin_value = S64_MIN;
12610 dst_reg->smax_value = S64_MAX;
12613 __update_reg_bounds(dst_reg);
12616 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12617 u64 umin_val, u64 umax_val)
12619 /* We lose all sign bit information (except what we can pick
12622 dst_reg->s32_min_value = S32_MIN;
12623 dst_reg->s32_max_value = S32_MAX;
12624 /* If we might shift our top bit out, then we know nothing */
12625 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12626 dst_reg->u32_min_value = 0;
12627 dst_reg->u32_max_value = U32_MAX;
12629 dst_reg->u32_min_value <<= umin_val;
12630 dst_reg->u32_max_value <<= umax_val;
12634 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12635 struct bpf_reg_state *src_reg)
12637 u32 umax_val = src_reg->u32_max_value;
12638 u32 umin_val = src_reg->u32_min_value;
12639 /* u32 alu operation will zext upper bits */
12640 struct tnum subreg = tnum_subreg(dst_reg->var_off);
12642 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12643 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12644 /* Not required but being careful mark reg64 bounds as unknown so
12645 * that we are forced to pick them up from tnum and zext later and
12646 * if some path skips this step we are still safe.
12648 __mark_reg64_unbounded(dst_reg);
12649 __update_reg32_bounds(dst_reg);
12652 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12653 u64 umin_val, u64 umax_val)
12655 /* Special case <<32 because it is a common compiler pattern to sign
12656 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12657 * positive we know this shift will also be positive so we can track
12658 * bounds correctly. Otherwise we lose all sign bit information except
12659 * what we can pick up from var_off. Perhaps we can generalize this
12660 * later to shifts of any length.
12662 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12663 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12665 dst_reg->smax_value = S64_MAX;
12667 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12668 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12670 dst_reg->smin_value = S64_MIN;
12672 /* If we might shift our top bit out, then we know nothing */
12673 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12674 dst_reg->umin_value = 0;
12675 dst_reg->umax_value = U64_MAX;
12677 dst_reg->umin_value <<= umin_val;
12678 dst_reg->umax_value <<= umax_val;
12682 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12683 struct bpf_reg_state *src_reg)
12685 u64 umax_val = src_reg->umax_value;
12686 u64 umin_val = src_reg->umin_value;
12688 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
12689 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12690 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12692 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12693 /* We may learn something more from the var_off */
12694 __update_reg_bounds(dst_reg);
12697 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12698 struct bpf_reg_state *src_reg)
12700 struct tnum subreg = tnum_subreg(dst_reg->var_off);
12701 u32 umax_val = src_reg->u32_max_value;
12702 u32 umin_val = src_reg->u32_min_value;
12704 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12705 * be negative, then either:
12706 * 1) src_reg might be zero, so the sign bit of the result is
12707 * unknown, so we lose our signed bounds
12708 * 2) it's known negative, thus the unsigned bounds capture the
12710 * 3) the signed bounds cross zero, so they tell us nothing
12712 * If the value in dst_reg is known nonnegative, then again the
12713 * unsigned bounds capture the signed bounds.
12714 * Thus, in all cases it suffices to blow away our signed bounds
12715 * and rely on inferring new ones from the unsigned bounds and
12716 * var_off of the result.
12718 dst_reg->s32_min_value = S32_MIN;
12719 dst_reg->s32_max_value = S32_MAX;
12721 dst_reg->var_off = tnum_rshift(subreg, umin_val);
12722 dst_reg->u32_min_value >>= umax_val;
12723 dst_reg->u32_max_value >>= umin_val;
12725 __mark_reg64_unbounded(dst_reg);
12726 __update_reg32_bounds(dst_reg);
12729 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12730 struct bpf_reg_state *src_reg)
12732 u64 umax_val = src_reg->umax_value;
12733 u64 umin_val = src_reg->umin_value;
12735 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12736 * be negative, then either:
12737 * 1) src_reg might be zero, so the sign bit of the result is
12738 * unknown, so we lose our signed bounds
12739 * 2) it's known negative, thus the unsigned bounds capture the
12741 * 3) the signed bounds cross zero, so they tell us nothing
12743 * If the value in dst_reg is known nonnegative, then again the
12744 * unsigned bounds capture the signed bounds.
12745 * Thus, in all cases it suffices to blow away our signed bounds
12746 * and rely on inferring new ones from the unsigned bounds and
12747 * var_off of the result.
12749 dst_reg->smin_value = S64_MIN;
12750 dst_reg->smax_value = S64_MAX;
12751 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12752 dst_reg->umin_value >>= umax_val;
12753 dst_reg->umax_value >>= umin_val;
12755 /* Its not easy to operate on alu32 bounds here because it depends
12756 * on bits being shifted in. Take easy way out and mark unbounded
12757 * so we can recalculate later from tnum.
12759 __mark_reg32_unbounded(dst_reg);
12760 __update_reg_bounds(dst_reg);
12763 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12764 struct bpf_reg_state *src_reg)
12766 u64 umin_val = src_reg->u32_min_value;
12768 /* Upon reaching here, src_known is true and
12769 * umax_val is equal to umin_val.
12771 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12772 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12774 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12776 /* blow away the dst_reg umin_value/umax_value and rely on
12777 * dst_reg var_off to refine the result.
12779 dst_reg->u32_min_value = 0;
12780 dst_reg->u32_max_value = U32_MAX;
12782 __mark_reg64_unbounded(dst_reg);
12783 __update_reg32_bounds(dst_reg);
12786 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12787 struct bpf_reg_state *src_reg)
12789 u64 umin_val = src_reg->umin_value;
12791 /* Upon reaching here, src_known is true and umax_val is equal
12794 dst_reg->smin_value >>= umin_val;
12795 dst_reg->smax_value >>= umin_val;
12797 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12799 /* blow away the dst_reg umin_value/umax_value and rely on
12800 * dst_reg var_off to refine the result.
12802 dst_reg->umin_value = 0;
12803 dst_reg->umax_value = U64_MAX;
12805 /* Its not easy to operate on alu32 bounds here because it depends
12806 * on bits being shifted in from upper 32-bits. Take easy way out
12807 * and mark unbounded so we can recalculate later from tnum.
12809 __mark_reg32_unbounded(dst_reg);
12810 __update_reg_bounds(dst_reg);
12813 /* WARNING: This function does calculations on 64-bit values, but the actual
12814 * execution may occur on 32-bit values. Therefore, things like bitshifts
12815 * need extra checks in the 32-bit case.
12817 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12818 struct bpf_insn *insn,
12819 struct bpf_reg_state *dst_reg,
12820 struct bpf_reg_state src_reg)
12822 struct bpf_reg_state *regs = cur_regs(env);
12823 u8 opcode = BPF_OP(insn->code);
12825 s64 smin_val, smax_val;
12826 u64 umin_val, umax_val;
12827 s32 s32_min_val, s32_max_val;
12828 u32 u32_min_val, u32_max_val;
12829 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12830 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12833 smin_val = src_reg.smin_value;
12834 smax_val = src_reg.smax_value;
12835 umin_val = src_reg.umin_value;
12836 umax_val = src_reg.umax_value;
12838 s32_min_val = src_reg.s32_min_value;
12839 s32_max_val = src_reg.s32_max_value;
12840 u32_min_val = src_reg.u32_min_value;
12841 u32_max_val = src_reg.u32_max_value;
12844 src_known = tnum_subreg_is_const(src_reg.var_off);
12846 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12847 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12848 /* Taint dst register if offset had invalid bounds
12849 * derived from e.g. dead branches.
12851 __mark_reg_unknown(env, dst_reg);
12855 src_known = tnum_is_const(src_reg.var_off);
12857 (smin_val != smax_val || umin_val != umax_val)) ||
12858 smin_val > smax_val || umin_val > umax_val) {
12859 /* Taint dst register if offset had invalid bounds
12860 * derived from e.g. dead branches.
12862 __mark_reg_unknown(env, dst_reg);
12868 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12869 __mark_reg_unknown(env, dst_reg);
12873 if (sanitize_needed(opcode)) {
12874 ret = sanitize_val_alu(env, insn);
12876 return sanitize_err(env, insn, ret, NULL, NULL);
12879 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12880 * There are two classes of instructions: The first class we track both
12881 * alu32 and alu64 sign/unsigned bounds independently this provides the
12882 * greatest amount of precision when alu operations are mixed with jmp32
12883 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12884 * and BPF_OR. This is possible because these ops have fairly easy to
12885 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12886 * See alu32 verifier tests for examples. The second class of
12887 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12888 * with regards to tracking sign/unsigned bounds because the bits may
12889 * cross subreg boundaries in the alu64 case. When this happens we mark
12890 * the reg unbounded in the subreg bound space and use the resulting
12891 * tnum to calculate an approximation of the sign/unsigned bounds.
12895 scalar32_min_max_add(dst_reg, &src_reg);
12896 scalar_min_max_add(dst_reg, &src_reg);
12897 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12900 scalar32_min_max_sub(dst_reg, &src_reg);
12901 scalar_min_max_sub(dst_reg, &src_reg);
12902 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12905 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12906 scalar32_min_max_mul(dst_reg, &src_reg);
12907 scalar_min_max_mul(dst_reg, &src_reg);
12910 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12911 scalar32_min_max_and(dst_reg, &src_reg);
12912 scalar_min_max_and(dst_reg, &src_reg);
12915 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12916 scalar32_min_max_or(dst_reg, &src_reg);
12917 scalar_min_max_or(dst_reg, &src_reg);
12920 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12921 scalar32_min_max_xor(dst_reg, &src_reg);
12922 scalar_min_max_xor(dst_reg, &src_reg);
12925 if (umax_val >= insn_bitness) {
12926 /* Shifts greater than 31 or 63 are undefined.
12927 * This includes shifts by a negative number.
12929 mark_reg_unknown(env, regs, insn->dst_reg);
12933 scalar32_min_max_lsh(dst_reg, &src_reg);
12935 scalar_min_max_lsh(dst_reg, &src_reg);
12938 if (umax_val >= insn_bitness) {
12939 /* Shifts greater than 31 or 63 are undefined.
12940 * This includes shifts by a negative number.
12942 mark_reg_unknown(env, regs, insn->dst_reg);
12946 scalar32_min_max_rsh(dst_reg, &src_reg);
12948 scalar_min_max_rsh(dst_reg, &src_reg);
12951 if (umax_val >= insn_bitness) {
12952 /* Shifts greater than 31 or 63 are undefined.
12953 * This includes shifts by a negative number.
12955 mark_reg_unknown(env, regs, insn->dst_reg);
12959 scalar32_min_max_arsh(dst_reg, &src_reg);
12961 scalar_min_max_arsh(dst_reg, &src_reg);
12964 mark_reg_unknown(env, regs, insn->dst_reg);
12968 /* ALU32 ops are zero extended into 64bit register */
12970 zext_32_to_64(dst_reg);
12971 reg_bounds_sync(dst_reg);
12975 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12978 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12979 struct bpf_insn *insn)
12981 struct bpf_verifier_state *vstate = env->cur_state;
12982 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12983 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12984 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12985 u8 opcode = BPF_OP(insn->code);
12988 dst_reg = ®s[insn->dst_reg];
12990 if (dst_reg->type != SCALAR_VALUE)
12993 /* Make sure ID is cleared otherwise dst_reg min/max could be
12994 * incorrectly propagated into other registers by find_equal_scalars()
12997 if (BPF_SRC(insn->code) == BPF_X) {
12998 src_reg = ®s[insn->src_reg];
12999 if (src_reg->type != SCALAR_VALUE) {
13000 if (dst_reg->type != SCALAR_VALUE) {
13001 /* Combining two pointers by any ALU op yields
13002 * an arbitrary scalar. Disallow all math except
13003 * pointer subtraction
13005 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13006 mark_reg_unknown(env, regs, insn->dst_reg);
13009 verbose(env, "R%d pointer %s pointer prohibited\n",
13011 bpf_alu_string[opcode >> 4]);
13014 /* scalar += pointer
13015 * This is legal, but we have to reverse our
13016 * src/dest handling in computing the range
13018 err = mark_chain_precision(env, insn->dst_reg);
13021 return adjust_ptr_min_max_vals(env, insn,
13024 } else if (ptr_reg) {
13025 /* pointer += scalar */
13026 err = mark_chain_precision(env, insn->src_reg);
13029 return adjust_ptr_min_max_vals(env, insn,
13031 } else if (dst_reg->precise) {
13032 /* if dst_reg is precise, src_reg should be precise as well */
13033 err = mark_chain_precision(env, insn->src_reg);
13038 /* Pretend the src is a reg with a known value, since we only
13039 * need to be able to read from this state.
13041 off_reg.type = SCALAR_VALUE;
13042 __mark_reg_known(&off_reg, insn->imm);
13043 src_reg = &off_reg;
13044 if (ptr_reg) /* pointer += K */
13045 return adjust_ptr_min_max_vals(env, insn,
13049 /* Got here implies adding two SCALAR_VALUEs */
13050 if (WARN_ON_ONCE(ptr_reg)) {
13051 print_verifier_state(env, state, true);
13052 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13055 if (WARN_ON(!src_reg)) {
13056 print_verifier_state(env, state, true);
13057 verbose(env, "verifier internal error: no src_reg\n");
13060 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13063 /* check validity of 32-bit and 64-bit arithmetic operations */
13064 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13066 struct bpf_reg_state *regs = cur_regs(env);
13067 u8 opcode = BPF_OP(insn->code);
13070 if (opcode == BPF_END || opcode == BPF_NEG) {
13071 if (opcode == BPF_NEG) {
13072 if (BPF_SRC(insn->code) != BPF_K ||
13073 insn->src_reg != BPF_REG_0 ||
13074 insn->off != 0 || insn->imm != 0) {
13075 verbose(env, "BPF_NEG uses reserved fields\n");
13079 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13080 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13081 (BPF_CLASS(insn->code) == BPF_ALU64 &&
13082 BPF_SRC(insn->code) != BPF_TO_LE)) {
13083 verbose(env, "BPF_END uses reserved fields\n");
13088 /* check src operand */
13089 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13093 if (is_pointer_value(env, insn->dst_reg)) {
13094 verbose(env, "R%d pointer arithmetic prohibited\n",
13099 /* check dest operand */
13100 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13104 } else if (opcode == BPF_MOV) {
13106 if (BPF_SRC(insn->code) == BPF_X) {
13107 if (insn->imm != 0) {
13108 verbose(env, "BPF_MOV uses reserved fields\n");
13112 if (BPF_CLASS(insn->code) == BPF_ALU) {
13113 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13114 verbose(env, "BPF_MOV uses reserved fields\n");
13118 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13120 verbose(env, "BPF_MOV uses reserved fields\n");
13125 /* check src operand */
13126 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13130 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13131 verbose(env, "BPF_MOV uses reserved fields\n");
13136 /* check dest operand, mark as required later */
13137 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13141 if (BPF_SRC(insn->code) == BPF_X) {
13142 struct bpf_reg_state *src_reg = regs + insn->src_reg;
13143 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13144 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13145 !tnum_is_const(src_reg->var_off);
13147 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13148 if (insn->off == 0) {
13150 * copy register state to dest reg
13153 /* Assign src and dst registers the same ID
13154 * that will be used by find_equal_scalars()
13155 * to propagate min/max range.
13157 src_reg->id = ++env->id_gen;
13158 copy_register_state(dst_reg, src_reg);
13159 dst_reg->live |= REG_LIVE_WRITTEN;
13160 dst_reg->subreg_def = DEF_NOT_SUBREG;
13162 /* case: R1 = (s8, s16 s32)R2 */
13165 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13166 if (no_sext && need_id)
13167 src_reg->id = ++env->id_gen;
13168 copy_register_state(dst_reg, src_reg);
13171 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13172 dst_reg->live |= REG_LIVE_WRITTEN;
13173 dst_reg->subreg_def = DEF_NOT_SUBREG;
13176 /* R1 = (u32) R2 */
13177 if (is_pointer_value(env, insn->src_reg)) {
13179 "R%d partial copy of pointer\n",
13182 } else if (src_reg->type == SCALAR_VALUE) {
13183 if (insn->off == 0) {
13184 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13186 if (is_src_reg_u32 && need_id)
13187 src_reg->id = ++env->id_gen;
13188 copy_register_state(dst_reg, src_reg);
13189 /* Make sure ID is cleared if src_reg is not in u32
13190 * range otherwise dst_reg min/max could be incorrectly
13191 * propagated into src_reg by find_equal_scalars()
13193 if (!is_src_reg_u32)
13195 dst_reg->live |= REG_LIVE_WRITTEN;
13196 dst_reg->subreg_def = env->insn_idx + 1;
13198 /* case: W1 = (s8, s16)W2 */
13199 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13201 if (no_sext && need_id)
13202 src_reg->id = ++env->id_gen;
13203 copy_register_state(dst_reg, src_reg);
13206 dst_reg->live |= REG_LIVE_WRITTEN;
13207 dst_reg->subreg_def = env->insn_idx + 1;
13208 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13211 mark_reg_unknown(env, regs,
13214 zext_32_to_64(dst_reg);
13215 reg_bounds_sync(dst_reg);
13219 * remember the value we stored into this reg
13221 /* clear any state __mark_reg_known doesn't set */
13222 mark_reg_unknown(env, regs, insn->dst_reg);
13223 regs[insn->dst_reg].type = SCALAR_VALUE;
13224 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13225 __mark_reg_known(regs + insn->dst_reg,
13228 __mark_reg_known(regs + insn->dst_reg,
13233 } else if (opcode > BPF_END) {
13234 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13237 } else { /* all other ALU ops: and, sub, xor, add, ... */
13239 if (BPF_SRC(insn->code) == BPF_X) {
13240 if (insn->imm != 0 || insn->off != 0) {
13241 verbose(env, "BPF_ALU uses reserved fields\n");
13244 /* check src1 operand */
13245 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13249 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13250 verbose(env, "BPF_ALU uses reserved fields\n");
13255 /* check src2 operand */
13256 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13260 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13261 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13262 verbose(env, "div by zero\n");
13266 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13267 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13268 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13270 if (insn->imm < 0 || insn->imm >= size) {
13271 verbose(env, "invalid shift %d\n", insn->imm);
13276 /* check dest operand */
13277 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13281 return adjust_reg_min_max_vals(env, insn);
13287 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13288 struct bpf_reg_state *dst_reg,
13289 enum bpf_reg_type type,
13290 bool range_right_open)
13292 struct bpf_func_state *state;
13293 struct bpf_reg_state *reg;
13296 if (dst_reg->off < 0 ||
13297 (dst_reg->off == 0 && range_right_open))
13298 /* This doesn't give us any range */
13301 if (dst_reg->umax_value > MAX_PACKET_OFF ||
13302 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13303 /* Risk of overflow. For instance, ptr + (1<<63) may be less
13304 * than pkt_end, but that's because it's also less than pkt.
13308 new_range = dst_reg->off;
13309 if (range_right_open)
13312 /* Examples for register markings:
13314 * pkt_data in dst register:
13318 * if (r2 > pkt_end) goto <handle exception>
13323 * if (r2 < pkt_end) goto <access okay>
13324 * <handle exception>
13327 * r2 == dst_reg, pkt_end == src_reg
13328 * r2=pkt(id=n,off=8,r=0)
13329 * r3=pkt(id=n,off=0,r=0)
13331 * pkt_data in src register:
13335 * if (pkt_end >= r2) goto <access okay>
13336 * <handle exception>
13340 * if (pkt_end <= r2) goto <handle exception>
13344 * pkt_end == dst_reg, r2 == src_reg
13345 * r2=pkt(id=n,off=8,r=0)
13346 * r3=pkt(id=n,off=0,r=0)
13348 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13349 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13350 * and [r3, r3 + 8-1) respectively is safe to access depending on
13354 /* If our ids match, then we must have the same max_value. And we
13355 * don't care about the other reg's fixed offset, since if it's too big
13356 * the range won't allow anything.
13357 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13359 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13360 if (reg->type == type && reg->id == dst_reg->id)
13361 /* keep the maximum range already checked */
13362 reg->range = max(reg->range, new_range);
13366 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13368 struct tnum subreg = tnum_subreg(reg->var_off);
13369 s32 sval = (s32)val;
13373 if (tnum_is_const(subreg))
13374 return !!tnum_equals_const(subreg, val);
13375 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13379 if (tnum_is_const(subreg))
13380 return !tnum_equals_const(subreg, val);
13381 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13385 if ((~subreg.mask & subreg.value) & val)
13387 if (!((subreg.mask | subreg.value) & val))
13391 if (reg->u32_min_value > val)
13393 else if (reg->u32_max_value <= val)
13397 if (reg->s32_min_value > sval)
13399 else if (reg->s32_max_value <= sval)
13403 if (reg->u32_max_value < val)
13405 else if (reg->u32_min_value >= val)
13409 if (reg->s32_max_value < sval)
13411 else if (reg->s32_min_value >= sval)
13415 if (reg->u32_min_value >= val)
13417 else if (reg->u32_max_value < val)
13421 if (reg->s32_min_value >= sval)
13423 else if (reg->s32_max_value < sval)
13427 if (reg->u32_max_value <= val)
13429 else if (reg->u32_min_value > val)
13433 if (reg->s32_max_value <= sval)
13435 else if (reg->s32_min_value > sval)
13444 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13446 s64 sval = (s64)val;
13450 if (tnum_is_const(reg->var_off))
13451 return !!tnum_equals_const(reg->var_off, val);
13452 else if (val < reg->umin_value || val > reg->umax_value)
13456 if (tnum_is_const(reg->var_off))
13457 return !tnum_equals_const(reg->var_off, val);
13458 else if (val < reg->umin_value || val > reg->umax_value)
13462 if ((~reg->var_off.mask & reg->var_off.value) & val)
13464 if (!((reg->var_off.mask | reg->var_off.value) & val))
13468 if (reg->umin_value > val)
13470 else if (reg->umax_value <= val)
13474 if (reg->smin_value > sval)
13476 else if (reg->smax_value <= sval)
13480 if (reg->umax_value < val)
13482 else if (reg->umin_value >= val)
13486 if (reg->smax_value < sval)
13488 else if (reg->smin_value >= sval)
13492 if (reg->umin_value >= val)
13494 else if (reg->umax_value < val)
13498 if (reg->smin_value >= sval)
13500 else if (reg->smax_value < sval)
13504 if (reg->umax_value <= val)
13506 else if (reg->umin_value > val)
13510 if (reg->smax_value <= sval)
13512 else if (reg->smin_value > sval)
13520 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13522 * 1 - branch will be taken and "goto target" will be executed
13523 * 0 - branch will not be taken and fall-through to next insn
13524 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13527 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13530 if (__is_pointer_value(false, reg)) {
13531 if (!reg_not_null(reg))
13534 /* If pointer is valid tests against zero will fail so we can
13535 * use this to direct branch taken.
13551 return is_branch32_taken(reg, val, opcode);
13552 return is_branch64_taken(reg, val, opcode);
13555 static int flip_opcode(u32 opcode)
13557 /* How can we transform "a <op> b" into "b <op> a"? */
13558 static const u8 opcode_flip[16] = {
13559 /* these stay the same */
13560 [BPF_JEQ >> 4] = BPF_JEQ,
13561 [BPF_JNE >> 4] = BPF_JNE,
13562 [BPF_JSET >> 4] = BPF_JSET,
13563 /* these swap "lesser" and "greater" (L and G in the opcodes) */
13564 [BPF_JGE >> 4] = BPF_JLE,
13565 [BPF_JGT >> 4] = BPF_JLT,
13566 [BPF_JLE >> 4] = BPF_JGE,
13567 [BPF_JLT >> 4] = BPF_JGT,
13568 [BPF_JSGE >> 4] = BPF_JSLE,
13569 [BPF_JSGT >> 4] = BPF_JSLT,
13570 [BPF_JSLE >> 4] = BPF_JSGE,
13571 [BPF_JSLT >> 4] = BPF_JSGT
13573 return opcode_flip[opcode >> 4];
13576 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13577 struct bpf_reg_state *src_reg,
13580 struct bpf_reg_state *pkt;
13582 if (src_reg->type == PTR_TO_PACKET_END) {
13584 } else if (dst_reg->type == PTR_TO_PACKET_END) {
13586 opcode = flip_opcode(opcode);
13591 if (pkt->range >= 0)
13596 /* pkt <= pkt_end */
13599 /* pkt > pkt_end */
13600 if (pkt->range == BEYOND_PKT_END)
13601 /* pkt has at last one extra byte beyond pkt_end */
13602 return opcode == BPF_JGT;
13605 /* pkt < pkt_end */
13608 /* pkt >= pkt_end */
13609 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13610 return opcode == BPF_JGE;
13616 /* Adjusts the register min/max values in the case that the dst_reg is the
13617 * variable register that we are working on, and src_reg is a constant or we're
13618 * simply doing a BPF_K check.
13619 * In JEQ/JNE cases we also adjust the var_off values.
13621 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13622 struct bpf_reg_state *false_reg,
13623 u64 val, u32 val32,
13624 u8 opcode, bool is_jmp32)
13626 struct tnum false_32off = tnum_subreg(false_reg->var_off);
13627 struct tnum false_64off = false_reg->var_off;
13628 struct tnum true_32off = tnum_subreg(true_reg->var_off);
13629 struct tnum true_64off = true_reg->var_off;
13630 s64 sval = (s64)val;
13631 s32 sval32 = (s32)val32;
13633 /* If the dst_reg is a pointer, we can't learn anything about its
13634 * variable offset from the compare (unless src_reg were a pointer into
13635 * the same object, but we don't bother with that.
13636 * Since false_reg and true_reg have the same type by construction, we
13637 * only need to check one of them for pointerness.
13639 if (__is_pointer_value(false, false_reg))
13643 /* JEQ/JNE comparison doesn't change the register equivalence.
13646 * if (r1 == 42) goto label;
13648 * label: // here both r1 and r2 are known to be 42.
13650 * Hence when marking register as known preserve it's ID.
13654 __mark_reg32_known(true_reg, val32);
13655 true_32off = tnum_subreg(true_reg->var_off);
13657 ___mark_reg_known(true_reg, val);
13658 true_64off = true_reg->var_off;
13663 __mark_reg32_known(false_reg, val32);
13664 false_32off = tnum_subreg(false_reg->var_off);
13666 ___mark_reg_known(false_reg, val);
13667 false_64off = false_reg->var_off;
13672 false_32off = tnum_and(false_32off, tnum_const(~val32));
13673 if (is_power_of_2(val32))
13674 true_32off = tnum_or(true_32off,
13675 tnum_const(val32));
13677 false_64off = tnum_and(false_64off, tnum_const(~val));
13678 if (is_power_of_2(val))
13679 true_64off = tnum_or(true_64off,
13687 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
13688 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13690 false_reg->u32_max_value = min(false_reg->u32_max_value,
13692 true_reg->u32_min_value = max(true_reg->u32_min_value,
13695 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
13696 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13698 false_reg->umax_value = min(false_reg->umax_value, false_umax);
13699 true_reg->umin_value = max(true_reg->umin_value, true_umin);
13707 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
13708 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13710 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13711 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13713 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
13714 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13716 false_reg->smax_value = min(false_reg->smax_value, false_smax);
13717 true_reg->smin_value = max(true_reg->smin_value, true_smin);
13725 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
13726 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13728 false_reg->u32_min_value = max(false_reg->u32_min_value,
13730 true_reg->u32_max_value = min(true_reg->u32_max_value,
13733 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
13734 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13736 false_reg->umin_value = max(false_reg->umin_value, false_umin);
13737 true_reg->umax_value = min(true_reg->umax_value, true_umax);
13745 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
13746 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13748 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13749 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13751 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
13752 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13754 false_reg->smin_value = max(false_reg->smin_value, false_smin);
13755 true_reg->smax_value = min(true_reg->smax_value, true_smax);
13764 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13765 tnum_subreg(false_32off));
13766 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13767 tnum_subreg(true_32off));
13768 __reg_combine_32_into_64(false_reg);
13769 __reg_combine_32_into_64(true_reg);
13771 false_reg->var_off = false_64off;
13772 true_reg->var_off = true_64off;
13773 __reg_combine_64_into_32(false_reg);
13774 __reg_combine_64_into_32(true_reg);
13778 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13779 * the variable reg.
13781 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13782 struct bpf_reg_state *false_reg,
13783 u64 val, u32 val32,
13784 u8 opcode, bool is_jmp32)
13786 opcode = flip_opcode(opcode);
13787 /* This uses zero as "not present in table"; luckily the zero opcode,
13788 * BPF_JA, can't get here.
13791 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13794 /* Regs are known to be equal, so intersect their min/max/var_off */
13795 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13796 struct bpf_reg_state *dst_reg)
13798 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13799 dst_reg->umin_value);
13800 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13801 dst_reg->umax_value);
13802 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13803 dst_reg->smin_value);
13804 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13805 dst_reg->smax_value);
13806 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13808 reg_bounds_sync(src_reg);
13809 reg_bounds_sync(dst_reg);
13812 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13813 struct bpf_reg_state *true_dst,
13814 struct bpf_reg_state *false_src,
13815 struct bpf_reg_state *false_dst,
13820 __reg_combine_min_max(true_src, true_dst);
13823 __reg_combine_min_max(false_src, false_dst);
13828 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13829 struct bpf_reg_state *reg, u32 id,
13832 if (type_may_be_null(reg->type) && reg->id == id &&
13833 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13834 /* Old offset (both fixed and variable parts) should have been
13835 * known-zero, because we don't allow pointer arithmetic on
13836 * pointers that might be NULL. If we see this happening, don't
13837 * convert the register.
13839 * But in some cases, some helpers that return local kptrs
13840 * advance offset for the returned pointer. In those cases, it
13841 * is fine to expect to see reg->off.
13843 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13845 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13846 WARN_ON_ONCE(reg->off))
13850 reg->type = SCALAR_VALUE;
13851 /* We don't need id and ref_obj_id from this point
13852 * onwards anymore, thus we should better reset it,
13853 * so that state pruning has chances to take effect.
13856 reg->ref_obj_id = 0;
13861 mark_ptr_not_null_reg(reg);
13863 if (!reg_may_point_to_spin_lock(reg)) {
13864 /* For not-NULL ptr, reg->ref_obj_id will be reset
13865 * in release_reference().
13867 * reg->id is still used by spin_lock ptr. Other
13868 * than spin_lock ptr type, reg->id can be reset.
13875 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13876 * be folded together at some point.
13878 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13881 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13882 struct bpf_reg_state *regs = state->regs, *reg;
13883 u32 ref_obj_id = regs[regno].ref_obj_id;
13884 u32 id = regs[regno].id;
13886 if (ref_obj_id && ref_obj_id == id && is_null)
13887 /* regs[regno] is in the " == NULL" branch.
13888 * No one could have freed the reference state before
13889 * doing the NULL check.
13891 WARN_ON_ONCE(release_reference_state(state, id));
13893 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13894 mark_ptr_or_null_reg(state, reg, id, is_null);
13898 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13899 struct bpf_reg_state *dst_reg,
13900 struct bpf_reg_state *src_reg,
13901 struct bpf_verifier_state *this_branch,
13902 struct bpf_verifier_state *other_branch)
13904 if (BPF_SRC(insn->code) != BPF_X)
13907 /* Pointers are always 64-bit. */
13908 if (BPF_CLASS(insn->code) == BPF_JMP32)
13911 switch (BPF_OP(insn->code)) {
13913 if ((dst_reg->type == PTR_TO_PACKET &&
13914 src_reg->type == PTR_TO_PACKET_END) ||
13915 (dst_reg->type == PTR_TO_PACKET_META &&
13916 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13917 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13918 find_good_pkt_pointers(this_branch, dst_reg,
13919 dst_reg->type, false);
13920 mark_pkt_end(other_branch, insn->dst_reg, true);
13921 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13922 src_reg->type == PTR_TO_PACKET) ||
13923 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13924 src_reg->type == PTR_TO_PACKET_META)) {
13925 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13926 find_good_pkt_pointers(other_branch, src_reg,
13927 src_reg->type, true);
13928 mark_pkt_end(this_branch, insn->src_reg, false);
13934 if ((dst_reg->type == PTR_TO_PACKET &&
13935 src_reg->type == PTR_TO_PACKET_END) ||
13936 (dst_reg->type == PTR_TO_PACKET_META &&
13937 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13938 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13939 find_good_pkt_pointers(other_branch, dst_reg,
13940 dst_reg->type, true);
13941 mark_pkt_end(this_branch, insn->dst_reg, false);
13942 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13943 src_reg->type == PTR_TO_PACKET) ||
13944 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13945 src_reg->type == PTR_TO_PACKET_META)) {
13946 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13947 find_good_pkt_pointers(this_branch, src_reg,
13948 src_reg->type, false);
13949 mark_pkt_end(other_branch, insn->src_reg, true);
13955 if ((dst_reg->type == PTR_TO_PACKET &&
13956 src_reg->type == PTR_TO_PACKET_END) ||
13957 (dst_reg->type == PTR_TO_PACKET_META &&
13958 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13959 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13960 find_good_pkt_pointers(this_branch, dst_reg,
13961 dst_reg->type, true);
13962 mark_pkt_end(other_branch, insn->dst_reg, false);
13963 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13964 src_reg->type == PTR_TO_PACKET) ||
13965 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13966 src_reg->type == PTR_TO_PACKET_META)) {
13967 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13968 find_good_pkt_pointers(other_branch, src_reg,
13969 src_reg->type, false);
13970 mark_pkt_end(this_branch, insn->src_reg, true);
13976 if ((dst_reg->type == PTR_TO_PACKET &&
13977 src_reg->type == PTR_TO_PACKET_END) ||
13978 (dst_reg->type == PTR_TO_PACKET_META &&
13979 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13980 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13981 find_good_pkt_pointers(other_branch, dst_reg,
13982 dst_reg->type, false);
13983 mark_pkt_end(this_branch, insn->dst_reg, true);
13984 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13985 src_reg->type == PTR_TO_PACKET) ||
13986 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13987 src_reg->type == PTR_TO_PACKET_META)) {
13988 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13989 find_good_pkt_pointers(this_branch, src_reg,
13990 src_reg->type, true);
13991 mark_pkt_end(other_branch, insn->src_reg, false);
14003 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14004 struct bpf_reg_state *known_reg)
14006 struct bpf_func_state *state;
14007 struct bpf_reg_state *reg;
14009 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14010 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14011 copy_register_state(reg, known_reg);
14015 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14016 struct bpf_insn *insn, int *insn_idx)
14018 struct bpf_verifier_state *this_branch = env->cur_state;
14019 struct bpf_verifier_state *other_branch;
14020 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14021 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14022 struct bpf_reg_state *eq_branch_regs;
14023 u8 opcode = BPF_OP(insn->code);
14028 /* Only conditional jumps are expected to reach here. */
14029 if (opcode == BPF_JA || opcode > BPF_JSLE) {
14030 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14034 if (BPF_SRC(insn->code) == BPF_X) {
14035 if (insn->imm != 0) {
14036 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14040 /* check src1 operand */
14041 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14045 if (is_pointer_value(env, insn->src_reg)) {
14046 verbose(env, "R%d pointer comparison prohibited\n",
14050 src_reg = ®s[insn->src_reg];
14052 if (insn->src_reg != BPF_REG_0) {
14053 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14058 /* check src2 operand */
14059 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14063 dst_reg = ®s[insn->dst_reg];
14064 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14066 if (BPF_SRC(insn->code) == BPF_K) {
14067 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14068 } else if (src_reg->type == SCALAR_VALUE &&
14069 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14070 pred = is_branch_taken(dst_reg,
14071 tnum_subreg(src_reg->var_off).value,
14074 } else if (src_reg->type == SCALAR_VALUE &&
14075 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14076 pred = is_branch_taken(dst_reg,
14077 src_reg->var_off.value,
14080 } else if (dst_reg->type == SCALAR_VALUE &&
14081 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14082 pred = is_branch_taken(src_reg,
14083 tnum_subreg(dst_reg->var_off).value,
14084 flip_opcode(opcode),
14086 } else if (dst_reg->type == SCALAR_VALUE &&
14087 !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14088 pred = is_branch_taken(src_reg,
14089 dst_reg->var_off.value,
14090 flip_opcode(opcode),
14092 } else if (reg_is_pkt_pointer_any(dst_reg) &&
14093 reg_is_pkt_pointer_any(src_reg) &&
14095 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14099 /* If we get here with a dst_reg pointer type it is because
14100 * above is_branch_taken() special cased the 0 comparison.
14102 if (!__is_pointer_value(false, dst_reg))
14103 err = mark_chain_precision(env, insn->dst_reg);
14104 if (BPF_SRC(insn->code) == BPF_X && !err &&
14105 !__is_pointer_value(false, src_reg))
14106 err = mark_chain_precision(env, insn->src_reg);
14112 /* Only follow the goto, ignore fall-through. If needed, push
14113 * the fall-through branch for simulation under speculative
14116 if (!env->bypass_spec_v1 &&
14117 !sanitize_speculative_path(env, insn, *insn_idx + 1,
14120 *insn_idx += insn->off;
14122 } else if (pred == 0) {
14123 /* Only follow the fall-through branch, since that's where the
14124 * program will go. If needed, push the goto branch for
14125 * simulation under speculative execution.
14127 if (!env->bypass_spec_v1 &&
14128 !sanitize_speculative_path(env, insn,
14129 *insn_idx + insn->off + 1,
14135 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14139 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14141 /* detect if we are comparing against a constant value so we can adjust
14142 * our min/max values for our dst register.
14143 * this is only legit if both are scalars (or pointers to the same
14144 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14145 * because otherwise the different base pointers mean the offsets aren't
14148 if (BPF_SRC(insn->code) == BPF_X) {
14149 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
14151 if (dst_reg->type == SCALAR_VALUE &&
14152 src_reg->type == SCALAR_VALUE) {
14153 if (tnum_is_const(src_reg->var_off) ||
14155 tnum_is_const(tnum_subreg(src_reg->var_off))))
14156 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14158 src_reg->var_off.value,
14159 tnum_subreg(src_reg->var_off).value,
14161 else if (tnum_is_const(dst_reg->var_off) ||
14163 tnum_is_const(tnum_subreg(dst_reg->var_off))))
14164 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14166 dst_reg->var_off.value,
14167 tnum_subreg(dst_reg->var_off).value,
14169 else if (!is_jmp32 &&
14170 (opcode == BPF_JEQ || opcode == BPF_JNE))
14171 /* Comparing for equality, we can combine knowledge */
14172 reg_combine_min_max(&other_branch_regs[insn->src_reg],
14173 &other_branch_regs[insn->dst_reg],
14174 src_reg, dst_reg, opcode);
14176 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14177 find_equal_scalars(this_branch, src_reg);
14178 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14182 } else if (dst_reg->type == SCALAR_VALUE) {
14183 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14184 dst_reg, insn->imm, (u32)insn->imm,
14188 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14189 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14190 find_equal_scalars(this_branch, dst_reg);
14191 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14194 /* if one pointer register is compared to another pointer
14195 * register check if PTR_MAYBE_NULL could be lifted.
14196 * E.g. register A - maybe null
14197 * register B - not null
14198 * for JNE A, B, ... - A is not null in the false branch;
14199 * for JEQ A, B, ... - A is not null in the true branch.
14201 * Since PTR_TO_BTF_ID points to a kernel struct that does
14202 * not need to be null checked by the BPF program, i.e.,
14203 * could be null even without PTR_MAYBE_NULL marking, so
14204 * only propagate nullness when neither reg is that type.
14206 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14207 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14208 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14209 base_type(src_reg->type) != PTR_TO_BTF_ID &&
14210 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14211 eq_branch_regs = NULL;
14214 eq_branch_regs = other_branch_regs;
14217 eq_branch_regs = regs;
14223 if (eq_branch_regs) {
14224 if (type_may_be_null(src_reg->type))
14225 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14227 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14231 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14232 * NOTE: these optimizations below are related with pointer comparison
14233 * which will never be JMP32.
14235 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14236 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14237 type_may_be_null(dst_reg->type)) {
14238 /* Mark all identical registers in each branch as either
14239 * safe or unknown depending R == 0 or R != 0 conditional.
14241 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14242 opcode == BPF_JNE);
14243 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14244 opcode == BPF_JEQ);
14245 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
14246 this_branch, other_branch) &&
14247 is_pointer_value(env, insn->dst_reg)) {
14248 verbose(env, "R%d pointer comparison prohibited\n",
14252 if (env->log.level & BPF_LOG_LEVEL)
14253 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14257 /* verify BPF_LD_IMM64 instruction */
14258 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14260 struct bpf_insn_aux_data *aux = cur_aux(env);
14261 struct bpf_reg_state *regs = cur_regs(env);
14262 struct bpf_reg_state *dst_reg;
14263 struct bpf_map *map;
14266 if (BPF_SIZE(insn->code) != BPF_DW) {
14267 verbose(env, "invalid BPF_LD_IMM insn\n");
14270 if (insn->off != 0) {
14271 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14275 err = check_reg_arg(env, insn->dst_reg, DST_OP);
14279 dst_reg = ®s[insn->dst_reg];
14280 if (insn->src_reg == 0) {
14281 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14283 dst_reg->type = SCALAR_VALUE;
14284 __mark_reg_known(®s[insn->dst_reg], imm);
14288 /* All special src_reg cases are listed below. From this point onwards
14289 * we either succeed and assign a corresponding dst_reg->type after
14290 * zeroing the offset, or fail and reject the program.
14292 mark_reg_known_zero(env, regs, insn->dst_reg);
14294 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14295 dst_reg->type = aux->btf_var.reg_type;
14296 switch (base_type(dst_reg->type)) {
14298 dst_reg->mem_size = aux->btf_var.mem_size;
14300 case PTR_TO_BTF_ID:
14301 dst_reg->btf = aux->btf_var.btf;
14302 dst_reg->btf_id = aux->btf_var.btf_id;
14305 verbose(env, "bpf verifier is misconfigured\n");
14311 if (insn->src_reg == BPF_PSEUDO_FUNC) {
14312 struct bpf_prog_aux *aux = env->prog->aux;
14313 u32 subprogno = find_subprog(env,
14314 env->insn_idx + insn->imm + 1);
14316 if (!aux->func_info) {
14317 verbose(env, "missing btf func_info\n");
14320 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14321 verbose(env, "callback function not static\n");
14325 dst_reg->type = PTR_TO_FUNC;
14326 dst_reg->subprogno = subprogno;
14330 map = env->used_maps[aux->map_index];
14331 dst_reg->map_ptr = map;
14333 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14334 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14335 dst_reg->type = PTR_TO_MAP_VALUE;
14336 dst_reg->off = aux->map_off;
14337 WARN_ON_ONCE(map->max_entries != 1);
14338 /* We want reg->id to be same (0) as map_value is not distinct */
14339 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14340 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14341 dst_reg->type = CONST_PTR_TO_MAP;
14343 verbose(env, "bpf verifier is misconfigured\n");
14350 static bool may_access_skb(enum bpf_prog_type type)
14353 case BPF_PROG_TYPE_SOCKET_FILTER:
14354 case BPF_PROG_TYPE_SCHED_CLS:
14355 case BPF_PROG_TYPE_SCHED_ACT:
14362 /* verify safety of LD_ABS|LD_IND instructions:
14363 * - they can only appear in the programs where ctx == skb
14364 * - since they are wrappers of function calls, they scratch R1-R5 registers,
14365 * preserve R6-R9, and store return value into R0
14368 * ctx == skb == R6 == CTX
14371 * SRC == any register
14372 * IMM == 32-bit immediate
14375 * R0 - 8/16/32-bit skb data converted to cpu endianness
14377 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14379 struct bpf_reg_state *regs = cur_regs(env);
14380 static const int ctx_reg = BPF_REG_6;
14381 u8 mode = BPF_MODE(insn->code);
14384 if (!may_access_skb(resolve_prog_type(env->prog))) {
14385 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14389 if (!env->ops->gen_ld_abs) {
14390 verbose(env, "bpf verifier is misconfigured\n");
14394 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14395 BPF_SIZE(insn->code) == BPF_DW ||
14396 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14397 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14401 /* check whether implicit source operand (register R6) is readable */
14402 err = check_reg_arg(env, ctx_reg, SRC_OP);
14406 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14407 * gen_ld_abs() may terminate the program at runtime, leading to
14410 err = check_reference_leak(env);
14412 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14416 if (env->cur_state->active_lock.ptr) {
14417 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14421 if (env->cur_state->active_rcu_lock) {
14422 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14426 if (regs[ctx_reg].type != PTR_TO_CTX) {
14428 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14432 if (mode == BPF_IND) {
14433 /* check explicit source operand */
14434 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14439 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
14443 /* reset caller saved regs to unreadable */
14444 for (i = 0; i < CALLER_SAVED_REGS; i++) {
14445 mark_reg_not_init(env, regs, caller_saved[i]);
14446 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14449 /* mark destination R0 register as readable, since it contains
14450 * the value fetched from the packet.
14451 * Already marked as written above.
14453 mark_reg_unknown(env, regs, BPF_REG_0);
14454 /* ld_abs load up to 32-bit skb data. */
14455 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14459 static int check_return_code(struct bpf_verifier_env *env)
14461 struct tnum enforce_attach_type_range = tnum_unknown;
14462 const struct bpf_prog *prog = env->prog;
14463 struct bpf_reg_state *reg;
14464 struct tnum range = tnum_range(0, 1);
14465 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14467 struct bpf_func_state *frame = env->cur_state->frame[0];
14468 const bool is_subprog = frame->subprogno;
14470 /* LSM and struct_ops func-ptr's return type could be "void" */
14472 switch (prog_type) {
14473 case BPF_PROG_TYPE_LSM:
14474 if (prog->expected_attach_type == BPF_LSM_CGROUP)
14475 /* See below, can be 0 or 0-1 depending on hook. */
14478 case BPF_PROG_TYPE_STRUCT_OPS:
14479 if (!prog->aux->attach_func_proto->type)
14487 /* eBPF calling convention is such that R0 is used
14488 * to return the value from eBPF program.
14489 * Make sure that it's readable at this time
14490 * of bpf_exit, which means that program wrote
14491 * something into it earlier
14493 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14497 if (is_pointer_value(env, BPF_REG_0)) {
14498 verbose(env, "R0 leaks addr as return value\n");
14502 reg = cur_regs(env) + BPF_REG_0;
14504 if (frame->in_async_callback_fn) {
14505 /* enforce return zero from async callbacks like timer */
14506 if (reg->type != SCALAR_VALUE) {
14507 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14508 reg_type_str(env, reg->type));
14512 if (!tnum_in(tnum_const(0), reg->var_off)) {
14513 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
14520 if (reg->type != SCALAR_VALUE) {
14521 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14522 reg_type_str(env, reg->type));
14528 switch (prog_type) {
14529 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14530 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14531 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14532 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14533 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14534 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14535 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14536 range = tnum_range(1, 1);
14537 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14538 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14539 range = tnum_range(0, 3);
14541 case BPF_PROG_TYPE_CGROUP_SKB:
14542 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14543 range = tnum_range(0, 3);
14544 enforce_attach_type_range = tnum_range(2, 3);
14547 case BPF_PROG_TYPE_CGROUP_SOCK:
14548 case BPF_PROG_TYPE_SOCK_OPS:
14549 case BPF_PROG_TYPE_CGROUP_DEVICE:
14550 case BPF_PROG_TYPE_CGROUP_SYSCTL:
14551 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14553 case BPF_PROG_TYPE_RAW_TRACEPOINT:
14554 if (!env->prog->aux->attach_btf_id)
14556 range = tnum_const(0);
14558 case BPF_PROG_TYPE_TRACING:
14559 switch (env->prog->expected_attach_type) {
14560 case BPF_TRACE_FENTRY:
14561 case BPF_TRACE_FEXIT:
14562 range = tnum_const(0);
14564 case BPF_TRACE_RAW_TP:
14565 case BPF_MODIFY_RETURN:
14567 case BPF_TRACE_ITER:
14573 case BPF_PROG_TYPE_SK_LOOKUP:
14574 range = tnum_range(SK_DROP, SK_PASS);
14577 case BPF_PROG_TYPE_LSM:
14578 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14579 /* Regular BPF_PROG_TYPE_LSM programs can return
14584 if (!env->prog->aux->attach_func_proto->type) {
14585 /* Make sure programs that attach to void
14586 * hooks don't try to modify return value.
14588 range = tnum_range(1, 1);
14592 case BPF_PROG_TYPE_NETFILTER:
14593 range = tnum_range(NF_DROP, NF_ACCEPT);
14595 case BPF_PROG_TYPE_EXT:
14596 /* freplace program can return anything as its return value
14597 * depends on the to-be-replaced kernel func or bpf program.
14603 if (reg->type != SCALAR_VALUE) {
14604 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14605 reg_type_str(env, reg->type));
14609 if (!tnum_in(range, reg->var_off)) {
14610 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14611 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14612 prog_type == BPF_PROG_TYPE_LSM &&
14613 !prog->aux->attach_func_proto->type)
14614 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14618 if (!tnum_is_unknown(enforce_attach_type_range) &&
14619 tnum_in(enforce_attach_type_range, reg->var_off))
14620 env->prog->enforce_expected_attach_type = 1;
14624 /* non-recursive DFS pseudo code
14625 * 1 procedure DFS-iterative(G,v):
14626 * 2 label v as discovered
14627 * 3 let S be a stack
14629 * 5 while S is not empty
14631 * 7 if t is what we're looking for:
14633 * 9 for all edges e in G.adjacentEdges(t) do
14634 * 10 if edge e is already labelled
14635 * 11 continue with the next edge
14636 * 12 w <- G.adjacentVertex(t,e)
14637 * 13 if vertex w is not discovered and not explored
14638 * 14 label e as tree-edge
14639 * 15 label w as discovered
14642 * 18 else if vertex w is discovered
14643 * 19 label e as back-edge
14645 * 21 // vertex w is explored
14646 * 22 label e as forward- or cross-edge
14647 * 23 label t as explored
14651 * 0x10 - discovered
14652 * 0x11 - discovered and fall-through edge labelled
14653 * 0x12 - discovered and fall-through and branch edges labelled
14664 static u32 state_htab_size(struct bpf_verifier_env *env)
14666 return env->prog->len;
14669 static struct bpf_verifier_state_list **explored_state(
14670 struct bpf_verifier_env *env,
14673 struct bpf_verifier_state *cur = env->cur_state;
14674 struct bpf_func_state *state = cur->frame[cur->curframe];
14676 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14679 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14681 env->insn_aux_data[idx].prune_point = true;
14684 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14686 return env->insn_aux_data[insn_idx].prune_point;
14689 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14691 env->insn_aux_data[idx].force_checkpoint = true;
14694 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14696 return env->insn_aux_data[insn_idx].force_checkpoint;
14701 DONE_EXPLORING = 0,
14702 KEEP_EXPLORING = 1,
14705 /* t, w, e - match pseudo-code above:
14706 * t - index of current instruction
14707 * w - next instruction
14710 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14713 int *insn_stack = env->cfg.insn_stack;
14714 int *insn_state = env->cfg.insn_state;
14716 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14717 return DONE_EXPLORING;
14719 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14720 return DONE_EXPLORING;
14722 if (w < 0 || w >= env->prog->len) {
14723 verbose_linfo(env, t, "%d: ", t);
14724 verbose(env, "jump out of range from insn %d to %d\n", t, w);
14729 /* mark branch target for state pruning */
14730 mark_prune_point(env, w);
14731 mark_jmp_point(env, w);
14734 if (insn_state[w] == 0) {
14736 insn_state[t] = DISCOVERED | e;
14737 insn_state[w] = DISCOVERED;
14738 if (env->cfg.cur_stack >= env->prog->len)
14740 insn_stack[env->cfg.cur_stack++] = w;
14741 return KEEP_EXPLORING;
14742 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14743 if (loop_ok && env->bpf_capable)
14744 return DONE_EXPLORING;
14745 verbose_linfo(env, t, "%d: ", t);
14746 verbose_linfo(env, w, "%d: ", w);
14747 verbose(env, "back-edge from insn %d to %d\n", t, w);
14749 } else if (insn_state[w] == EXPLORED) {
14750 /* forward- or cross-edge */
14751 insn_state[t] = DISCOVERED | e;
14753 verbose(env, "insn state internal bug\n");
14756 return DONE_EXPLORING;
14759 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14760 struct bpf_verifier_env *env,
14765 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14769 mark_prune_point(env, t + 1);
14770 /* when we exit from subprog, we need to record non-linear history */
14771 mark_jmp_point(env, t + 1);
14773 if (visit_callee) {
14774 mark_prune_point(env, t);
14775 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14776 /* It's ok to allow recursion from CFG point of
14777 * view. __check_func_call() will do the actual
14780 bpf_pseudo_func(insns + t));
14785 /* Visits the instruction at index t and returns one of the following:
14786 * < 0 - an error occurred
14787 * DONE_EXPLORING - the instruction was fully explored
14788 * KEEP_EXPLORING - there is still work to be done before it is fully explored
14790 static int visit_insn(int t, struct bpf_verifier_env *env)
14792 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14795 if (bpf_pseudo_func(insn))
14796 return visit_func_call_insn(t, insns, env, true);
14798 /* All non-branch instructions have a single fall-through edge. */
14799 if (BPF_CLASS(insn->code) != BPF_JMP &&
14800 BPF_CLASS(insn->code) != BPF_JMP32)
14801 return push_insn(t, t + 1, FALLTHROUGH, env, false);
14803 switch (BPF_OP(insn->code)) {
14805 return DONE_EXPLORING;
14808 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14809 /* Mark this call insn as a prune point to trigger
14810 * is_state_visited() check before call itself is
14811 * processed by __check_func_call(). Otherwise new
14812 * async state will be pushed for further exploration.
14814 mark_prune_point(env, t);
14815 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14816 struct bpf_kfunc_call_arg_meta meta;
14818 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14819 if (ret == 0 && is_iter_next_kfunc(&meta)) {
14820 mark_prune_point(env, t);
14821 /* Checking and saving state checkpoints at iter_next() call
14822 * is crucial for fast convergence of open-coded iterator loop
14823 * logic, so we need to force it. If we don't do that,
14824 * is_state_visited() might skip saving a checkpoint, causing
14825 * unnecessarily long sequence of not checkpointed
14826 * instructions and jumps, leading to exhaustion of jump
14827 * history buffer, and potentially other undesired outcomes.
14828 * It is expected that with correct open-coded iterators
14829 * convergence will happen quickly, so we don't run a risk of
14830 * exhausting memory.
14832 mark_force_checkpoint(env, t);
14835 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14838 if (BPF_SRC(insn->code) != BPF_K)
14841 /* unconditional jump with single edge */
14842 ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
14847 mark_prune_point(env, t + insn->off + 1);
14848 mark_jmp_point(env, t + insn->off + 1);
14853 /* conditional jump with two edges */
14854 mark_prune_point(env, t);
14856 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14860 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14864 /* non-recursive depth-first-search to detect loops in BPF program
14865 * loop == back-edge in directed graph
14867 static int check_cfg(struct bpf_verifier_env *env)
14869 int insn_cnt = env->prog->len;
14870 int *insn_stack, *insn_state;
14874 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14878 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14880 kvfree(insn_state);
14884 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14885 insn_stack[0] = 0; /* 0 is the first instruction */
14886 env->cfg.cur_stack = 1;
14888 while (env->cfg.cur_stack > 0) {
14889 int t = insn_stack[env->cfg.cur_stack - 1];
14891 ret = visit_insn(t, env);
14893 case DONE_EXPLORING:
14894 insn_state[t] = EXPLORED;
14895 env->cfg.cur_stack--;
14897 case KEEP_EXPLORING:
14901 verbose(env, "visit_insn internal bug\n");
14908 if (env->cfg.cur_stack < 0) {
14909 verbose(env, "pop stack internal bug\n");
14914 for (i = 0; i < insn_cnt; i++) {
14915 if (insn_state[i] != EXPLORED) {
14916 verbose(env, "unreachable insn %d\n", i);
14921 ret = 0; /* cfg looks good */
14924 kvfree(insn_state);
14925 kvfree(insn_stack);
14926 env->cfg.insn_state = env->cfg.insn_stack = NULL;
14930 static int check_abnormal_return(struct bpf_verifier_env *env)
14934 for (i = 1; i < env->subprog_cnt; i++) {
14935 if (env->subprog_info[i].has_ld_abs) {
14936 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14939 if (env->subprog_info[i].has_tail_call) {
14940 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14947 /* The minimum supported BTF func info size */
14948 #define MIN_BPF_FUNCINFO_SIZE 8
14949 #define MAX_FUNCINFO_REC_SIZE 252
14951 static int check_btf_func(struct bpf_verifier_env *env,
14952 const union bpf_attr *attr,
14955 const struct btf_type *type, *func_proto, *ret_type;
14956 u32 i, nfuncs, urec_size, min_size;
14957 u32 krec_size = sizeof(struct bpf_func_info);
14958 struct bpf_func_info *krecord;
14959 struct bpf_func_info_aux *info_aux = NULL;
14960 struct bpf_prog *prog;
14961 const struct btf *btf;
14963 u32 prev_offset = 0;
14964 bool scalar_return;
14967 nfuncs = attr->func_info_cnt;
14969 if (check_abnormal_return(env))
14974 if (nfuncs != env->subprog_cnt) {
14975 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14979 urec_size = attr->func_info_rec_size;
14980 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14981 urec_size > MAX_FUNCINFO_REC_SIZE ||
14982 urec_size % sizeof(u32)) {
14983 verbose(env, "invalid func info rec size %u\n", urec_size);
14988 btf = prog->aux->btf;
14990 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
14991 min_size = min_t(u32, krec_size, urec_size);
14993 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
14996 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15000 for (i = 0; i < nfuncs; i++) {
15001 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15003 if (ret == -E2BIG) {
15004 verbose(env, "nonzero tailing record in func info");
15005 /* set the size kernel expects so loader can zero
15006 * out the rest of the record.
15008 if (copy_to_bpfptr_offset(uattr,
15009 offsetof(union bpf_attr, func_info_rec_size),
15010 &min_size, sizeof(min_size)))
15016 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15021 /* check insn_off */
15024 if (krecord[i].insn_off) {
15026 "nonzero insn_off %u for the first func info record",
15027 krecord[i].insn_off);
15030 } else if (krecord[i].insn_off <= prev_offset) {
15032 "same or smaller insn offset (%u) than previous func info record (%u)",
15033 krecord[i].insn_off, prev_offset);
15037 if (env->subprog_info[i].start != krecord[i].insn_off) {
15038 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15042 /* check type_id */
15043 type = btf_type_by_id(btf, krecord[i].type_id);
15044 if (!type || !btf_type_is_func(type)) {
15045 verbose(env, "invalid type id %d in func info",
15046 krecord[i].type_id);
15049 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15051 func_proto = btf_type_by_id(btf, type->type);
15052 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15053 /* btf_func_check() already verified it during BTF load */
15055 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15057 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15058 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15059 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15062 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15063 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15067 prev_offset = krecord[i].insn_off;
15068 bpfptr_add(&urecord, urec_size);
15071 prog->aux->func_info = krecord;
15072 prog->aux->func_info_cnt = nfuncs;
15073 prog->aux->func_info_aux = info_aux;
15082 static void adjust_btf_func(struct bpf_verifier_env *env)
15084 struct bpf_prog_aux *aux = env->prog->aux;
15087 if (!aux->func_info)
15090 for (i = 0; i < env->subprog_cnt; i++)
15091 aux->func_info[i].insn_off = env->subprog_info[i].start;
15094 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
15095 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
15097 static int check_btf_line(struct bpf_verifier_env *env,
15098 const union bpf_attr *attr,
15101 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15102 struct bpf_subprog_info *sub;
15103 struct bpf_line_info *linfo;
15104 struct bpf_prog *prog;
15105 const struct btf *btf;
15109 nr_linfo = attr->line_info_cnt;
15112 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15115 rec_size = attr->line_info_rec_size;
15116 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15117 rec_size > MAX_LINEINFO_REC_SIZE ||
15118 rec_size & (sizeof(u32) - 1))
15121 /* Need to zero it in case the userspace may
15122 * pass in a smaller bpf_line_info object.
15124 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15125 GFP_KERNEL | __GFP_NOWARN);
15130 btf = prog->aux->btf;
15133 sub = env->subprog_info;
15134 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15135 expected_size = sizeof(struct bpf_line_info);
15136 ncopy = min_t(u32, expected_size, rec_size);
15137 for (i = 0; i < nr_linfo; i++) {
15138 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15140 if (err == -E2BIG) {
15141 verbose(env, "nonzero tailing record in line_info");
15142 if (copy_to_bpfptr_offset(uattr,
15143 offsetof(union bpf_attr, line_info_rec_size),
15144 &expected_size, sizeof(expected_size)))
15150 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15156 * Check insn_off to ensure
15157 * 1) strictly increasing AND
15158 * 2) bounded by prog->len
15160 * The linfo[0].insn_off == 0 check logically falls into
15161 * the later "missing bpf_line_info for func..." case
15162 * because the first linfo[0].insn_off must be the
15163 * first sub also and the first sub must have
15164 * subprog_info[0].start == 0.
15166 if ((i && linfo[i].insn_off <= prev_offset) ||
15167 linfo[i].insn_off >= prog->len) {
15168 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15169 i, linfo[i].insn_off, prev_offset,
15175 if (!prog->insnsi[linfo[i].insn_off].code) {
15177 "Invalid insn code at line_info[%u].insn_off\n",
15183 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15184 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15185 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15190 if (s != env->subprog_cnt) {
15191 if (linfo[i].insn_off == sub[s].start) {
15192 sub[s].linfo_idx = i;
15194 } else if (sub[s].start < linfo[i].insn_off) {
15195 verbose(env, "missing bpf_line_info for func#%u\n", s);
15201 prev_offset = linfo[i].insn_off;
15202 bpfptr_add(&ulinfo, rec_size);
15205 if (s != env->subprog_cnt) {
15206 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15207 env->subprog_cnt - s, s);
15212 prog->aux->linfo = linfo;
15213 prog->aux->nr_linfo = nr_linfo;
15222 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
15223 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
15225 static int check_core_relo(struct bpf_verifier_env *env,
15226 const union bpf_attr *attr,
15229 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15230 struct bpf_core_relo core_relo = {};
15231 struct bpf_prog *prog = env->prog;
15232 const struct btf *btf = prog->aux->btf;
15233 struct bpf_core_ctx ctx = {
15237 bpfptr_t u_core_relo;
15240 nr_core_relo = attr->core_relo_cnt;
15243 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15246 rec_size = attr->core_relo_rec_size;
15247 if (rec_size < MIN_CORE_RELO_SIZE ||
15248 rec_size > MAX_CORE_RELO_SIZE ||
15249 rec_size % sizeof(u32))
15252 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15253 expected_size = sizeof(struct bpf_core_relo);
15254 ncopy = min_t(u32, expected_size, rec_size);
15256 /* Unlike func_info and line_info, copy and apply each CO-RE
15257 * relocation record one at a time.
15259 for (i = 0; i < nr_core_relo; i++) {
15260 /* future proofing when sizeof(bpf_core_relo) changes */
15261 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15263 if (err == -E2BIG) {
15264 verbose(env, "nonzero tailing record in core_relo");
15265 if (copy_to_bpfptr_offset(uattr,
15266 offsetof(union bpf_attr, core_relo_rec_size),
15267 &expected_size, sizeof(expected_size)))
15273 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15278 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15279 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15280 i, core_relo.insn_off, prog->len);
15285 err = bpf_core_apply(&ctx, &core_relo, i,
15286 &prog->insnsi[core_relo.insn_off / 8]);
15289 bpfptr_add(&u_core_relo, rec_size);
15294 static int check_btf_info(struct bpf_verifier_env *env,
15295 const union bpf_attr *attr,
15301 if (!attr->func_info_cnt && !attr->line_info_cnt) {
15302 if (check_abnormal_return(env))
15307 btf = btf_get_by_fd(attr->prog_btf_fd);
15309 return PTR_ERR(btf);
15310 if (btf_is_kernel(btf)) {
15314 env->prog->aux->btf = btf;
15316 err = check_btf_func(env, attr, uattr);
15320 err = check_btf_line(env, attr, uattr);
15324 err = check_core_relo(env, attr, uattr);
15331 /* check %cur's range satisfies %old's */
15332 static bool range_within(struct bpf_reg_state *old,
15333 struct bpf_reg_state *cur)
15335 return old->umin_value <= cur->umin_value &&
15336 old->umax_value >= cur->umax_value &&
15337 old->smin_value <= cur->smin_value &&
15338 old->smax_value >= cur->smax_value &&
15339 old->u32_min_value <= cur->u32_min_value &&
15340 old->u32_max_value >= cur->u32_max_value &&
15341 old->s32_min_value <= cur->s32_min_value &&
15342 old->s32_max_value >= cur->s32_max_value;
15345 /* If in the old state two registers had the same id, then they need to have
15346 * the same id in the new state as well. But that id could be different from
15347 * the old state, so we need to track the mapping from old to new ids.
15348 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15349 * regs with old id 5 must also have new id 9 for the new state to be safe. But
15350 * regs with a different old id could still have new id 9, we don't care about
15352 * So we look through our idmap to see if this old id has been seen before. If
15353 * so, we require the new id to match; otherwise, we add the id pair to the map.
15355 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15357 struct bpf_id_pair *map = idmap->map;
15360 /* either both IDs should be set or both should be zero */
15361 if (!!old_id != !!cur_id)
15364 if (old_id == 0) /* cur_id == 0 as well */
15367 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15369 /* Reached an empty slot; haven't seen this id before */
15370 map[i].old = old_id;
15371 map[i].cur = cur_id;
15374 if (map[i].old == old_id)
15375 return map[i].cur == cur_id;
15376 if (map[i].cur == cur_id)
15379 /* We ran out of idmap slots, which should be impossible */
15384 /* Similar to check_ids(), but allocate a unique temporary ID
15385 * for 'old_id' or 'cur_id' of zero.
15386 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15388 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15390 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15391 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15393 return check_ids(old_id, cur_id, idmap);
15396 static void clean_func_state(struct bpf_verifier_env *env,
15397 struct bpf_func_state *st)
15399 enum bpf_reg_liveness live;
15402 for (i = 0; i < BPF_REG_FP; i++) {
15403 live = st->regs[i].live;
15404 /* liveness must not touch this register anymore */
15405 st->regs[i].live |= REG_LIVE_DONE;
15406 if (!(live & REG_LIVE_READ))
15407 /* since the register is unused, clear its state
15408 * to make further comparison simpler
15410 __mark_reg_not_init(env, &st->regs[i]);
15413 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15414 live = st->stack[i].spilled_ptr.live;
15415 /* liveness must not touch this stack slot anymore */
15416 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15417 if (!(live & REG_LIVE_READ)) {
15418 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15419 for (j = 0; j < BPF_REG_SIZE; j++)
15420 st->stack[i].slot_type[j] = STACK_INVALID;
15425 static void clean_verifier_state(struct bpf_verifier_env *env,
15426 struct bpf_verifier_state *st)
15430 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15431 /* all regs in this state in all frames were already marked */
15434 for (i = 0; i <= st->curframe; i++)
15435 clean_func_state(env, st->frame[i]);
15438 /* the parentage chains form a tree.
15439 * the verifier states are added to state lists at given insn and
15440 * pushed into state stack for future exploration.
15441 * when the verifier reaches bpf_exit insn some of the verifer states
15442 * stored in the state lists have their final liveness state already,
15443 * but a lot of states will get revised from liveness point of view when
15444 * the verifier explores other branches.
15447 * 2: if r1 == 100 goto pc+1
15450 * when the verifier reaches exit insn the register r0 in the state list of
15451 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15452 * of insn 2 and goes exploring further. At the insn 4 it will walk the
15453 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15455 * Since the verifier pushes the branch states as it sees them while exploring
15456 * the program the condition of walking the branch instruction for the second
15457 * time means that all states below this branch were already explored and
15458 * their final liveness marks are already propagated.
15459 * Hence when the verifier completes the search of state list in is_state_visited()
15460 * we can call this clean_live_states() function to mark all liveness states
15461 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15462 * will not be used.
15463 * This function also clears the registers and stack for states that !READ
15464 * to simplify state merging.
15466 * Important note here that walking the same branch instruction in the callee
15467 * doesn't meant that the states are DONE. The verifier has to compare
15470 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15471 struct bpf_verifier_state *cur)
15473 struct bpf_verifier_state_list *sl;
15476 sl = *explored_state(env, insn);
15478 if (sl->state.branches)
15480 if (sl->state.insn_idx != insn ||
15481 sl->state.curframe != cur->curframe)
15483 for (i = 0; i <= cur->curframe; i++)
15484 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15486 clean_verifier_state(env, &sl->state);
15492 static bool regs_exact(const struct bpf_reg_state *rold,
15493 const struct bpf_reg_state *rcur,
15494 struct bpf_idmap *idmap)
15496 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15497 check_ids(rold->id, rcur->id, idmap) &&
15498 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15501 /* Returns true if (rold safe implies rcur safe) */
15502 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15503 struct bpf_reg_state *rcur, struct bpf_idmap *idmap)
15505 if (!(rold->live & REG_LIVE_READ))
15506 /* explored state didn't use this */
15508 if (rold->type == NOT_INIT)
15509 /* explored state can't have used this */
15511 if (rcur->type == NOT_INIT)
15514 /* Enforce that register types have to match exactly, including their
15515 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15518 * One can make a point that using a pointer register as unbounded
15519 * SCALAR would be technically acceptable, but this could lead to
15520 * pointer leaks because scalars are allowed to leak while pointers
15521 * are not. We could make this safe in special cases if root is
15522 * calling us, but it's probably not worth the hassle.
15524 * Also, register types that are *not* MAYBE_NULL could technically be
15525 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15526 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15527 * to the same map).
15528 * However, if the old MAYBE_NULL register then got NULL checked,
15529 * doing so could have affected others with the same id, and we can't
15530 * check for that because we lost the id when we converted to
15531 * a non-MAYBE_NULL variant.
15532 * So, as a general rule we don't allow mixing MAYBE_NULL and
15533 * non-MAYBE_NULL registers as well.
15535 if (rold->type != rcur->type)
15538 switch (base_type(rold->type)) {
15540 if (env->explore_alu_limits) {
15541 /* explore_alu_limits disables tnum_in() and range_within()
15542 * logic and requires everything to be strict
15544 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15545 check_scalar_ids(rold->id, rcur->id, idmap);
15547 if (!rold->precise)
15549 /* Why check_ids() for scalar registers?
15551 * Consider the following BPF code:
15552 * 1: r6 = ... unbound scalar, ID=a ...
15553 * 2: r7 = ... unbound scalar, ID=b ...
15554 * 3: if (r6 > r7) goto +1
15556 * 5: if (r6 > X) goto ...
15557 * 6: ... memory operation using r7 ...
15559 * First verification path is [1-6]:
15560 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15561 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15562 * r7 <= X, because r6 and r7 share same id.
15563 * Next verification path is [1-4, 6].
15565 * Instruction (6) would be reached in two states:
15566 * I. r6{.id=b}, r7{.id=b} via path 1-6;
15567 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15569 * Use check_ids() to distinguish these states.
15571 * Also verify that new value satisfies old value range knowledge.
15573 return range_within(rold, rcur) &&
15574 tnum_in(rold->var_off, rcur->var_off) &&
15575 check_scalar_ids(rold->id, rcur->id, idmap);
15576 case PTR_TO_MAP_KEY:
15577 case PTR_TO_MAP_VALUE:
15580 case PTR_TO_TP_BUFFER:
15581 /* If the new min/max/var_off satisfy the old ones and
15582 * everything else matches, we are OK.
15584 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15585 range_within(rold, rcur) &&
15586 tnum_in(rold->var_off, rcur->var_off) &&
15587 check_ids(rold->id, rcur->id, idmap) &&
15588 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15589 case PTR_TO_PACKET_META:
15590 case PTR_TO_PACKET:
15591 /* We must have at least as much range as the old ptr
15592 * did, so that any accesses which were safe before are
15593 * still safe. This is true even if old range < old off,
15594 * since someone could have accessed through (ptr - k), or
15595 * even done ptr -= k in a register, to get a safe access.
15597 if (rold->range > rcur->range)
15599 /* If the offsets don't match, we can't trust our alignment;
15600 * nor can we be sure that we won't fall out of range.
15602 if (rold->off != rcur->off)
15604 /* id relations must be preserved */
15605 if (!check_ids(rold->id, rcur->id, idmap))
15607 /* new val must satisfy old val knowledge */
15608 return range_within(rold, rcur) &&
15609 tnum_in(rold->var_off, rcur->var_off);
15611 /* two stack pointers are equal only if they're pointing to
15612 * the same stack frame, since fp-8 in foo != fp-8 in bar
15614 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15616 return regs_exact(rold, rcur, idmap);
15620 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15621 struct bpf_func_state *cur, struct bpf_idmap *idmap)
15625 /* walk slots of the explored stack and ignore any additional
15626 * slots in the current stack, since explored(safe) state
15629 for (i = 0; i < old->allocated_stack; i++) {
15630 struct bpf_reg_state *old_reg, *cur_reg;
15632 spi = i / BPF_REG_SIZE;
15634 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15635 i += BPF_REG_SIZE - 1;
15636 /* explored state didn't use this */
15640 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15643 if (env->allow_uninit_stack &&
15644 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15647 /* explored stack has more populated slots than current stack
15648 * and these slots were used
15650 if (i >= cur->allocated_stack)
15653 /* if old state was safe with misc data in the stack
15654 * it will be safe with zero-initialized stack.
15655 * The opposite is not true
15657 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15658 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15660 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15661 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15662 /* Ex: old explored (safe) state has STACK_SPILL in
15663 * this stack slot, but current has STACK_MISC ->
15664 * this verifier states are not equivalent,
15665 * return false to continue verification of this path
15668 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15670 /* Both old and cur are having same slot_type */
15671 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15673 /* when explored and current stack slot are both storing
15674 * spilled registers, check that stored pointers types
15675 * are the same as well.
15676 * Ex: explored safe path could have stored
15677 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15678 * but current path has stored:
15679 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15680 * such verifier states are not equivalent.
15681 * return false to continue verification of this path
15683 if (!regsafe(env, &old->stack[spi].spilled_ptr,
15684 &cur->stack[spi].spilled_ptr, idmap))
15688 old_reg = &old->stack[spi].spilled_ptr;
15689 cur_reg = &cur->stack[spi].spilled_ptr;
15690 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15691 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15692 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15696 old_reg = &old->stack[spi].spilled_ptr;
15697 cur_reg = &cur->stack[spi].spilled_ptr;
15698 /* iter.depth is not compared between states as it
15699 * doesn't matter for correctness and would otherwise
15700 * prevent convergence; we maintain it only to prevent
15701 * infinite loop check triggering, see
15702 * iter_active_depths_differ()
15704 if (old_reg->iter.btf != cur_reg->iter.btf ||
15705 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15706 old_reg->iter.state != cur_reg->iter.state ||
15707 /* ignore {old_reg,cur_reg}->iter.depth, see above */
15708 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15713 case STACK_INVALID:
15715 /* Ensure that new unhandled slot types return false by default */
15723 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15724 struct bpf_idmap *idmap)
15728 if (old->acquired_refs != cur->acquired_refs)
15731 for (i = 0; i < old->acquired_refs; i++) {
15732 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15739 /* compare two verifier states
15741 * all states stored in state_list are known to be valid, since
15742 * verifier reached 'bpf_exit' instruction through them
15744 * this function is called when verifier exploring different branches of
15745 * execution popped from the state stack. If it sees an old state that has
15746 * more strict register state and more strict stack state then this execution
15747 * branch doesn't need to be explored further, since verifier already
15748 * concluded that more strict state leads to valid finish.
15750 * Therefore two states are equivalent if register state is more conservative
15751 * and explored stack state is more conservative than the current one.
15754 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15755 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15757 * In other words if current stack state (one being explored) has more
15758 * valid slots than old one that already passed validation, it means
15759 * the verifier can stop exploring and conclude that current state is valid too
15761 * Similarly with registers. If explored state has register type as invalid
15762 * whereas register type in current state is meaningful, it means that
15763 * the current state will reach 'bpf_exit' instruction safely
15765 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15766 struct bpf_func_state *cur)
15770 for (i = 0; i < MAX_BPF_REG; i++)
15771 if (!regsafe(env, &old->regs[i], &cur->regs[i],
15772 &env->idmap_scratch))
15775 if (!stacksafe(env, old, cur, &env->idmap_scratch))
15778 if (!refsafe(old, cur, &env->idmap_scratch))
15784 static bool states_equal(struct bpf_verifier_env *env,
15785 struct bpf_verifier_state *old,
15786 struct bpf_verifier_state *cur)
15790 if (old->curframe != cur->curframe)
15793 env->idmap_scratch.tmp_id_gen = env->id_gen;
15794 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
15796 /* Verification state from speculative execution simulation
15797 * must never prune a non-speculative execution one.
15799 if (old->speculative && !cur->speculative)
15802 if (old->active_lock.ptr != cur->active_lock.ptr)
15805 /* Old and cur active_lock's have to be either both present
15808 if (!!old->active_lock.id != !!cur->active_lock.id)
15811 if (old->active_lock.id &&
15812 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
15815 if (old->active_rcu_lock != cur->active_rcu_lock)
15818 /* for states to be equal callsites have to be the same
15819 * and all frame states need to be equivalent
15821 for (i = 0; i <= old->curframe; i++) {
15822 if (old->frame[i]->callsite != cur->frame[i]->callsite)
15824 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15830 /* Return 0 if no propagation happened. Return negative error code if error
15831 * happened. Otherwise, return the propagated bit.
15833 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15834 struct bpf_reg_state *reg,
15835 struct bpf_reg_state *parent_reg)
15837 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15838 u8 flag = reg->live & REG_LIVE_READ;
15841 /* When comes here, read flags of PARENT_REG or REG could be any of
15842 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15843 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15845 if (parent_flag == REG_LIVE_READ64 ||
15846 /* Or if there is no read flag from REG. */
15848 /* Or if the read flag from REG is the same as PARENT_REG. */
15849 parent_flag == flag)
15852 err = mark_reg_read(env, reg, parent_reg, flag);
15859 /* A write screens off any subsequent reads; but write marks come from the
15860 * straight-line code between a state and its parent. When we arrive at an
15861 * equivalent state (jump target or such) we didn't arrive by the straight-line
15862 * code, so read marks in the state must propagate to the parent regardless
15863 * of the state's write marks. That's what 'parent == state->parent' comparison
15864 * in mark_reg_read() is for.
15866 static int propagate_liveness(struct bpf_verifier_env *env,
15867 const struct bpf_verifier_state *vstate,
15868 struct bpf_verifier_state *vparent)
15870 struct bpf_reg_state *state_reg, *parent_reg;
15871 struct bpf_func_state *state, *parent;
15872 int i, frame, err = 0;
15874 if (vparent->curframe != vstate->curframe) {
15875 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15876 vparent->curframe, vstate->curframe);
15879 /* Propagate read liveness of registers... */
15880 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15881 for (frame = 0; frame <= vstate->curframe; frame++) {
15882 parent = vparent->frame[frame];
15883 state = vstate->frame[frame];
15884 parent_reg = parent->regs;
15885 state_reg = state->regs;
15886 /* We don't need to worry about FP liveness, it's read-only */
15887 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15888 err = propagate_liveness_reg(env, &state_reg[i],
15892 if (err == REG_LIVE_READ64)
15893 mark_insn_zext(env, &parent_reg[i]);
15896 /* Propagate stack slots. */
15897 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15898 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15899 parent_reg = &parent->stack[i].spilled_ptr;
15900 state_reg = &state->stack[i].spilled_ptr;
15901 err = propagate_liveness_reg(env, state_reg,
15910 /* find precise scalars in the previous equivalent state and
15911 * propagate them into the current state
15913 static int propagate_precision(struct bpf_verifier_env *env,
15914 const struct bpf_verifier_state *old)
15916 struct bpf_reg_state *state_reg;
15917 struct bpf_func_state *state;
15918 int i, err = 0, fr;
15921 for (fr = old->curframe; fr >= 0; fr--) {
15922 state = old->frame[fr];
15923 state_reg = state->regs;
15925 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15926 if (state_reg->type != SCALAR_VALUE ||
15927 !state_reg->precise ||
15928 !(state_reg->live & REG_LIVE_READ))
15930 if (env->log.level & BPF_LOG_LEVEL2) {
15932 verbose(env, "frame %d: propagating r%d", fr, i);
15934 verbose(env, ",r%d", i);
15936 bt_set_frame_reg(&env->bt, fr, i);
15940 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15941 if (!is_spilled_reg(&state->stack[i]))
15943 state_reg = &state->stack[i].spilled_ptr;
15944 if (state_reg->type != SCALAR_VALUE ||
15945 !state_reg->precise ||
15946 !(state_reg->live & REG_LIVE_READ))
15948 if (env->log.level & BPF_LOG_LEVEL2) {
15950 verbose(env, "frame %d: propagating fp%d",
15951 fr, (-i - 1) * BPF_REG_SIZE);
15953 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15955 bt_set_frame_slot(&env->bt, fr, i);
15959 verbose(env, "\n");
15962 err = mark_chain_precision_batch(env);
15969 static bool states_maybe_looping(struct bpf_verifier_state *old,
15970 struct bpf_verifier_state *cur)
15972 struct bpf_func_state *fold, *fcur;
15973 int i, fr = cur->curframe;
15975 if (old->curframe != fr)
15978 fold = old->frame[fr];
15979 fcur = cur->frame[fr];
15980 for (i = 0; i < MAX_BPF_REG; i++)
15981 if (memcmp(&fold->regs[i], &fcur->regs[i],
15982 offsetof(struct bpf_reg_state, parent)))
15987 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15989 return env->insn_aux_data[insn_idx].is_iter_next;
15992 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
15993 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15994 * states to match, which otherwise would look like an infinite loop. So while
15995 * iter_next() calls are taken care of, we still need to be careful and
15996 * prevent erroneous and too eager declaration of "ininite loop", when
15997 * iterators are involved.
15999 * Here's a situation in pseudo-BPF assembly form:
16001 * 0: again: ; set up iter_next() call args
16002 * 1: r1 = &it ; <CHECKPOINT HERE>
16003 * 2: call bpf_iter_num_next ; this is iter_next() call
16004 * 3: if r0 == 0 goto done
16005 * 4: ... something useful here ...
16006 * 5: goto again ; another iteration
16009 * 8: call bpf_iter_num_destroy ; clean up iter state
16012 * This is a typical loop. Let's assume that we have a prune point at 1:,
16013 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16014 * again`, assuming other heuristics don't get in a way).
16016 * When we first time come to 1:, let's say we have some state X. We proceed
16017 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16018 * Now we come back to validate that forked ACTIVE state. We proceed through
16019 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16020 * are converging. But the problem is that we don't know that yet, as this
16021 * convergence has to happen at iter_next() call site only. So if nothing is
16022 * done, at 1: verifier will use bounded loop logic and declare infinite
16023 * looping (and would be *technically* correct, if not for iterator's
16024 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16025 * don't want that. So what we do in process_iter_next_call() when we go on
16026 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16027 * a different iteration. So when we suspect an infinite loop, we additionally
16028 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16029 * pretend we are not looping and wait for next iter_next() call.
16031 * This only applies to ACTIVE state. In DRAINED state we don't expect to
16032 * loop, because that would actually mean infinite loop, as DRAINED state is
16033 * "sticky", and so we'll keep returning into the same instruction with the
16034 * same state (at least in one of possible code paths).
16036 * This approach allows to keep infinite loop heuristic even in the face of
16037 * active iterator. E.g., C snippet below is and will be detected as
16038 * inifintely looping:
16040 * struct bpf_iter_num it;
16043 * bpf_iter_num_new(&it, 0, 10);
16044 * while ((p = bpf_iter_num_next(&t))) {
16046 * while (x--) {} // <<-- infinite loop here
16050 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16052 struct bpf_reg_state *slot, *cur_slot;
16053 struct bpf_func_state *state;
16056 for (fr = old->curframe; fr >= 0; fr--) {
16057 state = old->frame[fr];
16058 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16059 if (state->stack[i].slot_type[0] != STACK_ITER)
16062 slot = &state->stack[i].spilled_ptr;
16063 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16066 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16067 if (cur_slot->iter.depth != slot->iter.depth)
16074 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16076 struct bpf_verifier_state_list *new_sl;
16077 struct bpf_verifier_state_list *sl, **pprev;
16078 struct bpf_verifier_state *cur = env->cur_state, *new;
16079 int i, j, err, states_cnt = 0;
16080 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16081 bool add_new_state = force_new_state;
16083 /* bpf progs typically have pruning point every 4 instructions
16084 * http://vger.kernel.org/bpfconf2019.html#session-1
16085 * Do not add new state for future pruning if the verifier hasn't seen
16086 * at least 2 jumps and at least 8 instructions.
16087 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16088 * In tests that amounts to up to 50% reduction into total verifier
16089 * memory consumption and 20% verifier time speedup.
16091 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16092 env->insn_processed - env->prev_insn_processed >= 8)
16093 add_new_state = true;
16095 pprev = explored_state(env, insn_idx);
16098 clean_live_states(env, insn_idx, cur);
16102 if (sl->state.insn_idx != insn_idx)
16105 if (sl->state.branches) {
16106 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16108 if (frame->in_async_callback_fn &&
16109 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16110 /* Different async_entry_cnt means that the verifier is
16111 * processing another entry into async callback.
16112 * Seeing the same state is not an indication of infinite
16113 * loop or infinite recursion.
16114 * But finding the same state doesn't mean that it's safe
16115 * to stop processing the current state. The previous state
16116 * hasn't yet reached bpf_exit, since state.branches > 0.
16117 * Checking in_async_callback_fn alone is not enough either.
16118 * Since the verifier still needs to catch infinite loops
16119 * inside async callbacks.
16121 goto skip_inf_loop_check;
16123 /* BPF open-coded iterators loop detection is special.
16124 * states_maybe_looping() logic is too simplistic in detecting
16125 * states that *might* be equivalent, because it doesn't know
16126 * about ID remapping, so don't even perform it.
16127 * See process_iter_next_call() and iter_active_depths_differ()
16128 * for overview of the logic. When current and one of parent
16129 * states are detected as equivalent, it's a good thing: we prove
16130 * convergence and can stop simulating further iterations.
16131 * It's safe to assume that iterator loop will finish, taking into
16132 * account iter_next() contract of eventually returning
16133 * sticky NULL result.
16135 if (is_iter_next_insn(env, insn_idx)) {
16136 if (states_equal(env, &sl->state, cur)) {
16137 struct bpf_func_state *cur_frame;
16138 struct bpf_reg_state *iter_state, *iter_reg;
16141 cur_frame = cur->frame[cur->curframe];
16142 /* btf_check_iter_kfuncs() enforces that
16143 * iter state pointer is always the first arg
16145 iter_reg = &cur_frame->regs[BPF_REG_1];
16146 /* current state is valid due to states_equal(),
16147 * so we can assume valid iter and reg state,
16148 * no need for extra (re-)validations
16150 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16151 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16152 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
16155 goto skip_inf_loop_check;
16157 /* attempt to detect infinite loop to avoid unnecessary doomed work */
16158 if (states_maybe_looping(&sl->state, cur) &&
16159 states_equal(env, &sl->state, cur) &&
16160 !iter_active_depths_differ(&sl->state, cur)) {
16161 verbose_linfo(env, insn_idx, "; ");
16162 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16165 /* if the verifier is processing a loop, avoid adding new state
16166 * too often, since different loop iterations have distinct
16167 * states and may not help future pruning.
16168 * This threshold shouldn't be too low to make sure that
16169 * a loop with large bound will be rejected quickly.
16170 * The most abusive loop will be:
16172 * if r1 < 1000000 goto pc-2
16173 * 1M insn_procssed limit / 100 == 10k peak states.
16174 * This threshold shouldn't be too high either, since states
16175 * at the end of the loop are likely to be useful in pruning.
16177 skip_inf_loop_check:
16178 if (!force_new_state &&
16179 env->jmps_processed - env->prev_jmps_processed < 20 &&
16180 env->insn_processed - env->prev_insn_processed < 100)
16181 add_new_state = false;
16184 if (states_equal(env, &sl->state, cur)) {
16187 /* reached equivalent register/stack state,
16188 * prune the search.
16189 * Registers read by the continuation are read by us.
16190 * If we have any write marks in env->cur_state, they
16191 * will prevent corresponding reads in the continuation
16192 * from reaching our parent (an explored_state). Our
16193 * own state will get the read marks recorded, but
16194 * they'll be immediately forgotten as we're pruning
16195 * this state and will pop a new one.
16197 err = propagate_liveness(env, &sl->state, cur);
16199 /* if previous state reached the exit with precision and
16200 * current state is equivalent to it (except precsion marks)
16201 * the precision needs to be propagated back in
16202 * the current state.
16204 err = err ? : push_jmp_history(env, cur);
16205 err = err ? : propagate_precision(env, &sl->state);
16211 /* when new state is not going to be added do not increase miss count.
16212 * Otherwise several loop iterations will remove the state
16213 * recorded earlier. The goal of these heuristics is to have
16214 * states from some iterations of the loop (some in the beginning
16215 * and some at the end) to help pruning.
16219 /* heuristic to determine whether this state is beneficial
16220 * to keep checking from state equivalence point of view.
16221 * Higher numbers increase max_states_per_insn and verification time,
16222 * but do not meaningfully decrease insn_processed.
16224 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
16225 /* the state is unlikely to be useful. Remove it to
16226 * speed up verification
16229 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
16230 u32 br = sl->state.branches;
16233 "BUG live_done but branches_to_explore %d\n",
16235 free_verifier_state(&sl->state, false);
16237 env->peak_states--;
16239 /* cannot free this state, since parentage chain may
16240 * walk it later. Add it for free_list instead to
16241 * be freed at the end of verification
16243 sl->next = env->free_list;
16244 env->free_list = sl;
16254 if (env->max_states_per_insn < states_cnt)
16255 env->max_states_per_insn = states_cnt;
16257 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16260 if (!add_new_state)
16263 /* There were no equivalent states, remember the current one.
16264 * Technically the current state is not proven to be safe yet,
16265 * but it will either reach outer most bpf_exit (which means it's safe)
16266 * or it will be rejected. When there are no loops the verifier won't be
16267 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16268 * again on the way to bpf_exit.
16269 * When looping the sl->state.branches will be > 0 and this state
16270 * will not be considered for equivalence until branches == 0.
16272 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16275 env->total_states++;
16276 env->peak_states++;
16277 env->prev_jmps_processed = env->jmps_processed;
16278 env->prev_insn_processed = env->insn_processed;
16280 /* forget precise markings we inherited, see __mark_chain_precision */
16281 if (env->bpf_capable)
16282 mark_all_scalars_imprecise(env, cur);
16284 /* add new state to the head of linked list */
16285 new = &new_sl->state;
16286 err = copy_verifier_state(new, cur);
16288 free_verifier_state(new, false);
16292 new->insn_idx = insn_idx;
16293 WARN_ONCE(new->branches != 1,
16294 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16297 cur->first_insn_idx = insn_idx;
16298 clear_jmp_history(cur);
16299 new_sl->next = *explored_state(env, insn_idx);
16300 *explored_state(env, insn_idx) = new_sl;
16301 /* connect new state to parentage chain. Current frame needs all
16302 * registers connected. Only r6 - r9 of the callers are alive (pushed
16303 * to the stack implicitly by JITs) so in callers' frames connect just
16304 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16305 * the state of the call instruction (with WRITTEN set), and r0 comes
16306 * from callee with its full parentage chain, anyway.
16308 /* clear write marks in current state: the writes we did are not writes
16309 * our child did, so they don't screen off its reads from us.
16310 * (There are no read marks in current state, because reads always mark
16311 * their parent and current state never has children yet. Only
16312 * explored_states can get read marks.)
16314 for (j = 0; j <= cur->curframe; j++) {
16315 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16316 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16317 for (i = 0; i < BPF_REG_FP; i++)
16318 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16321 /* all stack frames are accessible from callee, clear them all */
16322 for (j = 0; j <= cur->curframe; j++) {
16323 struct bpf_func_state *frame = cur->frame[j];
16324 struct bpf_func_state *newframe = new->frame[j];
16326 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16327 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16328 frame->stack[i].spilled_ptr.parent =
16329 &newframe->stack[i].spilled_ptr;
16335 /* Return true if it's OK to have the same insn return a different type. */
16336 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16338 switch (base_type(type)) {
16340 case PTR_TO_SOCKET:
16341 case PTR_TO_SOCK_COMMON:
16342 case PTR_TO_TCP_SOCK:
16343 case PTR_TO_XDP_SOCK:
16344 case PTR_TO_BTF_ID:
16351 /* If an instruction was previously used with particular pointer types, then we
16352 * need to be careful to avoid cases such as the below, where it may be ok
16353 * for one branch accessing the pointer, but not ok for the other branch:
16358 * R1 = some_other_valid_ptr;
16361 * R2 = *(u32 *)(R1 + 0);
16363 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16365 return src != prev && (!reg_type_mismatch_ok(src) ||
16366 !reg_type_mismatch_ok(prev));
16369 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16370 bool allow_trust_missmatch)
16372 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16374 if (*prev_type == NOT_INIT) {
16375 /* Saw a valid insn
16376 * dst_reg = *(u32 *)(src_reg + off)
16377 * save type to validate intersecting paths
16380 } else if (reg_type_mismatch(type, *prev_type)) {
16381 /* Abuser program is trying to use the same insn
16382 * dst_reg = *(u32*) (src_reg + off)
16383 * with different pointer types:
16384 * src_reg == ctx in one branch and
16385 * src_reg == stack|map in some other branch.
16388 if (allow_trust_missmatch &&
16389 base_type(type) == PTR_TO_BTF_ID &&
16390 base_type(*prev_type) == PTR_TO_BTF_ID) {
16392 * Have to support a use case when one path through
16393 * the program yields TRUSTED pointer while another
16394 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16395 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16397 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16399 verbose(env, "same insn cannot be used with different pointers\n");
16407 static int do_check(struct bpf_verifier_env *env)
16409 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16410 struct bpf_verifier_state *state = env->cur_state;
16411 struct bpf_insn *insns = env->prog->insnsi;
16412 struct bpf_reg_state *regs;
16413 int insn_cnt = env->prog->len;
16414 bool do_print_state = false;
16415 int prev_insn_idx = -1;
16418 struct bpf_insn *insn;
16422 env->prev_insn_idx = prev_insn_idx;
16423 if (env->insn_idx >= insn_cnt) {
16424 verbose(env, "invalid insn idx %d insn_cnt %d\n",
16425 env->insn_idx, insn_cnt);
16429 insn = &insns[env->insn_idx];
16430 class = BPF_CLASS(insn->code);
16432 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16434 "BPF program is too large. Processed %d insn\n",
16435 env->insn_processed);
16439 state->last_insn_idx = env->prev_insn_idx;
16441 if (is_prune_point(env, env->insn_idx)) {
16442 err = is_state_visited(env, env->insn_idx);
16446 /* found equivalent state, can prune the search */
16447 if (env->log.level & BPF_LOG_LEVEL) {
16448 if (do_print_state)
16449 verbose(env, "\nfrom %d to %d%s: safe\n",
16450 env->prev_insn_idx, env->insn_idx,
16451 env->cur_state->speculative ?
16452 " (speculative execution)" : "");
16454 verbose(env, "%d: safe\n", env->insn_idx);
16456 goto process_bpf_exit;
16460 if (is_jmp_point(env, env->insn_idx)) {
16461 err = push_jmp_history(env, state);
16466 if (signal_pending(current))
16469 if (need_resched())
16472 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16473 verbose(env, "\nfrom %d to %d%s:",
16474 env->prev_insn_idx, env->insn_idx,
16475 env->cur_state->speculative ?
16476 " (speculative execution)" : "");
16477 print_verifier_state(env, state->frame[state->curframe], true);
16478 do_print_state = false;
16481 if (env->log.level & BPF_LOG_LEVEL) {
16482 const struct bpf_insn_cbs cbs = {
16483 .cb_call = disasm_kfunc_name,
16484 .cb_print = verbose,
16485 .private_data = env,
16488 if (verifier_state_scratched(env))
16489 print_insn_state(env, state->frame[state->curframe]);
16491 verbose_linfo(env, env->insn_idx, "; ");
16492 env->prev_log_pos = env->log.end_pos;
16493 verbose(env, "%d: ", env->insn_idx);
16494 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16495 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16496 env->prev_log_pos = env->log.end_pos;
16499 if (bpf_prog_is_offloaded(env->prog->aux)) {
16500 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16501 env->prev_insn_idx);
16506 regs = cur_regs(env);
16507 sanitize_mark_insn_seen(env);
16508 prev_insn_idx = env->insn_idx;
16510 if (class == BPF_ALU || class == BPF_ALU64) {
16511 err = check_alu_op(env, insn);
16515 } else if (class == BPF_LDX) {
16516 enum bpf_reg_type src_reg_type;
16518 /* check for reserved fields is already done */
16520 /* check src operand */
16521 err = check_reg_arg(env, insn->src_reg, SRC_OP);
16525 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16529 src_reg_type = regs[insn->src_reg].type;
16531 /* check that memory (src_reg + off) is readable,
16532 * the state of dst_reg will be updated by this func
16534 err = check_mem_access(env, env->insn_idx, insn->src_reg,
16535 insn->off, BPF_SIZE(insn->code),
16536 BPF_READ, insn->dst_reg, false,
16537 BPF_MODE(insn->code) == BPF_MEMSX);
16541 err = save_aux_ptr_type(env, src_reg_type, true);
16544 } else if (class == BPF_STX) {
16545 enum bpf_reg_type dst_reg_type;
16547 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16548 err = check_atomic(env, env->insn_idx, insn);
16555 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16556 verbose(env, "BPF_STX uses reserved fields\n");
16560 /* check src1 operand */
16561 err = check_reg_arg(env, insn->src_reg, SRC_OP);
16564 /* check src2 operand */
16565 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16569 dst_reg_type = regs[insn->dst_reg].type;
16571 /* check that memory (dst_reg + off) is writeable */
16572 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16573 insn->off, BPF_SIZE(insn->code),
16574 BPF_WRITE, insn->src_reg, false, false);
16578 err = save_aux_ptr_type(env, dst_reg_type, false);
16581 } else if (class == BPF_ST) {
16582 enum bpf_reg_type dst_reg_type;
16584 if (BPF_MODE(insn->code) != BPF_MEM ||
16585 insn->src_reg != BPF_REG_0) {
16586 verbose(env, "BPF_ST uses reserved fields\n");
16589 /* check src operand */
16590 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16594 dst_reg_type = regs[insn->dst_reg].type;
16596 /* check that memory (dst_reg + off) is writeable */
16597 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16598 insn->off, BPF_SIZE(insn->code),
16599 BPF_WRITE, -1, false, false);
16603 err = save_aux_ptr_type(env, dst_reg_type, false);
16606 } else if (class == BPF_JMP || class == BPF_JMP32) {
16607 u8 opcode = BPF_OP(insn->code);
16609 env->jmps_processed++;
16610 if (opcode == BPF_CALL) {
16611 if (BPF_SRC(insn->code) != BPF_K ||
16612 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16613 && insn->off != 0) ||
16614 (insn->src_reg != BPF_REG_0 &&
16615 insn->src_reg != BPF_PSEUDO_CALL &&
16616 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16617 insn->dst_reg != BPF_REG_0 ||
16618 class == BPF_JMP32) {
16619 verbose(env, "BPF_CALL uses reserved fields\n");
16623 if (env->cur_state->active_lock.ptr) {
16624 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16625 (insn->src_reg == BPF_PSEUDO_CALL) ||
16626 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16627 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16628 verbose(env, "function calls are not allowed while holding a lock\n");
16632 if (insn->src_reg == BPF_PSEUDO_CALL)
16633 err = check_func_call(env, insn, &env->insn_idx);
16634 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16635 err = check_kfunc_call(env, insn, &env->insn_idx);
16637 err = check_helper_call(env, insn, &env->insn_idx);
16641 mark_reg_scratched(env, BPF_REG_0);
16642 } else if (opcode == BPF_JA) {
16643 if (BPF_SRC(insn->code) != BPF_K ||
16645 insn->src_reg != BPF_REG_0 ||
16646 insn->dst_reg != BPF_REG_0 ||
16647 class == BPF_JMP32) {
16648 verbose(env, "BPF_JA uses reserved fields\n");
16652 env->insn_idx += insn->off + 1;
16655 } else if (opcode == BPF_EXIT) {
16656 if (BPF_SRC(insn->code) != BPF_K ||
16658 insn->src_reg != BPF_REG_0 ||
16659 insn->dst_reg != BPF_REG_0 ||
16660 class == BPF_JMP32) {
16661 verbose(env, "BPF_EXIT uses reserved fields\n");
16665 if (env->cur_state->active_lock.ptr &&
16666 !in_rbtree_lock_required_cb(env)) {
16667 verbose(env, "bpf_spin_unlock is missing\n");
16671 if (env->cur_state->active_rcu_lock) {
16672 verbose(env, "bpf_rcu_read_unlock is missing\n");
16676 /* We must do check_reference_leak here before
16677 * prepare_func_exit to handle the case when
16678 * state->curframe > 0, it may be a callback
16679 * function, for which reference_state must
16680 * match caller reference state when it exits.
16682 err = check_reference_leak(env);
16686 if (state->curframe) {
16687 /* exit from nested function */
16688 err = prepare_func_exit(env, &env->insn_idx);
16691 do_print_state = true;
16695 err = check_return_code(env);
16699 mark_verifier_state_scratched(env);
16700 update_branch_counts(env, env->cur_state);
16701 err = pop_stack(env, &prev_insn_idx,
16702 &env->insn_idx, pop_log);
16704 if (err != -ENOENT)
16708 do_print_state = true;
16712 err = check_cond_jmp_op(env, insn, &env->insn_idx);
16716 } else if (class == BPF_LD) {
16717 u8 mode = BPF_MODE(insn->code);
16719 if (mode == BPF_ABS || mode == BPF_IND) {
16720 err = check_ld_abs(env, insn);
16724 } else if (mode == BPF_IMM) {
16725 err = check_ld_imm(env, insn);
16730 sanitize_mark_insn_seen(env);
16732 verbose(env, "invalid BPF_LD mode\n");
16736 verbose(env, "unknown insn class %d\n", class);
16746 static int find_btf_percpu_datasec(struct btf *btf)
16748 const struct btf_type *t;
16753 * Both vmlinux and module each have their own ".data..percpu"
16754 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16755 * types to look at only module's own BTF types.
16757 n = btf_nr_types(btf);
16758 if (btf_is_module(btf))
16759 i = btf_nr_types(btf_vmlinux);
16763 for(; i < n; i++) {
16764 t = btf_type_by_id(btf, i);
16765 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16768 tname = btf_name_by_offset(btf, t->name_off);
16769 if (!strcmp(tname, ".data..percpu"))
16776 /* replace pseudo btf_id with kernel symbol address */
16777 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16778 struct bpf_insn *insn,
16779 struct bpf_insn_aux_data *aux)
16781 const struct btf_var_secinfo *vsi;
16782 const struct btf_type *datasec;
16783 struct btf_mod_pair *btf_mod;
16784 const struct btf_type *t;
16785 const char *sym_name;
16786 bool percpu = false;
16787 u32 type, id = insn->imm;
16791 int i, btf_fd, err;
16793 btf_fd = insn[1].imm;
16795 btf = btf_get_by_fd(btf_fd);
16797 verbose(env, "invalid module BTF object FD specified.\n");
16801 if (!btf_vmlinux) {
16802 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16809 t = btf_type_by_id(btf, id);
16811 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16816 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16817 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16822 sym_name = btf_name_by_offset(btf, t->name_off);
16823 addr = kallsyms_lookup_name(sym_name);
16825 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16830 insn[0].imm = (u32)addr;
16831 insn[1].imm = addr >> 32;
16833 if (btf_type_is_func(t)) {
16834 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16835 aux->btf_var.mem_size = 0;
16839 datasec_id = find_btf_percpu_datasec(btf);
16840 if (datasec_id > 0) {
16841 datasec = btf_type_by_id(btf, datasec_id);
16842 for_each_vsi(i, datasec, vsi) {
16843 if (vsi->type == id) {
16851 t = btf_type_skip_modifiers(btf, type, NULL);
16853 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16854 aux->btf_var.btf = btf;
16855 aux->btf_var.btf_id = type;
16856 } else if (!btf_type_is_struct(t)) {
16857 const struct btf_type *ret;
16861 /* resolve the type size of ksym. */
16862 ret = btf_resolve_size(btf, t, &tsize);
16864 tname = btf_name_by_offset(btf, t->name_off);
16865 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16866 tname, PTR_ERR(ret));
16870 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16871 aux->btf_var.mem_size = tsize;
16873 aux->btf_var.reg_type = PTR_TO_BTF_ID;
16874 aux->btf_var.btf = btf;
16875 aux->btf_var.btf_id = type;
16878 /* check whether we recorded this BTF (and maybe module) already */
16879 for (i = 0; i < env->used_btf_cnt; i++) {
16880 if (env->used_btfs[i].btf == btf) {
16886 if (env->used_btf_cnt >= MAX_USED_BTFS) {
16891 btf_mod = &env->used_btfs[env->used_btf_cnt];
16892 btf_mod->btf = btf;
16893 btf_mod->module = NULL;
16895 /* if we reference variables from kernel module, bump its refcount */
16896 if (btf_is_module(btf)) {
16897 btf_mod->module = btf_try_get_module(btf);
16898 if (!btf_mod->module) {
16904 env->used_btf_cnt++;
16912 static bool is_tracing_prog_type(enum bpf_prog_type type)
16915 case BPF_PROG_TYPE_KPROBE:
16916 case BPF_PROG_TYPE_TRACEPOINT:
16917 case BPF_PROG_TYPE_PERF_EVENT:
16918 case BPF_PROG_TYPE_RAW_TRACEPOINT:
16919 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16926 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16927 struct bpf_map *map,
16928 struct bpf_prog *prog)
16931 enum bpf_prog_type prog_type = resolve_prog_type(prog);
16933 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16934 btf_record_has_field(map->record, BPF_RB_ROOT)) {
16935 if (is_tracing_prog_type(prog_type)) {
16936 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16941 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16942 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16943 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16947 if (is_tracing_prog_type(prog_type)) {
16948 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16952 if (prog->aux->sleepable) {
16953 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16958 if (btf_record_has_field(map->record, BPF_TIMER)) {
16959 if (is_tracing_prog_type(prog_type)) {
16960 verbose(env, "tracing progs cannot use bpf_timer yet\n");
16965 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16966 !bpf_offload_prog_map_match(prog, map)) {
16967 verbose(env, "offload device mismatch between prog and map\n");
16971 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16972 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16976 if (prog->aux->sleepable)
16977 switch (map->map_type) {
16978 case BPF_MAP_TYPE_HASH:
16979 case BPF_MAP_TYPE_LRU_HASH:
16980 case BPF_MAP_TYPE_ARRAY:
16981 case BPF_MAP_TYPE_PERCPU_HASH:
16982 case BPF_MAP_TYPE_PERCPU_ARRAY:
16983 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16984 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16985 case BPF_MAP_TYPE_HASH_OF_MAPS:
16986 case BPF_MAP_TYPE_RINGBUF:
16987 case BPF_MAP_TYPE_USER_RINGBUF:
16988 case BPF_MAP_TYPE_INODE_STORAGE:
16989 case BPF_MAP_TYPE_SK_STORAGE:
16990 case BPF_MAP_TYPE_TASK_STORAGE:
16991 case BPF_MAP_TYPE_CGRP_STORAGE:
16995 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17002 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17004 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17005 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17008 /* find and rewrite pseudo imm in ld_imm64 instructions:
17010 * 1. if it accesses map FD, replace it with actual map pointer.
17011 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17013 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17015 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17017 struct bpf_insn *insn = env->prog->insnsi;
17018 int insn_cnt = env->prog->len;
17021 err = bpf_prog_calc_tag(env->prog);
17025 for (i = 0; i < insn_cnt; i++, insn++) {
17026 if (BPF_CLASS(insn->code) == BPF_LDX &&
17027 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17029 verbose(env, "BPF_LDX uses reserved fields\n");
17033 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17034 struct bpf_insn_aux_data *aux;
17035 struct bpf_map *map;
17040 if (i == insn_cnt - 1 || insn[1].code != 0 ||
17041 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17042 insn[1].off != 0) {
17043 verbose(env, "invalid bpf_ld_imm64 insn\n");
17047 if (insn[0].src_reg == 0)
17048 /* valid generic load 64-bit imm */
17051 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17052 aux = &env->insn_aux_data[i];
17053 err = check_pseudo_btf_id(env, insn, aux);
17059 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17060 aux = &env->insn_aux_data[i];
17061 aux->ptr_type = PTR_TO_FUNC;
17065 /* In final convert_pseudo_ld_imm64() step, this is
17066 * converted into regular 64-bit imm load insn.
17068 switch (insn[0].src_reg) {
17069 case BPF_PSEUDO_MAP_VALUE:
17070 case BPF_PSEUDO_MAP_IDX_VALUE:
17072 case BPF_PSEUDO_MAP_FD:
17073 case BPF_PSEUDO_MAP_IDX:
17074 if (insn[1].imm == 0)
17078 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17082 switch (insn[0].src_reg) {
17083 case BPF_PSEUDO_MAP_IDX_VALUE:
17084 case BPF_PSEUDO_MAP_IDX:
17085 if (bpfptr_is_null(env->fd_array)) {
17086 verbose(env, "fd_idx without fd_array is invalid\n");
17089 if (copy_from_bpfptr_offset(&fd, env->fd_array,
17090 insn[0].imm * sizeof(fd),
17100 map = __bpf_map_get(f);
17102 verbose(env, "fd %d is not pointing to valid bpf_map\n",
17104 return PTR_ERR(map);
17107 err = check_map_prog_compatibility(env, map, env->prog);
17113 aux = &env->insn_aux_data[i];
17114 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17115 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17116 addr = (unsigned long)map;
17118 u32 off = insn[1].imm;
17120 if (off >= BPF_MAX_VAR_OFF) {
17121 verbose(env, "direct value offset of %u is not allowed\n", off);
17126 if (!map->ops->map_direct_value_addr) {
17127 verbose(env, "no direct value access support for this map type\n");
17132 err = map->ops->map_direct_value_addr(map, &addr, off);
17134 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17135 map->value_size, off);
17140 aux->map_off = off;
17144 insn[0].imm = (u32)addr;
17145 insn[1].imm = addr >> 32;
17147 /* check whether we recorded this map already */
17148 for (j = 0; j < env->used_map_cnt; j++) {
17149 if (env->used_maps[j] == map) {
17150 aux->map_index = j;
17156 if (env->used_map_cnt >= MAX_USED_MAPS) {
17161 /* hold the map. If the program is rejected by verifier,
17162 * the map will be released by release_maps() or it
17163 * will be used by the valid program until it's unloaded
17164 * and all maps are released in free_used_maps()
17168 aux->map_index = env->used_map_cnt;
17169 env->used_maps[env->used_map_cnt++] = map;
17171 if (bpf_map_is_cgroup_storage(map) &&
17172 bpf_cgroup_storage_assign(env->prog->aux, map)) {
17173 verbose(env, "only one cgroup storage of each type is allowed\n");
17185 /* Basic sanity check before we invest more work here. */
17186 if (!bpf_opcode_in_insntable(insn->code)) {
17187 verbose(env, "unknown opcode %02x\n", insn->code);
17192 /* now all pseudo BPF_LD_IMM64 instructions load valid
17193 * 'struct bpf_map *' into a register instead of user map_fd.
17194 * These pointers will be used later by verifier to validate map access.
17199 /* drop refcnt of maps used by the rejected program */
17200 static void release_maps(struct bpf_verifier_env *env)
17202 __bpf_free_used_maps(env->prog->aux, env->used_maps,
17203 env->used_map_cnt);
17206 /* drop refcnt of maps used by the rejected program */
17207 static void release_btfs(struct bpf_verifier_env *env)
17209 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17210 env->used_btf_cnt);
17213 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17214 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17216 struct bpf_insn *insn = env->prog->insnsi;
17217 int insn_cnt = env->prog->len;
17220 for (i = 0; i < insn_cnt; i++, insn++) {
17221 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17223 if (insn->src_reg == BPF_PSEUDO_FUNC)
17229 /* single env->prog->insni[off] instruction was replaced with the range
17230 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
17231 * [0, off) and [off, end) to new locations, so the patched range stays zero
17233 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17234 struct bpf_insn_aux_data *new_data,
17235 struct bpf_prog *new_prog, u32 off, u32 cnt)
17237 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17238 struct bpf_insn *insn = new_prog->insnsi;
17239 u32 old_seen = old_data[off].seen;
17243 /* aux info at OFF always needs adjustment, no matter fast path
17244 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17245 * original insn at old prog.
17247 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17251 prog_len = new_prog->len;
17253 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17254 memcpy(new_data + off + cnt - 1, old_data + off,
17255 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17256 for (i = off; i < off + cnt - 1; i++) {
17257 /* Expand insni[off]'s seen count to the patched range. */
17258 new_data[i].seen = old_seen;
17259 new_data[i].zext_dst = insn_has_def32(env, insn + i);
17261 env->insn_aux_data = new_data;
17265 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17271 /* NOTE: fake 'exit' subprog should be updated as well. */
17272 for (i = 0; i <= env->subprog_cnt; i++) {
17273 if (env->subprog_info[i].start <= off)
17275 env->subprog_info[i].start += len - 1;
17279 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17281 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17282 int i, sz = prog->aux->size_poke_tab;
17283 struct bpf_jit_poke_descriptor *desc;
17285 for (i = 0; i < sz; i++) {
17287 if (desc->insn_idx <= off)
17289 desc->insn_idx += len - 1;
17293 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17294 const struct bpf_insn *patch, u32 len)
17296 struct bpf_prog *new_prog;
17297 struct bpf_insn_aux_data *new_data = NULL;
17300 new_data = vzalloc(array_size(env->prog->len + len - 1,
17301 sizeof(struct bpf_insn_aux_data)));
17306 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17307 if (IS_ERR(new_prog)) {
17308 if (PTR_ERR(new_prog) == -ERANGE)
17310 "insn %d cannot be patched due to 16-bit range\n",
17311 env->insn_aux_data[off].orig_idx);
17315 adjust_insn_aux_data(env, new_data, new_prog, off, len);
17316 adjust_subprog_starts(env, off, len);
17317 adjust_poke_descs(new_prog, off, len);
17321 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17326 /* find first prog starting at or after off (first to remove) */
17327 for (i = 0; i < env->subprog_cnt; i++)
17328 if (env->subprog_info[i].start >= off)
17330 /* find first prog starting at or after off + cnt (first to stay) */
17331 for (j = i; j < env->subprog_cnt; j++)
17332 if (env->subprog_info[j].start >= off + cnt)
17334 /* if j doesn't start exactly at off + cnt, we are just removing
17335 * the front of previous prog
17337 if (env->subprog_info[j].start != off + cnt)
17341 struct bpf_prog_aux *aux = env->prog->aux;
17344 /* move fake 'exit' subprog as well */
17345 move = env->subprog_cnt + 1 - j;
17347 memmove(env->subprog_info + i,
17348 env->subprog_info + j,
17349 sizeof(*env->subprog_info) * move);
17350 env->subprog_cnt -= j - i;
17352 /* remove func_info */
17353 if (aux->func_info) {
17354 move = aux->func_info_cnt - j;
17356 memmove(aux->func_info + i,
17357 aux->func_info + j,
17358 sizeof(*aux->func_info) * move);
17359 aux->func_info_cnt -= j - i;
17360 /* func_info->insn_off is set after all code rewrites,
17361 * in adjust_btf_func() - no need to adjust
17365 /* convert i from "first prog to remove" to "first to adjust" */
17366 if (env->subprog_info[i].start == off)
17370 /* update fake 'exit' subprog as well */
17371 for (; i <= env->subprog_cnt; i++)
17372 env->subprog_info[i].start -= cnt;
17377 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17380 struct bpf_prog *prog = env->prog;
17381 u32 i, l_off, l_cnt, nr_linfo;
17382 struct bpf_line_info *linfo;
17384 nr_linfo = prog->aux->nr_linfo;
17388 linfo = prog->aux->linfo;
17390 /* find first line info to remove, count lines to be removed */
17391 for (i = 0; i < nr_linfo; i++)
17392 if (linfo[i].insn_off >= off)
17397 for (; i < nr_linfo; i++)
17398 if (linfo[i].insn_off < off + cnt)
17403 /* First live insn doesn't match first live linfo, it needs to "inherit"
17404 * last removed linfo. prog is already modified, so prog->len == off
17405 * means no live instructions after (tail of the program was removed).
17407 if (prog->len != off && l_cnt &&
17408 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17410 linfo[--i].insn_off = off + cnt;
17413 /* remove the line info which refer to the removed instructions */
17415 memmove(linfo + l_off, linfo + i,
17416 sizeof(*linfo) * (nr_linfo - i));
17418 prog->aux->nr_linfo -= l_cnt;
17419 nr_linfo = prog->aux->nr_linfo;
17422 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
17423 for (i = l_off; i < nr_linfo; i++)
17424 linfo[i].insn_off -= cnt;
17426 /* fix up all subprogs (incl. 'exit') which start >= off */
17427 for (i = 0; i <= env->subprog_cnt; i++)
17428 if (env->subprog_info[i].linfo_idx > l_off) {
17429 /* program may have started in the removed region but
17430 * may not be fully removed
17432 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17433 env->subprog_info[i].linfo_idx -= l_cnt;
17435 env->subprog_info[i].linfo_idx = l_off;
17441 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17443 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17444 unsigned int orig_prog_len = env->prog->len;
17447 if (bpf_prog_is_offloaded(env->prog->aux))
17448 bpf_prog_offload_remove_insns(env, off, cnt);
17450 err = bpf_remove_insns(env->prog, off, cnt);
17454 err = adjust_subprog_starts_after_remove(env, off, cnt);
17458 err = bpf_adj_linfo_after_remove(env, off, cnt);
17462 memmove(aux_data + off, aux_data + off + cnt,
17463 sizeof(*aux_data) * (orig_prog_len - off - cnt));
17468 /* The verifier does more data flow analysis than llvm and will not
17469 * explore branches that are dead at run time. Malicious programs can
17470 * have dead code too. Therefore replace all dead at-run-time code
17473 * Just nops are not optimal, e.g. if they would sit at the end of the
17474 * program and through another bug we would manage to jump there, then
17475 * we'd execute beyond program memory otherwise. Returning exception
17476 * code also wouldn't work since we can have subprogs where the dead
17477 * code could be located.
17479 static void sanitize_dead_code(struct bpf_verifier_env *env)
17481 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17482 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17483 struct bpf_insn *insn = env->prog->insnsi;
17484 const int insn_cnt = env->prog->len;
17487 for (i = 0; i < insn_cnt; i++) {
17488 if (aux_data[i].seen)
17490 memcpy(insn + i, &trap, sizeof(trap));
17491 aux_data[i].zext_dst = false;
17495 static bool insn_is_cond_jump(u8 code)
17499 if (BPF_CLASS(code) == BPF_JMP32)
17502 if (BPF_CLASS(code) != BPF_JMP)
17506 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17509 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17511 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17512 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17513 struct bpf_insn *insn = env->prog->insnsi;
17514 const int insn_cnt = env->prog->len;
17517 for (i = 0; i < insn_cnt; i++, insn++) {
17518 if (!insn_is_cond_jump(insn->code))
17521 if (!aux_data[i + 1].seen)
17522 ja.off = insn->off;
17523 else if (!aux_data[i + 1 + insn->off].seen)
17528 if (bpf_prog_is_offloaded(env->prog->aux))
17529 bpf_prog_offload_replace_insn(env, i, &ja);
17531 memcpy(insn, &ja, sizeof(ja));
17535 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17537 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17538 int insn_cnt = env->prog->len;
17541 for (i = 0; i < insn_cnt; i++) {
17545 while (i + j < insn_cnt && !aux_data[i + j].seen)
17550 err = verifier_remove_insns(env, i, j);
17553 insn_cnt = env->prog->len;
17559 static int opt_remove_nops(struct bpf_verifier_env *env)
17561 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17562 struct bpf_insn *insn = env->prog->insnsi;
17563 int insn_cnt = env->prog->len;
17566 for (i = 0; i < insn_cnt; i++) {
17567 if (memcmp(&insn[i], &ja, sizeof(ja)))
17570 err = verifier_remove_insns(env, i, 1);
17580 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17581 const union bpf_attr *attr)
17583 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17584 struct bpf_insn_aux_data *aux = env->insn_aux_data;
17585 int i, patch_len, delta = 0, len = env->prog->len;
17586 struct bpf_insn *insns = env->prog->insnsi;
17587 struct bpf_prog *new_prog;
17590 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17591 zext_patch[1] = BPF_ZEXT_REG(0);
17592 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17593 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17594 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17595 for (i = 0; i < len; i++) {
17596 int adj_idx = i + delta;
17597 struct bpf_insn insn;
17600 insn = insns[adj_idx];
17601 load_reg = insn_def_regno(&insn);
17602 if (!aux[adj_idx].zext_dst) {
17610 class = BPF_CLASS(code);
17611 if (load_reg == -1)
17614 /* NOTE: arg "reg" (the fourth one) is only used for
17615 * BPF_STX + SRC_OP, so it is safe to pass NULL
17618 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17619 if (class == BPF_LD &&
17620 BPF_MODE(code) == BPF_IMM)
17625 /* ctx load could be transformed into wider load. */
17626 if (class == BPF_LDX &&
17627 aux[adj_idx].ptr_type == PTR_TO_CTX)
17630 imm_rnd = get_random_u32();
17631 rnd_hi32_patch[0] = insn;
17632 rnd_hi32_patch[1].imm = imm_rnd;
17633 rnd_hi32_patch[3].dst_reg = load_reg;
17634 patch = rnd_hi32_patch;
17636 goto apply_patch_buffer;
17639 /* Add in an zero-extend instruction if a) the JIT has requested
17640 * it or b) it's a CMPXCHG.
17642 * The latter is because: BPF_CMPXCHG always loads a value into
17643 * R0, therefore always zero-extends. However some archs'
17644 * equivalent instruction only does this load when the
17645 * comparison is successful. This detail of CMPXCHG is
17646 * orthogonal to the general zero-extension behaviour of the
17647 * CPU, so it's treated independently of bpf_jit_needs_zext.
17649 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17652 /* Zero-extension is done by the caller. */
17653 if (bpf_pseudo_kfunc_call(&insn))
17656 if (WARN_ON(load_reg == -1)) {
17657 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17661 zext_patch[0] = insn;
17662 zext_patch[1].dst_reg = load_reg;
17663 zext_patch[1].src_reg = load_reg;
17664 patch = zext_patch;
17666 apply_patch_buffer:
17667 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17670 env->prog = new_prog;
17671 insns = new_prog->insnsi;
17672 aux = env->insn_aux_data;
17673 delta += patch_len - 1;
17679 /* convert load instructions that access fields of a context type into a
17680 * sequence of instructions that access fields of the underlying structure:
17681 * struct __sk_buff -> struct sk_buff
17682 * struct bpf_sock_ops -> struct sock
17684 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17686 const struct bpf_verifier_ops *ops = env->ops;
17687 int i, cnt, size, ctx_field_size, delta = 0;
17688 const int insn_cnt = env->prog->len;
17689 struct bpf_insn insn_buf[16], *insn;
17690 u32 target_size, size_default, off;
17691 struct bpf_prog *new_prog;
17692 enum bpf_access_type type;
17693 bool is_narrower_load;
17695 if (ops->gen_prologue || env->seen_direct_write) {
17696 if (!ops->gen_prologue) {
17697 verbose(env, "bpf verifier is misconfigured\n");
17700 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17702 if (cnt >= ARRAY_SIZE(insn_buf)) {
17703 verbose(env, "bpf verifier is misconfigured\n");
17706 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17710 env->prog = new_prog;
17715 if (bpf_prog_is_offloaded(env->prog->aux))
17718 insn = env->prog->insnsi + delta;
17720 for (i = 0; i < insn_cnt; i++, insn++) {
17721 bpf_convert_ctx_access_t convert_ctx_access;
17724 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17725 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17726 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17727 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
17728 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
17729 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
17730 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
17732 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17733 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17734 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17735 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17736 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17737 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17738 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17739 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17745 if (type == BPF_WRITE &&
17746 env->insn_aux_data[i + delta].sanitize_stack_spill) {
17747 struct bpf_insn patch[] = {
17752 cnt = ARRAY_SIZE(patch);
17753 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17758 env->prog = new_prog;
17759 insn = new_prog->insnsi + i + delta;
17763 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17765 if (!ops->convert_ctx_access)
17767 convert_ctx_access = ops->convert_ctx_access;
17769 case PTR_TO_SOCKET:
17770 case PTR_TO_SOCK_COMMON:
17771 convert_ctx_access = bpf_sock_convert_ctx_access;
17773 case PTR_TO_TCP_SOCK:
17774 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17776 case PTR_TO_XDP_SOCK:
17777 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17779 case PTR_TO_BTF_ID:
17780 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17781 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17782 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17783 * be said once it is marked PTR_UNTRUSTED, hence we must handle
17784 * any faults for loads into such types. BPF_WRITE is disallowed
17787 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17788 if (type == BPF_READ) {
17789 if (BPF_MODE(insn->code) == BPF_MEM)
17790 insn->code = BPF_LDX | BPF_PROBE_MEM |
17791 BPF_SIZE((insn)->code);
17793 insn->code = BPF_LDX | BPF_PROBE_MEMSX |
17794 BPF_SIZE((insn)->code);
17795 env->prog->aux->num_exentries++;
17802 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17803 size = BPF_LDST_BYTES(insn);
17804 mode = BPF_MODE(insn->code);
17806 /* If the read access is a narrower load of the field,
17807 * convert to a 4/8-byte load, to minimum program type specific
17808 * convert_ctx_access changes. If conversion is successful,
17809 * we will apply proper mask to the result.
17811 is_narrower_load = size < ctx_field_size;
17812 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17814 if (is_narrower_load) {
17817 if (type == BPF_WRITE) {
17818 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17823 if (ctx_field_size == 4)
17825 else if (ctx_field_size == 8)
17826 size_code = BPF_DW;
17828 insn->off = off & ~(size_default - 1);
17829 insn->code = BPF_LDX | BPF_MEM | size_code;
17833 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17835 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17836 (ctx_field_size && !target_size)) {
17837 verbose(env, "bpf verifier is misconfigured\n");
17841 if (is_narrower_load && size < target_size) {
17842 u8 shift = bpf_ctx_narrow_access_offset(
17843 off, size, size_default) * 8;
17844 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17845 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17848 if (ctx_field_size <= 4) {
17850 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17853 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17854 (1 << size * 8) - 1);
17857 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17860 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17861 (1ULL << size * 8) - 1);
17864 if (mode == BPF_MEMSX)
17865 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
17866 insn->dst_reg, insn->dst_reg,
17869 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17875 /* keep walking new program and skip insns we just inserted */
17876 env->prog = new_prog;
17877 insn = new_prog->insnsi + i + delta;
17883 static int jit_subprogs(struct bpf_verifier_env *env)
17885 struct bpf_prog *prog = env->prog, **func, *tmp;
17886 int i, j, subprog_start, subprog_end = 0, len, subprog;
17887 struct bpf_map *map_ptr;
17888 struct bpf_insn *insn;
17889 void *old_bpf_func;
17890 int err, num_exentries;
17892 if (env->subprog_cnt <= 1)
17895 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17896 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17899 /* Upon error here we cannot fall back to interpreter but
17900 * need a hard reject of the program. Thus -EFAULT is
17901 * propagated in any case.
17903 subprog = find_subprog(env, i + insn->imm + 1);
17905 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17906 i + insn->imm + 1);
17909 /* temporarily remember subprog id inside insn instead of
17910 * aux_data, since next loop will split up all insns into funcs
17912 insn->off = subprog;
17913 /* remember original imm in case JIT fails and fallback
17914 * to interpreter will be needed
17916 env->insn_aux_data[i].call_imm = insn->imm;
17917 /* point imm to __bpf_call_base+1 from JITs point of view */
17919 if (bpf_pseudo_func(insn))
17920 /* jit (e.g. x86_64) may emit fewer instructions
17921 * if it learns a u32 imm is the same as a u64 imm.
17922 * Force a non zero here.
17927 err = bpf_prog_alloc_jited_linfo(prog);
17929 goto out_undo_insn;
17932 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17934 goto out_undo_insn;
17936 for (i = 0; i < env->subprog_cnt; i++) {
17937 subprog_start = subprog_end;
17938 subprog_end = env->subprog_info[i + 1].start;
17940 len = subprog_end - subprog_start;
17941 /* bpf_prog_run() doesn't call subprogs directly,
17942 * hence main prog stats include the runtime of subprogs.
17943 * subprogs don't have IDs and not reachable via prog_get_next_id
17944 * func[i]->stats will never be accessed and stays NULL
17946 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17949 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17950 len * sizeof(struct bpf_insn));
17951 func[i]->type = prog->type;
17952 func[i]->len = len;
17953 if (bpf_prog_calc_tag(func[i]))
17955 func[i]->is_func = 1;
17956 func[i]->aux->func_idx = i;
17957 /* Below members will be freed only at prog->aux */
17958 func[i]->aux->btf = prog->aux->btf;
17959 func[i]->aux->func_info = prog->aux->func_info;
17960 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17961 func[i]->aux->poke_tab = prog->aux->poke_tab;
17962 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17964 for (j = 0; j < prog->aux->size_poke_tab; j++) {
17965 struct bpf_jit_poke_descriptor *poke;
17967 poke = &prog->aux->poke_tab[j];
17968 if (poke->insn_idx < subprog_end &&
17969 poke->insn_idx >= subprog_start)
17970 poke->aux = func[i]->aux;
17973 func[i]->aux->name[0] = 'F';
17974 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17975 func[i]->jit_requested = 1;
17976 func[i]->blinding_requested = prog->blinding_requested;
17977 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17978 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17979 func[i]->aux->linfo = prog->aux->linfo;
17980 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17981 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17982 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17984 insn = func[i]->insnsi;
17985 for (j = 0; j < func[i]->len; j++, insn++) {
17986 if (BPF_CLASS(insn->code) == BPF_LDX &&
17987 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
17988 BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
17991 func[i]->aux->num_exentries = num_exentries;
17992 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
17993 func[i] = bpf_int_jit_compile(func[i]);
17994 if (!func[i]->jited) {
18001 /* at this point all bpf functions were successfully JITed
18002 * now populate all bpf_calls with correct addresses and
18003 * run last pass of JIT
18005 for (i = 0; i < env->subprog_cnt; i++) {
18006 insn = func[i]->insnsi;
18007 for (j = 0; j < func[i]->len; j++, insn++) {
18008 if (bpf_pseudo_func(insn)) {
18009 subprog = insn->off;
18010 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18011 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18014 if (!bpf_pseudo_call(insn))
18016 subprog = insn->off;
18017 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18020 /* we use the aux data to keep a list of the start addresses
18021 * of the JITed images for each function in the program
18023 * for some architectures, such as powerpc64, the imm field
18024 * might not be large enough to hold the offset of the start
18025 * address of the callee's JITed image from __bpf_call_base
18027 * in such cases, we can lookup the start address of a callee
18028 * by using its subprog id, available from the off field of
18029 * the call instruction, as an index for this list
18031 func[i]->aux->func = func;
18032 func[i]->aux->func_cnt = env->subprog_cnt;
18034 for (i = 0; i < env->subprog_cnt; i++) {
18035 old_bpf_func = func[i]->bpf_func;
18036 tmp = bpf_int_jit_compile(func[i]);
18037 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18038 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18045 /* finally lock prog and jit images for all functions and
18046 * populate kallsysm. Begin at the first subprogram, since
18047 * bpf_prog_load will add the kallsyms for the main program.
18049 for (i = 1; i < env->subprog_cnt; i++) {
18050 bpf_prog_lock_ro(func[i]);
18051 bpf_prog_kallsyms_add(func[i]);
18054 /* Last step: make now unused interpreter insns from main
18055 * prog consistent for later dump requests, so they can
18056 * later look the same as if they were interpreted only.
18058 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18059 if (bpf_pseudo_func(insn)) {
18060 insn[0].imm = env->insn_aux_data[i].call_imm;
18061 insn[1].imm = insn->off;
18065 if (!bpf_pseudo_call(insn))
18067 insn->off = env->insn_aux_data[i].call_imm;
18068 subprog = find_subprog(env, i + insn->off + 1);
18069 insn->imm = subprog;
18073 prog->bpf_func = func[0]->bpf_func;
18074 prog->jited_len = func[0]->jited_len;
18075 prog->aux->extable = func[0]->aux->extable;
18076 prog->aux->num_exentries = func[0]->aux->num_exentries;
18077 prog->aux->func = func;
18078 prog->aux->func_cnt = env->subprog_cnt;
18079 bpf_prog_jit_attempt_done(prog);
18082 /* We failed JIT'ing, so at this point we need to unregister poke
18083 * descriptors from subprogs, so that kernel is not attempting to
18084 * patch it anymore as we're freeing the subprog JIT memory.
18086 for (i = 0; i < prog->aux->size_poke_tab; i++) {
18087 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18088 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18090 /* At this point we're guaranteed that poke descriptors are not
18091 * live anymore. We can just unlink its descriptor table as it's
18092 * released with the main prog.
18094 for (i = 0; i < env->subprog_cnt; i++) {
18097 func[i]->aux->poke_tab = NULL;
18098 bpf_jit_free(func[i]);
18102 /* cleanup main prog to be interpreted */
18103 prog->jit_requested = 0;
18104 prog->blinding_requested = 0;
18105 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18106 if (!bpf_pseudo_call(insn))
18109 insn->imm = env->insn_aux_data[i].call_imm;
18111 bpf_prog_jit_attempt_done(prog);
18115 static int fixup_call_args(struct bpf_verifier_env *env)
18117 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18118 struct bpf_prog *prog = env->prog;
18119 struct bpf_insn *insn = prog->insnsi;
18120 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18125 if (env->prog->jit_requested &&
18126 !bpf_prog_is_offloaded(env->prog->aux)) {
18127 err = jit_subprogs(env);
18130 if (err == -EFAULT)
18133 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18134 if (has_kfunc_call) {
18135 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18138 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18139 /* When JIT fails the progs with bpf2bpf calls and tail_calls
18140 * have to be rejected, since interpreter doesn't support them yet.
18142 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18145 for (i = 0; i < prog->len; i++, insn++) {
18146 if (bpf_pseudo_func(insn)) {
18147 /* When JIT fails the progs with callback calls
18148 * have to be rejected, since interpreter doesn't support them yet.
18150 verbose(env, "callbacks are not allowed in non-JITed programs\n");
18154 if (!bpf_pseudo_call(insn))
18156 depth = get_callee_stack_depth(env, insn, i);
18159 bpf_patch_call_args(insn, depth);
18166 /* replace a generic kfunc with a specialized version if necessary */
18167 static void specialize_kfunc(struct bpf_verifier_env *env,
18168 u32 func_id, u16 offset, unsigned long *addr)
18170 struct bpf_prog *prog = env->prog;
18171 bool seen_direct_write;
18175 if (bpf_dev_bound_kfunc_id(func_id)) {
18176 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18178 *addr = (unsigned long)xdp_kfunc;
18181 /* fallback to default kfunc when not supported by netdev */
18187 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18188 seen_direct_write = env->seen_direct_write;
18189 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18192 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18194 /* restore env->seen_direct_write to its original value, since
18195 * may_access_direct_pkt_data mutates it
18197 env->seen_direct_write = seen_direct_write;
18201 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18202 u16 struct_meta_reg,
18203 u16 node_offset_reg,
18204 struct bpf_insn *insn,
18205 struct bpf_insn *insn_buf,
18208 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18209 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18211 insn_buf[0] = addr[0];
18212 insn_buf[1] = addr[1];
18213 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18214 insn_buf[3] = *insn;
18218 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18219 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18221 const struct bpf_kfunc_desc *desc;
18224 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18230 /* insn->imm has the btf func_id. Replace it with an offset relative to
18231 * __bpf_call_base, unless the JIT needs to call functions that are
18232 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18234 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18236 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18241 if (!bpf_jit_supports_far_kfunc_call())
18242 insn->imm = BPF_CALL_IMM(desc->addr);
18245 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18246 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18247 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18248 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18250 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18251 insn_buf[1] = addr[0];
18252 insn_buf[2] = addr[1];
18253 insn_buf[3] = *insn;
18255 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18256 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18257 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18258 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18260 insn_buf[0] = addr[0];
18261 insn_buf[1] = addr[1];
18262 insn_buf[2] = *insn;
18264 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18265 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18266 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18267 int struct_meta_reg = BPF_REG_3;
18268 int node_offset_reg = BPF_REG_4;
18270 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18271 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18272 struct_meta_reg = BPF_REG_4;
18273 node_offset_reg = BPF_REG_5;
18276 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18277 node_offset_reg, insn, insn_buf, cnt);
18278 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18279 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18280 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18286 /* Do various post-verification rewrites in a single program pass.
18287 * These rewrites simplify JIT and interpreter implementations.
18289 static int do_misc_fixups(struct bpf_verifier_env *env)
18291 struct bpf_prog *prog = env->prog;
18292 enum bpf_attach_type eatype = prog->expected_attach_type;
18293 enum bpf_prog_type prog_type = resolve_prog_type(prog);
18294 struct bpf_insn *insn = prog->insnsi;
18295 const struct bpf_func_proto *fn;
18296 const int insn_cnt = prog->len;
18297 const struct bpf_map_ops *ops;
18298 struct bpf_insn_aux_data *aux;
18299 struct bpf_insn insn_buf[16];
18300 struct bpf_prog *new_prog;
18301 struct bpf_map *map_ptr;
18302 int i, ret, cnt, delta = 0;
18304 for (i = 0; i < insn_cnt; i++, insn++) {
18305 /* Make divide-by-zero exceptions impossible. */
18306 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18307 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18308 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18309 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18310 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18311 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18312 struct bpf_insn *patchlet;
18313 struct bpf_insn chk_and_div[] = {
18314 /* [R,W]x div 0 -> 0 */
18315 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18316 BPF_JNE | BPF_K, insn->src_reg,
18318 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18319 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18322 struct bpf_insn chk_and_mod[] = {
18323 /* [R,W]x mod 0 -> [R,W]x */
18324 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18325 BPF_JEQ | BPF_K, insn->src_reg,
18326 0, 1 + (is64 ? 0 : 1), 0),
18328 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18329 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18332 patchlet = isdiv ? chk_and_div : chk_and_mod;
18333 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18334 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18336 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18341 env->prog = prog = new_prog;
18342 insn = new_prog->insnsi + i + delta;
18346 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18347 if (BPF_CLASS(insn->code) == BPF_LD &&
18348 (BPF_MODE(insn->code) == BPF_ABS ||
18349 BPF_MODE(insn->code) == BPF_IND)) {
18350 cnt = env->ops->gen_ld_abs(insn, insn_buf);
18351 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18352 verbose(env, "bpf verifier is misconfigured\n");
18356 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18361 env->prog = prog = new_prog;
18362 insn = new_prog->insnsi + i + delta;
18366 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
18367 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18368 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18369 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18370 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18371 struct bpf_insn *patch = &insn_buf[0];
18372 bool issrc, isneg, isimm;
18375 aux = &env->insn_aux_data[i + delta];
18376 if (!aux->alu_state ||
18377 aux->alu_state == BPF_ALU_NON_POINTER)
18380 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18381 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18382 BPF_ALU_SANITIZE_SRC;
18383 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18385 off_reg = issrc ? insn->src_reg : insn->dst_reg;
18387 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18390 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18391 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18392 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18393 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18394 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18395 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18396 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18399 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18400 insn->src_reg = BPF_REG_AX;
18402 insn->code = insn->code == code_add ?
18403 code_sub : code_add;
18405 if (issrc && isneg && !isimm)
18406 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18407 cnt = patch - insn_buf;
18409 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18414 env->prog = prog = new_prog;
18415 insn = new_prog->insnsi + i + delta;
18419 if (insn->code != (BPF_JMP | BPF_CALL))
18421 if (insn->src_reg == BPF_PSEUDO_CALL)
18423 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18424 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18430 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18435 env->prog = prog = new_prog;
18436 insn = new_prog->insnsi + i + delta;
18440 if (insn->imm == BPF_FUNC_get_route_realm)
18441 prog->dst_needed = 1;
18442 if (insn->imm == BPF_FUNC_get_prandom_u32)
18443 bpf_user_rnd_init_once();
18444 if (insn->imm == BPF_FUNC_override_return)
18445 prog->kprobe_override = 1;
18446 if (insn->imm == BPF_FUNC_tail_call) {
18447 /* If we tail call into other programs, we
18448 * cannot make any assumptions since they can
18449 * be replaced dynamically during runtime in
18450 * the program array.
18452 prog->cb_access = 1;
18453 if (!allow_tail_call_in_subprogs(env))
18454 prog->aux->stack_depth = MAX_BPF_STACK;
18455 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18457 /* mark bpf_tail_call as different opcode to avoid
18458 * conditional branch in the interpreter for every normal
18459 * call and to prevent accidental JITing by JIT compiler
18460 * that doesn't support bpf_tail_call yet
18463 insn->code = BPF_JMP | BPF_TAIL_CALL;
18465 aux = &env->insn_aux_data[i + delta];
18466 if (env->bpf_capable && !prog->blinding_requested &&
18467 prog->jit_requested &&
18468 !bpf_map_key_poisoned(aux) &&
18469 !bpf_map_ptr_poisoned(aux) &&
18470 !bpf_map_ptr_unpriv(aux)) {
18471 struct bpf_jit_poke_descriptor desc = {
18472 .reason = BPF_POKE_REASON_TAIL_CALL,
18473 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18474 .tail_call.key = bpf_map_key_immediate(aux),
18475 .insn_idx = i + delta,
18478 ret = bpf_jit_add_poke_descriptor(prog, &desc);
18480 verbose(env, "adding tail call poke descriptor failed\n");
18484 insn->imm = ret + 1;
18488 if (!bpf_map_ptr_unpriv(aux))
18491 /* instead of changing every JIT dealing with tail_call
18492 * emit two extra insns:
18493 * if (index >= max_entries) goto out;
18494 * index &= array->index_mask;
18495 * to avoid out-of-bounds cpu speculation
18497 if (bpf_map_ptr_poisoned(aux)) {
18498 verbose(env, "tail_call abusing map_ptr\n");
18502 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18503 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18504 map_ptr->max_entries, 2);
18505 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18506 container_of(map_ptr,
18509 insn_buf[2] = *insn;
18511 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18516 env->prog = prog = new_prog;
18517 insn = new_prog->insnsi + i + delta;
18521 if (insn->imm == BPF_FUNC_timer_set_callback) {
18522 /* The verifier will process callback_fn as many times as necessary
18523 * with different maps and the register states prepared by
18524 * set_timer_callback_state will be accurate.
18526 * The following use case is valid:
18527 * map1 is shared by prog1, prog2, prog3.
18528 * prog1 calls bpf_timer_init for some map1 elements
18529 * prog2 calls bpf_timer_set_callback for some map1 elements.
18530 * Those that were not bpf_timer_init-ed will return -EINVAL.
18531 * prog3 calls bpf_timer_start for some map1 elements.
18532 * Those that were not both bpf_timer_init-ed and
18533 * bpf_timer_set_callback-ed will return -EINVAL.
18535 struct bpf_insn ld_addrs[2] = {
18536 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18539 insn_buf[0] = ld_addrs[0];
18540 insn_buf[1] = ld_addrs[1];
18541 insn_buf[2] = *insn;
18544 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18549 env->prog = prog = new_prog;
18550 insn = new_prog->insnsi + i + delta;
18551 goto patch_call_imm;
18554 if (is_storage_get_function(insn->imm)) {
18555 if (!env->prog->aux->sleepable ||
18556 env->insn_aux_data[i + delta].storage_get_func_atomic)
18557 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18559 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18560 insn_buf[1] = *insn;
18563 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18568 env->prog = prog = new_prog;
18569 insn = new_prog->insnsi + i + delta;
18570 goto patch_call_imm;
18573 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18574 * and other inlining handlers are currently limited to 64 bit
18577 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18578 (insn->imm == BPF_FUNC_map_lookup_elem ||
18579 insn->imm == BPF_FUNC_map_update_elem ||
18580 insn->imm == BPF_FUNC_map_delete_elem ||
18581 insn->imm == BPF_FUNC_map_push_elem ||
18582 insn->imm == BPF_FUNC_map_pop_elem ||
18583 insn->imm == BPF_FUNC_map_peek_elem ||
18584 insn->imm == BPF_FUNC_redirect_map ||
18585 insn->imm == BPF_FUNC_for_each_map_elem ||
18586 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18587 aux = &env->insn_aux_data[i + delta];
18588 if (bpf_map_ptr_poisoned(aux))
18589 goto patch_call_imm;
18591 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18592 ops = map_ptr->ops;
18593 if (insn->imm == BPF_FUNC_map_lookup_elem &&
18594 ops->map_gen_lookup) {
18595 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18596 if (cnt == -EOPNOTSUPP)
18597 goto patch_map_ops_generic;
18598 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18599 verbose(env, "bpf verifier is misconfigured\n");
18603 new_prog = bpf_patch_insn_data(env, i + delta,
18609 env->prog = prog = new_prog;
18610 insn = new_prog->insnsi + i + delta;
18614 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18615 (void *(*)(struct bpf_map *map, void *key))NULL));
18616 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18617 (long (*)(struct bpf_map *map, void *key))NULL));
18618 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18619 (long (*)(struct bpf_map *map, void *key, void *value,
18621 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18622 (long (*)(struct bpf_map *map, void *value,
18624 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18625 (long (*)(struct bpf_map *map, void *value))NULL));
18626 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18627 (long (*)(struct bpf_map *map, void *value))NULL));
18628 BUILD_BUG_ON(!__same_type(ops->map_redirect,
18629 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18630 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18631 (long (*)(struct bpf_map *map,
18632 bpf_callback_t callback_fn,
18633 void *callback_ctx,
18635 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18636 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18638 patch_map_ops_generic:
18639 switch (insn->imm) {
18640 case BPF_FUNC_map_lookup_elem:
18641 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18643 case BPF_FUNC_map_update_elem:
18644 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18646 case BPF_FUNC_map_delete_elem:
18647 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18649 case BPF_FUNC_map_push_elem:
18650 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18652 case BPF_FUNC_map_pop_elem:
18653 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18655 case BPF_FUNC_map_peek_elem:
18656 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18658 case BPF_FUNC_redirect_map:
18659 insn->imm = BPF_CALL_IMM(ops->map_redirect);
18661 case BPF_FUNC_for_each_map_elem:
18662 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18664 case BPF_FUNC_map_lookup_percpu_elem:
18665 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18669 goto patch_call_imm;
18672 /* Implement bpf_jiffies64 inline. */
18673 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18674 insn->imm == BPF_FUNC_jiffies64) {
18675 struct bpf_insn ld_jiffies_addr[2] = {
18676 BPF_LD_IMM64(BPF_REG_0,
18677 (unsigned long)&jiffies),
18680 insn_buf[0] = ld_jiffies_addr[0];
18681 insn_buf[1] = ld_jiffies_addr[1];
18682 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18686 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18692 env->prog = prog = new_prog;
18693 insn = new_prog->insnsi + i + delta;
18697 /* Implement bpf_get_func_arg inline. */
18698 if (prog_type == BPF_PROG_TYPE_TRACING &&
18699 insn->imm == BPF_FUNC_get_func_arg) {
18700 /* Load nr_args from ctx - 8 */
18701 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18702 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18703 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18704 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18705 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18706 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18707 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18708 insn_buf[7] = BPF_JMP_A(1);
18709 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18712 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18717 env->prog = prog = new_prog;
18718 insn = new_prog->insnsi + i + delta;
18722 /* Implement bpf_get_func_ret inline. */
18723 if (prog_type == BPF_PROG_TYPE_TRACING &&
18724 insn->imm == BPF_FUNC_get_func_ret) {
18725 if (eatype == BPF_TRACE_FEXIT ||
18726 eatype == BPF_MODIFY_RETURN) {
18727 /* Load nr_args from ctx - 8 */
18728 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18729 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18730 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18731 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18732 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18733 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18736 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18740 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18745 env->prog = prog = new_prog;
18746 insn = new_prog->insnsi + i + delta;
18750 /* Implement get_func_arg_cnt inline. */
18751 if (prog_type == BPF_PROG_TYPE_TRACING &&
18752 insn->imm == BPF_FUNC_get_func_arg_cnt) {
18753 /* Load nr_args from ctx - 8 */
18754 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18756 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18760 env->prog = prog = new_prog;
18761 insn = new_prog->insnsi + i + delta;
18765 /* Implement bpf_get_func_ip inline. */
18766 if (prog_type == BPF_PROG_TYPE_TRACING &&
18767 insn->imm == BPF_FUNC_get_func_ip) {
18768 /* Load IP address from ctx - 16 */
18769 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18771 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18775 env->prog = prog = new_prog;
18776 insn = new_prog->insnsi + i + delta;
18781 fn = env->ops->get_func_proto(insn->imm, env->prog);
18782 /* all functions that have prototype and verifier allowed
18783 * programs to call them, must be real in-kernel functions
18787 "kernel subsystem misconfigured func %s#%d\n",
18788 func_id_name(insn->imm), insn->imm);
18791 insn->imm = fn->func - __bpf_call_base;
18794 /* Since poke tab is now finalized, publish aux to tracker. */
18795 for (i = 0; i < prog->aux->size_poke_tab; i++) {
18796 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18797 if (!map_ptr->ops->map_poke_track ||
18798 !map_ptr->ops->map_poke_untrack ||
18799 !map_ptr->ops->map_poke_run) {
18800 verbose(env, "bpf verifier is misconfigured\n");
18804 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18806 verbose(env, "tracking tail call prog failed\n");
18811 sort_kfunc_descs_by_imm_off(env->prog);
18816 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18819 u32 callback_subprogno,
18822 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18823 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18824 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18825 int reg_loop_max = BPF_REG_6;
18826 int reg_loop_cnt = BPF_REG_7;
18827 int reg_loop_ctx = BPF_REG_8;
18829 struct bpf_prog *new_prog;
18830 u32 callback_start;
18831 u32 call_insn_offset;
18832 s32 callback_offset;
18834 /* This represents an inlined version of bpf_iter.c:bpf_loop,
18835 * be careful to modify this code in sync.
18837 struct bpf_insn insn_buf[] = {
18838 /* Return error and jump to the end of the patch if
18839 * expected number of iterations is too big.
18841 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18842 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18843 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18844 /* spill R6, R7, R8 to use these as loop vars */
18845 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18846 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18847 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18848 /* initialize loop vars */
18849 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18850 BPF_MOV32_IMM(reg_loop_cnt, 0),
18851 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18853 * if reg_loop_cnt >= reg_loop_max skip the loop body
18855 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18857 * correct callback offset would be set after patching
18859 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18860 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18862 /* increment loop counter */
18863 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18864 /* jump to loop header if callback returned 0 */
18865 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18866 /* return value of bpf_loop,
18867 * set R0 to the number of iterations
18869 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18870 /* restore original values of R6, R7, R8 */
18871 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18872 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18873 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18876 *cnt = ARRAY_SIZE(insn_buf);
18877 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18881 /* callback start is known only after patching */
18882 callback_start = env->subprog_info[callback_subprogno].start;
18883 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18884 call_insn_offset = position + 12;
18885 callback_offset = callback_start - call_insn_offset - 1;
18886 new_prog->insnsi[call_insn_offset].imm = callback_offset;
18891 static bool is_bpf_loop_call(struct bpf_insn *insn)
18893 return insn->code == (BPF_JMP | BPF_CALL) &&
18894 insn->src_reg == 0 &&
18895 insn->imm == BPF_FUNC_loop;
18898 /* For all sub-programs in the program (including main) check
18899 * insn_aux_data to see if there are bpf_loop calls that require
18900 * inlining. If such calls are found the calls are replaced with a
18901 * sequence of instructions produced by `inline_bpf_loop` function and
18902 * subprog stack_depth is increased by the size of 3 registers.
18903 * This stack space is used to spill values of the R6, R7, R8. These
18904 * registers are used to store the loop bound, counter and context
18907 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18909 struct bpf_subprog_info *subprogs = env->subprog_info;
18910 int i, cur_subprog = 0, cnt, delta = 0;
18911 struct bpf_insn *insn = env->prog->insnsi;
18912 int insn_cnt = env->prog->len;
18913 u16 stack_depth = subprogs[cur_subprog].stack_depth;
18914 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18915 u16 stack_depth_extra = 0;
18917 for (i = 0; i < insn_cnt; i++, insn++) {
18918 struct bpf_loop_inline_state *inline_state =
18919 &env->insn_aux_data[i + delta].loop_inline_state;
18921 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18922 struct bpf_prog *new_prog;
18924 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18925 new_prog = inline_bpf_loop(env,
18927 -(stack_depth + stack_depth_extra),
18928 inline_state->callback_subprogno,
18934 env->prog = new_prog;
18935 insn = new_prog->insnsi + i + delta;
18938 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18939 subprogs[cur_subprog].stack_depth += stack_depth_extra;
18941 stack_depth = subprogs[cur_subprog].stack_depth;
18942 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18943 stack_depth_extra = 0;
18947 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18952 static void free_states(struct bpf_verifier_env *env)
18954 struct bpf_verifier_state_list *sl, *sln;
18957 sl = env->free_list;
18960 free_verifier_state(&sl->state, false);
18964 env->free_list = NULL;
18966 if (!env->explored_states)
18969 for (i = 0; i < state_htab_size(env); i++) {
18970 sl = env->explored_states[i];
18974 free_verifier_state(&sl->state, false);
18978 env->explored_states[i] = NULL;
18982 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18984 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18985 struct bpf_verifier_state *state;
18986 struct bpf_reg_state *regs;
18989 env->prev_linfo = NULL;
18992 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18995 state->curframe = 0;
18996 state->speculative = false;
18997 state->branches = 1;
18998 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18999 if (!state->frame[0]) {
19003 env->cur_state = state;
19004 init_func_state(env, state->frame[0],
19005 BPF_MAIN_FUNC /* callsite */,
19008 state->first_insn_idx = env->subprog_info[subprog].start;
19009 state->last_insn_idx = -1;
19011 regs = state->frame[state->curframe]->regs;
19012 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19013 ret = btf_prepare_func_args(env, subprog, regs);
19016 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19017 if (regs[i].type == PTR_TO_CTX)
19018 mark_reg_known_zero(env, regs, i);
19019 else if (regs[i].type == SCALAR_VALUE)
19020 mark_reg_unknown(env, regs, i);
19021 else if (base_type(regs[i].type) == PTR_TO_MEM) {
19022 const u32 mem_size = regs[i].mem_size;
19024 mark_reg_known_zero(env, regs, i);
19025 regs[i].mem_size = mem_size;
19026 regs[i].id = ++env->id_gen;
19030 /* 1st arg to a function */
19031 regs[BPF_REG_1].type = PTR_TO_CTX;
19032 mark_reg_known_zero(env, regs, BPF_REG_1);
19033 ret = btf_check_subprog_arg_match(env, subprog, regs);
19034 if (ret == -EFAULT)
19035 /* unlikely verifier bug. abort.
19036 * ret == 0 and ret < 0 are sadly acceptable for
19037 * main() function due to backward compatibility.
19038 * Like socket filter program may be written as:
19039 * int bpf_prog(struct pt_regs *ctx)
19040 * and never dereference that ctx in the program.
19041 * 'struct pt_regs' is a type mismatch for socket
19042 * filter that should be using 'struct __sk_buff'.
19047 ret = do_check(env);
19049 /* check for NULL is necessary, since cur_state can be freed inside
19050 * do_check() under memory pressure.
19052 if (env->cur_state) {
19053 free_verifier_state(env->cur_state, true);
19054 env->cur_state = NULL;
19056 while (!pop_stack(env, NULL, NULL, false));
19057 if (!ret && pop_log)
19058 bpf_vlog_reset(&env->log, 0);
19063 /* Verify all global functions in a BPF program one by one based on their BTF.
19064 * All global functions must pass verification. Otherwise the whole program is rejected.
19075 * foo() will be verified first for R1=any_scalar_value. During verification it
19076 * will be assumed that bar() already verified successfully and call to bar()
19077 * from foo() will be checked for type match only. Later bar() will be verified
19078 * independently to check that it's safe for R1=any_scalar_value.
19080 static int do_check_subprogs(struct bpf_verifier_env *env)
19082 struct bpf_prog_aux *aux = env->prog->aux;
19085 if (!aux->func_info)
19088 for (i = 1; i < env->subprog_cnt; i++) {
19089 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19091 env->insn_idx = env->subprog_info[i].start;
19092 WARN_ON_ONCE(env->insn_idx == 0);
19093 ret = do_check_common(env, i);
19096 } else if (env->log.level & BPF_LOG_LEVEL) {
19098 "Func#%d is safe for any args that match its prototype\n",
19105 static int do_check_main(struct bpf_verifier_env *env)
19110 ret = do_check_common(env, 0);
19112 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19117 static void print_verification_stats(struct bpf_verifier_env *env)
19121 if (env->log.level & BPF_LOG_STATS) {
19122 verbose(env, "verification time %lld usec\n",
19123 div_u64(env->verification_time, 1000));
19124 verbose(env, "stack depth ");
19125 for (i = 0; i < env->subprog_cnt; i++) {
19126 u32 depth = env->subprog_info[i].stack_depth;
19128 verbose(env, "%d", depth);
19129 if (i + 1 < env->subprog_cnt)
19132 verbose(env, "\n");
19134 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19135 "total_states %d peak_states %d mark_read %d\n",
19136 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19137 env->max_states_per_insn, env->total_states,
19138 env->peak_states, env->longest_mark_read_walk);
19141 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19143 const struct btf_type *t, *func_proto;
19144 const struct bpf_struct_ops *st_ops;
19145 const struct btf_member *member;
19146 struct bpf_prog *prog = env->prog;
19147 u32 btf_id, member_idx;
19150 if (!prog->gpl_compatible) {
19151 verbose(env, "struct ops programs must have a GPL compatible license\n");
19155 btf_id = prog->aux->attach_btf_id;
19156 st_ops = bpf_struct_ops_find(btf_id);
19158 verbose(env, "attach_btf_id %u is not a supported struct\n",
19164 member_idx = prog->expected_attach_type;
19165 if (member_idx >= btf_type_vlen(t)) {
19166 verbose(env, "attach to invalid member idx %u of struct %s\n",
19167 member_idx, st_ops->name);
19171 member = &btf_type_member(t)[member_idx];
19172 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19173 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19176 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19177 mname, member_idx, st_ops->name);
19181 if (st_ops->check_member) {
19182 int err = st_ops->check_member(t, member, prog);
19185 verbose(env, "attach to unsupported member %s of struct %s\n",
19186 mname, st_ops->name);
19191 prog->aux->attach_func_proto = func_proto;
19192 prog->aux->attach_func_name = mname;
19193 env->ops = st_ops->verifier_ops;
19197 #define SECURITY_PREFIX "security_"
19199 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19201 if (within_error_injection_list(addr) ||
19202 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19208 /* list of non-sleepable functions that are otherwise on
19209 * ALLOW_ERROR_INJECTION list
19211 BTF_SET_START(btf_non_sleepable_error_inject)
19212 /* Three functions below can be called from sleepable and non-sleepable context.
19213 * Assume non-sleepable from bpf safety point of view.
19215 BTF_ID(func, __filemap_add_folio)
19216 BTF_ID(func, should_fail_alloc_page)
19217 BTF_ID(func, should_failslab)
19218 BTF_SET_END(btf_non_sleepable_error_inject)
19220 static int check_non_sleepable_error_inject(u32 btf_id)
19222 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19225 int bpf_check_attach_target(struct bpf_verifier_log *log,
19226 const struct bpf_prog *prog,
19227 const struct bpf_prog *tgt_prog,
19229 struct bpf_attach_target_info *tgt_info)
19231 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19232 const char prefix[] = "btf_trace_";
19233 int ret = 0, subprog = -1, i;
19234 const struct btf_type *t;
19235 bool conservative = true;
19239 struct module *mod = NULL;
19242 bpf_log(log, "Tracing programs must provide btf_id\n");
19245 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19248 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19251 t = btf_type_by_id(btf, btf_id);
19253 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19256 tname = btf_name_by_offset(btf, t->name_off);
19258 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19262 struct bpf_prog_aux *aux = tgt_prog->aux;
19264 if (bpf_prog_is_dev_bound(prog->aux) &&
19265 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19266 bpf_log(log, "Target program bound device mismatch");
19270 for (i = 0; i < aux->func_info_cnt; i++)
19271 if (aux->func_info[i].type_id == btf_id) {
19275 if (subprog == -1) {
19276 bpf_log(log, "Subprog %s doesn't exist\n", tname);
19279 conservative = aux->func_info_aux[subprog].unreliable;
19280 if (prog_extension) {
19281 if (conservative) {
19283 "Cannot replace static functions\n");
19286 if (!prog->jit_requested) {
19288 "Extension programs should be JITed\n");
19292 if (!tgt_prog->jited) {
19293 bpf_log(log, "Can attach to only JITed progs\n");
19296 if (tgt_prog->type == prog->type) {
19297 /* Cannot fentry/fexit another fentry/fexit program.
19298 * Cannot attach program extension to another extension.
19299 * It's ok to attach fentry/fexit to extension program.
19301 bpf_log(log, "Cannot recursively attach\n");
19304 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19306 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19307 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19308 /* Program extensions can extend all program types
19309 * except fentry/fexit. The reason is the following.
19310 * The fentry/fexit programs are used for performance
19311 * analysis, stats and can be attached to any program
19312 * type except themselves. When extension program is
19313 * replacing XDP function it is necessary to allow
19314 * performance analysis of all functions. Both original
19315 * XDP program and its program extension. Hence
19316 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19317 * allowed. If extending of fentry/fexit was allowed it
19318 * would be possible to create long call chain
19319 * fentry->extension->fentry->extension beyond
19320 * reasonable stack size. Hence extending fentry is not
19323 bpf_log(log, "Cannot extend fentry/fexit\n");
19327 if (prog_extension) {
19328 bpf_log(log, "Cannot replace kernel functions\n");
19333 switch (prog->expected_attach_type) {
19334 case BPF_TRACE_RAW_TP:
19337 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19340 if (!btf_type_is_typedef(t)) {
19341 bpf_log(log, "attach_btf_id %u is not a typedef\n",
19345 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19346 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19350 tname += sizeof(prefix) - 1;
19351 t = btf_type_by_id(btf, t->type);
19352 if (!btf_type_is_ptr(t))
19353 /* should never happen in valid vmlinux build */
19355 t = btf_type_by_id(btf, t->type);
19356 if (!btf_type_is_func_proto(t))
19357 /* should never happen in valid vmlinux build */
19361 case BPF_TRACE_ITER:
19362 if (!btf_type_is_func(t)) {
19363 bpf_log(log, "attach_btf_id %u is not a function\n",
19367 t = btf_type_by_id(btf, t->type);
19368 if (!btf_type_is_func_proto(t))
19370 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19375 if (!prog_extension)
19378 case BPF_MODIFY_RETURN:
19380 case BPF_LSM_CGROUP:
19381 case BPF_TRACE_FENTRY:
19382 case BPF_TRACE_FEXIT:
19383 if (!btf_type_is_func(t)) {
19384 bpf_log(log, "attach_btf_id %u is not a function\n",
19388 if (prog_extension &&
19389 btf_check_type_match(log, prog, btf, t))
19391 t = btf_type_by_id(btf, t->type);
19392 if (!btf_type_is_func_proto(t))
19395 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19396 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19397 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19400 if (tgt_prog && conservative)
19403 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19409 addr = (long) tgt_prog->bpf_func;
19411 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19413 if (btf_is_module(btf)) {
19414 mod = btf_try_get_module(btf);
19416 addr = find_kallsyms_symbol_value(mod, tname);
19420 addr = kallsyms_lookup_name(tname);
19425 "The address of function %s cannot be found\n",
19431 if (prog->aux->sleepable) {
19433 switch (prog->type) {
19434 case BPF_PROG_TYPE_TRACING:
19436 /* fentry/fexit/fmod_ret progs can be sleepable if they are
19437 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19439 if (!check_non_sleepable_error_inject(btf_id) &&
19440 within_error_injection_list(addr))
19442 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
19443 * in the fmodret id set with the KF_SLEEPABLE flag.
19446 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19449 if (flags && (*flags & KF_SLEEPABLE))
19453 case BPF_PROG_TYPE_LSM:
19454 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
19455 * Only some of them are sleepable.
19457 if (bpf_lsm_is_sleepable_hook(btf_id))
19465 bpf_log(log, "%s is not sleepable\n", tname);
19468 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19471 bpf_log(log, "can't modify return codes of BPF programs\n");
19475 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19476 !check_attach_modify_return(addr, tname))
19480 bpf_log(log, "%s() is not modifiable\n", tname);
19487 tgt_info->tgt_addr = addr;
19488 tgt_info->tgt_name = tname;
19489 tgt_info->tgt_type = t;
19490 tgt_info->tgt_mod = mod;
19494 BTF_SET_START(btf_id_deny)
19497 BTF_ID(func, migrate_disable)
19498 BTF_ID(func, migrate_enable)
19500 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19501 BTF_ID(func, rcu_read_unlock_strict)
19503 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19504 BTF_ID(func, preempt_count_add)
19505 BTF_ID(func, preempt_count_sub)
19507 #ifdef CONFIG_PREEMPT_RCU
19508 BTF_ID(func, __rcu_read_lock)
19509 BTF_ID(func, __rcu_read_unlock)
19511 BTF_SET_END(btf_id_deny)
19513 static bool can_be_sleepable(struct bpf_prog *prog)
19515 if (prog->type == BPF_PROG_TYPE_TRACING) {
19516 switch (prog->expected_attach_type) {
19517 case BPF_TRACE_FENTRY:
19518 case BPF_TRACE_FEXIT:
19519 case BPF_MODIFY_RETURN:
19520 case BPF_TRACE_ITER:
19526 return prog->type == BPF_PROG_TYPE_LSM ||
19527 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19528 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19531 static int check_attach_btf_id(struct bpf_verifier_env *env)
19533 struct bpf_prog *prog = env->prog;
19534 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19535 struct bpf_attach_target_info tgt_info = {};
19536 u32 btf_id = prog->aux->attach_btf_id;
19537 struct bpf_trampoline *tr;
19541 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19542 if (prog->aux->sleepable)
19543 /* attach_btf_id checked to be zero already */
19545 verbose(env, "Syscall programs can only be sleepable\n");
19549 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19550 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19554 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19555 return check_struct_ops_btf_id(env);
19557 if (prog->type != BPF_PROG_TYPE_TRACING &&
19558 prog->type != BPF_PROG_TYPE_LSM &&
19559 prog->type != BPF_PROG_TYPE_EXT)
19562 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19566 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19567 /* to make freplace equivalent to their targets, they need to
19568 * inherit env->ops and expected_attach_type for the rest of the
19571 env->ops = bpf_verifier_ops[tgt_prog->type];
19572 prog->expected_attach_type = tgt_prog->expected_attach_type;
19575 /* store info about the attachment target that will be used later */
19576 prog->aux->attach_func_proto = tgt_info.tgt_type;
19577 prog->aux->attach_func_name = tgt_info.tgt_name;
19578 prog->aux->mod = tgt_info.tgt_mod;
19581 prog->aux->saved_dst_prog_type = tgt_prog->type;
19582 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19585 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19586 prog->aux->attach_btf_trace = true;
19588 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19589 if (!bpf_iter_prog_supported(prog))
19594 if (prog->type == BPF_PROG_TYPE_LSM) {
19595 ret = bpf_lsm_verify_prog(&env->log, prog);
19598 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
19599 btf_id_set_contains(&btf_id_deny, btf_id)) {
19603 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19604 tr = bpf_trampoline_get(key, &tgt_info);
19608 prog->aux->dst_trampoline = tr;
19612 struct btf *bpf_get_btf_vmlinux(void)
19614 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19615 mutex_lock(&bpf_verifier_lock);
19617 btf_vmlinux = btf_parse_vmlinux();
19618 mutex_unlock(&bpf_verifier_lock);
19620 return btf_vmlinux;
19623 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19625 u64 start_time = ktime_get_ns();
19626 struct bpf_verifier_env *env;
19627 int i, len, ret = -EINVAL, err;
19631 /* no program is valid */
19632 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19635 /* 'struct bpf_verifier_env' can be global, but since it's not small,
19636 * allocate/free it every time bpf_check() is called
19638 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19644 len = (*prog)->len;
19645 env->insn_aux_data =
19646 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19648 if (!env->insn_aux_data)
19650 for (i = 0; i < len; i++)
19651 env->insn_aux_data[i].orig_idx = i;
19653 env->ops = bpf_verifier_ops[env->prog->type];
19654 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19655 is_priv = bpf_capable();
19657 bpf_get_btf_vmlinux();
19659 /* grab the mutex to protect few globals used by verifier */
19661 mutex_lock(&bpf_verifier_lock);
19663 /* user could have requested verbose verifier output
19664 * and supplied buffer to store the verification trace
19666 ret = bpf_vlog_init(&env->log, attr->log_level,
19667 (char __user *) (unsigned long) attr->log_buf,
19672 mark_verifier_state_clean(env);
19674 if (IS_ERR(btf_vmlinux)) {
19675 /* Either gcc or pahole or kernel are broken. */
19676 verbose(env, "in-kernel BTF is malformed\n");
19677 ret = PTR_ERR(btf_vmlinux);
19678 goto skip_full_check;
19681 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19682 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19683 env->strict_alignment = true;
19684 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19685 env->strict_alignment = false;
19687 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19688 env->allow_uninit_stack = bpf_allow_uninit_stack();
19689 env->bypass_spec_v1 = bpf_bypass_spec_v1();
19690 env->bypass_spec_v4 = bpf_bypass_spec_v4();
19691 env->bpf_capable = bpf_capable();
19694 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19696 env->explored_states = kvcalloc(state_htab_size(env),
19697 sizeof(struct bpf_verifier_state_list *),
19700 if (!env->explored_states)
19701 goto skip_full_check;
19703 ret = add_subprog_and_kfunc(env);
19705 goto skip_full_check;
19707 ret = check_subprogs(env);
19709 goto skip_full_check;
19711 ret = check_btf_info(env, attr, uattr);
19713 goto skip_full_check;
19715 ret = check_attach_btf_id(env);
19717 goto skip_full_check;
19719 ret = resolve_pseudo_ldimm64(env);
19721 goto skip_full_check;
19723 if (bpf_prog_is_offloaded(env->prog->aux)) {
19724 ret = bpf_prog_offload_verifier_prep(env->prog);
19726 goto skip_full_check;
19729 ret = check_cfg(env);
19731 goto skip_full_check;
19733 ret = do_check_subprogs(env);
19734 ret = ret ?: do_check_main(env);
19736 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19737 ret = bpf_prog_offload_finalize(env);
19740 kvfree(env->explored_states);
19743 ret = check_max_stack_depth(env);
19745 /* instruction rewrites happen after this point */
19747 ret = optimize_bpf_loop(env);
19751 opt_hard_wire_dead_code_branches(env);
19753 ret = opt_remove_dead_code(env);
19755 ret = opt_remove_nops(env);
19758 sanitize_dead_code(env);
19762 /* program is valid, convert *(u32*)(ctx + off) accesses */
19763 ret = convert_ctx_accesses(env);
19766 ret = do_misc_fixups(env);
19768 /* do 32-bit optimization after insn patching has done so those patched
19769 * insns could be handled correctly.
19771 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19772 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19773 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19778 ret = fixup_call_args(env);
19780 env->verification_time = ktime_get_ns() - start_time;
19781 print_verification_stats(env);
19782 env->prog->aux->verified_insns = env->insn_processed;
19784 /* preserve original error even if log finalization is successful */
19785 err = bpf_vlog_finalize(&env->log, &log_true_size);
19789 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19790 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19791 &log_true_size, sizeof(log_true_size))) {
19793 goto err_release_maps;
19797 goto err_release_maps;
19799 if (env->used_map_cnt) {
19800 /* if program passed verifier, update used_maps in bpf_prog_info */
19801 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19802 sizeof(env->used_maps[0]),
19805 if (!env->prog->aux->used_maps) {
19807 goto err_release_maps;
19810 memcpy(env->prog->aux->used_maps, env->used_maps,
19811 sizeof(env->used_maps[0]) * env->used_map_cnt);
19812 env->prog->aux->used_map_cnt = env->used_map_cnt;
19814 if (env->used_btf_cnt) {
19815 /* if program passed verifier, update used_btfs in bpf_prog_aux */
19816 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19817 sizeof(env->used_btfs[0]),
19819 if (!env->prog->aux->used_btfs) {
19821 goto err_release_maps;
19824 memcpy(env->prog->aux->used_btfs, env->used_btfs,
19825 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19826 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19828 if (env->used_map_cnt || env->used_btf_cnt) {
19829 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
19830 * bpf_ld_imm64 instructions
19832 convert_pseudo_ld_imm64(env);
19835 adjust_btf_func(env);
19838 if (!env->prog->aux->used_maps)
19839 /* if we didn't copy map pointers into bpf_prog_info, release
19840 * them now. Otherwise free_used_maps() will release them.
19843 if (!env->prog->aux->used_btfs)
19846 /* extension progs temporarily inherit the attach_type of their targets
19847 for verification purposes, so set it back to zero before returning
19849 if (env->prog->type == BPF_PROG_TYPE_EXT)
19850 env->prog->expected_attach_type = 0;
19855 mutex_unlock(&bpf_verifier_lock);
19856 vfree(env->insn_aux_data);