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 || class == BPF_JMP ||
3016 /* BPF_END always use BPF_ALU class. */
3017 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3020 if (class == BPF_ALU || class == BPF_JMP32)
3023 if (class == BPF_LDX) {
3025 return BPF_SIZE(code) == BPF_DW;
3026 /* LDX source must be ptr. */
3030 if (class == BPF_STX) {
3031 /* BPF_STX (including atomic variants) has multiple source
3032 * operands, one of which is a ptr. Check whether the caller is
3035 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3037 return BPF_SIZE(code) == BPF_DW;
3040 if (class == BPF_LD) {
3041 u8 mode = BPF_MODE(code);
3044 if (mode == BPF_IMM)
3047 /* Both LD_IND and LD_ABS return 32-bit data. */
3051 /* Implicit ctx ptr. */
3052 if (regno == BPF_REG_6)
3055 /* Explicit source could be any width. */
3059 if (class == BPF_ST)
3060 /* The only source register for BPF_ST is a ptr. */
3063 /* Conservatively return true at default. */
3067 /* Return the regno defined by the insn, or -1. */
3068 static int insn_def_regno(const struct bpf_insn *insn)
3070 switch (BPF_CLASS(insn->code)) {
3076 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3077 (insn->imm & BPF_FETCH)) {
3078 if (insn->imm == BPF_CMPXCHG)
3081 return insn->src_reg;
3086 return insn->dst_reg;
3090 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3091 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3093 int dst_reg = insn_def_regno(insn);
3098 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3101 static void mark_insn_zext(struct bpf_verifier_env *env,
3102 struct bpf_reg_state *reg)
3104 s32 def_idx = reg->subreg_def;
3106 if (def_idx == DEF_NOT_SUBREG)
3109 env->insn_aux_data[def_idx - 1].zext_dst = true;
3110 /* The dst will be zero extended, so won't be sub-register anymore. */
3111 reg->subreg_def = DEF_NOT_SUBREG;
3114 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3115 enum reg_arg_type t)
3117 struct bpf_verifier_state *vstate = env->cur_state;
3118 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3119 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3120 struct bpf_reg_state *reg, *regs = state->regs;
3123 if (regno >= MAX_BPF_REG) {
3124 verbose(env, "R%d is invalid\n", regno);
3128 mark_reg_scratched(env, regno);
3131 rw64 = is_reg64(env, insn, regno, reg, t);
3133 /* check whether register used as source operand can be read */
3134 if (reg->type == NOT_INIT) {
3135 verbose(env, "R%d !read_ok\n", regno);
3138 /* We don't need to worry about FP liveness because it's read-only */
3139 if (regno == BPF_REG_FP)
3143 mark_insn_zext(env, reg);
3145 return mark_reg_read(env, reg, reg->parent,
3146 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3148 /* check whether register used as dest operand can be written to */
3149 if (regno == BPF_REG_FP) {
3150 verbose(env, "frame pointer is read only\n");
3153 reg->live |= REG_LIVE_WRITTEN;
3154 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3156 mark_reg_unknown(env, regs, regno);
3161 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3163 env->insn_aux_data[idx].jmp_point = true;
3166 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3168 return env->insn_aux_data[insn_idx].jmp_point;
3171 /* for any branch, call, exit record the history of jmps in the given state */
3172 static int push_jmp_history(struct bpf_verifier_env *env,
3173 struct bpf_verifier_state *cur)
3175 u32 cnt = cur->jmp_history_cnt;
3176 struct bpf_idx_pair *p;
3179 if (!is_jmp_point(env, env->insn_idx))
3183 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3184 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3187 p[cnt - 1].idx = env->insn_idx;
3188 p[cnt - 1].prev_idx = env->prev_insn_idx;
3189 cur->jmp_history = p;
3190 cur->jmp_history_cnt = cnt;
3194 /* Backtrack one insn at a time. If idx is not at the top of recorded
3195 * history then previous instruction came from straight line execution.
3197 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3202 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3203 i = st->jmp_history[cnt - 1].prev_idx;
3211 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3213 const struct btf_type *func;
3214 struct btf *desc_btf;
3216 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3219 desc_btf = find_kfunc_desc_btf(data, insn->off);
3220 if (IS_ERR(desc_btf))
3223 func = btf_type_by_id(desc_btf, insn->imm);
3224 return btf_name_by_offset(desc_btf, func->name_off);
3227 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3232 static inline void bt_reset(struct backtrack_state *bt)
3234 struct bpf_verifier_env *env = bt->env;
3236 memset(bt, 0, sizeof(*bt));
3240 static inline u32 bt_empty(struct backtrack_state *bt)
3245 for (i = 0; i <= bt->frame; i++)
3246 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3251 static inline int bt_subprog_enter(struct backtrack_state *bt)
3253 if (bt->frame == MAX_CALL_FRAMES - 1) {
3254 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3255 WARN_ONCE(1, "verifier backtracking bug");
3262 static inline int bt_subprog_exit(struct backtrack_state *bt)
3264 if (bt->frame == 0) {
3265 verbose(bt->env, "BUG subprog exit from frame 0\n");
3266 WARN_ONCE(1, "verifier backtracking bug");
3273 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3275 bt->reg_masks[frame] |= 1 << reg;
3278 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3280 bt->reg_masks[frame] &= ~(1 << reg);
3283 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3285 bt_set_frame_reg(bt, bt->frame, reg);
3288 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3290 bt_clear_frame_reg(bt, bt->frame, reg);
3293 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3295 bt->stack_masks[frame] |= 1ull << slot;
3298 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3300 bt->stack_masks[frame] &= ~(1ull << slot);
3303 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3305 bt_set_frame_slot(bt, bt->frame, slot);
3308 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3310 bt_clear_frame_slot(bt, bt->frame, slot);
3313 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3315 return bt->reg_masks[frame];
3318 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3320 return bt->reg_masks[bt->frame];
3323 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3325 return bt->stack_masks[frame];
3328 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3330 return bt->stack_masks[bt->frame];
3333 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3335 return bt->reg_masks[bt->frame] & (1 << reg);
3338 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3340 return bt->stack_masks[bt->frame] & (1ull << slot);
3343 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3344 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3346 DECLARE_BITMAP(mask, 64);
3352 bitmap_from_u64(mask, reg_mask);
3353 for_each_set_bit(i, mask, 32) {
3354 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3362 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3363 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3365 DECLARE_BITMAP(mask, 64);
3371 bitmap_from_u64(mask, stack_mask);
3372 for_each_set_bit(i, mask, 64) {
3373 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3382 /* For given verifier state backtrack_insn() is called from the last insn to
3383 * the first insn. Its purpose is to compute a bitmask of registers and
3384 * stack slots that needs precision in the parent verifier state.
3386 * @idx is an index of the instruction we are currently processing;
3387 * @subseq_idx is an index of the subsequent instruction that:
3388 * - *would be* executed next, if jump history is viewed in forward order;
3389 * - *was* processed previously during backtracking.
3391 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3392 struct backtrack_state *bt)
3394 const struct bpf_insn_cbs cbs = {
3395 .cb_call = disasm_kfunc_name,
3396 .cb_print = verbose,
3397 .private_data = env,
3399 struct bpf_insn *insn = env->prog->insnsi + idx;
3400 u8 class = BPF_CLASS(insn->code);
3401 u8 opcode = BPF_OP(insn->code);
3402 u8 mode = BPF_MODE(insn->code);
3403 u32 dreg = insn->dst_reg;
3404 u32 sreg = insn->src_reg;
3407 if (insn->code == 0)
3409 if (env->log.level & BPF_LOG_LEVEL2) {
3410 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3411 verbose(env, "mark_precise: frame%d: regs=%s ",
3412 bt->frame, env->tmp_str_buf);
3413 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3414 verbose(env, "stack=%s before ", env->tmp_str_buf);
3415 verbose(env, "%d: ", idx);
3416 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3419 if (class == BPF_ALU || class == BPF_ALU64) {
3420 if (!bt_is_reg_set(bt, dreg))
3422 if (opcode == BPF_MOV) {
3423 if (BPF_SRC(insn->code) == BPF_X) {
3424 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3425 * dreg needs precision after this insn
3426 * sreg needs precision before this insn
3428 bt_clear_reg(bt, dreg);
3429 bt_set_reg(bt, sreg);
3432 * dreg needs precision after this insn.
3433 * Corresponding register is already marked
3434 * as precise=true in this verifier state.
3435 * No further markings in parent are necessary
3437 bt_clear_reg(bt, dreg);
3440 if (BPF_SRC(insn->code) == BPF_X) {
3442 * both dreg and sreg need precision
3445 bt_set_reg(bt, sreg);
3447 * dreg still needs precision before this insn
3450 } else if (class == BPF_LDX) {
3451 if (!bt_is_reg_set(bt, dreg))
3453 bt_clear_reg(bt, dreg);
3455 /* scalars can only be spilled into stack w/o losing precision.
3456 * Load from any other memory can be zero extended.
3457 * The desire to keep that precision is already indicated
3458 * by 'precise' mark in corresponding register of this state.
3459 * No further tracking necessary.
3461 if (insn->src_reg != BPF_REG_FP)
3464 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3465 * that [fp - off] slot contains scalar that needs to be
3466 * tracked with precision
3468 spi = (-insn->off - 1) / BPF_REG_SIZE;
3470 verbose(env, "BUG spi %d\n", spi);
3471 WARN_ONCE(1, "verifier backtracking bug");
3474 bt_set_slot(bt, spi);
3475 } else if (class == BPF_STX || class == BPF_ST) {
3476 if (bt_is_reg_set(bt, dreg))
3477 /* stx & st shouldn't be using _scalar_ dst_reg
3478 * to access memory. It means backtracking
3479 * encountered a case of pointer subtraction.
3482 /* scalars can only be spilled into stack */
3483 if (insn->dst_reg != BPF_REG_FP)
3485 spi = (-insn->off - 1) / BPF_REG_SIZE;
3487 verbose(env, "BUG spi %d\n", spi);
3488 WARN_ONCE(1, "verifier backtracking bug");
3491 if (!bt_is_slot_set(bt, spi))
3493 bt_clear_slot(bt, spi);
3494 if (class == BPF_STX)
3495 bt_set_reg(bt, sreg);
3496 } else if (class == BPF_JMP || class == BPF_JMP32) {
3497 if (bpf_pseudo_call(insn)) {
3498 int subprog_insn_idx, subprog;
3500 subprog_insn_idx = idx + insn->imm + 1;
3501 subprog = find_subprog(env, subprog_insn_idx);
3505 if (subprog_is_global(env, subprog)) {
3506 /* check that jump history doesn't have any
3507 * extra instructions from subprog; the next
3508 * instruction after call to global subprog
3509 * should be literally next instruction in
3512 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3513 /* r1-r5 are invalidated after subprog call,
3514 * so for global func call it shouldn't be set
3517 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3518 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3519 WARN_ONCE(1, "verifier backtracking bug");
3522 /* global subprog always sets R0 */
3523 bt_clear_reg(bt, BPF_REG_0);
3526 /* static subprog call instruction, which
3527 * means that we are exiting current subprog,
3528 * so only r1-r5 could be still requested as
3529 * precise, r0 and r6-r10 or any stack slot in
3530 * the current frame should be zero by now
3532 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3533 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3534 WARN_ONCE(1, "verifier backtracking bug");
3537 /* we don't track register spills perfectly,
3538 * so fallback to force-precise instead of failing */
3539 if (bt_stack_mask(bt) != 0)
3541 /* propagate r1-r5 to the caller */
3542 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3543 if (bt_is_reg_set(bt, i)) {
3544 bt_clear_reg(bt, i);
3545 bt_set_frame_reg(bt, bt->frame - 1, i);
3548 if (bt_subprog_exit(bt))
3552 } else if ((bpf_helper_call(insn) &&
3553 is_callback_calling_function(insn->imm) &&
3554 !is_async_callback_calling_function(insn->imm)) ||
3555 (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3556 /* callback-calling helper or kfunc call, which means
3557 * we are exiting from subprog, but unlike the subprog
3558 * call handling above, we shouldn't propagate
3559 * precision of r1-r5 (if any requested), as they are
3560 * not actually arguments passed directly to callback
3563 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3564 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3565 WARN_ONCE(1, "verifier backtracking bug");
3568 if (bt_stack_mask(bt) != 0)
3570 /* clear r1-r5 in callback subprog's mask */
3571 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3572 bt_clear_reg(bt, i);
3573 if (bt_subprog_exit(bt))
3576 } else if (opcode == BPF_CALL) {
3577 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3578 * catch this error later. Make backtracking conservative
3581 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3583 /* regular helper call sets R0 */
3584 bt_clear_reg(bt, BPF_REG_0);
3585 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3586 /* if backtracing was looking for registers R1-R5
3587 * they should have been found already.
3589 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3590 WARN_ONCE(1, "verifier backtracking bug");
3593 } else if (opcode == BPF_EXIT) {
3596 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3597 /* if backtracing was looking for registers R1-R5
3598 * they should have been found already.
3600 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3601 WARN_ONCE(1, "verifier backtracking bug");
3605 /* BPF_EXIT in subprog or callback always returns
3606 * right after the call instruction, so by checking
3607 * whether the instruction at subseq_idx-1 is subprog
3608 * call or not we can distinguish actual exit from
3609 * *subprog* from exit from *callback*. In the former
3610 * case, we need to propagate r0 precision, if
3611 * necessary. In the former we never do that.
3613 r0_precise = subseq_idx - 1 >= 0 &&
3614 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3615 bt_is_reg_set(bt, BPF_REG_0);
3617 bt_clear_reg(bt, BPF_REG_0);
3618 if (bt_subprog_enter(bt))
3622 bt_set_reg(bt, BPF_REG_0);
3623 /* r6-r9 and stack slots will stay set in caller frame
3624 * bitmasks until we return back from callee(s)
3627 } else if (BPF_SRC(insn->code) == BPF_X) {
3628 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3631 * Both dreg and sreg need precision before
3632 * this insn. If only sreg was marked precise
3633 * before it would be equally necessary to
3634 * propagate it to dreg.
3636 bt_set_reg(bt, dreg);
3637 bt_set_reg(bt, sreg);
3638 /* else dreg <cond> K
3639 * Only dreg still needs precision before
3640 * this insn, so for the K-based conditional
3641 * there is nothing new to be marked.
3644 } else if (class == BPF_LD) {
3645 if (!bt_is_reg_set(bt, dreg))
3647 bt_clear_reg(bt, dreg);
3648 /* It's ld_imm64 or ld_abs or ld_ind.
3649 * For ld_imm64 no further tracking of precision
3650 * into parent is necessary
3652 if (mode == BPF_IND || mode == BPF_ABS)
3653 /* to be analyzed */
3659 /* the scalar precision tracking algorithm:
3660 * . at the start all registers have precise=false.
3661 * . scalar ranges are tracked as normal through alu and jmp insns.
3662 * . once precise value of the scalar register is used in:
3663 * . ptr + scalar alu
3664 * . if (scalar cond K|scalar)
3665 * . helper_call(.., scalar, ...) where ARG_CONST is expected
3666 * backtrack through the verifier states and mark all registers and
3667 * stack slots with spilled constants that these scalar regisers
3668 * should be precise.
3669 * . during state pruning two registers (or spilled stack slots)
3670 * are equivalent if both are not precise.
3672 * Note the verifier cannot simply walk register parentage chain,
3673 * since many different registers and stack slots could have been
3674 * used to compute single precise scalar.
3676 * The approach of starting with precise=true for all registers and then
3677 * backtrack to mark a register as not precise when the verifier detects
3678 * that program doesn't care about specific value (e.g., when helper
3679 * takes register as ARG_ANYTHING parameter) is not safe.
3681 * It's ok to walk single parentage chain of the verifier states.
3682 * It's possible that this backtracking will go all the way till 1st insn.
3683 * All other branches will be explored for needing precision later.
3685 * The backtracking needs to deal with cases like:
3686 * 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)
3689 * if r5 > 0x79f goto pc+7
3690 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3693 * call bpf_perf_event_output#25
3694 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3698 * call foo // uses callee's r6 inside to compute r0
3702 * to track above reg_mask/stack_mask needs to be independent for each frame.
3704 * Also if parent's curframe > frame where backtracking started,
3705 * the verifier need to mark registers in both frames, otherwise callees
3706 * may incorrectly prune callers. This is similar to
3707 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3709 * For now backtracking falls back into conservative marking.
3711 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3712 struct bpf_verifier_state *st)
3714 struct bpf_func_state *func;
3715 struct bpf_reg_state *reg;
3718 if (env->log.level & BPF_LOG_LEVEL2) {
3719 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3723 /* big hammer: mark all scalars precise in this path.
3724 * pop_stack may still get !precise scalars.
3725 * We also skip current state and go straight to first parent state,
3726 * because precision markings in current non-checkpointed state are
3727 * not needed. See why in the comment in __mark_chain_precision below.
3729 for (st = st->parent; st; st = st->parent) {
3730 for (i = 0; i <= st->curframe; i++) {
3731 func = st->frame[i];
3732 for (j = 0; j < BPF_REG_FP; j++) {
3733 reg = &func->regs[j];
3734 if (reg->type != SCALAR_VALUE || reg->precise)
3736 reg->precise = true;
3737 if (env->log.level & BPF_LOG_LEVEL2) {
3738 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3742 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3743 if (!is_spilled_reg(&func->stack[j]))
3745 reg = &func->stack[j].spilled_ptr;
3746 if (reg->type != SCALAR_VALUE || reg->precise)
3748 reg->precise = true;
3749 if (env->log.level & BPF_LOG_LEVEL2) {
3750 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3758 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3760 struct bpf_func_state *func;
3761 struct bpf_reg_state *reg;
3764 for (i = 0; i <= st->curframe; i++) {
3765 func = st->frame[i];
3766 for (j = 0; j < BPF_REG_FP; j++) {
3767 reg = &func->regs[j];
3768 if (reg->type != SCALAR_VALUE)
3770 reg->precise = false;
3772 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3773 if (!is_spilled_reg(&func->stack[j]))
3775 reg = &func->stack[j].spilled_ptr;
3776 if (reg->type != SCALAR_VALUE)
3778 reg->precise = false;
3783 static bool idset_contains(struct bpf_idset *s, u32 id)
3787 for (i = 0; i < s->count; ++i)
3788 if (s->ids[i] == id)
3794 static int idset_push(struct bpf_idset *s, u32 id)
3796 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3798 s->ids[s->count++] = id;
3802 static void idset_reset(struct bpf_idset *s)
3807 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3808 * Mark all registers with these IDs as precise.
3810 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3812 struct bpf_idset *precise_ids = &env->idset_scratch;
3813 struct backtrack_state *bt = &env->bt;
3814 struct bpf_func_state *func;
3815 struct bpf_reg_state *reg;
3816 DECLARE_BITMAP(mask, 64);
3819 idset_reset(precise_ids);
3821 for (fr = bt->frame; fr >= 0; fr--) {
3822 func = st->frame[fr];
3824 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3825 for_each_set_bit(i, mask, 32) {
3826 reg = &func->regs[i];
3827 if (!reg->id || reg->type != SCALAR_VALUE)
3829 if (idset_push(precise_ids, reg->id))
3833 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3834 for_each_set_bit(i, mask, 64) {
3835 if (i >= func->allocated_stack / BPF_REG_SIZE)
3837 if (!is_spilled_scalar_reg(&func->stack[i]))
3839 reg = &func->stack[i].spilled_ptr;
3842 if (idset_push(precise_ids, reg->id))
3847 for (fr = 0; fr <= st->curframe; ++fr) {
3848 func = st->frame[fr];
3850 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
3851 reg = &func->regs[i];
3854 if (!idset_contains(precise_ids, reg->id))
3856 bt_set_frame_reg(bt, fr, i);
3858 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
3859 if (!is_spilled_scalar_reg(&func->stack[i]))
3861 reg = &func->stack[i].spilled_ptr;
3864 if (!idset_contains(precise_ids, reg->id))
3866 bt_set_frame_slot(bt, fr, i);
3874 * __mark_chain_precision() backtracks BPF program instruction sequence and
3875 * chain of verifier states making sure that register *regno* (if regno >= 0)
3876 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3877 * SCALARS, as well as any other registers and slots that contribute to
3878 * a tracked state of given registers/stack slots, depending on specific BPF
3879 * assembly instructions (see backtrack_insns() for exact instruction handling
3880 * logic). This backtracking relies on recorded jmp_history and is able to
3881 * traverse entire chain of parent states. This process ends only when all the
3882 * necessary registers/slots and their transitive dependencies are marked as
3885 * One important and subtle aspect is that precise marks *do not matter* in
3886 * the currently verified state (current state). It is important to understand
3887 * why this is the case.
3889 * First, note that current state is the state that is not yet "checkpointed",
3890 * i.e., it is not yet put into env->explored_states, and it has no children
3891 * states as well. It's ephemeral, and can end up either a) being discarded if
3892 * compatible explored state is found at some point or BPF_EXIT instruction is
3893 * reached or b) checkpointed and put into env->explored_states, branching out
3894 * into one or more children states.
3896 * In the former case, precise markings in current state are completely
3897 * ignored by state comparison code (see regsafe() for details). Only
3898 * checkpointed ("old") state precise markings are important, and if old
3899 * state's register/slot is precise, regsafe() assumes current state's
3900 * register/slot as precise and checks value ranges exactly and precisely. If
3901 * states turn out to be compatible, current state's necessary precise
3902 * markings and any required parent states' precise markings are enforced
3903 * after the fact with propagate_precision() logic, after the fact. But it's
3904 * important to realize that in this case, even after marking current state
3905 * registers/slots as precise, we immediately discard current state. So what
3906 * actually matters is any of the precise markings propagated into current
3907 * state's parent states, which are always checkpointed (due to b) case above).
3908 * As such, for scenario a) it doesn't matter if current state has precise
3909 * markings set or not.
3911 * Now, for the scenario b), checkpointing and forking into child(ren)
3912 * state(s). Note that before current state gets to checkpointing step, any
3913 * processed instruction always assumes precise SCALAR register/slot
3914 * knowledge: if precise value or range is useful to prune jump branch, BPF
3915 * verifier takes this opportunity enthusiastically. Similarly, when
3916 * register's value is used to calculate offset or memory address, exact
3917 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3918 * what we mentioned above about state comparison ignoring precise markings
3919 * during state comparison, BPF verifier ignores and also assumes precise
3920 * markings *at will* during instruction verification process. But as verifier
3921 * assumes precision, it also propagates any precision dependencies across
3922 * parent states, which are not yet finalized, so can be further restricted
3923 * based on new knowledge gained from restrictions enforced by their children
3924 * states. This is so that once those parent states are finalized, i.e., when
3925 * they have no more active children state, state comparison logic in
3926 * is_state_visited() would enforce strict and precise SCALAR ranges, if
3927 * required for correctness.
3929 * To build a bit more intuition, note also that once a state is checkpointed,
3930 * the path we took to get to that state is not important. This is crucial
3931 * property for state pruning. When state is checkpointed and finalized at
3932 * some instruction index, it can be correctly and safely used to "short
3933 * circuit" any *compatible* state that reaches exactly the same instruction
3934 * index. I.e., if we jumped to that instruction from a completely different
3935 * code path than original finalized state was derived from, it doesn't
3936 * matter, current state can be discarded because from that instruction
3937 * forward having a compatible state will ensure we will safely reach the
3938 * exit. States describe preconditions for further exploration, but completely
3939 * forget the history of how we got here.
3941 * This also means that even if we needed precise SCALAR range to get to
3942 * finalized state, but from that point forward *that same* SCALAR register is
3943 * never used in a precise context (i.e., it's precise value is not needed for
3944 * correctness), it's correct and safe to mark such register as "imprecise"
3945 * (i.e., precise marking set to false). This is what we rely on when we do
3946 * not set precise marking in current state. If no child state requires
3947 * precision for any given SCALAR register, it's safe to dictate that it can
3948 * be imprecise. If any child state does require this register to be precise,
3949 * we'll mark it precise later retroactively during precise markings
3950 * propagation from child state to parent states.
3952 * Skipping precise marking setting in current state is a mild version of
3953 * relying on the above observation. But we can utilize this property even
3954 * more aggressively by proactively forgetting any precise marking in the
3955 * current state (which we inherited from the parent state), right before we
3956 * checkpoint it and branch off into new child state. This is done by
3957 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3958 * finalized states which help in short circuiting more future states.
3960 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
3962 struct backtrack_state *bt = &env->bt;
3963 struct bpf_verifier_state *st = env->cur_state;
3964 int first_idx = st->first_insn_idx;
3965 int last_idx = env->insn_idx;
3966 int subseq_idx = -1;
3967 struct bpf_func_state *func;
3968 struct bpf_reg_state *reg;
3969 bool skip_first = true;
3972 if (!env->bpf_capable)
3975 /* set frame number from which we are starting to backtrack */
3976 bt_init(bt, env->cur_state->curframe);
3978 /* Do sanity checks against current state of register and/or stack
3979 * slot, but don't set precise flag in current state, as precision
3980 * tracking in the current state is unnecessary.
3982 func = st->frame[bt->frame];
3984 reg = &func->regs[regno];
3985 if (reg->type != SCALAR_VALUE) {
3986 WARN_ONCE(1, "backtracing misuse");
3989 bt_set_reg(bt, regno);
3996 DECLARE_BITMAP(mask, 64);
3997 u32 history = st->jmp_history_cnt;
3999 if (env->log.level & BPF_LOG_LEVEL2) {
4000 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4001 bt->frame, last_idx, first_idx, subseq_idx);
4004 /* If some register with scalar ID is marked as precise,
4005 * make sure that all registers sharing this ID are also precise.
4006 * This is needed to estimate effect of find_equal_scalars().
4007 * Do this at the last instruction of each state,
4008 * bpf_reg_state::id fields are valid for these instructions.
4010 * Allows to track precision in situation like below:
4012 * r2 = unknown value
4016 * r1 = r2 // r1 and r2 now share the same ID
4018 * --- state #1 {r1.id = A, r2.id = A} ---
4020 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4022 * --- state #2 {r1.id = A, r2.id = A} ---
4024 * r3 += r1 // need to mark both r1 and r2
4026 if (mark_precise_scalar_ids(env, st))
4030 /* we are at the entry into subprog, which
4031 * is expected for global funcs, but only if
4032 * requested precise registers are R1-R5
4033 * (which are global func's input arguments)
4035 if (st->curframe == 0 &&
4036 st->frame[0]->subprogno > 0 &&
4037 st->frame[0]->callsite == BPF_MAIN_FUNC &&
4038 bt_stack_mask(bt) == 0 &&
4039 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4040 bitmap_from_u64(mask, bt_reg_mask(bt));
4041 for_each_set_bit(i, mask, 32) {
4042 reg = &st->frame[0]->regs[i];
4043 if (reg->type != SCALAR_VALUE) {
4044 bt_clear_reg(bt, i);
4047 reg->precise = true;
4052 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4053 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4054 WARN_ONCE(1, "verifier backtracking bug");
4058 for (i = last_idx;;) {
4063 err = backtrack_insn(env, i, subseq_idx, bt);
4065 if (err == -ENOTSUPP) {
4066 mark_all_scalars_precise(env, env->cur_state);
4073 /* Found assignment(s) into tracked register in this state.
4074 * Since this state is already marked, just return.
4075 * Nothing to be tracked further in the parent state.
4081 i = get_prev_insn_idx(st, i, &history);
4082 if (i >= env->prog->len) {
4083 /* This can happen if backtracking reached insn 0
4084 * and there are still reg_mask or stack_mask
4086 * It means the backtracking missed the spot where
4087 * particular register was initialized with a constant.
4089 verbose(env, "BUG backtracking idx %d\n", i);
4090 WARN_ONCE(1, "verifier backtracking bug");
4098 for (fr = bt->frame; fr >= 0; fr--) {
4099 func = st->frame[fr];
4100 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4101 for_each_set_bit(i, mask, 32) {
4102 reg = &func->regs[i];
4103 if (reg->type != SCALAR_VALUE) {
4104 bt_clear_frame_reg(bt, fr, i);
4108 bt_clear_frame_reg(bt, fr, i);
4110 reg->precise = true;
4113 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4114 for_each_set_bit(i, mask, 64) {
4115 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4116 /* the sequence of instructions:
4118 * 3: (7b) *(u64 *)(r3 -8) = r0
4119 * 4: (79) r4 = *(u64 *)(r10 -8)
4120 * doesn't contain jmps. It's backtracked
4121 * as a single block.
4122 * During backtracking insn 3 is not recognized as
4123 * stack access, so at the end of backtracking
4124 * stack slot fp-8 is still marked in stack_mask.
4125 * However the parent state may not have accessed
4126 * fp-8 and it's "unallocated" stack space.
4127 * In such case fallback to conservative.
4129 mark_all_scalars_precise(env, env->cur_state);
4134 if (!is_spilled_scalar_reg(&func->stack[i])) {
4135 bt_clear_frame_slot(bt, fr, i);
4138 reg = &func->stack[i].spilled_ptr;
4140 bt_clear_frame_slot(bt, fr, i);
4142 reg->precise = true;
4144 if (env->log.level & BPF_LOG_LEVEL2) {
4145 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4146 bt_frame_reg_mask(bt, fr));
4147 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4148 fr, env->tmp_str_buf);
4149 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4150 bt_frame_stack_mask(bt, fr));
4151 verbose(env, "stack=%s: ", env->tmp_str_buf);
4152 print_verifier_state(env, func, true);
4159 subseq_idx = first_idx;
4160 last_idx = st->last_insn_idx;
4161 first_idx = st->first_insn_idx;
4164 /* if we still have requested precise regs or slots, we missed
4165 * something (e.g., stack access through non-r10 register), so
4166 * fallback to marking all precise
4168 if (!bt_empty(bt)) {
4169 mark_all_scalars_precise(env, env->cur_state);
4176 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4178 return __mark_chain_precision(env, regno);
4181 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4182 * desired reg and stack masks across all relevant frames
4184 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4186 return __mark_chain_precision(env, -1);
4189 static bool is_spillable_regtype(enum bpf_reg_type type)
4191 switch (base_type(type)) {
4192 case PTR_TO_MAP_VALUE:
4196 case PTR_TO_PACKET_META:
4197 case PTR_TO_PACKET_END:
4198 case PTR_TO_FLOW_KEYS:
4199 case CONST_PTR_TO_MAP:
4201 case PTR_TO_SOCK_COMMON:
4202 case PTR_TO_TCP_SOCK:
4203 case PTR_TO_XDP_SOCK:
4208 case PTR_TO_MAP_KEY:
4215 /* Does this register contain a constant zero? */
4216 static bool register_is_null(struct bpf_reg_state *reg)
4218 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4221 static bool register_is_const(struct bpf_reg_state *reg)
4223 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4226 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4228 return tnum_is_unknown(reg->var_off) &&
4229 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4230 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4231 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4232 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4235 static bool register_is_bounded(struct bpf_reg_state *reg)
4237 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4240 static bool __is_pointer_value(bool allow_ptr_leaks,
4241 const struct bpf_reg_state *reg)
4243 if (allow_ptr_leaks)
4246 return reg->type != SCALAR_VALUE;
4249 /* Copy src state preserving dst->parent and dst->live fields */
4250 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4252 struct bpf_reg_state *parent = dst->parent;
4253 enum bpf_reg_liveness live = dst->live;
4256 dst->parent = parent;
4260 static void save_register_state(struct bpf_func_state *state,
4261 int spi, struct bpf_reg_state *reg,
4266 copy_register_state(&state->stack[spi].spilled_ptr, reg);
4267 if (size == BPF_REG_SIZE)
4268 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4270 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4271 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4273 /* size < 8 bytes spill */
4275 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4278 static bool is_bpf_st_mem(struct bpf_insn *insn)
4280 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4283 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4284 * stack boundary and alignment are checked in check_mem_access()
4286 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4287 /* stack frame we're writing to */
4288 struct bpf_func_state *state,
4289 int off, int size, int value_regno,
4292 struct bpf_func_state *cur; /* state of the current function */
4293 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4294 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4295 struct bpf_reg_state *reg = NULL;
4296 u32 dst_reg = insn->dst_reg;
4298 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4301 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4302 * so it's aligned access and [off, off + size) are within stack limits
4304 if (!env->allow_ptr_leaks &&
4305 state->stack[spi].slot_type[0] == STACK_SPILL &&
4306 size != BPF_REG_SIZE) {
4307 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4311 cur = env->cur_state->frame[env->cur_state->curframe];
4312 if (value_regno >= 0)
4313 reg = &cur->regs[value_regno];
4314 if (!env->bypass_spec_v4) {
4315 bool sanitize = reg && is_spillable_regtype(reg->type);
4317 for (i = 0; i < size; i++) {
4318 u8 type = state->stack[spi].slot_type[i];
4320 if (type != STACK_MISC && type != STACK_ZERO) {
4327 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4330 err = destroy_if_dynptr_stack_slot(env, state, spi);
4334 mark_stack_slot_scratched(env, spi);
4335 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4336 !register_is_null(reg) && env->bpf_capable) {
4337 if (dst_reg != BPF_REG_FP) {
4338 /* The backtracking logic can only recognize explicit
4339 * stack slot address like [fp - 8]. Other spill of
4340 * scalar via different register has to be conservative.
4341 * Backtrack from here and mark all registers as precise
4342 * that contributed into 'reg' being a constant.
4344 err = mark_chain_precision(env, value_regno);
4348 save_register_state(state, spi, reg, size);
4349 /* Break the relation on a narrowing spill. */
4350 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4351 state->stack[spi].spilled_ptr.id = 0;
4352 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4353 insn->imm != 0 && env->bpf_capable) {
4354 struct bpf_reg_state fake_reg = {};
4356 __mark_reg_known(&fake_reg, (u32)insn->imm);
4357 fake_reg.type = SCALAR_VALUE;
4358 save_register_state(state, spi, &fake_reg, size);
4359 } else if (reg && is_spillable_regtype(reg->type)) {
4360 /* register containing pointer is being spilled into stack */
4361 if (size != BPF_REG_SIZE) {
4362 verbose_linfo(env, insn_idx, "; ");
4363 verbose(env, "invalid size of register spill\n");
4366 if (state != cur && reg->type == PTR_TO_STACK) {
4367 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4370 save_register_state(state, spi, reg, size);
4372 u8 type = STACK_MISC;
4374 /* regular write of data into stack destroys any spilled ptr */
4375 state->stack[spi].spilled_ptr.type = NOT_INIT;
4376 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4377 if (is_stack_slot_special(&state->stack[spi]))
4378 for (i = 0; i < BPF_REG_SIZE; i++)
4379 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4381 /* only mark the slot as written if all 8 bytes were written
4382 * otherwise read propagation may incorrectly stop too soon
4383 * when stack slots are partially written.
4384 * This heuristic means that read propagation will be
4385 * conservative, since it will add reg_live_read marks
4386 * to stack slots all the way to first state when programs
4387 * writes+reads less than 8 bytes
4389 if (size == BPF_REG_SIZE)
4390 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4392 /* when we zero initialize stack slots mark them as such */
4393 if ((reg && register_is_null(reg)) ||
4394 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4395 /* backtracking doesn't work for STACK_ZERO yet. */
4396 err = mark_chain_precision(env, value_regno);
4402 /* Mark slots affected by this stack write. */
4403 for (i = 0; i < size; i++)
4404 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4410 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4411 * known to contain a variable offset.
4412 * This function checks whether the write is permitted and conservatively
4413 * tracks the effects of the write, considering that each stack slot in the
4414 * dynamic range is potentially written to.
4416 * 'off' includes 'regno->off'.
4417 * 'value_regno' can be -1, meaning that an unknown value is being written to
4420 * Spilled pointers in range are not marked as written because we don't know
4421 * what's going to be actually written. This means that read propagation for
4422 * future reads cannot be terminated by this write.
4424 * For privileged programs, uninitialized stack slots are considered
4425 * initialized by this write (even though we don't know exactly what offsets
4426 * are going to be written to). The idea is that we don't want the verifier to
4427 * reject future reads that access slots written to through variable offsets.
4429 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4430 /* func where register points to */
4431 struct bpf_func_state *state,
4432 int ptr_regno, int off, int size,
4433 int value_regno, int insn_idx)
4435 struct bpf_func_state *cur; /* state of the current function */
4436 int min_off, max_off;
4438 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4439 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4440 bool writing_zero = false;
4441 /* set if the fact that we're writing a zero is used to let any
4442 * stack slots remain STACK_ZERO
4444 bool zero_used = false;
4446 cur = env->cur_state->frame[env->cur_state->curframe];
4447 ptr_reg = &cur->regs[ptr_regno];
4448 min_off = ptr_reg->smin_value + off;
4449 max_off = ptr_reg->smax_value + off + size;
4450 if (value_regno >= 0)
4451 value_reg = &cur->regs[value_regno];
4452 if ((value_reg && register_is_null(value_reg)) ||
4453 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4454 writing_zero = true;
4456 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4460 for (i = min_off; i < max_off; i++) {
4464 err = destroy_if_dynptr_stack_slot(env, state, spi);
4469 /* Variable offset writes destroy any spilled pointers in range. */
4470 for (i = min_off; i < max_off; i++) {
4471 u8 new_type, *stype;
4475 spi = slot / BPF_REG_SIZE;
4476 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4477 mark_stack_slot_scratched(env, spi);
4479 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4480 /* Reject the write if range we may write to has not
4481 * been initialized beforehand. If we didn't reject
4482 * here, the ptr status would be erased below (even
4483 * though not all slots are actually overwritten),
4484 * possibly opening the door to leaks.
4486 * We do however catch STACK_INVALID case below, and
4487 * only allow reading possibly uninitialized memory
4488 * later for CAP_PERFMON, as the write may not happen to
4491 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4496 /* Erase all spilled pointers. */
4497 state->stack[spi].spilled_ptr.type = NOT_INIT;
4499 /* Update the slot type. */
4500 new_type = STACK_MISC;
4501 if (writing_zero && *stype == STACK_ZERO) {
4502 new_type = STACK_ZERO;
4505 /* If the slot is STACK_INVALID, we check whether it's OK to
4506 * pretend that it will be initialized by this write. The slot
4507 * might not actually be written to, and so if we mark it as
4508 * initialized future reads might leak uninitialized memory.
4509 * For privileged programs, we will accept such reads to slots
4510 * that may or may not be written because, if we're reject
4511 * them, the error would be too confusing.
4513 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4514 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4521 /* backtracking doesn't work for STACK_ZERO yet. */
4522 err = mark_chain_precision(env, value_regno);
4529 /* When register 'dst_regno' is assigned some values from stack[min_off,
4530 * max_off), we set the register's type according to the types of the
4531 * respective stack slots. If all the stack values are known to be zeros, then
4532 * so is the destination reg. Otherwise, the register is considered to be
4533 * SCALAR. This function does not deal with register filling; the caller must
4534 * ensure that all spilled registers in the stack range have been marked as
4537 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4538 /* func where src register points to */
4539 struct bpf_func_state *ptr_state,
4540 int min_off, int max_off, int dst_regno)
4542 struct bpf_verifier_state *vstate = env->cur_state;
4543 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4548 for (i = min_off; i < max_off; i++) {
4550 spi = slot / BPF_REG_SIZE;
4551 mark_stack_slot_scratched(env, spi);
4552 stype = ptr_state->stack[spi].slot_type;
4553 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4557 if (zeros == max_off - min_off) {
4558 /* any access_size read into register is zero extended,
4559 * so the whole register == const_zero
4561 __mark_reg_const_zero(&state->regs[dst_regno]);
4562 /* backtracking doesn't support STACK_ZERO yet,
4563 * so mark it precise here, so that later
4564 * backtracking can stop here.
4565 * Backtracking may not need this if this register
4566 * doesn't participate in pointer adjustment.
4567 * Forward propagation of precise flag is not
4568 * necessary either. This mark is only to stop
4569 * backtracking. Any register that contributed
4570 * to const 0 was marked precise before spill.
4572 state->regs[dst_regno].precise = true;
4574 /* have read misc data from the stack */
4575 mark_reg_unknown(env, state->regs, dst_regno);
4577 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4580 /* Read the stack at 'off' and put the results into the register indicated by
4581 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4584 * 'dst_regno' can be -1, meaning that the read value is not going to a
4587 * The access is assumed to be within the current stack bounds.
4589 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4590 /* func where src register points to */
4591 struct bpf_func_state *reg_state,
4592 int off, int size, int dst_regno)
4594 struct bpf_verifier_state *vstate = env->cur_state;
4595 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4596 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4597 struct bpf_reg_state *reg;
4600 stype = reg_state->stack[spi].slot_type;
4601 reg = ®_state->stack[spi].spilled_ptr;
4603 mark_stack_slot_scratched(env, spi);
4605 if (is_spilled_reg(®_state->stack[spi])) {
4608 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4611 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4612 if (reg->type != SCALAR_VALUE) {
4613 verbose_linfo(env, env->insn_idx, "; ");
4614 verbose(env, "invalid size of register fill\n");
4618 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4622 if (!(off % BPF_REG_SIZE) && size == spill_size) {
4623 /* The earlier check_reg_arg() has decided the
4624 * subreg_def for this insn. Save it first.
4626 s32 subreg_def = state->regs[dst_regno].subreg_def;
4628 copy_register_state(&state->regs[dst_regno], reg);
4629 state->regs[dst_regno].subreg_def = subreg_def;
4631 for (i = 0; i < size; i++) {
4632 type = stype[(slot - i) % BPF_REG_SIZE];
4633 if (type == STACK_SPILL)
4635 if (type == STACK_MISC)
4637 if (type == STACK_INVALID && env->allow_uninit_stack)
4639 verbose(env, "invalid read from stack off %d+%d size %d\n",
4643 mark_reg_unknown(env, state->regs, dst_regno);
4645 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4649 if (dst_regno >= 0) {
4650 /* restore register state from stack */
4651 copy_register_state(&state->regs[dst_regno], reg);
4652 /* mark reg as written since spilled pointer state likely
4653 * has its liveness marks cleared by is_state_visited()
4654 * which resets stack/reg liveness for state transitions
4656 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4657 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4658 /* If dst_regno==-1, the caller is asking us whether
4659 * it is acceptable to use this value as a SCALAR_VALUE
4661 * We must not allow unprivileged callers to do that
4662 * with spilled pointers.
4664 verbose(env, "leaking pointer from stack off %d\n",
4668 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4670 for (i = 0; i < size; i++) {
4671 type = stype[(slot - i) % BPF_REG_SIZE];
4672 if (type == STACK_MISC)
4674 if (type == STACK_ZERO)
4676 if (type == STACK_INVALID && env->allow_uninit_stack)
4678 verbose(env, "invalid read from stack off %d+%d size %d\n",
4682 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4684 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4689 enum bpf_access_src {
4690 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
4691 ACCESS_HELPER = 2, /* the access is performed by a helper */
4694 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4695 int regno, int off, int access_size,
4696 bool zero_size_allowed,
4697 enum bpf_access_src type,
4698 struct bpf_call_arg_meta *meta);
4700 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4702 return cur_regs(env) + regno;
4705 /* Read the stack at 'ptr_regno + off' and put the result into the register
4707 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4708 * but not its variable offset.
4709 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4711 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4712 * filling registers (i.e. reads of spilled register cannot be detected when
4713 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4714 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4715 * offset; for a fixed offset check_stack_read_fixed_off should be used
4718 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4719 int ptr_regno, int off, int size, int dst_regno)
4721 /* The state of the source register. */
4722 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4723 struct bpf_func_state *ptr_state = func(env, reg);
4725 int min_off, max_off;
4727 /* Note that we pass a NULL meta, so raw access will not be permitted.
4729 err = check_stack_range_initialized(env, ptr_regno, off, size,
4730 false, ACCESS_DIRECT, NULL);
4734 min_off = reg->smin_value + off;
4735 max_off = reg->smax_value + off;
4736 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4740 /* check_stack_read dispatches to check_stack_read_fixed_off or
4741 * check_stack_read_var_off.
4743 * The caller must ensure that the offset falls within the allocated stack
4746 * 'dst_regno' is a register which will receive the value from the stack. It
4747 * can be -1, meaning that the read value is not going to a register.
4749 static int check_stack_read(struct bpf_verifier_env *env,
4750 int ptr_regno, int off, int size,
4753 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4754 struct bpf_func_state *state = func(env, reg);
4756 /* Some accesses are only permitted with a static offset. */
4757 bool var_off = !tnum_is_const(reg->var_off);
4759 /* The offset is required to be static when reads don't go to a
4760 * register, in order to not leak pointers (see
4761 * check_stack_read_fixed_off).
4763 if (dst_regno < 0 && var_off) {
4766 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4767 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4771 /* Variable offset is prohibited for unprivileged mode for simplicity
4772 * since it requires corresponding support in Spectre masking for stack
4773 * ALU. See also retrieve_ptr_limit(). The check in
4774 * check_stack_access_for_ptr_arithmetic() called by
4775 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4776 * with variable offsets, therefore no check is required here. Further,
4777 * just checking it here would be insufficient as speculative stack
4778 * writes could still lead to unsafe speculative behaviour.
4781 off += reg->var_off.value;
4782 err = check_stack_read_fixed_off(env, state, off, size,
4785 /* Variable offset stack reads need more conservative handling
4786 * than fixed offset ones. Note that dst_regno >= 0 on this
4789 err = check_stack_read_var_off(env, ptr_regno, off, size,
4796 /* check_stack_write dispatches to check_stack_write_fixed_off or
4797 * check_stack_write_var_off.
4799 * 'ptr_regno' is the register used as a pointer into the stack.
4800 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4801 * 'value_regno' is the register whose value we're writing to the stack. It can
4802 * be -1, meaning that we're not writing from a register.
4804 * The caller must ensure that the offset falls within the maximum stack size.
4806 static int check_stack_write(struct bpf_verifier_env *env,
4807 int ptr_regno, int off, int size,
4808 int value_regno, int insn_idx)
4810 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4811 struct bpf_func_state *state = func(env, reg);
4814 if (tnum_is_const(reg->var_off)) {
4815 off += reg->var_off.value;
4816 err = check_stack_write_fixed_off(env, state, off, size,
4817 value_regno, insn_idx);
4819 /* Variable offset stack reads need more conservative handling
4820 * than fixed offset ones.
4822 err = check_stack_write_var_off(env, state,
4823 ptr_regno, off, size,
4824 value_regno, insn_idx);
4829 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4830 int off, int size, enum bpf_access_type type)
4832 struct bpf_reg_state *regs = cur_regs(env);
4833 struct bpf_map *map = regs[regno].map_ptr;
4834 u32 cap = bpf_map_flags_to_cap(map);
4836 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4837 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4838 map->value_size, off, size);
4842 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4843 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4844 map->value_size, off, size);
4851 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4852 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4853 int off, int size, u32 mem_size,
4854 bool zero_size_allowed)
4856 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4857 struct bpf_reg_state *reg;
4859 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4862 reg = &cur_regs(env)[regno];
4863 switch (reg->type) {
4864 case PTR_TO_MAP_KEY:
4865 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4866 mem_size, off, size);
4868 case PTR_TO_MAP_VALUE:
4869 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4870 mem_size, off, size);
4873 case PTR_TO_PACKET_META:
4874 case PTR_TO_PACKET_END:
4875 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4876 off, size, regno, reg->id, off, mem_size);
4880 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4881 mem_size, off, size);
4887 /* check read/write into a memory region with possible variable offset */
4888 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4889 int off, int size, u32 mem_size,
4890 bool zero_size_allowed)
4892 struct bpf_verifier_state *vstate = env->cur_state;
4893 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4894 struct bpf_reg_state *reg = &state->regs[regno];
4897 /* We may have adjusted the register pointing to memory region, so we
4898 * need to try adding each of min_value and max_value to off
4899 * to make sure our theoretical access will be safe.
4901 * The minimum value is only important with signed
4902 * comparisons where we can't assume the floor of a
4903 * value is 0. If we are using signed variables for our
4904 * index'es we need to make sure that whatever we use
4905 * will have a set floor within our range.
4907 if (reg->smin_value < 0 &&
4908 (reg->smin_value == S64_MIN ||
4909 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4910 reg->smin_value + off < 0)) {
4911 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4915 err = __check_mem_access(env, regno, reg->smin_value + off, size,
4916 mem_size, zero_size_allowed);
4918 verbose(env, "R%d min value is outside of the allowed memory range\n",
4923 /* If we haven't set a max value then we need to bail since we can't be
4924 * sure we won't do bad things.
4925 * If reg->umax_value + off could overflow, treat that as unbounded too.
4927 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4928 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4932 err = __check_mem_access(env, regno, reg->umax_value + off, size,
4933 mem_size, zero_size_allowed);
4935 verbose(env, "R%d max value is outside of the allowed memory range\n",
4943 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4944 const struct bpf_reg_state *reg, int regno,
4947 /* Access to this pointer-typed register or passing it to a helper
4948 * is only allowed in its original, unmodified form.
4952 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4953 reg_type_str(env, reg->type), regno, reg->off);
4957 if (!fixed_off_ok && reg->off) {
4958 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4959 reg_type_str(env, reg->type), regno, reg->off);
4963 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4966 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4967 verbose(env, "variable %s access var_off=%s disallowed\n",
4968 reg_type_str(env, reg->type), tn_buf);
4975 int check_ptr_off_reg(struct bpf_verifier_env *env,
4976 const struct bpf_reg_state *reg, int regno)
4978 return __check_ptr_off_reg(env, reg, regno, false);
4981 static int map_kptr_match_type(struct bpf_verifier_env *env,
4982 struct btf_field *kptr_field,
4983 struct bpf_reg_state *reg, u32 regno)
4985 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4986 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4987 const char *reg_name = "";
4989 /* Only unreferenced case accepts untrusted pointers */
4990 if (kptr_field->type == BPF_KPTR_UNREF)
4991 perm_flags |= PTR_UNTRUSTED;
4993 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4996 if (!btf_is_kernel(reg->btf)) {
4997 verbose(env, "R%d must point to kernel BTF\n", regno);
5000 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5001 reg_name = btf_type_name(reg->btf, reg->btf_id);
5003 /* For ref_ptr case, release function check should ensure we get one
5004 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5005 * normal store of unreferenced kptr, we must ensure var_off is zero.
5006 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5007 * reg->off and reg->ref_obj_id are not needed here.
5009 if (__check_ptr_off_reg(env, reg, regno, true))
5012 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
5013 * we also need to take into account the reg->off.
5015 * We want to support cases like:
5023 * v = func(); // PTR_TO_BTF_ID
5024 * val->foo = v; // reg->off is zero, btf and btf_id match type
5025 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5026 * // first member type of struct after comparison fails
5027 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5030 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5031 * is zero. We must also ensure that btf_struct_ids_match does not walk
5032 * the struct to match type against first member of struct, i.e. reject
5033 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5034 * strict mode to true for type match.
5036 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5037 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5038 kptr_field->type == BPF_KPTR_REF))
5042 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5043 reg_type_str(env, reg->type), reg_name);
5044 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5045 if (kptr_field->type == BPF_KPTR_UNREF)
5046 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5053 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5054 * can dereference RCU protected pointers and result is PTR_TRUSTED.
5056 static bool in_rcu_cs(struct bpf_verifier_env *env)
5058 return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
5061 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5062 BTF_SET_START(rcu_protected_types)
5063 BTF_ID(struct, prog_test_ref_kfunc)
5064 BTF_ID(struct, cgroup)
5065 BTF_ID(struct, bpf_cpumask)
5066 BTF_ID(struct, task_struct)
5067 BTF_SET_END(rcu_protected_types)
5069 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5071 if (!btf_is_kernel(btf))
5073 return btf_id_set_contains(&rcu_protected_types, btf_id);
5076 static bool rcu_safe_kptr(const struct btf_field *field)
5078 const struct btf_field_kptr *kptr = &field->kptr;
5080 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5083 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5084 int value_regno, int insn_idx,
5085 struct btf_field *kptr_field)
5087 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5088 int class = BPF_CLASS(insn->code);
5089 struct bpf_reg_state *val_reg;
5091 /* Things we already checked for in check_map_access and caller:
5092 * - Reject cases where variable offset may touch kptr
5093 * - size of access (must be BPF_DW)
5094 * - tnum_is_const(reg->var_off)
5095 * - kptr_field->offset == off + reg->var_off.value
5097 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5098 if (BPF_MODE(insn->code) != BPF_MEM) {
5099 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5103 /* We only allow loading referenced kptr, since it will be marked as
5104 * untrusted, similar to unreferenced kptr.
5106 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5107 verbose(env, "store to referenced kptr disallowed\n");
5111 if (class == BPF_LDX) {
5112 val_reg = reg_state(env, value_regno);
5113 /* We can simply mark the value_regno receiving the pointer
5114 * value from map as PTR_TO_BTF_ID, with the correct type.
5116 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5117 kptr_field->kptr.btf_id,
5118 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5119 PTR_MAYBE_NULL | MEM_RCU :
5120 PTR_MAYBE_NULL | PTR_UNTRUSTED);
5121 /* For mark_ptr_or_null_reg */
5122 val_reg->id = ++env->id_gen;
5123 } else if (class == BPF_STX) {
5124 val_reg = reg_state(env, value_regno);
5125 if (!register_is_null(val_reg) &&
5126 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5128 } else if (class == BPF_ST) {
5130 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5131 kptr_field->offset);
5135 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5141 /* check read/write into a map element with possible variable offset */
5142 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5143 int off, int size, bool zero_size_allowed,
5144 enum bpf_access_src src)
5146 struct bpf_verifier_state *vstate = env->cur_state;
5147 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5148 struct bpf_reg_state *reg = &state->regs[regno];
5149 struct bpf_map *map = reg->map_ptr;
5150 struct btf_record *rec;
5153 err = check_mem_region_access(env, regno, off, size, map->value_size,
5158 if (IS_ERR_OR_NULL(map->record))
5161 for (i = 0; i < rec->cnt; i++) {
5162 struct btf_field *field = &rec->fields[i];
5163 u32 p = field->offset;
5165 /* If any part of a field can be touched by load/store, reject
5166 * this program. To check that [x1, x2) overlaps with [y1, y2),
5167 * it is sufficient to check x1 < y2 && y1 < x2.
5169 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5170 p < reg->umax_value + off + size) {
5171 switch (field->type) {
5172 case BPF_KPTR_UNREF:
5174 if (src != ACCESS_DIRECT) {
5175 verbose(env, "kptr cannot be accessed indirectly by helper\n");
5178 if (!tnum_is_const(reg->var_off)) {
5179 verbose(env, "kptr access cannot have variable offset\n");
5182 if (p != off + reg->var_off.value) {
5183 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5184 p, off + reg->var_off.value);
5187 if (size != bpf_size_to_bytes(BPF_DW)) {
5188 verbose(env, "kptr access size must be BPF_DW\n");
5193 verbose(env, "%s cannot be accessed directly by load/store\n",
5194 btf_field_type_name(field->type));
5202 #define MAX_PACKET_OFF 0xffff
5204 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5205 const struct bpf_call_arg_meta *meta,
5206 enum bpf_access_type t)
5208 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5210 switch (prog_type) {
5211 /* Program types only with direct read access go here! */
5212 case BPF_PROG_TYPE_LWT_IN:
5213 case BPF_PROG_TYPE_LWT_OUT:
5214 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5215 case BPF_PROG_TYPE_SK_REUSEPORT:
5216 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5217 case BPF_PROG_TYPE_CGROUP_SKB:
5222 /* Program types with direct read + write access go here! */
5223 case BPF_PROG_TYPE_SCHED_CLS:
5224 case BPF_PROG_TYPE_SCHED_ACT:
5225 case BPF_PROG_TYPE_XDP:
5226 case BPF_PROG_TYPE_LWT_XMIT:
5227 case BPF_PROG_TYPE_SK_SKB:
5228 case BPF_PROG_TYPE_SK_MSG:
5230 return meta->pkt_access;
5232 env->seen_direct_write = true;
5235 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5237 env->seen_direct_write = true;
5246 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5247 int size, bool zero_size_allowed)
5249 struct bpf_reg_state *regs = cur_regs(env);
5250 struct bpf_reg_state *reg = ®s[regno];
5253 /* We may have added a variable offset to the packet pointer; but any
5254 * reg->range we have comes after that. We are only checking the fixed
5258 /* We don't allow negative numbers, because we aren't tracking enough
5259 * detail to prove they're safe.
5261 if (reg->smin_value < 0) {
5262 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5267 err = reg->range < 0 ? -EINVAL :
5268 __check_mem_access(env, regno, off, size, reg->range,
5271 verbose(env, "R%d offset is outside of the packet\n", regno);
5275 /* __check_mem_access has made sure "off + size - 1" is within u16.
5276 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5277 * otherwise find_good_pkt_pointers would have refused to set range info
5278 * that __check_mem_access would have rejected this pkt access.
5279 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5281 env->prog->aux->max_pkt_offset =
5282 max_t(u32, env->prog->aux->max_pkt_offset,
5283 off + reg->umax_value + size - 1);
5288 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
5289 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5290 enum bpf_access_type t, enum bpf_reg_type *reg_type,
5291 struct btf **btf, u32 *btf_id)
5293 struct bpf_insn_access_aux info = {
5294 .reg_type = *reg_type,
5298 if (env->ops->is_valid_access &&
5299 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5300 /* A non zero info.ctx_field_size indicates that this field is a
5301 * candidate for later verifier transformation to load the whole
5302 * field and then apply a mask when accessed with a narrower
5303 * access than actual ctx access size. A zero info.ctx_field_size
5304 * will only allow for whole field access and rejects any other
5305 * type of narrower access.
5307 *reg_type = info.reg_type;
5309 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5311 *btf_id = info.btf_id;
5313 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5315 /* remember the offset of last byte accessed in ctx */
5316 if (env->prog->aux->max_ctx_offset < off + size)
5317 env->prog->aux->max_ctx_offset = off + size;
5321 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5325 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5328 if (size < 0 || off < 0 ||
5329 (u64)off + size > sizeof(struct bpf_flow_keys)) {
5330 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5337 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5338 u32 regno, int off, int size,
5339 enum bpf_access_type t)
5341 struct bpf_reg_state *regs = cur_regs(env);
5342 struct bpf_reg_state *reg = ®s[regno];
5343 struct bpf_insn_access_aux info = {};
5346 if (reg->smin_value < 0) {
5347 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5352 switch (reg->type) {
5353 case PTR_TO_SOCK_COMMON:
5354 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5357 valid = bpf_sock_is_valid_access(off, size, t, &info);
5359 case PTR_TO_TCP_SOCK:
5360 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5362 case PTR_TO_XDP_SOCK:
5363 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5371 env->insn_aux_data[insn_idx].ctx_field_size =
5372 info.ctx_field_size;
5376 verbose(env, "R%d invalid %s access off=%d size=%d\n",
5377 regno, reg_type_str(env, reg->type), off, size);
5382 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5384 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5387 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5389 const struct bpf_reg_state *reg = reg_state(env, regno);
5391 return reg->type == PTR_TO_CTX;
5394 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5396 const struct bpf_reg_state *reg = reg_state(env, regno);
5398 return type_is_sk_pointer(reg->type);
5401 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5403 const struct bpf_reg_state *reg = reg_state(env, regno);
5405 return type_is_pkt_pointer(reg->type);
5408 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5410 const struct bpf_reg_state *reg = reg_state(env, regno);
5412 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5413 return reg->type == PTR_TO_FLOW_KEYS;
5416 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5418 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5419 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5420 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5422 [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5425 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5427 /* A referenced register is always trusted. */
5428 if (reg->ref_obj_id)
5431 /* Types listed in the reg2btf_ids are always trusted */
5432 if (reg2btf_ids[base_type(reg->type)])
5435 /* If a register is not referenced, it is trusted if it has the
5436 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5437 * other type modifiers may be safe, but we elect to take an opt-in
5438 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5441 * Eventually, we should make PTR_TRUSTED the single source of truth
5442 * for whether a register is trusted.
5444 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5445 !bpf_type_has_unsafe_modifiers(reg->type);
5448 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5450 return reg->type & MEM_RCU;
5453 static void clear_trusted_flags(enum bpf_type_flag *flag)
5455 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5458 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5459 const struct bpf_reg_state *reg,
5460 int off, int size, bool strict)
5462 struct tnum reg_off;
5465 /* Byte size accesses are always allowed. */
5466 if (!strict || size == 1)
5469 /* For platforms that do not have a Kconfig enabling
5470 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5471 * NET_IP_ALIGN is universally set to '2'. And on platforms
5472 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5473 * to this code only in strict mode where we want to emulate
5474 * the NET_IP_ALIGN==2 checking. Therefore use an
5475 * unconditional IP align value of '2'.
5479 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5480 if (!tnum_is_aligned(reg_off, size)) {
5483 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5485 "misaligned packet access off %d+%s+%d+%d size %d\n",
5486 ip_align, tn_buf, reg->off, off, size);
5493 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5494 const struct bpf_reg_state *reg,
5495 const char *pointer_desc,
5496 int off, int size, bool strict)
5498 struct tnum reg_off;
5500 /* Byte size accesses are always allowed. */
5501 if (!strict || size == 1)
5504 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5505 if (!tnum_is_aligned(reg_off, size)) {
5508 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5509 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5510 pointer_desc, tn_buf, reg->off, off, size);
5517 static int check_ptr_alignment(struct bpf_verifier_env *env,
5518 const struct bpf_reg_state *reg, int off,
5519 int size, bool strict_alignment_once)
5521 bool strict = env->strict_alignment || strict_alignment_once;
5522 const char *pointer_desc = "";
5524 switch (reg->type) {
5526 case PTR_TO_PACKET_META:
5527 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5528 * right in front, treat it the very same way.
5530 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5531 case PTR_TO_FLOW_KEYS:
5532 pointer_desc = "flow keys ";
5534 case PTR_TO_MAP_KEY:
5535 pointer_desc = "key ";
5537 case PTR_TO_MAP_VALUE:
5538 pointer_desc = "value ";
5541 pointer_desc = "context ";
5544 pointer_desc = "stack ";
5545 /* The stack spill tracking logic in check_stack_write_fixed_off()
5546 * and check_stack_read_fixed_off() relies on stack accesses being
5552 pointer_desc = "sock ";
5554 case PTR_TO_SOCK_COMMON:
5555 pointer_desc = "sock_common ";
5557 case PTR_TO_TCP_SOCK:
5558 pointer_desc = "tcp_sock ";
5560 case PTR_TO_XDP_SOCK:
5561 pointer_desc = "xdp_sock ";
5566 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5570 static int update_stack_depth(struct bpf_verifier_env *env,
5571 const struct bpf_func_state *func,
5574 u16 stack = env->subprog_info[func->subprogno].stack_depth;
5579 /* update known max for given subprogram */
5580 env->subprog_info[func->subprogno].stack_depth = -off;
5584 /* starting from main bpf function walk all instructions of the function
5585 * and recursively walk all callees that given function can call.
5586 * Ignore jump and exit insns.
5587 * Since recursion is prevented by check_cfg() this algorithm
5588 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5590 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5592 struct bpf_subprog_info *subprog = env->subprog_info;
5593 struct bpf_insn *insn = env->prog->insnsi;
5594 int depth = 0, frame = 0, i, subprog_end;
5595 bool tail_call_reachable = false;
5596 int ret_insn[MAX_CALL_FRAMES];
5597 int ret_prog[MAX_CALL_FRAMES];
5600 i = subprog[idx].start;
5602 /* protect against potential stack overflow that might happen when
5603 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5604 * depth for such case down to 256 so that the worst case scenario
5605 * would result in 8k stack size (32 which is tailcall limit * 256 =
5608 * To get the idea what might happen, see an example:
5609 * func1 -> sub rsp, 128
5610 * subfunc1 -> sub rsp, 256
5611 * tailcall1 -> add rsp, 256
5612 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5613 * subfunc2 -> sub rsp, 64
5614 * subfunc22 -> sub rsp, 128
5615 * tailcall2 -> add rsp, 128
5616 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5618 * tailcall will unwind the current stack frame but it will not get rid
5619 * of caller's stack as shown on the example above.
5621 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5623 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5627 /* round up to 32-bytes, since this is granularity
5628 * of interpreter stack size
5630 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5631 if (depth > MAX_BPF_STACK) {
5632 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5637 subprog_end = subprog[idx + 1].start;
5638 for (; i < subprog_end; i++) {
5639 int next_insn, sidx;
5641 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5643 /* remember insn and function to return to */
5644 ret_insn[frame] = i + 1;
5645 ret_prog[frame] = idx;
5647 /* find the callee */
5648 next_insn = i + insn[i].imm + 1;
5649 sidx = find_subprog(env, next_insn);
5651 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5655 if (subprog[sidx].is_async_cb) {
5656 if (subprog[sidx].has_tail_call) {
5657 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5660 /* async callbacks don't increase bpf prog stack size unless called directly */
5661 if (!bpf_pseudo_call(insn + i))
5667 if (subprog[idx].has_tail_call)
5668 tail_call_reachable = true;
5671 if (frame >= MAX_CALL_FRAMES) {
5672 verbose(env, "the call stack of %d frames is too deep !\n",
5678 /* if tail call got detected across bpf2bpf calls then mark each of the
5679 * currently present subprog frames as tail call reachable subprogs;
5680 * this info will be utilized by JIT so that we will be preserving the
5681 * tail call counter throughout bpf2bpf calls combined with tailcalls
5683 if (tail_call_reachable)
5684 for (j = 0; j < frame; j++)
5685 subprog[ret_prog[j]].tail_call_reachable = true;
5686 if (subprog[0].tail_call_reachable)
5687 env->prog->aux->tail_call_reachable = true;
5689 /* end of for() loop means the last insn of the 'subprog'
5690 * was reached. Doesn't matter whether it was JA or EXIT
5694 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5696 i = ret_insn[frame];
5697 idx = ret_prog[frame];
5701 static int check_max_stack_depth(struct bpf_verifier_env *env)
5703 struct bpf_subprog_info *si = env->subprog_info;
5706 for (int i = 0; i < env->subprog_cnt; i++) {
5707 if (!i || si[i].is_async_cb) {
5708 ret = check_max_stack_depth_subprog(env, i);
5717 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5718 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5719 const struct bpf_insn *insn, int idx)
5721 int start = idx + insn->imm + 1, subprog;
5723 subprog = find_subprog(env, start);
5725 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5729 return env->subprog_info[subprog].stack_depth;
5733 static int __check_buffer_access(struct bpf_verifier_env *env,
5734 const char *buf_info,
5735 const struct bpf_reg_state *reg,
5736 int regno, int off, int size)
5740 "R%d invalid %s buffer access: off=%d, size=%d\n",
5741 regno, buf_info, off, size);
5744 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5747 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5749 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5750 regno, off, tn_buf);
5757 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5758 const struct bpf_reg_state *reg,
5759 int regno, int off, int size)
5763 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5767 if (off + size > env->prog->aux->max_tp_access)
5768 env->prog->aux->max_tp_access = off + size;
5773 static int check_buffer_access(struct bpf_verifier_env *env,
5774 const struct bpf_reg_state *reg,
5775 int regno, int off, int size,
5776 bool zero_size_allowed,
5779 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5782 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5786 if (off + size > *max_access)
5787 *max_access = off + size;
5792 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5793 static void zext_32_to_64(struct bpf_reg_state *reg)
5795 reg->var_off = tnum_subreg(reg->var_off);
5796 __reg_assign_32_into_64(reg);
5799 /* truncate register to smaller size (in bytes)
5800 * must be called with size < BPF_REG_SIZE
5802 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5806 /* clear high bits in bit representation */
5807 reg->var_off = tnum_cast(reg->var_off, size);
5809 /* fix arithmetic bounds */
5810 mask = ((u64)1 << (size * 8)) - 1;
5811 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5812 reg->umin_value &= mask;
5813 reg->umax_value &= mask;
5815 reg->umin_value = 0;
5816 reg->umax_value = mask;
5818 reg->smin_value = reg->umin_value;
5819 reg->smax_value = reg->umax_value;
5821 /* If size is smaller than 32bit register the 32bit register
5822 * values are also truncated so we push 64-bit bounds into
5823 * 32-bit bounds. Above were truncated < 32-bits already.
5827 __reg_combine_64_into_32(reg);
5830 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
5833 reg->smin_value = reg->s32_min_value = S8_MIN;
5834 reg->smax_value = reg->s32_max_value = S8_MAX;
5835 } else if (size == 2) {
5836 reg->smin_value = reg->s32_min_value = S16_MIN;
5837 reg->smax_value = reg->s32_max_value = S16_MAX;
5840 reg->smin_value = reg->s32_min_value = S32_MIN;
5841 reg->smax_value = reg->s32_max_value = S32_MAX;
5843 reg->umin_value = reg->u32_min_value = 0;
5844 reg->umax_value = U64_MAX;
5845 reg->u32_max_value = U32_MAX;
5846 reg->var_off = tnum_unknown;
5849 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
5851 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
5852 u64 top_smax_value, top_smin_value;
5853 u64 num_bits = size * 8;
5855 if (tnum_is_const(reg->var_off)) {
5856 u64_cval = reg->var_off.value;
5858 reg->var_off = tnum_const((s8)u64_cval);
5860 reg->var_off = tnum_const((s16)u64_cval);
5863 reg->var_off = tnum_const((s32)u64_cval);
5865 u64_cval = reg->var_off.value;
5866 reg->smax_value = reg->smin_value = u64_cval;
5867 reg->umax_value = reg->umin_value = u64_cval;
5868 reg->s32_max_value = reg->s32_min_value = u64_cval;
5869 reg->u32_max_value = reg->u32_min_value = u64_cval;
5873 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
5874 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
5876 if (top_smax_value != top_smin_value)
5879 /* find the s64_min and s64_min after sign extension */
5881 init_s64_max = (s8)reg->smax_value;
5882 init_s64_min = (s8)reg->smin_value;
5883 } else if (size == 2) {
5884 init_s64_max = (s16)reg->smax_value;
5885 init_s64_min = (s16)reg->smin_value;
5887 init_s64_max = (s32)reg->smax_value;
5888 init_s64_min = (s32)reg->smin_value;
5891 s64_max = max(init_s64_max, init_s64_min);
5892 s64_min = min(init_s64_max, init_s64_min);
5894 /* both of s64_max/s64_min positive or negative */
5895 if (s64_max >= 0 == s64_min >= 0) {
5896 reg->smin_value = reg->s32_min_value = s64_min;
5897 reg->smax_value = reg->s32_max_value = s64_max;
5898 reg->umin_value = reg->u32_min_value = s64_min;
5899 reg->umax_value = reg->u32_max_value = s64_max;
5900 reg->var_off = tnum_range(s64_min, s64_max);
5905 set_sext64_default_val(reg, size);
5908 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
5911 reg->s32_min_value = S8_MIN;
5912 reg->s32_max_value = S8_MAX;
5915 reg->s32_min_value = S16_MIN;
5916 reg->s32_max_value = S16_MAX;
5918 reg->u32_min_value = 0;
5919 reg->u32_max_value = U32_MAX;
5922 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
5924 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
5925 u32 top_smax_value, top_smin_value;
5926 u32 num_bits = size * 8;
5928 if (tnum_is_const(reg->var_off)) {
5929 u32_val = reg->var_off.value;
5931 reg->var_off = tnum_const((s8)u32_val);
5933 reg->var_off = tnum_const((s16)u32_val);
5935 u32_val = reg->var_off.value;
5936 reg->s32_min_value = reg->s32_max_value = u32_val;
5937 reg->u32_min_value = reg->u32_max_value = u32_val;
5941 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
5942 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
5944 if (top_smax_value != top_smin_value)
5947 /* find the s32_min and s32_min after sign extension */
5949 init_s32_max = (s8)reg->s32_max_value;
5950 init_s32_min = (s8)reg->s32_min_value;
5953 init_s32_max = (s16)reg->s32_max_value;
5954 init_s32_min = (s16)reg->s32_min_value;
5956 s32_max = max(init_s32_max, init_s32_min);
5957 s32_min = min(init_s32_max, init_s32_min);
5959 if (s32_min >= 0 == s32_max >= 0) {
5960 reg->s32_min_value = s32_min;
5961 reg->s32_max_value = s32_max;
5962 reg->u32_min_value = (u32)s32_min;
5963 reg->u32_max_value = (u32)s32_max;
5968 set_sext32_default_val(reg, size);
5971 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5973 /* A map is considered read-only if the following condition are true:
5975 * 1) BPF program side cannot change any of the map content. The
5976 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5977 * and was set at map creation time.
5978 * 2) The map value(s) have been initialized from user space by a
5979 * loader and then "frozen", such that no new map update/delete
5980 * operations from syscall side are possible for the rest of
5981 * the map's lifetime from that point onwards.
5982 * 3) Any parallel/pending map update/delete operations from syscall
5983 * side have been completed. Only after that point, it's safe to
5984 * assume that map value(s) are immutable.
5986 return (map->map_flags & BPF_F_RDONLY_PROG) &&
5987 READ_ONCE(map->frozen) &&
5988 !bpf_map_write_active(map);
5991 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
5998 err = map->ops->map_direct_value_addr(map, &addr, off);
6001 ptr = (void *)(long)addr + off;
6005 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6008 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6011 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6022 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
6023 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
6024 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
6027 * Allow list few fields as RCU trusted or full trusted.
6028 * This logic doesn't allow mix tagging and will be removed once GCC supports
6032 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6033 BTF_TYPE_SAFE_RCU(struct task_struct) {
6034 const cpumask_t *cpus_ptr;
6035 struct css_set __rcu *cgroups;
6036 struct task_struct __rcu *real_parent;
6037 struct task_struct *group_leader;
6040 BTF_TYPE_SAFE_RCU(struct cgroup) {
6041 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6042 struct kernfs_node *kn;
6045 BTF_TYPE_SAFE_RCU(struct css_set) {
6046 struct cgroup *dfl_cgrp;
6049 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6050 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6051 struct file __rcu *exe_file;
6054 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6055 * because bpf prog accessible sockets are SOCK_RCU_FREE.
6057 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6061 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6065 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6066 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6067 struct seq_file *seq;
6070 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6071 struct bpf_iter_meta *meta;
6072 struct task_struct *task;
6075 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6079 BTF_TYPE_SAFE_TRUSTED(struct file) {
6080 struct inode *f_inode;
6083 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6084 /* no negative dentry-s in places where bpf can see it */
6085 struct inode *d_inode;
6088 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6092 static bool type_is_rcu(struct bpf_verifier_env *env,
6093 struct bpf_reg_state *reg,
6094 const char *field_name, u32 btf_id)
6096 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6097 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6098 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6100 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6103 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6104 struct bpf_reg_state *reg,
6105 const char *field_name, u32 btf_id)
6107 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6108 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6109 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6111 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6114 static bool type_is_trusted(struct bpf_verifier_env *env,
6115 struct bpf_reg_state *reg,
6116 const char *field_name, u32 btf_id)
6118 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6119 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6120 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6121 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6122 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6123 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6125 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6128 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6129 struct bpf_reg_state *regs,
6130 int regno, int off, int size,
6131 enum bpf_access_type atype,
6134 struct bpf_reg_state *reg = regs + regno;
6135 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6136 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6137 const char *field_name = NULL;
6138 enum bpf_type_flag flag = 0;
6142 if (!env->allow_ptr_leaks) {
6144 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6148 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6150 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6156 "R%d is ptr_%s invalid negative access: off=%d\n",
6160 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6163 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6165 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6166 regno, tname, off, tn_buf);
6170 if (reg->type & MEM_USER) {
6172 "R%d is ptr_%s access user memory: off=%d\n",
6177 if (reg->type & MEM_PERCPU) {
6179 "R%d is ptr_%s access percpu memory: off=%d\n",
6184 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6185 if (!btf_is_kernel(reg->btf)) {
6186 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6189 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6191 /* Writes are permitted with default btf_struct_access for
6192 * program allocated objects (which always have ref_obj_id > 0),
6193 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6195 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6196 verbose(env, "only read is supported\n");
6200 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6202 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6206 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6212 if (ret != PTR_TO_BTF_ID) {
6215 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6216 /* If this is an untrusted pointer, all pointers formed by walking it
6217 * also inherit the untrusted flag.
6219 flag = PTR_UNTRUSTED;
6221 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6222 /* By default any pointer obtained from walking a trusted pointer is no
6223 * longer trusted, unless the field being accessed has explicitly been
6224 * marked as inheriting its parent's state of trust (either full or RCU).
6226 * 'cgroups' pointer is untrusted if task->cgroups dereference
6227 * happened in a sleepable program outside of bpf_rcu_read_lock()
6228 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6229 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6231 * A regular RCU-protected pointer with __rcu tag can also be deemed
6232 * trusted if we are in an RCU CS. Such pointer can be NULL.
6234 if (type_is_trusted(env, reg, field_name, btf_id)) {
6235 flag |= PTR_TRUSTED;
6236 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6237 if (type_is_rcu(env, reg, field_name, btf_id)) {
6238 /* ignore __rcu tag and mark it MEM_RCU */
6240 } else if (flag & MEM_RCU ||
6241 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6242 /* __rcu tagged pointers can be NULL */
6243 flag |= MEM_RCU | PTR_MAYBE_NULL;
6245 /* We always trust them */
6246 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6247 flag & PTR_UNTRUSTED)
6248 flag &= ~PTR_UNTRUSTED;
6249 } else if (flag & (MEM_PERCPU | MEM_USER)) {
6252 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6253 clear_trusted_flags(&flag);
6257 * If not in RCU CS or MEM_RCU pointer can be NULL then
6258 * aggressively mark as untrusted otherwise such
6259 * pointers will be plain PTR_TO_BTF_ID without flags
6260 * and will be allowed to be passed into helpers for
6263 flag = PTR_UNTRUSTED;
6266 /* Old compat. Deprecated */
6267 clear_trusted_flags(&flag);
6270 if (atype == BPF_READ && value_regno >= 0)
6271 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6276 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6277 struct bpf_reg_state *regs,
6278 int regno, int off, int size,
6279 enum bpf_access_type atype,
6282 struct bpf_reg_state *reg = regs + regno;
6283 struct bpf_map *map = reg->map_ptr;
6284 struct bpf_reg_state map_reg;
6285 enum bpf_type_flag flag = 0;
6286 const struct btf_type *t;
6292 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6296 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6297 verbose(env, "map_ptr access not supported for map type %d\n",
6302 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6303 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6305 if (!env->allow_ptr_leaks) {
6307 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6313 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6318 if (atype != BPF_READ) {
6319 verbose(env, "only read from %s is supported\n", tname);
6323 /* Simulate access to a PTR_TO_BTF_ID */
6324 memset(&map_reg, 0, sizeof(map_reg));
6325 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6326 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6330 if (value_regno >= 0)
6331 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6336 /* Check that the stack access at the given offset is within bounds. The
6337 * maximum valid offset is -1.
6339 * The minimum valid offset is -MAX_BPF_STACK for writes, and
6340 * -state->allocated_stack for reads.
6342 static int check_stack_slot_within_bounds(int off,
6343 struct bpf_func_state *state,
6344 enum bpf_access_type t)
6349 min_valid_off = -MAX_BPF_STACK;
6351 min_valid_off = -state->allocated_stack;
6353 if (off < min_valid_off || off > -1)
6358 /* Check that the stack access at 'regno + off' falls within the maximum stack
6361 * 'off' includes `regno->offset`, but not its dynamic part (if any).
6363 static int check_stack_access_within_bounds(
6364 struct bpf_verifier_env *env,
6365 int regno, int off, int access_size,
6366 enum bpf_access_src src, enum bpf_access_type type)
6368 struct bpf_reg_state *regs = cur_regs(env);
6369 struct bpf_reg_state *reg = regs + regno;
6370 struct bpf_func_state *state = func(env, reg);
6371 int min_off, max_off;
6375 if (src == ACCESS_HELPER)
6376 /* We don't know if helpers are reading or writing (or both). */
6377 err_extra = " indirect access to";
6378 else if (type == BPF_READ)
6379 err_extra = " read from";
6381 err_extra = " write to";
6383 if (tnum_is_const(reg->var_off)) {
6384 min_off = reg->var_off.value + off;
6385 if (access_size > 0)
6386 max_off = min_off + access_size - 1;
6390 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6391 reg->smin_value <= -BPF_MAX_VAR_OFF) {
6392 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6396 min_off = reg->smin_value + off;
6397 if (access_size > 0)
6398 max_off = reg->smax_value + off + access_size - 1;
6403 err = check_stack_slot_within_bounds(min_off, state, type);
6405 err = check_stack_slot_within_bounds(max_off, state, type);
6408 if (tnum_is_const(reg->var_off)) {
6409 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6410 err_extra, regno, off, access_size);
6414 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6415 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6416 err_extra, regno, tn_buf, access_size);
6422 /* check whether memory at (regno + off) is accessible for t = (read | write)
6423 * if t==write, value_regno is a register which value is stored into memory
6424 * if t==read, value_regno is a register which will receive the value from memory
6425 * if t==write && value_regno==-1, some unknown value is stored into memory
6426 * if t==read && value_regno==-1, don't care what we read from memory
6428 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6429 int off, int bpf_size, enum bpf_access_type t,
6430 int value_regno, bool strict_alignment_once, bool is_ldsx)
6432 struct bpf_reg_state *regs = cur_regs(env);
6433 struct bpf_reg_state *reg = regs + regno;
6434 struct bpf_func_state *state;
6437 size = bpf_size_to_bytes(bpf_size);
6441 /* alignment checks will add in reg->off themselves */
6442 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6446 /* for access checks, reg->off is just part of off */
6449 if (reg->type == PTR_TO_MAP_KEY) {
6450 if (t == BPF_WRITE) {
6451 verbose(env, "write to change key R%d not allowed\n", regno);
6455 err = check_mem_region_access(env, regno, off, size,
6456 reg->map_ptr->key_size, false);
6459 if (value_regno >= 0)
6460 mark_reg_unknown(env, regs, value_regno);
6461 } else if (reg->type == PTR_TO_MAP_VALUE) {
6462 struct btf_field *kptr_field = NULL;
6464 if (t == BPF_WRITE && value_regno >= 0 &&
6465 is_pointer_value(env, value_regno)) {
6466 verbose(env, "R%d leaks addr into map\n", value_regno);
6469 err = check_map_access_type(env, regno, off, size, t);
6472 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6475 if (tnum_is_const(reg->var_off))
6476 kptr_field = btf_record_find(reg->map_ptr->record,
6477 off + reg->var_off.value, BPF_KPTR);
6479 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6480 } else if (t == BPF_READ && value_regno >= 0) {
6481 struct bpf_map *map = reg->map_ptr;
6483 /* if map is read-only, track its contents as scalars */
6484 if (tnum_is_const(reg->var_off) &&
6485 bpf_map_is_rdonly(map) &&
6486 map->ops->map_direct_value_addr) {
6487 int map_off = off + reg->var_off.value;
6490 err = bpf_map_direct_read(map, map_off, size,
6495 regs[value_regno].type = SCALAR_VALUE;
6496 __mark_reg_known(®s[value_regno], val);
6498 mark_reg_unknown(env, regs, value_regno);
6501 } else if (base_type(reg->type) == PTR_TO_MEM) {
6502 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6504 if (type_may_be_null(reg->type)) {
6505 verbose(env, "R%d invalid mem access '%s'\n", regno,
6506 reg_type_str(env, reg->type));
6510 if (t == BPF_WRITE && rdonly_mem) {
6511 verbose(env, "R%d cannot write into %s\n",
6512 regno, reg_type_str(env, reg->type));
6516 if (t == BPF_WRITE && value_regno >= 0 &&
6517 is_pointer_value(env, value_regno)) {
6518 verbose(env, "R%d leaks addr into mem\n", value_regno);
6522 err = check_mem_region_access(env, regno, off, size,
6523 reg->mem_size, false);
6524 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6525 mark_reg_unknown(env, regs, value_regno);
6526 } else if (reg->type == PTR_TO_CTX) {
6527 enum bpf_reg_type reg_type = SCALAR_VALUE;
6528 struct btf *btf = NULL;
6531 if (t == BPF_WRITE && value_regno >= 0 &&
6532 is_pointer_value(env, value_regno)) {
6533 verbose(env, "R%d leaks addr into ctx\n", value_regno);
6537 err = check_ptr_off_reg(env, reg, regno);
6541 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
6544 verbose_linfo(env, insn_idx, "; ");
6545 if (!err && t == BPF_READ && value_regno >= 0) {
6546 /* ctx access returns either a scalar, or a
6547 * PTR_TO_PACKET[_META,_END]. In the latter
6548 * case, we know the offset is zero.
6550 if (reg_type == SCALAR_VALUE) {
6551 mark_reg_unknown(env, regs, value_regno);
6553 mark_reg_known_zero(env, regs,
6555 if (type_may_be_null(reg_type))
6556 regs[value_regno].id = ++env->id_gen;
6557 /* A load of ctx field could have different
6558 * actual load size with the one encoded in the
6559 * insn. When the dst is PTR, it is for sure not
6562 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6563 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6564 regs[value_regno].btf = btf;
6565 regs[value_regno].btf_id = btf_id;
6568 regs[value_regno].type = reg_type;
6571 } else if (reg->type == PTR_TO_STACK) {
6572 /* Basic bounds checks. */
6573 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6577 state = func(env, reg);
6578 err = update_stack_depth(env, state, off);
6583 err = check_stack_read(env, regno, off, size,
6586 err = check_stack_write(env, regno, off, size,
6587 value_regno, insn_idx);
6588 } else if (reg_is_pkt_pointer(reg)) {
6589 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6590 verbose(env, "cannot write into packet\n");
6593 if (t == BPF_WRITE && value_regno >= 0 &&
6594 is_pointer_value(env, value_regno)) {
6595 verbose(env, "R%d leaks addr into packet\n",
6599 err = check_packet_access(env, regno, off, size, false);
6600 if (!err && t == BPF_READ && value_regno >= 0)
6601 mark_reg_unknown(env, regs, value_regno);
6602 } else if (reg->type == PTR_TO_FLOW_KEYS) {
6603 if (t == BPF_WRITE && value_regno >= 0 &&
6604 is_pointer_value(env, value_regno)) {
6605 verbose(env, "R%d leaks addr into flow keys\n",
6610 err = check_flow_keys_access(env, off, size);
6611 if (!err && t == BPF_READ && value_regno >= 0)
6612 mark_reg_unknown(env, regs, value_regno);
6613 } else if (type_is_sk_pointer(reg->type)) {
6614 if (t == BPF_WRITE) {
6615 verbose(env, "R%d cannot write into %s\n",
6616 regno, reg_type_str(env, reg->type));
6619 err = check_sock_access(env, insn_idx, regno, off, size, t);
6620 if (!err && value_regno >= 0)
6621 mark_reg_unknown(env, regs, value_regno);
6622 } else if (reg->type == PTR_TO_TP_BUFFER) {
6623 err = check_tp_buffer_access(env, reg, regno, off, size);
6624 if (!err && t == BPF_READ && value_regno >= 0)
6625 mark_reg_unknown(env, regs, value_regno);
6626 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6627 !type_may_be_null(reg->type)) {
6628 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6630 } else if (reg->type == CONST_PTR_TO_MAP) {
6631 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6633 } else if (base_type(reg->type) == PTR_TO_BUF) {
6634 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6638 if (t == BPF_WRITE) {
6639 verbose(env, "R%d cannot write into %s\n",
6640 regno, reg_type_str(env, reg->type));
6643 max_access = &env->prog->aux->max_rdonly_access;
6645 max_access = &env->prog->aux->max_rdwr_access;
6648 err = check_buffer_access(env, reg, regno, off, size, false,
6651 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6652 mark_reg_unknown(env, regs, value_regno);
6654 verbose(env, "R%d invalid mem access '%s'\n", regno,
6655 reg_type_str(env, reg->type));
6659 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6660 regs[value_regno].type == SCALAR_VALUE) {
6662 /* b/h/w load zero-extends, mark upper bits as known 0 */
6663 coerce_reg_to_size(®s[value_regno], size);
6665 coerce_reg_to_size_sx(®s[value_regno], size);
6670 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6675 switch (insn->imm) {
6677 case BPF_ADD | BPF_FETCH:
6679 case BPF_AND | BPF_FETCH:
6681 case BPF_OR | BPF_FETCH:
6683 case BPF_XOR | BPF_FETCH:
6688 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6692 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6693 verbose(env, "invalid atomic operand size\n");
6697 /* check src1 operand */
6698 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6702 /* check src2 operand */
6703 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6707 if (insn->imm == BPF_CMPXCHG) {
6708 /* Check comparison of R0 with memory location */
6709 const u32 aux_reg = BPF_REG_0;
6711 err = check_reg_arg(env, aux_reg, SRC_OP);
6715 if (is_pointer_value(env, aux_reg)) {
6716 verbose(env, "R%d leaks addr into mem\n", aux_reg);
6721 if (is_pointer_value(env, insn->src_reg)) {
6722 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6726 if (is_ctx_reg(env, insn->dst_reg) ||
6727 is_pkt_reg(env, insn->dst_reg) ||
6728 is_flow_key_reg(env, insn->dst_reg) ||
6729 is_sk_reg(env, insn->dst_reg)) {
6730 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6732 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6736 if (insn->imm & BPF_FETCH) {
6737 if (insn->imm == BPF_CMPXCHG)
6738 load_reg = BPF_REG_0;
6740 load_reg = insn->src_reg;
6742 /* check and record load of old value */
6743 err = check_reg_arg(env, load_reg, DST_OP);
6747 /* This instruction accesses a memory location but doesn't
6748 * actually load it into a register.
6753 /* Check whether we can read the memory, with second call for fetch
6754 * case to simulate the register fill.
6756 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6757 BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6758 if (!err && load_reg >= 0)
6759 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6760 BPF_SIZE(insn->code), BPF_READ, load_reg,
6765 /* Check whether we can write into the same memory. */
6766 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6767 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6774 /* When register 'regno' is used to read the stack (either directly or through
6775 * a helper function) make sure that it's within stack boundary and, depending
6776 * on the access type, that all elements of the stack are initialized.
6778 * 'off' includes 'regno->off', but not its dynamic part (if any).
6780 * All registers that have been spilled on the stack in the slots within the
6781 * read offsets are marked as read.
6783 static int check_stack_range_initialized(
6784 struct bpf_verifier_env *env, int regno, int off,
6785 int access_size, bool zero_size_allowed,
6786 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6788 struct bpf_reg_state *reg = reg_state(env, regno);
6789 struct bpf_func_state *state = func(env, reg);
6790 int err, min_off, max_off, i, j, slot, spi;
6791 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6792 enum bpf_access_type bounds_check_type;
6793 /* Some accesses can write anything into the stack, others are
6796 bool clobber = false;
6798 if (access_size == 0 && !zero_size_allowed) {
6799 verbose(env, "invalid zero-sized read\n");
6803 if (type == ACCESS_HELPER) {
6804 /* The bounds checks for writes are more permissive than for
6805 * reads. However, if raw_mode is not set, we'll do extra
6808 bounds_check_type = BPF_WRITE;
6811 bounds_check_type = BPF_READ;
6813 err = check_stack_access_within_bounds(env, regno, off, access_size,
6814 type, bounds_check_type);
6819 if (tnum_is_const(reg->var_off)) {
6820 min_off = max_off = reg->var_off.value + off;
6822 /* Variable offset is prohibited for unprivileged mode for
6823 * simplicity since it requires corresponding support in
6824 * Spectre masking for stack ALU.
6825 * See also retrieve_ptr_limit().
6827 if (!env->bypass_spec_v1) {
6830 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6831 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6832 regno, err_extra, tn_buf);
6835 /* Only initialized buffer on stack is allowed to be accessed
6836 * with variable offset. With uninitialized buffer it's hard to
6837 * guarantee that whole memory is marked as initialized on
6838 * helper return since specific bounds are unknown what may
6839 * cause uninitialized stack leaking.
6841 if (meta && meta->raw_mode)
6844 min_off = reg->smin_value + off;
6845 max_off = reg->smax_value + off;
6848 if (meta && meta->raw_mode) {
6849 /* Ensure we won't be overwriting dynptrs when simulating byte
6850 * by byte access in check_helper_call using meta.access_size.
6851 * This would be a problem if we have a helper in the future
6854 * helper(uninit_mem, len, dynptr)
6856 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6857 * may end up writing to dynptr itself when touching memory from
6858 * arg 1. This can be relaxed on a case by case basis for known
6859 * safe cases, but reject due to the possibilitiy of aliasing by
6862 for (i = min_off; i < max_off + access_size; i++) {
6863 int stack_off = -i - 1;
6866 /* raw_mode may write past allocated_stack */
6867 if (state->allocated_stack <= stack_off)
6869 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6870 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6874 meta->access_size = access_size;
6875 meta->regno = regno;
6879 for (i = min_off; i < max_off + access_size; i++) {
6883 spi = slot / BPF_REG_SIZE;
6884 if (state->allocated_stack <= slot)
6886 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6887 if (*stype == STACK_MISC)
6889 if ((*stype == STACK_ZERO) ||
6890 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6892 /* helper can write anything into the stack */
6893 *stype = STACK_MISC;
6898 if (is_spilled_reg(&state->stack[spi]) &&
6899 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6900 env->allow_ptr_leaks)) {
6902 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6903 for (j = 0; j < BPF_REG_SIZE; j++)
6904 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6910 if (tnum_is_const(reg->var_off)) {
6911 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6912 err_extra, regno, min_off, i - min_off, access_size);
6916 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6917 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6918 err_extra, regno, tn_buf, i - min_off, access_size);
6922 /* reading any byte out of 8-byte 'spill_slot' will cause
6923 * the whole slot to be marked as 'read'
6925 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6926 state->stack[spi].spilled_ptr.parent,
6928 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6929 * be sure that whether stack slot is written to or not. Hence,
6930 * we must still conservatively propagate reads upwards even if
6931 * helper may write to the entire memory range.
6934 return update_stack_depth(env, state, min_off);
6937 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6938 int access_size, bool zero_size_allowed,
6939 struct bpf_call_arg_meta *meta)
6941 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6944 switch (base_type(reg->type)) {
6946 case PTR_TO_PACKET_META:
6947 return check_packet_access(env, regno, reg->off, access_size,
6949 case PTR_TO_MAP_KEY:
6950 if (meta && meta->raw_mode) {
6951 verbose(env, "R%d cannot write into %s\n", regno,
6952 reg_type_str(env, reg->type));
6955 return check_mem_region_access(env, regno, reg->off, access_size,
6956 reg->map_ptr->key_size, false);
6957 case PTR_TO_MAP_VALUE:
6958 if (check_map_access_type(env, regno, reg->off, access_size,
6959 meta && meta->raw_mode ? BPF_WRITE :
6962 return check_map_access(env, regno, reg->off, access_size,
6963 zero_size_allowed, ACCESS_HELPER);
6965 if (type_is_rdonly_mem(reg->type)) {
6966 if (meta && meta->raw_mode) {
6967 verbose(env, "R%d cannot write into %s\n", regno,
6968 reg_type_str(env, reg->type));
6972 return check_mem_region_access(env, regno, reg->off,
6973 access_size, reg->mem_size,
6976 if (type_is_rdonly_mem(reg->type)) {
6977 if (meta && meta->raw_mode) {
6978 verbose(env, "R%d cannot write into %s\n", regno,
6979 reg_type_str(env, reg->type));
6983 max_access = &env->prog->aux->max_rdonly_access;
6985 max_access = &env->prog->aux->max_rdwr_access;
6987 return check_buffer_access(env, reg, regno, reg->off,
6988 access_size, zero_size_allowed,
6991 return check_stack_range_initialized(
6993 regno, reg->off, access_size,
6994 zero_size_allowed, ACCESS_HELPER, meta);
6996 return check_ptr_to_btf_access(env, regs, regno, reg->off,
6997 access_size, BPF_READ, -1);
6999 /* in case the function doesn't know how to access the context,
7000 * (because we are in a program of type SYSCALL for example), we
7001 * can not statically check its size.
7002 * Dynamically check it now.
7004 if (!env->ops->convert_ctx_access) {
7005 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7006 int offset = access_size - 1;
7008 /* Allow zero-byte read from PTR_TO_CTX */
7009 if (access_size == 0)
7010 return zero_size_allowed ? 0 : -EACCES;
7012 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7013 atype, -1, false, false);
7017 default: /* scalar_value or invalid ptr */
7018 /* Allow zero-byte read from NULL, regardless of pointer type */
7019 if (zero_size_allowed && access_size == 0 &&
7020 register_is_null(reg))
7023 verbose(env, "R%d type=%s ", regno,
7024 reg_type_str(env, reg->type));
7025 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7030 static int check_mem_size_reg(struct bpf_verifier_env *env,
7031 struct bpf_reg_state *reg, u32 regno,
7032 bool zero_size_allowed,
7033 struct bpf_call_arg_meta *meta)
7037 /* This is used to refine r0 return value bounds for helpers
7038 * that enforce this value as an upper bound on return values.
7039 * See do_refine_retval_range() for helpers that can refine
7040 * the return value. C type of helper is u32 so we pull register
7041 * bound from umax_value however, if negative verifier errors
7042 * out. Only upper bounds can be learned because retval is an
7043 * int type and negative retvals are allowed.
7045 meta->msize_max_value = reg->umax_value;
7047 /* The register is SCALAR_VALUE; the access check
7048 * happens using its boundaries.
7050 if (!tnum_is_const(reg->var_off))
7051 /* For unprivileged variable accesses, disable raw
7052 * mode so that the program is required to
7053 * initialize all the memory that the helper could
7054 * just partially fill up.
7058 if (reg->smin_value < 0) {
7059 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7064 if (reg->umin_value == 0) {
7065 err = check_helper_mem_access(env, regno - 1, 0,
7072 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7073 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7077 err = check_helper_mem_access(env, regno - 1,
7079 zero_size_allowed, meta);
7081 err = mark_chain_precision(env, regno);
7085 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7086 u32 regno, u32 mem_size)
7088 bool may_be_null = type_may_be_null(reg->type);
7089 struct bpf_reg_state saved_reg;
7090 struct bpf_call_arg_meta meta;
7093 if (register_is_null(reg))
7096 memset(&meta, 0, sizeof(meta));
7097 /* Assuming that the register contains a value check if the memory
7098 * access is safe. Temporarily save and restore the register's state as
7099 * the conversion shouldn't be visible to a caller.
7103 mark_ptr_not_null_reg(reg);
7106 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7107 /* Check access for BPF_WRITE */
7108 meta.raw_mode = true;
7109 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7117 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7120 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7121 bool may_be_null = type_may_be_null(mem_reg->type);
7122 struct bpf_reg_state saved_reg;
7123 struct bpf_call_arg_meta meta;
7126 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7128 memset(&meta, 0, sizeof(meta));
7131 saved_reg = *mem_reg;
7132 mark_ptr_not_null_reg(mem_reg);
7135 err = check_mem_size_reg(env, reg, regno, true, &meta);
7136 /* Check access for BPF_WRITE */
7137 meta.raw_mode = true;
7138 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7141 *mem_reg = saved_reg;
7145 /* Implementation details:
7146 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7147 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7148 * Two bpf_map_lookups (even with the same key) will have different reg->id.
7149 * Two separate bpf_obj_new will also have different reg->id.
7150 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7151 * clears reg->id after value_or_null->value transition, since the verifier only
7152 * cares about the range of access to valid map value pointer and doesn't care
7153 * about actual address of the map element.
7154 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7155 * reg->id > 0 after value_or_null->value transition. By doing so
7156 * two bpf_map_lookups will be considered two different pointers that
7157 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7158 * returned from bpf_obj_new.
7159 * The verifier allows taking only one bpf_spin_lock at a time to avoid
7161 * Since only one bpf_spin_lock is allowed the checks are simpler than
7162 * reg_is_refcounted() logic. The verifier needs to remember only
7163 * one spin_lock instead of array of acquired_refs.
7164 * cur_state->active_lock remembers which map value element or allocated
7165 * object got locked and clears it after bpf_spin_unlock.
7167 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7170 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7171 struct bpf_verifier_state *cur = env->cur_state;
7172 bool is_const = tnum_is_const(reg->var_off);
7173 u64 val = reg->var_off.value;
7174 struct bpf_map *map = NULL;
7175 struct btf *btf = NULL;
7176 struct btf_record *rec;
7180 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7184 if (reg->type == PTR_TO_MAP_VALUE) {
7188 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7196 rec = reg_btf_record(reg);
7197 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7198 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7199 map ? map->name : "kptr");
7202 if (rec->spin_lock_off != val + reg->off) {
7203 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7204 val + reg->off, rec->spin_lock_off);
7208 if (cur->active_lock.ptr) {
7210 "Locking two bpf_spin_locks are not allowed\n");
7214 cur->active_lock.ptr = map;
7216 cur->active_lock.ptr = btf;
7217 cur->active_lock.id = reg->id;
7226 if (!cur->active_lock.ptr) {
7227 verbose(env, "bpf_spin_unlock without taking a lock\n");
7230 if (cur->active_lock.ptr != ptr ||
7231 cur->active_lock.id != reg->id) {
7232 verbose(env, "bpf_spin_unlock of different lock\n");
7236 invalidate_non_owning_refs(env);
7238 cur->active_lock.ptr = NULL;
7239 cur->active_lock.id = 0;
7244 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7245 struct bpf_call_arg_meta *meta)
7247 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7248 bool is_const = tnum_is_const(reg->var_off);
7249 struct bpf_map *map = reg->map_ptr;
7250 u64 val = reg->var_off.value;
7254 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7259 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7263 if (!btf_record_has_field(map->record, BPF_TIMER)) {
7264 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7267 if (map->record->timer_off != val + reg->off) {
7268 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7269 val + reg->off, map->record->timer_off);
7272 if (meta->map_ptr) {
7273 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7276 meta->map_uid = reg->map_uid;
7277 meta->map_ptr = map;
7281 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7282 struct bpf_call_arg_meta *meta)
7284 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7285 struct bpf_map *map_ptr = reg->map_ptr;
7286 struct btf_field *kptr_field;
7289 if (!tnum_is_const(reg->var_off)) {
7291 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7295 if (!map_ptr->btf) {
7296 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7300 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7301 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7305 meta->map_ptr = map_ptr;
7306 kptr_off = reg->off + reg->var_off.value;
7307 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7309 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7312 if (kptr_field->type != BPF_KPTR_REF) {
7313 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7316 meta->kptr_field = kptr_field;
7320 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7321 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7323 * In both cases we deal with the first 8 bytes, but need to mark the next 8
7324 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7325 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7327 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7328 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7329 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7330 * mutate the view of the dynptr and also possibly destroy it. In the latter
7331 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7332 * memory that dynptr points to.
7334 * The verifier will keep track both levels of mutation (bpf_dynptr's in
7335 * reg->type and the memory's in reg->dynptr.type), but there is no support for
7336 * readonly dynptr view yet, hence only the first case is tracked and checked.
7338 * This is consistent with how C applies the const modifier to a struct object,
7339 * where the pointer itself inside bpf_dynptr becomes const but not what it
7342 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7343 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7345 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7346 enum bpf_arg_type arg_type, int clone_ref_obj_id)
7348 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7351 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7352 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7354 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7355 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7359 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
7360 * constructing a mutable bpf_dynptr object.
7362 * Currently, this is only possible with PTR_TO_STACK
7363 * pointing to a region of at least 16 bytes which doesn't
7364 * contain an existing bpf_dynptr.
7366 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7367 * mutated or destroyed. However, the memory it points to
7370 * None - Points to a initialized dynptr that can be mutated and
7371 * destroyed, including mutation of the memory it points
7374 if (arg_type & MEM_UNINIT) {
7377 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7378 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7382 /* we write BPF_DW bits (8 bytes) at a time */
7383 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7384 err = check_mem_access(env, insn_idx, regno,
7385 i, BPF_DW, BPF_WRITE, -1, false, false);
7390 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7391 } else /* MEM_RDONLY and None case from above */ {
7392 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7393 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7394 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7398 if (!is_dynptr_reg_valid_init(env, reg)) {
7400 "Expected an initialized dynptr as arg #%d\n",
7405 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7406 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7408 "Expected a dynptr of type %s as arg #%d\n",
7409 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7413 err = mark_dynptr_read(env, reg);
7418 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7420 struct bpf_func_state *state = func(env, reg);
7422 return state->stack[spi].spilled_ptr.ref_obj_id;
7425 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7427 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7430 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7432 return meta->kfunc_flags & KF_ITER_NEW;
7435 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7437 return meta->kfunc_flags & KF_ITER_NEXT;
7440 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7442 return meta->kfunc_flags & KF_ITER_DESTROY;
7445 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7447 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7448 * kfunc is iter state pointer
7450 return arg == 0 && is_iter_kfunc(meta);
7453 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7454 struct bpf_kfunc_call_arg_meta *meta)
7456 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7457 const struct btf_type *t;
7458 const struct btf_param *arg;
7459 int spi, err, i, nr_slots;
7462 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7463 arg = &btf_params(meta->func_proto)[0];
7464 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
7465 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
7466 nr_slots = t->size / BPF_REG_SIZE;
7468 if (is_iter_new_kfunc(meta)) {
7469 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7470 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7471 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7472 iter_type_str(meta->btf, btf_id), regno);
7476 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7477 err = check_mem_access(env, insn_idx, regno,
7478 i, BPF_DW, BPF_WRITE, -1, false, false);
7483 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7487 /* iter_next() or iter_destroy() expect initialized iter state*/
7488 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7489 verbose(env, "expected an initialized iter_%s as arg #%d\n",
7490 iter_type_str(meta->btf, btf_id), regno);
7494 spi = iter_get_spi(env, reg, nr_slots);
7498 err = mark_iter_read(env, reg, spi, nr_slots);
7502 /* remember meta->iter info for process_iter_next_call() */
7503 meta->iter.spi = spi;
7504 meta->iter.frameno = reg->frameno;
7505 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7507 if (is_iter_destroy_kfunc(meta)) {
7508 err = unmark_stack_slots_iter(env, reg, nr_slots);
7517 /* process_iter_next_call() is called when verifier gets to iterator's next
7518 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7519 * to it as just "iter_next()" in comments below.
7521 * BPF verifier relies on a crucial contract for any iter_next()
7522 * implementation: it should *eventually* return NULL, and once that happens
7523 * it should keep returning NULL. That is, once iterator exhausts elements to
7524 * iterate, it should never reset or spuriously return new elements.
7526 * With the assumption of such contract, process_iter_next_call() simulates
7527 * a fork in the verifier state to validate loop logic correctness and safety
7528 * without having to simulate infinite amount of iterations.
7530 * In current state, we first assume that iter_next() returned NULL and
7531 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7532 * conditions we should not form an infinite loop and should eventually reach
7535 * Besides that, we also fork current state and enqueue it for later
7536 * verification. In a forked state we keep iterator state as ACTIVE
7537 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7538 * also bump iteration depth to prevent erroneous infinite loop detection
7539 * later on (see iter_active_depths_differ() comment for details). In this
7540 * state we assume that we'll eventually loop back to another iter_next()
7541 * calls (it could be in exactly same location or in some other instruction,
7542 * it doesn't matter, we don't make any unnecessary assumptions about this,
7543 * everything revolves around iterator state in a stack slot, not which
7544 * instruction is calling iter_next()). When that happens, we either will come
7545 * to iter_next() with equivalent state and can conclude that next iteration
7546 * will proceed in exactly the same way as we just verified, so it's safe to
7547 * assume that loop converges. If not, we'll go on another iteration
7548 * simulation with a different input state, until all possible starting states
7549 * are validated or we reach maximum number of instructions limit.
7551 * This way, we will either exhaustively discover all possible input states
7552 * that iterator loop can start with and eventually will converge, or we'll
7553 * effectively regress into bounded loop simulation logic and either reach
7554 * maximum number of instructions if loop is not provably convergent, or there
7555 * is some statically known limit on number of iterations (e.g., if there is
7556 * an explicit `if n > 100 then break;` statement somewhere in the loop).
7558 * One very subtle but very important aspect is that we *always* simulate NULL
7559 * condition first (as the current state) before we simulate non-NULL case.
7560 * This has to do with intricacies of scalar precision tracking. By simulating
7561 * "exit condition" of iter_next() returning NULL first, we make sure all the
7562 * relevant precision marks *that will be set **after** we exit iterator loop*
7563 * are propagated backwards to common parent state of NULL and non-NULL
7564 * branches. Thanks to that, state equivalence checks done later in forked
7565 * state, when reaching iter_next() for ACTIVE iterator, can assume that
7566 * precision marks are finalized and won't change. Because simulating another
7567 * ACTIVE iterator iteration won't change them (because given same input
7568 * states we'll end up with exactly same output states which we are currently
7569 * comparing; and verification after the loop already propagated back what
7570 * needs to be **additionally** tracked as precise). It's subtle, grok
7571 * precision tracking for more intuitive understanding.
7573 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7574 struct bpf_kfunc_call_arg_meta *meta)
7576 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7577 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7578 struct bpf_reg_state *cur_iter, *queued_iter;
7579 int iter_frameno = meta->iter.frameno;
7580 int iter_spi = meta->iter.spi;
7582 BTF_TYPE_EMIT(struct bpf_iter);
7584 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7586 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7587 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7588 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7589 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7593 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7594 /* branch out active iter state */
7595 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7599 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7600 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7601 queued_iter->iter.depth++;
7603 queued_fr = queued_st->frame[queued_st->curframe];
7604 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7607 /* switch to DRAINED state, but keep the depth unchanged */
7608 /* mark current iter state as drained and assume returned NULL */
7609 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7610 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7615 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7617 return type == ARG_CONST_SIZE ||
7618 type == ARG_CONST_SIZE_OR_ZERO;
7621 static bool arg_type_is_release(enum bpf_arg_type type)
7623 return type & OBJ_RELEASE;
7626 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7628 return base_type(type) == ARG_PTR_TO_DYNPTR;
7631 static int int_ptr_type_to_size(enum bpf_arg_type type)
7633 if (type == ARG_PTR_TO_INT)
7635 else if (type == ARG_PTR_TO_LONG)
7641 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7642 const struct bpf_call_arg_meta *meta,
7643 enum bpf_arg_type *arg_type)
7645 if (!meta->map_ptr) {
7646 /* kernel subsystem misconfigured verifier */
7647 verbose(env, "invalid map_ptr to access map->type\n");
7651 switch (meta->map_ptr->map_type) {
7652 case BPF_MAP_TYPE_SOCKMAP:
7653 case BPF_MAP_TYPE_SOCKHASH:
7654 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7655 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7657 verbose(env, "invalid arg_type for sockmap/sockhash\n");
7661 case BPF_MAP_TYPE_BLOOM_FILTER:
7662 if (meta->func_id == BPF_FUNC_map_peek_elem)
7663 *arg_type = ARG_PTR_TO_MAP_VALUE;
7671 struct bpf_reg_types {
7672 const enum bpf_reg_type types[10];
7676 static const struct bpf_reg_types sock_types = {
7686 static const struct bpf_reg_types btf_id_sock_common_types = {
7693 PTR_TO_BTF_ID | PTR_TRUSTED,
7695 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7699 static const struct bpf_reg_types mem_types = {
7707 PTR_TO_MEM | MEM_RINGBUF,
7709 PTR_TO_BTF_ID | PTR_TRUSTED,
7713 static const struct bpf_reg_types int_ptr_types = {
7723 static const struct bpf_reg_types spin_lock_types = {
7726 PTR_TO_BTF_ID | MEM_ALLOC,
7730 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7731 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7732 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7733 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7734 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7735 static const struct bpf_reg_types btf_ptr_types = {
7738 PTR_TO_BTF_ID | PTR_TRUSTED,
7739 PTR_TO_BTF_ID | MEM_RCU,
7742 static const struct bpf_reg_types percpu_btf_ptr_types = {
7744 PTR_TO_BTF_ID | MEM_PERCPU,
7745 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7748 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7749 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7750 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7751 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7752 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7753 static const struct bpf_reg_types dynptr_types = {
7756 CONST_PTR_TO_DYNPTR,
7760 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7761 [ARG_PTR_TO_MAP_KEY] = &mem_types,
7762 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
7763 [ARG_CONST_SIZE] = &scalar_types,
7764 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
7765 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
7766 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
7767 [ARG_PTR_TO_CTX] = &context_types,
7768 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
7770 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
7772 [ARG_PTR_TO_SOCKET] = &fullsock_types,
7773 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
7774 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
7775 [ARG_PTR_TO_MEM] = &mem_types,
7776 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
7777 [ARG_PTR_TO_INT] = &int_ptr_types,
7778 [ARG_PTR_TO_LONG] = &int_ptr_types,
7779 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
7780 [ARG_PTR_TO_FUNC] = &func_ptr_types,
7781 [ARG_PTR_TO_STACK] = &stack_ptr_types,
7782 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
7783 [ARG_PTR_TO_TIMER] = &timer_types,
7784 [ARG_PTR_TO_KPTR] = &kptr_types,
7785 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
7788 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7789 enum bpf_arg_type arg_type,
7790 const u32 *arg_btf_id,
7791 struct bpf_call_arg_meta *meta)
7793 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7794 enum bpf_reg_type expected, type = reg->type;
7795 const struct bpf_reg_types *compatible;
7798 compatible = compatible_reg_types[base_type(arg_type)];
7800 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7804 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7805 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7807 * Same for MAYBE_NULL:
7809 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7810 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7812 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7814 * Therefore we fold these flags depending on the arg_type before comparison.
7816 if (arg_type & MEM_RDONLY)
7817 type &= ~MEM_RDONLY;
7818 if (arg_type & PTR_MAYBE_NULL)
7819 type &= ~PTR_MAYBE_NULL;
7820 if (base_type(arg_type) == ARG_PTR_TO_MEM)
7821 type &= ~DYNPTR_TYPE_FLAG_MASK;
7823 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
7826 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7827 expected = compatible->types[i];
7828 if (expected == NOT_INIT)
7831 if (type == expected)
7835 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7836 for (j = 0; j + 1 < i; j++)
7837 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7838 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7842 if (base_type(reg->type) != PTR_TO_BTF_ID)
7845 if (compatible == &mem_types) {
7846 if (!(arg_type & MEM_RDONLY)) {
7848 "%s() may write into memory pointed by R%d type=%s\n",
7849 func_id_name(meta->func_id),
7850 regno, reg_type_str(env, reg->type));
7856 switch ((int)reg->type) {
7858 case PTR_TO_BTF_ID | PTR_TRUSTED:
7859 case PTR_TO_BTF_ID | MEM_RCU:
7860 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7861 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7863 /* For bpf_sk_release, it needs to match against first member
7864 * 'struct sock_common', hence make an exception for it. This
7865 * allows bpf_sk_release to work for multiple socket types.
7867 bool strict_type_match = arg_type_is_release(arg_type) &&
7868 meta->func_id != BPF_FUNC_sk_release;
7870 if (type_may_be_null(reg->type) &&
7871 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7872 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7877 if (!compatible->btf_id) {
7878 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7881 arg_btf_id = compatible->btf_id;
7884 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7885 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7888 if (arg_btf_id == BPF_PTR_POISON) {
7889 verbose(env, "verifier internal error:");
7890 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7895 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7896 btf_vmlinux, *arg_btf_id,
7897 strict_type_match)) {
7898 verbose(env, "R%d is of type %s but %s is expected\n",
7899 regno, btf_type_name(reg->btf, reg->btf_id),
7900 btf_type_name(btf_vmlinux, *arg_btf_id));
7906 case PTR_TO_BTF_ID | MEM_ALLOC:
7907 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7908 meta->func_id != BPF_FUNC_kptr_xchg) {
7909 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7912 /* Handled by helper specific checks */
7914 case PTR_TO_BTF_ID | MEM_PERCPU:
7915 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7916 /* Handled by helper specific checks */
7919 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7925 static struct btf_field *
7926 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7928 struct btf_field *field;
7929 struct btf_record *rec;
7931 rec = reg_btf_record(reg);
7935 field = btf_record_find(rec, off, fields);
7942 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7943 const struct bpf_reg_state *reg, int regno,
7944 enum bpf_arg_type arg_type)
7946 u32 type = reg->type;
7948 /* When referenced register is passed to release function, its fixed
7951 * We will check arg_type_is_release reg has ref_obj_id when storing
7952 * meta->release_regno.
7954 if (arg_type_is_release(arg_type)) {
7955 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7956 * may not directly point to the object being released, but to
7957 * dynptr pointing to such object, which might be at some offset
7958 * on the stack. In that case, we simply to fallback to the
7961 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7964 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7965 if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7966 return __check_ptr_off_reg(env, reg, regno, true);
7968 verbose(env, "R%d must have zero offset when passed to release func\n",
7970 verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7971 btf_type_name(reg->btf, reg->btf_id), reg->off);
7975 /* Doing check_ptr_off_reg check for the offset will catch this
7976 * because fixed_off_ok is false, but checking here allows us
7977 * to give the user a better error message.
7980 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7984 return __check_ptr_off_reg(env, reg, regno, false);
7988 /* Pointer types where both fixed and variable offset is explicitly allowed: */
7991 case PTR_TO_PACKET_META:
7992 case PTR_TO_MAP_KEY:
7993 case PTR_TO_MAP_VALUE:
7995 case PTR_TO_MEM | MEM_RDONLY:
7996 case PTR_TO_MEM | MEM_RINGBUF:
7998 case PTR_TO_BUF | MEM_RDONLY:
8001 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8005 case PTR_TO_BTF_ID | MEM_ALLOC:
8006 case PTR_TO_BTF_ID | PTR_TRUSTED:
8007 case PTR_TO_BTF_ID | MEM_RCU:
8008 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8009 /* When referenced PTR_TO_BTF_ID is passed to release function,
8010 * its fixed offset must be 0. In the other cases, fixed offset
8011 * can be non-zero. This was already checked above. So pass
8012 * fixed_off_ok as true to allow fixed offset for all other
8013 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8014 * still need to do checks instead of returning.
8016 return __check_ptr_off_reg(env, reg, regno, true);
8018 return __check_ptr_off_reg(env, reg, regno, false);
8022 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8023 const struct bpf_func_proto *fn,
8024 struct bpf_reg_state *regs)
8026 struct bpf_reg_state *state = NULL;
8029 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8030 if (arg_type_is_dynptr(fn->arg_type[i])) {
8032 verbose(env, "verifier internal error: multiple dynptr args\n");
8035 state = ®s[BPF_REG_1 + i];
8039 verbose(env, "verifier internal error: no dynptr arg found\n");
8044 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8046 struct bpf_func_state *state = func(env, reg);
8049 if (reg->type == CONST_PTR_TO_DYNPTR)
8051 spi = dynptr_get_spi(env, reg);
8054 return state->stack[spi].spilled_ptr.id;
8057 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8059 struct bpf_func_state *state = func(env, reg);
8062 if (reg->type == CONST_PTR_TO_DYNPTR)
8063 return reg->ref_obj_id;
8064 spi = dynptr_get_spi(env, reg);
8067 return state->stack[spi].spilled_ptr.ref_obj_id;
8070 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8071 struct bpf_reg_state *reg)
8073 struct bpf_func_state *state = func(env, reg);
8076 if (reg->type == CONST_PTR_TO_DYNPTR)
8077 return reg->dynptr.type;
8079 spi = __get_spi(reg->off);
8081 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8082 return BPF_DYNPTR_TYPE_INVALID;
8085 return state->stack[spi].spilled_ptr.dynptr.type;
8088 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8089 struct bpf_call_arg_meta *meta,
8090 const struct bpf_func_proto *fn,
8093 u32 regno = BPF_REG_1 + arg;
8094 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8095 enum bpf_arg_type arg_type = fn->arg_type[arg];
8096 enum bpf_reg_type type = reg->type;
8097 u32 *arg_btf_id = NULL;
8100 if (arg_type == ARG_DONTCARE)
8103 err = check_reg_arg(env, regno, SRC_OP);
8107 if (arg_type == ARG_ANYTHING) {
8108 if (is_pointer_value(env, regno)) {
8109 verbose(env, "R%d leaks addr into helper function\n",
8116 if (type_is_pkt_pointer(type) &&
8117 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8118 verbose(env, "helper access to the packet is not allowed\n");
8122 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8123 err = resolve_map_arg_type(env, meta, &arg_type);
8128 if (register_is_null(reg) && type_may_be_null(arg_type))
8129 /* A NULL register has a SCALAR_VALUE type, so skip
8132 goto skip_type_check;
8134 /* arg_btf_id and arg_size are in a union. */
8135 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8136 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8137 arg_btf_id = fn->arg_btf_id[arg];
8139 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8143 err = check_func_arg_reg_off(env, reg, regno, arg_type);
8148 if (arg_type_is_release(arg_type)) {
8149 if (arg_type_is_dynptr(arg_type)) {
8150 struct bpf_func_state *state = func(env, reg);
8153 /* Only dynptr created on stack can be released, thus
8154 * the get_spi and stack state checks for spilled_ptr
8155 * should only be done before process_dynptr_func for
8158 if (reg->type == PTR_TO_STACK) {
8159 spi = dynptr_get_spi(env, reg);
8160 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8161 verbose(env, "arg %d is an unacquired reference\n", regno);
8165 verbose(env, "cannot release unowned const bpf_dynptr\n");
8168 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8169 verbose(env, "R%d must be referenced when passed to release function\n",
8173 if (meta->release_regno) {
8174 verbose(env, "verifier internal error: more than one release argument\n");
8177 meta->release_regno = regno;
8180 if (reg->ref_obj_id) {
8181 if (meta->ref_obj_id) {
8182 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8183 regno, reg->ref_obj_id,
8187 meta->ref_obj_id = reg->ref_obj_id;
8190 switch (base_type(arg_type)) {
8191 case ARG_CONST_MAP_PTR:
8192 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8193 if (meta->map_ptr) {
8194 /* Use map_uid (which is unique id of inner map) to reject:
8195 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8196 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8197 * if (inner_map1 && inner_map2) {
8198 * timer = bpf_map_lookup_elem(inner_map1);
8200 * // mismatch would have been allowed
8201 * bpf_timer_init(timer, inner_map2);
8204 * Comparing map_ptr is enough to distinguish normal and outer maps.
8206 if (meta->map_ptr != reg->map_ptr ||
8207 meta->map_uid != reg->map_uid) {
8209 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8210 meta->map_uid, reg->map_uid);
8214 meta->map_ptr = reg->map_ptr;
8215 meta->map_uid = reg->map_uid;
8217 case ARG_PTR_TO_MAP_KEY:
8218 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8219 * check that [key, key + map->key_size) are within
8220 * stack limits and initialized
8222 if (!meta->map_ptr) {
8223 /* in function declaration map_ptr must come before
8224 * map_key, so that it's verified and known before
8225 * we have to check map_key here. Otherwise it means
8226 * that kernel subsystem misconfigured verifier
8228 verbose(env, "invalid map_ptr to access map->key\n");
8231 err = check_helper_mem_access(env, regno,
8232 meta->map_ptr->key_size, false,
8235 case ARG_PTR_TO_MAP_VALUE:
8236 if (type_may_be_null(arg_type) && register_is_null(reg))
8239 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8240 * check [value, value + map->value_size) validity
8242 if (!meta->map_ptr) {
8243 /* kernel subsystem misconfigured verifier */
8244 verbose(env, "invalid map_ptr to access map->value\n");
8247 meta->raw_mode = arg_type & MEM_UNINIT;
8248 err = check_helper_mem_access(env, regno,
8249 meta->map_ptr->value_size, false,
8252 case ARG_PTR_TO_PERCPU_BTF_ID:
8254 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8257 meta->ret_btf = reg->btf;
8258 meta->ret_btf_id = reg->btf_id;
8260 case ARG_PTR_TO_SPIN_LOCK:
8261 if (in_rbtree_lock_required_cb(env)) {
8262 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8265 if (meta->func_id == BPF_FUNC_spin_lock) {
8266 err = process_spin_lock(env, regno, true);
8269 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8270 err = process_spin_lock(env, regno, false);
8274 verbose(env, "verifier internal error\n");
8278 case ARG_PTR_TO_TIMER:
8279 err = process_timer_func(env, regno, meta);
8283 case ARG_PTR_TO_FUNC:
8284 meta->subprogno = reg->subprogno;
8286 case ARG_PTR_TO_MEM:
8287 /* The access to this pointer is only checked when we hit the
8288 * next is_mem_size argument below.
8290 meta->raw_mode = arg_type & MEM_UNINIT;
8291 if (arg_type & MEM_FIXED_SIZE) {
8292 err = check_helper_mem_access(env, regno,
8293 fn->arg_size[arg], false,
8297 case ARG_CONST_SIZE:
8298 err = check_mem_size_reg(env, reg, regno, false, meta);
8300 case ARG_CONST_SIZE_OR_ZERO:
8301 err = check_mem_size_reg(env, reg, regno, true, meta);
8303 case ARG_PTR_TO_DYNPTR:
8304 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8308 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8309 if (!tnum_is_const(reg->var_off)) {
8310 verbose(env, "R%d is not a known constant'\n",
8314 meta->mem_size = reg->var_off.value;
8315 err = mark_chain_precision(env, regno);
8319 case ARG_PTR_TO_INT:
8320 case ARG_PTR_TO_LONG:
8322 int size = int_ptr_type_to_size(arg_type);
8324 err = check_helper_mem_access(env, regno, size, false, meta);
8327 err = check_ptr_alignment(env, reg, 0, size, true);
8330 case ARG_PTR_TO_CONST_STR:
8332 struct bpf_map *map = reg->map_ptr;
8337 if (!bpf_map_is_rdonly(map)) {
8338 verbose(env, "R%d does not point to a readonly map'\n", regno);
8342 if (!tnum_is_const(reg->var_off)) {
8343 verbose(env, "R%d is not a constant address'\n", regno);
8347 if (!map->ops->map_direct_value_addr) {
8348 verbose(env, "no direct value access support for this map type\n");
8352 err = check_map_access(env, regno, reg->off,
8353 map->value_size - reg->off, false,
8358 map_off = reg->off + reg->var_off.value;
8359 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8361 verbose(env, "direct value access on string failed\n");
8365 str_ptr = (char *)(long)(map_addr);
8366 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8367 verbose(env, "string is not zero-terminated\n");
8372 case ARG_PTR_TO_KPTR:
8373 err = process_kptr_func(env, regno, meta);
8382 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8384 enum bpf_attach_type eatype = env->prog->expected_attach_type;
8385 enum bpf_prog_type type = resolve_prog_type(env->prog);
8387 if (func_id != BPF_FUNC_map_update_elem)
8390 /* It's not possible to get access to a locked struct sock in these
8391 * contexts, so updating is safe.
8394 case BPF_PROG_TYPE_TRACING:
8395 if (eatype == BPF_TRACE_ITER)
8398 case BPF_PROG_TYPE_SOCKET_FILTER:
8399 case BPF_PROG_TYPE_SCHED_CLS:
8400 case BPF_PROG_TYPE_SCHED_ACT:
8401 case BPF_PROG_TYPE_XDP:
8402 case BPF_PROG_TYPE_SK_REUSEPORT:
8403 case BPF_PROG_TYPE_FLOW_DISSECTOR:
8404 case BPF_PROG_TYPE_SK_LOOKUP:
8410 verbose(env, "cannot update sockmap in this context\n");
8414 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8416 return env->prog->jit_requested &&
8417 bpf_jit_supports_subprog_tailcalls();
8420 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8421 struct bpf_map *map, int func_id)
8426 /* We need a two way check, first is from map perspective ... */
8427 switch (map->map_type) {
8428 case BPF_MAP_TYPE_PROG_ARRAY:
8429 if (func_id != BPF_FUNC_tail_call)
8432 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8433 if (func_id != BPF_FUNC_perf_event_read &&
8434 func_id != BPF_FUNC_perf_event_output &&
8435 func_id != BPF_FUNC_skb_output &&
8436 func_id != BPF_FUNC_perf_event_read_value &&
8437 func_id != BPF_FUNC_xdp_output)
8440 case BPF_MAP_TYPE_RINGBUF:
8441 if (func_id != BPF_FUNC_ringbuf_output &&
8442 func_id != BPF_FUNC_ringbuf_reserve &&
8443 func_id != BPF_FUNC_ringbuf_query &&
8444 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8445 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8446 func_id != BPF_FUNC_ringbuf_discard_dynptr)
8449 case BPF_MAP_TYPE_USER_RINGBUF:
8450 if (func_id != BPF_FUNC_user_ringbuf_drain)
8453 case BPF_MAP_TYPE_STACK_TRACE:
8454 if (func_id != BPF_FUNC_get_stackid)
8457 case BPF_MAP_TYPE_CGROUP_ARRAY:
8458 if (func_id != BPF_FUNC_skb_under_cgroup &&
8459 func_id != BPF_FUNC_current_task_under_cgroup)
8462 case BPF_MAP_TYPE_CGROUP_STORAGE:
8463 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8464 if (func_id != BPF_FUNC_get_local_storage)
8467 case BPF_MAP_TYPE_DEVMAP:
8468 case BPF_MAP_TYPE_DEVMAP_HASH:
8469 if (func_id != BPF_FUNC_redirect_map &&
8470 func_id != BPF_FUNC_map_lookup_elem)
8473 /* Restrict bpf side of cpumap and xskmap, open when use-cases
8476 case BPF_MAP_TYPE_CPUMAP:
8477 if (func_id != BPF_FUNC_redirect_map)
8480 case BPF_MAP_TYPE_XSKMAP:
8481 if (func_id != BPF_FUNC_redirect_map &&
8482 func_id != BPF_FUNC_map_lookup_elem)
8485 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8486 case BPF_MAP_TYPE_HASH_OF_MAPS:
8487 if (func_id != BPF_FUNC_map_lookup_elem)
8490 case BPF_MAP_TYPE_SOCKMAP:
8491 if (func_id != BPF_FUNC_sk_redirect_map &&
8492 func_id != BPF_FUNC_sock_map_update &&
8493 func_id != BPF_FUNC_map_delete_elem &&
8494 func_id != BPF_FUNC_msg_redirect_map &&
8495 func_id != BPF_FUNC_sk_select_reuseport &&
8496 func_id != BPF_FUNC_map_lookup_elem &&
8497 !may_update_sockmap(env, func_id))
8500 case BPF_MAP_TYPE_SOCKHASH:
8501 if (func_id != BPF_FUNC_sk_redirect_hash &&
8502 func_id != BPF_FUNC_sock_hash_update &&
8503 func_id != BPF_FUNC_map_delete_elem &&
8504 func_id != BPF_FUNC_msg_redirect_hash &&
8505 func_id != BPF_FUNC_sk_select_reuseport &&
8506 func_id != BPF_FUNC_map_lookup_elem &&
8507 !may_update_sockmap(env, func_id))
8510 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8511 if (func_id != BPF_FUNC_sk_select_reuseport)
8514 case BPF_MAP_TYPE_QUEUE:
8515 case BPF_MAP_TYPE_STACK:
8516 if (func_id != BPF_FUNC_map_peek_elem &&
8517 func_id != BPF_FUNC_map_pop_elem &&
8518 func_id != BPF_FUNC_map_push_elem)
8521 case BPF_MAP_TYPE_SK_STORAGE:
8522 if (func_id != BPF_FUNC_sk_storage_get &&
8523 func_id != BPF_FUNC_sk_storage_delete &&
8524 func_id != BPF_FUNC_kptr_xchg)
8527 case BPF_MAP_TYPE_INODE_STORAGE:
8528 if (func_id != BPF_FUNC_inode_storage_get &&
8529 func_id != BPF_FUNC_inode_storage_delete &&
8530 func_id != BPF_FUNC_kptr_xchg)
8533 case BPF_MAP_TYPE_TASK_STORAGE:
8534 if (func_id != BPF_FUNC_task_storage_get &&
8535 func_id != BPF_FUNC_task_storage_delete &&
8536 func_id != BPF_FUNC_kptr_xchg)
8539 case BPF_MAP_TYPE_CGRP_STORAGE:
8540 if (func_id != BPF_FUNC_cgrp_storage_get &&
8541 func_id != BPF_FUNC_cgrp_storage_delete &&
8542 func_id != BPF_FUNC_kptr_xchg)
8545 case BPF_MAP_TYPE_BLOOM_FILTER:
8546 if (func_id != BPF_FUNC_map_peek_elem &&
8547 func_id != BPF_FUNC_map_push_elem)
8554 /* ... and second from the function itself. */
8556 case BPF_FUNC_tail_call:
8557 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8559 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8560 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8564 case BPF_FUNC_perf_event_read:
8565 case BPF_FUNC_perf_event_output:
8566 case BPF_FUNC_perf_event_read_value:
8567 case BPF_FUNC_skb_output:
8568 case BPF_FUNC_xdp_output:
8569 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8572 case BPF_FUNC_ringbuf_output:
8573 case BPF_FUNC_ringbuf_reserve:
8574 case BPF_FUNC_ringbuf_query:
8575 case BPF_FUNC_ringbuf_reserve_dynptr:
8576 case BPF_FUNC_ringbuf_submit_dynptr:
8577 case BPF_FUNC_ringbuf_discard_dynptr:
8578 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8581 case BPF_FUNC_user_ringbuf_drain:
8582 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8585 case BPF_FUNC_get_stackid:
8586 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8589 case BPF_FUNC_current_task_under_cgroup:
8590 case BPF_FUNC_skb_under_cgroup:
8591 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8594 case BPF_FUNC_redirect_map:
8595 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8596 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8597 map->map_type != BPF_MAP_TYPE_CPUMAP &&
8598 map->map_type != BPF_MAP_TYPE_XSKMAP)
8601 case BPF_FUNC_sk_redirect_map:
8602 case BPF_FUNC_msg_redirect_map:
8603 case BPF_FUNC_sock_map_update:
8604 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8607 case BPF_FUNC_sk_redirect_hash:
8608 case BPF_FUNC_msg_redirect_hash:
8609 case BPF_FUNC_sock_hash_update:
8610 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8613 case BPF_FUNC_get_local_storage:
8614 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8615 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8618 case BPF_FUNC_sk_select_reuseport:
8619 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8620 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8621 map->map_type != BPF_MAP_TYPE_SOCKHASH)
8624 case BPF_FUNC_map_pop_elem:
8625 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8626 map->map_type != BPF_MAP_TYPE_STACK)
8629 case BPF_FUNC_map_peek_elem:
8630 case BPF_FUNC_map_push_elem:
8631 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8632 map->map_type != BPF_MAP_TYPE_STACK &&
8633 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8636 case BPF_FUNC_map_lookup_percpu_elem:
8637 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8638 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8639 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8642 case BPF_FUNC_sk_storage_get:
8643 case BPF_FUNC_sk_storage_delete:
8644 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8647 case BPF_FUNC_inode_storage_get:
8648 case BPF_FUNC_inode_storage_delete:
8649 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8652 case BPF_FUNC_task_storage_get:
8653 case BPF_FUNC_task_storage_delete:
8654 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8657 case BPF_FUNC_cgrp_storage_get:
8658 case BPF_FUNC_cgrp_storage_delete:
8659 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8668 verbose(env, "cannot pass map_type %d into func %s#%d\n",
8669 map->map_type, func_id_name(func_id), func_id);
8673 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8677 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8679 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8681 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8683 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8685 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8688 /* We only support one arg being in raw mode at the moment,
8689 * which is sufficient for the helper functions we have
8695 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8697 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8698 bool has_size = fn->arg_size[arg] != 0;
8699 bool is_next_size = false;
8701 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8702 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8704 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8705 return is_next_size;
8707 return has_size == is_next_size || is_next_size == is_fixed;
8710 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8712 /* bpf_xxx(..., buf, len) call will access 'len'
8713 * bytes from memory 'buf'. Both arg types need
8714 * to be paired, so make sure there's no buggy
8715 * helper function specification.
8717 if (arg_type_is_mem_size(fn->arg1_type) ||
8718 check_args_pair_invalid(fn, 0) ||
8719 check_args_pair_invalid(fn, 1) ||
8720 check_args_pair_invalid(fn, 2) ||
8721 check_args_pair_invalid(fn, 3) ||
8722 check_args_pair_invalid(fn, 4))
8728 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8732 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8733 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8734 return !!fn->arg_btf_id[i];
8735 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8736 return fn->arg_btf_id[i] == BPF_PTR_POISON;
8737 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8738 /* arg_btf_id and arg_size are in a union. */
8739 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8740 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8747 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8749 return check_raw_mode_ok(fn) &&
8750 check_arg_pair_ok(fn) &&
8751 check_btf_id_ok(fn) ? 0 : -EINVAL;
8754 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8755 * are now invalid, so turn them into unknown SCALAR_VALUE.
8757 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8758 * since these slices point to packet data.
8760 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8762 struct bpf_func_state *state;
8763 struct bpf_reg_state *reg;
8765 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8766 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8767 mark_reg_invalid(env, reg);
8773 BEYOND_PKT_END = -2,
8776 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8778 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8779 struct bpf_reg_state *reg = &state->regs[regn];
8781 if (reg->type != PTR_TO_PACKET)
8782 /* PTR_TO_PACKET_META is not supported yet */
8785 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8786 * How far beyond pkt_end it goes is unknown.
8787 * if (!range_open) it's the case of pkt >= pkt_end
8788 * if (range_open) it's the case of pkt > pkt_end
8789 * hence this pointer is at least 1 byte bigger than pkt_end
8792 reg->range = BEYOND_PKT_END;
8794 reg->range = AT_PKT_END;
8797 /* The pointer with the specified id has released its reference to kernel
8798 * resources. Identify all copies of the same pointer and clear the reference.
8800 static int release_reference(struct bpf_verifier_env *env,
8803 struct bpf_func_state *state;
8804 struct bpf_reg_state *reg;
8807 err = release_reference_state(cur_func(env), ref_obj_id);
8811 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8812 if (reg->ref_obj_id == ref_obj_id)
8813 mark_reg_invalid(env, reg);
8819 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8821 struct bpf_func_state *unused;
8822 struct bpf_reg_state *reg;
8824 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8825 if (type_is_non_owning_ref(reg->type))
8826 mark_reg_invalid(env, reg);
8830 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8831 struct bpf_reg_state *regs)
8835 /* after the call registers r0 - r5 were scratched */
8836 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8837 mark_reg_not_init(env, regs, caller_saved[i]);
8838 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8842 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8843 struct bpf_func_state *caller,
8844 struct bpf_func_state *callee,
8847 static int set_callee_state(struct bpf_verifier_env *env,
8848 struct bpf_func_state *caller,
8849 struct bpf_func_state *callee, int insn_idx);
8851 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8852 int *insn_idx, int subprog,
8853 set_callee_state_fn set_callee_state_cb)
8855 struct bpf_verifier_state *state = env->cur_state;
8856 struct bpf_func_state *caller, *callee;
8859 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8860 verbose(env, "the call stack of %d frames is too deep\n",
8861 state->curframe + 2);
8865 caller = state->frame[state->curframe];
8866 if (state->frame[state->curframe + 1]) {
8867 verbose(env, "verifier bug. Frame %d already allocated\n",
8868 state->curframe + 1);
8872 err = btf_check_subprog_call(env, subprog, caller->regs);
8875 if (subprog_is_global(env, subprog)) {
8877 verbose(env, "Caller passes invalid args into func#%d\n",
8881 if (env->log.level & BPF_LOG_LEVEL)
8883 "Func#%d is global and valid. Skipping.\n",
8885 clear_caller_saved_regs(env, caller->regs);
8887 /* All global functions return a 64-bit SCALAR_VALUE */
8888 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8889 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8891 /* continue with next insn after call */
8896 /* set_callee_state is used for direct subprog calls, but we are
8897 * interested in validating only BPF helpers that can call subprogs as
8900 if (set_callee_state_cb != set_callee_state) {
8901 if (bpf_pseudo_kfunc_call(insn) &&
8902 !is_callback_calling_kfunc(insn->imm)) {
8903 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8904 func_id_name(insn->imm), insn->imm);
8906 } else if (!bpf_pseudo_kfunc_call(insn) &&
8907 !is_callback_calling_function(insn->imm)) { /* helper */
8908 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8909 func_id_name(insn->imm), insn->imm);
8914 if (insn->code == (BPF_JMP | BPF_CALL) &&
8915 insn->src_reg == 0 &&
8916 insn->imm == BPF_FUNC_timer_set_callback) {
8917 struct bpf_verifier_state *async_cb;
8919 /* there is no real recursion here. timer callbacks are async */
8920 env->subprog_info[subprog].is_async_cb = true;
8921 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8922 *insn_idx, subprog);
8925 callee = async_cb->frame[0];
8926 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8928 /* Convert bpf_timer_set_callback() args into timer callback args */
8929 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8933 clear_caller_saved_regs(env, caller->regs);
8934 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8935 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8936 /* continue with next insn after call */
8940 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8943 state->frame[state->curframe + 1] = callee;
8945 /* callee cannot access r0, r6 - r9 for reading and has to write
8946 * into its own stack before reading from it.
8947 * callee can read/write into caller's stack
8949 init_func_state(env, callee,
8950 /* remember the callsite, it will be used by bpf_exit */
8951 *insn_idx /* callsite */,
8952 state->curframe + 1 /* frameno within this callchain */,
8953 subprog /* subprog number within this prog */);
8955 /* Transfer references to the callee */
8956 err = copy_reference_state(callee, caller);
8960 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8964 clear_caller_saved_regs(env, caller->regs);
8966 /* only increment it after check_reg_arg() finished */
8969 /* and go analyze first insn of the callee */
8970 *insn_idx = env->subprog_info[subprog].start - 1;
8972 if (env->log.level & BPF_LOG_LEVEL) {
8973 verbose(env, "caller:\n");
8974 print_verifier_state(env, caller, true);
8975 verbose(env, "callee:\n");
8976 print_verifier_state(env, callee, true);
8981 free_func_state(callee);
8982 state->frame[state->curframe + 1] = NULL;
8986 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8987 struct bpf_func_state *caller,
8988 struct bpf_func_state *callee)
8990 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8991 * void *callback_ctx, u64 flags);
8992 * callback_fn(struct bpf_map *map, void *key, void *value,
8993 * void *callback_ctx);
8995 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8997 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8998 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8999 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9001 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9002 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9003 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9005 /* pointer to stack or null */
9006 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9009 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9013 static int set_callee_state(struct bpf_verifier_env *env,
9014 struct bpf_func_state *caller,
9015 struct bpf_func_state *callee, int insn_idx)
9019 /* copy r1 - r5 args that callee can access. The copy includes parent
9020 * pointers, which connects us up to the liveness chain
9022 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9023 callee->regs[i] = caller->regs[i];
9027 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9030 int subprog, target_insn;
9032 target_insn = *insn_idx + insn->imm + 1;
9033 subprog = find_subprog(env, target_insn);
9035 verbose(env, "verifier bug. No program starts at insn %d\n",
9040 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
9043 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9044 struct bpf_func_state *caller,
9045 struct bpf_func_state *callee,
9048 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9049 struct bpf_map *map;
9052 if (bpf_map_ptr_poisoned(insn_aux)) {
9053 verbose(env, "tail_call abusing map_ptr\n");
9057 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9058 if (!map->ops->map_set_for_each_callback_args ||
9059 !map->ops->map_for_each_callback) {
9060 verbose(env, "callback function not allowed for map\n");
9064 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9068 callee->in_callback_fn = true;
9069 callee->callback_ret_range = tnum_range(0, 1);
9073 static int set_loop_callback_state(struct bpf_verifier_env *env,
9074 struct bpf_func_state *caller,
9075 struct bpf_func_state *callee,
9078 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9080 * callback_fn(u32 index, void *callback_ctx);
9082 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9083 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9086 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9087 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9088 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9090 callee->in_callback_fn = true;
9091 callee->callback_ret_range = tnum_range(0, 1);
9095 static int set_timer_callback_state(struct bpf_verifier_env *env,
9096 struct bpf_func_state *caller,
9097 struct bpf_func_state *callee,
9100 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9102 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9103 * callback_fn(struct bpf_map *map, void *key, void *value);
9105 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9106 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9107 callee->regs[BPF_REG_1].map_ptr = map_ptr;
9109 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9110 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9111 callee->regs[BPF_REG_2].map_ptr = map_ptr;
9113 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9114 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9115 callee->regs[BPF_REG_3].map_ptr = map_ptr;
9118 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9119 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9120 callee->in_async_callback_fn = true;
9121 callee->callback_ret_range = tnum_range(0, 1);
9125 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9126 struct bpf_func_state *caller,
9127 struct bpf_func_state *callee,
9130 /* bpf_find_vma(struct task_struct *task, u64 addr,
9131 * void *callback_fn, void *callback_ctx, u64 flags)
9132 * (callback_fn)(struct task_struct *task,
9133 * struct vm_area_struct *vma, void *callback_ctx);
9135 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9137 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9138 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9139 callee->regs[BPF_REG_2].btf = btf_vmlinux;
9140 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9142 /* pointer to stack or null */
9143 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9146 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9147 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9148 callee->in_callback_fn = true;
9149 callee->callback_ret_range = tnum_range(0, 1);
9153 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9154 struct bpf_func_state *caller,
9155 struct bpf_func_state *callee,
9158 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9159 * callback_ctx, u64 flags);
9160 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9162 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9163 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9164 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9167 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9168 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9169 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9171 callee->in_callback_fn = true;
9172 callee->callback_ret_range = tnum_range(0, 1);
9176 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9177 struct bpf_func_state *caller,
9178 struct bpf_func_state *callee,
9181 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9182 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9184 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9185 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9186 * by this point, so look at 'root'
9188 struct btf_field *field;
9190 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9192 if (!field || !field->graph_root.value_btf_id)
9195 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9196 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9197 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9198 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9200 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9201 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9202 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9203 callee->in_callback_fn = true;
9204 callee->callback_ret_range = tnum_range(0, 1);
9208 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9210 /* Are we currently verifying the callback for a rbtree helper that must
9211 * be called with lock held? If so, no need to complain about unreleased
9214 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9216 struct bpf_verifier_state *state = env->cur_state;
9217 struct bpf_insn *insn = env->prog->insnsi;
9218 struct bpf_func_state *callee;
9221 if (!state->curframe)
9224 callee = state->frame[state->curframe];
9226 if (!callee->in_callback_fn)
9229 kfunc_btf_id = insn[callee->callsite].imm;
9230 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9233 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9235 struct bpf_verifier_state *state = env->cur_state;
9236 struct bpf_func_state *caller, *callee;
9237 struct bpf_reg_state *r0;
9240 callee = state->frame[state->curframe];
9241 r0 = &callee->regs[BPF_REG_0];
9242 if (r0->type == PTR_TO_STACK) {
9243 /* technically it's ok to return caller's stack pointer
9244 * (or caller's caller's pointer) back to the caller,
9245 * since these pointers are valid. Only current stack
9246 * pointer will be invalid as soon as function exits,
9247 * but let's be conservative
9249 verbose(env, "cannot return stack pointer to the caller\n");
9253 caller = state->frame[state->curframe - 1];
9254 if (callee->in_callback_fn) {
9255 /* enforce R0 return value range [0, 1]. */
9256 struct tnum range = callee->callback_ret_range;
9258 if (r0->type != SCALAR_VALUE) {
9259 verbose(env, "R0 not a scalar value\n");
9262 if (!tnum_in(range, r0->var_off)) {
9263 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9267 /* return to the caller whatever r0 had in the callee */
9268 caller->regs[BPF_REG_0] = *r0;
9271 /* callback_fn frame should have released its own additions to parent's
9272 * reference state at this point, or check_reference_leak would
9273 * complain, hence it must be the same as the caller. There is no need
9276 if (!callee->in_callback_fn) {
9277 /* Transfer references to the caller */
9278 err = copy_reference_state(caller, callee);
9283 *insn_idx = callee->callsite + 1;
9284 if (env->log.level & BPF_LOG_LEVEL) {
9285 verbose(env, "returning from callee:\n");
9286 print_verifier_state(env, callee, true);
9287 verbose(env, "to caller at %d:\n", *insn_idx);
9288 print_verifier_state(env, caller, true);
9290 /* clear everything in the callee */
9291 free_func_state(callee);
9292 state->frame[state->curframe--] = NULL;
9296 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9298 struct bpf_call_arg_meta *meta)
9300 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
9302 if (ret_type != RET_INTEGER)
9306 case BPF_FUNC_get_stack:
9307 case BPF_FUNC_get_task_stack:
9308 case BPF_FUNC_probe_read_str:
9309 case BPF_FUNC_probe_read_kernel_str:
9310 case BPF_FUNC_probe_read_user_str:
9311 ret_reg->smax_value = meta->msize_max_value;
9312 ret_reg->s32_max_value = meta->msize_max_value;
9313 ret_reg->smin_value = -MAX_ERRNO;
9314 ret_reg->s32_min_value = -MAX_ERRNO;
9315 reg_bounds_sync(ret_reg);
9317 case BPF_FUNC_get_smp_processor_id:
9318 ret_reg->umax_value = nr_cpu_ids - 1;
9319 ret_reg->u32_max_value = nr_cpu_ids - 1;
9320 ret_reg->smax_value = nr_cpu_ids - 1;
9321 ret_reg->s32_max_value = nr_cpu_ids - 1;
9322 ret_reg->umin_value = 0;
9323 ret_reg->u32_min_value = 0;
9324 ret_reg->smin_value = 0;
9325 ret_reg->s32_min_value = 0;
9326 reg_bounds_sync(ret_reg);
9332 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9333 int func_id, int insn_idx)
9335 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9336 struct bpf_map *map = meta->map_ptr;
9338 if (func_id != BPF_FUNC_tail_call &&
9339 func_id != BPF_FUNC_map_lookup_elem &&
9340 func_id != BPF_FUNC_map_update_elem &&
9341 func_id != BPF_FUNC_map_delete_elem &&
9342 func_id != BPF_FUNC_map_push_elem &&
9343 func_id != BPF_FUNC_map_pop_elem &&
9344 func_id != BPF_FUNC_map_peek_elem &&
9345 func_id != BPF_FUNC_for_each_map_elem &&
9346 func_id != BPF_FUNC_redirect_map &&
9347 func_id != BPF_FUNC_map_lookup_percpu_elem)
9351 verbose(env, "kernel subsystem misconfigured verifier\n");
9355 /* In case of read-only, some additional restrictions
9356 * need to be applied in order to prevent altering the
9357 * state of the map from program side.
9359 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9360 (func_id == BPF_FUNC_map_delete_elem ||
9361 func_id == BPF_FUNC_map_update_elem ||
9362 func_id == BPF_FUNC_map_push_elem ||
9363 func_id == BPF_FUNC_map_pop_elem)) {
9364 verbose(env, "write into map forbidden\n");
9368 if (!BPF_MAP_PTR(aux->map_ptr_state))
9369 bpf_map_ptr_store(aux, meta->map_ptr,
9370 !meta->map_ptr->bypass_spec_v1);
9371 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9372 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9373 !meta->map_ptr->bypass_spec_v1);
9378 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9379 int func_id, int insn_idx)
9381 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9382 struct bpf_reg_state *regs = cur_regs(env), *reg;
9383 struct bpf_map *map = meta->map_ptr;
9387 if (func_id != BPF_FUNC_tail_call)
9389 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9390 verbose(env, "kernel subsystem misconfigured verifier\n");
9394 reg = ®s[BPF_REG_3];
9395 val = reg->var_off.value;
9396 max = map->max_entries;
9398 if (!(register_is_const(reg) && val < max)) {
9399 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9403 err = mark_chain_precision(env, BPF_REG_3);
9406 if (bpf_map_key_unseen(aux))
9407 bpf_map_key_store(aux, val);
9408 else if (!bpf_map_key_poisoned(aux) &&
9409 bpf_map_key_immediate(aux) != val)
9410 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9414 static int check_reference_leak(struct bpf_verifier_env *env)
9416 struct bpf_func_state *state = cur_func(env);
9417 bool refs_lingering = false;
9420 if (state->frameno && !state->in_callback_fn)
9423 for (i = 0; i < state->acquired_refs; i++) {
9424 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9426 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9427 state->refs[i].id, state->refs[i].insn_idx);
9428 refs_lingering = true;
9430 return refs_lingering ? -EINVAL : 0;
9433 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9434 struct bpf_reg_state *regs)
9436 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
9437 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
9438 struct bpf_map *fmt_map = fmt_reg->map_ptr;
9439 struct bpf_bprintf_data data = {};
9440 int err, fmt_map_off, num_args;
9444 /* data must be an array of u64 */
9445 if (data_len_reg->var_off.value % 8)
9447 num_args = data_len_reg->var_off.value / 8;
9449 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9450 * and map_direct_value_addr is set.
9452 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9453 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9456 verbose(env, "verifier bug\n");
9459 fmt = (char *)(long)fmt_addr + fmt_map_off;
9461 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9462 * can focus on validating the format specifiers.
9464 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9466 verbose(env, "Invalid format string\n");
9471 static int check_get_func_ip(struct bpf_verifier_env *env)
9473 enum bpf_prog_type type = resolve_prog_type(env->prog);
9474 int func_id = BPF_FUNC_get_func_ip;
9476 if (type == BPF_PROG_TYPE_TRACING) {
9477 if (!bpf_prog_has_trampoline(env->prog)) {
9478 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9479 func_id_name(func_id), func_id);
9483 } else if (type == BPF_PROG_TYPE_KPROBE) {
9487 verbose(env, "func %s#%d not supported for program type %d\n",
9488 func_id_name(func_id), func_id, type);
9492 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9494 return &env->insn_aux_data[env->insn_idx];
9497 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9499 struct bpf_reg_state *regs = cur_regs(env);
9500 struct bpf_reg_state *reg = ®s[BPF_REG_4];
9501 bool reg_is_null = register_is_null(reg);
9504 mark_chain_precision(env, BPF_REG_4);
9509 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9511 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9513 if (!state->initialized) {
9514 state->initialized = 1;
9515 state->fit_for_inline = loop_flag_is_zero(env);
9516 state->callback_subprogno = subprogno;
9520 if (!state->fit_for_inline)
9523 state->fit_for_inline = (loop_flag_is_zero(env) &&
9524 state->callback_subprogno == subprogno);
9527 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9530 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9531 const struct bpf_func_proto *fn = NULL;
9532 enum bpf_return_type ret_type;
9533 enum bpf_type_flag ret_flag;
9534 struct bpf_reg_state *regs;
9535 struct bpf_call_arg_meta meta;
9536 int insn_idx = *insn_idx_p;
9538 int i, err, func_id;
9540 /* find function prototype */
9541 func_id = insn->imm;
9542 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9543 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9548 if (env->ops->get_func_proto)
9549 fn = env->ops->get_func_proto(func_id, env->prog);
9551 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9556 /* eBPF programs must be GPL compatible to use GPL-ed functions */
9557 if (!env->prog->gpl_compatible && fn->gpl_only) {
9558 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9562 if (fn->allowed && !fn->allowed(env->prog)) {
9563 verbose(env, "helper call is not allowed in probe\n");
9567 if (!env->prog->aux->sleepable && fn->might_sleep) {
9568 verbose(env, "helper call might sleep in a non-sleepable prog\n");
9572 /* With LD_ABS/IND some JITs save/restore skb from r1. */
9573 changes_data = bpf_helper_changes_pkt_data(fn->func);
9574 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9575 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9576 func_id_name(func_id), func_id);
9580 memset(&meta, 0, sizeof(meta));
9581 meta.pkt_access = fn->pkt_access;
9583 err = check_func_proto(fn, func_id);
9585 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9586 func_id_name(func_id), func_id);
9590 if (env->cur_state->active_rcu_lock) {
9591 if (fn->might_sleep) {
9592 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9593 func_id_name(func_id), func_id);
9597 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9598 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9601 meta.func_id = func_id;
9603 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9604 err = check_func_arg(env, i, &meta, fn, insn_idx);
9609 err = record_func_map(env, &meta, func_id, insn_idx);
9613 err = record_func_key(env, &meta, func_id, insn_idx);
9617 /* Mark slots with STACK_MISC in case of raw mode, stack offset
9618 * is inferred from register state.
9620 for (i = 0; i < meta.access_size; i++) {
9621 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9622 BPF_WRITE, -1, false, false);
9627 regs = cur_regs(env);
9629 if (meta.release_regno) {
9631 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9632 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9633 * is safe to do directly.
9635 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9636 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9637 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9640 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
9641 } else if (meta.ref_obj_id) {
9642 err = release_reference(env, meta.ref_obj_id);
9643 } else if (register_is_null(®s[meta.release_regno])) {
9644 /* meta.ref_obj_id can only be 0 if register that is meant to be
9645 * released is NULL, which must be > R0.
9650 verbose(env, "func %s#%d reference has not been acquired before\n",
9651 func_id_name(func_id), func_id);
9657 case BPF_FUNC_tail_call:
9658 err = check_reference_leak(env);
9660 verbose(env, "tail_call would lead to reference leak\n");
9664 case BPF_FUNC_get_local_storage:
9665 /* check that flags argument in get_local_storage(map, flags) is 0,
9666 * this is required because get_local_storage() can't return an error.
9668 if (!register_is_null(®s[BPF_REG_2])) {
9669 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9673 case BPF_FUNC_for_each_map_elem:
9674 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9675 set_map_elem_callback_state);
9677 case BPF_FUNC_timer_set_callback:
9678 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9679 set_timer_callback_state);
9681 case BPF_FUNC_find_vma:
9682 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9683 set_find_vma_callback_state);
9685 case BPF_FUNC_snprintf:
9686 err = check_bpf_snprintf_call(env, regs);
9689 update_loop_inline_state(env, meta.subprogno);
9690 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9691 set_loop_callback_state);
9693 case BPF_FUNC_dynptr_from_mem:
9694 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9695 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9696 reg_type_str(env, regs[BPF_REG_1].type));
9700 case BPF_FUNC_set_retval:
9701 if (prog_type == BPF_PROG_TYPE_LSM &&
9702 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9703 if (!env->prog->aux->attach_func_proto->type) {
9704 /* Make sure programs that attach to void
9705 * hooks don't try to modify return value.
9707 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9712 case BPF_FUNC_dynptr_data:
9714 struct bpf_reg_state *reg;
9717 reg = get_dynptr_arg_reg(env, fn, regs);
9722 if (meta.dynptr_id) {
9723 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9726 if (meta.ref_obj_id) {
9727 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9731 id = dynptr_id(env, reg);
9733 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9737 ref_obj_id = dynptr_ref_obj_id(env, reg);
9738 if (ref_obj_id < 0) {
9739 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9743 meta.dynptr_id = id;
9744 meta.ref_obj_id = ref_obj_id;
9748 case BPF_FUNC_dynptr_write:
9750 enum bpf_dynptr_type dynptr_type;
9751 struct bpf_reg_state *reg;
9753 reg = get_dynptr_arg_reg(env, fn, regs);
9757 dynptr_type = dynptr_get_type(env, reg);
9758 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9761 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9762 /* this will trigger clear_all_pkt_pointers(), which will
9763 * invalidate all dynptr slices associated with the skb
9765 changes_data = true;
9769 case BPF_FUNC_user_ringbuf_drain:
9770 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9771 set_user_ringbuf_callback_state);
9778 /* reset caller saved regs */
9779 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9780 mark_reg_not_init(env, regs, caller_saved[i]);
9781 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9784 /* helper call returns 64-bit value. */
9785 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9787 /* update return register (already marked as written above) */
9788 ret_type = fn->ret_type;
9789 ret_flag = type_flag(ret_type);
9791 switch (base_type(ret_type)) {
9793 /* sets type to SCALAR_VALUE */
9794 mark_reg_unknown(env, regs, BPF_REG_0);
9797 regs[BPF_REG_0].type = NOT_INIT;
9799 case RET_PTR_TO_MAP_VALUE:
9800 /* There is no offset yet applied, variable or fixed */
9801 mark_reg_known_zero(env, regs, BPF_REG_0);
9802 /* remember map_ptr, so that check_map_access()
9803 * can check 'value_size' boundary of memory access
9804 * to map element returned from bpf_map_lookup_elem()
9806 if (meta.map_ptr == NULL) {
9808 "kernel subsystem misconfigured verifier\n");
9811 regs[BPF_REG_0].map_ptr = meta.map_ptr;
9812 regs[BPF_REG_0].map_uid = meta.map_uid;
9813 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9814 if (!type_may_be_null(ret_type) &&
9815 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9816 regs[BPF_REG_0].id = ++env->id_gen;
9819 case RET_PTR_TO_SOCKET:
9820 mark_reg_known_zero(env, regs, BPF_REG_0);
9821 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9823 case RET_PTR_TO_SOCK_COMMON:
9824 mark_reg_known_zero(env, regs, BPF_REG_0);
9825 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9827 case RET_PTR_TO_TCP_SOCK:
9828 mark_reg_known_zero(env, regs, BPF_REG_0);
9829 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9831 case RET_PTR_TO_MEM:
9832 mark_reg_known_zero(env, regs, BPF_REG_0);
9833 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9834 regs[BPF_REG_0].mem_size = meta.mem_size;
9836 case RET_PTR_TO_MEM_OR_BTF_ID:
9838 const struct btf_type *t;
9840 mark_reg_known_zero(env, regs, BPF_REG_0);
9841 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9842 if (!btf_type_is_struct(t)) {
9844 const struct btf_type *ret;
9847 /* resolve the type size of ksym. */
9848 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9850 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9851 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9852 tname, PTR_ERR(ret));
9855 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9856 regs[BPF_REG_0].mem_size = tsize;
9858 /* MEM_RDONLY may be carried from ret_flag, but it
9859 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9860 * it will confuse the check of PTR_TO_BTF_ID in
9861 * check_mem_access().
9863 ret_flag &= ~MEM_RDONLY;
9865 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9866 regs[BPF_REG_0].btf = meta.ret_btf;
9867 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9871 case RET_PTR_TO_BTF_ID:
9873 struct btf *ret_btf;
9876 mark_reg_known_zero(env, regs, BPF_REG_0);
9877 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9878 if (func_id == BPF_FUNC_kptr_xchg) {
9879 ret_btf = meta.kptr_field->kptr.btf;
9880 ret_btf_id = meta.kptr_field->kptr.btf_id;
9881 if (!btf_is_kernel(ret_btf))
9882 regs[BPF_REG_0].type |= MEM_ALLOC;
9884 if (fn->ret_btf_id == BPF_PTR_POISON) {
9885 verbose(env, "verifier internal error:");
9886 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9887 func_id_name(func_id));
9890 ret_btf = btf_vmlinux;
9891 ret_btf_id = *fn->ret_btf_id;
9893 if (ret_btf_id == 0) {
9894 verbose(env, "invalid return type %u of func %s#%d\n",
9895 base_type(ret_type), func_id_name(func_id),
9899 regs[BPF_REG_0].btf = ret_btf;
9900 regs[BPF_REG_0].btf_id = ret_btf_id;
9904 verbose(env, "unknown return type %u of func %s#%d\n",
9905 base_type(ret_type), func_id_name(func_id), func_id);
9909 if (type_may_be_null(regs[BPF_REG_0].type))
9910 regs[BPF_REG_0].id = ++env->id_gen;
9912 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9913 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9914 func_id_name(func_id), func_id);
9918 if (is_dynptr_ref_function(func_id))
9919 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9921 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9922 /* For release_reference() */
9923 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9924 } else if (is_acquire_function(func_id, meta.map_ptr)) {
9925 int id = acquire_reference_state(env, insn_idx);
9929 /* For mark_ptr_or_null_reg() */
9930 regs[BPF_REG_0].id = id;
9931 /* For release_reference() */
9932 regs[BPF_REG_0].ref_obj_id = id;
9935 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9937 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9941 if ((func_id == BPF_FUNC_get_stack ||
9942 func_id == BPF_FUNC_get_task_stack) &&
9943 !env->prog->has_callchain_buf) {
9944 const char *err_str;
9946 #ifdef CONFIG_PERF_EVENTS
9947 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9948 err_str = "cannot get callchain buffer for func %s#%d\n";
9951 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9954 verbose(env, err_str, func_id_name(func_id), func_id);
9958 env->prog->has_callchain_buf = true;
9961 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9962 env->prog->call_get_stack = true;
9964 if (func_id == BPF_FUNC_get_func_ip) {
9965 if (check_get_func_ip(env))
9967 env->prog->call_get_func_ip = true;
9971 clear_all_pkt_pointers(env);
9975 /* mark_btf_func_reg_size() is used when the reg size is determined by
9976 * the BTF func_proto's return value size and argument.
9978 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9981 struct bpf_reg_state *reg = &cur_regs(env)[regno];
9983 if (regno == BPF_REG_0) {
9984 /* Function return value */
9985 reg->live |= REG_LIVE_WRITTEN;
9986 reg->subreg_def = reg_size == sizeof(u64) ?
9987 DEF_NOT_SUBREG : env->insn_idx + 1;
9989 /* Function argument */
9990 if (reg_size == sizeof(u64)) {
9991 mark_insn_zext(env, reg);
9992 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9994 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9999 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10001 return meta->kfunc_flags & KF_ACQUIRE;
10004 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10006 return meta->kfunc_flags & KF_RELEASE;
10009 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10011 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10014 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10016 return meta->kfunc_flags & KF_SLEEPABLE;
10019 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10021 return meta->kfunc_flags & KF_DESTRUCTIVE;
10024 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10026 return meta->kfunc_flags & KF_RCU;
10029 static bool __kfunc_param_match_suffix(const struct btf *btf,
10030 const struct btf_param *arg,
10031 const char *suffix)
10033 int suffix_len = strlen(suffix), len;
10034 const char *param_name;
10036 /* In the future, this can be ported to use BTF tagging */
10037 param_name = btf_name_by_offset(btf, arg->name_off);
10038 if (str_is_empty(param_name))
10040 len = strlen(param_name);
10041 if (len < suffix_len)
10043 param_name += len - suffix_len;
10044 return !strncmp(param_name, suffix, suffix_len);
10047 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10048 const struct btf_param *arg,
10049 const struct bpf_reg_state *reg)
10051 const struct btf_type *t;
10053 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10054 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10057 return __kfunc_param_match_suffix(btf, arg, "__sz");
10060 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10061 const struct btf_param *arg,
10062 const struct bpf_reg_state *reg)
10064 const struct btf_type *t;
10066 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10067 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10070 return __kfunc_param_match_suffix(btf, arg, "__szk");
10073 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10075 return __kfunc_param_match_suffix(btf, arg, "__opt");
10078 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10080 return __kfunc_param_match_suffix(btf, arg, "__k");
10083 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10085 return __kfunc_param_match_suffix(btf, arg, "__ign");
10088 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10090 return __kfunc_param_match_suffix(btf, arg, "__alloc");
10093 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10095 return __kfunc_param_match_suffix(btf, arg, "__uninit");
10098 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10100 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10103 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10104 const struct btf_param *arg,
10107 int len, target_len = strlen(name);
10108 const char *param_name;
10110 param_name = btf_name_by_offset(btf, arg->name_off);
10111 if (str_is_empty(param_name))
10113 len = strlen(param_name);
10114 if (len != target_len)
10116 if (strcmp(param_name, name))
10124 KF_ARG_LIST_HEAD_ID,
10125 KF_ARG_LIST_NODE_ID,
10130 BTF_ID_LIST(kf_arg_btf_ids)
10131 BTF_ID(struct, bpf_dynptr_kern)
10132 BTF_ID(struct, bpf_list_head)
10133 BTF_ID(struct, bpf_list_node)
10134 BTF_ID(struct, bpf_rb_root)
10135 BTF_ID(struct, bpf_rb_node)
10137 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10138 const struct btf_param *arg, int type)
10140 const struct btf_type *t;
10143 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10146 if (!btf_type_is_ptr(t))
10148 t = btf_type_skip_modifiers(btf, t->type, &res_id);
10151 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10154 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10156 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10159 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10161 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10164 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10166 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10169 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10171 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10174 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10176 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10179 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10180 const struct btf_param *arg)
10182 const struct btf_type *t;
10184 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10191 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10192 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10193 const struct btf *btf,
10194 const struct btf_type *t, int rec)
10196 const struct btf_type *member_type;
10197 const struct btf_member *member;
10200 if (!btf_type_is_struct(t))
10203 for_each_member(i, t, member) {
10204 const struct btf_array *array;
10206 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10207 if (btf_type_is_struct(member_type)) {
10209 verbose(env, "max struct nesting depth exceeded\n");
10212 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10216 if (btf_type_is_array(member_type)) {
10217 array = btf_array(member_type);
10218 if (!array->nelems)
10220 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10221 if (!btf_type_is_scalar(member_type))
10225 if (!btf_type_is_scalar(member_type))
10231 enum kfunc_ptr_arg_type {
10233 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
10234 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10235 KF_ARG_PTR_TO_DYNPTR,
10236 KF_ARG_PTR_TO_ITER,
10237 KF_ARG_PTR_TO_LIST_HEAD,
10238 KF_ARG_PTR_TO_LIST_NODE,
10239 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
10241 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
10242 KF_ARG_PTR_TO_CALLBACK,
10243 KF_ARG_PTR_TO_RB_ROOT,
10244 KF_ARG_PTR_TO_RB_NODE,
10247 enum special_kfunc_type {
10248 KF_bpf_obj_new_impl,
10249 KF_bpf_obj_drop_impl,
10250 KF_bpf_refcount_acquire_impl,
10251 KF_bpf_list_push_front_impl,
10252 KF_bpf_list_push_back_impl,
10253 KF_bpf_list_pop_front,
10254 KF_bpf_list_pop_back,
10255 KF_bpf_cast_to_kern_ctx,
10256 KF_bpf_rdonly_cast,
10257 KF_bpf_rcu_read_lock,
10258 KF_bpf_rcu_read_unlock,
10259 KF_bpf_rbtree_remove,
10260 KF_bpf_rbtree_add_impl,
10261 KF_bpf_rbtree_first,
10262 KF_bpf_dynptr_from_skb,
10263 KF_bpf_dynptr_from_xdp,
10264 KF_bpf_dynptr_slice,
10265 KF_bpf_dynptr_slice_rdwr,
10266 KF_bpf_dynptr_clone,
10269 BTF_SET_START(special_kfunc_set)
10270 BTF_ID(func, bpf_obj_new_impl)
10271 BTF_ID(func, bpf_obj_drop_impl)
10272 BTF_ID(func, bpf_refcount_acquire_impl)
10273 BTF_ID(func, bpf_list_push_front_impl)
10274 BTF_ID(func, bpf_list_push_back_impl)
10275 BTF_ID(func, bpf_list_pop_front)
10276 BTF_ID(func, bpf_list_pop_back)
10277 BTF_ID(func, bpf_cast_to_kern_ctx)
10278 BTF_ID(func, bpf_rdonly_cast)
10279 BTF_ID(func, bpf_rbtree_remove)
10280 BTF_ID(func, bpf_rbtree_add_impl)
10281 BTF_ID(func, bpf_rbtree_first)
10282 BTF_ID(func, bpf_dynptr_from_skb)
10283 BTF_ID(func, bpf_dynptr_from_xdp)
10284 BTF_ID(func, bpf_dynptr_slice)
10285 BTF_ID(func, bpf_dynptr_slice_rdwr)
10286 BTF_ID(func, bpf_dynptr_clone)
10287 BTF_SET_END(special_kfunc_set)
10289 BTF_ID_LIST(special_kfunc_list)
10290 BTF_ID(func, bpf_obj_new_impl)
10291 BTF_ID(func, bpf_obj_drop_impl)
10292 BTF_ID(func, bpf_refcount_acquire_impl)
10293 BTF_ID(func, bpf_list_push_front_impl)
10294 BTF_ID(func, bpf_list_push_back_impl)
10295 BTF_ID(func, bpf_list_pop_front)
10296 BTF_ID(func, bpf_list_pop_back)
10297 BTF_ID(func, bpf_cast_to_kern_ctx)
10298 BTF_ID(func, bpf_rdonly_cast)
10299 BTF_ID(func, bpf_rcu_read_lock)
10300 BTF_ID(func, bpf_rcu_read_unlock)
10301 BTF_ID(func, bpf_rbtree_remove)
10302 BTF_ID(func, bpf_rbtree_add_impl)
10303 BTF_ID(func, bpf_rbtree_first)
10304 BTF_ID(func, bpf_dynptr_from_skb)
10305 BTF_ID(func, bpf_dynptr_from_xdp)
10306 BTF_ID(func, bpf_dynptr_slice)
10307 BTF_ID(func, bpf_dynptr_slice_rdwr)
10308 BTF_ID(func, bpf_dynptr_clone)
10310 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10312 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10313 meta->arg_owning_ref) {
10317 return meta->kfunc_flags & KF_RET_NULL;
10320 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10322 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10325 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10327 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10330 static enum kfunc_ptr_arg_type
10331 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10332 struct bpf_kfunc_call_arg_meta *meta,
10333 const struct btf_type *t, const struct btf_type *ref_t,
10334 const char *ref_tname, const struct btf_param *args,
10335 int argno, int nargs)
10337 u32 regno = argno + 1;
10338 struct bpf_reg_state *regs = cur_regs(env);
10339 struct bpf_reg_state *reg = ®s[regno];
10340 bool arg_mem_size = false;
10342 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10343 return KF_ARG_PTR_TO_CTX;
10345 /* In this function, we verify the kfunc's BTF as per the argument type,
10346 * leaving the rest of the verification with respect to the register
10347 * type to our caller. When a set of conditions hold in the BTF type of
10348 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10350 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10351 return KF_ARG_PTR_TO_CTX;
10353 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10354 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10356 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10357 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10359 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10360 return KF_ARG_PTR_TO_DYNPTR;
10362 if (is_kfunc_arg_iter(meta, argno))
10363 return KF_ARG_PTR_TO_ITER;
10365 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10366 return KF_ARG_PTR_TO_LIST_HEAD;
10368 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10369 return KF_ARG_PTR_TO_LIST_NODE;
10371 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10372 return KF_ARG_PTR_TO_RB_ROOT;
10374 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10375 return KF_ARG_PTR_TO_RB_NODE;
10377 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10378 if (!btf_type_is_struct(ref_t)) {
10379 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10380 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10383 return KF_ARG_PTR_TO_BTF_ID;
10386 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10387 return KF_ARG_PTR_TO_CALLBACK;
10390 if (argno + 1 < nargs &&
10391 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
10392 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
10393 arg_mem_size = true;
10395 /* This is the catch all argument type of register types supported by
10396 * check_helper_mem_access. However, we only allow when argument type is
10397 * pointer to scalar, or struct composed (recursively) of scalars. When
10398 * arg_mem_size is true, the pointer can be void *.
10400 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10401 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10402 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10403 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10406 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10409 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10410 struct bpf_reg_state *reg,
10411 const struct btf_type *ref_t,
10412 const char *ref_tname, u32 ref_id,
10413 struct bpf_kfunc_call_arg_meta *meta,
10416 const struct btf_type *reg_ref_t;
10417 bool strict_type_match = false;
10418 const struct btf *reg_btf;
10419 const char *reg_ref_tname;
10422 if (base_type(reg->type) == PTR_TO_BTF_ID) {
10423 reg_btf = reg->btf;
10424 reg_ref_id = reg->btf_id;
10426 reg_btf = btf_vmlinux;
10427 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10430 /* Enforce strict type matching for calls to kfuncs that are acquiring
10431 * or releasing a reference, or are no-cast aliases. We do _not_
10432 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10433 * as we want to enable BPF programs to pass types that are bitwise
10434 * equivalent without forcing them to explicitly cast with something
10435 * like bpf_cast_to_kern_ctx().
10437 * For example, say we had a type like the following:
10439 * struct bpf_cpumask {
10440 * cpumask_t cpumask;
10441 * refcount_t usage;
10444 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10445 * to a struct cpumask, so it would be safe to pass a struct
10446 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10448 * The philosophy here is similar to how we allow scalars of different
10449 * types to be passed to kfuncs as long as the size is the same. The
10450 * only difference here is that we're simply allowing
10451 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10454 if (is_kfunc_acquire(meta) ||
10455 (is_kfunc_release(meta) && reg->ref_obj_id) ||
10456 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10457 strict_type_match = true;
10459 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10461 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
10462 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10463 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10464 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10465 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10466 btf_type_str(reg_ref_t), reg_ref_tname);
10472 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10474 struct bpf_verifier_state *state = env->cur_state;
10476 if (!state->active_lock.ptr) {
10477 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10481 if (type_flag(reg->type) & NON_OWN_REF) {
10482 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10486 reg->type |= NON_OWN_REF;
10490 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10492 struct bpf_func_state *state, *unused;
10493 struct bpf_reg_state *reg;
10496 state = cur_func(env);
10499 verbose(env, "verifier internal error: ref_obj_id is zero for "
10500 "owning -> non-owning conversion\n");
10504 for (i = 0; i < state->acquired_refs; i++) {
10505 if (state->refs[i].id != ref_obj_id)
10508 /* Clear ref_obj_id here so release_reference doesn't clobber
10511 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10512 if (reg->ref_obj_id == ref_obj_id) {
10513 reg->ref_obj_id = 0;
10514 ref_set_non_owning(env, reg);
10520 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10524 /* Implementation details:
10526 * Each register points to some region of memory, which we define as an
10527 * allocation. Each allocation may embed a bpf_spin_lock which protects any
10528 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10529 * allocation. The lock and the data it protects are colocated in the same
10532 * Hence, everytime a register holds a pointer value pointing to such
10533 * allocation, the verifier preserves a unique reg->id for it.
10535 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10536 * bpf_spin_lock is called.
10538 * To enable this, lock state in the verifier captures two values:
10539 * active_lock.ptr = Register's type specific pointer
10540 * active_lock.id = A unique ID for each register pointer value
10542 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10543 * supported register types.
10545 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10546 * allocated objects is the reg->btf pointer.
10548 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10549 * can establish the provenance of the map value statically for each distinct
10550 * lookup into such maps. They always contain a single map value hence unique
10551 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10553 * So, in case of global variables, they use array maps with max_entries = 1,
10554 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10555 * into the same map value as max_entries is 1, as described above).
10557 * In case of inner map lookups, the inner map pointer has same map_ptr as the
10558 * outer map pointer (in verifier context), but each lookup into an inner map
10559 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10560 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10561 * will get different reg->id assigned to each lookup, hence different
10564 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10565 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10566 * returned from bpf_obj_new. Each allocation receives a new reg->id.
10568 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10573 switch ((int)reg->type) {
10574 case PTR_TO_MAP_VALUE:
10575 ptr = reg->map_ptr;
10577 case PTR_TO_BTF_ID | MEM_ALLOC:
10581 verbose(env, "verifier internal error: unknown reg type for lock check\n");
10586 if (!env->cur_state->active_lock.ptr)
10588 if (env->cur_state->active_lock.ptr != ptr ||
10589 env->cur_state->active_lock.id != id) {
10590 verbose(env, "held lock and object are not in the same allocation\n");
10596 static bool is_bpf_list_api_kfunc(u32 btf_id)
10598 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10599 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10600 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10601 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10604 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10606 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10607 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10608 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10611 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10613 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10614 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10617 static bool is_callback_calling_kfunc(u32 btf_id)
10619 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10622 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10624 return is_bpf_rbtree_api_kfunc(btf_id);
10627 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10628 enum btf_field_type head_field_type,
10633 switch (head_field_type) {
10634 case BPF_LIST_HEAD:
10635 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10638 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10641 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10642 btf_field_type_name(head_field_type));
10647 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10648 btf_field_type_name(head_field_type));
10652 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10653 enum btf_field_type node_field_type,
10658 switch (node_field_type) {
10659 case BPF_LIST_NODE:
10660 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10661 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10664 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10665 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10668 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10669 btf_field_type_name(node_field_type));
10674 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10675 btf_field_type_name(node_field_type));
10680 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10681 struct bpf_reg_state *reg, u32 regno,
10682 struct bpf_kfunc_call_arg_meta *meta,
10683 enum btf_field_type head_field_type,
10684 struct btf_field **head_field)
10686 const char *head_type_name;
10687 struct btf_field *field;
10688 struct btf_record *rec;
10691 if (meta->btf != btf_vmlinux) {
10692 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10696 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10699 head_type_name = btf_field_type_name(head_field_type);
10700 if (!tnum_is_const(reg->var_off)) {
10702 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10703 regno, head_type_name);
10707 rec = reg_btf_record(reg);
10708 head_off = reg->off + reg->var_off.value;
10709 field = btf_record_find(rec, head_off, head_field_type);
10711 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10715 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10716 if (check_reg_allocation_locked(env, reg)) {
10717 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10718 rec->spin_lock_off, head_type_name);
10723 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10726 *head_field = field;
10730 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10731 struct bpf_reg_state *reg, u32 regno,
10732 struct bpf_kfunc_call_arg_meta *meta)
10734 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10735 &meta->arg_list_head.field);
10738 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10739 struct bpf_reg_state *reg, u32 regno,
10740 struct bpf_kfunc_call_arg_meta *meta)
10742 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10743 &meta->arg_rbtree_root.field);
10747 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10748 struct bpf_reg_state *reg, u32 regno,
10749 struct bpf_kfunc_call_arg_meta *meta,
10750 enum btf_field_type head_field_type,
10751 enum btf_field_type node_field_type,
10752 struct btf_field **node_field)
10754 const char *node_type_name;
10755 const struct btf_type *et, *t;
10756 struct btf_field *field;
10759 if (meta->btf != btf_vmlinux) {
10760 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10764 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10767 node_type_name = btf_field_type_name(node_field_type);
10768 if (!tnum_is_const(reg->var_off)) {
10770 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10771 regno, node_type_name);
10775 node_off = reg->off + reg->var_off.value;
10776 field = reg_find_field_offset(reg, node_off, node_field_type);
10777 if (!field || field->offset != node_off) {
10778 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10782 field = *node_field;
10784 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10785 t = btf_type_by_id(reg->btf, reg->btf_id);
10786 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10787 field->graph_root.value_btf_id, true)) {
10788 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10789 "in struct %s, but arg is at offset=%d in struct %s\n",
10790 btf_field_type_name(head_field_type),
10791 btf_field_type_name(node_field_type),
10792 field->graph_root.node_offset,
10793 btf_name_by_offset(field->graph_root.btf, et->name_off),
10794 node_off, btf_name_by_offset(reg->btf, t->name_off));
10797 meta->arg_btf = reg->btf;
10798 meta->arg_btf_id = reg->btf_id;
10800 if (node_off != field->graph_root.node_offset) {
10801 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10802 node_off, btf_field_type_name(node_field_type),
10803 field->graph_root.node_offset,
10804 btf_name_by_offset(field->graph_root.btf, et->name_off));
10811 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10812 struct bpf_reg_state *reg, u32 regno,
10813 struct bpf_kfunc_call_arg_meta *meta)
10815 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10816 BPF_LIST_HEAD, BPF_LIST_NODE,
10817 &meta->arg_list_head.field);
10820 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10821 struct bpf_reg_state *reg, u32 regno,
10822 struct bpf_kfunc_call_arg_meta *meta)
10824 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10825 BPF_RB_ROOT, BPF_RB_NODE,
10826 &meta->arg_rbtree_root.field);
10829 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10832 const char *func_name = meta->func_name, *ref_tname;
10833 const struct btf *btf = meta->btf;
10834 const struct btf_param *args;
10835 struct btf_record *rec;
10839 args = (const struct btf_param *)(meta->func_proto + 1);
10840 nargs = btf_type_vlen(meta->func_proto);
10841 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10842 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10843 MAX_BPF_FUNC_REG_ARGS);
10847 /* Check that BTF function arguments match actual types that the
10850 for (i = 0; i < nargs; i++) {
10851 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
10852 const struct btf_type *t, *ref_t, *resolve_ret;
10853 enum bpf_arg_type arg_type = ARG_DONTCARE;
10854 u32 regno = i + 1, ref_id, type_size;
10855 bool is_ret_buf_sz = false;
10858 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10860 if (is_kfunc_arg_ignore(btf, &args[i]))
10863 if (btf_type_is_scalar(t)) {
10864 if (reg->type != SCALAR_VALUE) {
10865 verbose(env, "R%d is not a scalar\n", regno);
10869 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10870 if (meta->arg_constant.found) {
10871 verbose(env, "verifier internal error: only one constant argument permitted\n");
10874 if (!tnum_is_const(reg->var_off)) {
10875 verbose(env, "R%d must be a known constant\n", regno);
10878 ret = mark_chain_precision(env, regno);
10881 meta->arg_constant.found = true;
10882 meta->arg_constant.value = reg->var_off.value;
10883 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10884 meta->r0_rdonly = true;
10885 is_ret_buf_sz = true;
10886 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10887 is_ret_buf_sz = true;
10890 if (is_ret_buf_sz) {
10891 if (meta->r0_size) {
10892 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10896 if (!tnum_is_const(reg->var_off)) {
10897 verbose(env, "R%d is not a const\n", regno);
10901 meta->r0_size = reg->var_off.value;
10902 ret = mark_chain_precision(env, regno);
10909 if (!btf_type_is_ptr(t)) {
10910 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10914 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10915 (register_is_null(reg) || type_may_be_null(reg->type))) {
10916 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10920 if (reg->ref_obj_id) {
10921 if (is_kfunc_release(meta) && meta->ref_obj_id) {
10922 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10923 regno, reg->ref_obj_id,
10927 meta->ref_obj_id = reg->ref_obj_id;
10928 if (is_kfunc_release(meta))
10929 meta->release_regno = regno;
10932 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10933 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10935 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10936 if (kf_arg_type < 0)
10937 return kf_arg_type;
10939 switch (kf_arg_type) {
10940 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10941 case KF_ARG_PTR_TO_BTF_ID:
10942 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10945 if (!is_trusted_reg(reg)) {
10946 if (!is_kfunc_rcu(meta)) {
10947 verbose(env, "R%d must be referenced or trusted\n", regno);
10950 if (!is_rcu_reg(reg)) {
10951 verbose(env, "R%d must be a rcu pointer\n", regno);
10957 case KF_ARG_PTR_TO_CTX:
10958 /* Trusted arguments have the same offset checks as release arguments */
10959 arg_type |= OBJ_RELEASE;
10961 case KF_ARG_PTR_TO_DYNPTR:
10962 case KF_ARG_PTR_TO_ITER:
10963 case KF_ARG_PTR_TO_LIST_HEAD:
10964 case KF_ARG_PTR_TO_LIST_NODE:
10965 case KF_ARG_PTR_TO_RB_ROOT:
10966 case KF_ARG_PTR_TO_RB_NODE:
10967 case KF_ARG_PTR_TO_MEM:
10968 case KF_ARG_PTR_TO_MEM_SIZE:
10969 case KF_ARG_PTR_TO_CALLBACK:
10970 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10971 /* Trusted by default */
10978 if (is_kfunc_release(meta) && reg->ref_obj_id)
10979 arg_type |= OBJ_RELEASE;
10980 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10984 switch (kf_arg_type) {
10985 case KF_ARG_PTR_TO_CTX:
10986 if (reg->type != PTR_TO_CTX) {
10987 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10991 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10992 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10995 meta->ret_btf_id = ret;
10998 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10999 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11000 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11003 if (!reg->ref_obj_id) {
11004 verbose(env, "allocated object must be referenced\n");
11007 if (meta->btf == btf_vmlinux &&
11008 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11009 meta->arg_btf = reg->btf;
11010 meta->arg_btf_id = reg->btf_id;
11013 case KF_ARG_PTR_TO_DYNPTR:
11015 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11016 int clone_ref_obj_id = 0;
11018 if (reg->type != PTR_TO_STACK &&
11019 reg->type != CONST_PTR_TO_DYNPTR) {
11020 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11024 if (reg->type == CONST_PTR_TO_DYNPTR)
11025 dynptr_arg_type |= MEM_RDONLY;
11027 if (is_kfunc_arg_uninit(btf, &args[i]))
11028 dynptr_arg_type |= MEM_UNINIT;
11030 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11031 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11032 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11033 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11034 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11035 (dynptr_arg_type & MEM_UNINIT)) {
11036 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11038 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11039 verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11043 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11044 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11045 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11046 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11051 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11055 if (!(dynptr_arg_type & MEM_UNINIT)) {
11056 int id = dynptr_id(env, reg);
11059 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11062 meta->initialized_dynptr.id = id;
11063 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11064 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11069 case KF_ARG_PTR_TO_ITER:
11070 ret = process_iter_arg(env, regno, insn_idx, meta);
11074 case KF_ARG_PTR_TO_LIST_HEAD:
11075 if (reg->type != PTR_TO_MAP_VALUE &&
11076 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11077 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11080 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11081 verbose(env, "allocated object must be referenced\n");
11084 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11088 case KF_ARG_PTR_TO_RB_ROOT:
11089 if (reg->type != PTR_TO_MAP_VALUE &&
11090 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11091 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11094 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11095 verbose(env, "allocated object must be referenced\n");
11098 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11102 case KF_ARG_PTR_TO_LIST_NODE:
11103 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11104 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11107 if (!reg->ref_obj_id) {
11108 verbose(env, "allocated object must be referenced\n");
11111 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11115 case KF_ARG_PTR_TO_RB_NODE:
11116 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11117 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11118 verbose(env, "rbtree_remove node input must be non-owning ref\n");
11121 if (in_rbtree_lock_required_cb(env)) {
11122 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11126 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11127 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11130 if (!reg->ref_obj_id) {
11131 verbose(env, "allocated object must be referenced\n");
11136 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11140 case KF_ARG_PTR_TO_BTF_ID:
11141 /* Only base_type is checked, further checks are done here */
11142 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11143 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11144 !reg2btf_ids[base_type(reg->type)]) {
11145 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11146 verbose(env, "expected %s or socket\n",
11147 reg_type_str(env, base_type(reg->type) |
11148 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11151 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11155 case KF_ARG_PTR_TO_MEM:
11156 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11157 if (IS_ERR(resolve_ret)) {
11158 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11159 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11162 ret = check_mem_reg(env, reg, regno, type_size);
11166 case KF_ARG_PTR_TO_MEM_SIZE:
11168 struct bpf_reg_state *buff_reg = ®s[regno];
11169 const struct btf_param *buff_arg = &args[i];
11170 struct bpf_reg_state *size_reg = ®s[regno + 1];
11171 const struct btf_param *size_arg = &args[i + 1];
11173 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11174 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11176 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11181 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11182 if (meta->arg_constant.found) {
11183 verbose(env, "verifier internal error: only one constant argument permitted\n");
11186 if (!tnum_is_const(size_reg->var_off)) {
11187 verbose(env, "R%d must be a known constant\n", regno + 1);
11190 meta->arg_constant.found = true;
11191 meta->arg_constant.value = size_reg->var_off.value;
11194 /* Skip next '__sz' or '__szk' argument */
11198 case KF_ARG_PTR_TO_CALLBACK:
11199 meta->subprogno = reg->subprogno;
11201 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11202 if (!type_is_ptr_alloc_obj(reg->type)) {
11203 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11206 if (!type_is_non_owning_ref(reg->type))
11207 meta->arg_owning_ref = true;
11209 rec = reg_btf_record(reg);
11211 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11215 if (rec->refcount_off < 0) {
11216 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11219 if (rec->refcount_off >= 0) {
11220 verbose(env, "bpf_refcount_acquire calls are disabled for now\n");
11223 meta->arg_btf = reg->btf;
11224 meta->arg_btf_id = reg->btf_id;
11229 if (is_kfunc_release(meta) && !meta->release_regno) {
11230 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11238 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11239 struct bpf_insn *insn,
11240 struct bpf_kfunc_call_arg_meta *meta,
11241 const char **kfunc_name)
11243 const struct btf_type *func, *func_proto;
11244 u32 func_id, *kfunc_flags;
11245 const char *func_name;
11246 struct btf *desc_btf;
11249 *kfunc_name = NULL;
11254 desc_btf = find_kfunc_desc_btf(env, insn->off);
11255 if (IS_ERR(desc_btf))
11256 return PTR_ERR(desc_btf);
11258 func_id = insn->imm;
11259 func = btf_type_by_id(desc_btf, func_id);
11260 func_name = btf_name_by_offset(desc_btf, func->name_off);
11262 *kfunc_name = func_name;
11263 func_proto = btf_type_by_id(desc_btf, func->type);
11265 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11266 if (!kfunc_flags) {
11270 memset(meta, 0, sizeof(*meta));
11271 meta->btf = desc_btf;
11272 meta->func_id = func_id;
11273 meta->kfunc_flags = *kfunc_flags;
11274 meta->func_proto = func_proto;
11275 meta->func_name = func_name;
11280 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11283 const struct btf_type *t, *ptr_type;
11284 u32 i, nargs, ptr_type_id, release_ref_obj_id;
11285 struct bpf_reg_state *regs = cur_regs(env);
11286 const char *func_name, *ptr_type_name;
11287 bool sleepable, rcu_lock, rcu_unlock;
11288 struct bpf_kfunc_call_arg_meta meta;
11289 struct bpf_insn_aux_data *insn_aux;
11290 int err, insn_idx = *insn_idx_p;
11291 const struct btf_param *args;
11292 const struct btf_type *ret_t;
11293 struct btf *desc_btf;
11295 /* skip for now, but return error when we find this in fixup_kfunc_call */
11299 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11300 if (err == -EACCES && func_name)
11301 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11304 desc_btf = meta.btf;
11305 insn_aux = &env->insn_aux_data[insn_idx];
11307 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11309 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11310 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11314 sleepable = is_kfunc_sleepable(&meta);
11315 if (sleepable && !env->prog->aux->sleepable) {
11316 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11320 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11321 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11323 if (env->cur_state->active_rcu_lock) {
11324 struct bpf_func_state *state;
11325 struct bpf_reg_state *reg;
11328 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11330 } else if (rcu_unlock) {
11331 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11332 if (reg->type & MEM_RCU) {
11333 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11334 reg->type |= PTR_UNTRUSTED;
11337 env->cur_state->active_rcu_lock = false;
11338 } else if (sleepable) {
11339 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11342 } else if (rcu_lock) {
11343 env->cur_state->active_rcu_lock = true;
11344 } else if (rcu_unlock) {
11345 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11349 /* Check the arguments */
11350 err = check_kfunc_args(env, &meta, insn_idx);
11353 /* In case of release function, we get register number of refcounted
11354 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11356 if (meta.release_regno) {
11357 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11359 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11360 func_name, meta.func_id);
11365 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11366 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11367 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11368 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11369 insn_aux->insert_off = regs[BPF_REG_2].off;
11370 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11371 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11373 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11374 func_name, meta.func_id);
11378 err = release_reference(env, release_ref_obj_id);
11380 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11381 func_name, meta.func_id);
11386 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11387 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11388 set_rbtree_add_callback_state);
11390 verbose(env, "kfunc %s#%d failed callback verification\n",
11391 func_name, meta.func_id);
11396 for (i = 0; i < CALLER_SAVED_REGS; i++)
11397 mark_reg_not_init(env, regs, caller_saved[i]);
11399 /* Check return type */
11400 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11402 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11403 /* Only exception is bpf_obj_new_impl */
11404 if (meta.btf != btf_vmlinux ||
11405 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11406 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11407 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11412 if (btf_type_is_scalar(t)) {
11413 mark_reg_unknown(env, regs, BPF_REG_0);
11414 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11415 } else if (btf_type_is_ptr(t)) {
11416 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11418 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11419 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11420 struct btf *ret_btf;
11423 if (unlikely(!bpf_global_ma_set))
11426 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11427 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11431 ret_btf = env->prog->aux->btf;
11432 ret_btf_id = meta.arg_constant.value;
11434 /* This may be NULL due to user not supplying a BTF */
11436 verbose(env, "bpf_obj_new requires prog BTF\n");
11440 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11441 if (!ret_t || !__btf_type_is_struct(ret_t)) {
11442 verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11446 mark_reg_known_zero(env, regs, BPF_REG_0);
11447 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11448 regs[BPF_REG_0].btf = ret_btf;
11449 regs[BPF_REG_0].btf_id = ret_btf_id;
11451 insn_aux->obj_new_size = ret_t->size;
11452 insn_aux->kptr_struct_meta =
11453 btf_find_struct_meta(ret_btf, ret_btf_id);
11454 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11455 mark_reg_known_zero(env, regs, BPF_REG_0);
11456 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11457 regs[BPF_REG_0].btf = meta.arg_btf;
11458 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11460 insn_aux->kptr_struct_meta =
11461 btf_find_struct_meta(meta.arg_btf,
11463 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11464 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11465 struct btf_field *field = meta.arg_list_head.field;
11467 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11468 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11469 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11470 struct btf_field *field = meta.arg_rbtree_root.field;
11472 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11473 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11474 mark_reg_known_zero(env, regs, BPF_REG_0);
11475 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11476 regs[BPF_REG_0].btf = desc_btf;
11477 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11478 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11479 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11480 if (!ret_t || !btf_type_is_struct(ret_t)) {
11482 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11486 mark_reg_known_zero(env, regs, BPF_REG_0);
11487 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11488 regs[BPF_REG_0].btf = desc_btf;
11489 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11490 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11491 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11492 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11494 mark_reg_known_zero(env, regs, BPF_REG_0);
11496 if (!meta.arg_constant.found) {
11497 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11501 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11503 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11504 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11506 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11507 regs[BPF_REG_0].type |= MEM_RDONLY;
11509 /* this will set env->seen_direct_write to true */
11510 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11511 verbose(env, "the prog does not allow writes to packet data\n");
11516 if (!meta.initialized_dynptr.id) {
11517 verbose(env, "verifier internal error: no dynptr id\n");
11520 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11522 /* we don't need to set BPF_REG_0's ref obj id
11523 * because packet slices are not refcounted (see
11524 * dynptr_type_refcounted)
11527 verbose(env, "kernel function %s unhandled dynamic return type\n",
11531 } else if (!__btf_type_is_struct(ptr_type)) {
11532 if (!meta.r0_size) {
11535 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11537 meta.r0_rdonly = true;
11540 if (!meta.r0_size) {
11541 ptr_type_name = btf_name_by_offset(desc_btf,
11542 ptr_type->name_off);
11544 "kernel function %s returns pointer type %s %s is not supported\n",
11546 btf_type_str(ptr_type),
11551 mark_reg_known_zero(env, regs, BPF_REG_0);
11552 regs[BPF_REG_0].type = PTR_TO_MEM;
11553 regs[BPF_REG_0].mem_size = meta.r0_size;
11555 if (meta.r0_rdonly)
11556 regs[BPF_REG_0].type |= MEM_RDONLY;
11558 /* Ensures we don't access the memory after a release_reference() */
11559 if (meta.ref_obj_id)
11560 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11562 mark_reg_known_zero(env, regs, BPF_REG_0);
11563 regs[BPF_REG_0].btf = desc_btf;
11564 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11565 regs[BPF_REG_0].btf_id = ptr_type_id;
11568 if (is_kfunc_ret_null(&meta)) {
11569 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11570 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11571 regs[BPF_REG_0].id = ++env->id_gen;
11573 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11574 if (is_kfunc_acquire(&meta)) {
11575 int id = acquire_reference_state(env, insn_idx);
11579 if (is_kfunc_ret_null(&meta))
11580 regs[BPF_REG_0].id = id;
11581 regs[BPF_REG_0].ref_obj_id = id;
11582 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11583 ref_set_non_owning(env, ®s[BPF_REG_0]);
11586 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
11587 regs[BPF_REG_0].id = ++env->id_gen;
11588 } else if (btf_type_is_void(t)) {
11589 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11590 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11591 insn_aux->kptr_struct_meta =
11592 btf_find_struct_meta(meta.arg_btf,
11598 nargs = btf_type_vlen(meta.func_proto);
11599 args = (const struct btf_param *)(meta.func_proto + 1);
11600 for (i = 0; i < nargs; i++) {
11603 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11604 if (btf_type_is_ptr(t))
11605 mark_btf_func_reg_size(env, regno, sizeof(void *));
11607 /* scalar. ensured by btf_check_kfunc_arg_match() */
11608 mark_btf_func_reg_size(env, regno, t->size);
11611 if (is_iter_next_kfunc(&meta)) {
11612 err = process_iter_next_call(env, insn_idx, &meta);
11620 static bool signed_add_overflows(s64 a, s64 b)
11622 /* Do the add in u64, where overflow is well-defined */
11623 s64 res = (s64)((u64)a + (u64)b);
11630 static bool signed_add32_overflows(s32 a, s32 b)
11632 /* Do the add in u32, where overflow is well-defined */
11633 s32 res = (s32)((u32)a + (u32)b);
11640 static bool signed_sub_overflows(s64 a, s64 b)
11642 /* Do the sub in u64, where overflow is well-defined */
11643 s64 res = (s64)((u64)a - (u64)b);
11650 static bool signed_sub32_overflows(s32 a, s32 b)
11652 /* Do the sub in u32, where overflow is well-defined */
11653 s32 res = (s32)((u32)a - (u32)b);
11660 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11661 const struct bpf_reg_state *reg,
11662 enum bpf_reg_type type)
11664 bool known = tnum_is_const(reg->var_off);
11665 s64 val = reg->var_off.value;
11666 s64 smin = reg->smin_value;
11668 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11669 verbose(env, "math between %s pointer and %lld is not allowed\n",
11670 reg_type_str(env, type), val);
11674 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11675 verbose(env, "%s pointer offset %d is not allowed\n",
11676 reg_type_str(env, type), reg->off);
11680 if (smin == S64_MIN) {
11681 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11682 reg_type_str(env, type));
11686 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11687 verbose(env, "value %lld makes %s pointer be out of bounds\n",
11688 smin, reg_type_str(env, type));
11696 REASON_BOUNDS = -1,
11703 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11704 u32 *alu_limit, bool mask_to_left)
11706 u32 max = 0, ptr_limit = 0;
11708 switch (ptr_reg->type) {
11710 /* Offset 0 is out-of-bounds, but acceptable start for the
11711 * left direction, see BPF_REG_FP. Also, unknown scalar
11712 * offset where we would need to deal with min/max bounds is
11713 * currently prohibited for unprivileged.
11715 max = MAX_BPF_STACK + mask_to_left;
11716 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11718 case PTR_TO_MAP_VALUE:
11719 max = ptr_reg->map_ptr->value_size;
11720 ptr_limit = (mask_to_left ?
11721 ptr_reg->smin_value :
11722 ptr_reg->umax_value) + ptr_reg->off;
11725 return REASON_TYPE;
11728 if (ptr_limit >= max)
11729 return REASON_LIMIT;
11730 *alu_limit = ptr_limit;
11734 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11735 const struct bpf_insn *insn)
11737 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11740 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11741 u32 alu_state, u32 alu_limit)
11743 /* If we arrived here from different branches with different
11744 * state or limits to sanitize, then this won't work.
11746 if (aux->alu_state &&
11747 (aux->alu_state != alu_state ||
11748 aux->alu_limit != alu_limit))
11749 return REASON_PATHS;
11751 /* Corresponding fixup done in do_misc_fixups(). */
11752 aux->alu_state = alu_state;
11753 aux->alu_limit = alu_limit;
11757 static int sanitize_val_alu(struct bpf_verifier_env *env,
11758 struct bpf_insn *insn)
11760 struct bpf_insn_aux_data *aux = cur_aux(env);
11762 if (can_skip_alu_sanitation(env, insn))
11765 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11768 static bool sanitize_needed(u8 opcode)
11770 return opcode == BPF_ADD || opcode == BPF_SUB;
11773 struct bpf_sanitize_info {
11774 struct bpf_insn_aux_data aux;
11778 static struct bpf_verifier_state *
11779 sanitize_speculative_path(struct bpf_verifier_env *env,
11780 const struct bpf_insn *insn,
11781 u32 next_idx, u32 curr_idx)
11783 struct bpf_verifier_state *branch;
11784 struct bpf_reg_state *regs;
11786 branch = push_stack(env, next_idx, curr_idx, true);
11787 if (branch && insn) {
11788 regs = branch->frame[branch->curframe]->regs;
11789 if (BPF_SRC(insn->code) == BPF_K) {
11790 mark_reg_unknown(env, regs, insn->dst_reg);
11791 } else if (BPF_SRC(insn->code) == BPF_X) {
11792 mark_reg_unknown(env, regs, insn->dst_reg);
11793 mark_reg_unknown(env, regs, insn->src_reg);
11799 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11800 struct bpf_insn *insn,
11801 const struct bpf_reg_state *ptr_reg,
11802 const struct bpf_reg_state *off_reg,
11803 struct bpf_reg_state *dst_reg,
11804 struct bpf_sanitize_info *info,
11805 const bool commit_window)
11807 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11808 struct bpf_verifier_state *vstate = env->cur_state;
11809 bool off_is_imm = tnum_is_const(off_reg->var_off);
11810 bool off_is_neg = off_reg->smin_value < 0;
11811 bool ptr_is_dst_reg = ptr_reg == dst_reg;
11812 u8 opcode = BPF_OP(insn->code);
11813 u32 alu_state, alu_limit;
11814 struct bpf_reg_state tmp;
11818 if (can_skip_alu_sanitation(env, insn))
11821 /* We already marked aux for masking from non-speculative
11822 * paths, thus we got here in the first place. We only care
11823 * to explore bad access from here.
11825 if (vstate->speculative)
11828 if (!commit_window) {
11829 if (!tnum_is_const(off_reg->var_off) &&
11830 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11831 return REASON_BOUNDS;
11833 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
11834 (opcode == BPF_SUB && !off_is_neg);
11837 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11841 if (commit_window) {
11842 /* In commit phase we narrow the masking window based on
11843 * the observed pointer move after the simulated operation.
11845 alu_state = info->aux.alu_state;
11846 alu_limit = abs(info->aux.alu_limit - alu_limit);
11848 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11849 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11850 alu_state |= ptr_is_dst_reg ?
11851 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11853 /* Limit pruning on unknown scalars to enable deep search for
11854 * potential masking differences from other program paths.
11857 env->explore_alu_limits = true;
11860 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11864 /* If we're in commit phase, we're done here given we already
11865 * pushed the truncated dst_reg into the speculative verification
11868 * Also, when register is a known constant, we rewrite register-based
11869 * operation to immediate-based, and thus do not need masking (and as
11870 * a consequence, do not need to simulate the zero-truncation either).
11872 if (commit_window || off_is_imm)
11875 /* Simulate and find potential out-of-bounds access under
11876 * speculative execution from truncation as a result of
11877 * masking when off was not within expected range. If off
11878 * sits in dst, then we temporarily need to move ptr there
11879 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11880 * for cases where we use K-based arithmetic in one direction
11881 * and truncated reg-based in the other in order to explore
11884 if (!ptr_is_dst_reg) {
11886 copy_register_state(dst_reg, ptr_reg);
11888 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11890 if (!ptr_is_dst_reg && ret)
11892 return !ret ? REASON_STACK : 0;
11895 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11897 struct bpf_verifier_state *vstate = env->cur_state;
11899 /* If we simulate paths under speculation, we don't update the
11900 * insn as 'seen' such that when we verify unreachable paths in
11901 * the non-speculative domain, sanitize_dead_code() can still
11902 * rewrite/sanitize them.
11904 if (!vstate->speculative)
11905 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11908 static int sanitize_err(struct bpf_verifier_env *env,
11909 const struct bpf_insn *insn, int reason,
11910 const struct bpf_reg_state *off_reg,
11911 const struct bpf_reg_state *dst_reg)
11913 static const char *err = "pointer arithmetic with it prohibited for !root";
11914 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11915 u32 dst = insn->dst_reg, src = insn->src_reg;
11918 case REASON_BOUNDS:
11919 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11920 off_reg == dst_reg ? dst : src, err);
11923 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11924 off_reg == dst_reg ? src : dst, err);
11927 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11931 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11935 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11939 verbose(env, "verifier internal error: unknown reason (%d)\n",
11947 /* check that stack access falls within stack limits and that 'reg' doesn't
11948 * have a variable offset.
11950 * Variable offset is prohibited for unprivileged mode for simplicity since it
11951 * requires corresponding support in Spectre masking for stack ALU. See also
11952 * retrieve_ptr_limit().
11955 * 'off' includes 'reg->off'.
11957 static int check_stack_access_for_ptr_arithmetic(
11958 struct bpf_verifier_env *env,
11960 const struct bpf_reg_state *reg,
11963 if (!tnum_is_const(reg->var_off)) {
11966 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11967 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11968 regno, tn_buf, off);
11972 if (off >= 0 || off < -MAX_BPF_STACK) {
11973 verbose(env, "R%d stack pointer arithmetic goes out of range, "
11974 "prohibited for !root; off=%d\n", regno, off);
11981 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11982 const struct bpf_insn *insn,
11983 const struct bpf_reg_state *dst_reg)
11985 u32 dst = insn->dst_reg;
11987 /* For unprivileged we require that resulting offset must be in bounds
11988 * in order to be able to sanitize access later on.
11990 if (env->bypass_spec_v1)
11993 switch (dst_reg->type) {
11995 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11996 dst_reg->off + dst_reg->var_off.value))
11999 case PTR_TO_MAP_VALUE:
12000 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12001 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12002 "prohibited for !root\n", dst);
12013 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12014 * Caller should also handle BPF_MOV case separately.
12015 * If we return -EACCES, caller may want to try again treating pointer as a
12016 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
12018 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12019 struct bpf_insn *insn,
12020 const struct bpf_reg_state *ptr_reg,
12021 const struct bpf_reg_state *off_reg)
12023 struct bpf_verifier_state *vstate = env->cur_state;
12024 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12025 struct bpf_reg_state *regs = state->regs, *dst_reg;
12026 bool known = tnum_is_const(off_reg->var_off);
12027 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12028 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12029 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12030 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12031 struct bpf_sanitize_info info = {};
12032 u8 opcode = BPF_OP(insn->code);
12033 u32 dst = insn->dst_reg;
12036 dst_reg = ®s[dst];
12038 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12039 smin_val > smax_val || umin_val > umax_val) {
12040 /* Taint dst register if offset had invalid bounds derived from
12041 * e.g. dead branches.
12043 __mark_reg_unknown(env, dst_reg);
12047 if (BPF_CLASS(insn->code) != BPF_ALU64) {
12048 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12049 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12050 __mark_reg_unknown(env, dst_reg);
12055 "R%d 32-bit pointer arithmetic prohibited\n",
12060 if (ptr_reg->type & PTR_MAYBE_NULL) {
12061 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12062 dst, reg_type_str(env, ptr_reg->type));
12066 switch (base_type(ptr_reg->type)) {
12067 case CONST_PTR_TO_MAP:
12068 /* smin_val represents the known value */
12069 if (known && smin_val == 0 && opcode == BPF_ADD)
12072 case PTR_TO_PACKET_END:
12073 case PTR_TO_SOCKET:
12074 case PTR_TO_SOCK_COMMON:
12075 case PTR_TO_TCP_SOCK:
12076 case PTR_TO_XDP_SOCK:
12077 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12078 dst, reg_type_str(env, ptr_reg->type));
12084 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12085 * The id may be overwritten later if we create a new variable offset.
12087 dst_reg->type = ptr_reg->type;
12088 dst_reg->id = ptr_reg->id;
12090 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12091 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12094 /* pointer types do not carry 32-bit bounds at the moment. */
12095 __mark_reg32_unbounded(dst_reg);
12097 if (sanitize_needed(opcode)) {
12098 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12101 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12106 /* We can take a fixed offset as long as it doesn't overflow
12107 * the s32 'off' field
12109 if (known && (ptr_reg->off + smin_val ==
12110 (s64)(s32)(ptr_reg->off + smin_val))) {
12111 /* pointer += K. Accumulate it into fixed offset */
12112 dst_reg->smin_value = smin_ptr;
12113 dst_reg->smax_value = smax_ptr;
12114 dst_reg->umin_value = umin_ptr;
12115 dst_reg->umax_value = umax_ptr;
12116 dst_reg->var_off = ptr_reg->var_off;
12117 dst_reg->off = ptr_reg->off + smin_val;
12118 dst_reg->raw = ptr_reg->raw;
12121 /* A new variable offset is created. Note that off_reg->off
12122 * == 0, since it's a scalar.
12123 * dst_reg gets the pointer type and since some positive
12124 * integer value was added to the pointer, give it a new 'id'
12125 * if it's a PTR_TO_PACKET.
12126 * this creates a new 'base' pointer, off_reg (variable) gets
12127 * added into the variable offset, and we copy the fixed offset
12130 if (signed_add_overflows(smin_ptr, smin_val) ||
12131 signed_add_overflows(smax_ptr, smax_val)) {
12132 dst_reg->smin_value = S64_MIN;
12133 dst_reg->smax_value = S64_MAX;
12135 dst_reg->smin_value = smin_ptr + smin_val;
12136 dst_reg->smax_value = smax_ptr + smax_val;
12138 if (umin_ptr + umin_val < umin_ptr ||
12139 umax_ptr + umax_val < umax_ptr) {
12140 dst_reg->umin_value = 0;
12141 dst_reg->umax_value = U64_MAX;
12143 dst_reg->umin_value = umin_ptr + umin_val;
12144 dst_reg->umax_value = umax_ptr + umax_val;
12146 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12147 dst_reg->off = ptr_reg->off;
12148 dst_reg->raw = ptr_reg->raw;
12149 if (reg_is_pkt_pointer(ptr_reg)) {
12150 dst_reg->id = ++env->id_gen;
12151 /* something was added to pkt_ptr, set range to zero */
12152 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12156 if (dst_reg == off_reg) {
12157 /* scalar -= pointer. Creates an unknown scalar */
12158 verbose(env, "R%d tried to subtract pointer from scalar\n",
12162 /* We don't allow subtraction from FP, because (according to
12163 * test_verifier.c test "invalid fp arithmetic", JITs might not
12164 * be able to deal with it.
12166 if (ptr_reg->type == PTR_TO_STACK) {
12167 verbose(env, "R%d subtraction from stack pointer prohibited\n",
12171 if (known && (ptr_reg->off - smin_val ==
12172 (s64)(s32)(ptr_reg->off - smin_val))) {
12173 /* pointer -= K. Subtract it from fixed offset */
12174 dst_reg->smin_value = smin_ptr;
12175 dst_reg->smax_value = smax_ptr;
12176 dst_reg->umin_value = umin_ptr;
12177 dst_reg->umax_value = umax_ptr;
12178 dst_reg->var_off = ptr_reg->var_off;
12179 dst_reg->id = ptr_reg->id;
12180 dst_reg->off = ptr_reg->off - smin_val;
12181 dst_reg->raw = ptr_reg->raw;
12184 /* A new variable offset is created. If the subtrahend is known
12185 * nonnegative, then any reg->range we had before is still good.
12187 if (signed_sub_overflows(smin_ptr, smax_val) ||
12188 signed_sub_overflows(smax_ptr, smin_val)) {
12189 /* Overflow possible, we know nothing */
12190 dst_reg->smin_value = S64_MIN;
12191 dst_reg->smax_value = S64_MAX;
12193 dst_reg->smin_value = smin_ptr - smax_val;
12194 dst_reg->smax_value = smax_ptr - smin_val;
12196 if (umin_ptr < umax_val) {
12197 /* Overflow possible, we know nothing */
12198 dst_reg->umin_value = 0;
12199 dst_reg->umax_value = U64_MAX;
12201 /* Cannot overflow (as long as bounds are consistent) */
12202 dst_reg->umin_value = umin_ptr - umax_val;
12203 dst_reg->umax_value = umax_ptr - umin_val;
12205 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12206 dst_reg->off = ptr_reg->off;
12207 dst_reg->raw = ptr_reg->raw;
12208 if (reg_is_pkt_pointer(ptr_reg)) {
12209 dst_reg->id = ++env->id_gen;
12210 /* something was added to pkt_ptr, set range to zero */
12212 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12218 /* bitwise ops on pointers are troublesome, prohibit. */
12219 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12220 dst, bpf_alu_string[opcode >> 4]);
12223 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12224 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12225 dst, bpf_alu_string[opcode >> 4]);
12229 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12231 reg_bounds_sync(dst_reg);
12232 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12234 if (sanitize_needed(opcode)) {
12235 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12238 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12244 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12245 struct bpf_reg_state *src_reg)
12247 s32 smin_val = src_reg->s32_min_value;
12248 s32 smax_val = src_reg->s32_max_value;
12249 u32 umin_val = src_reg->u32_min_value;
12250 u32 umax_val = src_reg->u32_max_value;
12252 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12253 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12254 dst_reg->s32_min_value = S32_MIN;
12255 dst_reg->s32_max_value = S32_MAX;
12257 dst_reg->s32_min_value += smin_val;
12258 dst_reg->s32_max_value += smax_val;
12260 if (dst_reg->u32_min_value + umin_val < umin_val ||
12261 dst_reg->u32_max_value + umax_val < umax_val) {
12262 dst_reg->u32_min_value = 0;
12263 dst_reg->u32_max_value = U32_MAX;
12265 dst_reg->u32_min_value += umin_val;
12266 dst_reg->u32_max_value += umax_val;
12270 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12271 struct bpf_reg_state *src_reg)
12273 s64 smin_val = src_reg->smin_value;
12274 s64 smax_val = src_reg->smax_value;
12275 u64 umin_val = src_reg->umin_value;
12276 u64 umax_val = src_reg->umax_value;
12278 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12279 signed_add_overflows(dst_reg->smax_value, smax_val)) {
12280 dst_reg->smin_value = S64_MIN;
12281 dst_reg->smax_value = S64_MAX;
12283 dst_reg->smin_value += smin_val;
12284 dst_reg->smax_value += smax_val;
12286 if (dst_reg->umin_value + umin_val < umin_val ||
12287 dst_reg->umax_value + umax_val < umax_val) {
12288 dst_reg->umin_value = 0;
12289 dst_reg->umax_value = U64_MAX;
12291 dst_reg->umin_value += umin_val;
12292 dst_reg->umax_value += umax_val;
12296 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12297 struct bpf_reg_state *src_reg)
12299 s32 smin_val = src_reg->s32_min_value;
12300 s32 smax_val = src_reg->s32_max_value;
12301 u32 umin_val = src_reg->u32_min_value;
12302 u32 umax_val = src_reg->u32_max_value;
12304 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12305 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12306 /* Overflow possible, we know nothing */
12307 dst_reg->s32_min_value = S32_MIN;
12308 dst_reg->s32_max_value = S32_MAX;
12310 dst_reg->s32_min_value -= smax_val;
12311 dst_reg->s32_max_value -= smin_val;
12313 if (dst_reg->u32_min_value < umax_val) {
12314 /* Overflow possible, we know nothing */
12315 dst_reg->u32_min_value = 0;
12316 dst_reg->u32_max_value = U32_MAX;
12318 /* Cannot overflow (as long as bounds are consistent) */
12319 dst_reg->u32_min_value -= umax_val;
12320 dst_reg->u32_max_value -= umin_val;
12324 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12325 struct bpf_reg_state *src_reg)
12327 s64 smin_val = src_reg->smin_value;
12328 s64 smax_val = src_reg->smax_value;
12329 u64 umin_val = src_reg->umin_value;
12330 u64 umax_val = src_reg->umax_value;
12332 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12333 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12334 /* Overflow possible, we know nothing */
12335 dst_reg->smin_value = S64_MIN;
12336 dst_reg->smax_value = S64_MAX;
12338 dst_reg->smin_value -= smax_val;
12339 dst_reg->smax_value -= smin_val;
12341 if (dst_reg->umin_value < umax_val) {
12342 /* Overflow possible, we know nothing */
12343 dst_reg->umin_value = 0;
12344 dst_reg->umax_value = U64_MAX;
12346 /* Cannot overflow (as long as bounds are consistent) */
12347 dst_reg->umin_value -= umax_val;
12348 dst_reg->umax_value -= umin_val;
12352 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12353 struct bpf_reg_state *src_reg)
12355 s32 smin_val = src_reg->s32_min_value;
12356 u32 umin_val = src_reg->u32_min_value;
12357 u32 umax_val = src_reg->u32_max_value;
12359 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12360 /* Ain't nobody got time to multiply that sign */
12361 __mark_reg32_unbounded(dst_reg);
12364 /* Both values are positive, so we can work with unsigned and
12365 * copy the result to signed (unless it exceeds S32_MAX).
12367 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12368 /* Potential overflow, we know nothing */
12369 __mark_reg32_unbounded(dst_reg);
12372 dst_reg->u32_min_value *= umin_val;
12373 dst_reg->u32_max_value *= umax_val;
12374 if (dst_reg->u32_max_value > S32_MAX) {
12375 /* Overflow possible, we know nothing */
12376 dst_reg->s32_min_value = S32_MIN;
12377 dst_reg->s32_max_value = S32_MAX;
12379 dst_reg->s32_min_value = dst_reg->u32_min_value;
12380 dst_reg->s32_max_value = dst_reg->u32_max_value;
12384 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12385 struct bpf_reg_state *src_reg)
12387 s64 smin_val = src_reg->smin_value;
12388 u64 umin_val = src_reg->umin_value;
12389 u64 umax_val = src_reg->umax_value;
12391 if (smin_val < 0 || dst_reg->smin_value < 0) {
12392 /* Ain't nobody got time to multiply that sign */
12393 __mark_reg64_unbounded(dst_reg);
12396 /* Both values are positive, so we can work with unsigned and
12397 * copy the result to signed (unless it exceeds S64_MAX).
12399 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12400 /* Potential overflow, we know nothing */
12401 __mark_reg64_unbounded(dst_reg);
12404 dst_reg->umin_value *= umin_val;
12405 dst_reg->umax_value *= umax_val;
12406 if (dst_reg->umax_value > S64_MAX) {
12407 /* Overflow possible, we know nothing */
12408 dst_reg->smin_value = S64_MIN;
12409 dst_reg->smax_value = S64_MAX;
12411 dst_reg->smin_value = dst_reg->umin_value;
12412 dst_reg->smax_value = dst_reg->umax_value;
12416 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12417 struct bpf_reg_state *src_reg)
12419 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12420 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12421 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12422 s32 smin_val = src_reg->s32_min_value;
12423 u32 umax_val = src_reg->u32_max_value;
12425 if (src_known && dst_known) {
12426 __mark_reg32_known(dst_reg, var32_off.value);
12430 /* We get our minimum from the var_off, since that's inherently
12431 * bitwise. Our maximum is the minimum of the operands' maxima.
12433 dst_reg->u32_min_value = var32_off.value;
12434 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12435 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12436 /* Lose signed bounds when ANDing negative numbers,
12437 * ain't nobody got time for that.
12439 dst_reg->s32_min_value = S32_MIN;
12440 dst_reg->s32_max_value = S32_MAX;
12442 /* ANDing two positives gives a positive, so safe to
12443 * cast result into s64.
12445 dst_reg->s32_min_value = dst_reg->u32_min_value;
12446 dst_reg->s32_max_value = dst_reg->u32_max_value;
12450 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12451 struct bpf_reg_state *src_reg)
12453 bool src_known = tnum_is_const(src_reg->var_off);
12454 bool dst_known = tnum_is_const(dst_reg->var_off);
12455 s64 smin_val = src_reg->smin_value;
12456 u64 umax_val = src_reg->umax_value;
12458 if (src_known && dst_known) {
12459 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12463 /* We get our minimum from the var_off, since that's inherently
12464 * bitwise. Our maximum is the minimum of the operands' maxima.
12466 dst_reg->umin_value = dst_reg->var_off.value;
12467 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12468 if (dst_reg->smin_value < 0 || smin_val < 0) {
12469 /* Lose signed bounds when ANDing negative numbers,
12470 * ain't nobody got time for that.
12472 dst_reg->smin_value = S64_MIN;
12473 dst_reg->smax_value = S64_MAX;
12475 /* ANDing two positives gives a positive, so safe to
12476 * cast result into s64.
12478 dst_reg->smin_value = dst_reg->umin_value;
12479 dst_reg->smax_value = dst_reg->umax_value;
12481 /* We may learn something more from the var_off */
12482 __update_reg_bounds(dst_reg);
12485 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12486 struct bpf_reg_state *src_reg)
12488 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12489 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12490 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12491 s32 smin_val = src_reg->s32_min_value;
12492 u32 umin_val = src_reg->u32_min_value;
12494 if (src_known && dst_known) {
12495 __mark_reg32_known(dst_reg, var32_off.value);
12499 /* We get our maximum from the var_off, and our minimum is the
12500 * maximum of the operands' minima
12502 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12503 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12504 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12505 /* Lose signed bounds when ORing negative numbers,
12506 * ain't nobody got time for that.
12508 dst_reg->s32_min_value = S32_MIN;
12509 dst_reg->s32_max_value = S32_MAX;
12511 /* ORing two positives gives a positive, so safe to
12512 * cast result into s64.
12514 dst_reg->s32_min_value = dst_reg->u32_min_value;
12515 dst_reg->s32_max_value = dst_reg->u32_max_value;
12519 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12520 struct bpf_reg_state *src_reg)
12522 bool src_known = tnum_is_const(src_reg->var_off);
12523 bool dst_known = tnum_is_const(dst_reg->var_off);
12524 s64 smin_val = src_reg->smin_value;
12525 u64 umin_val = src_reg->umin_value;
12527 if (src_known && dst_known) {
12528 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12532 /* We get our maximum from the var_off, and our minimum is the
12533 * maximum of the operands' minima
12535 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12536 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12537 if (dst_reg->smin_value < 0 || smin_val < 0) {
12538 /* Lose signed bounds when ORing negative numbers,
12539 * ain't nobody got time for that.
12541 dst_reg->smin_value = S64_MIN;
12542 dst_reg->smax_value = S64_MAX;
12544 /* ORing two positives gives a positive, so safe to
12545 * cast result into s64.
12547 dst_reg->smin_value = dst_reg->umin_value;
12548 dst_reg->smax_value = dst_reg->umax_value;
12550 /* We may learn something more from the var_off */
12551 __update_reg_bounds(dst_reg);
12554 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12555 struct bpf_reg_state *src_reg)
12557 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12558 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12559 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12560 s32 smin_val = src_reg->s32_min_value;
12562 if (src_known && dst_known) {
12563 __mark_reg32_known(dst_reg, var32_off.value);
12567 /* We get both minimum and maximum from the var32_off. */
12568 dst_reg->u32_min_value = var32_off.value;
12569 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12571 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12572 /* XORing two positive sign numbers gives a positive,
12573 * so safe to cast u32 result into s32.
12575 dst_reg->s32_min_value = dst_reg->u32_min_value;
12576 dst_reg->s32_max_value = dst_reg->u32_max_value;
12578 dst_reg->s32_min_value = S32_MIN;
12579 dst_reg->s32_max_value = S32_MAX;
12583 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12584 struct bpf_reg_state *src_reg)
12586 bool src_known = tnum_is_const(src_reg->var_off);
12587 bool dst_known = tnum_is_const(dst_reg->var_off);
12588 s64 smin_val = src_reg->smin_value;
12590 if (src_known && dst_known) {
12591 /* dst_reg->var_off.value has been updated earlier */
12592 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12596 /* We get both minimum and maximum from the var_off. */
12597 dst_reg->umin_value = dst_reg->var_off.value;
12598 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12600 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12601 /* XORing two positive sign numbers gives a positive,
12602 * so safe to cast u64 result into s64.
12604 dst_reg->smin_value = dst_reg->umin_value;
12605 dst_reg->smax_value = dst_reg->umax_value;
12607 dst_reg->smin_value = S64_MIN;
12608 dst_reg->smax_value = S64_MAX;
12611 __update_reg_bounds(dst_reg);
12614 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12615 u64 umin_val, u64 umax_val)
12617 /* We lose all sign bit information (except what we can pick
12620 dst_reg->s32_min_value = S32_MIN;
12621 dst_reg->s32_max_value = S32_MAX;
12622 /* If we might shift our top bit out, then we know nothing */
12623 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12624 dst_reg->u32_min_value = 0;
12625 dst_reg->u32_max_value = U32_MAX;
12627 dst_reg->u32_min_value <<= umin_val;
12628 dst_reg->u32_max_value <<= umax_val;
12632 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12633 struct bpf_reg_state *src_reg)
12635 u32 umax_val = src_reg->u32_max_value;
12636 u32 umin_val = src_reg->u32_min_value;
12637 /* u32 alu operation will zext upper bits */
12638 struct tnum subreg = tnum_subreg(dst_reg->var_off);
12640 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12641 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12642 /* Not required but being careful mark reg64 bounds as unknown so
12643 * that we are forced to pick them up from tnum and zext later and
12644 * if some path skips this step we are still safe.
12646 __mark_reg64_unbounded(dst_reg);
12647 __update_reg32_bounds(dst_reg);
12650 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12651 u64 umin_val, u64 umax_val)
12653 /* Special case <<32 because it is a common compiler pattern to sign
12654 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12655 * positive we know this shift will also be positive so we can track
12656 * bounds correctly. Otherwise we lose all sign bit information except
12657 * what we can pick up from var_off. Perhaps we can generalize this
12658 * later to shifts of any length.
12660 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12661 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12663 dst_reg->smax_value = S64_MAX;
12665 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12666 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12668 dst_reg->smin_value = S64_MIN;
12670 /* If we might shift our top bit out, then we know nothing */
12671 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12672 dst_reg->umin_value = 0;
12673 dst_reg->umax_value = U64_MAX;
12675 dst_reg->umin_value <<= umin_val;
12676 dst_reg->umax_value <<= umax_val;
12680 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12681 struct bpf_reg_state *src_reg)
12683 u64 umax_val = src_reg->umax_value;
12684 u64 umin_val = src_reg->umin_value;
12686 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
12687 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12688 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12690 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12691 /* We may learn something more from the var_off */
12692 __update_reg_bounds(dst_reg);
12695 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12696 struct bpf_reg_state *src_reg)
12698 struct tnum subreg = tnum_subreg(dst_reg->var_off);
12699 u32 umax_val = src_reg->u32_max_value;
12700 u32 umin_val = src_reg->u32_min_value;
12702 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12703 * be negative, then either:
12704 * 1) src_reg might be zero, so the sign bit of the result is
12705 * unknown, so we lose our signed bounds
12706 * 2) it's known negative, thus the unsigned bounds capture the
12708 * 3) the signed bounds cross zero, so they tell us nothing
12710 * If the value in dst_reg is known nonnegative, then again the
12711 * unsigned bounds capture the signed bounds.
12712 * Thus, in all cases it suffices to blow away our signed bounds
12713 * and rely on inferring new ones from the unsigned bounds and
12714 * var_off of the result.
12716 dst_reg->s32_min_value = S32_MIN;
12717 dst_reg->s32_max_value = S32_MAX;
12719 dst_reg->var_off = tnum_rshift(subreg, umin_val);
12720 dst_reg->u32_min_value >>= umax_val;
12721 dst_reg->u32_max_value >>= umin_val;
12723 __mark_reg64_unbounded(dst_reg);
12724 __update_reg32_bounds(dst_reg);
12727 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12728 struct bpf_reg_state *src_reg)
12730 u64 umax_val = src_reg->umax_value;
12731 u64 umin_val = src_reg->umin_value;
12733 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12734 * be negative, then either:
12735 * 1) src_reg might be zero, so the sign bit of the result is
12736 * unknown, so we lose our signed bounds
12737 * 2) it's known negative, thus the unsigned bounds capture the
12739 * 3) the signed bounds cross zero, so they tell us nothing
12741 * If the value in dst_reg is known nonnegative, then again the
12742 * unsigned bounds capture the signed bounds.
12743 * Thus, in all cases it suffices to blow away our signed bounds
12744 * and rely on inferring new ones from the unsigned bounds and
12745 * var_off of the result.
12747 dst_reg->smin_value = S64_MIN;
12748 dst_reg->smax_value = S64_MAX;
12749 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12750 dst_reg->umin_value >>= umax_val;
12751 dst_reg->umax_value >>= umin_val;
12753 /* Its not easy to operate on alu32 bounds here because it depends
12754 * on bits being shifted in. Take easy way out and mark unbounded
12755 * so we can recalculate later from tnum.
12757 __mark_reg32_unbounded(dst_reg);
12758 __update_reg_bounds(dst_reg);
12761 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12762 struct bpf_reg_state *src_reg)
12764 u64 umin_val = src_reg->u32_min_value;
12766 /* Upon reaching here, src_known is true and
12767 * umax_val is equal to umin_val.
12769 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12770 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12772 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12774 /* blow away the dst_reg umin_value/umax_value and rely on
12775 * dst_reg var_off to refine the result.
12777 dst_reg->u32_min_value = 0;
12778 dst_reg->u32_max_value = U32_MAX;
12780 __mark_reg64_unbounded(dst_reg);
12781 __update_reg32_bounds(dst_reg);
12784 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12785 struct bpf_reg_state *src_reg)
12787 u64 umin_val = src_reg->umin_value;
12789 /* Upon reaching here, src_known is true and umax_val is equal
12792 dst_reg->smin_value >>= umin_val;
12793 dst_reg->smax_value >>= umin_val;
12795 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12797 /* blow away the dst_reg umin_value/umax_value and rely on
12798 * dst_reg var_off to refine the result.
12800 dst_reg->umin_value = 0;
12801 dst_reg->umax_value = U64_MAX;
12803 /* Its not easy to operate on alu32 bounds here because it depends
12804 * on bits being shifted in from upper 32-bits. Take easy way out
12805 * and mark unbounded so we can recalculate later from tnum.
12807 __mark_reg32_unbounded(dst_reg);
12808 __update_reg_bounds(dst_reg);
12811 /* WARNING: This function does calculations on 64-bit values, but the actual
12812 * execution may occur on 32-bit values. Therefore, things like bitshifts
12813 * need extra checks in the 32-bit case.
12815 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12816 struct bpf_insn *insn,
12817 struct bpf_reg_state *dst_reg,
12818 struct bpf_reg_state src_reg)
12820 struct bpf_reg_state *regs = cur_regs(env);
12821 u8 opcode = BPF_OP(insn->code);
12823 s64 smin_val, smax_val;
12824 u64 umin_val, umax_val;
12825 s32 s32_min_val, s32_max_val;
12826 u32 u32_min_val, u32_max_val;
12827 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12828 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12831 smin_val = src_reg.smin_value;
12832 smax_val = src_reg.smax_value;
12833 umin_val = src_reg.umin_value;
12834 umax_val = src_reg.umax_value;
12836 s32_min_val = src_reg.s32_min_value;
12837 s32_max_val = src_reg.s32_max_value;
12838 u32_min_val = src_reg.u32_min_value;
12839 u32_max_val = src_reg.u32_max_value;
12842 src_known = tnum_subreg_is_const(src_reg.var_off);
12844 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12845 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12846 /* Taint dst register if offset had invalid bounds
12847 * derived from e.g. dead branches.
12849 __mark_reg_unknown(env, dst_reg);
12853 src_known = tnum_is_const(src_reg.var_off);
12855 (smin_val != smax_val || umin_val != umax_val)) ||
12856 smin_val > smax_val || umin_val > umax_val) {
12857 /* Taint dst register if offset had invalid bounds
12858 * derived from e.g. dead branches.
12860 __mark_reg_unknown(env, dst_reg);
12866 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12867 __mark_reg_unknown(env, dst_reg);
12871 if (sanitize_needed(opcode)) {
12872 ret = sanitize_val_alu(env, insn);
12874 return sanitize_err(env, insn, ret, NULL, NULL);
12877 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12878 * There are two classes of instructions: The first class we track both
12879 * alu32 and alu64 sign/unsigned bounds independently this provides the
12880 * greatest amount of precision when alu operations are mixed with jmp32
12881 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12882 * and BPF_OR. This is possible because these ops have fairly easy to
12883 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12884 * See alu32 verifier tests for examples. The second class of
12885 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12886 * with regards to tracking sign/unsigned bounds because the bits may
12887 * cross subreg boundaries in the alu64 case. When this happens we mark
12888 * the reg unbounded in the subreg bound space and use the resulting
12889 * tnum to calculate an approximation of the sign/unsigned bounds.
12893 scalar32_min_max_add(dst_reg, &src_reg);
12894 scalar_min_max_add(dst_reg, &src_reg);
12895 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12898 scalar32_min_max_sub(dst_reg, &src_reg);
12899 scalar_min_max_sub(dst_reg, &src_reg);
12900 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12903 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12904 scalar32_min_max_mul(dst_reg, &src_reg);
12905 scalar_min_max_mul(dst_reg, &src_reg);
12908 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12909 scalar32_min_max_and(dst_reg, &src_reg);
12910 scalar_min_max_and(dst_reg, &src_reg);
12913 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12914 scalar32_min_max_or(dst_reg, &src_reg);
12915 scalar_min_max_or(dst_reg, &src_reg);
12918 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12919 scalar32_min_max_xor(dst_reg, &src_reg);
12920 scalar_min_max_xor(dst_reg, &src_reg);
12923 if (umax_val >= insn_bitness) {
12924 /* Shifts greater than 31 or 63 are undefined.
12925 * This includes shifts by a negative number.
12927 mark_reg_unknown(env, regs, insn->dst_reg);
12931 scalar32_min_max_lsh(dst_reg, &src_reg);
12933 scalar_min_max_lsh(dst_reg, &src_reg);
12936 if (umax_val >= insn_bitness) {
12937 /* Shifts greater than 31 or 63 are undefined.
12938 * This includes shifts by a negative number.
12940 mark_reg_unknown(env, regs, insn->dst_reg);
12944 scalar32_min_max_rsh(dst_reg, &src_reg);
12946 scalar_min_max_rsh(dst_reg, &src_reg);
12949 if (umax_val >= insn_bitness) {
12950 /* Shifts greater than 31 or 63 are undefined.
12951 * This includes shifts by a negative number.
12953 mark_reg_unknown(env, regs, insn->dst_reg);
12957 scalar32_min_max_arsh(dst_reg, &src_reg);
12959 scalar_min_max_arsh(dst_reg, &src_reg);
12962 mark_reg_unknown(env, regs, insn->dst_reg);
12966 /* ALU32 ops are zero extended into 64bit register */
12968 zext_32_to_64(dst_reg);
12969 reg_bounds_sync(dst_reg);
12973 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12976 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12977 struct bpf_insn *insn)
12979 struct bpf_verifier_state *vstate = env->cur_state;
12980 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12981 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12982 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12983 u8 opcode = BPF_OP(insn->code);
12986 dst_reg = ®s[insn->dst_reg];
12988 if (dst_reg->type != SCALAR_VALUE)
12991 /* Make sure ID is cleared otherwise dst_reg min/max could be
12992 * incorrectly propagated into other registers by find_equal_scalars()
12995 if (BPF_SRC(insn->code) == BPF_X) {
12996 src_reg = ®s[insn->src_reg];
12997 if (src_reg->type != SCALAR_VALUE) {
12998 if (dst_reg->type != SCALAR_VALUE) {
12999 /* Combining two pointers by any ALU op yields
13000 * an arbitrary scalar. Disallow all math except
13001 * pointer subtraction
13003 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13004 mark_reg_unknown(env, regs, insn->dst_reg);
13007 verbose(env, "R%d pointer %s pointer prohibited\n",
13009 bpf_alu_string[opcode >> 4]);
13012 /* scalar += pointer
13013 * This is legal, but we have to reverse our
13014 * src/dest handling in computing the range
13016 err = mark_chain_precision(env, insn->dst_reg);
13019 return adjust_ptr_min_max_vals(env, insn,
13022 } else if (ptr_reg) {
13023 /* pointer += scalar */
13024 err = mark_chain_precision(env, insn->src_reg);
13027 return adjust_ptr_min_max_vals(env, insn,
13029 } else if (dst_reg->precise) {
13030 /* if dst_reg is precise, src_reg should be precise as well */
13031 err = mark_chain_precision(env, insn->src_reg);
13036 /* Pretend the src is a reg with a known value, since we only
13037 * need to be able to read from this state.
13039 off_reg.type = SCALAR_VALUE;
13040 __mark_reg_known(&off_reg, insn->imm);
13041 src_reg = &off_reg;
13042 if (ptr_reg) /* pointer += K */
13043 return adjust_ptr_min_max_vals(env, insn,
13047 /* Got here implies adding two SCALAR_VALUEs */
13048 if (WARN_ON_ONCE(ptr_reg)) {
13049 print_verifier_state(env, state, true);
13050 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13053 if (WARN_ON(!src_reg)) {
13054 print_verifier_state(env, state, true);
13055 verbose(env, "verifier internal error: no src_reg\n");
13058 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13061 /* check validity of 32-bit and 64-bit arithmetic operations */
13062 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13064 struct bpf_reg_state *regs = cur_regs(env);
13065 u8 opcode = BPF_OP(insn->code);
13068 if (opcode == BPF_END || opcode == BPF_NEG) {
13069 if (opcode == BPF_NEG) {
13070 if (BPF_SRC(insn->code) != BPF_K ||
13071 insn->src_reg != BPF_REG_0 ||
13072 insn->off != 0 || insn->imm != 0) {
13073 verbose(env, "BPF_NEG uses reserved fields\n");
13077 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13078 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13079 BPF_CLASS(insn->code) == BPF_ALU64) {
13080 verbose(env, "BPF_END uses reserved fields\n");
13085 /* check src operand */
13086 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13090 if (is_pointer_value(env, insn->dst_reg)) {
13091 verbose(env, "R%d pointer arithmetic prohibited\n",
13096 /* check dest operand */
13097 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13101 } else if (opcode == BPF_MOV) {
13103 if (BPF_SRC(insn->code) == BPF_X) {
13104 if (insn->imm != 0) {
13105 verbose(env, "BPF_MOV uses reserved fields\n");
13109 if (BPF_CLASS(insn->code) == BPF_ALU) {
13110 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13111 verbose(env, "BPF_MOV uses reserved fields\n");
13115 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13117 verbose(env, "BPF_MOV uses reserved fields\n");
13122 /* check src operand */
13123 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13127 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13128 verbose(env, "BPF_MOV uses reserved fields\n");
13133 /* check dest operand, mark as required later */
13134 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13138 if (BPF_SRC(insn->code) == BPF_X) {
13139 struct bpf_reg_state *src_reg = regs + insn->src_reg;
13140 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13141 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13142 !tnum_is_const(src_reg->var_off);
13144 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13145 if (insn->off == 0) {
13147 * copy register state to dest reg
13150 /* Assign src and dst registers the same ID
13151 * that will be used by find_equal_scalars()
13152 * to propagate min/max range.
13154 src_reg->id = ++env->id_gen;
13155 copy_register_state(dst_reg, src_reg);
13156 dst_reg->live |= REG_LIVE_WRITTEN;
13157 dst_reg->subreg_def = DEF_NOT_SUBREG;
13159 /* case: R1 = (s8, s16 s32)R2 */
13162 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13163 if (no_sext && need_id)
13164 src_reg->id = ++env->id_gen;
13165 copy_register_state(dst_reg, src_reg);
13168 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13169 dst_reg->live |= REG_LIVE_WRITTEN;
13170 dst_reg->subreg_def = DEF_NOT_SUBREG;
13173 /* R1 = (u32) R2 */
13174 if (is_pointer_value(env, insn->src_reg)) {
13176 "R%d partial copy of pointer\n",
13179 } else if (src_reg->type == SCALAR_VALUE) {
13180 if (insn->off == 0) {
13181 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13183 if (is_src_reg_u32 && need_id)
13184 src_reg->id = ++env->id_gen;
13185 copy_register_state(dst_reg, src_reg);
13186 /* Make sure ID is cleared if src_reg is not in u32
13187 * range otherwise dst_reg min/max could be incorrectly
13188 * propagated into src_reg by find_equal_scalars()
13190 if (!is_src_reg_u32)
13192 dst_reg->live |= REG_LIVE_WRITTEN;
13193 dst_reg->subreg_def = env->insn_idx + 1;
13195 /* case: W1 = (s8, s16)W2 */
13196 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13198 if (no_sext && need_id)
13199 src_reg->id = ++env->id_gen;
13200 copy_register_state(dst_reg, src_reg);
13203 dst_reg->live |= REG_LIVE_WRITTEN;
13204 dst_reg->subreg_def = env->insn_idx + 1;
13205 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13208 mark_reg_unknown(env, regs,
13211 zext_32_to_64(dst_reg);
13212 reg_bounds_sync(dst_reg);
13216 * remember the value we stored into this reg
13218 /* clear any state __mark_reg_known doesn't set */
13219 mark_reg_unknown(env, regs, insn->dst_reg);
13220 regs[insn->dst_reg].type = SCALAR_VALUE;
13221 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13222 __mark_reg_known(regs + insn->dst_reg,
13225 __mark_reg_known(regs + insn->dst_reg,
13230 } else if (opcode > BPF_END) {
13231 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13234 } else { /* all other ALU ops: and, sub, xor, add, ... */
13236 if (BPF_SRC(insn->code) == BPF_X) {
13237 if (insn->imm != 0 || insn->off != 0) {
13238 verbose(env, "BPF_ALU uses reserved fields\n");
13241 /* check src1 operand */
13242 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13246 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13247 verbose(env, "BPF_ALU uses reserved fields\n");
13252 /* check src2 operand */
13253 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13257 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13258 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13259 verbose(env, "div by zero\n");
13263 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13264 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13265 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13267 if (insn->imm < 0 || insn->imm >= size) {
13268 verbose(env, "invalid shift %d\n", insn->imm);
13273 /* check dest operand */
13274 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13278 return adjust_reg_min_max_vals(env, insn);
13284 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13285 struct bpf_reg_state *dst_reg,
13286 enum bpf_reg_type type,
13287 bool range_right_open)
13289 struct bpf_func_state *state;
13290 struct bpf_reg_state *reg;
13293 if (dst_reg->off < 0 ||
13294 (dst_reg->off == 0 && range_right_open))
13295 /* This doesn't give us any range */
13298 if (dst_reg->umax_value > MAX_PACKET_OFF ||
13299 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13300 /* Risk of overflow. For instance, ptr + (1<<63) may be less
13301 * than pkt_end, but that's because it's also less than pkt.
13305 new_range = dst_reg->off;
13306 if (range_right_open)
13309 /* Examples for register markings:
13311 * pkt_data in dst register:
13315 * if (r2 > pkt_end) goto <handle exception>
13320 * if (r2 < pkt_end) goto <access okay>
13321 * <handle exception>
13324 * r2 == dst_reg, pkt_end == src_reg
13325 * r2=pkt(id=n,off=8,r=0)
13326 * r3=pkt(id=n,off=0,r=0)
13328 * pkt_data in src register:
13332 * if (pkt_end >= r2) goto <access okay>
13333 * <handle exception>
13337 * if (pkt_end <= r2) goto <handle exception>
13341 * pkt_end == dst_reg, r2 == src_reg
13342 * r2=pkt(id=n,off=8,r=0)
13343 * r3=pkt(id=n,off=0,r=0)
13345 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13346 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13347 * and [r3, r3 + 8-1) respectively is safe to access depending on
13351 /* If our ids match, then we must have the same max_value. And we
13352 * don't care about the other reg's fixed offset, since if it's too big
13353 * the range won't allow anything.
13354 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13356 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13357 if (reg->type == type && reg->id == dst_reg->id)
13358 /* keep the maximum range already checked */
13359 reg->range = max(reg->range, new_range);
13363 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13365 struct tnum subreg = tnum_subreg(reg->var_off);
13366 s32 sval = (s32)val;
13370 if (tnum_is_const(subreg))
13371 return !!tnum_equals_const(subreg, val);
13372 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13376 if (tnum_is_const(subreg))
13377 return !tnum_equals_const(subreg, val);
13378 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13382 if ((~subreg.mask & subreg.value) & val)
13384 if (!((subreg.mask | subreg.value) & val))
13388 if (reg->u32_min_value > val)
13390 else if (reg->u32_max_value <= val)
13394 if (reg->s32_min_value > sval)
13396 else if (reg->s32_max_value <= sval)
13400 if (reg->u32_max_value < val)
13402 else if (reg->u32_min_value >= val)
13406 if (reg->s32_max_value < sval)
13408 else if (reg->s32_min_value >= sval)
13412 if (reg->u32_min_value >= val)
13414 else if (reg->u32_max_value < val)
13418 if (reg->s32_min_value >= sval)
13420 else if (reg->s32_max_value < sval)
13424 if (reg->u32_max_value <= val)
13426 else if (reg->u32_min_value > val)
13430 if (reg->s32_max_value <= sval)
13432 else if (reg->s32_min_value > sval)
13441 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13443 s64 sval = (s64)val;
13447 if (tnum_is_const(reg->var_off))
13448 return !!tnum_equals_const(reg->var_off, val);
13449 else if (val < reg->umin_value || val > reg->umax_value)
13453 if (tnum_is_const(reg->var_off))
13454 return !tnum_equals_const(reg->var_off, val);
13455 else if (val < reg->umin_value || val > reg->umax_value)
13459 if ((~reg->var_off.mask & reg->var_off.value) & val)
13461 if (!((reg->var_off.mask | reg->var_off.value) & val))
13465 if (reg->umin_value > val)
13467 else if (reg->umax_value <= val)
13471 if (reg->smin_value > sval)
13473 else if (reg->smax_value <= sval)
13477 if (reg->umax_value < val)
13479 else if (reg->umin_value >= val)
13483 if (reg->smax_value < sval)
13485 else if (reg->smin_value >= sval)
13489 if (reg->umin_value >= val)
13491 else if (reg->umax_value < val)
13495 if (reg->smin_value >= sval)
13497 else if (reg->smax_value < sval)
13501 if (reg->umax_value <= val)
13503 else if (reg->umin_value > val)
13507 if (reg->smax_value <= sval)
13509 else if (reg->smin_value > sval)
13517 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13519 * 1 - branch will be taken and "goto target" will be executed
13520 * 0 - branch will not be taken and fall-through to next insn
13521 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13524 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13527 if (__is_pointer_value(false, reg)) {
13528 if (!reg_not_null(reg))
13531 /* If pointer is valid tests against zero will fail so we can
13532 * use this to direct branch taken.
13548 return is_branch32_taken(reg, val, opcode);
13549 return is_branch64_taken(reg, val, opcode);
13552 static int flip_opcode(u32 opcode)
13554 /* How can we transform "a <op> b" into "b <op> a"? */
13555 static const u8 opcode_flip[16] = {
13556 /* these stay the same */
13557 [BPF_JEQ >> 4] = BPF_JEQ,
13558 [BPF_JNE >> 4] = BPF_JNE,
13559 [BPF_JSET >> 4] = BPF_JSET,
13560 /* these swap "lesser" and "greater" (L and G in the opcodes) */
13561 [BPF_JGE >> 4] = BPF_JLE,
13562 [BPF_JGT >> 4] = BPF_JLT,
13563 [BPF_JLE >> 4] = BPF_JGE,
13564 [BPF_JLT >> 4] = BPF_JGT,
13565 [BPF_JSGE >> 4] = BPF_JSLE,
13566 [BPF_JSGT >> 4] = BPF_JSLT,
13567 [BPF_JSLE >> 4] = BPF_JSGE,
13568 [BPF_JSLT >> 4] = BPF_JSGT
13570 return opcode_flip[opcode >> 4];
13573 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13574 struct bpf_reg_state *src_reg,
13577 struct bpf_reg_state *pkt;
13579 if (src_reg->type == PTR_TO_PACKET_END) {
13581 } else if (dst_reg->type == PTR_TO_PACKET_END) {
13583 opcode = flip_opcode(opcode);
13588 if (pkt->range >= 0)
13593 /* pkt <= pkt_end */
13596 /* pkt > pkt_end */
13597 if (pkt->range == BEYOND_PKT_END)
13598 /* pkt has at last one extra byte beyond pkt_end */
13599 return opcode == BPF_JGT;
13602 /* pkt < pkt_end */
13605 /* pkt >= pkt_end */
13606 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13607 return opcode == BPF_JGE;
13613 /* Adjusts the register min/max values in the case that the dst_reg is the
13614 * variable register that we are working on, and src_reg is a constant or we're
13615 * simply doing a BPF_K check.
13616 * In JEQ/JNE cases we also adjust the var_off values.
13618 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13619 struct bpf_reg_state *false_reg,
13620 u64 val, u32 val32,
13621 u8 opcode, bool is_jmp32)
13623 struct tnum false_32off = tnum_subreg(false_reg->var_off);
13624 struct tnum false_64off = false_reg->var_off;
13625 struct tnum true_32off = tnum_subreg(true_reg->var_off);
13626 struct tnum true_64off = true_reg->var_off;
13627 s64 sval = (s64)val;
13628 s32 sval32 = (s32)val32;
13630 /* If the dst_reg is a pointer, we can't learn anything about its
13631 * variable offset from the compare (unless src_reg were a pointer into
13632 * the same object, but we don't bother with that.
13633 * Since false_reg and true_reg have the same type by construction, we
13634 * only need to check one of them for pointerness.
13636 if (__is_pointer_value(false, false_reg))
13640 /* JEQ/JNE comparison doesn't change the register equivalence.
13643 * if (r1 == 42) goto label;
13645 * label: // here both r1 and r2 are known to be 42.
13647 * Hence when marking register as known preserve it's ID.
13651 __mark_reg32_known(true_reg, val32);
13652 true_32off = tnum_subreg(true_reg->var_off);
13654 ___mark_reg_known(true_reg, val);
13655 true_64off = true_reg->var_off;
13660 __mark_reg32_known(false_reg, val32);
13661 false_32off = tnum_subreg(false_reg->var_off);
13663 ___mark_reg_known(false_reg, val);
13664 false_64off = false_reg->var_off;
13669 false_32off = tnum_and(false_32off, tnum_const(~val32));
13670 if (is_power_of_2(val32))
13671 true_32off = tnum_or(true_32off,
13672 tnum_const(val32));
13674 false_64off = tnum_and(false_64off, tnum_const(~val));
13675 if (is_power_of_2(val))
13676 true_64off = tnum_or(true_64off,
13684 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
13685 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13687 false_reg->u32_max_value = min(false_reg->u32_max_value,
13689 true_reg->u32_min_value = max(true_reg->u32_min_value,
13692 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
13693 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13695 false_reg->umax_value = min(false_reg->umax_value, false_umax);
13696 true_reg->umin_value = max(true_reg->umin_value, true_umin);
13704 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
13705 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13707 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13708 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13710 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
13711 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13713 false_reg->smax_value = min(false_reg->smax_value, false_smax);
13714 true_reg->smin_value = max(true_reg->smin_value, true_smin);
13722 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
13723 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13725 false_reg->u32_min_value = max(false_reg->u32_min_value,
13727 true_reg->u32_max_value = min(true_reg->u32_max_value,
13730 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
13731 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13733 false_reg->umin_value = max(false_reg->umin_value, false_umin);
13734 true_reg->umax_value = min(true_reg->umax_value, true_umax);
13742 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
13743 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13745 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13746 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13748 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
13749 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13751 false_reg->smin_value = max(false_reg->smin_value, false_smin);
13752 true_reg->smax_value = min(true_reg->smax_value, true_smax);
13761 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13762 tnum_subreg(false_32off));
13763 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13764 tnum_subreg(true_32off));
13765 __reg_combine_32_into_64(false_reg);
13766 __reg_combine_32_into_64(true_reg);
13768 false_reg->var_off = false_64off;
13769 true_reg->var_off = true_64off;
13770 __reg_combine_64_into_32(false_reg);
13771 __reg_combine_64_into_32(true_reg);
13775 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13776 * the variable reg.
13778 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13779 struct bpf_reg_state *false_reg,
13780 u64 val, u32 val32,
13781 u8 opcode, bool is_jmp32)
13783 opcode = flip_opcode(opcode);
13784 /* This uses zero as "not present in table"; luckily the zero opcode,
13785 * BPF_JA, can't get here.
13788 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13791 /* Regs are known to be equal, so intersect their min/max/var_off */
13792 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13793 struct bpf_reg_state *dst_reg)
13795 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13796 dst_reg->umin_value);
13797 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13798 dst_reg->umax_value);
13799 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13800 dst_reg->smin_value);
13801 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13802 dst_reg->smax_value);
13803 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13805 reg_bounds_sync(src_reg);
13806 reg_bounds_sync(dst_reg);
13809 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13810 struct bpf_reg_state *true_dst,
13811 struct bpf_reg_state *false_src,
13812 struct bpf_reg_state *false_dst,
13817 __reg_combine_min_max(true_src, true_dst);
13820 __reg_combine_min_max(false_src, false_dst);
13825 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13826 struct bpf_reg_state *reg, u32 id,
13829 if (type_may_be_null(reg->type) && reg->id == id &&
13830 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13831 /* Old offset (both fixed and variable parts) should have been
13832 * known-zero, because we don't allow pointer arithmetic on
13833 * pointers that might be NULL. If we see this happening, don't
13834 * convert the register.
13836 * But in some cases, some helpers that return local kptrs
13837 * advance offset for the returned pointer. In those cases, it
13838 * is fine to expect to see reg->off.
13840 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13842 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13843 WARN_ON_ONCE(reg->off))
13847 reg->type = SCALAR_VALUE;
13848 /* We don't need id and ref_obj_id from this point
13849 * onwards anymore, thus we should better reset it,
13850 * so that state pruning has chances to take effect.
13853 reg->ref_obj_id = 0;
13858 mark_ptr_not_null_reg(reg);
13860 if (!reg_may_point_to_spin_lock(reg)) {
13861 /* For not-NULL ptr, reg->ref_obj_id will be reset
13862 * in release_reference().
13864 * reg->id is still used by spin_lock ptr. Other
13865 * than spin_lock ptr type, reg->id can be reset.
13872 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13873 * be folded together at some point.
13875 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13878 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13879 struct bpf_reg_state *regs = state->regs, *reg;
13880 u32 ref_obj_id = regs[regno].ref_obj_id;
13881 u32 id = regs[regno].id;
13883 if (ref_obj_id && ref_obj_id == id && is_null)
13884 /* regs[regno] is in the " == NULL" branch.
13885 * No one could have freed the reference state before
13886 * doing the NULL check.
13888 WARN_ON_ONCE(release_reference_state(state, id));
13890 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13891 mark_ptr_or_null_reg(state, reg, id, is_null);
13895 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13896 struct bpf_reg_state *dst_reg,
13897 struct bpf_reg_state *src_reg,
13898 struct bpf_verifier_state *this_branch,
13899 struct bpf_verifier_state *other_branch)
13901 if (BPF_SRC(insn->code) != BPF_X)
13904 /* Pointers are always 64-bit. */
13905 if (BPF_CLASS(insn->code) == BPF_JMP32)
13908 switch (BPF_OP(insn->code)) {
13910 if ((dst_reg->type == PTR_TO_PACKET &&
13911 src_reg->type == PTR_TO_PACKET_END) ||
13912 (dst_reg->type == PTR_TO_PACKET_META &&
13913 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13914 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13915 find_good_pkt_pointers(this_branch, dst_reg,
13916 dst_reg->type, false);
13917 mark_pkt_end(other_branch, insn->dst_reg, true);
13918 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13919 src_reg->type == PTR_TO_PACKET) ||
13920 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13921 src_reg->type == PTR_TO_PACKET_META)) {
13922 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13923 find_good_pkt_pointers(other_branch, src_reg,
13924 src_reg->type, true);
13925 mark_pkt_end(this_branch, insn->src_reg, false);
13931 if ((dst_reg->type == PTR_TO_PACKET &&
13932 src_reg->type == PTR_TO_PACKET_END) ||
13933 (dst_reg->type == PTR_TO_PACKET_META &&
13934 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13935 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13936 find_good_pkt_pointers(other_branch, dst_reg,
13937 dst_reg->type, true);
13938 mark_pkt_end(this_branch, insn->dst_reg, false);
13939 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13940 src_reg->type == PTR_TO_PACKET) ||
13941 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13942 src_reg->type == PTR_TO_PACKET_META)) {
13943 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13944 find_good_pkt_pointers(this_branch, src_reg,
13945 src_reg->type, false);
13946 mark_pkt_end(other_branch, insn->src_reg, true);
13952 if ((dst_reg->type == PTR_TO_PACKET &&
13953 src_reg->type == PTR_TO_PACKET_END) ||
13954 (dst_reg->type == PTR_TO_PACKET_META &&
13955 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13956 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13957 find_good_pkt_pointers(this_branch, dst_reg,
13958 dst_reg->type, true);
13959 mark_pkt_end(other_branch, insn->dst_reg, false);
13960 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13961 src_reg->type == PTR_TO_PACKET) ||
13962 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13963 src_reg->type == PTR_TO_PACKET_META)) {
13964 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13965 find_good_pkt_pointers(other_branch, src_reg,
13966 src_reg->type, false);
13967 mark_pkt_end(this_branch, insn->src_reg, true);
13973 if ((dst_reg->type == PTR_TO_PACKET &&
13974 src_reg->type == PTR_TO_PACKET_END) ||
13975 (dst_reg->type == PTR_TO_PACKET_META &&
13976 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13977 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13978 find_good_pkt_pointers(other_branch, dst_reg,
13979 dst_reg->type, false);
13980 mark_pkt_end(this_branch, insn->dst_reg, true);
13981 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13982 src_reg->type == PTR_TO_PACKET) ||
13983 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13984 src_reg->type == PTR_TO_PACKET_META)) {
13985 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13986 find_good_pkt_pointers(this_branch, src_reg,
13987 src_reg->type, true);
13988 mark_pkt_end(other_branch, insn->src_reg, false);
14000 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14001 struct bpf_reg_state *known_reg)
14003 struct bpf_func_state *state;
14004 struct bpf_reg_state *reg;
14006 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14007 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14008 copy_register_state(reg, known_reg);
14012 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14013 struct bpf_insn *insn, int *insn_idx)
14015 struct bpf_verifier_state *this_branch = env->cur_state;
14016 struct bpf_verifier_state *other_branch;
14017 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14018 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14019 struct bpf_reg_state *eq_branch_regs;
14020 u8 opcode = BPF_OP(insn->code);
14025 /* Only conditional jumps are expected to reach here. */
14026 if (opcode == BPF_JA || opcode > BPF_JSLE) {
14027 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14031 if (BPF_SRC(insn->code) == BPF_X) {
14032 if (insn->imm != 0) {
14033 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14037 /* check src1 operand */
14038 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14042 if (is_pointer_value(env, insn->src_reg)) {
14043 verbose(env, "R%d pointer comparison prohibited\n",
14047 src_reg = ®s[insn->src_reg];
14049 if (insn->src_reg != BPF_REG_0) {
14050 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14055 /* check src2 operand */
14056 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14060 dst_reg = ®s[insn->dst_reg];
14061 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14063 if (BPF_SRC(insn->code) == BPF_K) {
14064 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14065 } else if (src_reg->type == SCALAR_VALUE &&
14066 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14067 pred = is_branch_taken(dst_reg,
14068 tnum_subreg(src_reg->var_off).value,
14071 } else if (src_reg->type == SCALAR_VALUE &&
14072 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14073 pred = is_branch_taken(dst_reg,
14074 src_reg->var_off.value,
14077 } else if (dst_reg->type == SCALAR_VALUE &&
14078 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14079 pred = is_branch_taken(src_reg,
14080 tnum_subreg(dst_reg->var_off).value,
14081 flip_opcode(opcode),
14083 } else if (dst_reg->type == SCALAR_VALUE &&
14084 !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14085 pred = is_branch_taken(src_reg,
14086 dst_reg->var_off.value,
14087 flip_opcode(opcode),
14089 } else if (reg_is_pkt_pointer_any(dst_reg) &&
14090 reg_is_pkt_pointer_any(src_reg) &&
14092 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14096 /* If we get here with a dst_reg pointer type it is because
14097 * above is_branch_taken() special cased the 0 comparison.
14099 if (!__is_pointer_value(false, dst_reg))
14100 err = mark_chain_precision(env, insn->dst_reg);
14101 if (BPF_SRC(insn->code) == BPF_X && !err &&
14102 !__is_pointer_value(false, src_reg))
14103 err = mark_chain_precision(env, insn->src_reg);
14109 /* Only follow the goto, ignore fall-through. If needed, push
14110 * the fall-through branch for simulation under speculative
14113 if (!env->bypass_spec_v1 &&
14114 !sanitize_speculative_path(env, insn, *insn_idx + 1,
14117 *insn_idx += insn->off;
14119 } else if (pred == 0) {
14120 /* Only follow the fall-through branch, since that's where the
14121 * program will go. If needed, push the goto branch for
14122 * simulation under speculative execution.
14124 if (!env->bypass_spec_v1 &&
14125 !sanitize_speculative_path(env, insn,
14126 *insn_idx + insn->off + 1,
14132 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14136 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14138 /* detect if we are comparing against a constant value so we can adjust
14139 * our min/max values for our dst register.
14140 * this is only legit if both are scalars (or pointers to the same
14141 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14142 * because otherwise the different base pointers mean the offsets aren't
14145 if (BPF_SRC(insn->code) == BPF_X) {
14146 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
14148 if (dst_reg->type == SCALAR_VALUE &&
14149 src_reg->type == SCALAR_VALUE) {
14150 if (tnum_is_const(src_reg->var_off) ||
14152 tnum_is_const(tnum_subreg(src_reg->var_off))))
14153 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14155 src_reg->var_off.value,
14156 tnum_subreg(src_reg->var_off).value,
14158 else if (tnum_is_const(dst_reg->var_off) ||
14160 tnum_is_const(tnum_subreg(dst_reg->var_off))))
14161 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14163 dst_reg->var_off.value,
14164 tnum_subreg(dst_reg->var_off).value,
14166 else if (!is_jmp32 &&
14167 (opcode == BPF_JEQ || opcode == BPF_JNE))
14168 /* Comparing for equality, we can combine knowledge */
14169 reg_combine_min_max(&other_branch_regs[insn->src_reg],
14170 &other_branch_regs[insn->dst_reg],
14171 src_reg, dst_reg, opcode);
14173 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14174 find_equal_scalars(this_branch, src_reg);
14175 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14179 } else if (dst_reg->type == SCALAR_VALUE) {
14180 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14181 dst_reg, insn->imm, (u32)insn->imm,
14185 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14186 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14187 find_equal_scalars(this_branch, dst_reg);
14188 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14191 /* if one pointer register is compared to another pointer
14192 * register check if PTR_MAYBE_NULL could be lifted.
14193 * E.g. register A - maybe null
14194 * register B - not null
14195 * for JNE A, B, ... - A is not null in the false branch;
14196 * for JEQ A, B, ... - A is not null in the true branch.
14198 * Since PTR_TO_BTF_ID points to a kernel struct that does
14199 * not need to be null checked by the BPF program, i.e.,
14200 * could be null even without PTR_MAYBE_NULL marking, so
14201 * only propagate nullness when neither reg is that type.
14203 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14204 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14205 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14206 base_type(src_reg->type) != PTR_TO_BTF_ID &&
14207 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14208 eq_branch_regs = NULL;
14211 eq_branch_regs = other_branch_regs;
14214 eq_branch_regs = regs;
14220 if (eq_branch_regs) {
14221 if (type_may_be_null(src_reg->type))
14222 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14224 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14228 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14229 * NOTE: these optimizations below are related with pointer comparison
14230 * which will never be JMP32.
14232 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14233 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14234 type_may_be_null(dst_reg->type)) {
14235 /* Mark all identical registers in each branch as either
14236 * safe or unknown depending R == 0 or R != 0 conditional.
14238 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14239 opcode == BPF_JNE);
14240 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14241 opcode == BPF_JEQ);
14242 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
14243 this_branch, other_branch) &&
14244 is_pointer_value(env, insn->dst_reg)) {
14245 verbose(env, "R%d pointer comparison prohibited\n",
14249 if (env->log.level & BPF_LOG_LEVEL)
14250 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14254 /* verify BPF_LD_IMM64 instruction */
14255 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14257 struct bpf_insn_aux_data *aux = cur_aux(env);
14258 struct bpf_reg_state *regs = cur_regs(env);
14259 struct bpf_reg_state *dst_reg;
14260 struct bpf_map *map;
14263 if (BPF_SIZE(insn->code) != BPF_DW) {
14264 verbose(env, "invalid BPF_LD_IMM insn\n");
14267 if (insn->off != 0) {
14268 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14272 err = check_reg_arg(env, insn->dst_reg, DST_OP);
14276 dst_reg = ®s[insn->dst_reg];
14277 if (insn->src_reg == 0) {
14278 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14280 dst_reg->type = SCALAR_VALUE;
14281 __mark_reg_known(®s[insn->dst_reg], imm);
14285 /* All special src_reg cases are listed below. From this point onwards
14286 * we either succeed and assign a corresponding dst_reg->type after
14287 * zeroing the offset, or fail and reject the program.
14289 mark_reg_known_zero(env, regs, insn->dst_reg);
14291 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14292 dst_reg->type = aux->btf_var.reg_type;
14293 switch (base_type(dst_reg->type)) {
14295 dst_reg->mem_size = aux->btf_var.mem_size;
14297 case PTR_TO_BTF_ID:
14298 dst_reg->btf = aux->btf_var.btf;
14299 dst_reg->btf_id = aux->btf_var.btf_id;
14302 verbose(env, "bpf verifier is misconfigured\n");
14308 if (insn->src_reg == BPF_PSEUDO_FUNC) {
14309 struct bpf_prog_aux *aux = env->prog->aux;
14310 u32 subprogno = find_subprog(env,
14311 env->insn_idx + insn->imm + 1);
14313 if (!aux->func_info) {
14314 verbose(env, "missing btf func_info\n");
14317 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14318 verbose(env, "callback function not static\n");
14322 dst_reg->type = PTR_TO_FUNC;
14323 dst_reg->subprogno = subprogno;
14327 map = env->used_maps[aux->map_index];
14328 dst_reg->map_ptr = map;
14330 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14331 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14332 dst_reg->type = PTR_TO_MAP_VALUE;
14333 dst_reg->off = aux->map_off;
14334 WARN_ON_ONCE(map->max_entries != 1);
14335 /* We want reg->id to be same (0) as map_value is not distinct */
14336 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14337 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14338 dst_reg->type = CONST_PTR_TO_MAP;
14340 verbose(env, "bpf verifier is misconfigured\n");
14347 static bool may_access_skb(enum bpf_prog_type type)
14350 case BPF_PROG_TYPE_SOCKET_FILTER:
14351 case BPF_PROG_TYPE_SCHED_CLS:
14352 case BPF_PROG_TYPE_SCHED_ACT:
14359 /* verify safety of LD_ABS|LD_IND instructions:
14360 * - they can only appear in the programs where ctx == skb
14361 * - since they are wrappers of function calls, they scratch R1-R5 registers,
14362 * preserve R6-R9, and store return value into R0
14365 * ctx == skb == R6 == CTX
14368 * SRC == any register
14369 * IMM == 32-bit immediate
14372 * R0 - 8/16/32-bit skb data converted to cpu endianness
14374 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14376 struct bpf_reg_state *regs = cur_regs(env);
14377 static const int ctx_reg = BPF_REG_6;
14378 u8 mode = BPF_MODE(insn->code);
14381 if (!may_access_skb(resolve_prog_type(env->prog))) {
14382 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14386 if (!env->ops->gen_ld_abs) {
14387 verbose(env, "bpf verifier is misconfigured\n");
14391 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14392 BPF_SIZE(insn->code) == BPF_DW ||
14393 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14394 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14398 /* check whether implicit source operand (register R6) is readable */
14399 err = check_reg_arg(env, ctx_reg, SRC_OP);
14403 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14404 * gen_ld_abs() may terminate the program at runtime, leading to
14407 err = check_reference_leak(env);
14409 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14413 if (env->cur_state->active_lock.ptr) {
14414 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14418 if (env->cur_state->active_rcu_lock) {
14419 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14423 if (regs[ctx_reg].type != PTR_TO_CTX) {
14425 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14429 if (mode == BPF_IND) {
14430 /* check explicit source operand */
14431 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14436 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
14440 /* reset caller saved regs to unreadable */
14441 for (i = 0; i < CALLER_SAVED_REGS; i++) {
14442 mark_reg_not_init(env, regs, caller_saved[i]);
14443 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14446 /* mark destination R0 register as readable, since it contains
14447 * the value fetched from the packet.
14448 * Already marked as written above.
14450 mark_reg_unknown(env, regs, BPF_REG_0);
14451 /* ld_abs load up to 32-bit skb data. */
14452 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14456 static int check_return_code(struct bpf_verifier_env *env)
14458 struct tnum enforce_attach_type_range = tnum_unknown;
14459 const struct bpf_prog *prog = env->prog;
14460 struct bpf_reg_state *reg;
14461 struct tnum range = tnum_range(0, 1);
14462 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14464 struct bpf_func_state *frame = env->cur_state->frame[0];
14465 const bool is_subprog = frame->subprogno;
14467 /* LSM and struct_ops func-ptr's return type could be "void" */
14469 switch (prog_type) {
14470 case BPF_PROG_TYPE_LSM:
14471 if (prog->expected_attach_type == BPF_LSM_CGROUP)
14472 /* See below, can be 0 or 0-1 depending on hook. */
14475 case BPF_PROG_TYPE_STRUCT_OPS:
14476 if (!prog->aux->attach_func_proto->type)
14484 /* eBPF calling convention is such that R0 is used
14485 * to return the value from eBPF program.
14486 * Make sure that it's readable at this time
14487 * of bpf_exit, which means that program wrote
14488 * something into it earlier
14490 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14494 if (is_pointer_value(env, BPF_REG_0)) {
14495 verbose(env, "R0 leaks addr as return value\n");
14499 reg = cur_regs(env) + BPF_REG_0;
14501 if (frame->in_async_callback_fn) {
14502 /* enforce return zero from async callbacks like timer */
14503 if (reg->type != SCALAR_VALUE) {
14504 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14505 reg_type_str(env, reg->type));
14509 if (!tnum_in(tnum_const(0), reg->var_off)) {
14510 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
14517 if (reg->type != SCALAR_VALUE) {
14518 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14519 reg_type_str(env, reg->type));
14525 switch (prog_type) {
14526 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14527 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14528 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14529 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14530 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14531 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14532 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14533 range = tnum_range(1, 1);
14534 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14535 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14536 range = tnum_range(0, 3);
14538 case BPF_PROG_TYPE_CGROUP_SKB:
14539 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14540 range = tnum_range(0, 3);
14541 enforce_attach_type_range = tnum_range(2, 3);
14544 case BPF_PROG_TYPE_CGROUP_SOCK:
14545 case BPF_PROG_TYPE_SOCK_OPS:
14546 case BPF_PROG_TYPE_CGROUP_DEVICE:
14547 case BPF_PROG_TYPE_CGROUP_SYSCTL:
14548 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14550 case BPF_PROG_TYPE_RAW_TRACEPOINT:
14551 if (!env->prog->aux->attach_btf_id)
14553 range = tnum_const(0);
14555 case BPF_PROG_TYPE_TRACING:
14556 switch (env->prog->expected_attach_type) {
14557 case BPF_TRACE_FENTRY:
14558 case BPF_TRACE_FEXIT:
14559 range = tnum_const(0);
14561 case BPF_TRACE_RAW_TP:
14562 case BPF_MODIFY_RETURN:
14564 case BPF_TRACE_ITER:
14570 case BPF_PROG_TYPE_SK_LOOKUP:
14571 range = tnum_range(SK_DROP, SK_PASS);
14574 case BPF_PROG_TYPE_LSM:
14575 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14576 /* Regular BPF_PROG_TYPE_LSM programs can return
14581 if (!env->prog->aux->attach_func_proto->type) {
14582 /* Make sure programs that attach to void
14583 * hooks don't try to modify return value.
14585 range = tnum_range(1, 1);
14589 case BPF_PROG_TYPE_NETFILTER:
14590 range = tnum_range(NF_DROP, NF_ACCEPT);
14592 case BPF_PROG_TYPE_EXT:
14593 /* freplace program can return anything as its return value
14594 * depends on the to-be-replaced kernel func or bpf program.
14600 if (reg->type != SCALAR_VALUE) {
14601 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14602 reg_type_str(env, reg->type));
14606 if (!tnum_in(range, reg->var_off)) {
14607 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14608 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14609 prog_type == BPF_PROG_TYPE_LSM &&
14610 !prog->aux->attach_func_proto->type)
14611 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14615 if (!tnum_is_unknown(enforce_attach_type_range) &&
14616 tnum_in(enforce_attach_type_range, reg->var_off))
14617 env->prog->enforce_expected_attach_type = 1;
14621 /* non-recursive DFS pseudo code
14622 * 1 procedure DFS-iterative(G,v):
14623 * 2 label v as discovered
14624 * 3 let S be a stack
14626 * 5 while S is not empty
14628 * 7 if t is what we're looking for:
14630 * 9 for all edges e in G.adjacentEdges(t) do
14631 * 10 if edge e is already labelled
14632 * 11 continue with the next edge
14633 * 12 w <- G.adjacentVertex(t,e)
14634 * 13 if vertex w is not discovered and not explored
14635 * 14 label e as tree-edge
14636 * 15 label w as discovered
14639 * 18 else if vertex w is discovered
14640 * 19 label e as back-edge
14642 * 21 // vertex w is explored
14643 * 22 label e as forward- or cross-edge
14644 * 23 label t as explored
14648 * 0x10 - discovered
14649 * 0x11 - discovered and fall-through edge labelled
14650 * 0x12 - discovered and fall-through and branch edges labelled
14661 static u32 state_htab_size(struct bpf_verifier_env *env)
14663 return env->prog->len;
14666 static struct bpf_verifier_state_list **explored_state(
14667 struct bpf_verifier_env *env,
14670 struct bpf_verifier_state *cur = env->cur_state;
14671 struct bpf_func_state *state = cur->frame[cur->curframe];
14673 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14676 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14678 env->insn_aux_data[idx].prune_point = true;
14681 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14683 return env->insn_aux_data[insn_idx].prune_point;
14686 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14688 env->insn_aux_data[idx].force_checkpoint = true;
14691 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14693 return env->insn_aux_data[insn_idx].force_checkpoint;
14698 DONE_EXPLORING = 0,
14699 KEEP_EXPLORING = 1,
14702 /* t, w, e - match pseudo-code above:
14703 * t - index of current instruction
14704 * w - next instruction
14707 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14710 int *insn_stack = env->cfg.insn_stack;
14711 int *insn_state = env->cfg.insn_state;
14713 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14714 return DONE_EXPLORING;
14716 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14717 return DONE_EXPLORING;
14719 if (w < 0 || w >= env->prog->len) {
14720 verbose_linfo(env, t, "%d: ", t);
14721 verbose(env, "jump out of range from insn %d to %d\n", t, w);
14726 /* mark branch target for state pruning */
14727 mark_prune_point(env, w);
14728 mark_jmp_point(env, w);
14731 if (insn_state[w] == 0) {
14733 insn_state[t] = DISCOVERED | e;
14734 insn_state[w] = DISCOVERED;
14735 if (env->cfg.cur_stack >= env->prog->len)
14737 insn_stack[env->cfg.cur_stack++] = w;
14738 return KEEP_EXPLORING;
14739 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14740 if (loop_ok && env->bpf_capable)
14741 return DONE_EXPLORING;
14742 verbose_linfo(env, t, "%d: ", t);
14743 verbose_linfo(env, w, "%d: ", w);
14744 verbose(env, "back-edge from insn %d to %d\n", t, w);
14746 } else if (insn_state[w] == EXPLORED) {
14747 /* forward- or cross-edge */
14748 insn_state[t] = DISCOVERED | e;
14750 verbose(env, "insn state internal bug\n");
14753 return DONE_EXPLORING;
14756 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14757 struct bpf_verifier_env *env,
14762 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14766 mark_prune_point(env, t + 1);
14767 /* when we exit from subprog, we need to record non-linear history */
14768 mark_jmp_point(env, t + 1);
14770 if (visit_callee) {
14771 mark_prune_point(env, t);
14772 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14773 /* It's ok to allow recursion from CFG point of
14774 * view. __check_func_call() will do the actual
14777 bpf_pseudo_func(insns + t));
14782 /* Visits the instruction at index t and returns one of the following:
14783 * < 0 - an error occurred
14784 * DONE_EXPLORING - the instruction was fully explored
14785 * KEEP_EXPLORING - there is still work to be done before it is fully explored
14787 static int visit_insn(int t, struct bpf_verifier_env *env)
14789 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14792 if (bpf_pseudo_func(insn))
14793 return visit_func_call_insn(t, insns, env, true);
14795 /* All non-branch instructions have a single fall-through edge. */
14796 if (BPF_CLASS(insn->code) != BPF_JMP &&
14797 BPF_CLASS(insn->code) != BPF_JMP32)
14798 return push_insn(t, t + 1, FALLTHROUGH, env, false);
14800 switch (BPF_OP(insn->code)) {
14802 return DONE_EXPLORING;
14805 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14806 /* Mark this call insn as a prune point to trigger
14807 * is_state_visited() check before call itself is
14808 * processed by __check_func_call(). Otherwise new
14809 * async state will be pushed for further exploration.
14811 mark_prune_point(env, t);
14812 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14813 struct bpf_kfunc_call_arg_meta meta;
14815 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14816 if (ret == 0 && is_iter_next_kfunc(&meta)) {
14817 mark_prune_point(env, t);
14818 /* Checking and saving state checkpoints at iter_next() call
14819 * is crucial for fast convergence of open-coded iterator loop
14820 * logic, so we need to force it. If we don't do that,
14821 * is_state_visited() might skip saving a checkpoint, causing
14822 * unnecessarily long sequence of not checkpointed
14823 * instructions and jumps, leading to exhaustion of jump
14824 * history buffer, and potentially other undesired outcomes.
14825 * It is expected that with correct open-coded iterators
14826 * convergence will happen quickly, so we don't run a risk of
14827 * exhausting memory.
14829 mark_force_checkpoint(env, t);
14832 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14835 if (BPF_SRC(insn->code) != BPF_K)
14838 /* unconditional jump with single edge */
14839 ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
14844 mark_prune_point(env, t + insn->off + 1);
14845 mark_jmp_point(env, t + insn->off + 1);
14850 /* conditional jump with two edges */
14851 mark_prune_point(env, t);
14853 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14857 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14861 /* non-recursive depth-first-search to detect loops in BPF program
14862 * loop == back-edge in directed graph
14864 static int check_cfg(struct bpf_verifier_env *env)
14866 int insn_cnt = env->prog->len;
14867 int *insn_stack, *insn_state;
14871 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14875 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14877 kvfree(insn_state);
14881 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14882 insn_stack[0] = 0; /* 0 is the first instruction */
14883 env->cfg.cur_stack = 1;
14885 while (env->cfg.cur_stack > 0) {
14886 int t = insn_stack[env->cfg.cur_stack - 1];
14888 ret = visit_insn(t, env);
14890 case DONE_EXPLORING:
14891 insn_state[t] = EXPLORED;
14892 env->cfg.cur_stack--;
14894 case KEEP_EXPLORING:
14898 verbose(env, "visit_insn internal bug\n");
14905 if (env->cfg.cur_stack < 0) {
14906 verbose(env, "pop stack internal bug\n");
14911 for (i = 0; i < insn_cnt; i++) {
14912 if (insn_state[i] != EXPLORED) {
14913 verbose(env, "unreachable insn %d\n", i);
14918 ret = 0; /* cfg looks good */
14921 kvfree(insn_state);
14922 kvfree(insn_stack);
14923 env->cfg.insn_state = env->cfg.insn_stack = NULL;
14927 static int check_abnormal_return(struct bpf_verifier_env *env)
14931 for (i = 1; i < env->subprog_cnt; i++) {
14932 if (env->subprog_info[i].has_ld_abs) {
14933 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14936 if (env->subprog_info[i].has_tail_call) {
14937 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14944 /* The minimum supported BTF func info size */
14945 #define MIN_BPF_FUNCINFO_SIZE 8
14946 #define MAX_FUNCINFO_REC_SIZE 252
14948 static int check_btf_func(struct bpf_verifier_env *env,
14949 const union bpf_attr *attr,
14952 const struct btf_type *type, *func_proto, *ret_type;
14953 u32 i, nfuncs, urec_size, min_size;
14954 u32 krec_size = sizeof(struct bpf_func_info);
14955 struct bpf_func_info *krecord;
14956 struct bpf_func_info_aux *info_aux = NULL;
14957 struct bpf_prog *prog;
14958 const struct btf *btf;
14960 u32 prev_offset = 0;
14961 bool scalar_return;
14964 nfuncs = attr->func_info_cnt;
14966 if (check_abnormal_return(env))
14971 if (nfuncs != env->subprog_cnt) {
14972 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14976 urec_size = attr->func_info_rec_size;
14977 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14978 urec_size > MAX_FUNCINFO_REC_SIZE ||
14979 urec_size % sizeof(u32)) {
14980 verbose(env, "invalid func info rec size %u\n", urec_size);
14985 btf = prog->aux->btf;
14987 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
14988 min_size = min_t(u32, krec_size, urec_size);
14990 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
14993 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
14997 for (i = 0; i < nfuncs; i++) {
14998 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15000 if (ret == -E2BIG) {
15001 verbose(env, "nonzero tailing record in func info");
15002 /* set the size kernel expects so loader can zero
15003 * out the rest of the record.
15005 if (copy_to_bpfptr_offset(uattr,
15006 offsetof(union bpf_attr, func_info_rec_size),
15007 &min_size, sizeof(min_size)))
15013 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15018 /* check insn_off */
15021 if (krecord[i].insn_off) {
15023 "nonzero insn_off %u for the first func info record",
15024 krecord[i].insn_off);
15027 } else if (krecord[i].insn_off <= prev_offset) {
15029 "same or smaller insn offset (%u) than previous func info record (%u)",
15030 krecord[i].insn_off, prev_offset);
15034 if (env->subprog_info[i].start != krecord[i].insn_off) {
15035 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15039 /* check type_id */
15040 type = btf_type_by_id(btf, krecord[i].type_id);
15041 if (!type || !btf_type_is_func(type)) {
15042 verbose(env, "invalid type id %d in func info",
15043 krecord[i].type_id);
15046 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15048 func_proto = btf_type_by_id(btf, type->type);
15049 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15050 /* btf_func_check() already verified it during BTF load */
15052 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15054 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15055 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15056 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15059 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15060 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15064 prev_offset = krecord[i].insn_off;
15065 bpfptr_add(&urecord, urec_size);
15068 prog->aux->func_info = krecord;
15069 prog->aux->func_info_cnt = nfuncs;
15070 prog->aux->func_info_aux = info_aux;
15079 static void adjust_btf_func(struct bpf_verifier_env *env)
15081 struct bpf_prog_aux *aux = env->prog->aux;
15084 if (!aux->func_info)
15087 for (i = 0; i < env->subprog_cnt; i++)
15088 aux->func_info[i].insn_off = env->subprog_info[i].start;
15091 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
15092 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
15094 static int check_btf_line(struct bpf_verifier_env *env,
15095 const union bpf_attr *attr,
15098 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15099 struct bpf_subprog_info *sub;
15100 struct bpf_line_info *linfo;
15101 struct bpf_prog *prog;
15102 const struct btf *btf;
15106 nr_linfo = attr->line_info_cnt;
15109 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15112 rec_size = attr->line_info_rec_size;
15113 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15114 rec_size > MAX_LINEINFO_REC_SIZE ||
15115 rec_size & (sizeof(u32) - 1))
15118 /* Need to zero it in case the userspace may
15119 * pass in a smaller bpf_line_info object.
15121 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15122 GFP_KERNEL | __GFP_NOWARN);
15127 btf = prog->aux->btf;
15130 sub = env->subprog_info;
15131 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15132 expected_size = sizeof(struct bpf_line_info);
15133 ncopy = min_t(u32, expected_size, rec_size);
15134 for (i = 0; i < nr_linfo; i++) {
15135 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15137 if (err == -E2BIG) {
15138 verbose(env, "nonzero tailing record in line_info");
15139 if (copy_to_bpfptr_offset(uattr,
15140 offsetof(union bpf_attr, line_info_rec_size),
15141 &expected_size, sizeof(expected_size)))
15147 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15153 * Check insn_off to ensure
15154 * 1) strictly increasing AND
15155 * 2) bounded by prog->len
15157 * The linfo[0].insn_off == 0 check logically falls into
15158 * the later "missing bpf_line_info for func..." case
15159 * because the first linfo[0].insn_off must be the
15160 * first sub also and the first sub must have
15161 * subprog_info[0].start == 0.
15163 if ((i && linfo[i].insn_off <= prev_offset) ||
15164 linfo[i].insn_off >= prog->len) {
15165 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15166 i, linfo[i].insn_off, prev_offset,
15172 if (!prog->insnsi[linfo[i].insn_off].code) {
15174 "Invalid insn code at line_info[%u].insn_off\n",
15180 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15181 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15182 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15187 if (s != env->subprog_cnt) {
15188 if (linfo[i].insn_off == sub[s].start) {
15189 sub[s].linfo_idx = i;
15191 } else if (sub[s].start < linfo[i].insn_off) {
15192 verbose(env, "missing bpf_line_info for func#%u\n", s);
15198 prev_offset = linfo[i].insn_off;
15199 bpfptr_add(&ulinfo, rec_size);
15202 if (s != env->subprog_cnt) {
15203 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15204 env->subprog_cnt - s, s);
15209 prog->aux->linfo = linfo;
15210 prog->aux->nr_linfo = nr_linfo;
15219 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
15220 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
15222 static int check_core_relo(struct bpf_verifier_env *env,
15223 const union bpf_attr *attr,
15226 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15227 struct bpf_core_relo core_relo = {};
15228 struct bpf_prog *prog = env->prog;
15229 const struct btf *btf = prog->aux->btf;
15230 struct bpf_core_ctx ctx = {
15234 bpfptr_t u_core_relo;
15237 nr_core_relo = attr->core_relo_cnt;
15240 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15243 rec_size = attr->core_relo_rec_size;
15244 if (rec_size < MIN_CORE_RELO_SIZE ||
15245 rec_size > MAX_CORE_RELO_SIZE ||
15246 rec_size % sizeof(u32))
15249 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15250 expected_size = sizeof(struct bpf_core_relo);
15251 ncopy = min_t(u32, expected_size, rec_size);
15253 /* Unlike func_info and line_info, copy and apply each CO-RE
15254 * relocation record one at a time.
15256 for (i = 0; i < nr_core_relo; i++) {
15257 /* future proofing when sizeof(bpf_core_relo) changes */
15258 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15260 if (err == -E2BIG) {
15261 verbose(env, "nonzero tailing record in core_relo");
15262 if (copy_to_bpfptr_offset(uattr,
15263 offsetof(union bpf_attr, core_relo_rec_size),
15264 &expected_size, sizeof(expected_size)))
15270 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15275 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15276 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15277 i, core_relo.insn_off, prog->len);
15282 err = bpf_core_apply(&ctx, &core_relo, i,
15283 &prog->insnsi[core_relo.insn_off / 8]);
15286 bpfptr_add(&u_core_relo, rec_size);
15291 static int check_btf_info(struct bpf_verifier_env *env,
15292 const union bpf_attr *attr,
15298 if (!attr->func_info_cnt && !attr->line_info_cnt) {
15299 if (check_abnormal_return(env))
15304 btf = btf_get_by_fd(attr->prog_btf_fd);
15306 return PTR_ERR(btf);
15307 if (btf_is_kernel(btf)) {
15311 env->prog->aux->btf = btf;
15313 err = check_btf_func(env, attr, uattr);
15317 err = check_btf_line(env, attr, uattr);
15321 err = check_core_relo(env, attr, uattr);
15328 /* check %cur's range satisfies %old's */
15329 static bool range_within(struct bpf_reg_state *old,
15330 struct bpf_reg_state *cur)
15332 return old->umin_value <= cur->umin_value &&
15333 old->umax_value >= cur->umax_value &&
15334 old->smin_value <= cur->smin_value &&
15335 old->smax_value >= cur->smax_value &&
15336 old->u32_min_value <= cur->u32_min_value &&
15337 old->u32_max_value >= cur->u32_max_value &&
15338 old->s32_min_value <= cur->s32_min_value &&
15339 old->s32_max_value >= cur->s32_max_value;
15342 /* If in the old state two registers had the same id, then they need to have
15343 * the same id in the new state as well. But that id could be different from
15344 * the old state, so we need to track the mapping from old to new ids.
15345 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15346 * regs with old id 5 must also have new id 9 for the new state to be safe. But
15347 * regs with a different old id could still have new id 9, we don't care about
15349 * So we look through our idmap to see if this old id has been seen before. If
15350 * so, we require the new id to match; otherwise, we add the id pair to the map.
15352 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15354 struct bpf_id_pair *map = idmap->map;
15357 /* either both IDs should be set or both should be zero */
15358 if (!!old_id != !!cur_id)
15361 if (old_id == 0) /* cur_id == 0 as well */
15364 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15366 /* Reached an empty slot; haven't seen this id before */
15367 map[i].old = old_id;
15368 map[i].cur = cur_id;
15371 if (map[i].old == old_id)
15372 return map[i].cur == cur_id;
15373 if (map[i].cur == cur_id)
15376 /* We ran out of idmap slots, which should be impossible */
15381 /* Similar to check_ids(), but allocate a unique temporary ID
15382 * for 'old_id' or 'cur_id' of zero.
15383 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15385 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15387 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15388 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15390 return check_ids(old_id, cur_id, idmap);
15393 static void clean_func_state(struct bpf_verifier_env *env,
15394 struct bpf_func_state *st)
15396 enum bpf_reg_liveness live;
15399 for (i = 0; i < BPF_REG_FP; i++) {
15400 live = st->regs[i].live;
15401 /* liveness must not touch this register anymore */
15402 st->regs[i].live |= REG_LIVE_DONE;
15403 if (!(live & REG_LIVE_READ))
15404 /* since the register is unused, clear its state
15405 * to make further comparison simpler
15407 __mark_reg_not_init(env, &st->regs[i]);
15410 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15411 live = st->stack[i].spilled_ptr.live;
15412 /* liveness must not touch this stack slot anymore */
15413 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15414 if (!(live & REG_LIVE_READ)) {
15415 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15416 for (j = 0; j < BPF_REG_SIZE; j++)
15417 st->stack[i].slot_type[j] = STACK_INVALID;
15422 static void clean_verifier_state(struct bpf_verifier_env *env,
15423 struct bpf_verifier_state *st)
15427 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15428 /* all regs in this state in all frames were already marked */
15431 for (i = 0; i <= st->curframe; i++)
15432 clean_func_state(env, st->frame[i]);
15435 /* the parentage chains form a tree.
15436 * the verifier states are added to state lists at given insn and
15437 * pushed into state stack for future exploration.
15438 * when the verifier reaches bpf_exit insn some of the verifer states
15439 * stored in the state lists have their final liveness state already,
15440 * but a lot of states will get revised from liveness point of view when
15441 * the verifier explores other branches.
15444 * 2: if r1 == 100 goto pc+1
15447 * when the verifier reaches exit insn the register r0 in the state list of
15448 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15449 * of insn 2 and goes exploring further. At the insn 4 it will walk the
15450 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15452 * Since the verifier pushes the branch states as it sees them while exploring
15453 * the program the condition of walking the branch instruction for the second
15454 * time means that all states below this branch were already explored and
15455 * their final liveness marks are already propagated.
15456 * Hence when the verifier completes the search of state list in is_state_visited()
15457 * we can call this clean_live_states() function to mark all liveness states
15458 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15459 * will not be used.
15460 * This function also clears the registers and stack for states that !READ
15461 * to simplify state merging.
15463 * Important note here that walking the same branch instruction in the callee
15464 * doesn't meant that the states are DONE. The verifier has to compare
15467 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15468 struct bpf_verifier_state *cur)
15470 struct bpf_verifier_state_list *sl;
15473 sl = *explored_state(env, insn);
15475 if (sl->state.branches)
15477 if (sl->state.insn_idx != insn ||
15478 sl->state.curframe != cur->curframe)
15480 for (i = 0; i <= cur->curframe; i++)
15481 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15483 clean_verifier_state(env, &sl->state);
15489 static bool regs_exact(const struct bpf_reg_state *rold,
15490 const struct bpf_reg_state *rcur,
15491 struct bpf_idmap *idmap)
15493 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15494 check_ids(rold->id, rcur->id, idmap) &&
15495 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15498 /* Returns true if (rold safe implies rcur safe) */
15499 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15500 struct bpf_reg_state *rcur, struct bpf_idmap *idmap)
15502 if (!(rold->live & REG_LIVE_READ))
15503 /* explored state didn't use this */
15505 if (rold->type == NOT_INIT)
15506 /* explored state can't have used this */
15508 if (rcur->type == NOT_INIT)
15511 /* Enforce that register types have to match exactly, including their
15512 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15515 * One can make a point that using a pointer register as unbounded
15516 * SCALAR would be technically acceptable, but this could lead to
15517 * pointer leaks because scalars are allowed to leak while pointers
15518 * are not. We could make this safe in special cases if root is
15519 * calling us, but it's probably not worth the hassle.
15521 * Also, register types that are *not* MAYBE_NULL could technically be
15522 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15523 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15524 * to the same map).
15525 * However, if the old MAYBE_NULL register then got NULL checked,
15526 * doing so could have affected others with the same id, and we can't
15527 * check for that because we lost the id when we converted to
15528 * a non-MAYBE_NULL variant.
15529 * So, as a general rule we don't allow mixing MAYBE_NULL and
15530 * non-MAYBE_NULL registers as well.
15532 if (rold->type != rcur->type)
15535 switch (base_type(rold->type)) {
15537 if (env->explore_alu_limits) {
15538 /* explore_alu_limits disables tnum_in() and range_within()
15539 * logic and requires everything to be strict
15541 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15542 check_scalar_ids(rold->id, rcur->id, idmap);
15544 if (!rold->precise)
15546 /* Why check_ids() for scalar registers?
15548 * Consider the following BPF code:
15549 * 1: r6 = ... unbound scalar, ID=a ...
15550 * 2: r7 = ... unbound scalar, ID=b ...
15551 * 3: if (r6 > r7) goto +1
15553 * 5: if (r6 > X) goto ...
15554 * 6: ... memory operation using r7 ...
15556 * First verification path is [1-6]:
15557 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15558 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15559 * r7 <= X, because r6 and r7 share same id.
15560 * Next verification path is [1-4, 6].
15562 * Instruction (6) would be reached in two states:
15563 * I. r6{.id=b}, r7{.id=b} via path 1-6;
15564 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15566 * Use check_ids() to distinguish these states.
15568 * Also verify that new value satisfies old value range knowledge.
15570 return range_within(rold, rcur) &&
15571 tnum_in(rold->var_off, rcur->var_off) &&
15572 check_scalar_ids(rold->id, rcur->id, idmap);
15573 case PTR_TO_MAP_KEY:
15574 case PTR_TO_MAP_VALUE:
15577 case PTR_TO_TP_BUFFER:
15578 /* If the new min/max/var_off satisfy the old ones and
15579 * everything else matches, we are OK.
15581 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15582 range_within(rold, rcur) &&
15583 tnum_in(rold->var_off, rcur->var_off) &&
15584 check_ids(rold->id, rcur->id, idmap) &&
15585 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15586 case PTR_TO_PACKET_META:
15587 case PTR_TO_PACKET:
15588 /* We must have at least as much range as the old ptr
15589 * did, so that any accesses which were safe before are
15590 * still safe. This is true even if old range < old off,
15591 * since someone could have accessed through (ptr - k), or
15592 * even done ptr -= k in a register, to get a safe access.
15594 if (rold->range > rcur->range)
15596 /* If the offsets don't match, we can't trust our alignment;
15597 * nor can we be sure that we won't fall out of range.
15599 if (rold->off != rcur->off)
15601 /* id relations must be preserved */
15602 if (!check_ids(rold->id, rcur->id, idmap))
15604 /* new val must satisfy old val knowledge */
15605 return range_within(rold, rcur) &&
15606 tnum_in(rold->var_off, rcur->var_off);
15608 /* two stack pointers are equal only if they're pointing to
15609 * the same stack frame, since fp-8 in foo != fp-8 in bar
15611 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15613 return regs_exact(rold, rcur, idmap);
15617 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15618 struct bpf_func_state *cur, struct bpf_idmap *idmap)
15622 /* walk slots of the explored stack and ignore any additional
15623 * slots in the current stack, since explored(safe) state
15626 for (i = 0; i < old->allocated_stack; i++) {
15627 struct bpf_reg_state *old_reg, *cur_reg;
15629 spi = i / BPF_REG_SIZE;
15631 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15632 i += BPF_REG_SIZE - 1;
15633 /* explored state didn't use this */
15637 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15640 if (env->allow_uninit_stack &&
15641 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15644 /* explored stack has more populated slots than current stack
15645 * and these slots were used
15647 if (i >= cur->allocated_stack)
15650 /* if old state was safe with misc data in the stack
15651 * it will be safe with zero-initialized stack.
15652 * The opposite is not true
15654 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15655 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15657 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15658 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15659 /* Ex: old explored (safe) state has STACK_SPILL in
15660 * this stack slot, but current has STACK_MISC ->
15661 * this verifier states are not equivalent,
15662 * return false to continue verification of this path
15665 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15667 /* Both old and cur are having same slot_type */
15668 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15670 /* when explored and current stack slot are both storing
15671 * spilled registers, check that stored pointers types
15672 * are the same as well.
15673 * Ex: explored safe path could have stored
15674 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15675 * but current path has stored:
15676 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15677 * such verifier states are not equivalent.
15678 * return false to continue verification of this path
15680 if (!regsafe(env, &old->stack[spi].spilled_ptr,
15681 &cur->stack[spi].spilled_ptr, idmap))
15685 old_reg = &old->stack[spi].spilled_ptr;
15686 cur_reg = &cur->stack[spi].spilled_ptr;
15687 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15688 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15689 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15693 old_reg = &old->stack[spi].spilled_ptr;
15694 cur_reg = &cur->stack[spi].spilled_ptr;
15695 /* iter.depth is not compared between states as it
15696 * doesn't matter for correctness and would otherwise
15697 * prevent convergence; we maintain it only to prevent
15698 * infinite loop check triggering, see
15699 * iter_active_depths_differ()
15701 if (old_reg->iter.btf != cur_reg->iter.btf ||
15702 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15703 old_reg->iter.state != cur_reg->iter.state ||
15704 /* ignore {old_reg,cur_reg}->iter.depth, see above */
15705 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15710 case STACK_INVALID:
15712 /* Ensure that new unhandled slot types return false by default */
15720 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15721 struct bpf_idmap *idmap)
15725 if (old->acquired_refs != cur->acquired_refs)
15728 for (i = 0; i < old->acquired_refs; i++) {
15729 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15736 /* compare two verifier states
15738 * all states stored in state_list are known to be valid, since
15739 * verifier reached 'bpf_exit' instruction through them
15741 * this function is called when verifier exploring different branches of
15742 * execution popped from the state stack. If it sees an old state that has
15743 * more strict register state and more strict stack state then this execution
15744 * branch doesn't need to be explored further, since verifier already
15745 * concluded that more strict state leads to valid finish.
15747 * Therefore two states are equivalent if register state is more conservative
15748 * and explored stack state is more conservative than the current one.
15751 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15752 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15754 * In other words if current stack state (one being explored) has more
15755 * valid slots than old one that already passed validation, it means
15756 * the verifier can stop exploring and conclude that current state is valid too
15758 * Similarly with registers. If explored state has register type as invalid
15759 * whereas register type in current state is meaningful, it means that
15760 * the current state will reach 'bpf_exit' instruction safely
15762 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15763 struct bpf_func_state *cur)
15767 for (i = 0; i < MAX_BPF_REG; i++)
15768 if (!regsafe(env, &old->regs[i], &cur->regs[i],
15769 &env->idmap_scratch))
15772 if (!stacksafe(env, old, cur, &env->idmap_scratch))
15775 if (!refsafe(old, cur, &env->idmap_scratch))
15781 static bool states_equal(struct bpf_verifier_env *env,
15782 struct bpf_verifier_state *old,
15783 struct bpf_verifier_state *cur)
15787 if (old->curframe != cur->curframe)
15790 env->idmap_scratch.tmp_id_gen = env->id_gen;
15791 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
15793 /* Verification state from speculative execution simulation
15794 * must never prune a non-speculative execution one.
15796 if (old->speculative && !cur->speculative)
15799 if (old->active_lock.ptr != cur->active_lock.ptr)
15802 /* Old and cur active_lock's have to be either both present
15805 if (!!old->active_lock.id != !!cur->active_lock.id)
15808 if (old->active_lock.id &&
15809 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
15812 if (old->active_rcu_lock != cur->active_rcu_lock)
15815 /* for states to be equal callsites have to be the same
15816 * and all frame states need to be equivalent
15818 for (i = 0; i <= old->curframe; i++) {
15819 if (old->frame[i]->callsite != cur->frame[i]->callsite)
15821 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15827 /* Return 0 if no propagation happened. Return negative error code if error
15828 * happened. Otherwise, return the propagated bit.
15830 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15831 struct bpf_reg_state *reg,
15832 struct bpf_reg_state *parent_reg)
15834 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15835 u8 flag = reg->live & REG_LIVE_READ;
15838 /* When comes here, read flags of PARENT_REG or REG could be any of
15839 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15840 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15842 if (parent_flag == REG_LIVE_READ64 ||
15843 /* Or if there is no read flag from REG. */
15845 /* Or if the read flag from REG is the same as PARENT_REG. */
15846 parent_flag == flag)
15849 err = mark_reg_read(env, reg, parent_reg, flag);
15856 /* A write screens off any subsequent reads; but write marks come from the
15857 * straight-line code between a state and its parent. When we arrive at an
15858 * equivalent state (jump target or such) we didn't arrive by the straight-line
15859 * code, so read marks in the state must propagate to the parent regardless
15860 * of the state's write marks. That's what 'parent == state->parent' comparison
15861 * in mark_reg_read() is for.
15863 static int propagate_liveness(struct bpf_verifier_env *env,
15864 const struct bpf_verifier_state *vstate,
15865 struct bpf_verifier_state *vparent)
15867 struct bpf_reg_state *state_reg, *parent_reg;
15868 struct bpf_func_state *state, *parent;
15869 int i, frame, err = 0;
15871 if (vparent->curframe != vstate->curframe) {
15872 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15873 vparent->curframe, vstate->curframe);
15876 /* Propagate read liveness of registers... */
15877 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15878 for (frame = 0; frame <= vstate->curframe; frame++) {
15879 parent = vparent->frame[frame];
15880 state = vstate->frame[frame];
15881 parent_reg = parent->regs;
15882 state_reg = state->regs;
15883 /* We don't need to worry about FP liveness, it's read-only */
15884 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15885 err = propagate_liveness_reg(env, &state_reg[i],
15889 if (err == REG_LIVE_READ64)
15890 mark_insn_zext(env, &parent_reg[i]);
15893 /* Propagate stack slots. */
15894 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15895 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15896 parent_reg = &parent->stack[i].spilled_ptr;
15897 state_reg = &state->stack[i].spilled_ptr;
15898 err = propagate_liveness_reg(env, state_reg,
15907 /* find precise scalars in the previous equivalent state and
15908 * propagate them into the current state
15910 static int propagate_precision(struct bpf_verifier_env *env,
15911 const struct bpf_verifier_state *old)
15913 struct bpf_reg_state *state_reg;
15914 struct bpf_func_state *state;
15915 int i, err = 0, fr;
15918 for (fr = old->curframe; fr >= 0; fr--) {
15919 state = old->frame[fr];
15920 state_reg = state->regs;
15922 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15923 if (state_reg->type != SCALAR_VALUE ||
15924 !state_reg->precise ||
15925 !(state_reg->live & REG_LIVE_READ))
15927 if (env->log.level & BPF_LOG_LEVEL2) {
15929 verbose(env, "frame %d: propagating r%d", fr, i);
15931 verbose(env, ",r%d", i);
15933 bt_set_frame_reg(&env->bt, fr, i);
15937 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15938 if (!is_spilled_reg(&state->stack[i]))
15940 state_reg = &state->stack[i].spilled_ptr;
15941 if (state_reg->type != SCALAR_VALUE ||
15942 !state_reg->precise ||
15943 !(state_reg->live & REG_LIVE_READ))
15945 if (env->log.level & BPF_LOG_LEVEL2) {
15947 verbose(env, "frame %d: propagating fp%d",
15948 fr, (-i - 1) * BPF_REG_SIZE);
15950 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15952 bt_set_frame_slot(&env->bt, fr, i);
15956 verbose(env, "\n");
15959 err = mark_chain_precision_batch(env);
15966 static bool states_maybe_looping(struct bpf_verifier_state *old,
15967 struct bpf_verifier_state *cur)
15969 struct bpf_func_state *fold, *fcur;
15970 int i, fr = cur->curframe;
15972 if (old->curframe != fr)
15975 fold = old->frame[fr];
15976 fcur = cur->frame[fr];
15977 for (i = 0; i < MAX_BPF_REG; i++)
15978 if (memcmp(&fold->regs[i], &fcur->regs[i],
15979 offsetof(struct bpf_reg_state, parent)))
15984 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15986 return env->insn_aux_data[insn_idx].is_iter_next;
15989 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
15990 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15991 * states to match, which otherwise would look like an infinite loop. So while
15992 * iter_next() calls are taken care of, we still need to be careful and
15993 * prevent erroneous and too eager declaration of "ininite loop", when
15994 * iterators are involved.
15996 * Here's a situation in pseudo-BPF assembly form:
15998 * 0: again: ; set up iter_next() call args
15999 * 1: r1 = &it ; <CHECKPOINT HERE>
16000 * 2: call bpf_iter_num_next ; this is iter_next() call
16001 * 3: if r0 == 0 goto done
16002 * 4: ... something useful here ...
16003 * 5: goto again ; another iteration
16006 * 8: call bpf_iter_num_destroy ; clean up iter state
16009 * This is a typical loop. Let's assume that we have a prune point at 1:,
16010 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16011 * again`, assuming other heuristics don't get in a way).
16013 * When we first time come to 1:, let's say we have some state X. We proceed
16014 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16015 * Now we come back to validate that forked ACTIVE state. We proceed through
16016 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16017 * are converging. But the problem is that we don't know that yet, as this
16018 * convergence has to happen at iter_next() call site only. So if nothing is
16019 * done, at 1: verifier will use bounded loop logic and declare infinite
16020 * looping (and would be *technically* correct, if not for iterator's
16021 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16022 * don't want that. So what we do in process_iter_next_call() when we go on
16023 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16024 * a different iteration. So when we suspect an infinite loop, we additionally
16025 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16026 * pretend we are not looping and wait for next iter_next() call.
16028 * This only applies to ACTIVE state. In DRAINED state we don't expect to
16029 * loop, because that would actually mean infinite loop, as DRAINED state is
16030 * "sticky", and so we'll keep returning into the same instruction with the
16031 * same state (at least in one of possible code paths).
16033 * This approach allows to keep infinite loop heuristic even in the face of
16034 * active iterator. E.g., C snippet below is and will be detected as
16035 * inifintely looping:
16037 * struct bpf_iter_num it;
16040 * bpf_iter_num_new(&it, 0, 10);
16041 * while ((p = bpf_iter_num_next(&t))) {
16043 * while (x--) {} // <<-- infinite loop here
16047 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16049 struct bpf_reg_state *slot, *cur_slot;
16050 struct bpf_func_state *state;
16053 for (fr = old->curframe; fr >= 0; fr--) {
16054 state = old->frame[fr];
16055 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16056 if (state->stack[i].slot_type[0] != STACK_ITER)
16059 slot = &state->stack[i].spilled_ptr;
16060 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16063 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16064 if (cur_slot->iter.depth != slot->iter.depth)
16071 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16073 struct bpf_verifier_state_list *new_sl;
16074 struct bpf_verifier_state_list *sl, **pprev;
16075 struct bpf_verifier_state *cur = env->cur_state, *new;
16076 int i, j, err, states_cnt = 0;
16077 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16078 bool add_new_state = force_new_state;
16080 /* bpf progs typically have pruning point every 4 instructions
16081 * http://vger.kernel.org/bpfconf2019.html#session-1
16082 * Do not add new state for future pruning if the verifier hasn't seen
16083 * at least 2 jumps and at least 8 instructions.
16084 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16085 * In tests that amounts to up to 50% reduction into total verifier
16086 * memory consumption and 20% verifier time speedup.
16088 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16089 env->insn_processed - env->prev_insn_processed >= 8)
16090 add_new_state = true;
16092 pprev = explored_state(env, insn_idx);
16095 clean_live_states(env, insn_idx, cur);
16099 if (sl->state.insn_idx != insn_idx)
16102 if (sl->state.branches) {
16103 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16105 if (frame->in_async_callback_fn &&
16106 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16107 /* Different async_entry_cnt means that the verifier is
16108 * processing another entry into async callback.
16109 * Seeing the same state is not an indication of infinite
16110 * loop or infinite recursion.
16111 * But finding the same state doesn't mean that it's safe
16112 * to stop processing the current state. The previous state
16113 * hasn't yet reached bpf_exit, since state.branches > 0.
16114 * Checking in_async_callback_fn alone is not enough either.
16115 * Since the verifier still needs to catch infinite loops
16116 * inside async callbacks.
16118 goto skip_inf_loop_check;
16120 /* BPF open-coded iterators loop detection is special.
16121 * states_maybe_looping() logic is too simplistic in detecting
16122 * states that *might* be equivalent, because it doesn't know
16123 * about ID remapping, so don't even perform it.
16124 * See process_iter_next_call() and iter_active_depths_differ()
16125 * for overview of the logic. When current and one of parent
16126 * states are detected as equivalent, it's a good thing: we prove
16127 * convergence and can stop simulating further iterations.
16128 * It's safe to assume that iterator loop will finish, taking into
16129 * account iter_next() contract of eventually returning
16130 * sticky NULL result.
16132 if (is_iter_next_insn(env, insn_idx)) {
16133 if (states_equal(env, &sl->state, cur)) {
16134 struct bpf_func_state *cur_frame;
16135 struct bpf_reg_state *iter_state, *iter_reg;
16138 cur_frame = cur->frame[cur->curframe];
16139 /* btf_check_iter_kfuncs() enforces that
16140 * iter state pointer is always the first arg
16142 iter_reg = &cur_frame->regs[BPF_REG_1];
16143 /* current state is valid due to states_equal(),
16144 * so we can assume valid iter and reg state,
16145 * no need for extra (re-)validations
16147 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16148 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16149 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
16152 goto skip_inf_loop_check;
16154 /* attempt to detect infinite loop to avoid unnecessary doomed work */
16155 if (states_maybe_looping(&sl->state, cur) &&
16156 states_equal(env, &sl->state, cur) &&
16157 !iter_active_depths_differ(&sl->state, cur)) {
16158 verbose_linfo(env, insn_idx, "; ");
16159 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16162 /* if the verifier is processing a loop, avoid adding new state
16163 * too often, since different loop iterations have distinct
16164 * states and may not help future pruning.
16165 * This threshold shouldn't be too low to make sure that
16166 * a loop with large bound will be rejected quickly.
16167 * The most abusive loop will be:
16169 * if r1 < 1000000 goto pc-2
16170 * 1M insn_procssed limit / 100 == 10k peak states.
16171 * This threshold shouldn't be too high either, since states
16172 * at the end of the loop are likely to be useful in pruning.
16174 skip_inf_loop_check:
16175 if (!force_new_state &&
16176 env->jmps_processed - env->prev_jmps_processed < 20 &&
16177 env->insn_processed - env->prev_insn_processed < 100)
16178 add_new_state = false;
16181 if (states_equal(env, &sl->state, cur)) {
16184 /* reached equivalent register/stack state,
16185 * prune the search.
16186 * Registers read by the continuation are read by us.
16187 * If we have any write marks in env->cur_state, they
16188 * will prevent corresponding reads in the continuation
16189 * from reaching our parent (an explored_state). Our
16190 * own state will get the read marks recorded, but
16191 * they'll be immediately forgotten as we're pruning
16192 * this state and will pop a new one.
16194 err = propagate_liveness(env, &sl->state, cur);
16196 /* if previous state reached the exit with precision and
16197 * current state is equivalent to it (except precsion marks)
16198 * the precision needs to be propagated back in
16199 * the current state.
16201 err = err ? : push_jmp_history(env, cur);
16202 err = err ? : propagate_precision(env, &sl->state);
16208 /* when new state is not going to be added do not increase miss count.
16209 * Otherwise several loop iterations will remove the state
16210 * recorded earlier. The goal of these heuristics is to have
16211 * states from some iterations of the loop (some in the beginning
16212 * and some at the end) to help pruning.
16216 /* heuristic to determine whether this state is beneficial
16217 * to keep checking from state equivalence point of view.
16218 * Higher numbers increase max_states_per_insn and verification time,
16219 * but do not meaningfully decrease insn_processed.
16221 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
16222 /* the state is unlikely to be useful. Remove it to
16223 * speed up verification
16226 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
16227 u32 br = sl->state.branches;
16230 "BUG live_done but branches_to_explore %d\n",
16232 free_verifier_state(&sl->state, false);
16234 env->peak_states--;
16236 /* cannot free this state, since parentage chain may
16237 * walk it later. Add it for free_list instead to
16238 * be freed at the end of verification
16240 sl->next = env->free_list;
16241 env->free_list = sl;
16251 if (env->max_states_per_insn < states_cnt)
16252 env->max_states_per_insn = states_cnt;
16254 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16257 if (!add_new_state)
16260 /* There were no equivalent states, remember the current one.
16261 * Technically the current state is not proven to be safe yet,
16262 * but it will either reach outer most bpf_exit (which means it's safe)
16263 * or it will be rejected. When there are no loops the verifier won't be
16264 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16265 * again on the way to bpf_exit.
16266 * When looping the sl->state.branches will be > 0 and this state
16267 * will not be considered for equivalence until branches == 0.
16269 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16272 env->total_states++;
16273 env->peak_states++;
16274 env->prev_jmps_processed = env->jmps_processed;
16275 env->prev_insn_processed = env->insn_processed;
16277 /* forget precise markings we inherited, see __mark_chain_precision */
16278 if (env->bpf_capable)
16279 mark_all_scalars_imprecise(env, cur);
16281 /* add new state to the head of linked list */
16282 new = &new_sl->state;
16283 err = copy_verifier_state(new, cur);
16285 free_verifier_state(new, false);
16289 new->insn_idx = insn_idx;
16290 WARN_ONCE(new->branches != 1,
16291 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16294 cur->first_insn_idx = insn_idx;
16295 clear_jmp_history(cur);
16296 new_sl->next = *explored_state(env, insn_idx);
16297 *explored_state(env, insn_idx) = new_sl;
16298 /* connect new state to parentage chain. Current frame needs all
16299 * registers connected. Only r6 - r9 of the callers are alive (pushed
16300 * to the stack implicitly by JITs) so in callers' frames connect just
16301 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16302 * the state of the call instruction (with WRITTEN set), and r0 comes
16303 * from callee with its full parentage chain, anyway.
16305 /* clear write marks in current state: the writes we did are not writes
16306 * our child did, so they don't screen off its reads from us.
16307 * (There are no read marks in current state, because reads always mark
16308 * their parent and current state never has children yet. Only
16309 * explored_states can get read marks.)
16311 for (j = 0; j <= cur->curframe; j++) {
16312 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16313 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16314 for (i = 0; i < BPF_REG_FP; i++)
16315 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16318 /* all stack frames are accessible from callee, clear them all */
16319 for (j = 0; j <= cur->curframe; j++) {
16320 struct bpf_func_state *frame = cur->frame[j];
16321 struct bpf_func_state *newframe = new->frame[j];
16323 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16324 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16325 frame->stack[i].spilled_ptr.parent =
16326 &newframe->stack[i].spilled_ptr;
16332 /* Return true if it's OK to have the same insn return a different type. */
16333 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16335 switch (base_type(type)) {
16337 case PTR_TO_SOCKET:
16338 case PTR_TO_SOCK_COMMON:
16339 case PTR_TO_TCP_SOCK:
16340 case PTR_TO_XDP_SOCK:
16341 case PTR_TO_BTF_ID:
16348 /* If an instruction was previously used with particular pointer types, then we
16349 * need to be careful to avoid cases such as the below, where it may be ok
16350 * for one branch accessing the pointer, but not ok for the other branch:
16355 * R1 = some_other_valid_ptr;
16358 * R2 = *(u32 *)(R1 + 0);
16360 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16362 return src != prev && (!reg_type_mismatch_ok(src) ||
16363 !reg_type_mismatch_ok(prev));
16366 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16367 bool allow_trust_missmatch)
16369 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16371 if (*prev_type == NOT_INIT) {
16372 /* Saw a valid insn
16373 * dst_reg = *(u32 *)(src_reg + off)
16374 * save type to validate intersecting paths
16377 } else if (reg_type_mismatch(type, *prev_type)) {
16378 /* Abuser program is trying to use the same insn
16379 * dst_reg = *(u32*) (src_reg + off)
16380 * with different pointer types:
16381 * src_reg == ctx in one branch and
16382 * src_reg == stack|map in some other branch.
16385 if (allow_trust_missmatch &&
16386 base_type(type) == PTR_TO_BTF_ID &&
16387 base_type(*prev_type) == PTR_TO_BTF_ID) {
16389 * Have to support a use case when one path through
16390 * the program yields TRUSTED pointer while another
16391 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16392 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16394 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16396 verbose(env, "same insn cannot be used with different pointers\n");
16404 static int do_check(struct bpf_verifier_env *env)
16406 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16407 struct bpf_verifier_state *state = env->cur_state;
16408 struct bpf_insn *insns = env->prog->insnsi;
16409 struct bpf_reg_state *regs;
16410 int insn_cnt = env->prog->len;
16411 bool do_print_state = false;
16412 int prev_insn_idx = -1;
16415 struct bpf_insn *insn;
16419 env->prev_insn_idx = prev_insn_idx;
16420 if (env->insn_idx >= insn_cnt) {
16421 verbose(env, "invalid insn idx %d insn_cnt %d\n",
16422 env->insn_idx, insn_cnt);
16426 insn = &insns[env->insn_idx];
16427 class = BPF_CLASS(insn->code);
16429 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16431 "BPF program is too large. Processed %d insn\n",
16432 env->insn_processed);
16436 state->last_insn_idx = env->prev_insn_idx;
16438 if (is_prune_point(env, env->insn_idx)) {
16439 err = is_state_visited(env, env->insn_idx);
16443 /* found equivalent state, can prune the search */
16444 if (env->log.level & BPF_LOG_LEVEL) {
16445 if (do_print_state)
16446 verbose(env, "\nfrom %d to %d%s: safe\n",
16447 env->prev_insn_idx, env->insn_idx,
16448 env->cur_state->speculative ?
16449 " (speculative execution)" : "");
16451 verbose(env, "%d: safe\n", env->insn_idx);
16453 goto process_bpf_exit;
16457 if (is_jmp_point(env, env->insn_idx)) {
16458 err = push_jmp_history(env, state);
16463 if (signal_pending(current))
16466 if (need_resched())
16469 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16470 verbose(env, "\nfrom %d to %d%s:",
16471 env->prev_insn_idx, env->insn_idx,
16472 env->cur_state->speculative ?
16473 " (speculative execution)" : "");
16474 print_verifier_state(env, state->frame[state->curframe], true);
16475 do_print_state = false;
16478 if (env->log.level & BPF_LOG_LEVEL) {
16479 const struct bpf_insn_cbs cbs = {
16480 .cb_call = disasm_kfunc_name,
16481 .cb_print = verbose,
16482 .private_data = env,
16485 if (verifier_state_scratched(env))
16486 print_insn_state(env, state->frame[state->curframe]);
16488 verbose_linfo(env, env->insn_idx, "; ");
16489 env->prev_log_pos = env->log.end_pos;
16490 verbose(env, "%d: ", env->insn_idx);
16491 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16492 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16493 env->prev_log_pos = env->log.end_pos;
16496 if (bpf_prog_is_offloaded(env->prog->aux)) {
16497 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16498 env->prev_insn_idx);
16503 regs = cur_regs(env);
16504 sanitize_mark_insn_seen(env);
16505 prev_insn_idx = env->insn_idx;
16507 if (class == BPF_ALU || class == BPF_ALU64) {
16508 err = check_alu_op(env, insn);
16512 } else if (class == BPF_LDX) {
16513 enum bpf_reg_type src_reg_type;
16515 /* check for reserved fields is already done */
16517 /* check src operand */
16518 err = check_reg_arg(env, insn->src_reg, SRC_OP);
16522 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16526 src_reg_type = regs[insn->src_reg].type;
16528 /* check that memory (src_reg + off) is readable,
16529 * the state of dst_reg will be updated by this func
16531 err = check_mem_access(env, env->insn_idx, insn->src_reg,
16532 insn->off, BPF_SIZE(insn->code),
16533 BPF_READ, insn->dst_reg, false,
16534 BPF_MODE(insn->code) == BPF_MEMSX);
16538 err = save_aux_ptr_type(env, src_reg_type, true);
16541 } else if (class == BPF_STX) {
16542 enum bpf_reg_type dst_reg_type;
16544 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16545 err = check_atomic(env, env->insn_idx, insn);
16552 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16553 verbose(env, "BPF_STX uses reserved fields\n");
16557 /* check src1 operand */
16558 err = check_reg_arg(env, insn->src_reg, SRC_OP);
16561 /* check src2 operand */
16562 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16566 dst_reg_type = regs[insn->dst_reg].type;
16568 /* check that memory (dst_reg + off) is writeable */
16569 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16570 insn->off, BPF_SIZE(insn->code),
16571 BPF_WRITE, insn->src_reg, false, false);
16575 err = save_aux_ptr_type(env, dst_reg_type, false);
16578 } else if (class == BPF_ST) {
16579 enum bpf_reg_type dst_reg_type;
16581 if (BPF_MODE(insn->code) != BPF_MEM ||
16582 insn->src_reg != BPF_REG_0) {
16583 verbose(env, "BPF_ST uses reserved fields\n");
16586 /* check src operand */
16587 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16591 dst_reg_type = regs[insn->dst_reg].type;
16593 /* check that memory (dst_reg + off) is writeable */
16594 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16595 insn->off, BPF_SIZE(insn->code),
16596 BPF_WRITE, -1, false, false);
16600 err = save_aux_ptr_type(env, dst_reg_type, false);
16603 } else if (class == BPF_JMP || class == BPF_JMP32) {
16604 u8 opcode = BPF_OP(insn->code);
16606 env->jmps_processed++;
16607 if (opcode == BPF_CALL) {
16608 if (BPF_SRC(insn->code) != BPF_K ||
16609 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16610 && insn->off != 0) ||
16611 (insn->src_reg != BPF_REG_0 &&
16612 insn->src_reg != BPF_PSEUDO_CALL &&
16613 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16614 insn->dst_reg != BPF_REG_0 ||
16615 class == BPF_JMP32) {
16616 verbose(env, "BPF_CALL uses reserved fields\n");
16620 if (env->cur_state->active_lock.ptr) {
16621 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16622 (insn->src_reg == BPF_PSEUDO_CALL) ||
16623 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16624 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16625 verbose(env, "function calls are not allowed while holding a lock\n");
16629 if (insn->src_reg == BPF_PSEUDO_CALL)
16630 err = check_func_call(env, insn, &env->insn_idx);
16631 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16632 err = check_kfunc_call(env, insn, &env->insn_idx);
16634 err = check_helper_call(env, insn, &env->insn_idx);
16638 mark_reg_scratched(env, BPF_REG_0);
16639 } else if (opcode == BPF_JA) {
16640 if (BPF_SRC(insn->code) != BPF_K ||
16642 insn->src_reg != BPF_REG_0 ||
16643 insn->dst_reg != BPF_REG_0 ||
16644 class == BPF_JMP32) {
16645 verbose(env, "BPF_JA uses reserved fields\n");
16649 env->insn_idx += insn->off + 1;
16652 } else if (opcode == BPF_EXIT) {
16653 if (BPF_SRC(insn->code) != BPF_K ||
16655 insn->src_reg != BPF_REG_0 ||
16656 insn->dst_reg != BPF_REG_0 ||
16657 class == BPF_JMP32) {
16658 verbose(env, "BPF_EXIT uses reserved fields\n");
16662 if (env->cur_state->active_lock.ptr &&
16663 !in_rbtree_lock_required_cb(env)) {
16664 verbose(env, "bpf_spin_unlock is missing\n");
16668 if (env->cur_state->active_rcu_lock) {
16669 verbose(env, "bpf_rcu_read_unlock is missing\n");
16673 /* We must do check_reference_leak here before
16674 * prepare_func_exit to handle the case when
16675 * state->curframe > 0, it may be a callback
16676 * function, for which reference_state must
16677 * match caller reference state when it exits.
16679 err = check_reference_leak(env);
16683 if (state->curframe) {
16684 /* exit from nested function */
16685 err = prepare_func_exit(env, &env->insn_idx);
16688 do_print_state = true;
16692 err = check_return_code(env);
16696 mark_verifier_state_scratched(env);
16697 update_branch_counts(env, env->cur_state);
16698 err = pop_stack(env, &prev_insn_idx,
16699 &env->insn_idx, pop_log);
16701 if (err != -ENOENT)
16705 do_print_state = true;
16709 err = check_cond_jmp_op(env, insn, &env->insn_idx);
16713 } else if (class == BPF_LD) {
16714 u8 mode = BPF_MODE(insn->code);
16716 if (mode == BPF_ABS || mode == BPF_IND) {
16717 err = check_ld_abs(env, insn);
16721 } else if (mode == BPF_IMM) {
16722 err = check_ld_imm(env, insn);
16727 sanitize_mark_insn_seen(env);
16729 verbose(env, "invalid BPF_LD mode\n");
16733 verbose(env, "unknown insn class %d\n", class);
16743 static int find_btf_percpu_datasec(struct btf *btf)
16745 const struct btf_type *t;
16750 * Both vmlinux and module each have their own ".data..percpu"
16751 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16752 * types to look at only module's own BTF types.
16754 n = btf_nr_types(btf);
16755 if (btf_is_module(btf))
16756 i = btf_nr_types(btf_vmlinux);
16760 for(; i < n; i++) {
16761 t = btf_type_by_id(btf, i);
16762 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16765 tname = btf_name_by_offset(btf, t->name_off);
16766 if (!strcmp(tname, ".data..percpu"))
16773 /* replace pseudo btf_id with kernel symbol address */
16774 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16775 struct bpf_insn *insn,
16776 struct bpf_insn_aux_data *aux)
16778 const struct btf_var_secinfo *vsi;
16779 const struct btf_type *datasec;
16780 struct btf_mod_pair *btf_mod;
16781 const struct btf_type *t;
16782 const char *sym_name;
16783 bool percpu = false;
16784 u32 type, id = insn->imm;
16788 int i, btf_fd, err;
16790 btf_fd = insn[1].imm;
16792 btf = btf_get_by_fd(btf_fd);
16794 verbose(env, "invalid module BTF object FD specified.\n");
16798 if (!btf_vmlinux) {
16799 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16806 t = btf_type_by_id(btf, id);
16808 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16813 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16814 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16819 sym_name = btf_name_by_offset(btf, t->name_off);
16820 addr = kallsyms_lookup_name(sym_name);
16822 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16827 insn[0].imm = (u32)addr;
16828 insn[1].imm = addr >> 32;
16830 if (btf_type_is_func(t)) {
16831 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16832 aux->btf_var.mem_size = 0;
16836 datasec_id = find_btf_percpu_datasec(btf);
16837 if (datasec_id > 0) {
16838 datasec = btf_type_by_id(btf, datasec_id);
16839 for_each_vsi(i, datasec, vsi) {
16840 if (vsi->type == id) {
16848 t = btf_type_skip_modifiers(btf, type, NULL);
16850 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16851 aux->btf_var.btf = btf;
16852 aux->btf_var.btf_id = type;
16853 } else if (!btf_type_is_struct(t)) {
16854 const struct btf_type *ret;
16858 /* resolve the type size of ksym. */
16859 ret = btf_resolve_size(btf, t, &tsize);
16861 tname = btf_name_by_offset(btf, t->name_off);
16862 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16863 tname, PTR_ERR(ret));
16867 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16868 aux->btf_var.mem_size = tsize;
16870 aux->btf_var.reg_type = PTR_TO_BTF_ID;
16871 aux->btf_var.btf = btf;
16872 aux->btf_var.btf_id = type;
16875 /* check whether we recorded this BTF (and maybe module) already */
16876 for (i = 0; i < env->used_btf_cnt; i++) {
16877 if (env->used_btfs[i].btf == btf) {
16883 if (env->used_btf_cnt >= MAX_USED_BTFS) {
16888 btf_mod = &env->used_btfs[env->used_btf_cnt];
16889 btf_mod->btf = btf;
16890 btf_mod->module = NULL;
16892 /* if we reference variables from kernel module, bump its refcount */
16893 if (btf_is_module(btf)) {
16894 btf_mod->module = btf_try_get_module(btf);
16895 if (!btf_mod->module) {
16901 env->used_btf_cnt++;
16909 static bool is_tracing_prog_type(enum bpf_prog_type type)
16912 case BPF_PROG_TYPE_KPROBE:
16913 case BPF_PROG_TYPE_TRACEPOINT:
16914 case BPF_PROG_TYPE_PERF_EVENT:
16915 case BPF_PROG_TYPE_RAW_TRACEPOINT:
16916 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16923 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16924 struct bpf_map *map,
16925 struct bpf_prog *prog)
16928 enum bpf_prog_type prog_type = resolve_prog_type(prog);
16930 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16931 btf_record_has_field(map->record, BPF_RB_ROOT)) {
16932 if (is_tracing_prog_type(prog_type)) {
16933 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16938 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16939 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16940 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16944 if (is_tracing_prog_type(prog_type)) {
16945 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16949 if (prog->aux->sleepable) {
16950 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16955 if (btf_record_has_field(map->record, BPF_TIMER)) {
16956 if (is_tracing_prog_type(prog_type)) {
16957 verbose(env, "tracing progs cannot use bpf_timer yet\n");
16962 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16963 !bpf_offload_prog_map_match(prog, map)) {
16964 verbose(env, "offload device mismatch between prog and map\n");
16968 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16969 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16973 if (prog->aux->sleepable)
16974 switch (map->map_type) {
16975 case BPF_MAP_TYPE_HASH:
16976 case BPF_MAP_TYPE_LRU_HASH:
16977 case BPF_MAP_TYPE_ARRAY:
16978 case BPF_MAP_TYPE_PERCPU_HASH:
16979 case BPF_MAP_TYPE_PERCPU_ARRAY:
16980 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16981 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16982 case BPF_MAP_TYPE_HASH_OF_MAPS:
16983 case BPF_MAP_TYPE_RINGBUF:
16984 case BPF_MAP_TYPE_USER_RINGBUF:
16985 case BPF_MAP_TYPE_INODE_STORAGE:
16986 case BPF_MAP_TYPE_SK_STORAGE:
16987 case BPF_MAP_TYPE_TASK_STORAGE:
16988 case BPF_MAP_TYPE_CGRP_STORAGE:
16992 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
16999 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17001 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17002 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17005 /* find and rewrite pseudo imm in ld_imm64 instructions:
17007 * 1. if it accesses map FD, replace it with actual map pointer.
17008 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17010 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17012 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17014 struct bpf_insn *insn = env->prog->insnsi;
17015 int insn_cnt = env->prog->len;
17018 err = bpf_prog_calc_tag(env->prog);
17022 for (i = 0; i < insn_cnt; i++, insn++) {
17023 if (BPF_CLASS(insn->code) == BPF_LDX &&
17024 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17026 verbose(env, "BPF_LDX uses reserved fields\n");
17030 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17031 struct bpf_insn_aux_data *aux;
17032 struct bpf_map *map;
17037 if (i == insn_cnt - 1 || insn[1].code != 0 ||
17038 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17039 insn[1].off != 0) {
17040 verbose(env, "invalid bpf_ld_imm64 insn\n");
17044 if (insn[0].src_reg == 0)
17045 /* valid generic load 64-bit imm */
17048 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17049 aux = &env->insn_aux_data[i];
17050 err = check_pseudo_btf_id(env, insn, aux);
17056 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17057 aux = &env->insn_aux_data[i];
17058 aux->ptr_type = PTR_TO_FUNC;
17062 /* In final convert_pseudo_ld_imm64() step, this is
17063 * converted into regular 64-bit imm load insn.
17065 switch (insn[0].src_reg) {
17066 case BPF_PSEUDO_MAP_VALUE:
17067 case BPF_PSEUDO_MAP_IDX_VALUE:
17069 case BPF_PSEUDO_MAP_FD:
17070 case BPF_PSEUDO_MAP_IDX:
17071 if (insn[1].imm == 0)
17075 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17079 switch (insn[0].src_reg) {
17080 case BPF_PSEUDO_MAP_IDX_VALUE:
17081 case BPF_PSEUDO_MAP_IDX:
17082 if (bpfptr_is_null(env->fd_array)) {
17083 verbose(env, "fd_idx without fd_array is invalid\n");
17086 if (copy_from_bpfptr_offset(&fd, env->fd_array,
17087 insn[0].imm * sizeof(fd),
17097 map = __bpf_map_get(f);
17099 verbose(env, "fd %d is not pointing to valid bpf_map\n",
17101 return PTR_ERR(map);
17104 err = check_map_prog_compatibility(env, map, env->prog);
17110 aux = &env->insn_aux_data[i];
17111 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17112 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17113 addr = (unsigned long)map;
17115 u32 off = insn[1].imm;
17117 if (off >= BPF_MAX_VAR_OFF) {
17118 verbose(env, "direct value offset of %u is not allowed\n", off);
17123 if (!map->ops->map_direct_value_addr) {
17124 verbose(env, "no direct value access support for this map type\n");
17129 err = map->ops->map_direct_value_addr(map, &addr, off);
17131 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17132 map->value_size, off);
17137 aux->map_off = off;
17141 insn[0].imm = (u32)addr;
17142 insn[1].imm = addr >> 32;
17144 /* check whether we recorded this map already */
17145 for (j = 0; j < env->used_map_cnt; j++) {
17146 if (env->used_maps[j] == map) {
17147 aux->map_index = j;
17153 if (env->used_map_cnt >= MAX_USED_MAPS) {
17158 /* hold the map. If the program is rejected by verifier,
17159 * the map will be released by release_maps() or it
17160 * will be used by the valid program until it's unloaded
17161 * and all maps are released in free_used_maps()
17165 aux->map_index = env->used_map_cnt;
17166 env->used_maps[env->used_map_cnt++] = map;
17168 if (bpf_map_is_cgroup_storage(map) &&
17169 bpf_cgroup_storage_assign(env->prog->aux, map)) {
17170 verbose(env, "only one cgroup storage of each type is allowed\n");
17182 /* Basic sanity check before we invest more work here. */
17183 if (!bpf_opcode_in_insntable(insn->code)) {
17184 verbose(env, "unknown opcode %02x\n", insn->code);
17189 /* now all pseudo BPF_LD_IMM64 instructions load valid
17190 * 'struct bpf_map *' into a register instead of user map_fd.
17191 * These pointers will be used later by verifier to validate map access.
17196 /* drop refcnt of maps used by the rejected program */
17197 static void release_maps(struct bpf_verifier_env *env)
17199 __bpf_free_used_maps(env->prog->aux, env->used_maps,
17200 env->used_map_cnt);
17203 /* drop refcnt of maps used by the rejected program */
17204 static void release_btfs(struct bpf_verifier_env *env)
17206 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17207 env->used_btf_cnt);
17210 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17211 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17213 struct bpf_insn *insn = env->prog->insnsi;
17214 int insn_cnt = env->prog->len;
17217 for (i = 0; i < insn_cnt; i++, insn++) {
17218 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17220 if (insn->src_reg == BPF_PSEUDO_FUNC)
17226 /* single env->prog->insni[off] instruction was replaced with the range
17227 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
17228 * [0, off) and [off, end) to new locations, so the patched range stays zero
17230 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17231 struct bpf_insn_aux_data *new_data,
17232 struct bpf_prog *new_prog, u32 off, u32 cnt)
17234 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17235 struct bpf_insn *insn = new_prog->insnsi;
17236 u32 old_seen = old_data[off].seen;
17240 /* aux info at OFF always needs adjustment, no matter fast path
17241 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17242 * original insn at old prog.
17244 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17248 prog_len = new_prog->len;
17250 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17251 memcpy(new_data + off + cnt - 1, old_data + off,
17252 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17253 for (i = off; i < off + cnt - 1; i++) {
17254 /* Expand insni[off]'s seen count to the patched range. */
17255 new_data[i].seen = old_seen;
17256 new_data[i].zext_dst = insn_has_def32(env, insn + i);
17258 env->insn_aux_data = new_data;
17262 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17268 /* NOTE: fake 'exit' subprog should be updated as well. */
17269 for (i = 0; i <= env->subprog_cnt; i++) {
17270 if (env->subprog_info[i].start <= off)
17272 env->subprog_info[i].start += len - 1;
17276 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17278 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17279 int i, sz = prog->aux->size_poke_tab;
17280 struct bpf_jit_poke_descriptor *desc;
17282 for (i = 0; i < sz; i++) {
17284 if (desc->insn_idx <= off)
17286 desc->insn_idx += len - 1;
17290 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17291 const struct bpf_insn *patch, u32 len)
17293 struct bpf_prog *new_prog;
17294 struct bpf_insn_aux_data *new_data = NULL;
17297 new_data = vzalloc(array_size(env->prog->len + len - 1,
17298 sizeof(struct bpf_insn_aux_data)));
17303 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17304 if (IS_ERR(new_prog)) {
17305 if (PTR_ERR(new_prog) == -ERANGE)
17307 "insn %d cannot be patched due to 16-bit range\n",
17308 env->insn_aux_data[off].orig_idx);
17312 adjust_insn_aux_data(env, new_data, new_prog, off, len);
17313 adjust_subprog_starts(env, off, len);
17314 adjust_poke_descs(new_prog, off, len);
17318 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17323 /* find first prog starting at or after off (first to remove) */
17324 for (i = 0; i < env->subprog_cnt; i++)
17325 if (env->subprog_info[i].start >= off)
17327 /* find first prog starting at or after off + cnt (first to stay) */
17328 for (j = i; j < env->subprog_cnt; j++)
17329 if (env->subprog_info[j].start >= off + cnt)
17331 /* if j doesn't start exactly at off + cnt, we are just removing
17332 * the front of previous prog
17334 if (env->subprog_info[j].start != off + cnt)
17338 struct bpf_prog_aux *aux = env->prog->aux;
17341 /* move fake 'exit' subprog as well */
17342 move = env->subprog_cnt + 1 - j;
17344 memmove(env->subprog_info + i,
17345 env->subprog_info + j,
17346 sizeof(*env->subprog_info) * move);
17347 env->subprog_cnt -= j - i;
17349 /* remove func_info */
17350 if (aux->func_info) {
17351 move = aux->func_info_cnt - j;
17353 memmove(aux->func_info + i,
17354 aux->func_info + j,
17355 sizeof(*aux->func_info) * move);
17356 aux->func_info_cnt -= j - i;
17357 /* func_info->insn_off is set after all code rewrites,
17358 * in adjust_btf_func() - no need to adjust
17362 /* convert i from "first prog to remove" to "first to adjust" */
17363 if (env->subprog_info[i].start == off)
17367 /* update fake 'exit' subprog as well */
17368 for (; i <= env->subprog_cnt; i++)
17369 env->subprog_info[i].start -= cnt;
17374 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17377 struct bpf_prog *prog = env->prog;
17378 u32 i, l_off, l_cnt, nr_linfo;
17379 struct bpf_line_info *linfo;
17381 nr_linfo = prog->aux->nr_linfo;
17385 linfo = prog->aux->linfo;
17387 /* find first line info to remove, count lines to be removed */
17388 for (i = 0; i < nr_linfo; i++)
17389 if (linfo[i].insn_off >= off)
17394 for (; i < nr_linfo; i++)
17395 if (linfo[i].insn_off < off + cnt)
17400 /* First live insn doesn't match first live linfo, it needs to "inherit"
17401 * last removed linfo. prog is already modified, so prog->len == off
17402 * means no live instructions after (tail of the program was removed).
17404 if (prog->len != off && l_cnt &&
17405 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17407 linfo[--i].insn_off = off + cnt;
17410 /* remove the line info which refer to the removed instructions */
17412 memmove(linfo + l_off, linfo + i,
17413 sizeof(*linfo) * (nr_linfo - i));
17415 prog->aux->nr_linfo -= l_cnt;
17416 nr_linfo = prog->aux->nr_linfo;
17419 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
17420 for (i = l_off; i < nr_linfo; i++)
17421 linfo[i].insn_off -= cnt;
17423 /* fix up all subprogs (incl. 'exit') which start >= off */
17424 for (i = 0; i <= env->subprog_cnt; i++)
17425 if (env->subprog_info[i].linfo_idx > l_off) {
17426 /* program may have started in the removed region but
17427 * may not be fully removed
17429 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17430 env->subprog_info[i].linfo_idx -= l_cnt;
17432 env->subprog_info[i].linfo_idx = l_off;
17438 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17440 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17441 unsigned int orig_prog_len = env->prog->len;
17444 if (bpf_prog_is_offloaded(env->prog->aux))
17445 bpf_prog_offload_remove_insns(env, off, cnt);
17447 err = bpf_remove_insns(env->prog, off, cnt);
17451 err = adjust_subprog_starts_after_remove(env, off, cnt);
17455 err = bpf_adj_linfo_after_remove(env, off, cnt);
17459 memmove(aux_data + off, aux_data + off + cnt,
17460 sizeof(*aux_data) * (orig_prog_len - off - cnt));
17465 /* The verifier does more data flow analysis than llvm and will not
17466 * explore branches that are dead at run time. Malicious programs can
17467 * have dead code too. Therefore replace all dead at-run-time code
17470 * Just nops are not optimal, e.g. if they would sit at the end of the
17471 * program and through another bug we would manage to jump there, then
17472 * we'd execute beyond program memory otherwise. Returning exception
17473 * code also wouldn't work since we can have subprogs where the dead
17474 * code could be located.
17476 static void sanitize_dead_code(struct bpf_verifier_env *env)
17478 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17479 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17480 struct bpf_insn *insn = env->prog->insnsi;
17481 const int insn_cnt = env->prog->len;
17484 for (i = 0; i < insn_cnt; i++) {
17485 if (aux_data[i].seen)
17487 memcpy(insn + i, &trap, sizeof(trap));
17488 aux_data[i].zext_dst = false;
17492 static bool insn_is_cond_jump(u8 code)
17496 if (BPF_CLASS(code) == BPF_JMP32)
17499 if (BPF_CLASS(code) != BPF_JMP)
17503 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17506 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17508 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17509 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17510 struct bpf_insn *insn = env->prog->insnsi;
17511 const int insn_cnt = env->prog->len;
17514 for (i = 0; i < insn_cnt; i++, insn++) {
17515 if (!insn_is_cond_jump(insn->code))
17518 if (!aux_data[i + 1].seen)
17519 ja.off = insn->off;
17520 else if (!aux_data[i + 1 + insn->off].seen)
17525 if (bpf_prog_is_offloaded(env->prog->aux))
17526 bpf_prog_offload_replace_insn(env, i, &ja);
17528 memcpy(insn, &ja, sizeof(ja));
17532 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17534 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17535 int insn_cnt = env->prog->len;
17538 for (i = 0; i < insn_cnt; i++) {
17542 while (i + j < insn_cnt && !aux_data[i + j].seen)
17547 err = verifier_remove_insns(env, i, j);
17550 insn_cnt = env->prog->len;
17556 static int opt_remove_nops(struct bpf_verifier_env *env)
17558 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17559 struct bpf_insn *insn = env->prog->insnsi;
17560 int insn_cnt = env->prog->len;
17563 for (i = 0; i < insn_cnt; i++) {
17564 if (memcmp(&insn[i], &ja, sizeof(ja)))
17567 err = verifier_remove_insns(env, i, 1);
17577 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17578 const union bpf_attr *attr)
17580 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17581 struct bpf_insn_aux_data *aux = env->insn_aux_data;
17582 int i, patch_len, delta = 0, len = env->prog->len;
17583 struct bpf_insn *insns = env->prog->insnsi;
17584 struct bpf_prog *new_prog;
17587 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17588 zext_patch[1] = BPF_ZEXT_REG(0);
17589 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17590 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17591 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17592 for (i = 0; i < len; i++) {
17593 int adj_idx = i + delta;
17594 struct bpf_insn insn;
17597 insn = insns[adj_idx];
17598 load_reg = insn_def_regno(&insn);
17599 if (!aux[adj_idx].zext_dst) {
17607 class = BPF_CLASS(code);
17608 if (load_reg == -1)
17611 /* NOTE: arg "reg" (the fourth one) is only used for
17612 * BPF_STX + SRC_OP, so it is safe to pass NULL
17615 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17616 if (class == BPF_LD &&
17617 BPF_MODE(code) == BPF_IMM)
17622 /* ctx load could be transformed into wider load. */
17623 if (class == BPF_LDX &&
17624 aux[adj_idx].ptr_type == PTR_TO_CTX)
17627 imm_rnd = get_random_u32();
17628 rnd_hi32_patch[0] = insn;
17629 rnd_hi32_patch[1].imm = imm_rnd;
17630 rnd_hi32_patch[3].dst_reg = load_reg;
17631 patch = rnd_hi32_patch;
17633 goto apply_patch_buffer;
17636 /* Add in an zero-extend instruction if a) the JIT has requested
17637 * it or b) it's a CMPXCHG.
17639 * The latter is because: BPF_CMPXCHG always loads a value into
17640 * R0, therefore always zero-extends. However some archs'
17641 * equivalent instruction only does this load when the
17642 * comparison is successful. This detail of CMPXCHG is
17643 * orthogonal to the general zero-extension behaviour of the
17644 * CPU, so it's treated independently of bpf_jit_needs_zext.
17646 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17649 /* Zero-extension is done by the caller. */
17650 if (bpf_pseudo_kfunc_call(&insn))
17653 if (WARN_ON(load_reg == -1)) {
17654 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17658 zext_patch[0] = insn;
17659 zext_patch[1].dst_reg = load_reg;
17660 zext_patch[1].src_reg = load_reg;
17661 patch = zext_patch;
17663 apply_patch_buffer:
17664 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17667 env->prog = new_prog;
17668 insns = new_prog->insnsi;
17669 aux = env->insn_aux_data;
17670 delta += patch_len - 1;
17676 /* convert load instructions that access fields of a context type into a
17677 * sequence of instructions that access fields of the underlying structure:
17678 * struct __sk_buff -> struct sk_buff
17679 * struct bpf_sock_ops -> struct sock
17681 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17683 const struct bpf_verifier_ops *ops = env->ops;
17684 int i, cnt, size, ctx_field_size, delta = 0;
17685 const int insn_cnt = env->prog->len;
17686 struct bpf_insn insn_buf[16], *insn;
17687 u32 target_size, size_default, off;
17688 struct bpf_prog *new_prog;
17689 enum bpf_access_type type;
17690 bool is_narrower_load;
17692 if (ops->gen_prologue || env->seen_direct_write) {
17693 if (!ops->gen_prologue) {
17694 verbose(env, "bpf verifier is misconfigured\n");
17697 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17699 if (cnt >= ARRAY_SIZE(insn_buf)) {
17700 verbose(env, "bpf verifier is misconfigured\n");
17703 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17707 env->prog = new_prog;
17712 if (bpf_prog_is_offloaded(env->prog->aux))
17715 insn = env->prog->insnsi + delta;
17717 for (i = 0; i < insn_cnt; i++, insn++) {
17718 bpf_convert_ctx_access_t convert_ctx_access;
17720 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17721 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17722 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17723 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
17724 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
17725 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
17726 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
17728 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17729 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17730 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17731 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17732 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17733 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17734 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17735 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17741 if (type == BPF_WRITE &&
17742 env->insn_aux_data[i + delta].sanitize_stack_spill) {
17743 struct bpf_insn patch[] = {
17748 cnt = ARRAY_SIZE(patch);
17749 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17754 env->prog = new_prog;
17755 insn = new_prog->insnsi + i + delta;
17759 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17761 if (!ops->convert_ctx_access)
17763 convert_ctx_access = ops->convert_ctx_access;
17765 case PTR_TO_SOCKET:
17766 case PTR_TO_SOCK_COMMON:
17767 convert_ctx_access = bpf_sock_convert_ctx_access;
17769 case PTR_TO_TCP_SOCK:
17770 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17772 case PTR_TO_XDP_SOCK:
17773 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17775 case PTR_TO_BTF_ID:
17776 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17777 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17778 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17779 * be said once it is marked PTR_UNTRUSTED, hence we must handle
17780 * any faults for loads into such types. BPF_WRITE is disallowed
17783 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17784 if (type == BPF_READ) {
17785 if (BPF_MODE(insn->code) == BPF_MEM)
17786 insn->code = BPF_LDX | BPF_PROBE_MEM |
17787 BPF_SIZE((insn)->code);
17789 insn->code = BPF_LDX | BPF_PROBE_MEMSX |
17790 BPF_SIZE((insn)->code);
17791 env->prog->aux->num_exentries++;
17798 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17799 size = BPF_LDST_BYTES(insn);
17801 /* If the read access is a narrower load of the field,
17802 * convert to a 4/8-byte load, to minimum program type specific
17803 * convert_ctx_access changes. If conversion is successful,
17804 * we will apply proper mask to the result.
17806 is_narrower_load = size < ctx_field_size;
17807 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17809 if (is_narrower_load) {
17812 if (type == BPF_WRITE) {
17813 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17818 if (ctx_field_size == 4)
17820 else if (ctx_field_size == 8)
17821 size_code = BPF_DW;
17823 insn->off = off & ~(size_default - 1);
17824 insn->code = BPF_LDX | BPF_MEM | size_code;
17828 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17830 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17831 (ctx_field_size && !target_size)) {
17832 verbose(env, "bpf verifier is misconfigured\n");
17836 if (is_narrower_load && size < target_size) {
17837 u8 shift = bpf_ctx_narrow_access_offset(
17838 off, size, size_default) * 8;
17839 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17840 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17843 if (ctx_field_size <= 4) {
17845 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17848 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17849 (1 << size * 8) - 1);
17852 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17855 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17856 (1ULL << size * 8) - 1);
17860 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17866 /* keep walking new program and skip insns we just inserted */
17867 env->prog = new_prog;
17868 insn = new_prog->insnsi + i + delta;
17874 static int jit_subprogs(struct bpf_verifier_env *env)
17876 struct bpf_prog *prog = env->prog, **func, *tmp;
17877 int i, j, subprog_start, subprog_end = 0, len, subprog;
17878 struct bpf_map *map_ptr;
17879 struct bpf_insn *insn;
17880 void *old_bpf_func;
17881 int err, num_exentries;
17883 if (env->subprog_cnt <= 1)
17886 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17887 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17890 /* Upon error here we cannot fall back to interpreter but
17891 * need a hard reject of the program. Thus -EFAULT is
17892 * propagated in any case.
17894 subprog = find_subprog(env, i + insn->imm + 1);
17896 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17897 i + insn->imm + 1);
17900 /* temporarily remember subprog id inside insn instead of
17901 * aux_data, since next loop will split up all insns into funcs
17903 insn->off = subprog;
17904 /* remember original imm in case JIT fails and fallback
17905 * to interpreter will be needed
17907 env->insn_aux_data[i].call_imm = insn->imm;
17908 /* point imm to __bpf_call_base+1 from JITs point of view */
17910 if (bpf_pseudo_func(insn))
17911 /* jit (e.g. x86_64) may emit fewer instructions
17912 * if it learns a u32 imm is the same as a u64 imm.
17913 * Force a non zero here.
17918 err = bpf_prog_alloc_jited_linfo(prog);
17920 goto out_undo_insn;
17923 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17925 goto out_undo_insn;
17927 for (i = 0; i < env->subprog_cnt; i++) {
17928 subprog_start = subprog_end;
17929 subprog_end = env->subprog_info[i + 1].start;
17931 len = subprog_end - subprog_start;
17932 /* bpf_prog_run() doesn't call subprogs directly,
17933 * hence main prog stats include the runtime of subprogs.
17934 * subprogs don't have IDs and not reachable via prog_get_next_id
17935 * func[i]->stats will never be accessed and stays NULL
17937 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17940 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17941 len * sizeof(struct bpf_insn));
17942 func[i]->type = prog->type;
17943 func[i]->len = len;
17944 if (bpf_prog_calc_tag(func[i]))
17946 func[i]->is_func = 1;
17947 func[i]->aux->func_idx = i;
17948 /* Below members will be freed only at prog->aux */
17949 func[i]->aux->btf = prog->aux->btf;
17950 func[i]->aux->func_info = prog->aux->func_info;
17951 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17952 func[i]->aux->poke_tab = prog->aux->poke_tab;
17953 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17955 for (j = 0; j < prog->aux->size_poke_tab; j++) {
17956 struct bpf_jit_poke_descriptor *poke;
17958 poke = &prog->aux->poke_tab[j];
17959 if (poke->insn_idx < subprog_end &&
17960 poke->insn_idx >= subprog_start)
17961 poke->aux = func[i]->aux;
17964 func[i]->aux->name[0] = 'F';
17965 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17966 func[i]->jit_requested = 1;
17967 func[i]->blinding_requested = prog->blinding_requested;
17968 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17969 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17970 func[i]->aux->linfo = prog->aux->linfo;
17971 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17972 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17973 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17975 insn = func[i]->insnsi;
17976 for (j = 0; j < func[i]->len; j++, insn++) {
17977 if (BPF_CLASS(insn->code) == BPF_LDX &&
17978 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
17979 BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
17982 func[i]->aux->num_exentries = num_exentries;
17983 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
17984 func[i] = bpf_int_jit_compile(func[i]);
17985 if (!func[i]->jited) {
17992 /* at this point all bpf functions were successfully JITed
17993 * now populate all bpf_calls with correct addresses and
17994 * run last pass of JIT
17996 for (i = 0; i < env->subprog_cnt; i++) {
17997 insn = func[i]->insnsi;
17998 for (j = 0; j < func[i]->len; j++, insn++) {
17999 if (bpf_pseudo_func(insn)) {
18000 subprog = insn->off;
18001 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18002 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18005 if (!bpf_pseudo_call(insn))
18007 subprog = insn->off;
18008 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18011 /* we use the aux data to keep a list of the start addresses
18012 * of the JITed images for each function in the program
18014 * for some architectures, such as powerpc64, the imm field
18015 * might not be large enough to hold the offset of the start
18016 * address of the callee's JITed image from __bpf_call_base
18018 * in such cases, we can lookup the start address of a callee
18019 * by using its subprog id, available from the off field of
18020 * the call instruction, as an index for this list
18022 func[i]->aux->func = func;
18023 func[i]->aux->func_cnt = env->subprog_cnt;
18025 for (i = 0; i < env->subprog_cnt; i++) {
18026 old_bpf_func = func[i]->bpf_func;
18027 tmp = bpf_int_jit_compile(func[i]);
18028 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18029 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18036 /* finally lock prog and jit images for all functions and
18037 * populate kallsysm. Begin at the first subprogram, since
18038 * bpf_prog_load will add the kallsyms for the main program.
18040 for (i = 1; i < env->subprog_cnt; i++) {
18041 bpf_prog_lock_ro(func[i]);
18042 bpf_prog_kallsyms_add(func[i]);
18045 /* Last step: make now unused interpreter insns from main
18046 * prog consistent for later dump requests, so they can
18047 * later look the same as if they were interpreted only.
18049 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18050 if (bpf_pseudo_func(insn)) {
18051 insn[0].imm = env->insn_aux_data[i].call_imm;
18052 insn[1].imm = insn->off;
18056 if (!bpf_pseudo_call(insn))
18058 insn->off = env->insn_aux_data[i].call_imm;
18059 subprog = find_subprog(env, i + insn->off + 1);
18060 insn->imm = subprog;
18064 prog->bpf_func = func[0]->bpf_func;
18065 prog->jited_len = func[0]->jited_len;
18066 prog->aux->extable = func[0]->aux->extable;
18067 prog->aux->num_exentries = func[0]->aux->num_exentries;
18068 prog->aux->func = func;
18069 prog->aux->func_cnt = env->subprog_cnt;
18070 bpf_prog_jit_attempt_done(prog);
18073 /* We failed JIT'ing, so at this point we need to unregister poke
18074 * descriptors from subprogs, so that kernel is not attempting to
18075 * patch it anymore as we're freeing the subprog JIT memory.
18077 for (i = 0; i < prog->aux->size_poke_tab; i++) {
18078 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18079 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18081 /* At this point we're guaranteed that poke descriptors are not
18082 * live anymore. We can just unlink its descriptor table as it's
18083 * released with the main prog.
18085 for (i = 0; i < env->subprog_cnt; i++) {
18088 func[i]->aux->poke_tab = NULL;
18089 bpf_jit_free(func[i]);
18093 /* cleanup main prog to be interpreted */
18094 prog->jit_requested = 0;
18095 prog->blinding_requested = 0;
18096 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18097 if (!bpf_pseudo_call(insn))
18100 insn->imm = env->insn_aux_data[i].call_imm;
18102 bpf_prog_jit_attempt_done(prog);
18106 static int fixup_call_args(struct bpf_verifier_env *env)
18108 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18109 struct bpf_prog *prog = env->prog;
18110 struct bpf_insn *insn = prog->insnsi;
18111 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18116 if (env->prog->jit_requested &&
18117 !bpf_prog_is_offloaded(env->prog->aux)) {
18118 err = jit_subprogs(env);
18121 if (err == -EFAULT)
18124 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18125 if (has_kfunc_call) {
18126 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18129 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18130 /* When JIT fails the progs with bpf2bpf calls and tail_calls
18131 * have to be rejected, since interpreter doesn't support them yet.
18133 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18136 for (i = 0; i < prog->len; i++, insn++) {
18137 if (bpf_pseudo_func(insn)) {
18138 /* When JIT fails the progs with callback calls
18139 * have to be rejected, since interpreter doesn't support them yet.
18141 verbose(env, "callbacks are not allowed in non-JITed programs\n");
18145 if (!bpf_pseudo_call(insn))
18147 depth = get_callee_stack_depth(env, insn, i);
18150 bpf_patch_call_args(insn, depth);
18157 /* replace a generic kfunc with a specialized version if necessary */
18158 static void specialize_kfunc(struct bpf_verifier_env *env,
18159 u32 func_id, u16 offset, unsigned long *addr)
18161 struct bpf_prog *prog = env->prog;
18162 bool seen_direct_write;
18166 if (bpf_dev_bound_kfunc_id(func_id)) {
18167 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18169 *addr = (unsigned long)xdp_kfunc;
18172 /* fallback to default kfunc when not supported by netdev */
18178 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18179 seen_direct_write = env->seen_direct_write;
18180 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18183 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18185 /* restore env->seen_direct_write to its original value, since
18186 * may_access_direct_pkt_data mutates it
18188 env->seen_direct_write = seen_direct_write;
18192 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18193 u16 struct_meta_reg,
18194 u16 node_offset_reg,
18195 struct bpf_insn *insn,
18196 struct bpf_insn *insn_buf,
18199 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18200 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18202 insn_buf[0] = addr[0];
18203 insn_buf[1] = addr[1];
18204 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18205 insn_buf[3] = *insn;
18209 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18210 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18212 const struct bpf_kfunc_desc *desc;
18215 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18221 /* insn->imm has the btf func_id. Replace it with an offset relative to
18222 * __bpf_call_base, unless the JIT needs to call functions that are
18223 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18225 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18227 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18232 if (!bpf_jit_supports_far_kfunc_call())
18233 insn->imm = BPF_CALL_IMM(desc->addr);
18236 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18237 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18238 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18239 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18241 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18242 insn_buf[1] = addr[0];
18243 insn_buf[2] = addr[1];
18244 insn_buf[3] = *insn;
18246 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18247 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18248 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18249 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18251 insn_buf[0] = addr[0];
18252 insn_buf[1] = addr[1];
18253 insn_buf[2] = *insn;
18255 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18256 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18257 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18258 int struct_meta_reg = BPF_REG_3;
18259 int node_offset_reg = BPF_REG_4;
18261 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18262 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18263 struct_meta_reg = BPF_REG_4;
18264 node_offset_reg = BPF_REG_5;
18267 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18268 node_offset_reg, insn, insn_buf, cnt);
18269 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18270 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18271 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18277 /* Do various post-verification rewrites in a single program pass.
18278 * These rewrites simplify JIT and interpreter implementations.
18280 static int do_misc_fixups(struct bpf_verifier_env *env)
18282 struct bpf_prog *prog = env->prog;
18283 enum bpf_attach_type eatype = prog->expected_attach_type;
18284 enum bpf_prog_type prog_type = resolve_prog_type(prog);
18285 struct bpf_insn *insn = prog->insnsi;
18286 const struct bpf_func_proto *fn;
18287 const int insn_cnt = prog->len;
18288 const struct bpf_map_ops *ops;
18289 struct bpf_insn_aux_data *aux;
18290 struct bpf_insn insn_buf[16];
18291 struct bpf_prog *new_prog;
18292 struct bpf_map *map_ptr;
18293 int i, ret, cnt, delta = 0;
18295 for (i = 0; i < insn_cnt; i++, insn++) {
18296 /* Make divide-by-zero exceptions impossible. */
18297 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18298 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18299 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18300 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18301 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18302 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18303 struct bpf_insn *patchlet;
18304 struct bpf_insn chk_and_div[] = {
18305 /* [R,W]x div 0 -> 0 */
18306 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18307 BPF_JNE | BPF_K, insn->src_reg,
18309 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18310 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18313 struct bpf_insn chk_and_mod[] = {
18314 /* [R,W]x mod 0 -> [R,W]x */
18315 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18316 BPF_JEQ | BPF_K, insn->src_reg,
18317 0, 1 + (is64 ? 0 : 1), 0),
18319 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18320 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18323 patchlet = isdiv ? chk_and_div : chk_and_mod;
18324 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18325 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18327 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18332 env->prog = prog = new_prog;
18333 insn = new_prog->insnsi + i + delta;
18337 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18338 if (BPF_CLASS(insn->code) == BPF_LD &&
18339 (BPF_MODE(insn->code) == BPF_ABS ||
18340 BPF_MODE(insn->code) == BPF_IND)) {
18341 cnt = env->ops->gen_ld_abs(insn, insn_buf);
18342 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18343 verbose(env, "bpf verifier is misconfigured\n");
18347 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18352 env->prog = prog = new_prog;
18353 insn = new_prog->insnsi + i + delta;
18357 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
18358 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18359 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18360 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18361 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18362 struct bpf_insn *patch = &insn_buf[0];
18363 bool issrc, isneg, isimm;
18366 aux = &env->insn_aux_data[i + delta];
18367 if (!aux->alu_state ||
18368 aux->alu_state == BPF_ALU_NON_POINTER)
18371 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18372 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18373 BPF_ALU_SANITIZE_SRC;
18374 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18376 off_reg = issrc ? insn->src_reg : insn->dst_reg;
18378 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18381 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18382 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18383 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18384 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18385 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18386 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18387 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18390 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18391 insn->src_reg = BPF_REG_AX;
18393 insn->code = insn->code == code_add ?
18394 code_sub : code_add;
18396 if (issrc && isneg && !isimm)
18397 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18398 cnt = patch - insn_buf;
18400 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18405 env->prog = prog = new_prog;
18406 insn = new_prog->insnsi + i + delta;
18410 if (insn->code != (BPF_JMP | BPF_CALL))
18412 if (insn->src_reg == BPF_PSEUDO_CALL)
18414 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18415 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18421 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18426 env->prog = prog = new_prog;
18427 insn = new_prog->insnsi + i + delta;
18431 if (insn->imm == BPF_FUNC_get_route_realm)
18432 prog->dst_needed = 1;
18433 if (insn->imm == BPF_FUNC_get_prandom_u32)
18434 bpf_user_rnd_init_once();
18435 if (insn->imm == BPF_FUNC_override_return)
18436 prog->kprobe_override = 1;
18437 if (insn->imm == BPF_FUNC_tail_call) {
18438 /* If we tail call into other programs, we
18439 * cannot make any assumptions since they can
18440 * be replaced dynamically during runtime in
18441 * the program array.
18443 prog->cb_access = 1;
18444 if (!allow_tail_call_in_subprogs(env))
18445 prog->aux->stack_depth = MAX_BPF_STACK;
18446 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18448 /* mark bpf_tail_call as different opcode to avoid
18449 * conditional branch in the interpreter for every normal
18450 * call and to prevent accidental JITing by JIT compiler
18451 * that doesn't support bpf_tail_call yet
18454 insn->code = BPF_JMP | BPF_TAIL_CALL;
18456 aux = &env->insn_aux_data[i + delta];
18457 if (env->bpf_capable && !prog->blinding_requested &&
18458 prog->jit_requested &&
18459 !bpf_map_key_poisoned(aux) &&
18460 !bpf_map_ptr_poisoned(aux) &&
18461 !bpf_map_ptr_unpriv(aux)) {
18462 struct bpf_jit_poke_descriptor desc = {
18463 .reason = BPF_POKE_REASON_TAIL_CALL,
18464 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18465 .tail_call.key = bpf_map_key_immediate(aux),
18466 .insn_idx = i + delta,
18469 ret = bpf_jit_add_poke_descriptor(prog, &desc);
18471 verbose(env, "adding tail call poke descriptor failed\n");
18475 insn->imm = ret + 1;
18479 if (!bpf_map_ptr_unpriv(aux))
18482 /* instead of changing every JIT dealing with tail_call
18483 * emit two extra insns:
18484 * if (index >= max_entries) goto out;
18485 * index &= array->index_mask;
18486 * to avoid out-of-bounds cpu speculation
18488 if (bpf_map_ptr_poisoned(aux)) {
18489 verbose(env, "tail_call abusing map_ptr\n");
18493 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18494 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18495 map_ptr->max_entries, 2);
18496 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18497 container_of(map_ptr,
18500 insn_buf[2] = *insn;
18502 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18507 env->prog = prog = new_prog;
18508 insn = new_prog->insnsi + i + delta;
18512 if (insn->imm == BPF_FUNC_timer_set_callback) {
18513 /* The verifier will process callback_fn as many times as necessary
18514 * with different maps and the register states prepared by
18515 * set_timer_callback_state will be accurate.
18517 * The following use case is valid:
18518 * map1 is shared by prog1, prog2, prog3.
18519 * prog1 calls bpf_timer_init for some map1 elements
18520 * prog2 calls bpf_timer_set_callback for some map1 elements.
18521 * Those that were not bpf_timer_init-ed will return -EINVAL.
18522 * prog3 calls bpf_timer_start for some map1 elements.
18523 * Those that were not both bpf_timer_init-ed and
18524 * bpf_timer_set_callback-ed will return -EINVAL.
18526 struct bpf_insn ld_addrs[2] = {
18527 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18530 insn_buf[0] = ld_addrs[0];
18531 insn_buf[1] = ld_addrs[1];
18532 insn_buf[2] = *insn;
18535 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18540 env->prog = prog = new_prog;
18541 insn = new_prog->insnsi + i + delta;
18542 goto patch_call_imm;
18545 if (is_storage_get_function(insn->imm)) {
18546 if (!env->prog->aux->sleepable ||
18547 env->insn_aux_data[i + delta].storage_get_func_atomic)
18548 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18550 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18551 insn_buf[1] = *insn;
18554 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18559 env->prog = prog = new_prog;
18560 insn = new_prog->insnsi + i + delta;
18561 goto patch_call_imm;
18564 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18565 * and other inlining handlers are currently limited to 64 bit
18568 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18569 (insn->imm == BPF_FUNC_map_lookup_elem ||
18570 insn->imm == BPF_FUNC_map_update_elem ||
18571 insn->imm == BPF_FUNC_map_delete_elem ||
18572 insn->imm == BPF_FUNC_map_push_elem ||
18573 insn->imm == BPF_FUNC_map_pop_elem ||
18574 insn->imm == BPF_FUNC_map_peek_elem ||
18575 insn->imm == BPF_FUNC_redirect_map ||
18576 insn->imm == BPF_FUNC_for_each_map_elem ||
18577 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18578 aux = &env->insn_aux_data[i + delta];
18579 if (bpf_map_ptr_poisoned(aux))
18580 goto patch_call_imm;
18582 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18583 ops = map_ptr->ops;
18584 if (insn->imm == BPF_FUNC_map_lookup_elem &&
18585 ops->map_gen_lookup) {
18586 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18587 if (cnt == -EOPNOTSUPP)
18588 goto patch_map_ops_generic;
18589 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18590 verbose(env, "bpf verifier is misconfigured\n");
18594 new_prog = bpf_patch_insn_data(env, i + delta,
18600 env->prog = prog = new_prog;
18601 insn = new_prog->insnsi + i + delta;
18605 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18606 (void *(*)(struct bpf_map *map, void *key))NULL));
18607 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18608 (long (*)(struct bpf_map *map, void *key))NULL));
18609 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18610 (long (*)(struct bpf_map *map, void *key, void *value,
18612 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18613 (long (*)(struct bpf_map *map, void *value,
18615 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18616 (long (*)(struct bpf_map *map, void *value))NULL));
18617 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18618 (long (*)(struct bpf_map *map, void *value))NULL));
18619 BUILD_BUG_ON(!__same_type(ops->map_redirect,
18620 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18621 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18622 (long (*)(struct bpf_map *map,
18623 bpf_callback_t callback_fn,
18624 void *callback_ctx,
18626 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18627 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18629 patch_map_ops_generic:
18630 switch (insn->imm) {
18631 case BPF_FUNC_map_lookup_elem:
18632 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18634 case BPF_FUNC_map_update_elem:
18635 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18637 case BPF_FUNC_map_delete_elem:
18638 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18640 case BPF_FUNC_map_push_elem:
18641 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18643 case BPF_FUNC_map_pop_elem:
18644 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18646 case BPF_FUNC_map_peek_elem:
18647 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18649 case BPF_FUNC_redirect_map:
18650 insn->imm = BPF_CALL_IMM(ops->map_redirect);
18652 case BPF_FUNC_for_each_map_elem:
18653 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18655 case BPF_FUNC_map_lookup_percpu_elem:
18656 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18660 goto patch_call_imm;
18663 /* Implement bpf_jiffies64 inline. */
18664 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18665 insn->imm == BPF_FUNC_jiffies64) {
18666 struct bpf_insn ld_jiffies_addr[2] = {
18667 BPF_LD_IMM64(BPF_REG_0,
18668 (unsigned long)&jiffies),
18671 insn_buf[0] = ld_jiffies_addr[0];
18672 insn_buf[1] = ld_jiffies_addr[1];
18673 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18677 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18683 env->prog = prog = new_prog;
18684 insn = new_prog->insnsi + i + delta;
18688 /* Implement bpf_get_func_arg inline. */
18689 if (prog_type == BPF_PROG_TYPE_TRACING &&
18690 insn->imm == BPF_FUNC_get_func_arg) {
18691 /* Load nr_args from ctx - 8 */
18692 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18693 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18694 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18695 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18696 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18697 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18698 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18699 insn_buf[7] = BPF_JMP_A(1);
18700 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18703 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18708 env->prog = prog = new_prog;
18709 insn = new_prog->insnsi + i + delta;
18713 /* Implement bpf_get_func_ret inline. */
18714 if (prog_type == BPF_PROG_TYPE_TRACING &&
18715 insn->imm == BPF_FUNC_get_func_ret) {
18716 if (eatype == BPF_TRACE_FEXIT ||
18717 eatype == BPF_MODIFY_RETURN) {
18718 /* Load nr_args from ctx - 8 */
18719 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18720 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18721 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18722 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18723 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18724 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18727 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18731 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18736 env->prog = prog = new_prog;
18737 insn = new_prog->insnsi + i + delta;
18741 /* Implement get_func_arg_cnt inline. */
18742 if (prog_type == BPF_PROG_TYPE_TRACING &&
18743 insn->imm == BPF_FUNC_get_func_arg_cnt) {
18744 /* Load nr_args from ctx - 8 */
18745 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18747 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18751 env->prog = prog = new_prog;
18752 insn = new_prog->insnsi + i + delta;
18756 /* Implement bpf_get_func_ip inline. */
18757 if (prog_type == BPF_PROG_TYPE_TRACING &&
18758 insn->imm == BPF_FUNC_get_func_ip) {
18759 /* Load IP address from ctx - 16 */
18760 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18762 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18766 env->prog = prog = new_prog;
18767 insn = new_prog->insnsi + i + delta;
18772 fn = env->ops->get_func_proto(insn->imm, env->prog);
18773 /* all functions that have prototype and verifier allowed
18774 * programs to call them, must be real in-kernel functions
18778 "kernel subsystem misconfigured func %s#%d\n",
18779 func_id_name(insn->imm), insn->imm);
18782 insn->imm = fn->func - __bpf_call_base;
18785 /* Since poke tab is now finalized, publish aux to tracker. */
18786 for (i = 0; i < prog->aux->size_poke_tab; i++) {
18787 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18788 if (!map_ptr->ops->map_poke_track ||
18789 !map_ptr->ops->map_poke_untrack ||
18790 !map_ptr->ops->map_poke_run) {
18791 verbose(env, "bpf verifier is misconfigured\n");
18795 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18797 verbose(env, "tracking tail call prog failed\n");
18802 sort_kfunc_descs_by_imm_off(env->prog);
18807 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18810 u32 callback_subprogno,
18813 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18814 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18815 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18816 int reg_loop_max = BPF_REG_6;
18817 int reg_loop_cnt = BPF_REG_7;
18818 int reg_loop_ctx = BPF_REG_8;
18820 struct bpf_prog *new_prog;
18821 u32 callback_start;
18822 u32 call_insn_offset;
18823 s32 callback_offset;
18825 /* This represents an inlined version of bpf_iter.c:bpf_loop,
18826 * be careful to modify this code in sync.
18828 struct bpf_insn insn_buf[] = {
18829 /* Return error and jump to the end of the patch if
18830 * expected number of iterations is too big.
18832 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18833 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18834 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18835 /* spill R6, R7, R8 to use these as loop vars */
18836 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18837 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18838 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18839 /* initialize loop vars */
18840 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18841 BPF_MOV32_IMM(reg_loop_cnt, 0),
18842 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18844 * if reg_loop_cnt >= reg_loop_max skip the loop body
18846 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18848 * correct callback offset would be set after patching
18850 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18851 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18853 /* increment loop counter */
18854 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18855 /* jump to loop header if callback returned 0 */
18856 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18857 /* return value of bpf_loop,
18858 * set R0 to the number of iterations
18860 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18861 /* restore original values of R6, R7, R8 */
18862 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18863 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18864 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18867 *cnt = ARRAY_SIZE(insn_buf);
18868 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18872 /* callback start is known only after patching */
18873 callback_start = env->subprog_info[callback_subprogno].start;
18874 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18875 call_insn_offset = position + 12;
18876 callback_offset = callback_start - call_insn_offset - 1;
18877 new_prog->insnsi[call_insn_offset].imm = callback_offset;
18882 static bool is_bpf_loop_call(struct bpf_insn *insn)
18884 return insn->code == (BPF_JMP | BPF_CALL) &&
18885 insn->src_reg == 0 &&
18886 insn->imm == BPF_FUNC_loop;
18889 /* For all sub-programs in the program (including main) check
18890 * insn_aux_data to see if there are bpf_loop calls that require
18891 * inlining. If such calls are found the calls are replaced with a
18892 * sequence of instructions produced by `inline_bpf_loop` function and
18893 * subprog stack_depth is increased by the size of 3 registers.
18894 * This stack space is used to spill values of the R6, R7, R8. These
18895 * registers are used to store the loop bound, counter and context
18898 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18900 struct bpf_subprog_info *subprogs = env->subprog_info;
18901 int i, cur_subprog = 0, cnt, delta = 0;
18902 struct bpf_insn *insn = env->prog->insnsi;
18903 int insn_cnt = env->prog->len;
18904 u16 stack_depth = subprogs[cur_subprog].stack_depth;
18905 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18906 u16 stack_depth_extra = 0;
18908 for (i = 0; i < insn_cnt; i++, insn++) {
18909 struct bpf_loop_inline_state *inline_state =
18910 &env->insn_aux_data[i + delta].loop_inline_state;
18912 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18913 struct bpf_prog *new_prog;
18915 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18916 new_prog = inline_bpf_loop(env,
18918 -(stack_depth + stack_depth_extra),
18919 inline_state->callback_subprogno,
18925 env->prog = new_prog;
18926 insn = new_prog->insnsi + i + delta;
18929 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18930 subprogs[cur_subprog].stack_depth += stack_depth_extra;
18932 stack_depth = subprogs[cur_subprog].stack_depth;
18933 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18934 stack_depth_extra = 0;
18938 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18943 static void free_states(struct bpf_verifier_env *env)
18945 struct bpf_verifier_state_list *sl, *sln;
18948 sl = env->free_list;
18951 free_verifier_state(&sl->state, false);
18955 env->free_list = NULL;
18957 if (!env->explored_states)
18960 for (i = 0; i < state_htab_size(env); i++) {
18961 sl = env->explored_states[i];
18965 free_verifier_state(&sl->state, false);
18969 env->explored_states[i] = NULL;
18973 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18975 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18976 struct bpf_verifier_state *state;
18977 struct bpf_reg_state *regs;
18980 env->prev_linfo = NULL;
18983 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18986 state->curframe = 0;
18987 state->speculative = false;
18988 state->branches = 1;
18989 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18990 if (!state->frame[0]) {
18994 env->cur_state = state;
18995 init_func_state(env, state->frame[0],
18996 BPF_MAIN_FUNC /* callsite */,
18999 state->first_insn_idx = env->subprog_info[subprog].start;
19000 state->last_insn_idx = -1;
19002 regs = state->frame[state->curframe]->regs;
19003 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19004 ret = btf_prepare_func_args(env, subprog, regs);
19007 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19008 if (regs[i].type == PTR_TO_CTX)
19009 mark_reg_known_zero(env, regs, i);
19010 else if (regs[i].type == SCALAR_VALUE)
19011 mark_reg_unknown(env, regs, i);
19012 else if (base_type(regs[i].type) == PTR_TO_MEM) {
19013 const u32 mem_size = regs[i].mem_size;
19015 mark_reg_known_zero(env, regs, i);
19016 regs[i].mem_size = mem_size;
19017 regs[i].id = ++env->id_gen;
19021 /* 1st arg to a function */
19022 regs[BPF_REG_1].type = PTR_TO_CTX;
19023 mark_reg_known_zero(env, regs, BPF_REG_1);
19024 ret = btf_check_subprog_arg_match(env, subprog, regs);
19025 if (ret == -EFAULT)
19026 /* unlikely verifier bug. abort.
19027 * ret == 0 and ret < 0 are sadly acceptable for
19028 * main() function due to backward compatibility.
19029 * Like socket filter program may be written as:
19030 * int bpf_prog(struct pt_regs *ctx)
19031 * and never dereference that ctx in the program.
19032 * 'struct pt_regs' is a type mismatch for socket
19033 * filter that should be using 'struct __sk_buff'.
19038 ret = do_check(env);
19040 /* check for NULL is necessary, since cur_state can be freed inside
19041 * do_check() under memory pressure.
19043 if (env->cur_state) {
19044 free_verifier_state(env->cur_state, true);
19045 env->cur_state = NULL;
19047 while (!pop_stack(env, NULL, NULL, false));
19048 if (!ret && pop_log)
19049 bpf_vlog_reset(&env->log, 0);
19054 /* Verify all global functions in a BPF program one by one based on their BTF.
19055 * All global functions must pass verification. Otherwise the whole program is rejected.
19066 * foo() will be verified first for R1=any_scalar_value. During verification it
19067 * will be assumed that bar() already verified successfully and call to bar()
19068 * from foo() will be checked for type match only. Later bar() will be verified
19069 * independently to check that it's safe for R1=any_scalar_value.
19071 static int do_check_subprogs(struct bpf_verifier_env *env)
19073 struct bpf_prog_aux *aux = env->prog->aux;
19076 if (!aux->func_info)
19079 for (i = 1; i < env->subprog_cnt; i++) {
19080 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19082 env->insn_idx = env->subprog_info[i].start;
19083 WARN_ON_ONCE(env->insn_idx == 0);
19084 ret = do_check_common(env, i);
19087 } else if (env->log.level & BPF_LOG_LEVEL) {
19089 "Func#%d is safe for any args that match its prototype\n",
19096 static int do_check_main(struct bpf_verifier_env *env)
19101 ret = do_check_common(env, 0);
19103 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19108 static void print_verification_stats(struct bpf_verifier_env *env)
19112 if (env->log.level & BPF_LOG_STATS) {
19113 verbose(env, "verification time %lld usec\n",
19114 div_u64(env->verification_time, 1000));
19115 verbose(env, "stack depth ");
19116 for (i = 0; i < env->subprog_cnt; i++) {
19117 u32 depth = env->subprog_info[i].stack_depth;
19119 verbose(env, "%d", depth);
19120 if (i + 1 < env->subprog_cnt)
19123 verbose(env, "\n");
19125 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19126 "total_states %d peak_states %d mark_read %d\n",
19127 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19128 env->max_states_per_insn, env->total_states,
19129 env->peak_states, env->longest_mark_read_walk);
19132 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19134 const struct btf_type *t, *func_proto;
19135 const struct bpf_struct_ops *st_ops;
19136 const struct btf_member *member;
19137 struct bpf_prog *prog = env->prog;
19138 u32 btf_id, member_idx;
19141 if (!prog->gpl_compatible) {
19142 verbose(env, "struct ops programs must have a GPL compatible license\n");
19146 btf_id = prog->aux->attach_btf_id;
19147 st_ops = bpf_struct_ops_find(btf_id);
19149 verbose(env, "attach_btf_id %u is not a supported struct\n",
19155 member_idx = prog->expected_attach_type;
19156 if (member_idx >= btf_type_vlen(t)) {
19157 verbose(env, "attach to invalid member idx %u of struct %s\n",
19158 member_idx, st_ops->name);
19162 member = &btf_type_member(t)[member_idx];
19163 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19164 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19167 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19168 mname, member_idx, st_ops->name);
19172 if (st_ops->check_member) {
19173 int err = st_ops->check_member(t, member, prog);
19176 verbose(env, "attach to unsupported member %s of struct %s\n",
19177 mname, st_ops->name);
19182 prog->aux->attach_func_proto = func_proto;
19183 prog->aux->attach_func_name = mname;
19184 env->ops = st_ops->verifier_ops;
19188 #define SECURITY_PREFIX "security_"
19190 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19192 if (within_error_injection_list(addr) ||
19193 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19199 /* list of non-sleepable functions that are otherwise on
19200 * ALLOW_ERROR_INJECTION list
19202 BTF_SET_START(btf_non_sleepable_error_inject)
19203 /* Three functions below can be called from sleepable and non-sleepable context.
19204 * Assume non-sleepable from bpf safety point of view.
19206 BTF_ID(func, __filemap_add_folio)
19207 BTF_ID(func, should_fail_alloc_page)
19208 BTF_ID(func, should_failslab)
19209 BTF_SET_END(btf_non_sleepable_error_inject)
19211 static int check_non_sleepable_error_inject(u32 btf_id)
19213 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19216 int bpf_check_attach_target(struct bpf_verifier_log *log,
19217 const struct bpf_prog *prog,
19218 const struct bpf_prog *tgt_prog,
19220 struct bpf_attach_target_info *tgt_info)
19222 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19223 const char prefix[] = "btf_trace_";
19224 int ret = 0, subprog = -1, i;
19225 const struct btf_type *t;
19226 bool conservative = true;
19230 struct module *mod = NULL;
19233 bpf_log(log, "Tracing programs must provide btf_id\n");
19236 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19239 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19242 t = btf_type_by_id(btf, btf_id);
19244 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19247 tname = btf_name_by_offset(btf, t->name_off);
19249 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19253 struct bpf_prog_aux *aux = tgt_prog->aux;
19255 if (bpf_prog_is_dev_bound(prog->aux) &&
19256 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19257 bpf_log(log, "Target program bound device mismatch");
19261 for (i = 0; i < aux->func_info_cnt; i++)
19262 if (aux->func_info[i].type_id == btf_id) {
19266 if (subprog == -1) {
19267 bpf_log(log, "Subprog %s doesn't exist\n", tname);
19270 conservative = aux->func_info_aux[subprog].unreliable;
19271 if (prog_extension) {
19272 if (conservative) {
19274 "Cannot replace static functions\n");
19277 if (!prog->jit_requested) {
19279 "Extension programs should be JITed\n");
19283 if (!tgt_prog->jited) {
19284 bpf_log(log, "Can attach to only JITed progs\n");
19287 if (tgt_prog->type == prog->type) {
19288 /* Cannot fentry/fexit another fentry/fexit program.
19289 * Cannot attach program extension to another extension.
19290 * It's ok to attach fentry/fexit to extension program.
19292 bpf_log(log, "Cannot recursively attach\n");
19295 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19297 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19298 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19299 /* Program extensions can extend all program types
19300 * except fentry/fexit. The reason is the following.
19301 * The fentry/fexit programs are used for performance
19302 * analysis, stats and can be attached to any program
19303 * type except themselves. When extension program is
19304 * replacing XDP function it is necessary to allow
19305 * performance analysis of all functions. Both original
19306 * XDP program and its program extension. Hence
19307 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19308 * allowed. If extending of fentry/fexit was allowed it
19309 * would be possible to create long call chain
19310 * fentry->extension->fentry->extension beyond
19311 * reasonable stack size. Hence extending fentry is not
19314 bpf_log(log, "Cannot extend fentry/fexit\n");
19318 if (prog_extension) {
19319 bpf_log(log, "Cannot replace kernel functions\n");
19324 switch (prog->expected_attach_type) {
19325 case BPF_TRACE_RAW_TP:
19328 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19331 if (!btf_type_is_typedef(t)) {
19332 bpf_log(log, "attach_btf_id %u is not a typedef\n",
19336 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19337 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19341 tname += sizeof(prefix) - 1;
19342 t = btf_type_by_id(btf, t->type);
19343 if (!btf_type_is_ptr(t))
19344 /* should never happen in valid vmlinux build */
19346 t = btf_type_by_id(btf, t->type);
19347 if (!btf_type_is_func_proto(t))
19348 /* should never happen in valid vmlinux build */
19352 case BPF_TRACE_ITER:
19353 if (!btf_type_is_func(t)) {
19354 bpf_log(log, "attach_btf_id %u is not a function\n",
19358 t = btf_type_by_id(btf, t->type);
19359 if (!btf_type_is_func_proto(t))
19361 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19366 if (!prog_extension)
19369 case BPF_MODIFY_RETURN:
19371 case BPF_LSM_CGROUP:
19372 case BPF_TRACE_FENTRY:
19373 case BPF_TRACE_FEXIT:
19374 if (!btf_type_is_func(t)) {
19375 bpf_log(log, "attach_btf_id %u is not a function\n",
19379 if (prog_extension &&
19380 btf_check_type_match(log, prog, btf, t))
19382 t = btf_type_by_id(btf, t->type);
19383 if (!btf_type_is_func_proto(t))
19386 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19387 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19388 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19391 if (tgt_prog && conservative)
19394 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19400 addr = (long) tgt_prog->bpf_func;
19402 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19404 if (btf_is_module(btf)) {
19405 mod = btf_try_get_module(btf);
19407 addr = find_kallsyms_symbol_value(mod, tname);
19411 addr = kallsyms_lookup_name(tname);
19416 "The address of function %s cannot be found\n",
19422 if (prog->aux->sleepable) {
19424 switch (prog->type) {
19425 case BPF_PROG_TYPE_TRACING:
19427 /* fentry/fexit/fmod_ret progs can be sleepable if they are
19428 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19430 if (!check_non_sleepable_error_inject(btf_id) &&
19431 within_error_injection_list(addr))
19433 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
19434 * in the fmodret id set with the KF_SLEEPABLE flag.
19437 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19440 if (flags && (*flags & KF_SLEEPABLE))
19444 case BPF_PROG_TYPE_LSM:
19445 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
19446 * Only some of them are sleepable.
19448 if (bpf_lsm_is_sleepable_hook(btf_id))
19456 bpf_log(log, "%s is not sleepable\n", tname);
19459 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19462 bpf_log(log, "can't modify return codes of BPF programs\n");
19466 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19467 !check_attach_modify_return(addr, tname))
19471 bpf_log(log, "%s() is not modifiable\n", tname);
19478 tgt_info->tgt_addr = addr;
19479 tgt_info->tgt_name = tname;
19480 tgt_info->tgt_type = t;
19481 tgt_info->tgt_mod = mod;
19485 BTF_SET_START(btf_id_deny)
19488 BTF_ID(func, migrate_disable)
19489 BTF_ID(func, migrate_enable)
19491 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19492 BTF_ID(func, rcu_read_unlock_strict)
19494 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19495 BTF_ID(func, preempt_count_add)
19496 BTF_ID(func, preempt_count_sub)
19498 #ifdef CONFIG_PREEMPT_RCU
19499 BTF_ID(func, __rcu_read_lock)
19500 BTF_ID(func, __rcu_read_unlock)
19502 BTF_SET_END(btf_id_deny)
19504 static bool can_be_sleepable(struct bpf_prog *prog)
19506 if (prog->type == BPF_PROG_TYPE_TRACING) {
19507 switch (prog->expected_attach_type) {
19508 case BPF_TRACE_FENTRY:
19509 case BPF_TRACE_FEXIT:
19510 case BPF_MODIFY_RETURN:
19511 case BPF_TRACE_ITER:
19517 return prog->type == BPF_PROG_TYPE_LSM ||
19518 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19519 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19522 static int check_attach_btf_id(struct bpf_verifier_env *env)
19524 struct bpf_prog *prog = env->prog;
19525 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19526 struct bpf_attach_target_info tgt_info = {};
19527 u32 btf_id = prog->aux->attach_btf_id;
19528 struct bpf_trampoline *tr;
19532 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19533 if (prog->aux->sleepable)
19534 /* attach_btf_id checked to be zero already */
19536 verbose(env, "Syscall programs can only be sleepable\n");
19540 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19541 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19545 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19546 return check_struct_ops_btf_id(env);
19548 if (prog->type != BPF_PROG_TYPE_TRACING &&
19549 prog->type != BPF_PROG_TYPE_LSM &&
19550 prog->type != BPF_PROG_TYPE_EXT)
19553 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19557 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19558 /* to make freplace equivalent to their targets, they need to
19559 * inherit env->ops and expected_attach_type for the rest of the
19562 env->ops = bpf_verifier_ops[tgt_prog->type];
19563 prog->expected_attach_type = tgt_prog->expected_attach_type;
19566 /* store info about the attachment target that will be used later */
19567 prog->aux->attach_func_proto = tgt_info.tgt_type;
19568 prog->aux->attach_func_name = tgt_info.tgt_name;
19569 prog->aux->mod = tgt_info.tgt_mod;
19572 prog->aux->saved_dst_prog_type = tgt_prog->type;
19573 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19576 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19577 prog->aux->attach_btf_trace = true;
19579 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19580 if (!bpf_iter_prog_supported(prog))
19585 if (prog->type == BPF_PROG_TYPE_LSM) {
19586 ret = bpf_lsm_verify_prog(&env->log, prog);
19589 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
19590 btf_id_set_contains(&btf_id_deny, btf_id)) {
19594 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19595 tr = bpf_trampoline_get(key, &tgt_info);
19599 prog->aux->dst_trampoline = tr;
19603 struct btf *bpf_get_btf_vmlinux(void)
19605 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19606 mutex_lock(&bpf_verifier_lock);
19608 btf_vmlinux = btf_parse_vmlinux();
19609 mutex_unlock(&bpf_verifier_lock);
19611 return btf_vmlinux;
19614 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19616 u64 start_time = ktime_get_ns();
19617 struct bpf_verifier_env *env;
19618 int i, len, ret = -EINVAL, err;
19622 /* no program is valid */
19623 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19626 /* 'struct bpf_verifier_env' can be global, but since it's not small,
19627 * allocate/free it every time bpf_check() is called
19629 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19635 len = (*prog)->len;
19636 env->insn_aux_data =
19637 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19639 if (!env->insn_aux_data)
19641 for (i = 0; i < len; i++)
19642 env->insn_aux_data[i].orig_idx = i;
19644 env->ops = bpf_verifier_ops[env->prog->type];
19645 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19646 is_priv = bpf_capable();
19648 bpf_get_btf_vmlinux();
19650 /* grab the mutex to protect few globals used by verifier */
19652 mutex_lock(&bpf_verifier_lock);
19654 /* user could have requested verbose verifier output
19655 * and supplied buffer to store the verification trace
19657 ret = bpf_vlog_init(&env->log, attr->log_level,
19658 (char __user *) (unsigned long) attr->log_buf,
19663 mark_verifier_state_clean(env);
19665 if (IS_ERR(btf_vmlinux)) {
19666 /* Either gcc or pahole or kernel are broken. */
19667 verbose(env, "in-kernel BTF is malformed\n");
19668 ret = PTR_ERR(btf_vmlinux);
19669 goto skip_full_check;
19672 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19673 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19674 env->strict_alignment = true;
19675 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19676 env->strict_alignment = false;
19678 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19679 env->allow_uninit_stack = bpf_allow_uninit_stack();
19680 env->bypass_spec_v1 = bpf_bypass_spec_v1();
19681 env->bypass_spec_v4 = bpf_bypass_spec_v4();
19682 env->bpf_capable = bpf_capable();
19685 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19687 env->explored_states = kvcalloc(state_htab_size(env),
19688 sizeof(struct bpf_verifier_state_list *),
19691 if (!env->explored_states)
19692 goto skip_full_check;
19694 ret = add_subprog_and_kfunc(env);
19696 goto skip_full_check;
19698 ret = check_subprogs(env);
19700 goto skip_full_check;
19702 ret = check_btf_info(env, attr, uattr);
19704 goto skip_full_check;
19706 ret = check_attach_btf_id(env);
19708 goto skip_full_check;
19710 ret = resolve_pseudo_ldimm64(env);
19712 goto skip_full_check;
19714 if (bpf_prog_is_offloaded(env->prog->aux)) {
19715 ret = bpf_prog_offload_verifier_prep(env->prog);
19717 goto skip_full_check;
19720 ret = check_cfg(env);
19722 goto skip_full_check;
19724 ret = do_check_subprogs(env);
19725 ret = ret ?: do_check_main(env);
19727 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19728 ret = bpf_prog_offload_finalize(env);
19731 kvfree(env->explored_states);
19734 ret = check_max_stack_depth(env);
19736 /* instruction rewrites happen after this point */
19738 ret = optimize_bpf_loop(env);
19742 opt_hard_wire_dead_code_branches(env);
19744 ret = opt_remove_dead_code(env);
19746 ret = opt_remove_nops(env);
19749 sanitize_dead_code(env);
19753 /* program is valid, convert *(u32*)(ctx + off) accesses */
19754 ret = convert_ctx_accesses(env);
19757 ret = do_misc_fixups(env);
19759 /* do 32-bit optimization after insn patching has done so those patched
19760 * insns could be handled correctly.
19762 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19763 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19764 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19769 ret = fixup_call_args(env);
19771 env->verification_time = ktime_get_ns() - start_time;
19772 print_verification_stats(env);
19773 env->prog->aux->verified_insns = env->insn_processed;
19775 /* preserve original error even if log finalization is successful */
19776 err = bpf_vlog_finalize(&env->log, &log_true_size);
19780 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19781 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19782 &log_true_size, sizeof(log_true_size))) {
19784 goto err_release_maps;
19788 goto err_release_maps;
19790 if (env->used_map_cnt) {
19791 /* if program passed verifier, update used_maps in bpf_prog_info */
19792 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19793 sizeof(env->used_maps[0]),
19796 if (!env->prog->aux->used_maps) {
19798 goto err_release_maps;
19801 memcpy(env->prog->aux->used_maps, env->used_maps,
19802 sizeof(env->used_maps[0]) * env->used_map_cnt);
19803 env->prog->aux->used_map_cnt = env->used_map_cnt;
19805 if (env->used_btf_cnt) {
19806 /* if program passed verifier, update used_btfs in bpf_prog_aux */
19807 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19808 sizeof(env->used_btfs[0]),
19810 if (!env->prog->aux->used_btfs) {
19812 goto err_release_maps;
19815 memcpy(env->prog->aux->used_btfs, env->used_btfs,
19816 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19817 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19819 if (env->used_map_cnt || env->used_btf_cnt) {
19820 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
19821 * bpf_ld_imm64 instructions
19823 convert_pseudo_ld_imm64(env);
19826 adjust_btf_func(env);
19829 if (!env->prog->aux->used_maps)
19830 /* if we didn't copy map pointers into bpf_prog_info, release
19831 * them now. Otherwise free_used_maps() will release them.
19834 if (!env->prog->aux->used_btfs)
19837 /* extension progs temporarily inherit the attach_type of their targets
19838 for verification purposes, so set it back to zero before returning
19840 if (env->prog->type == BPF_PROG_TYPE_EXT)
19841 env->prog->expected_attach_type = 0;
19846 mutex_unlock(&bpf_verifier_lock);
19847 vfree(env->insn_aux_data);