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) {
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 bool is_trusted_reg(const struct bpf_reg_state *reg)
5418 /* A referenced register is always trusted. */
5419 if (reg->ref_obj_id)
5422 /* If a register is not referenced, it is trusted if it has the
5423 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5424 * other type modifiers may be safe, but we elect to take an opt-in
5425 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5428 * Eventually, we should make PTR_TRUSTED the single source of truth
5429 * for whether a register is trusted.
5431 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5432 !bpf_type_has_unsafe_modifiers(reg->type);
5435 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5437 return reg->type & MEM_RCU;
5440 static void clear_trusted_flags(enum bpf_type_flag *flag)
5442 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5445 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5446 const struct bpf_reg_state *reg,
5447 int off, int size, bool strict)
5449 struct tnum reg_off;
5452 /* Byte size accesses are always allowed. */
5453 if (!strict || size == 1)
5456 /* For platforms that do not have a Kconfig enabling
5457 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5458 * NET_IP_ALIGN is universally set to '2'. And on platforms
5459 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5460 * to this code only in strict mode where we want to emulate
5461 * the NET_IP_ALIGN==2 checking. Therefore use an
5462 * unconditional IP align value of '2'.
5466 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5467 if (!tnum_is_aligned(reg_off, size)) {
5470 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5472 "misaligned packet access off %d+%s+%d+%d size %d\n",
5473 ip_align, tn_buf, reg->off, off, size);
5480 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5481 const struct bpf_reg_state *reg,
5482 const char *pointer_desc,
5483 int off, int size, bool strict)
5485 struct tnum reg_off;
5487 /* Byte size accesses are always allowed. */
5488 if (!strict || size == 1)
5491 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5492 if (!tnum_is_aligned(reg_off, size)) {
5495 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5496 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5497 pointer_desc, tn_buf, reg->off, off, size);
5504 static int check_ptr_alignment(struct bpf_verifier_env *env,
5505 const struct bpf_reg_state *reg, int off,
5506 int size, bool strict_alignment_once)
5508 bool strict = env->strict_alignment || strict_alignment_once;
5509 const char *pointer_desc = "";
5511 switch (reg->type) {
5513 case PTR_TO_PACKET_META:
5514 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5515 * right in front, treat it the very same way.
5517 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5518 case PTR_TO_FLOW_KEYS:
5519 pointer_desc = "flow keys ";
5521 case PTR_TO_MAP_KEY:
5522 pointer_desc = "key ";
5524 case PTR_TO_MAP_VALUE:
5525 pointer_desc = "value ";
5528 pointer_desc = "context ";
5531 pointer_desc = "stack ";
5532 /* The stack spill tracking logic in check_stack_write_fixed_off()
5533 * and check_stack_read_fixed_off() relies on stack accesses being
5539 pointer_desc = "sock ";
5541 case PTR_TO_SOCK_COMMON:
5542 pointer_desc = "sock_common ";
5544 case PTR_TO_TCP_SOCK:
5545 pointer_desc = "tcp_sock ";
5547 case PTR_TO_XDP_SOCK:
5548 pointer_desc = "xdp_sock ";
5553 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5557 static int update_stack_depth(struct bpf_verifier_env *env,
5558 const struct bpf_func_state *func,
5561 u16 stack = env->subprog_info[func->subprogno].stack_depth;
5566 /* update known max for given subprogram */
5567 env->subprog_info[func->subprogno].stack_depth = -off;
5571 /* starting from main bpf function walk all instructions of the function
5572 * and recursively walk all callees that given function can call.
5573 * Ignore jump and exit insns.
5574 * Since recursion is prevented by check_cfg() this algorithm
5575 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5577 static int check_max_stack_depth(struct bpf_verifier_env *env)
5579 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
5580 struct bpf_subprog_info *subprog = env->subprog_info;
5581 struct bpf_insn *insn = env->prog->insnsi;
5582 bool tail_call_reachable = false;
5583 int ret_insn[MAX_CALL_FRAMES];
5584 int ret_prog[MAX_CALL_FRAMES];
5588 /* protect against potential stack overflow that might happen when
5589 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5590 * depth for such case down to 256 so that the worst case scenario
5591 * would result in 8k stack size (32 which is tailcall limit * 256 =
5594 * To get the idea what might happen, see an example:
5595 * func1 -> sub rsp, 128
5596 * subfunc1 -> sub rsp, 256
5597 * tailcall1 -> add rsp, 256
5598 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5599 * subfunc2 -> sub rsp, 64
5600 * subfunc22 -> sub rsp, 128
5601 * tailcall2 -> add rsp, 128
5602 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5604 * tailcall will unwind the current stack frame but it will not get rid
5605 * of caller's stack as shown on the example above.
5607 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5609 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5613 /* round up to 32-bytes, since this is granularity
5614 * of interpreter stack size
5616 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5617 if (depth > MAX_BPF_STACK) {
5618 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5623 subprog_end = subprog[idx + 1].start;
5624 for (; i < subprog_end; i++) {
5627 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5629 /* remember insn and function to return to */
5630 ret_insn[frame] = i + 1;
5631 ret_prog[frame] = idx;
5633 /* find the callee */
5634 next_insn = i + insn[i].imm + 1;
5635 idx = find_subprog(env, next_insn);
5637 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5641 if (subprog[idx].is_async_cb) {
5642 if (subprog[idx].has_tail_call) {
5643 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5646 /* async callbacks don't increase bpf prog stack size unless called directly */
5647 if (!bpf_pseudo_call(insn + i))
5652 if (subprog[idx].has_tail_call)
5653 tail_call_reachable = true;
5656 if (frame >= MAX_CALL_FRAMES) {
5657 verbose(env, "the call stack of %d frames is too deep !\n",
5663 /* if tail call got detected across bpf2bpf calls then mark each of the
5664 * currently present subprog frames as tail call reachable subprogs;
5665 * this info will be utilized by JIT so that we will be preserving the
5666 * tail call counter throughout bpf2bpf calls combined with tailcalls
5668 if (tail_call_reachable)
5669 for (j = 0; j < frame; j++)
5670 subprog[ret_prog[j]].tail_call_reachable = true;
5671 if (subprog[0].tail_call_reachable)
5672 env->prog->aux->tail_call_reachable = true;
5674 /* end of for() loop means the last insn of the 'subprog'
5675 * was reached. Doesn't matter whether it was JA or EXIT
5679 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5681 i = ret_insn[frame];
5682 idx = ret_prog[frame];
5686 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5687 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5688 const struct bpf_insn *insn, int idx)
5690 int start = idx + insn->imm + 1, subprog;
5692 subprog = find_subprog(env, start);
5694 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5698 return env->subprog_info[subprog].stack_depth;
5702 static int __check_buffer_access(struct bpf_verifier_env *env,
5703 const char *buf_info,
5704 const struct bpf_reg_state *reg,
5705 int regno, int off, int size)
5709 "R%d invalid %s buffer access: off=%d, size=%d\n",
5710 regno, buf_info, off, size);
5713 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5716 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5718 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5719 regno, off, tn_buf);
5726 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5727 const struct bpf_reg_state *reg,
5728 int regno, int off, int size)
5732 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5736 if (off + size > env->prog->aux->max_tp_access)
5737 env->prog->aux->max_tp_access = off + size;
5742 static int check_buffer_access(struct bpf_verifier_env *env,
5743 const struct bpf_reg_state *reg,
5744 int regno, int off, int size,
5745 bool zero_size_allowed,
5748 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5751 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5755 if (off + size > *max_access)
5756 *max_access = off + size;
5761 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5762 static void zext_32_to_64(struct bpf_reg_state *reg)
5764 reg->var_off = tnum_subreg(reg->var_off);
5765 __reg_assign_32_into_64(reg);
5768 /* truncate register to smaller size (in bytes)
5769 * must be called with size < BPF_REG_SIZE
5771 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5775 /* clear high bits in bit representation */
5776 reg->var_off = tnum_cast(reg->var_off, size);
5778 /* fix arithmetic bounds */
5779 mask = ((u64)1 << (size * 8)) - 1;
5780 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5781 reg->umin_value &= mask;
5782 reg->umax_value &= mask;
5784 reg->umin_value = 0;
5785 reg->umax_value = mask;
5787 reg->smin_value = reg->umin_value;
5788 reg->smax_value = reg->umax_value;
5790 /* If size is smaller than 32bit register the 32bit register
5791 * values are also truncated so we push 64-bit bounds into
5792 * 32-bit bounds. Above were truncated < 32-bits already.
5796 __reg_combine_64_into_32(reg);
5799 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5801 /* A map is considered read-only if the following condition are true:
5803 * 1) BPF program side cannot change any of the map content. The
5804 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5805 * and was set at map creation time.
5806 * 2) The map value(s) have been initialized from user space by a
5807 * loader and then "frozen", such that no new map update/delete
5808 * operations from syscall side are possible for the rest of
5809 * the map's lifetime from that point onwards.
5810 * 3) Any parallel/pending map update/delete operations from syscall
5811 * side have been completed. Only after that point, it's safe to
5812 * assume that map value(s) are immutable.
5814 return (map->map_flags & BPF_F_RDONLY_PROG) &&
5815 READ_ONCE(map->frozen) &&
5816 !bpf_map_write_active(map);
5819 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
5825 err = map->ops->map_direct_value_addr(map, &addr, off);
5828 ptr = (void *)(long)addr + off;
5832 *val = (u64)*(u8 *)ptr;
5835 *val = (u64)*(u16 *)ptr;
5838 *val = (u64)*(u32 *)ptr;
5849 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
5850 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
5851 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
5854 * Allow list few fields as RCU trusted or full trusted.
5855 * This logic doesn't allow mix tagging and will be removed once GCC supports
5859 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5860 BTF_TYPE_SAFE_RCU(struct task_struct) {
5861 const cpumask_t *cpus_ptr;
5862 struct css_set __rcu *cgroups;
5863 struct task_struct __rcu *real_parent;
5864 struct task_struct *group_leader;
5867 BTF_TYPE_SAFE_RCU(struct cgroup) {
5868 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
5869 struct kernfs_node *kn;
5872 BTF_TYPE_SAFE_RCU(struct css_set) {
5873 struct cgroup *dfl_cgrp;
5876 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
5877 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
5878 struct file __rcu *exe_file;
5881 /* skb->sk, req->sk are not RCU protected, but we mark them as such
5882 * because bpf prog accessible sockets are SOCK_RCU_FREE.
5884 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
5888 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
5892 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5893 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5894 struct seq_file *seq;
5897 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5898 struct bpf_iter_meta *meta;
5899 struct task_struct *task;
5902 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5906 BTF_TYPE_SAFE_TRUSTED(struct file) {
5907 struct inode *f_inode;
5910 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
5911 /* no negative dentry-s in places where bpf can see it */
5912 struct inode *d_inode;
5915 BTF_TYPE_SAFE_TRUSTED(struct socket) {
5919 static bool type_is_rcu(struct bpf_verifier_env *env,
5920 struct bpf_reg_state *reg,
5921 const char *field_name, u32 btf_id)
5923 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5924 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
5925 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5927 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
5930 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
5931 struct bpf_reg_state *reg,
5932 const char *field_name, u32 btf_id)
5934 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
5935 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
5936 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
5938 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
5941 static bool type_is_trusted(struct bpf_verifier_env *env,
5942 struct bpf_reg_state *reg,
5943 const char *field_name, u32 btf_id)
5945 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5946 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5947 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5948 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5949 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
5950 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
5952 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
5955 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5956 struct bpf_reg_state *regs,
5957 int regno, int off, int size,
5958 enum bpf_access_type atype,
5961 struct bpf_reg_state *reg = regs + regno;
5962 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5963 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5964 const char *field_name = NULL;
5965 enum bpf_type_flag flag = 0;
5969 if (!env->allow_ptr_leaks) {
5971 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5975 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5977 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5983 "R%d is ptr_%s invalid negative access: off=%d\n",
5987 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5990 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5992 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5993 regno, tname, off, tn_buf);
5997 if (reg->type & MEM_USER) {
5999 "R%d is ptr_%s access user memory: off=%d\n",
6004 if (reg->type & MEM_PERCPU) {
6006 "R%d is ptr_%s access percpu memory: off=%d\n",
6011 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6012 if (!btf_is_kernel(reg->btf)) {
6013 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6016 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6018 /* Writes are permitted with default btf_struct_access for
6019 * program allocated objects (which always have ref_obj_id > 0),
6020 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6022 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6023 verbose(env, "only read is supported\n");
6027 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6029 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6033 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6039 if (ret != PTR_TO_BTF_ID) {
6042 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6043 /* If this is an untrusted pointer, all pointers formed by walking it
6044 * also inherit the untrusted flag.
6046 flag = PTR_UNTRUSTED;
6048 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6049 /* By default any pointer obtained from walking a trusted pointer is no
6050 * longer trusted, unless the field being accessed has explicitly been
6051 * marked as inheriting its parent's state of trust (either full or RCU).
6053 * 'cgroups' pointer is untrusted if task->cgroups dereference
6054 * happened in a sleepable program outside of bpf_rcu_read_lock()
6055 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6056 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6058 * A regular RCU-protected pointer with __rcu tag can also be deemed
6059 * trusted if we are in an RCU CS. Such pointer can be NULL.
6061 if (type_is_trusted(env, reg, field_name, btf_id)) {
6062 flag |= PTR_TRUSTED;
6063 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6064 if (type_is_rcu(env, reg, field_name, btf_id)) {
6065 /* ignore __rcu tag and mark it MEM_RCU */
6067 } else if (flag & MEM_RCU ||
6068 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6069 /* __rcu tagged pointers can be NULL */
6070 flag |= MEM_RCU | PTR_MAYBE_NULL;
6072 /* We always trust them */
6073 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6074 flag & PTR_UNTRUSTED)
6075 flag &= ~PTR_UNTRUSTED;
6076 } else if (flag & (MEM_PERCPU | MEM_USER)) {
6079 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6080 clear_trusted_flags(&flag);
6084 * If not in RCU CS or MEM_RCU pointer can be NULL then
6085 * aggressively mark as untrusted otherwise such
6086 * pointers will be plain PTR_TO_BTF_ID without flags
6087 * and will be allowed to be passed into helpers for
6090 flag = PTR_UNTRUSTED;
6093 /* Old compat. Deprecated */
6094 clear_trusted_flags(&flag);
6097 if (atype == BPF_READ && value_regno >= 0)
6098 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6103 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6104 struct bpf_reg_state *regs,
6105 int regno, int off, int size,
6106 enum bpf_access_type atype,
6109 struct bpf_reg_state *reg = regs + regno;
6110 struct bpf_map *map = reg->map_ptr;
6111 struct bpf_reg_state map_reg;
6112 enum bpf_type_flag flag = 0;
6113 const struct btf_type *t;
6119 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6123 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6124 verbose(env, "map_ptr access not supported for map type %d\n",
6129 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6130 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6132 if (!env->allow_ptr_leaks) {
6134 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6140 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6145 if (atype != BPF_READ) {
6146 verbose(env, "only read from %s is supported\n", tname);
6150 /* Simulate access to a PTR_TO_BTF_ID */
6151 memset(&map_reg, 0, sizeof(map_reg));
6152 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6153 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6157 if (value_regno >= 0)
6158 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6163 /* Check that the stack access at the given offset is within bounds. The
6164 * maximum valid offset is -1.
6166 * The minimum valid offset is -MAX_BPF_STACK for writes, and
6167 * -state->allocated_stack for reads.
6169 static int check_stack_slot_within_bounds(int off,
6170 struct bpf_func_state *state,
6171 enum bpf_access_type t)
6176 min_valid_off = -MAX_BPF_STACK;
6178 min_valid_off = -state->allocated_stack;
6180 if (off < min_valid_off || off > -1)
6185 /* Check that the stack access at 'regno + off' falls within the maximum stack
6188 * 'off' includes `regno->offset`, but not its dynamic part (if any).
6190 static int check_stack_access_within_bounds(
6191 struct bpf_verifier_env *env,
6192 int regno, int off, int access_size,
6193 enum bpf_access_src src, enum bpf_access_type type)
6195 struct bpf_reg_state *regs = cur_regs(env);
6196 struct bpf_reg_state *reg = regs + regno;
6197 struct bpf_func_state *state = func(env, reg);
6198 int min_off, max_off;
6202 if (src == ACCESS_HELPER)
6203 /* We don't know if helpers are reading or writing (or both). */
6204 err_extra = " indirect access to";
6205 else if (type == BPF_READ)
6206 err_extra = " read from";
6208 err_extra = " write to";
6210 if (tnum_is_const(reg->var_off)) {
6211 min_off = reg->var_off.value + off;
6212 if (access_size > 0)
6213 max_off = min_off + access_size - 1;
6217 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6218 reg->smin_value <= -BPF_MAX_VAR_OFF) {
6219 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6223 min_off = reg->smin_value + off;
6224 if (access_size > 0)
6225 max_off = reg->smax_value + off + access_size - 1;
6230 err = check_stack_slot_within_bounds(min_off, state, type);
6232 err = check_stack_slot_within_bounds(max_off, state, type);
6235 if (tnum_is_const(reg->var_off)) {
6236 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6237 err_extra, regno, off, access_size);
6241 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6242 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6243 err_extra, regno, tn_buf, access_size);
6249 /* check whether memory at (regno + off) is accessible for t = (read | write)
6250 * if t==write, value_regno is a register which value is stored into memory
6251 * if t==read, value_regno is a register which will receive the value from memory
6252 * if t==write && value_regno==-1, some unknown value is stored into memory
6253 * if t==read && value_regno==-1, don't care what we read from memory
6255 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6256 int off, int bpf_size, enum bpf_access_type t,
6257 int value_regno, bool strict_alignment_once)
6259 struct bpf_reg_state *regs = cur_regs(env);
6260 struct bpf_reg_state *reg = regs + regno;
6261 struct bpf_func_state *state;
6264 size = bpf_size_to_bytes(bpf_size);
6268 /* alignment checks will add in reg->off themselves */
6269 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6273 /* for access checks, reg->off is just part of off */
6276 if (reg->type == PTR_TO_MAP_KEY) {
6277 if (t == BPF_WRITE) {
6278 verbose(env, "write to change key R%d not allowed\n", regno);
6282 err = check_mem_region_access(env, regno, off, size,
6283 reg->map_ptr->key_size, false);
6286 if (value_regno >= 0)
6287 mark_reg_unknown(env, regs, value_regno);
6288 } else if (reg->type == PTR_TO_MAP_VALUE) {
6289 struct btf_field *kptr_field = NULL;
6291 if (t == BPF_WRITE && value_regno >= 0 &&
6292 is_pointer_value(env, value_regno)) {
6293 verbose(env, "R%d leaks addr into map\n", value_regno);
6296 err = check_map_access_type(env, regno, off, size, t);
6299 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6302 if (tnum_is_const(reg->var_off))
6303 kptr_field = btf_record_find(reg->map_ptr->record,
6304 off + reg->var_off.value, BPF_KPTR);
6306 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6307 } else if (t == BPF_READ && value_regno >= 0) {
6308 struct bpf_map *map = reg->map_ptr;
6310 /* if map is read-only, track its contents as scalars */
6311 if (tnum_is_const(reg->var_off) &&
6312 bpf_map_is_rdonly(map) &&
6313 map->ops->map_direct_value_addr) {
6314 int map_off = off + reg->var_off.value;
6317 err = bpf_map_direct_read(map, map_off, size,
6322 regs[value_regno].type = SCALAR_VALUE;
6323 __mark_reg_known(®s[value_regno], val);
6325 mark_reg_unknown(env, regs, value_regno);
6328 } else if (base_type(reg->type) == PTR_TO_MEM) {
6329 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6331 if (type_may_be_null(reg->type)) {
6332 verbose(env, "R%d invalid mem access '%s'\n", regno,
6333 reg_type_str(env, reg->type));
6337 if (t == BPF_WRITE && rdonly_mem) {
6338 verbose(env, "R%d cannot write into %s\n",
6339 regno, reg_type_str(env, reg->type));
6343 if (t == BPF_WRITE && value_regno >= 0 &&
6344 is_pointer_value(env, value_regno)) {
6345 verbose(env, "R%d leaks addr into mem\n", value_regno);
6349 err = check_mem_region_access(env, regno, off, size,
6350 reg->mem_size, false);
6351 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6352 mark_reg_unknown(env, regs, value_regno);
6353 } else if (reg->type == PTR_TO_CTX) {
6354 enum bpf_reg_type reg_type = SCALAR_VALUE;
6355 struct btf *btf = NULL;
6358 if (t == BPF_WRITE && value_regno >= 0 &&
6359 is_pointer_value(env, value_regno)) {
6360 verbose(env, "R%d leaks addr into ctx\n", value_regno);
6364 err = check_ptr_off_reg(env, reg, regno);
6368 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
6371 verbose_linfo(env, insn_idx, "; ");
6372 if (!err && t == BPF_READ && value_regno >= 0) {
6373 /* ctx access returns either a scalar, or a
6374 * PTR_TO_PACKET[_META,_END]. In the latter
6375 * case, we know the offset is zero.
6377 if (reg_type == SCALAR_VALUE) {
6378 mark_reg_unknown(env, regs, value_regno);
6380 mark_reg_known_zero(env, regs,
6382 if (type_may_be_null(reg_type))
6383 regs[value_regno].id = ++env->id_gen;
6384 /* A load of ctx field could have different
6385 * actual load size with the one encoded in the
6386 * insn. When the dst is PTR, it is for sure not
6389 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6390 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6391 regs[value_regno].btf = btf;
6392 regs[value_regno].btf_id = btf_id;
6395 regs[value_regno].type = reg_type;
6398 } else if (reg->type == PTR_TO_STACK) {
6399 /* Basic bounds checks. */
6400 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6404 state = func(env, reg);
6405 err = update_stack_depth(env, state, off);
6410 err = check_stack_read(env, regno, off, size,
6413 err = check_stack_write(env, regno, off, size,
6414 value_regno, insn_idx);
6415 } else if (reg_is_pkt_pointer(reg)) {
6416 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6417 verbose(env, "cannot write into packet\n");
6420 if (t == BPF_WRITE && value_regno >= 0 &&
6421 is_pointer_value(env, value_regno)) {
6422 verbose(env, "R%d leaks addr into packet\n",
6426 err = check_packet_access(env, regno, off, size, false);
6427 if (!err && t == BPF_READ && value_regno >= 0)
6428 mark_reg_unknown(env, regs, value_regno);
6429 } else if (reg->type == PTR_TO_FLOW_KEYS) {
6430 if (t == BPF_WRITE && value_regno >= 0 &&
6431 is_pointer_value(env, value_regno)) {
6432 verbose(env, "R%d leaks addr into flow keys\n",
6437 err = check_flow_keys_access(env, off, size);
6438 if (!err && t == BPF_READ && value_regno >= 0)
6439 mark_reg_unknown(env, regs, value_regno);
6440 } else if (type_is_sk_pointer(reg->type)) {
6441 if (t == BPF_WRITE) {
6442 verbose(env, "R%d cannot write into %s\n",
6443 regno, reg_type_str(env, reg->type));
6446 err = check_sock_access(env, insn_idx, regno, off, size, t);
6447 if (!err && value_regno >= 0)
6448 mark_reg_unknown(env, regs, value_regno);
6449 } else if (reg->type == PTR_TO_TP_BUFFER) {
6450 err = check_tp_buffer_access(env, reg, regno, off, size);
6451 if (!err && t == BPF_READ && value_regno >= 0)
6452 mark_reg_unknown(env, regs, value_regno);
6453 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6454 !type_may_be_null(reg->type)) {
6455 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6457 } else if (reg->type == CONST_PTR_TO_MAP) {
6458 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6460 } else if (base_type(reg->type) == PTR_TO_BUF) {
6461 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6465 if (t == BPF_WRITE) {
6466 verbose(env, "R%d cannot write into %s\n",
6467 regno, reg_type_str(env, reg->type));
6470 max_access = &env->prog->aux->max_rdonly_access;
6472 max_access = &env->prog->aux->max_rdwr_access;
6475 err = check_buffer_access(env, reg, regno, off, size, false,
6478 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6479 mark_reg_unknown(env, regs, value_regno);
6481 verbose(env, "R%d invalid mem access '%s'\n", regno,
6482 reg_type_str(env, reg->type));
6486 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6487 regs[value_regno].type == SCALAR_VALUE) {
6488 /* b/h/w load zero-extends, mark upper bits as known 0 */
6489 coerce_reg_to_size(®s[value_regno], size);
6494 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6499 switch (insn->imm) {
6501 case BPF_ADD | BPF_FETCH:
6503 case BPF_AND | BPF_FETCH:
6505 case BPF_OR | BPF_FETCH:
6507 case BPF_XOR | BPF_FETCH:
6512 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6516 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6517 verbose(env, "invalid atomic operand size\n");
6521 /* check src1 operand */
6522 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6526 /* check src2 operand */
6527 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6531 if (insn->imm == BPF_CMPXCHG) {
6532 /* Check comparison of R0 with memory location */
6533 const u32 aux_reg = BPF_REG_0;
6535 err = check_reg_arg(env, aux_reg, SRC_OP);
6539 if (is_pointer_value(env, aux_reg)) {
6540 verbose(env, "R%d leaks addr into mem\n", aux_reg);
6545 if (is_pointer_value(env, insn->src_reg)) {
6546 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6550 if (is_ctx_reg(env, insn->dst_reg) ||
6551 is_pkt_reg(env, insn->dst_reg) ||
6552 is_flow_key_reg(env, insn->dst_reg) ||
6553 is_sk_reg(env, insn->dst_reg)) {
6554 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6556 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6560 if (insn->imm & BPF_FETCH) {
6561 if (insn->imm == BPF_CMPXCHG)
6562 load_reg = BPF_REG_0;
6564 load_reg = insn->src_reg;
6566 /* check and record load of old value */
6567 err = check_reg_arg(env, load_reg, DST_OP);
6571 /* This instruction accesses a memory location but doesn't
6572 * actually load it into a register.
6577 /* Check whether we can read the memory, with second call for fetch
6578 * case to simulate the register fill.
6580 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6581 BPF_SIZE(insn->code), BPF_READ, -1, true);
6582 if (!err && load_reg >= 0)
6583 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6584 BPF_SIZE(insn->code), BPF_READ, load_reg,
6589 /* Check whether we can write into the same memory. */
6590 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6591 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
6598 /* When register 'regno' is used to read the stack (either directly or through
6599 * a helper function) make sure that it's within stack boundary and, depending
6600 * on the access type, that all elements of the stack are initialized.
6602 * 'off' includes 'regno->off', but not its dynamic part (if any).
6604 * All registers that have been spilled on the stack in the slots within the
6605 * read offsets are marked as read.
6607 static int check_stack_range_initialized(
6608 struct bpf_verifier_env *env, int regno, int off,
6609 int access_size, bool zero_size_allowed,
6610 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6612 struct bpf_reg_state *reg = reg_state(env, regno);
6613 struct bpf_func_state *state = func(env, reg);
6614 int err, min_off, max_off, i, j, slot, spi;
6615 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6616 enum bpf_access_type bounds_check_type;
6617 /* Some accesses can write anything into the stack, others are
6620 bool clobber = false;
6622 if (access_size == 0 && !zero_size_allowed) {
6623 verbose(env, "invalid zero-sized read\n");
6627 if (type == ACCESS_HELPER) {
6628 /* The bounds checks for writes are more permissive than for
6629 * reads. However, if raw_mode is not set, we'll do extra
6632 bounds_check_type = BPF_WRITE;
6635 bounds_check_type = BPF_READ;
6637 err = check_stack_access_within_bounds(env, regno, off, access_size,
6638 type, bounds_check_type);
6643 if (tnum_is_const(reg->var_off)) {
6644 min_off = max_off = reg->var_off.value + off;
6646 /* Variable offset is prohibited for unprivileged mode for
6647 * simplicity since it requires corresponding support in
6648 * Spectre masking for stack ALU.
6649 * See also retrieve_ptr_limit().
6651 if (!env->bypass_spec_v1) {
6654 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6655 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6656 regno, err_extra, tn_buf);
6659 /* Only initialized buffer on stack is allowed to be accessed
6660 * with variable offset. With uninitialized buffer it's hard to
6661 * guarantee that whole memory is marked as initialized on
6662 * helper return since specific bounds are unknown what may
6663 * cause uninitialized stack leaking.
6665 if (meta && meta->raw_mode)
6668 min_off = reg->smin_value + off;
6669 max_off = reg->smax_value + off;
6672 if (meta && meta->raw_mode) {
6673 /* Ensure we won't be overwriting dynptrs when simulating byte
6674 * by byte access in check_helper_call using meta.access_size.
6675 * This would be a problem if we have a helper in the future
6678 * helper(uninit_mem, len, dynptr)
6680 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6681 * may end up writing to dynptr itself when touching memory from
6682 * arg 1. This can be relaxed on a case by case basis for known
6683 * safe cases, but reject due to the possibilitiy of aliasing by
6686 for (i = min_off; i < max_off + access_size; i++) {
6687 int stack_off = -i - 1;
6690 /* raw_mode may write past allocated_stack */
6691 if (state->allocated_stack <= stack_off)
6693 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6694 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6698 meta->access_size = access_size;
6699 meta->regno = regno;
6703 for (i = min_off; i < max_off + access_size; i++) {
6707 spi = slot / BPF_REG_SIZE;
6708 if (state->allocated_stack <= slot)
6710 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6711 if (*stype == STACK_MISC)
6713 if ((*stype == STACK_ZERO) ||
6714 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6716 /* helper can write anything into the stack */
6717 *stype = STACK_MISC;
6722 if (is_spilled_reg(&state->stack[spi]) &&
6723 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6724 env->allow_ptr_leaks)) {
6726 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6727 for (j = 0; j < BPF_REG_SIZE; j++)
6728 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6734 if (tnum_is_const(reg->var_off)) {
6735 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6736 err_extra, regno, min_off, i - min_off, access_size);
6740 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6741 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6742 err_extra, regno, tn_buf, i - min_off, access_size);
6746 /* reading any byte out of 8-byte 'spill_slot' will cause
6747 * the whole slot to be marked as 'read'
6749 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6750 state->stack[spi].spilled_ptr.parent,
6752 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6753 * be sure that whether stack slot is written to or not. Hence,
6754 * we must still conservatively propagate reads upwards even if
6755 * helper may write to the entire memory range.
6758 return update_stack_depth(env, state, min_off);
6761 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6762 int access_size, bool zero_size_allowed,
6763 struct bpf_call_arg_meta *meta)
6765 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6768 switch (base_type(reg->type)) {
6770 case PTR_TO_PACKET_META:
6771 return check_packet_access(env, regno, reg->off, access_size,
6773 case PTR_TO_MAP_KEY:
6774 if (meta && meta->raw_mode) {
6775 verbose(env, "R%d cannot write into %s\n", regno,
6776 reg_type_str(env, reg->type));
6779 return check_mem_region_access(env, regno, reg->off, access_size,
6780 reg->map_ptr->key_size, false);
6781 case PTR_TO_MAP_VALUE:
6782 if (check_map_access_type(env, regno, reg->off, access_size,
6783 meta && meta->raw_mode ? BPF_WRITE :
6786 return check_map_access(env, regno, reg->off, access_size,
6787 zero_size_allowed, ACCESS_HELPER);
6789 if (type_is_rdonly_mem(reg->type)) {
6790 if (meta && meta->raw_mode) {
6791 verbose(env, "R%d cannot write into %s\n", regno,
6792 reg_type_str(env, reg->type));
6796 return check_mem_region_access(env, regno, reg->off,
6797 access_size, reg->mem_size,
6800 if (type_is_rdonly_mem(reg->type)) {
6801 if (meta && meta->raw_mode) {
6802 verbose(env, "R%d cannot write into %s\n", regno,
6803 reg_type_str(env, reg->type));
6807 max_access = &env->prog->aux->max_rdonly_access;
6809 max_access = &env->prog->aux->max_rdwr_access;
6811 return check_buffer_access(env, reg, regno, reg->off,
6812 access_size, zero_size_allowed,
6815 return check_stack_range_initialized(
6817 regno, reg->off, access_size,
6818 zero_size_allowed, ACCESS_HELPER, meta);
6820 return check_ptr_to_btf_access(env, regs, regno, reg->off,
6821 access_size, BPF_READ, -1);
6823 /* in case the function doesn't know how to access the context,
6824 * (because we are in a program of type SYSCALL for example), we
6825 * can not statically check its size.
6826 * Dynamically check it now.
6828 if (!env->ops->convert_ctx_access) {
6829 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6830 int offset = access_size - 1;
6832 /* Allow zero-byte read from PTR_TO_CTX */
6833 if (access_size == 0)
6834 return zero_size_allowed ? 0 : -EACCES;
6836 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
6841 default: /* scalar_value or invalid ptr */
6842 /* Allow zero-byte read from NULL, regardless of pointer type */
6843 if (zero_size_allowed && access_size == 0 &&
6844 register_is_null(reg))
6847 verbose(env, "R%d type=%s ", regno,
6848 reg_type_str(env, reg->type));
6849 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6854 static int check_mem_size_reg(struct bpf_verifier_env *env,
6855 struct bpf_reg_state *reg, u32 regno,
6856 bool zero_size_allowed,
6857 struct bpf_call_arg_meta *meta)
6861 /* This is used to refine r0 return value bounds for helpers
6862 * that enforce this value as an upper bound on return values.
6863 * See do_refine_retval_range() for helpers that can refine
6864 * the return value. C type of helper is u32 so we pull register
6865 * bound from umax_value however, if negative verifier errors
6866 * out. Only upper bounds can be learned because retval is an
6867 * int type and negative retvals are allowed.
6869 meta->msize_max_value = reg->umax_value;
6871 /* The register is SCALAR_VALUE; the access check
6872 * happens using its boundaries.
6874 if (!tnum_is_const(reg->var_off))
6875 /* For unprivileged variable accesses, disable raw
6876 * mode so that the program is required to
6877 * initialize all the memory that the helper could
6878 * just partially fill up.
6882 if (reg->smin_value < 0) {
6883 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6888 if (reg->umin_value == 0) {
6889 err = check_helper_mem_access(env, regno - 1, 0,
6896 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
6897 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6901 err = check_helper_mem_access(env, regno - 1,
6903 zero_size_allowed, meta);
6905 err = mark_chain_precision(env, regno);
6909 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6910 u32 regno, u32 mem_size)
6912 bool may_be_null = type_may_be_null(reg->type);
6913 struct bpf_reg_state saved_reg;
6914 struct bpf_call_arg_meta meta;
6917 if (register_is_null(reg))
6920 memset(&meta, 0, sizeof(meta));
6921 /* Assuming that the register contains a value check if the memory
6922 * access is safe. Temporarily save and restore the register's state as
6923 * the conversion shouldn't be visible to a caller.
6927 mark_ptr_not_null_reg(reg);
6930 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
6931 /* Check access for BPF_WRITE */
6932 meta.raw_mode = true;
6933 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
6941 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6944 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
6945 bool may_be_null = type_may_be_null(mem_reg->type);
6946 struct bpf_reg_state saved_reg;
6947 struct bpf_call_arg_meta meta;
6950 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
6952 memset(&meta, 0, sizeof(meta));
6955 saved_reg = *mem_reg;
6956 mark_ptr_not_null_reg(mem_reg);
6959 err = check_mem_size_reg(env, reg, regno, true, &meta);
6960 /* Check access for BPF_WRITE */
6961 meta.raw_mode = true;
6962 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6965 *mem_reg = saved_reg;
6969 /* Implementation details:
6970 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6971 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6972 * Two bpf_map_lookups (even with the same key) will have different reg->id.
6973 * Two separate bpf_obj_new will also have different reg->id.
6974 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6975 * clears reg->id after value_or_null->value transition, since the verifier only
6976 * cares about the range of access to valid map value pointer and doesn't care
6977 * about actual address of the map element.
6978 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6979 * reg->id > 0 after value_or_null->value transition. By doing so
6980 * two bpf_map_lookups will be considered two different pointers that
6981 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6982 * returned from bpf_obj_new.
6983 * The verifier allows taking only one bpf_spin_lock at a time to avoid
6985 * Since only one bpf_spin_lock is allowed the checks are simpler than
6986 * reg_is_refcounted() logic. The verifier needs to remember only
6987 * one spin_lock instead of array of acquired_refs.
6988 * cur_state->active_lock remembers which map value element or allocated
6989 * object got locked and clears it after bpf_spin_unlock.
6991 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
6994 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6995 struct bpf_verifier_state *cur = env->cur_state;
6996 bool is_const = tnum_is_const(reg->var_off);
6997 u64 val = reg->var_off.value;
6998 struct bpf_map *map = NULL;
6999 struct btf *btf = NULL;
7000 struct btf_record *rec;
7004 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7008 if (reg->type == PTR_TO_MAP_VALUE) {
7012 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7020 rec = reg_btf_record(reg);
7021 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7022 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7023 map ? map->name : "kptr");
7026 if (rec->spin_lock_off != val + reg->off) {
7027 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7028 val + reg->off, rec->spin_lock_off);
7032 if (cur->active_lock.ptr) {
7034 "Locking two bpf_spin_locks are not allowed\n");
7038 cur->active_lock.ptr = map;
7040 cur->active_lock.ptr = btf;
7041 cur->active_lock.id = reg->id;
7050 if (!cur->active_lock.ptr) {
7051 verbose(env, "bpf_spin_unlock without taking a lock\n");
7054 if (cur->active_lock.ptr != ptr ||
7055 cur->active_lock.id != reg->id) {
7056 verbose(env, "bpf_spin_unlock of different lock\n");
7060 invalidate_non_owning_refs(env);
7062 cur->active_lock.ptr = NULL;
7063 cur->active_lock.id = 0;
7068 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7069 struct bpf_call_arg_meta *meta)
7071 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7072 bool is_const = tnum_is_const(reg->var_off);
7073 struct bpf_map *map = reg->map_ptr;
7074 u64 val = reg->var_off.value;
7078 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7083 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7087 if (!btf_record_has_field(map->record, BPF_TIMER)) {
7088 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7091 if (map->record->timer_off != val + reg->off) {
7092 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7093 val + reg->off, map->record->timer_off);
7096 if (meta->map_ptr) {
7097 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7100 meta->map_uid = reg->map_uid;
7101 meta->map_ptr = map;
7105 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7106 struct bpf_call_arg_meta *meta)
7108 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7109 struct bpf_map *map_ptr = reg->map_ptr;
7110 struct btf_field *kptr_field;
7113 if (!tnum_is_const(reg->var_off)) {
7115 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7119 if (!map_ptr->btf) {
7120 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7124 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7125 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7129 meta->map_ptr = map_ptr;
7130 kptr_off = reg->off + reg->var_off.value;
7131 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7133 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7136 if (kptr_field->type != BPF_KPTR_REF) {
7137 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7140 meta->kptr_field = kptr_field;
7144 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7145 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7147 * In both cases we deal with the first 8 bytes, but need to mark the next 8
7148 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7149 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7151 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7152 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7153 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7154 * mutate the view of the dynptr and also possibly destroy it. In the latter
7155 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7156 * memory that dynptr points to.
7158 * The verifier will keep track both levels of mutation (bpf_dynptr's in
7159 * reg->type and the memory's in reg->dynptr.type), but there is no support for
7160 * readonly dynptr view yet, hence only the first case is tracked and checked.
7162 * This is consistent with how C applies the const modifier to a struct object,
7163 * where the pointer itself inside bpf_dynptr becomes const but not what it
7166 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7167 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7169 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7170 enum bpf_arg_type arg_type, int clone_ref_obj_id)
7172 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7175 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7176 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7178 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7179 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7183 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
7184 * constructing a mutable bpf_dynptr object.
7186 * Currently, this is only possible with PTR_TO_STACK
7187 * pointing to a region of at least 16 bytes which doesn't
7188 * contain an existing bpf_dynptr.
7190 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7191 * mutated or destroyed. However, the memory it points to
7194 * None - Points to a initialized dynptr that can be mutated and
7195 * destroyed, including mutation of the memory it points
7198 if (arg_type & MEM_UNINIT) {
7201 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7202 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7206 /* we write BPF_DW bits (8 bytes) at a time */
7207 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7208 err = check_mem_access(env, insn_idx, regno,
7209 i, BPF_DW, BPF_WRITE, -1, false);
7214 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7215 } else /* MEM_RDONLY and None case from above */ {
7216 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7217 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7218 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7222 if (!is_dynptr_reg_valid_init(env, reg)) {
7224 "Expected an initialized dynptr as arg #%d\n",
7229 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7230 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7232 "Expected a dynptr of type %s as arg #%d\n",
7233 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7237 err = mark_dynptr_read(env, reg);
7242 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7244 struct bpf_func_state *state = func(env, reg);
7246 return state->stack[spi].spilled_ptr.ref_obj_id;
7249 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7251 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7254 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7256 return meta->kfunc_flags & KF_ITER_NEW;
7259 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7261 return meta->kfunc_flags & KF_ITER_NEXT;
7264 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7266 return meta->kfunc_flags & KF_ITER_DESTROY;
7269 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7271 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7272 * kfunc is iter state pointer
7274 return arg == 0 && is_iter_kfunc(meta);
7277 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7278 struct bpf_kfunc_call_arg_meta *meta)
7280 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7281 const struct btf_type *t;
7282 const struct btf_param *arg;
7283 int spi, err, i, nr_slots;
7286 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7287 arg = &btf_params(meta->func_proto)[0];
7288 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
7289 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
7290 nr_slots = t->size / BPF_REG_SIZE;
7292 if (is_iter_new_kfunc(meta)) {
7293 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7294 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7295 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7296 iter_type_str(meta->btf, btf_id), regno);
7300 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7301 err = check_mem_access(env, insn_idx, regno,
7302 i, BPF_DW, BPF_WRITE, -1, false);
7307 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7311 /* iter_next() or iter_destroy() expect initialized iter state*/
7312 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7313 verbose(env, "expected an initialized iter_%s as arg #%d\n",
7314 iter_type_str(meta->btf, btf_id), regno);
7318 spi = iter_get_spi(env, reg, nr_slots);
7322 err = mark_iter_read(env, reg, spi, nr_slots);
7326 /* remember meta->iter info for process_iter_next_call() */
7327 meta->iter.spi = spi;
7328 meta->iter.frameno = reg->frameno;
7329 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7331 if (is_iter_destroy_kfunc(meta)) {
7332 err = unmark_stack_slots_iter(env, reg, nr_slots);
7341 /* process_iter_next_call() is called when verifier gets to iterator's next
7342 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7343 * to it as just "iter_next()" in comments below.
7345 * BPF verifier relies on a crucial contract for any iter_next()
7346 * implementation: it should *eventually* return NULL, and once that happens
7347 * it should keep returning NULL. That is, once iterator exhausts elements to
7348 * iterate, it should never reset or spuriously return new elements.
7350 * With the assumption of such contract, process_iter_next_call() simulates
7351 * a fork in the verifier state to validate loop logic correctness and safety
7352 * without having to simulate infinite amount of iterations.
7354 * In current state, we first assume that iter_next() returned NULL and
7355 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7356 * conditions we should not form an infinite loop and should eventually reach
7359 * Besides that, we also fork current state and enqueue it for later
7360 * verification. In a forked state we keep iterator state as ACTIVE
7361 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7362 * also bump iteration depth to prevent erroneous infinite loop detection
7363 * later on (see iter_active_depths_differ() comment for details). In this
7364 * state we assume that we'll eventually loop back to another iter_next()
7365 * calls (it could be in exactly same location or in some other instruction,
7366 * it doesn't matter, we don't make any unnecessary assumptions about this,
7367 * everything revolves around iterator state in a stack slot, not which
7368 * instruction is calling iter_next()). When that happens, we either will come
7369 * to iter_next() with equivalent state and can conclude that next iteration
7370 * will proceed in exactly the same way as we just verified, so it's safe to
7371 * assume that loop converges. If not, we'll go on another iteration
7372 * simulation with a different input state, until all possible starting states
7373 * are validated or we reach maximum number of instructions limit.
7375 * This way, we will either exhaustively discover all possible input states
7376 * that iterator loop can start with and eventually will converge, or we'll
7377 * effectively regress into bounded loop simulation logic and either reach
7378 * maximum number of instructions if loop is not provably convergent, or there
7379 * is some statically known limit on number of iterations (e.g., if there is
7380 * an explicit `if n > 100 then break;` statement somewhere in the loop).
7382 * One very subtle but very important aspect is that we *always* simulate NULL
7383 * condition first (as the current state) before we simulate non-NULL case.
7384 * This has to do with intricacies of scalar precision tracking. By simulating
7385 * "exit condition" of iter_next() returning NULL first, we make sure all the
7386 * relevant precision marks *that will be set **after** we exit iterator loop*
7387 * are propagated backwards to common parent state of NULL and non-NULL
7388 * branches. Thanks to that, state equivalence checks done later in forked
7389 * state, when reaching iter_next() for ACTIVE iterator, can assume that
7390 * precision marks are finalized and won't change. Because simulating another
7391 * ACTIVE iterator iteration won't change them (because given same input
7392 * states we'll end up with exactly same output states which we are currently
7393 * comparing; and verification after the loop already propagated back what
7394 * needs to be **additionally** tracked as precise). It's subtle, grok
7395 * precision tracking for more intuitive understanding.
7397 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7398 struct bpf_kfunc_call_arg_meta *meta)
7400 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7401 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7402 struct bpf_reg_state *cur_iter, *queued_iter;
7403 int iter_frameno = meta->iter.frameno;
7404 int iter_spi = meta->iter.spi;
7406 BTF_TYPE_EMIT(struct bpf_iter);
7408 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7410 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7411 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7412 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7413 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7417 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7418 /* branch out active iter state */
7419 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7423 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7424 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7425 queued_iter->iter.depth++;
7427 queued_fr = queued_st->frame[queued_st->curframe];
7428 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7431 /* switch to DRAINED state, but keep the depth unchanged */
7432 /* mark current iter state as drained and assume returned NULL */
7433 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7434 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7439 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7441 return type == ARG_CONST_SIZE ||
7442 type == ARG_CONST_SIZE_OR_ZERO;
7445 static bool arg_type_is_release(enum bpf_arg_type type)
7447 return type & OBJ_RELEASE;
7450 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7452 return base_type(type) == ARG_PTR_TO_DYNPTR;
7455 static int int_ptr_type_to_size(enum bpf_arg_type type)
7457 if (type == ARG_PTR_TO_INT)
7459 else if (type == ARG_PTR_TO_LONG)
7465 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7466 const struct bpf_call_arg_meta *meta,
7467 enum bpf_arg_type *arg_type)
7469 if (!meta->map_ptr) {
7470 /* kernel subsystem misconfigured verifier */
7471 verbose(env, "invalid map_ptr to access map->type\n");
7475 switch (meta->map_ptr->map_type) {
7476 case BPF_MAP_TYPE_SOCKMAP:
7477 case BPF_MAP_TYPE_SOCKHASH:
7478 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7479 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7481 verbose(env, "invalid arg_type for sockmap/sockhash\n");
7485 case BPF_MAP_TYPE_BLOOM_FILTER:
7486 if (meta->func_id == BPF_FUNC_map_peek_elem)
7487 *arg_type = ARG_PTR_TO_MAP_VALUE;
7495 struct bpf_reg_types {
7496 const enum bpf_reg_type types[10];
7500 static const struct bpf_reg_types sock_types = {
7510 static const struct bpf_reg_types btf_id_sock_common_types = {
7517 PTR_TO_BTF_ID | PTR_TRUSTED,
7519 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7523 static const struct bpf_reg_types mem_types = {
7531 PTR_TO_MEM | MEM_RINGBUF,
7533 PTR_TO_BTF_ID | PTR_TRUSTED,
7537 static const struct bpf_reg_types int_ptr_types = {
7547 static const struct bpf_reg_types spin_lock_types = {
7550 PTR_TO_BTF_ID | MEM_ALLOC,
7554 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7555 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7556 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7557 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7558 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7559 static const struct bpf_reg_types btf_ptr_types = {
7562 PTR_TO_BTF_ID | PTR_TRUSTED,
7563 PTR_TO_BTF_ID | MEM_RCU,
7566 static const struct bpf_reg_types percpu_btf_ptr_types = {
7568 PTR_TO_BTF_ID | MEM_PERCPU,
7569 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7572 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7573 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7574 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7575 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7576 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7577 static const struct bpf_reg_types dynptr_types = {
7580 CONST_PTR_TO_DYNPTR,
7584 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7585 [ARG_PTR_TO_MAP_KEY] = &mem_types,
7586 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
7587 [ARG_CONST_SIZE] = &scalar_types,
7588 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
7589 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
7590 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
7591 [ARG_PTR_TO_CTX] = &context_types,
7592 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
7594 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
7596 [ARG_PTR_TO_SOCKET] = &fullsock_types,
7597 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
7598 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
7599 [ARG_PTR_TO_MEM] = &mem_types,
7600 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
7601 [ARG_PTR_TO_INT] = &int_ptr_types,
7602 [ARG_PTR_TO_LONG] = &int_ptr_types,
7603 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
7604 [ARG_PTR_TO_FUNC] = &func_ptr_types,
7605 [ARG_PTR_TO_STACK] = &stack_ptr_types,
7606 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
7607 [ARG_PTR_TO_TIMER] = &timer_types,
7608 [ARG_PTR_TO_KPTR] = &kptr_types,
7609 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
7612 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7613 enum bpf_arg_type arg_type,
7614 const u32 *arg_btf_id,
7615 struct bpf_call_arg_meta *meta)
7617 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7618 enum bpf_reg_type expected, type = reg->type;
7619 const struct bpf_reg_types *compatible;
7622 compatible = compatible_reg_types[base_type(arg_type)];
7624 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7628 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7629 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7631 * Same for MAYBE_NULL:
7633 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7634 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7636 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7638 * Therefore we fold these flags depending on the arg_type before comparison.
7640 if (arg_type & MEM_RDONLY)
7641 type &= ~MEM_RDONLY;
7642 if (arg_type & PTR_MAYBE_NULL)
7643 type &= ~PTR_MAYBE_NULL;
7644 if (base_type(arg_type) == ARG_PTR_TO_MEM)
7645 type &= ~DYNPTR_TYPE_FLAG_MASK;
7647 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
7650 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7651 expected = compatible->types[i];
7652 if (expected == NOT_INIT)
7655 if (type == expected)
7659 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7660 for (j = 0; j + 1 < i; j++)
7661 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7662 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7666 if (base_type(reg->type) != PTR_TO_BTF_ID)
7669 if (compatible == &mem_types) {
7670 if (!(arg_type & MEM_RDONLY)) {
7672 "%s() may write into memory pointed by R%d type=%s\n",
7673 func_id_name(meta->func_id),
7674 regno, reg_type_str(env, reg->type));
7680 switch ((int)reg->type) {
7682 case PTR_TO_BTF_ID | PTR_TRUSTED:
7683 case PTR_TO_BTF_ID | MEM_RCU:
7684 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7685 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7687 /* For bpf_sk_release, it needs to match against first member
7688 * 'struct sock_common', hence make an exception for it. This
7689 * allows bpf_sk_release to work for multiple socket types.
7691 bool strict_type_match = arg_type_is_release(arg_type) &&
7692 meta->func_id != BPF_FUNC_sk_release;
7694 if (type_may_be_null(reg->type) &&
7695 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7696 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7701 if (!compatible->btf_id) {
7702 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7705 arg_btf_id = compatible->btf_id;
7708 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7709 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7712 if (arg_btf_id == BPF_PTR_POISON) {
7713 verbose(env, "verifier internal error:");
7714 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7719 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7720 btf_vmlinux, *arg_btf_id,
7721 strict_type_match)) {
7722 verbose(env, "R%d is of type %s but %s is expected\n",
7723 regno, btf_type_name(reg->btf, reg->btf_id),
7724 btf_type_name(btf_vmlinux, *arg_btf_id));
7730 case PTR_TO_BTF_ID | MEM_ALLOC:
7731 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7732 meta->func_id != BPF_FUNC_kptr_xchg) {
7733 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7736 /* Handled by helper specific checks */
7738 case PTR_TO_BTF_ID | MEM_PERCPU:
7739 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7740 /* Handled by helper specific checks */
7743 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7749 static struct btf_field *
7750 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7752 struct btf_field *field;
7753 struct btf_record *rec;
7755 rec = reg_btf_record(reg);
7759 field = btf_record_find(rec, off, fields);
7766 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7767 const struct bpf_reg_state *reg, int regno,
7768 enum bpf_arg_type arg_type)
7770 u32 type = reg->type;
7772 /* When referenced register is passed to release function, its fixed
7775 * We will check arg_type_is_release reg has ref_obj_id when storing
7776 * meta->release_regno.
7778 if (arg_type_is_release(arg_type)) {
7779 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7780 * may not directly point to the object being released, but to
7781 * dynptr pointing to such object, which might be at some offset
7782 * on the stack. In that case, we simply to fallback to the
7785 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7788 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7789 if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7790 return __check_ptr_off_reg(env, reg, regno, true);
7792 verbose(env, "R%d must have zero offset when passed to release func\n",
7794 verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7795 btf_type_name(reg->btf, reg->btf_id), reg->off);
7799 /* Doing check_ptr_off_reg check for the offset will catch this
7800 * because fixed_off_ok is false, but checking here allows us
7801 * to give the user a better error message.
7804 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7808 return __check_ptr_off_reg(env, reg, regno, false);
7812 /* Pointer types where both fixed and variable offset is explicitly allowed: */
7815 case PTR_TO_PACKET_META:
7816 case PTR_TO_MAP_KEY:
7817 case PTR_TO_MAP_VALUE:
7819 case PTR_TO_MEM | MEM_RDONLY:
7820 case PTR_TO_MEM | MEM_RINGBUF:
7822 case PTR_TO_BUF | MEM_RDONLY:
7825 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
7829 case PTR_TO_BTF_ID | MEM_ALLOC:
7830 case PTR_TO_BTF_ID | PTR_TRUSTED:
7831 case PTR_TO_BTF_ID | MEM_RCU:
7832 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
7833 /* When referenced PTR_TO_BTF_ID is passed to release function,
7834 * its fixed offset must be 0. In the other cases, fixed offset
7835 * can be non-zero. This was already checked above. So pass
7836 * fixed_off_ok as true to allow fixed offset for all other
7837 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
7838 * still need to do checks instead of returning.
7840 return __check_ptr_off_reg(env, reg, regno, true);
7842 return __check_ptr_off_reg(env, reg, regno, false);
7846 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
7847 const struct bpf_func_proto *fn,
7848 struct bpf_reg_state *regs)
7850 struct bpf_reg_state *state = NULL;
7853 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
7854 if (arg_type_is_dynptr(fn->arg_type[i])) {
7856 verbose(env, "verifier internal error: multiple dynptr args\n");
7859 state = ®s[BPF_REG_1 + i];
7863 verbose(env, "verifier internal error: no dynptr arg found\n");
7868 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7870 struct bpf_func_state *state = func(env, reg);
7873 if (reg->type == CONST_PTR_TO_DYNPTR)
7875 spi = dynptr_get_spi(env, reg);
7878 return state->stack[spi].spilled_ptr.id;
7881 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7883 struct bpf_func_state *state = func(env, reg);
7886 if (reg->type == CONST_PTR_TO_DYNPTR)
7887 return reg->ref_obj_id;
7888 spi = dynptr_get_spi(env, reg);
7891 return state->stack[spi].spilled_ptr.ref_obj_id;
7894 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
7895 struct bpf_reg_state *reg)
7897 struct bpf_func_state *state = func(env, reg);
7900 if (reg->type == CONST_PTR_TO_DYNPTR)
7901 return reg->dynptr.type;
7903 spi = __get_spi(reg->off);
7905 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
7906 return BPF_DYNPTR_TYPE_INVALID;
7909 return state->stack[spi].spilled_ptr.dynptr.type;
7912 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
7913 struct bpf_call_arg_meta *meta,
7914 const struct bpf_func_proto *fn,
7917 u32 regno = BPF_REG_1 + arg;
7918 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7919 enum bpf_arg_type arg_type = fn->arg_type[arg];
7920 enum bpf_reg_type type = reg->type;
7921 u32 *arg_btf_id = NULL;
7924 if (arg_type == ARG_DONTCARE)
7927 err = check_reg_arg(env, regno, SRC_OP);
7931 if (arg_type == ARG_ANYTHING) {
7932 if (is_pointer_value(env, regno)) {
7933 verbose(env, "R%d leaks addr into helper function\n",
7940 if (type_is_pkt_pointer(type) &&
7941 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
7942 verbose(env, "helper access to the packet is not allowed\n");
7946 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
7947 err = resolve_map_arg_type(env, meta, &arg_type);
7952 if (register_is_null(reg) && type_may_be_null(arg_type))
7953 /* A NULL register has a SCALAR_VALUE type, so skip
7956 goto skip_type_check;
7958 /* arg_btf_id and arg_size are in a union. */
7959 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
7960 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
7961 arg_btf_id = fn->arg_btf_id[arg];
7963 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
7967 err = check_func_arg_reg_off(env, reg, regno, arg_type);
7972 if (arg_type_is_release(arg_type)) {
7973 if (arg_type_is_dynptr(arg_type)) {
7974 struct bpf_func_state *state = func(env, reg);
7977 /* Only dynptr created on stack can be released, thus
7978 * the get_spi and stack state checks for spilled_ptr
7979 * should only be done before process_dynptr_func for
7982 if (reg->type == PTR_TO_STACK) {
7983 spi = dynptr_get_spi(env, reg);
7984 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
7985 verbose(env, "arg %d is an unacquired reference\n", regno);
7989 verbose(env, "cannot release unowned const bpf_dynptr\n");
7992 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
7993 verbose(env, "R%d must be referenced when passed to release function\n",
7997 if (meta->release_regno) {
7998 verbose(env, "verifier internal error: more than one release argument\n");
8001 meta->release_regno = regno;
8004 if (reg->ref_obj_id) {
8005 if (meta->ref_obj_id) {
8006 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8007 regno, reg->ref_obj_id,
8011 meta->ref_obj_id = reg->ref_obj_id;
8014 switch (base_type(arg_type)) {
8015 case ARG_CONST_MAP_PTR:
8016 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8017 if (meta->map_ptr) {
8018 /* Use map_uid (which is unique id of inner map) to reject:
8019 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8020 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8021 * if (inner_map1 && inner_map2) {
8022 * timer = bpf_map_lookup_elem(inner_map1);
8024 * // mismatch would have been allowed
8025 * bpf_timer_init(timer, inner_map2);
8028 * Comparing map_ptr is enough to distinguish normal and outer maps.
8030 if (meta->map_ptr != reg->map_ptr ||
8031 meta->map_uid != reg->map_uid) {
8033 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8034 meta->map_uid, reg->map_uid);
8038 meta->map_ptr = reg->map_ptr;
8039 meta->map_uid = reg->map_uid;
8041 case ARG_PTR_TO_MAP_KEY:
8042 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8043 * check that [key, key + map->key_size) are within
8044 * stack limits and initialized
8046 if (!meta->map_ptr) {
8047 /* in function declaration map_ptr must come before
8048 * map_key, so that it's verified and known before
8049 * we have to check map_key here. Otherwise it means
8050 * that kernel subsystem misconfigured verifier
8052 verbose(env, "invalid map_ptr to access map->key\n");
8055 err = check_helper_mem_access(env, regno,
8056 meta->map_ptr->key_size, false,
8059 case ARG_PTR_TO_MAP_VALUE:
8060 if (type_may_be_null(arg_type) && register_is_null(reg))
8063 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8064 * check [value, value + map->value_size) validity
8066 if (!meta->map_ptr) {
8067 /* kernel subsystem misconfigured verifier */
8068 verbose(env, "invalid map_ptr to access map->value\n");
8071 meta->raw_mode = arg_type & MEM_UNINIT;
8072 err = check_helper_mem_access(env, regno,
8073 meta->map_ptr->value_size, false,
8076 case ARG_PTR_TO_PERCPU_BTF_ID:
8078 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8081 meta->ret_btf = reg->btf;
8082 meta->ret_btf_id = reg->btf_id;
8084 case ARG_PTR_TO_SPIN_LOCK:
8085 if (in_rbtree_lock_required_cb(env)) {
8086 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8089 if (meta->func_id == BPF_FUNC_spin_lock) {
8090 err = process_spin_lock(env, regno, true);
8093 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8094 err = process_spin_lock(env, regno, false);
8098 verbose(env, "verifier internal error\n");
8102 case ARG_PTR_TO_TIMER:
8103 err = process_timer_func(env, regno, meta);
8107 case ARG_PTR_TO_FUNC:
8108 meta->subprogno = reg->subprogno;
8110 case ARG_PTR_TO_MEM:
8111 /* The access to this pointer is only checked when we hit the
8112 * next is_mem_size argument below.
8114 meta->raw_mode = arg_type & MEM_UNINIT;
8115 if (arg_type & MEM_FIXED_SIZE) {
8116 err = check_helper_mem_access(env, regno,
8117 fn->arg_size[arg], false,
8121 case ARG_CONST_SIZE:
8122 err = check_mem_size_reg(env, reg, regno, false, meta);
8124 case ARG_CONST_SIZE_OR_ZERO:
8125 err = check_mem_size_reg(env, reg, regno, true, meta);
8127 case ARG_PTR_TO_DYNPTR:
8128 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8132 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8133 if (!tnum_is_const(reg->var_off)) {
8134 verbose(env, "R%d is not a known constant'\n",
8138 meta->mem_size = reg->var_off.value;
8139 err = mark_chain_precision(env, regno);
8143 case ARG_PTR_TO_INT:
8144 case ARG_PTR_TO_LONG:
8146 int size = int_ptr_type_to_size(arg_type);
8148 err = check_helper_mem_access(env, regno, size, false, meta);
8151 err = check_ptr_alignment(env, reg, 0, size, true);
8154 case ARG_PTR_TO_CONST_STR:
8156 struct bpf_map *map = reg->map_ptr;
8161 if (!bpf_map_is_rdonly(map)) {
8162 verbose(env, "R%d does not point to a readonly map'\n", regno);
8166 if (!tnum_is_const(reg->var_off)) {
8167 verbose(env, "R%d is not a constant address'\n", regno);
8171 if (!map->ops->map_direct_value_addr) {
8172 verbose(env, "no direct value access support for this map type\n");
8176 err = check_map_access(env, regno, reg->off,
8177 map->value_size - reg->off, false,
8182 map_off = reg->off + reg->var_off.value;
8183 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8185 verbose(env, "direct value access on string failed\n");
8189 str_ptr = (char *)(long)(map_addr);
8190 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8191 verbose(env, "string is not zero-terminated\n");
8196 case ARG_PTR_TO_KPTR:
8197 err = process_kptr_func(env, regno, meta);
8206 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8208 enum bpf_attach_type eatype = env->prog->expected_attach_type;
8209 enum bpf_prog_type type = resolve_prog_type(env->prog);
8211 if (func_id != BPF_FUNC_map_update_elem)
8214 /* It's not possible to get access to a locked struct sock in these
8215 * contexts, so updating is safe.
8218 case BPF_PROG_TYPE_TRACING:
8219 if (eatype == BPF_TRACE_ITER)
8222 case BPF_PROG_TYPE_SOCKET_FILTER:
8223 case BPF_PROG_TYPE_SCHED_CLS:
8224 case BPF_PROG_TYPE_SCHED_ACT:
8225 case BPF_PROG_TYPE_XDP:
8226 case BPF_PROG_TYPE_SK_REUSEPORT:
8227 case BPF_PROG_TYPE_FLOW_DISSECTOR:
8228 case BPF_PROG_TYPE_SK_LOOKUP:
8234 verbose(env, "cannot update sockmap in this context\n");
8238 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8240 return env->prog->jit_requested &&
8241 bpf_jit_supports_subprog_tailcalls();
8244 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8245 struct bpf_map *map, int func_id)
8250 /* We need a two way check, first is from map perspective ... */
8251 switch (map->map_type) {
8252 case BPF_MAP_TYPE_PROG_ARRAY:
8253 if (func_id != BPF_FUNC_tail_call)
8256 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8257 if (func_id != BPF_FUNC_perf_event_read &&
8258 func_id != BPF_FUNC_perf_event_output &&
8259 func_id != BPF_FUNC_skb_output &&
8260 func_id != BPF_FUNC_perf_event_read_value &&
8261 func_id != BPF_FUNC_xdp_output)
8264 case BPF_MAP_TYPE_RINGBUF:
8265 if (func_id != BPF_FUNC_ringbuf_output &&
8266 func_id != BPF_FUNC_ringbuf_reserve &&
8267 func_id != BPF_FUNC_ringbuf_query &&
8268 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8269 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8270 func_id != BPF_FUNC_ringbuf_discard_dynptr)
8273 case BPF_MAP_TYPE_USER_RINGBUF:
8274 if (func_id != BPF_FUNC_user_ringbuf_drain)
8277 case BPF_MAP_TYPE_STACK_TRACE:
8278 if (func_id != BPF_FUNC_get_stackid)
8281 case BPF_MAP_TYPE_CGROUP_ARRAY:
8282 if (func_id != BPF_FUNC_skb_under_cgroup &&
8283 func_id != BPF_FUNC_current_task_under_cgroup)
8286 case BPF_MAP_TYPE_CGROUP_STORAGE:
8287 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8288 if (func_id != BPF_FUNC_get_local_storage)
8291 case BPF_MAP_TYPE_DEVMAP:
8292 case BPF_MAP_TYPE_DEVMAP_HASH:
8293 if (func_id != BPF_FUNC_redirect_map &&
8294 func_id != BPF_FUNC_map_lookup_elem)
8297 /* Restrict bpf side of cpumap and xskmap, open when use-cases
8300 case BPF_MAP_TYPE_CPUMAP:
8301 if (func_id != BPF_FUNC_redirect_map)
8304 case BPF_MAP_TYPE_XSKMAP:
8305 if (func_id != BPF_FUNC_redirect_map &&
8306 func_id != BPF_FUNC_map_lookup_elem)
8309 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8310 case BPF_MAP_TYPE_HASH_OF_MAPS:
8311 if (func_id != BPF_FUNC_map_lookup_elem)
8314 case BPF_MAP_TYPE_SOCKMAP:
8315 if (func_id != BPF_FUNC_sk_redirect_map &&
8316 func_id != BPF_FUNC_sock_map_update &&
8317 func_id != BPF_FUNC_map_delete_elem &&
8318 func_id != BPF_FUNC_msg_redirect_map &&
8319 func_id != BPF_FUNC_sk_select_reuseport &&
8320 func_id != BPF_FUNC_map_lookup_elem &&
8321 !may_update_sockmap(env, func_id))
8324 case BPF_MAP_TYPE_SOCKHASH:
8325 if (func_id != BPF_FUNC_sk_redirect_hash &&
8326 func_id != BPF_FUNC_sock_hash_update &&
8327 func_id != BPF_FUNC_map_delete_elem &&
8328 func_id != BPF_FUNC_msg_redirect_hash &&
8329 func_id != BPF_FUNC_sk_select_reuseport &&
8330 func_id != BPF_FUNC_map_lookup_elem &&
8331 !may_update_sockmap(env, func_id))
8334 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8335 if (func_id != BPF_FUNC_sk_select_reuseport)
8338 case BPF_MAP_TYPE_QUEUE:
8339 case BPF_MAP_TYPE_STACK:
8340 if (func_id != BPF_FUNC_map_peek_elem &&
8341 func_id != BPF_FUNC_map_pop_elem &&
8342 func_id != BPF_FUNC_map_push_elem)
8345 case BPF_MAP_TYPE_SK_STORAGE:
8346 if (func_id != BPF_FUNC_sk_storage_get &&
8347 func_id != BPF_FUNC_sk_storage_delete &&
8348 func_id != BPF_FUNC_kptr_xchg)
8351 case BPF_MAP_TYPE_INODE_STORAGE:
8352 if (func_id != BPF_FUNC_inode_storage_get &&
8353 func_id != BPF_FUNC_inode_storage_delete &&
8354 func_id != BPF_FUNC_kptr_xchg)
8357 case BPF_MAP_TYPE_TASK_STORAGE:
8358 if (func_id != BPF_FUNC_task_storage_get &&
8359 func_id != BPF_FUNC_task_storage_delete &&
8360 func_id != BPF_FUNC_kptr_xchg)
8363 case BPF_MAP_TYPE_CGRP_STORAGE:
8364 if (func_id != BPF_FUNC_cgrp_storage_get &&
8365 func_id != BPF_FUNC_cgrp_storage_delete &&
8366 func_id != BPF_FUNC_kptr_xchg)
8369 case BPF_MAP_TYPE_BLOOM_FILTER:
8370 if (func_id != BPF_FUNC_map_peek_elem &&
8371 func_id != BPF_FUNC_map_push_elem)
8378 /* ... and second from the function itself. */
8380 case BPF_FUNC_tail_call:
8381 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8383 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8384 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8388 case BPF_FUNC_perf_event_read:
8389 case BPF_FUNC_perf_event_output:
8390 case BPF_FUNC_perf_event_read_value:
8391 case BPF_FUNC_skb_output:
8392 case BPF_FUNC_xdp_output:
8393 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8396 case BPF_FUNC_ringbuf_output:
8397 case BPF_FUNC_ringbuf_reserve:
8398 case BPF_FUNC_ringbuf_query:
8399 case BPF_FUNC_ringbuf_reserve_dynptr:
8400 case BPF_FUNC_ringbuf_submit_dynptr:
8401 case BPF_FUNC_ringbuf_discard_dynptr:
8402 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8405 case BPF_FUNC_user_ringbuf_drain:
8406 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8409 case BPF_FUNC_get_stackid:
8410 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8413 case BPF_FUNC_current_task_under_cgroup:
8414 case BPF_FUNC_skb_under_cgroup:
8415 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8418 case BPF_FUNC_redirect_map:
8419 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8420 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8421 map->map_type != BPF_MAP_TYPE_CPUMAP &&
8422 map->map_type != BPF_MAP_TYPE_XSKMAP)
8425 case BPF_FUNC_sk_redirect_map:
8426 case BPF_FUNC_msg_redirect_map:
8427 case BPF_FUNC_sock_map_update:
8428 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8431 case BPF_FUNC_sk_redirect_hash:
8432 case BPF_FUNC_msg_redirect_hash:
8433 case BPF_FUNC_sock_hash_update:
8434 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8437 case BPF_FUNC_get_local_storage:
8438 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8439 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8442 case BPF_FUNC_sk_select_reuseport:
8443 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8444 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8445 map->map_type != BPF_MAP_TYPE_SOCKHASH)
8448 case BPF_FUNC_map_pop_elem:
8449 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8450 map->map_type != BPF_MAP_TYPE_STACK)
8453 case BPF_FUNC_map_peek_elem:
8454 case BPF_FUNC_map_push_elem:
8455 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8456 map->map_type != BPF_MAP_TYPE_STACK &&
8457 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8460 case BPF_FUNC_map_lookup_percpu_elem:
8461 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8462 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8463 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8466 case BPF_FUNC_sk_storage_get:
8467 case BPF_FUNC_sk_storage_delete:
8468 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8471 case BPF_FUNC_inode_storage_get:
8472 case BPF_FUNC_inode_storage_delete:
8473 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8476 case BPF_FUNC_task_storage_get:
8477 case BPF_FUNC_task_storage_delete:
8478 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8481 case BPF_FUNC_cgrp_storage_get:
8482 case BPF_FUNC_cgrp_storage_delete:
8483 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8492 verbose(env, "cannot pass map_type %d into func %s#%d\n",
8493 map->map_type, func_id_name(func_id), func_id);
8497 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8501 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8503 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8505 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8507 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8509 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8512 /* We only support one arg being in raw mode at the moment,
8513 * which is sufficient for the helper functions we have
8519 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8521 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8522 bool has_size = fn->arg_size[arg] != 0;
8523 bool is_next_size = false;
8525 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8526 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8528 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8529 return is_next_size;
8531 return has_size == is_next_size || is_next_size == is_fixed;
8534 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8536 /* bpf_xxx(..., buf, len) call will access 'len'
8537 * bytes from memory 'buf'. Both arg types need
8538 * to be paired, so make sure there's no buggy
8539 * helper function specification.
8541 if (arg_type_is_mem_size(fn->arg1_type) ||
8542 check_args_pair_invalid(fn, 0) ||
8543 check_args_pair_invalid(fn, 1) ||
8544 check_args_pair_invalid(fn, 2) ||
8545 check_args_pair_invalid(fn, 3) ||
8546 check_args_pair_invalid(fn, 4))
8552 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8556 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8557 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8558 return !!fn->arg_btf_id[i];
8559 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8560 return fn->arg_btf_id[i] == BPF_PTR_POISON;
8561 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8562 /* arg_btf_id and arg_size are in a union. */
8563 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8564 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8571 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8573 return check_raw_mode_ok(fn) &&
8574 check_arg_pair_ok(fn) &&
8575 check_btf_id_ok(fn) ? 0 : -EINVAL;
8578 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8579 * are now invalid, so turn them into unknown SCALAR_VALUE.
8581 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8582 * since these slices point to packet data.
8584 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8586 struct bpf_func_state *state;
8587 struct bpf_reg_state *reg;
8589 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8590 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8591 mark_reg_invalid(env, reg);
8597 BEYOND_PKT_END = -2,
8600 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8602 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8603 struct bpf_reg_state *reg = &state->regs[regn];
8605 if (reg->type != PTR_TO_PACKET)
8606 /* PTR_TO_PACKET_META is not supported yet */
8609 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8610 * How far beyond pkt_end it goes is unknown.
8611 * if (!range_open) it's the case of pkt >= pkt_end
8612 * if (range_open) it's the case of pkt > pkt_end
8613 * hence this pointer is at least 1 byte bigger than pkt_end
8616 reg->range = BEYOND_PKT_END;
8618 reg->range = AT_PKT_END;
8621 /* The pointer with the specified id has released its reference to kernel
8622 * resources. Identify all copies of the same pointer and clear the reference.
8624 static int release_reference(struct bpf_verifier_env *env,
8627 struct bpf_func_state *state;
8628 struct bpf_reg_state *reg;
8631 err = release_reference_state(cur_func(env), ref_obj_id);
8635 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8636 if (reg->ref_obj_id == ref_obj_id)
8637 mark_reg_invalid(env, reg);
8643 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8645 struct bpf_func_state *unused;
8646 struct bpf_reg_state *reg;
8648 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8649 if (type_is_non_owning_ref(reg->type))
8650 mark_reg_invalid(env, reg);
8654 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8655 struct bpf_reg_state *regs)
8659 /* after the call registers r0 - r5 were scratched */
8660 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8661 mark_reg_not_init(env, regs, caller_saved[i]);
8662 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8666 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8667 struct bpf_func_state *caller,
8668 struct bpf_func_state *callee,
8671 static int set_callee_state(struct bpf_verifier_env *env,
8672 struct bpf_func_state *caller,
8673 struct bpf_func_state *callee, int insn_idx);
8675 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8676 int *insn_idx, int subprog,
8677 set_callee_state_fn set_callee_state_cb)
8679 struct bpf_verifier_state *state = env->cur_state;
8680 struct bpf_func_state *caller, *callee;
8683 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8684 verbose(env, "the call stack of %d frames is too deep\n",
8685 state->curframe + 2);
8689 caller = state->frame[state->curframe];
8690 if (state->frame[state->curframe + 1]) {
8691 verbose(env, "verifier bug. Frame %d already allocated\n",
8692 state->curframe + 1);
8696 err = btf_check_subprog_call(env, subprog, caller->regs);
8699 if (subprog_is_global(env, subprog)) {
8701 verbose(env, "Caller passes invalid args into func#%d\n",
8705 if (env->log.level & BPF_LOG_LEVEL)
8707 "Func#%d is global and valid. Skipping.\n",
8709 clear_caller_saved_regs(env, caller->regs);
8711 /* All global functions return a 64-bit SCALAR_VALUE */
8712 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8713 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8715 /* continue with next insn after call */
8720 /* set_callee_state is used for direct subprog calls, but we are
8721 * interested in validating only BPF helpers that can call subprogs as
8724 if (set_callee_state_cb != set_callee_state) {
8725 if (bpf_pseudo_kfunc_call(insn) &&
8726 !is_callback_calling_kfunc(insn->imm)) {
8727 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8728 func_id_name(insn->imm), insn->imm);
8730 } else if (!bpf_pseudo_kfunc_call(insn) &&
8731 !is_callback_calling_function(insn->imm)) { /* helper */
8732 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8733 func_id_name(insn->imm), insn->imm);
8738 if (insn->code == (BPF_JMP | BPF_CALL) &&
8739 insn->src_reg == 0 &&
8740 insn->imm == BPF_FUNC_timer_set_callback) {
8741 struct bpf_verifier_state *async_cb;
8743 /* there is no real recursion here. timer callbacks are async */
8744 env->subprog_info[subprog].is_async_cb = true;
8745 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8746 *insn_idx, subprog);
8749 callee = async_cb->frame[0];
8750 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8752 /* Convert bpf_timer_set_callback() args into timer callback args */
8753 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8757 clear_caller_saved_regs(env, caller->regs);
8758 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8759 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8760 /* continue with next insn after call */
8764 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8767 state->frame[state->curframe + 1] = callee;
8769 /* callee cannot access r0, r6 - r9 for reading and has to write
8770 * into its own stack before reading from it.
8771 * callee can read/write into caller's stack
8773 init_func_state(env, callee,
8774 /* remember the callsite, it will be used by bpf_exit */
8775 *insn_idx /* callsite */,
8776 state->curframe + 1 /* frameno within this callchain */,
8777 subprog /* subprog number within this prog */);
8779 /* Transfer references to the callee */
8780 err = copy_reference_state(callee, caller);
8784 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8788 clear_caller_saved_regs(env, caller->regs);
8790 /* only increment it after check_reg_arg() finished */
8793 /* and go analyze first insn of the callee */
8794 *insn_idx = env->subprog_info[subprog].start - 1;
8796 if (env->log.level & BPF_LOG_LEVEL) {
8797 verbose(env, "caller:\n");
8798 print_verifier_state(env, caller, true);
8799 verbose(env, "callee:\n");
8800 print_verifier_state(env, callee, true);
8805 free_func_state(callee);
8806 state->frame[state->curframe + 1] = NULL;
8810 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8811 struct bpf_func_state *caller,
8812 struct bpf_func_state *callee)
8814 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8815 * void *callback_ctx, u64 flags);
8816 * callback_fn(struct bpf_map *map, void *key, void *value,
8817 * void *callback_ctx);
8819 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8821 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8822 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8823 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8825 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8826 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8827 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8829 /* pointer to stack or null */
8830 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
8833 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8837 static int set_callee_state(struct bpf_verifier_env *env,
8838 struct bpf_func_state *caller,
8839 struct bpf_func_state *callee, int insn_idx)
8843 /* copy r1 - r5 args that callee can access. The copy includes parent
8844 * pointers, which connects us up to the liveness chain
8846 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
8847 callee->regs[i] = caller->regs[i];
8851 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8854 int subprog, target_insn;
8856 target_insn = *insn_idx + insn->imm + 1;
8857 subprog = find_subprog(env, target_insn);
8859 verbose(env, "verifier bug. No program starts at insn %d\n",
8864 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
8867 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
8868 struct bpf_func_state *caller,
8869 struct bpf_func_state *callee,
8872 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
8873 struct bpf_map *map;
8876 if (bpf_map_ptr_poisoned(insn_aux)) {
8877 verbose(env, "tail_call abusing map_ptr\n");
8881 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
8882 if (!map->ops->map_set_for_each_callback_args ||
8883 !map->ops->map_for_each_callback) {
8884 verbose(env, "callback function not allowed for map\n");
8888 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
8892 callee->in_callback_fn = true;
8893 callee->callback_ret_range = tnum_range(0, 1);
8897 static int set_loop_callback_state(struct bpf_verifier_env *env,
8898 struct bpf_func_state *caller,
8899 struct bpf_func_state *callee,
8902 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
8904 * callback_fn(u32 index, void *callback_ctx);
8906 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
8907 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8910 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8911 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8912 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8914 callee->in_callback_fn = true;
8915 callee->callback_ret_range = tnum_range(0, 1);
8919 static int set_timer_callback_state(struct bpf_verifier_env *env,
8920 struct bpf_func_state *caller,
8921 struct bpf_func_state *callee,
8924 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
8926 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
8927 * callback_fn(struct bpf_map *map, void *key, void *value);
8929 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
8930 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
8931 callee->regs[BPF_REG_1].map_ptr = map_ptr;
8933 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8934 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8935 callee->regs[BPF_REG_2].map_ptr = map_ptr;
8937 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8938 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8939 callee->regs[BPF_REG_3].map_ptr = map_ptr;
8942 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8943 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8944 callee->in_async_callback_fn = true;
8945 callee->callback_ret_range = tnum_range(0, 1);
8949 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
8950 struct bpf_func_state *caller,
8951 struct bpf_func_state *callee,
8954 /* bpf_find_vma(struct task_struct *task, u64 addr,
8955 * void *callback_fn, void *callback_ctx, u64 flags)
8956 * (callback_fn)(struct task_struct *task,
8957 * struct vm_area_struct *vma, void *callback_ctx);
8959 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8961 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
8962 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8963 callee->regs[BPF_REG_2].btf = btf_vmlinux;
8964 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
8966 /* pointer to stack or null */
8967 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
8970 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8971 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8972 callee->in_callback_fn = true;
8973 callee->callback_ret_range = tnum_range(0, 1);
8977 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
8978 struct bpf_func_state *caller,
8979 struct bpf_func_state *callee,
8982 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
8983 * callback_ctx, u64 flags);
8984 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
8986 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
8987 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
8988 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8991 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8992 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8993 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8995 callee->in_callback_fn = true;
8996 callee->callback_ret_range = tnum_range(0, 1);
9000 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9001 struct bpf_func_state *caller,
9002 struct bpf_func_state *callee,
9005 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9006 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9008 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9009 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9010 * by this point, so look at 'root'
9012 struct btf_field *field;
9014 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9016 if (!field || !field->graph_root.value_btf_id)
9019 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9020 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9021 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9022 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9024 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9025 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9026 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9027 callee->in_callback_fn = true;
9028 callee->callback_ret_range = tnum_range(0, 1);
9032 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9034 /* Are we currently verifying the callback for a rbtree helper that must
9035 * be called with lock held? If so, no need to complain about unreleased
9038 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9040 struct bpf_verifier_state *state = env->cur_state;
9041 struct bpf_insn *insn = env->prog->insnsi;
9042 struct bpf_func_state *callee;
9045 if (!state->curframe)
9048 callee = state->frame[state->curframe];
9050 if (!callee->in_callback_fn)
9053 kfunc_btf_id = insn[callee->callsite].imm;
9054 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9057 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9059 struct bpf_verifier_state *state = env->cur_state;
9060 struct bpf_func_state *caller, *callee;
9061 struct bpf_reg_state *r0;
9064 callee = state->frame[state->curframe];
9065 r0 = &callee->regs[BPF_REG_0];
9066 if (r0->type == PTR_TO_STACK) {
9067 /* technically it's ok to return caller's stack pointer
9068 * (or caller's caller's pointer) back to the caller,
9069 * since these pointers are valid. Only current stack
9070 * pointer will be invalid as soon as function exits,
9071 * but let's be conservative
9073 verbose(env, "cannot return stack pointer to the caller\n");
9077 caller = state->frame[state->curframe - 1];
9078 if (callee->in_callback_fn) {
9079 /* enforce R0 return value range [0, 1]. */
9080 struct tnum range = callee->callback_ret_range;
9082 if (r0->type != SCALAR_VALUE) {
9083 verbose(env, "R0 not a scalar value\n");
9086 if (!tnum_in(range, r0->var_off)) {
9087 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9091 /* return to the caller whatever r0 had in the callee */
9092 caller->regs[BPF_REG_0] = *r0;
9095 /* callback_fn frame should have released its own additions to parent's
9096 * reference state at this point, or check_reference_leak would
9097 * complain, hence it must be the same as the caller. There is no need
9100 if (!callee->in_callback_fn) {
9101 /* Transfer references to the caller */
9102 err = copy_reference_state(caller, callee);
9107 *insn_idx = callee->callsite + 1;
9108 if (env->log.level & BPF_LOG_LEVEL) {
9109 verbose(env, "returning from callee:\n");
9110 print_verifier_state(env, callee, true);
9111 verbose(env, "to caller at %d:\n", *insn_idx);
9112 print_verifier_state(env, caller, true);
9114 /* clear everything in the callee */
9115 free_func_state(callee);
9116 state->frame[state->curframe--] = NULL;
9120 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9122 struct bpf_call_arg_meta *meta)
9124 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
9126 if (ret_type != RET_INTEGER)
9130 case BPF_FUNC_get_stack:
9131 case BPF_FUNC_get_task_stack:
9132 case BPF_FUNC_probe_read_str:
9133 case BPF_FUNC_probe_read_kernel_str:
9134 case BPF_FUNC_probe_read_user_str:
9135 ret_reg->smax_value = meta->msize_max_value;
9136 ret_reg->s32_max_value = meta->msize_max_value;
9137 ret_reg->smin_value = -MAX_ERRNO;
9138 ret_reg->s32_min_value = -MAX_ERRNO;
9139 reg_bounds_sync(ret_reg);
9141 case BPF_FUNC_get_smp_processor_id:
9142 ret_reg->umax_value = nr_cpu_ids - 1;
9143 ret_reg->u32_max_value = nr_cpu_ids - 1;
9144 ret_reg->smax_value = nr_cpu_ids - 1;
9145 ret_reg->s32_max_value = nr_cpu_ids - 1;
9146 ret_reg->umin_value = 0;
9147 ret_reg->u32_min_value = 0;
9148 ret_reg->smin_value = 0;
9149 ret_reg->s32_min_value = 0;
9150 reg_bounds_sync(ret_reg);
9156 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9157 int func_id, int insn_idx)
9159 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9160 struct bpf_map *map = meta->map_ptr;
9162 if (func_id != BPF_FUNC_tail_call &&
9163 func_id != BPF_FUNC_map_lookup_elem &&
9164 func_id != BPF_FUNC_map_update_elem &&
9165 func_id != BPF_FUNC_map_delete_elem &&
9166 func_id != BPF_FUNC_map_push_elem &&
9167 func_id != BPF_FUNC_map_pop_elem &&
9168 func_id != BPF_FUNC_map_peek_elem &&
9169 func_id != BPF_FUNC_for_each_map_elem &&
9170 func_id != BPF_FUNC_redirect_map &&
9171 func_id != BPF_FUNC_map_lookup_percpu_elem)
9175 verbose(env, "kernel subsystem misconfigured verifier\n");
9179 /* In case of read-only, some additional restrictions
9180 * need to be applied in order to prevent altering the
9181 * state of the map from program side.
9183 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9184 (func_id == BPF_FUNC_map_delete_elem ||
9185 func_id == BPF_FUNC_map_update_elem ||
9186 func_id == BPF_FUNC_map_push_elem ||
9187 func_id == BPF_FUNC_map_pop_elem)) {
9188 verbose(env, "write into map forbidden\n");
9192 if (!BPF_MAP_PTR(aux->map_ptr_state))
9193 bpf_map_ptr_store(aux, meta->map_ptr,
9194 !meta->map_ptr->bypass_spec_v1);
9195 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9196 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9197 !meta->map_ptr->bypass_spec_v1);
9202 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9203 int func_id, int insn_idx)
9205 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9206 struct bpf_reg_state *regs = cur_regs(env), *reg;
9207 struct bpf_map *map = meta->map_ptr;
9211 if (func_id != BPF_FUNC_tail_call)
9213 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9214 verbose(env, "kernel subsystem misconfigured verifier\n");
9218 reg = ®s[BPF_REG_3];
9219 val = reg->var_off.value;
9220 max = map->max_entries;
9222 if (!(register_is_const(reg) && val < max)) {
9223 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9227 err = mark_chain_precision(env, BPF_REG_3);
9230 if (bpf_map_key_unseen(aux))
9231 bpf_map_key_store(aux, val);
9232 else if (!bpf_map_key_poisoned(aux) &&
9233 bpf_map_key_immediate(aux) != val)
9234 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9238 static int check_reference_leak(struct bpf_verifier_env *env)
9240 struct bpf_func_state *state = cur_func(env);
9241 bool refs_lingering = false;
9244 if (state->frameno && !state->in_callback_fn)
9247 for (i = 0; i < state->acquired_refs; i++) {
9248 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9250 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9251 state->refs[i].id, state->refs[i].insn_idx);
9252 refs_lingering = true;
9254 return refs_lingering ? -EINVAL : 0;
9257 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9258 struct bpf_reg_state *regs)
9260 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
9261 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
9262 struct bpf_map *fmt_map = fmt_reg->map_ptr;
9263 struct bpf_bprintf_data data = {};
9264 int err, fmt_map_off, num_args;
9268 /* data must be an array of u64 */
9269 if (data_len_reg->var_off.value % 8)
9271 num_args = data_len_reg->var_off.value / 8;
9273 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9274 * and map_direct_value_addr is set.
9276 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9277 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9280 verbose(env, "verifier bug\n");
9283 fmt = (char *)(long)fmt_addr + fmt_map_off;
9285 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9286 * can focus on validating the format specifiers.
9288 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9290 verbose(env, "Invalid format string\n");
9295 static int check_get_func_ip(struct bpf_verifier_env *env)
9297 enum bpf_prog_type type = resolve_prog_type(env->prog);
9298 int func_id = BPF_FUNC_get_func_ip;
9300 if (type == BPF_PROG_TYPE_TRACING) {
9301 if (!bpf_prog_has_trampoline(env->prog)) {
9302 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9303 func_id_name(func_id), func_id);
9307 } else if (type == BPF_PROG_TYPE_KPROBE) {
9311 verbose(env, "func %s#%d not supported for program type %d\n",
9312 func_id_name(func_id), func_id, type);
9316 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9318 return &env->insn_aux_data[env->insn_idx];
9321 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9323 struct bpf_reg_state *regs = cur_regs(env);
9324 struct bpf_reg_state *reg = ®s[BPF_REG_4];
9325 bool reg_is_null = register_is_null(reg);
9328 mark_chain_precision(env, BPF_REG_4);
9333 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9335 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9337 if (!state->initialized) {
9338 state->initialized = 1;
9339 state->fit_for_inline = loop_flag_is_zero(env);
9340 state->callback_subprogno = subprogno;
9344 if (!state->fit_for_inline)
9347 state->fit_for_inline = (loop_flag_is_zero(env) &&
9348 state->callback_subprogno == subprogno);
9351 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9354 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9355 const struct bpf_func_proto *fn = NULL;
9356 enum bpf_return_type ret_type;
9357 enum bpf_type_flag ret_flag;
9358 struct bpf_reg_state *regs;
9359 struct bpf_call_arg_meta meta;
9360 int insn_idx = *insn_idx_p;
9362 int i, err, func_id;
9364 /* find function prototype */
9365 func_id = insn->imm;
9366 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9367 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9372 if (env->ops->get_func_proto)
9373 fn = env->ops->get_func_proto(func_id, env->prog);
9375 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9380 /* eBPF programs must be GPL compatible to use GPL-ed functions */
9381 if (!env->prog->gpl_compatible && fn->gpl_only) {
9382 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9386 if (fn->allowed && !fn->allowed(env->prog)) {
9387 verbose(env, "helper call is not allowed in probe\n");
9391 if (!env->prog->aux->sleepable && fn->might_sleep) {
9392 verbose(env, "helper call might sleep in a non-sleepable prog\n");
9396 /* With LD_ABS/IND some JITs save/restore skb from r1. */
9397 changes_data = bpf_helper_changes_pkt_data(fn->func);
9398 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9399 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9400 func_id_name(func_id), func_id);
9404 memset(&meta, 0, sizeof(meta));
9405 meta.pkt_access = fn->pkt_access;
9407 err = check_func_proto(fn, func_id);
9409 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9410 func_id_name(func_id), func_id);
9414 if (env->cur_state->active_rcu_lock) {
9415 if (fn->might_sleep) {
9416 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9417 func_id_name(func_id), func_id);
9421 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9422 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9425 meta.func_id = func_id;
9427 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9428 err = check_func_arg(env, i, &meta, fn, insn_idx);
9433 err = record_func_map(env, &meta, func_id, insn_idx);
9437 err = record_func_key(env, &meta, func_id, insn_idx);
9441 /* Mark slots with STACK_MISC in case of raw mode, stack offset
9442 * is inferred from register state.
9444 for (i = 0; i < meta.access_size; i++) {
9445 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9446 BPF_WRITE, -1, false);
9451 regs = cur_regs(env);
9453 if (meta.release_regno) {
9455 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9456 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9457 * is safe to do directly.
9459 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9460 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9461 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9464 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
9465 } else if (meta.ref_obj_id) {
9466 err = release_reference(env, meta.ref_obj_id);
9467 } else if (register_is_null(®s[meta.release_regno])) {
9468 /* meta.ref_obj_id can only be 0 if register that is meant to be
9469 * released is NULL, which must be > R0.
9474 verbose(env, "func %s#%d reference has not been acquired before\n",
9475 func_id_name(func_id), func_id);
9481 case BPF_FUNC_tail_call:
9482 err = check_reference_leak(env);
9484 verbose(env, "tail_call would lead to reference leak\n");
9488 case BPF_FUNC_get_local_storage:
9489 /* check that flags argument in get_local_storage(map, flags) is 0,
9490 * this is required because get_local_storage() can't return an error.
9492 if (!register_is_null(®s[BPF_REG_2])) {
9493 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9497 case BPF_FUNC_for_each_map_elem:
9498 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9499 set_map_elem_callback_state);
9501 case BPF_FUNC_timer_set_callback:
9502 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9503 set_timer_callback_state);
9505 case BPF_FUNC_find_vma:
9506 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9507 set_find_vma_callback_state);
9509 case BPF_FUNC_snprintf:
9510 err = check_bpf_snprintf_call(env, regs);
9513 update_loop_inline_state(env, meta.subprogno);
9514 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9515 set_loop_callback_state);
9517 case BPF_FUNC_dynptr_from_mem:
9518 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9519 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9520 reg_type_str(env, regs[BPF_REG_1].type));
9524 case BPF_FUNC_set_retval:
9525 if (prog_type == BPF_PROG_TYPE_LSM &&
9526 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9527 if (!env->prog->aux->attach_func_proto->type) {
9528 /* Make sure programs that attach to void
9529 * hooks don't try to modify return value.
9531 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9536 case BPF_FUNC_dynptr_data:
9538 struct bpf_reg_state *reg;
9541 reg = get_dynptr_arg_reg(env, fn, regs);
9546 if (meta.dynptr_id) {
9547 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9550 if (meta.ref_obj_id) {
9551 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9555 id = dynptr_id(env, reg);
9557 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9561 ref_obj_id = dynptr_ref_obj_id(env, reg);
9562 if (ref_obj_id < 0) {
9563 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9567 meta.dynptr_id = id;
9568 meta.ref_obj_id = ref_obj_id;
9572 case BPF_FUNC_dynptr_write:
9574 enum bpf_dynptr_type dynptr_type;
9575 struct bpf_reg_state *reg;
9577 reg = get_dynptr_arg_reg(env, fn, regs);
9581 dynptr_type = dynptr_get_type(env, reg);
9582 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9585 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9586 /* this will trigger clear_all_pkt_pointers(), which will
9587 * invalidate all dynptr slices associated with the skb
9589 changes_data = true;
9593 case BPF_FUNC_user_ringbuf_drain:
9594 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9595 set_user_ringbuf_callback_state);
9602 /* reset caller saved regs */
9603 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9604 mark_reg_not_init(env, regs, caller_saved[i]);
9605 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9608 /* helper call returns 64-bit value. */
9609 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9611 /* update return register (already marked as written above) */
9612 ret_type = fn->ret_type;
9613 ret_flag = type_flag(ret_type);
9615 switch (base_type(ret_type)) {
9617 /* sets type to SCALAR_VALUE */
9618 mark_reg_unknown(env, regs, BPF_REG_0);
9621 regs[BPF_REG_0].type = NOT_INIT;
9623 case RET_PTR_TO_MAP_VALUE:
9624 /* There is no offset yet applied, variable or fixed */
9625 mark_reg_known_zero(env, regs, BPF_REG_0);
9626 /* remember map_ptr, so that check_map_access()
9627 * can check 'value_size' boundary of memory access
9628 * to map element returned from bpf_map_lookup_elem()
9630 if (meta.map_ptr == NULL) {
9632 "kernel subsystem misconfigured verifier\n");
9635 regs[BPF_REG_0].map_ptr = meta.map_ptr;
9636 regs[BPF_REG_0].map_uid = meta.map_uid;
9637 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9638 if (!type_may_be_null(ret_type) &&
9639 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9640 regs[BPF_REG_0].id = ++env->id_gen;
9643 case RET_PTR_TO_SOCKET:
9644 mark_reg_known_zero(env, regs, BPF_REG_0);
9645 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9647 case RET_PTR_TO_SOCK_COMMON:
9648 mark_reg_known_zero(env, regs, BPF_REG_0);
9649 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9651 case RET_PTR_TO_TCP_SOCK:
9652 mark_reg_known_zero(env, regs, BPF_REG_0);
9653 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9655 case RET_PTR_TO_MEM:
9656 mark_reg_known_zero(env, regs, BPF_REG_0);
9657 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9658 regs[BPF_REG_0].mem_size = meta.mem_size;
9660 case RET_PTR_TO_MEM_OR_BTF_ID:
9662 const struct btf_type *t;
9664 mark_reg_known_zero(env, regs, BPF_REG_0);
9665 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9666 if (!btf_type_is_struct(t)) {
9668 const struct btf_type *ret;
9671 /* resolve the type size of ksym. */
9672 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9674 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9675 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9676 tname, PTR_ERR(ret));
9679 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9680 regs[BPF_REG_0].mem_size = tsize;
9682 /* MEM_RDONLY may be carried from ret_flag, but it
9683 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9684 * it will confuse the check of PTR_TO_BTF_ID in
9685 * check_mem_access().
9687 ret_flag &= ~MEM_RDONLY;
9689 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9690 regs[BPF_REG_0].btf = meta.ret_btf;
9691 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9695 case RET_PTR_TO_BTF_ID:
9697 struct btf *ret_btf;
9700 mark_reg_known_zero(env, regs, BPF_REG_0);
9701 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9702 if (func_id == BPF_FUNC_kptr_xchg) {
9703 ret_btf = meta.kptr_field->kptr.btf;
9704 ret_btf_id = meta.kptr_field->kptr.btf_id;
9705 if (!btf_is_kernel(ret_btf))
9706 regs[BPF_REG_0].type |= MEM_ALLOC;
9708 if (fn->ret_btf_id == BPF_PTR_POISON) {
9709 verbose(env, "verifier internal error:");
9710 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9711 func_id_name(func_id));
9714 ret_btf = btf_vmlinux;
9715 ret_btf_id = *fn->ret_btf_id;
9717 if (ret_btf_id == 0) {
9718 verbose(env, "invalid return type %u of func %s#%d\n",
9719 base_type(ret_type), func_id_name(func_id),
9723 regs[BPF_REG_0].btf = ret_btf;
9724 regs[BPF_REG_0].btf_id = ret_btf_id;
9728 verbose(env, "unknown return type %u of func %s#%d\n",
9729 base_type(ret_type), func_id_name(func_id), func_id);
9733 if (type_may_be_null(regs[BPF_REG_0].type))
9734 regs[BPF_REG_0].id = ++env->id_gen;
9736 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9737 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9738 func_id_name(func_id), func_id);
9742 if (is_dynptr_ref_function(func_id))
9743 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9745 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9746 /* For release_reference() */
9747 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9748 } else if (is_acquire_function(func_id, meta.map_ptr)) {
9749 int id = acquire_reference_state(env, insn_idx);
9753 /* For mark_ptr_or_null_reg() */
9754 regs[BPF_REG_0].id = id;
9755 /* For release_reference() */
9756 regs[BPF_REG_0].ref_obj_id = id;
9759 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9761 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9765 if ((func_id == BPF_FUNC_get_stack ||
9766 func_id == BPF_FUNC_get_task_stack) &&
9767 !env->prog->has_callchain_buf) {
9768 const char *err_str;
9770 #ifdef CONFIG_PERF_EVENTS
9771 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9772 err_str = "cannot get callchain buffer for func %s#%d\n";
9775 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9778 verbose(env, err_str, func_id_name(func_id), func_id);
9782 env->prog->has_callchain_buf = true;
9785 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9786 env->prog->call_get_stack = true;
9788 if (func_id == BPF_FUNC_get_func_ip) {
9789 if (check_get_func_ip(env))
9791 env->prog->call_get_func_ip = true;
9795 clear_all_pkt_pointers(env);
9799 /* mark_btf_func_reg_size() is used when the reg size is determined by
9800 * the BTF func_proto's return value size and argument.
9802 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9805 struct bpf_reg_state *reg = &cur_regs(env)[regno];
9807 if (regno == BPF_REG_0) {
9808 /* Function return value */
9809 reg->live |= REG_LIVE_WRITTEN;
9810 reg->subreg_def = reg_size == sizeof(u64) ?
9811 DEF_NOT_SUBREG : env->insn_idx + 1;
9813 /* Function argument */
9814 if (reg_size == sizeof(u64)) {
9815 mark_insn_zext(env, reg);
9816 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9818 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9823 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
9825 return meta->kfunc_flags & KF_ACQUIRE;
9828 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
9830 return meta->kfunc_flags & KF_RELEASE;
9833 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
9835 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
9838 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
9840 return meta->kfunc_flags & KF_SLEEPABLE;
9843 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
9845 return meta->kfunc_flags & KF_DESTRUCTIVE;
9848 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
9850 return meta->kfunc_flags & KF_RCU;
9853 static bool __kfunc_param_match_suffix(const struct btf *btf,
9854 const struct btf_param *arg,
9857 int suffix_len = strlen(suffix), len;
9858 const char *param_name;
9860 /* In the future, this can be ported to use BTF tagging */
9861 param_name = btf_name_by_offset(btf, arg->name_off);
9862 if (str_is_empty(param_name))
9864 len = strlen(param_name);
9865 if (len < suffix_len)
9867 param_name += len - suffix_len;
9868 return !strncmp(param_name, suffix, suffix_len);
9871 static bool is_kfunc_arg_mem_size(const struct btf *btf,
9872 const struct btf_param *arg,
9873 const struct bpf_reg_state *reg)
9875 const struct btf_type *t;
9877 t = btf_type_skip_modifiers(btf, arg->type, NULL);
9878 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9881 return __kfunc_param_match_suffix(btf, arg, "__sz");
9884 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
9885 const struct btf_param *arg,
9886 const struct bpf_reg_state *reg)
9888 const struct btf_type *t;
9890 t = btf_type_skip_modifiers(btf, arg->type, NULL);
9891 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9894 return __kfunc_param_match_suffix(btf, arg, "__szk");
9897 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
9899 return __kfunc_param_match_suffix(btf, arg, "__opt");
9902 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
9904 return __kfunc_param_match_suffix(btf, arg, "__k");
9907 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
9909 return __kfunc_param_match_suffix(btf, arg, "__ign");
9912 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
9914 return __kfunc_param_match_suffix(btf, arg, "__alloc");
9917 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
9919 return __kfunc_param_match_suffix(btf, arg, "__uninit");
9922 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
9924 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
9927 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
9928 const struct btf_param *arg,
9931 int len, target_len = strlen(name);
9932 const char *param_name;
9934 param_name = btf_name_by_offset(btf, arg->name_off);
9935 if (str_is_empty(param_name))
9937 len = strlen(param_name);
9938 if (len != target_len)
9940 if (strcmp(param_name, name))
9948 KF_ARG_LIST_HEAD_ID,
9949 KF_ARG_LIST_NODE_ID,
9954 BTF_ID_LIST(kf_arg_btf_ids)
9955 BTF_ID(struct, bpf_dynptr_kern)
9956 BTF_ID(struct, bpf_list_head)
9957 BTF_ID(struct, bpf_list_node)
9958 BTF_ID(struct, bpf_rb_root)
9959 BTF_ID(struct, bpf_rb_node)
9961 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
9962 const struct btf_param *arg, int type)
9964 const struct btf_type *t;
9967 t = btf_type_skip_modifiers(btf, arg->type, NULL);
9970 if (!btf_type_is_ptr(t))
9972 t = btf_type_skip_modifiers(btf, t->type, &res_id);
9975 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
9978 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
9980 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
9983 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
9985 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
9988 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
9990 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
9993 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
9995 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
9998 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10000 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10003 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10004 const struct btf_param *arg)
10006 const struct btf_type *t;
10008 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10015 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10016 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10017 const struct btf *btf,
10018 const struct btf_type *t, int rec)
10020 const struct btf_type *member_type;
10021 const struct btf_member *member;
10024 if (!btf_type_is_struct(t))
10027 for_each_member(i, t, member) {
10028 const struct btf_array *array;
10030 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10031 if (btf_type_is_struct(member_type)) {
10033 verbose(env, "max struct nesting depth exceeded\n");
10036 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10040 if (btf_type_is_array(member_type)) {
10041 array = btf_array(member_type);
10042 if (!array->nelems)
10044 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10045 if (!btf_type_is_scalar(member_type))
10049 if (!btf_type_is_scalar(member_type))
10056 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
10058 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
10059 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
10060 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
10064 enum kfunc_ptr_arg_type {
10066 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
10067 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10068 KF_ARG_PTR_TO_DYNPTR,
10069 KF_ARG_PTR_TO_ITER,
10070 KF_ARG_PTR_TO_LIST_HEAD,
10071 KF_ARG_PTR_TO_LIST_NODE,
10072 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
10074 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
10075 KF_ARG_PTR_TO_CALLBACK,
10076 KF_ARG_PTR_TO_RB_ROOT,
10077 KF_ARG_PTR_TO_RB_NODE,
10080 enum special_kfunc_type {
10081 KF_bpf_obj_new_impl,
10082 KF_bpf_obj_drop_impl,
10083 KF_bpf_refcount_acquire_impl,
10084 KF_bpf_list_push_front_impl,
10085 KF_bpf_list_push_back_impl,
10086 KF_bpf_list_pop_front,
10087 KF_bpf_list_pop_back,
10088 KF_bpf_cast_to_kern_ctx,
10089 KF_bpf_rdonly_cast,
10090 KF_bpf_rcu_read_lock,
10091 KF_bpf_rcu_read_unlock,
10092 KF_bpf_rbtree_remove,
10093 KF_bpf_rbtree_add_impl,
10094 KF_bpf_rbtree_first,
10095 KF_bpf_dynptr_from_skb,
10096 KF_bpf_dynptr_from_xdp,
10097 KF_bpf_dynptr_slice,
10098 KF_bpf_dynptr_slice_rdwr,
10099 KF_bpf_dynptr_clone,
10102 BTF_SET_START(special_kfunc_set)
10103 BTF_ID(func, bpf_obj_new_impl)
10104 BTF_ID(func, bpf_obj_drop_impl)
10105 BTF_ID(func, bpf_refcount_acquire_impl)
10106 BTF_ID(func, bpf_list_push_front_impl)
10107 BTF_ID(func, bpf_list_push_back_impl)
10108 BTF_ID(func, bpf_list_pop_front)
10109 BTF_ID(func, bpf_list_pop_back)
10110 BTF_ID(func, bpf_cast_to_kern_ctx)
10111 BTF_ID(func, bpf_rdonly_cast)
10112 BTF_ID(func, bpf_rbtree_remove)
10113 BTF_ID(func, bpf_rbtree_add_impl)
10114 BTF_ID(func, bpf_rbtree_first)
10115 BTF_ID(func, bpf_dynptr_from_skb)
10116 BTF_ID(func, bpf_dynptr_from_xdp)
10117 BTF_ID(func, bpf_dynptr_slice)
10118 BTF_ID(func, bpf_dynptr_slice_rdwr)
10119 BTF_ID(func, bpf_dynptr_clone)
10120 BTF_SET_END(special_kfunc_set)
10122 BTF_ID_LIST(special_kfunc_list)
10123 BTF_ID(func, bpf_obj_new_impl)
10124 BTF_ID(func, bpf_obj_drop_impl)
10125 BTF_ID(func, bpf_refcount_acquire_impl)
10126 BTF_ID(func, bpf_list_push_front_impl)
10127 BTF_ID(func, bpf_list_push_back_impl)
10128 BTF_ID(func, bpf_list_pop_front)
10129 BTF_ID(func, bpf_list_pop_back)
10130 BTF_ID(func, bpf_cast_to_kern_ctx)
10131 BTF_ID(func, bpf_rdonly_cast)
10132 BTF_ID(func, bpf_rcu_read_lock)
10133 BTF_ID(func, bpf_rcu_read_unlock)
10134 BTF_ID(func, bpf_rbtree_remove)
10135 BTF_ID(func, bpf_rbtree_add_impl)
10136 BTF_ID(func, bpf_rbtree_first)
10137 BTF_ID(func, bpf_dynptr_from_skb)
10138 BTF_ID(func, bpf_dynptr_from_xdp)
10139 BTF_ID(func, bpf_dynptr_slice)
10140 BTF_ID(func, bpf_dynptr_slice_rdwr)
10141 BTF_ID(func, bpf_dynptr_clone)
10143 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10145 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10146 meta->arg_owning_ref) {
10150 return meta->kfunc_flags & KF_RET_NULL;
10153 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10155 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10158 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10160 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10163 static enum kfunc_ptr_arg_type
10164 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10165 struct bpf_kfunc_call_arg_meta *meta,
10166 const struct btf_type *t, const struct btf_type *ref_t,
10167 const char *ref_tname, const struct btf_param *args,
10168 int argno, int nargs)
10170 u32 regno = argno + 1;
10171 struct bpf_reg_state *regs = cur_regs(env);
10172 struct bpf_reg_state *reg = ®s[regno];
10173 bool arg_mem_size = false;
10175 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10176 return KF_ARG_PTR_TO_CTX;
10178 /* In this function, we verify the kfunc's BTF as per the argument type,
10179 * leaving the rest of the verification with respect to the register
10180 * type to our caller. When a set of conditions hold in the BTF type of
10181 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10183 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10184 return KF_ARG_PTR_TO_CTX;
10186 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10187 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10189 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10190 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10192 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10193 return KF_ARG_PTR_TO_DYNPTR;
10195 if (is_kfunc_arg_iter(meta, argno))
10196 return KF_ARG_PTR_TO_ITER;
10198 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10199 return KF_ARG_PTR_TO_LIST_HEAD;
10201 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10202 return KF_ARG_PTR_TO_LIST_NODE;
10204 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10205 return KF_ARG_PTR_TO_RB_ROOT;
10207 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10208 return KF_ARG_PTR_TO_RB_NODE;
10210 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10211 if (!btf_type_is_struct(ref_t)) {
10212 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10213 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10216 return KF_ARG_PTR_TO_BTF_ID;
10219 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10220 return KF_ARG_PTR_TO_CALLBACK;
10223 if (argno + 1 < nargs &&
10224 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
10225 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
10226 arg_mem_size = true;
10228 /* This is the catch all argument type of register types supported by
10229 * check_helper_mem_access. However, we only allow when argument type is
10230 * pointer to scalar, or struct composed (recursively) of scalars. When
10231 * arg_mem_size is true, the pointer can be void *.
10233 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10234 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10235 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10236 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10239 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10242 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10243 struct bpf_reg_state *reg,
10244 const struct btf_type *ref_t,
10245 const char *ref_tname, u32 ref_id,
10246 struct bpf_kfunc_call_arg_meta *meta,
10249 const struct btf_type *reg_ref_t;
10250 bool strict_type_match = false;
10251 const struct btf *reg_btf;
10252 const char *reg_ref_tname;
10255 if (base_type(reg->type) == PTR_TO_BTF_ID) {
10256 reg_btf = reg->btf;
10257 reg_ref_id = reg->btf_id;
10259 reg_btf = btf_vmlinux;
10260 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10263 /* Enforce strict type matching for calls to kfuncs that are acquiring
10264 * or releasing a reference, or are no-cast aliases. We do _not_
10265 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10266 * as we want to enable BPF programs to pass types that are bitwise
10267 * equivalent without forcing them to explicitly cast with something
10268 * like bpf_cast_to_kern_ctx().
10270 * For example, say we had a type like the following:
10272 * struct bpf_cpumask {
10273 * cpumask_t cpumask;
10274 * refcount_t usage;
10277 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10278 * to a struct cpumask, so it would be safe to pass a struct
10279 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10281 * The philosophy here is similar to how we allow scalars of different
10282 * types to be passed to kfuncs as long as the size is the same. The
10283 * only difference here is that we're simply allowing
10284 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10287 if (is_kfunc_acquire(meta) ||
10288 (is_kfunc_release(meta) && reg->ref_obj_id) ||
10289 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10290 strict_type_match = true;
10292 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10294 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
10295 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10296 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10297 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10298 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10299 btf_type_str(reg_ref_t), reg_ref_tname);
10305 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10307 struct bpf_verifier_state *state = env->cur_state;
10309 if (!state->active_lock.ptr) {
10310 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10314 if (type_flag(reg->type) & NON_OWN_REF) {
10315 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10319 reg->type |= NON_OWN_REF;
10323 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10325 struct bpf_func_state *state, *unused;
10326 struct bpf_reg_state *reg;
10329 state = cur_func(env);
10332 verbose(env, "verifier internal error: ref_obj_id is zero for "
10333 "owning -> non-owning conversion\n");
10337 for (i = 0; i < state->acquired_refs; i++) {
10338 if (state->refs[i].id != ref_obj_id)
10341 /* Clear ref_obj_id here so release_reference doesn't clobber
10344 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10345 if (reg->ref_obj_id == ref_obj_id) {
10346 reg->ref_obj_id = 0;
10347 ref_set_non_owning(env, reg);
10353 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10357 /* Implementation details:
10359 * Each register points to some region of memory, which we define as an
10360 * allocation. Each allocation may embed a bpf_spin_lock which protects any
10361 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10362 * allocation. The lock and the data it protects are colocated in the same
10365 * Hence, everytime a register holds a pointer value pointing to such
10366 * allocation, the verifier preserves a unique reg->id for it.
10368 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10369 * bpf_spin_lock is called.
10371 * To enable this, lock state in the verifier captures two values:
10372 * active_lock.ptr = Register's type specific pointer
10373 * active_lock.id = A unique ID for each register pointer value
10375 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10376 * supported register types.
10378 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10379 * allocated objects is the reg->btf pointer.
10381 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10382 * can establish the provenance of the map value statically for each distinct
10383 * lookup into such maps. They always contain a single map value hence unique
10384 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10386 * So, in case of global variables, they use array maps with max_entries = 1,
10387 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10388 * into the same map value as max_entries is 1, as described above).
10390 * In case of inner map lookups, the inner map pointer has same map_ptr as the
10391 * outer map pointer (in verifier context), but each lookup into an inner map
10392 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10393 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10394 * will get different reg->id assigned to each lookup, hence different
10397 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10398 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10399 * returned from bpf_obj_new. Each allocation receives a new reg->id.
10401 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10406 switch ((int)reg->type) {
10407 case PTR_TO_MAP_VALUE:
10408 ptr = reg->map_ptr;
10410 case PTR_TO_BTF_ID | MEM_ALLOC:
10414 verbose(env, "verifier internal error: unknown reg type for lock check\n");
10419 if (!env->cur_state->active_lock.ptr)
10421 if (env->cur_state->active_lock.ptr != ptr ||
10422 env->cur_state->active_lock.id != id) {
10423 verbose(env, "held lock and object are not in the same allocation\n");
10429 static bool is_bpf_list_api_kfunc(u32 btf_id)
10431 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10432 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10433 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10434 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10437 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10439 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10440 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10441 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10444 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10446 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10447 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10450 static bool is_callback_calling_kfunc(u32 btf_id)
10452 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10455 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10457 return is_bpf_rbtree_api_kfunc(btf_id);
10460 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10461 enum btf_field_type head_field_type,
10466 switch (head_field_type) {
10467 case BPF_LIST_HEAD:
10468 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10471 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10474 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10475 btf_field_type_name(head_field_type));
10480 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10481 btf_field_type_name(head_field_type));
10485 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10486 enum btf_field_type node_field_type,
10491 switch (node_field_type) {
10492 case BPF_LIST_NODE:
10493 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10494 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10497 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10498 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10501 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10502 btf_field_type_name(node_field_type));
10507 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10508 btf_field_type_name(node_field_type));
10513 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10514 struct bpf_reg_state *reg, u32 regno,
10515 struct bpf_kfunc_call_arg_meta *meta,
10516 enum btf_field_type head_field_type,
10517 struct btf_field **head_field)
10519 const char *head_type_name;
10520 struct btf_field *field;
10521 struct btf_record *rec;
10524 if (meta->btf != btf_vmlinux) {
10525 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10529 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10532 head_type_name = btf_field_type_name(head_field_type);
10533 if (!tnum_is_const(reg->var_off)) {
10535 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10536 regno, head_type_name);
10540 rec = reg_btf_record(reg);
10541 head_off = reg->off + reg->var_off.value;
10542 field = btf_record_find(rec, head_off, head_field_type);
10544 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10548 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10549 if (check_reg_allocation_locked(env, reg)) {
10550 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10551 rec->spin_lock_off, head_type_name);
10556 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10559 *head_field = field;
10563 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10564 struct bpf_reg_state *reg, u32 regno,
10565 struct bpf_kfunc_call_arg_meta *meta)
10567 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10568 &meta->arg_list_head.field);
10571 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10572 struct bpf_reg_state *reg, u32 regno,
10573 struct bpf_kfunc_call_arg_meta *meta)
10575 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10576 &meta->arg_rbtree_root.field);
10580 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10581 struct bpf_reg_state *reg, u32 regno,
10582 struct bpf_kfunc_call_arg_meta *meta,
10583 enum btf_field_type head_field_type,
10584 enum btf_field_type node_field_type,
10585 struct btf_field **node_field)
10587 const char *node_type_name;
10588 const struct btf_type *et, *t;
10589 struct btf_field *field;
10592 if (meta->btf != btf_vmlinux) {
10593 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10597 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10600 node_type_name = btf_field_type_name(node_field_type);
10601 if (!tnum_is_const(reg->var_off)) {
10603 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10604 regno, node_type_name);
10608 node_off = reg->off + reg->var_off.value;
10609 field = reg_find_field_offset(reg, node_off, node_field_type);
10610 if (!field || field->offset != node_off) {
10611 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10615 field = *node_field;
10617 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10618 t = btf_type_by_id(reg->btf, reg->btf_id);
10619 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10620 field->graph_root.value_btf_id, true)) {
10621 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10622 "in struct %s, but arg is at offset=%d in struct %s\n",
10623 btf_field_type_name(head_field_type),
10624 btf_field_type_name(node_field_type),
10625 field->graph_root.node_offset,
10626 btf_name_by_offset(field->graph_root.btf, et->name_off),
10627 node_off, btf_name_by_offset(reg->btf, t->name_off));
10630 meta->arg_btf = reg->btf;
10631 meta->arg_btf_id = reg->btf_id;
10633 if (node_off != field->graph_root.node_offset) {
10634 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10635 node_off, btf_field_type_name(node_field_type),
10636 field->graph_root.node_offset,
10637 btf_name_by_offset(field->graph_root.btf, et->name_off));
10644 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10645 struct bpf_reg_state *reg, u32 regno,
10646 struct bpf_kfunc_call_arg_meta *meta)
10648 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10649 BPF_LIST_HEAD, BPF_LIST_NODE,
10650 &meta->arg_list_head.field);
10653 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10654 struct bpf_reg_state *reg, u32 regno,
10655 struct bpf_kfunc_call_arg_meta *meta)
10657 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10658 BPF_RB_ROOT, BPF_RB_NODE,
10659 &meta->arg_rbtree_root.field);
10662 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10665 const char *func_name = meta->func_name, *ref_tname;
10666 const struct btf *btf = meta->btf;
10667 const struct btf_param *args;
10668 struct btf_record *rec;
10672 args = (const struct btf_param *)(meta->func_proto + 1);
10673 nargs = btf_type_vlen(meta->func_proto);
10674 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10675 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10676 MAX_BPF_FUNC_REG_ARGS);
10680 /* Check that BTF function arguments match actual types that the
10683 for (i = 0; i < nargs; i++) {
10684 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
10685 const struct btf_type *t, *ref_t, *resolve_ret;
10686 enum bpf_arg_type arg_type = ARG_DONTCARE;
10687 u32 regno = i + 1, ref_id, type_size;
10688 bool is_ret_buf_sz = false;
10691 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10693 if (is_kfunc_arg_ignore(btf, &args[i]))
10696 if (btf_type_is_scalar(t)) {
10697 if (reg->type != SCALAR_VALUE) {
10698 verbose(env, "R%d is not a scalar\n", regno);
10702 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10703 if (meta->arg_constant.found) {
10704 verbose(env, "verifier internal error: only one constant argument permitted\n");
10707 if (!tnum_is_const(reg->var_off)) {
10708 verbose(env, "R%d must be a known constant\n", regno);
10711 ret = mark_chain_precision(env, regno);
10714 meta->arg_constant.found = true;
10715 meta->arg_constant.value = reg->var_off.value;
10716 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10717 meta->r0_rdonly = true;
10718 is_ret_buf_sz = true;
10719 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10720 is_ret_buf_sz = true;
10723 if (is_ret_buf_sz) {
10724 if (meta->r0_size) {
10725 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10729 if (!tnum_is_const(reg->var_off)) {
10730 verbose(env, "R%d is not a const\n", regno);
10734 meta->r0_size = reg->var_off.value;
10735 ret = mark_chain_precision(env, regno);
10742 if (!btf_type_is_ptr(t)) {
10743 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10747 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10748 (register_is_null(reg) || type_may_be_null(reg->type))) {
10749 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10753 if (reg->ref_obj_id) {
10754 if (is_kfunc_release(meta) && meta->ref_obj_id) {
10755 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10756 regno, reg->ref_obj_id,
10760 meta->ref_obj_id = reg->ref_obj_id;
10761 if (is_kfunc_release(meta))
10762 meta->release_regno = regno;
10765 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10766 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10768 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10769 if (kf_arg_type < 0)
10770 return kf_arg_type;
10772 switch (kf_arg_type) {
10773 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10774 case KF_ARG_PTR_TO_BTF_ID:
10775 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10778 if (!is_trusted_reg(reg)) {
10779 if (!is_kfunc_rcu(meta)) {
10780 verbose(env, "R%d must be referenced or trusted\n", regno);
10783 if (!is_rcu_reg(reg)) {
10784 verbose(env, "R%d must be a rcu pointer\n", regno);
10790 case KF_ARG_PTR_TO_CTX:
10791 /* Trusted arguments have the same offset checks as release arguments */
10792 arg_type |= OBJ_RELEASE;
10794 case KF_ARG_PTR_TO_DYNPTR:
10795 case KF_ARG_PTR_TO_ITER:
10796 case KF_ARG_PTR_TO_LIST_HEAD:
10797 case KF_ARG_PTR_TO_LIST_NODE:
10798 case KF_ARG_PTR_TO_RB_ROOT:
10799 case KF_ARG_PTR_TO_RB_NODE:
10800 case KF_ARG_PTR_TO_MEM:
10801 case KF_ARG_PTR_TO_MEM_SIZE:
10802 case KF_ARG_PTR_TO_CALLBACK:
10803 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10804 /* Trusted by default */
10811 if (is_kfunc_release(meta) && reg->ref_obj_id)
10812 arg_type |= OBJ_RELEASE;
10813 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10817 switch (kf_arg_type) {
10818 case KF_ARG_PTR_TO_CTX:
10819 if (reg->type != PTR_TO_CTX) {
10820 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10824 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10825 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10828 meta->ret_btf_id = ret;
10831 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10832 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10833 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10836 if (!reg->ref_obj_id) {
10837 verbose(env, "allocated object must be referenced\n");
10840 if (meta->btf == btf_vmlinux &&
10841 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10842 meta->arg_btf = reg->btf;
10843 meta->arg_btf_id = reg->btf_id;
10846 case KF_ARG_PTR_TO_DYNPTR:
10848 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
10849 int clone_ref_obj_id = 0;
10851 if (reg->type != PTR_TO_STACK &&
10852 reg->type != CONST_PTR_TO_DYNPTR) {
10853 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
10857 if (reg->type == CONST_PTR_TO_DYNPTR)
10858 dynptr_arg_type |= MEM_RDONLY;
10860 if (is_kfunc_arg_uninit(btf, &args[i]))
10861 dynptr_arg_type |= MEM_UNINIT;
10863 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
10864 dynptr_arg_type |= DYNPTR_TYPE_SKB;
10865 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
10866 dynptr_arg_type |= DYNPTR_TYPE_XDP;
10867 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
10868 (dynptr_arg_type & MEM_UNINIT)) {
10869 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
10871 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
10872 verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
10876 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
10877 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
10878 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
10879 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
10884 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
10888 if (!(dynptr_arg_type & MEM_UNINIT)) {
10889 int id = dynptr_id(env, reg);
10892 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10895 meta->initialized_dynptr.id = id;
10896 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
10897 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
10902 case KF_ARG_PTR_TO_ITER:
10903 ret = process_iter_arg(env, regno, insn_idx, meta);
10907 case KF_ARG_PTR_TO_LIST_HEAD:
10908 if (reg->type != PTR_TO_MAP_VALUE &&
10909 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10910 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10913 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10914 verbose(env, "allocated object must be referenced\n");
10917 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
10921 case KF_ARG_PTR_TO_RB_ROOT:
10922 if (reg->type != PTR_TO_MAP_VALUE &&
10923 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10924 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10927 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10928 verbose(env, "allocated object must be referenced\n");
10931 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
10935 case KF_ARG_PTR_TO_LIST_NODE:
10936 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10937 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10940 if (!reg->ref_obj_id) {
10941 verbose(env, "allocated object must be referenced\n");
10944 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
10948 case KF_ARG_PTR_TO_RB_NODE:
10949 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
10950 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
10951 verbose(env, "rbtree_remove node input must be non-owning ref\n");
10954 if (in_rbtree_lock_required_cb(env)) {
10955 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
10959 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10960 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10963 if (!reg->ref_obj_id) {
10964 verbose(env, "allocated object must be referenced\n");
10969 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
10973 case KF_ARG_PTR_TO_BTF_ID:
10974 /* Only base_type is checked, further checks are done here */
10975 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
10976 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
10977 !reg2btf_ids[base_type(reg->type)]) {
10978 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
10979 verbose(env, "expected %s or socket\n",
10980 reg_type_str(env, base_type(reg->type) |
10981 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
10984 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
10988 case KF_ARG_PTR_TO_MEM:
10989 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
10990 if (IS_ERR(resolve_ret)) {
10991 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
10992 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
10995 ret = check_mem_reg(env, reg, regno, type_size);
10999 case KF_ARG_PTR_TO_MEM_SIZE:
11001 struct bpf_reg_state *buff_reg = ®s[regno];
11002 const struct btf_param *buff_arg = &args[i];
11003 struct bpf_reg_state *size_reg = ®s[regno + 1];
11004 const struct btf_param *size_arg = &args[i + 1];
11006 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11007 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11009 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11014 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11015 if (meta->arg_constant.found) {
11016 verbose(env, "verifier internal error: only one constant argument permitted\n");
11019 if (!tnum_is_const(size_reg->var_off)) {
11020 verbose(env, "R%d must be a known constant\n", regno + 1);
11023 meta->arg_constant.found = true;
11024 meta->arg_constant.value = size_reg->var_off.value;
11027 /* Skip next '__sz' or '__szk' argument */
11031 case KF_ARG_PTR_TO_CALLBACK:
11032 meta->subprogno = reg->subprogno;
11034 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11035 if (!type_is_ptr_alloc_obj(reg->type)) {
11036 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11039 if (!type_is_non_owning_ref(reg->type))
11040 meta->arg_owning_ref = true;
11042 rec = reg_btf_record(reg);
11044 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11048 if (rec->refcount_off < 0) {
11049 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11052 if (rec->refcount_off >= 0) {
11053 verbose(env, "bpf_refcount_acquire calls are disabled for now\n");
11056 meta->arg_btf = reg->btf;
11057 meta->arg_btf_id = reg->btf_id;
11062 if (is_kfunc_release(meta) && !meta->release_regno) {
11063 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11071 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11072 struct bpf_insn *insn,
11073 struct bpf_kfunc_call_arg_meta *meta,
11074 const char **kfunc_name)
11076 const struct btf_type *func, *func_proto;
11077 u32 func_id, *kfunc_flags;
11078 const char *func_name;
11079 struct btf *desc_btf;
11082 *kfunc_name = NULL;
11087 desc_btf = find_kfunc_desc_btf(env, insn->off);
11088 if (IS_ERR(desc_btf))
11089 return PTR_ERR(desc_btf);
11091 func_id = insn->imm;
11092 func = btf_type_by_id(desc_btf, func_id);
11093 func_name = btf_name_by_offset(desc_btf, func->name_off);
11095 *kfunc_name = func_name;
11096 func_proto = btf_type_by_id(desc_btf, func->type);
11098 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11099 if (!kfunc_flags) {
11103 memset(meta, 0, sizeof(*meta));
11104 meta->btf = desc_btf;
11105 meta->func_id = func_id;
11106 meta->kfunc_flags = *kfunc_flags;
11107 meta->func_proto = func_proto;
11108 meta->func_name = func_name;
11113 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11116 const struct btf_type *t, *ptr_type;
11117 u32 i, nargs, ptr_type_id, release_ref_obj_id;
11118 struct bpf_reg_state *regs = cur_regs(env);
11119 const char *func_name, *ptr_type_name;
11120 bool sleepable, rcu_lock, rcu_unlock;
11121 struct bpf_kfunc_call_arg_meta meta;
11122 struct bpf_insn_aux_data *insn_aux;
11123 int err, insn_idx = *insn_idx_p;
11124 const struct btf_param *args;
11125 const struct btf_type *ret_t;
11126 struct btf *desc_btf;
11128 /* skip for now, but return error when we find this in fixup_kfunc_call */
11132 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11133 if (err == -EACCES && func_name)
11134 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11137 desc_btf = meta.btf;
11138 insn_aux = &env->insn_aux_data[insn_idx];
11140 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11142 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11143 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11147 sleepable = is_kfunc_sleepable(&meta);
11148 if (sleepable && !env->prog->aux->sleepable) {
11149 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11153 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11154 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11156 if (env->cur_state->active_rcu_lock) {
11157 struct bpf_func_state *state;
11158 struct bpf_reg_state *reg;
11161 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11163 } else if (rcu_unlock) {
11164 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11165 if (reg->type & MEM_RCU) {
11166 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11167 reg->type |= PTR_UNTRUSTED;
11170 env->cur_state->active_rcu_lock = false;
11171 } else if (sleepable) {
11172 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11175 } else if (rcu_lock) {
11176 env->cur_state->active_rcu_lock = true;
11177 } else if (rcu_unlock) {
11178 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11182 /* Check the arguments */
11183 err = check_kfunc_args(env, &meta, insn_idx);
11186 /* In case of release function, we get register number of refcounted
11187 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11189 if (meta.release_regno) {
11190 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11192 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11193 func_name, meta.func_id);
11198 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11199 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11200 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11201 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11202 insn_aux->insert_off = regs[BPF_REG_2].off;
11203 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11204 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11206 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11207 func_name, meta.func_id);
11211 err = release_reference(env, release_ref_obj_id);
11213 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11214 func_name, meta.func_id);
11219 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11220 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11221 set_rbtree_add_callback_state);
11223 verbose(env, "kfunc %s#%d failed callback verification\n",
11224 func_name, meta.func_id);
11229 for (i = 0; i < CALLER_SAVED_REGS; i++)
11230 mark_reg_not_init(env, regs, caller_saved[i]);
11232 /* Check return type */
11233 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11235 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11236 /* Only exception is bpf_obj_new_impl */
11237 if (meta.btf != btf_vmlinux ||
11238 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11239 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11240 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11245 if (btf_type_is_scalar(t)) {
11246 mark_reg_unknown(env, regs, BPF_REG_0);
11247 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11248 } else if (btf_type_is_ptr(t)) {
11249 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11251 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11252 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11253 struct btf *ret_btf;
11256 if (unlikely(!bpf_global_ma_set))
11259 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11260 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11264 ret_btf = env->prog->aux->btf;
11265 ret_btf_id = meta.arg_constant.value;
11267 /* This may be NULL due to user not supplying a BTF */
11269 verbose(env, "bpf_obj_new requires prog BTF\n");
11273 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11274 if (!ret_t || !__btf_type_is_struct(ret_t)) {
11275 verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11279 mark_reg_known_zero(env, regs, BPF_REG_0);
11280 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11281 regs[BPF_REG_0].btf = ret_btf;
11282 regs[BPF_REG_0].btf_id = ret_btf_id;
11284 insn_aux->obj_new_size = ret_t->size;
11285 insn_aux->kptr_struct_meta =
11286 btf_find_struct_meta(ret_btf, ret_btf_id);
11287 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11288 mark_reg_known_zero(env, regs, BPF_REG_0);
11289 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11290 regs[BPF_REG_0].btf = meta.arg_btf;
11291 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11293 insn_aux->kptr_struct_meta =
11294 btf_find_struct_meta(meta.arg_btf,
11296 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11297 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11298 struct btf_field *field = meta.arg_list_head.field;
11300 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11301 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11302 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11303 struct btf_field *field = meta.arg_rbtree_root.field;
11305 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11306 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11307 mark_reg_known_zero(env, regs, BPF_REG_0);
11308 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11309 regs[BPF_REG_0].btf = desc_btf;
11310 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11311 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11312 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11313 if (!ret_t || !btf_type_is_struct(ret_t)) {
11315 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11319 mark_reg_known_zero(env, regs, BPF_REG_0);
11320 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11321 regs[BPF_REG_0].btf = desc_btf;
11322 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11323 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11324 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11325 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11327 mark_reg_known_zero(env, regs, BPF_REG_0);
11329 if (!meta.arg_constant.found) {
11330 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11334 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11336 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11337 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11339 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11340 regs[BPF_REG_0].type |= MEM_RDONLY;
11342 /* this will set env->seen_direct_write to true */
11343 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11344 verbose(env, "the prog does not allow writes to packet data\n");
11349 if (!meta.initialized_dynptr.id) {
11350 verbose(env, "verifier internal error: no dynptr id\n");
11353 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11355 /* we don't need to set BPF_REG_0's ref obj id
11356 * because packet slices are not refcounted (see
11357 * dynptr_type_refcounted)
11360 verbose(env, "kernel function %s unhandled dynamic return type\n",
11364 } else if (!__btf_type_is_struct(ptr_type)) {
11365 if (!meta.r0_size) {
11368 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11370 meta.r0_rdonly = true;
11373 if (!meta.r0_size) {
11374 ptr_type_name = btf_name_by_offset(desc_btf,
11375 ptr_type->name_off);
11377 "kernel function %s returns pointer type %s %s is not supported\n",
11379 btf_type_str(ptr_type),
11384 mark_reg_known_zero(env, regs, BPF_REG_0);
11385 regs[BPF_REG_0].type = PTR_TO_MEM;
11386 regs[BPF_REG_0].mem_size = meta.r0_size;
11388 if (meta.r0_rdonly)
11389 regs[BPF_REG_0].type |= MEM_RDONLY;
11391 /* Ensures we don't access the memory after a release_reference() */
11392 if (meta.ref_obj_id)
11393 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11395 mark_reg_known_zero(env, regs, BPF_REG_0);
11396 regs[BPF_REG_0].btf = desc_btf;
11397 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11398 regs[BPF_REG_0].btf_id = ptr_type_id;
11401 if (is_kfunc_ret_null(&meta)) {
11402 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11403 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11404 regs[BPF_REG_0].id = ++env->id_gen;
11406 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11407 if (is_kfunc_acquire(&meta)) {
11408 int id = acquire_reference_state(env, insn_idx);
11412 if (is_kfunc_ret_null(&meta))
11413 regs[BPF_REG_0].id = id;
11414 regs[BPF_REG_0].ref_obj_id = id;
11415 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11416 ref_set_non_owning(env, ®s[BPF_REG_0]);
11419 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
11420 regs[BPF_REG_0].id = ++env->id_gen;
11421 } else if (btf_type_is_void(t)) {
11422 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11423 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11424 insn_aux->kptr_struct_meta =
11425 btf_find_struct_meta(meta.arg_btf,
11431 nargs = btf_type_vlen(meta.func_proto);
11432 args = (const struct btf_param *)(meta.func_proto + 1);
11433 for (i = 0; i < nargs; i++) {
11436 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11437 if (btf_type_is_ptr(t))
11438 mark_btf_func_reg_size(env, regno, sizeof(void *));
11440 /* scalar. ensured by btf_check_kfunc_arg_match() */
11441 mark_btf_func_reg_size(env, regno, t->size);
11444 if (is_iter_next_kfunc(&meta)) {
11445 err = process_iter_next_call(env, insn_idx, &meta);
11453 static bool signed_add_overflows(s64 a, s64 b)
11455 /* Do the add in u64, where overflow is well-defined */
11456 s64 res = (s64)((u64)a + (u64)b);
11463 static bool signed_add32_overflows(s32 a, s32 b)
11465 /* Do the add in u32, where overflow is well-defined */
11466 s32 res = (s32)((u32)a + (u32)b);
11473 static bool signed_sub_overflows(s64 a, s64 b)
11475 /* Do the sub in u64, where overflow is well-defined */
11476 s64 res = (s64)((u64)a - (u64)b);
11483 static bool signed_sub32_overflows(s32 a, s32 b)
11485 /* Do the sub in u32, where overflow is well-defined */
11486 s32 res = (s32)((u32)a - (u32)b);
11493 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11494 const struct bpf_reg_state *reg,
11495 enum bpf_reg_type type)
11497 bool known = tnum_is_const(reg->var_off);
11498 s64 val = reg->var_off.value;
11499 s64 smin = reg->smin_value;
11501 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11502 verbose(env, "math between %s pointer and %lld is not allowed\n",
11503 reg_type_str(env, type), val);
11507 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11508 verbose(env, "%s pointer offset %d is not allowed\n",
11509 reg_type_str(env, type), reg->off);
11513 if (smin == S64_MIN) {
11514 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11515 reg_type_str(env, type));
11519 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11520 verbose(env, "value %lld makes %s pointer be out of bounds\n",
11521 smin, reg_type_str(env, type));
11529 REASON_BOUNDS = -1,
11536 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11537 u32 *alu_limit, bool mask_to_left)
11539 u32 max = 0, ptr_limit = 0;
11541 switch (ptr_reg->type) {
11543 /* Offset 0 is out-of-bounds, but acceptable start for the
11544 * left direction, see BPF_REG_FP. Also, unknown scalar
11545 * offset where we would need to deal with min/max bounds is
11546 * currently prohibited for unprivileged.
11548 max = MAX_BPF_STACK + mask_to_left;
11549 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11551 case PTR_TO_MAP_VALUE:
11552 max = ptr_reg->map_ptr->value_size;
11553 ptr_limit = (mask_to_left ?
11554 ptr_reg->smin_value :
11555 ptr_reg->umax_value) + ptr_reg->off;
11558 return REASON_TYPE;
11561 if (ptr_limit >= max)
11562 return REASON_LIMIT;
11563 *alu_limit = ptr_limit;
11567 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11568 const struct bpf_insn *insn)
11570 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11573 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11574 u32 alu_state, u32 alu_limit)
11576 /* If we arrived here from different branches with different
11577 * state or limits to sanitize, then this won't work.
11579 if (aux->alu_state &&
11580 (aux->alu_state != alu_state ||
11581 aux->alu_limit != alu_limit))
11582 return REASON_PATHS;
11584 /* Corresponding fixup done in do_misc_fixups(). */
11585 aux->alu_state = alu_state;
11586 aux->alu_limit = alu_limit;
11590 static int sanitize_val_alu(struct bpf_verifier_env *env,
11591 struct bpf_insn *insn)
11593 struct bpf_insn_aux_data *aux = cur_aux(env);
11595 if (can_skip_alu_sanitation(env, insn))
11598 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11601 static bool sanitize_needed(u8 opcode)
11603 return opcode == BPF_ADD || opcode == BPF_SUB;
11606 struct bpf_sanitize_info {
11607 struct bpf_insn_aux_data aux;
11611 static struct bpf_verifier_state *
11612 sanitize_speculative_path(struct bpf_verifier_env *env,
11613 const struct bpf_insn *insn,
11614 u32 next_idx, u32 curr_idx)
11616 struct bpf_verifier_state *branch;
11617 struct bpf_reg_state *regs;
11619 branch = push_stack(env, next_idx, curr_idx, true);
11620 if (branch && insn) {
11621 regs = branch->frame[branch->curframe]->regs;
11622 if (BPF_SRC(insn->code) == BPF_K) {
11623 mark_reg_unknown(env, regs, insn->dst_reg);
11624 } else if (BPF_SRC(insn->code) == BPF_X) {
11625 mark_reg_unknown(env, regs, insn->dst_reg);
11626 mark_reg_unknown(env, regs, insn->src_reg);
11632 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11633 struct bpf_insn *insn,
11634 const struct bpf_reg_state *ptr_reg,
11635 const struct bpf_reg_state *off_reg,
11636 struct bpf_reg_state *dst_reg,
11637 struct bpf_sanitize_info *info,
11638 const bool commit_window)
11640 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11641 struct bpf_verifier_state *vstate = env->cur_state;
11642 bool off_is_imm = tnum_is_const(off_reg->var_off);
11643 bool off_is_neg = off_reg->smin_value < 0;
11644 bool ptr_is_dst_reg = ptr_reg == dst_reg;
11645 u8 opcode = BPF_OP(insn->code);
11646 u32 alu_state, alu_limit;
11647 struct bpf_reg_state tmp;
11651 if (can_skip_alu_sanitation(env, insn))
11654 /* We already marked aux for masking from non-speculative
11655 * paths, thus we got here in the first place. We only care
11656 * to explore bad access from here.
11658 if (vstate->speculative)
11661 if (!commit_window) {
11662 if (!tnum_is_const(off_reg->var_off) &&
11663 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11664 return REASON_BOUNDS;
11666 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
11667 (opcode == BPF_SUB && !off_is_neg);
11670 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11674 if (commit_window) {
11675 /* In commit phase we narrow the masking window based on
11676 * the observed pointer move after the simulated operation.
11678 alu_state = info->aux.alu_state;
11679 alu_limit = abs(info->aux.alu_limit - alu_limit);
11681 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11682 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11683 alu_state |= ptr_is_dst_reg ?
11684 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11686 /* Limit pruning on unknown scalars to enable deep search for
11687 * potential masking differences from other program paths.
11690 env->explore_alu_limits = true;
11693 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11697 /* If we're in commit phase, we're done here given we already
11698 * pushed the truncated dst_reg into the speculative verification
11701 * Also, when register is a known constant, we rewrite register-based
11702 * operation to immediate-based, and thus do not need masking (and as
11703 * a consequence, do not need to simulate the zero-truncation either).
11705 if (commit_window || off_is_imm)
11708 /* Simulate and find potential out-of-bounds access under
11709 * speculative execution from truncation as a result of
11710 * masking when off was not within expected range. If off
11711 * sits in dst, then we temporarily need to move ptr there
11712 * to simulate dst (== 0) +/-= ptr. Needed, for example,
11713 * for cases where we use K-based arithmetic in one direction
11714 * and truncated reg-based in the other in order to explore
11717 if (!ptr_is_dst_reg) {
11719 copy_register_state(dst_reg, ptr_reg);
11721 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11723 if (!ptr_is_dst_reg && ret)
11725 return !ret ? REASON_STACK : 0;
11728 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11730 struct bpf_verifier_state *vstate = env->cur_state;
11732 /* If we simulate paths under speculation, we don't update the
11733 * insn as 'seen' such that when we verify unreachable paths in
11734 * the non-speculative domain, sanitize_dead_code() can still
11735 * rewrite/sanitize them.
11737 if (!vstate->speculative)
11738 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11741 static int sanitize_err(struct bpf_verifier_env *env,
11742 const struct bpf_insn *insn, int reason,
11743 const struct bpf_reg_state *off_reg,
11744 const struct bpf_reg_state *dst_reg)
11746 static const char *err = "pointer arithmetic with it prohibited for !root";
11747 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11748 u32 dst = insn->dst_reg, src = insn->src_reg;
11751 case REASON_BOUNDS:
11752 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11753 off_reg == dst_reg ? dst : src, err);
11756 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11757 off_reg == dst_reg ? src : dst, err);
11760 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11764 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11768 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11772 verbose(env, "verifier internal error: unknown reason (%d)\n",
11780 /* check that stack access falls within stack limits and that 'reg' doesn't
11781 * have a variable offset.
11783 * Variable offset is prohibited for unprivileged mode for simplicity since it
11784 * requires corresponding support in Spectre masking for stack ALU. See also
11785 * retrieve_ptr_limit().
11788 * 'off' includes 'reg->off'.
11790 static int check_stack_access_for_ptr_arithmetic(
11791 struct bpf_verifier_env *env,
11793 const struct bpf_reg_state *reg,
11796 if (!tnum_is_const(reg->var_off)) {
11799 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11800 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11801 regno, tn_buf, off);
11805 if (off >= 0 || off < -MAX_BPF_STACK) {
11806 verbose(env, "R%d stack pointer arithmetic goes out of range, "
11807 "prohibited for !root; off=%d\n", regno, off);
11814 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11815 const struct bpf_insn *insn,
11816 const struct bpf_reg_state *dst_reg)
11818 u32 dst = insn->dst_reg;
11820 /* For unprivileged we require that resulting offset must be in bounds
11821 * in order to be able to sanitize access later on.
11823 if (env->bypass_spec_v1)
11826 switch (dst_reg->type) {
11828 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11829 dst_reg->off + dst_reg->var_off.value))
11832 case PTR_TO_MAP_VALUE:
11833 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
11834 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
11835 "prohibited for !root\n", dst);
11846 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
11847 * Caller should also handle BPF_MOV case separately.
11848 * If we return -EACCES, caller may want to try again treating pointer as a
11849 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
11851 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
11852 struct bpf_insn *insn,
11853 const struct bpf_reg_state *ptr_reg,
11854 const struct bpf_reg_state *off_reg)
11856 struct bpf_verifier_state *vstate = env->cur_state;
11857 struct bpf_func_state *state = vstate->frame[vstate->curframe];
11858 struct bpf_reg_state *regs = state->regs, *dst_reg;
11859 bool known = tnum_is_const(off_reg->var_off);
11860 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
11861 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
11862 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
11863 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
11864 struct bpf_sanitize_info info = {};
11865 u8 opcode = BPF_OP(insn->code);
11866 u32 dst = insn->dst_reg;
11869 dst_reg = ®s[dst];
11871 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
11872 smin_val > smax_val || umin_val > umax_val) {
11873 /* Taint dst register if offset had invalid bounds derived from
11874 * e.g. dead branches.
11876 __mark_reg_unknown(env, dst_reg);
11880 if (BPF_CLASS(insn->code) != BPF_ALU64) {
11881 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
11882 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11883 __mark_reg_unknown(env, dst_reg);
11888 "R%d 32-bit pointer arithmetic prohibited\n",
11893 if (ptr_reg->type & PTR_MAYBE_NULL) {
11894 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
11895 dst, reg_type_str(env, ptr_reg->type));
11899 switch (base_type(ptr_reg->type)) {
11900 case CONST_PTR_TO_MAP:
11901 /* smin_val represents the known value */
11902 if (known && smin_val == 0 && opcode == BPF_ADD)
11905 case PTR_TO_PACKET_END:
11906 case PTR_TO_SOCKET:
11907 case PTR_TO_SOCK_COMMON:
11908 case PTR_TO_TCP_SOCK:
11909 case PTR_TO_XDP_SOCK:
11910 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
11911 dst, reg_type_str(env, ptr_reg->type));
11917 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
11918 * The id may be overwritten later if we create a new variable offset.
11920 dst_reg->type = ptr_reg->type;
11921 dst_reg->id = ptr_reg->id;
11923 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
11924 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
11927 /* pointer types do not carry 32-bit bounds at the moment. */
11928 __mark_reg32_unbounded(dst_reg);
11930 if (sanitize_needed(opcode)) {
11931 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
11934 return sanitize_err(env, insn, ret, off_reg, dst_reg);
11939 /* We can take a fixed offset as long as it doesn't overflow
11940 * the s32 'off' field
11942 if (known && (ptr_reg->off + smin_val ==
11943 (s64)(s32)(ptr_reg->off + smin_val))) {
11944 /* pointer += K. Accumulate it into fixed offset */
11945 dst_reg->smin_value = smin_ptr;
11946 dst_reg->smax_value = smax_ptr;
11947 dst_reg->umin_value = umin_ptr;
11948 dst_reg->umax_value = umax_ptr;
11949 dst_reg->var_off = ptr_reg->var_off;
11950 dst_reg->off = ptr_reg->off + smin_val;
11951 dst_reg->raw = ptr_reg->raw;
11954 /* A new variable offset is created. Note that off_reg->off
11955 * == 0, since it's a scalar.
11956 * dst_reg gets the pointer type and since some positive
11957 * integer value was added to the pointer, give it a new 'id'
11958 * if it's a PTR_TO_PACKET.
11959 * this creates a new 'base' pointer, off_reg (variable) gets
11960 * added into the variable offset, and we copy the fixed offset
11963 if (signed_add_overflows(smin_ptr, smin_val) ||
11964 signed_add_overflows(smax_ptr, smax_val)) {
11965 dst_reg->smin_value = S64_MIN;
11966 dst_reg->smax_value = S64_MAX;
11968 dst_reg->smin_value = smin_ptr + smin_val;
11969 dst_reg->smax_value = smax_ptr + smax_val;
11971 if (umin_ptr + umin_val < umin_ptr ||
11972 umax_ptr + umax_val < umax_ptr) {
11973 dst_reg->umin_value = 0;
11974 dst_reg->umax_value = U64_MAX;
11976 dst_reg->umin_value = umin_ptr + umin_val;
11977 dst_reg->umax_value = umax_ptr + umax_val;
11979 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
11980 dst_reg->off = ptr_reg->off;
11981 dst_reg->raw = ptr_reg->raw;
11982 if (reg_is_pkt_pointer(ptr_reg)) {
11983 dst_reg->id = ++env->id_gen;
11984 /* something was added to pkt_ptr, set range to zero */
11985 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11989 if (dst_reg == off_reg) {
11990 /* scalar -= pointer. Creates an unknown scalar */
11991 verbose(env, "R%d tried to subtract pointer from scalar\n",
11995 /* We don't allow subtraction from FP, because (according to
11996 * test_verifier.c test "invalid fp arithmetic", JITs might not
11997 * be able to deal with it.
11999 if (ptr_reg->type == PTR_TO_STACK) {
12000 verbose(env, "R%d subtraction from stack pointer prohibited\n",
12004 if (known && (ptr_reg->off - smin_val ==
12005 (s64)(s32)(ptr_reg->off - smin_val))) {
12006 /* pointer -= K. Subtract it from fixed offset */
12007 dst_reg->smin_value = smin_ptr;
12008 dst_reg->smax_value = smax_ptr;
12009 dst_reg->umin_value = umin_ptr;
12010 dst_reg->umax_value = umax_ptr;
12011 dst_reg->var_off = ptr_reg->var_off;
12012 dst_reg->id = ptr_reg->id;
12013 dst_reg->off = ptr_reg->off - smin_val;
12014 dst_reg->raw = ptr_reg->raw;
12017 /* A new variable offset is created. If the subtrahend is known
12018 * nonnegative, then any reg->range we had before is still good.
12020 if (signed_sub_overflows(smin_ptr, smax_val) ||
12021 signed_sub_overflows(smax_ptr, smin_val)) {
12022 /* Overflow possible, we know nothing */
12023 dst_reg->smin_value = S64_MIN;
12024 dst_reg->smax_value = S64_MAX;
12026 dst_reg->smin_value = smin_ptr - smax_val;
12027 dst_reg->smax_value = smax_ptr - smin_val;
12029 if (umin_ptr < umax_val) {
12030 /* Overflow possible, we know nothing */
12031 dst_reg->umin_value = 0;
12032 dst_reg->umax_value = U64_MAX;
12034 /* Cannot overflow (as long as bounds are consistent) */
12035 dst_reg->umin_value = umin_ptr - umax_val;
12036 dst_reg->umax_value = umax_ptr - umin_val;
12038 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12039 dst_reg->off = ptr_reg->off;
12040 dst_reg->raw = ptr_reg->raw;
12041 if (reg_is_pkt_pointer(ptr_reg)) {
12042 dst_reg->id = ++env->id_gen;
12043 /* something was added to pkt_ptr, set range to zero */
12045 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12051 /* bitwise ops on pointers are troublesome, prohibit. */
12052 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12053 dst, bpf_alu_string[opcode >> 4]);
12056 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12057 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12058 dst, bpf_alu_string[opcode >> 4]);
12062 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12064 reg_bounds_sync(dst_reg);
12065 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12067 if (sanitize_needed(opcode)) {
12068 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12071 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12077 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12078 struct bpf_reg_state *src_reg)
12080 s32 smin_val = src_reg->s32_min_value;
12081 s32 smax_val = src_reg->s32_max_value;
12082 u32 umin_val = src_reg->u32_min_value;
12083 u32 umax_val = src_reg->u32_max_value;
12085 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12086 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12087 dst_reg->s32_min_value = S32_MIN;
12088 dst_reg->s32_max_value = S32_MAX;
12090 dst_reg->s32_min_value += smin_val;
12091 dst_reg->s32_max_value += smax_val;
12093 if (dst_reg->u32_min_value + umin_val < umin_val ||
12094 dst_reg->u32_max_value + umax_val < umax_val) {
12095 dst_reg->u32_min_value = 0;
12096 dst_reg->u32_max_value = U32_MAX;
12098 dst_reg->u32_min_value += umin_val;
12099 dst_reg->u32_max_value += umax_val;
12103 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12104 struct bpf_reg_state *src_reg)
12106 s64 smin_val = src_reg->smin_value;
12107 s64 smax_val = src_reg->smax_value;
12108 u64 umin_val = src_reg->umin_value;
12109 u64 umax_val = src_reg->umax_value;
12111 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12112 signed_add_overflows(dst_reg->smax_value, smax_val)) {
12113 dst_reg->smin_value = S64_MIN;
12114 dst_reg->smax_value = S64_MAX;
12116 dst_reg->smin_value += smin_val;
12117 dst_reg->smax_value += smax_val;
12119 if (dst_reg->umin_value + umin_val < umin_val ||
12120 dst_reg->umax_value + umax_val < umax_val) {
12121 dst_reg->umin_value = 0;
12122 dst_reg->umax_value = U64_MAX;
12124 dst_reg->umin_value += umin_val;
12125 dst_reg->umax_value += umax_val;
12129 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12130 struct bpf_reg_state *src_reg)
12132 s32 smin_val = src_reg->s32_min_value;
12133 s32 smax_val = src_reg->s32_max_value;
12134 u32 umin_val = src_reg->u32_min_value;
12135 u32 umax_val = src_reg->u32_max_value;
12137 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12138 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12139 /* Overflow possible, we know nothing */
12140 dst_reg->s32_min_value = S32_MIN;
12141 dst_reg->s32_max_value = S32_MAX;
12143 dst_reg->s32_min_value -= smax_val;
12144 dst_reg->s32_max_value -= smin_val;
12146 if (dst_reg->u32_min_value < umax_val) {
12147 /* Overflow possible, we know nothing */
12148 dst_reg->u32_min_value = 0;
12149 dst_reg->u32_max_value = U32_MAX;
12151 /* Cannot overflow (as long as bounds are consistent) */
12152 dst_reg->u32_min_value -= umax_val;
12153 dst_reg->u32_max_value -= umin_val;
12157 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12158 struct bpf_reg_state *src_reg)
12160 s64 smin_val = src_reg->smin_value;
12161 s64 smax_val = src_reg->smax_value;
12162 u64 umin_val = src_reg->umin_value;
12163 u64 umax_val = src_reg->umax_value;
12165 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12166 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12167 /* Overflow possible, we know nothing */
12168 dst_reg->smin_value = S64_MIN;
12169 dst_reg->smax_value = S64_MAX;
12171 dst_reg->smin_value -= smax_val;
12172 dst_reg->smax_value -= smin_val;
12174 if (dst_reg->umin_value < umax_val) {
12175 /* Overflow possible, we know nothing */
12176 dst_reg->umin_value = 0;
12177 dst_reg->umax_value = U64_MAX;
12179 /* Cannot overflow (as long as bounds are consistent) */
12180 dst_reg->umin_value -= umax_val;
12181 dst_reg->umax_value -= umin_val;
12185 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12186 struct bpf_reg_state *src_reg)
12188 s32 smin_val = src_reg->s32_min_value;
12189 u32 umin_val = src_reg->u32_min_value;
12190 u32 umax_val = src_reg->u32_max_value;
12192 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12193 /* Ain't nobody got time to multiply that sign */
12194 __mark_reg32_unbounded(dst_reg);
12197 /* Both values are positive, so we can work with unsigned and
12198 * copy the result to signed (unless it exceeds S32_MAX).
12200 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12201 /* Potential overflow, we know nothing */
12202 __mark_reg32_unbounded(dst_reg);
12205 dst_reg->u32_min_value *= umin_val;
12206 dst_reg->u32_max_value *= umax_val;
12207 if (dst_reg->u32_max_value > S32_MAX) {
12208 /* Overflow possible, we know nothing */
12209 dst_reg->s32_min_value = S32_MIN;
12210 dst_reg->s32_max_value = S32_MAX;
12212 dst_reg->s32_min_value = dst_reg->u32_min_value;
12213 dst_reg->s32_max_value = dst_reg->u32_max_value;
12217 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12218 struct bpf_reg_state *src_reg)
12220 s64 smin_val = src_reg->smin_value;
12221 u64 umin_val = src_reg->umin_value;
12222 u64 umax_val = src_reg->umax_value;
12224 if (smin_val < 0 || dst_reg->smin_value < 0) {
12225 /* Ain't nobody got time to multiply that sign */
12226 __mark_reg64_unbounded(dst_reg);
12229 /* Both values are positive, so we can work with unsigned and
12230 * copy the result to signed (unless it exceeds S64_MAX).
12232 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12233 /* Potential overflow, we know nothing */
12234 __mark_reg64_unbounded(dst_reg);
12237 dst_reg->umin_value *= umin_val;
12238 dst_reg->umax_value *= umax_val;
12239 if (dst_reg->umax_value > S64_MAX) {
12240 /* Overflow possible, we know nothing */
12241 dst_reg->smin_value = S64_MIN;
12242 dst_reg->smax_value = S64_MAX;
12244 dst_reg->smin_value = dst_reg->umin_value;
12245 dst_reg->smax_value = dst_reg->umax_value;
12249 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12250 struct bpf_reg_state *src_reg)
12252 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12253 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12254 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12255 s32 smin_val = src_reg->s32_min_value;
12256 u32 umax_val = src_reg->u32_max_value;
12258 if (src_known && dst_known) {
12259 __mark_reg32_known(dst_reg, var32_off.value);
12263 /* We get our minimum from the var_off, since that's inherently
12264 * bitwise. Our maximum is the minimum of the operands' maxima.
12266 dst_reg->u32_min_value = var32_off.value;
12267 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12268 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12269 /* Lose signed bounds when ANDing negative numbers,
12270 * ain't nobody got time for that.
12272 dst_reg->s32_min_value = S32_MIN;
12273 dst_reg->s32_max_value = S32_MAX;
12275 /* ANDing two positives gives a positive, so safe to
12276 * cast result into s64.
12278 dst_reg->s32_min_value = dst_reg->u32_min_value;
12279 dst_reg->s32_max_value = dst_reg->u32_max_value;
12283 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12284 struct bpf_reg_state *src_reg)
12286 bool src_known = tnum_is_const(src_reg->var_off);
12287 bool dst_known = tnum_is_const(dst_reg->var_off);
12288 s64 smin_val = src_reg->smin_value;
12289 u64 umax_val = src_reg->umax_value;
12291 if (src_known && dst_known) {
12292 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12296 /* We get our minimum from the var_off, since that's inherently
12297 * bitwise. Our maximum is the minimum of the operands' maxima.
12299 dst_reg->umin_value = dst_reg->var_off.value;
12300 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12301 if (dst_reg->smin_value < 0 || smin_val < 0) {
12302 /* Lose signed bounds when ANDing negative numbers,
12303 * ain't nobody got time for that.
12305 dst_reg->smin_value = S64_MIN;
12306 dst_reg->smax_value = S64_MAX;
12308 /* ANDing two positives gives a positive, so safe to
12309 * cast result into s64.
12311 dst_reg->smin_value = dst_reg->umin_value;
12312 dst_reg->smax_value = dst_reg->umax_value;
12314 /* We may learn something more from the var_off */
12315 __update_reg_bounds(dst_reg);
12318 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12319 struct bpf_reg_state *src_reg)
12321 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12322 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12323 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12324 s32 smin_val = src_reg->s32_min_value;
12325 u32 umin_val = src_reg->u32_min_value;
12327 if (src_known && dst_known) {
12328 __mark_reg32_known(dst_reg, var32_off.value);
12332 /* We get our maximum from the var_off, and our minimum is the
12333 * maximum of the operands' minima
12335 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12336 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12337 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12338 /* Lose signed bounds when ORing negative numbers,
12339 * ain't nobody got time for that.
12341 dst_reg->s32_min_value = S32_MIN;
12342 dst_reg->s32_max_value = S32_MAX;
12344 /* ORing two positives gives a positive, so safe to
12345 * cast result into s64.
12347 dst_reg->s32_min_value = dst_reg->u32_min_value;
12348 dst_reg->s32_max_value = dst_reg->u32_max_value;
12352 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12353 struct bpf_reg_state *src_reg)
12355 bool src_known = tnum_is_const(src_reg->var_off);
12356 bool dst_known = tnum_is_const(dst_reg->var_off);
12357 s64 smin_val = src_reg->smin_value;
12358 u64 umin_val = src_reg->umin_value;
12360 if (src_known && dst_known) {
12361 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12365 /* We get our maximum from the var_off, and our minimum is the
12366 * maximum of the operands' minima
12368 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12369 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12370 if (dst_reg->smin_value < 0 || smin_val < 0) {
12371 /* Lose signed bounds when ORing negative numbers,
12372 * ain't nobody got time for that.
12374 dst_reg->smin_value = S64_MIN;
12375 dst_reg->smax_value = S64_MAX;
12377 /* ORing two positives gives a positive, so safe to
12378 * cast result into s64.
12380 dst_reg->smin_value = dst_reg->umin_value;
12381 dst_reg->smax_value = dst_reg->umax_value;
12383 /* We may learn something more from the var_off */
12384 __update_reg_bounds(dst_reg);
12387 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12388 struct bpf_reg_state *src_reg)
12390 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12391 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12392 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12393 s32 smin_val = src_reg->s32_min_value;
12395 if (src_known && dst_known) {
12396 __mark_reg32_known(dst_reg, var32_off.value);
12400 /* We get both minimum and maximum from the var32_off. */
12401 dst_reg->u32_min_value = var32_off.value;
12402 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12404 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12405 /* XORing two positive sign numbers gives a positive,
12406 * so safe to cast u32 result into s32.
12408 dst_reg->s32_min_value = dst_reg->u32_min_value;
12409 dst_reg->s32_max_value = dst_reg->u32_max_value;
12411 dst_reg->s32_min_value = S32_MIN;
12412 dst_reg->s32_max_value = S32_MAX;
12416 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12417 struct bpf_reg_state *src_reg)
12419 bool src_known = tnum_is_const(src_reg->var_off);
12420 bool dst_known = tnum_is_const(dst_reg->var_off);
12421 s64 smin_val = src_reg->smin_value;
12423 if (src_known && dst_known) {
12424 /* dst_reg->var_off.value has been updated earlier */
12425 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12429 /* We get both minimum and maximum from the var_off. */
12430 dst_reg->umin_value = dst_reg->var_off.value;
12431 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12433 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12434 /* XORing two positive sign numbers gives a positive,
12435 * so safe to cast u64 result into s64.
12437 dst_reg->smin_value = dst_reg->umin_value;
12438 dst_reg->smax_value = dst_reg->umax_value;
12440 dst_reg->smin_value = S64_MIN;
12441 dst_reg->smax_value = S64_MAX;
12444 __update_reg_bounds(dst_reg);
12447 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12448 u64 umin_val, u64 umax_val)
12450 /* We lose all sign bit information (except what we can pick
12453 dst_reg->s32_min_value = S32_MIN;
12454 dst_reg->s32_max_value = S32_MAX;
12455 /* If we might shift our top bit out, then we know nothing */
12456 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12457 dst_reg->u32_min_value = 0;
12458 dst_reg->u32_max_value = U32_MAX;
12460 dst_reg->u32_min_value <<= umin_val;
12461 dst_reg->u32_max_value <<= umax_val;
12465 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12466 struct bpf_reg_state *src_reg)
12468 u32 umax_val = src_reg->u32_max_value;
12469 u32 umin_val = src_reg->u32_min_value;
12470 /* u32 alu operation will zext upper bits */
12471 struct tnum subreg = tnum_subreg(dst_reg->var_off);
12473 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12474 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12475 /* Not required but being careful mark reg64 bounds as unknown so
12476 * that we are forced to pick them up from tnum and zext later and
12477 * if some path skips this step we are still safe.
12479 __mark_reg64_unbounded(dst_reg);
12480 __update_reg32_bounds(dst_reg);
12483 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12484 u64 umin_val, u64 umax_val)
12486 /* Special case <<32 because it is a common compiler pattern to sign
12487 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12488 * positive we know this shift will also be positive so we can track
12489 * bounds correctly. Otherwise we lose all sign bit information except
12490 * what we can pick up from var_off. Perhaps we can generalize this
12491 * later to shifts of any length.
12493 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12494 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12496 dst_reg->smax_value = S64_MAX;
12498 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12499 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12501 dst_reg->smin_value = S64_MIN;
12503 /* If we might shift our top bit out, then we know nothing */
12504 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12505 dst_reg->umin_value = 0;
12506 dst_reg->umax_value = U64_MAX;
12508 dst_reg->umin_value <<= umin_val;
12509 dst_reg->umax_value <<= umax_val;
12513 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12514 struct bpf_reg_state *src_reg)
12516 u64 umax_val = src_reg->umax_value;
12517 u64 umin_val = src_reg->umin_value;
12519 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
12520 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12521 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12523 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12524 /* We may learn something more from the var_off */
12525 __update_reg_bounds(dst_reg);
12528 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12529 struct bpf_reg_state *src_reg)
12531 struct tnum subreg = tnum_subreg(dst_reg->var_off);
12532 u32 umax_val = src_reg->u32_max_value;
12533 u32 umin_val = src_reg->u32_min_value;
12535 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12536 * be negative, then either:
12537 * 1) src_reg might be zero, so the sign bit of the result is
12538 * unknown, so we lose our signed bounds
12539 * 2) it's known negative, thus the unsigned bounds capture the
12541 * 3) the signed bounds cross zero, so they tell us nothing
12543 * If the value in dst_reg is known nonnegative, then again the
12544 * unsigned bounds capture the signed bounds.
12545 * Thus, in all cases it suffices to blow away our signed bounds
12546 * and rely on inferring new ones from the unsigned bounds and
12547 * var_off of the result.
12549 dst_reg->s32_min_value = S32_MIN;
12550 dst_reg->s32_max_value = S32_MAX;
12552 dst_reg->var_off = tnum_rshift(subreg, umin_val);
12553 dst_reg->u32_min_value >>= umax_val;
12554 dst_reg->u32_max_value >>= umin_val;
12556 __mark_reg64_unbounded(dst_reg);
12557 __update_reg32_bounds(dst_reg);
12560 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12561 struct bpf_reg_state *src_reg)
12563 u64 umax_val = src_reg->umax_value;
12564 u64 umin_val = src_reg->umin_value;
12566 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
12567 * be negative, then either:
12568 * 1) src_reg might be zero, so the sign bit of the result is
12569 * unknown, so we lose our signed bounds
12570 * 2) it's known negative, thus the unsigned bounds capture the
12572 * 3) the signed bounds cross zero, so they tell us nothing
12574 * If the value in dst_reg is known nonnegative, then again the
12575 * unsigned bounds capture the signed bounds.
12576 * Thus, in all cases it suffices to blow away our signed bounds
12577 * and rely on inferring new ones from the unsigned bounds and
12578 * var_off of the result.
12580 dst_reg->smin_value = S64_MIN;
12581 dst_reg->smax_value = S64_MAX;
12582 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12583 dst_reg->umin_value >>= umax_val;
12584 dst_reg->umax_value >>= umin_val;
12586 /* Its not easy to operate on alu32 bounds here because it depends
12587 * on bits being shifted in. Take easy way out and mark unbounded
12588 * so we can recalculate later from tnum.
12590 __mark_reg32_unbounded(dst_reg);
12591 __update_reg_bounds(dst_reg);
12594 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12595 struct bpf_reg_state *src_reg)
12597 u64 umin_val = src_reg->u32_min_value;
12599 /* Upon reaching here, src_known is true and
12600 * umax_val is equal to umin_val.
12602 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12603 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12605 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12607 /* blow away the dst_reg umin_value/umax_value and rely on
12608 * dst_reg var_off to refine the result.
12610 dst_reg->u32_min_value = 0;
12611 dst_reg->u32_max_value = U32_MAX;
12613 __mark_reg64_unbounded(dst_reg);
12614 __update_reg32_bounds(dst_reg);
12617 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12618 struct bpf_reg_state *src_reg)
12620 u64 umin_val = src_reg->umin_value;
12622 /* Upon reaching here, src_known is true and umax_val is equal
12625 dst_reg->smin_value >>= umin_val;
12626 dst_reg->smax_value >>= umin_val;
12628 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12630 /* blow away the dst_reg umin_value/umax_value and rely on
12631 * dst_reg var_off to refine the result.
12633 dst_reg->umin_value = 0;
12634 dst_reg->umax_value = U64_MAX;
12636 /* Its not easy to operate on alu32 bounds here because it depends
12637 * on bits being shifted in from upper 32-bits. Take easy way out
12638 * and mark unbounded so we can recalculate later from tnum.
12640 __mark_reg32_unbounded(dst_reg);
12641 __update_reg_bounds(dst_reg);
12644 /* WARNING: This function does calculations on 64-bit values, but the actual
12645 * execution may occur on 32-bit values. Therefore, things like bitshifts
12646 * need extra checks in the 32-bit case.
12648 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12649 struct bpf_insn *insn,
12650 struct bpf_reg_state *dst_reg,
12651 struct bpf_reg_state src_reg)
12653 struct bpf_reg_state *regs = cur_regs(env);
12654 u8 opcode = BPF_OP(insn->code);
12656 s64 smin_val, smax_val;
12657 u64 umin_val, umax_val;
12658 s32 s32_min_val, s32_max_val;
12659 u32 u32_min_val, u32_max_val;
12660 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12661 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12664 smin_val = src_reg.smin_value;
12665 smax_val = src_reg.smax_value;
12666 umin_val = src_reg.umin_value;
12667 umax_val = src_reg.umax_value;
12669 s32_min_val = src_reg.s32_min_value;
12670 s32_max_val = src_reg.s32_max_value;
12671 u32_min_val = src_reg.u32_min_value;
12672 u32_max_val = src_reg.u32_max_value;
12675 src_known = tnum_subreg_is_const(src_reg.var_off);
12677 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12678 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12679 /* Taint dst register if offset had invalid bounds
12680 * derived from e.g. dead branches.
12682 __mark_reg_unknown(env, dst_reg);
12686 src_known = tnum_is_const(src_reg.var_off);
12688 (smin_val != smax_val || umin_val != umax_val)) ||
12689 smin_val > smax_val || umin_val > umax_val) {
12690 /* Taint dst register if offset had invalid bounds
12691 * derived from e.g. dead branches.
12693 __mark_reg_unknown(env, dst_reg);
12699 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12700 __mark_reg_unknown(env, dst_reg);
12704 if (sanitize_needed(opcode)) {
12705 ret = sanitize_val_alu(env, insn);
12707 return sanitize_err(env, insn, ret, NULL, NULL);
12710 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12711 * There are two classes of instructions: The first class we track both
12712 * alu32 and alu64 sign/unsigned bounds independently this provides the
12713 * greatest amount of precision when alu operations are mixed with jmp32
12714 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12715 * and BPF_OR. This is possible because these ops have fairly easy to
12716 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12717 * See alu32 verifier tests for examples. The second class of
12718 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12719 * with regards to tracking sign/unsigned bounds because the bits may
12720 * cross subreg boundaries in the alu64 case. When this happens we mark
12721 * the reg unbounded in the subreg bound space and use the resulting
12722 * tnum to calculate an approximation of the sign/unsigned bounds.
12726 scalar32_min_max_add(dst_reg, &src_reg);
12727 scalar_min_max_add(dst_reg, &src_reg);
12728 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12731 scalar32_min_max_sub(dst_reg, &src_reg);
12732 scalar_min_max_sub(dst_reg, &src_reg);
12733 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12736 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12737 scalar32_min_max_mul(dst_reg, &src_reg);
12738 scalar_min_max_mul(dst_reg, &src_reg);
12741 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12742 scalar32_min_max_and(dst_reg, &src_reg);
12743 scalar_min_max_and(dst_reg, &src_reg);
12746 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12747 scalar32_min_max_or(dst_reg, &src_reg);
12748 scalar_min_max_or(dst_reg, &src_reg);
12751 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12752 scalar32_min_max_xor(dst_reg, &src_reg);
12753 scalar_min_max_xor(dst_reg, &src_reg);
12756 if (umax_val >= insn_bitness) {
12757 /* Shifts greater than 31 or 63 are undefined.
12758 * This includes shifts by a negative number.
12760 mark_reg_unknown(env, regs, insn->dst_reg);
12764 scalar32_min_max_lsh(dst_reg, &src_reg);
12766 scalar_min_max_lsh(dst_reg, &src_reg);
12769 if (umax_val >= insn_bitness) {
12770 /* Shifts greater than 31 or 63 are undefined.
12771 * This includes shifts by a negative number.
12773 mark_reg_unknown(env, regs, insn->dst_reg);
12777 scalar32_min_max_rsh(dst_reg, &src_reg);
12779 scalar_min_max_rsh(dst_reg, &src_reg);
12782 if (umax_val >= insn_bitness) {
12783 /* Shifts greater than 31 or 63 are undefined.
12784 * This includes shifts by a negative number.
12786 mark_reg_unknown(env, regs, insn->dst_reg);
12790 scalar32_min_max_arsh(dst_reg, &src_reg);
12792 scalar_min_max_arsh(dst_reg, &src_reg);
12795 mark_reg_unknown(env, regs, insn->dst_reg);
12799 /* ALU32 ops are zero extended into 64bit register */
12801 zext_32_to_64(dst_reg);
12802 reg_bounds_sync(dst_reg);
12806 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12809 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12810 struct bpf_insn *insn)
12812 struct bpf_verifier_state *vstate = env->cur_state;
12813 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12814 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12815 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12816 u8 opcode = BPF_OP(insn->code);
12819 dst_reg = ®s[insn->dst_reg];
12821 if (dst_reg->type != SCALAR_VALUE)
12824 /* Make sure ID is cleared otherwise dst_reg min/max could be
12825 * incorrectly propagated into other registers by find_equal_scalars()
12828 if (BPF_SRC(insn->code) == BPF_X) {
12829 src_reg = ®s[insn->src_reg];
12830 if (src_reg->type != SCALAR_VALUE) {
12831 if (dst_reg->type != SCALAR_VALUE) {
12832 /* Combining two pointers by any ALU op yields
12833 * an arbitrary scalar. Disallow all math except
12834 * pointer subtraction
12836 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12837 mark_reg_unknown(env, regs, insn->dst_reg);
12840 verbose(env, "R%d pointer %s pointer prohibited\n",
12842 bpf_alu_string[opcode >> 4]);
12845 /* scalar += pointer
12846 * This is legal, but we have to reverse our
12847 * src/dest handling in computing the range
12849 err = mark_chain_precision(env, insn->dst_reg);
12852 return adjust_ptr_min_max_vals(env, insn,
12855 } else if (ptr_reg) {
12856 /* pointer += scalar */
12857 err = mark_chain_precision(env, insn->src_reg);
12860 return adjust_ptr_min_max_vals(env, insn,
12862 } else if (dst_reg->precise) {
12863 /* if dst_reg is precise, src_reg should be precise as well */
12864 err = mark_chain_precision(env, insn->src_reg);
12869 /* Pretend the src is a reg with a known value, since we only
12870 * need to be able to read from this state.
12872 off_reg.type = SCALAR_VALUE;
12873 __mark_reg_known(&off_reg, insn->imm);
12874 src_reg = &off_reg;
12875 if (ptr_reg) /* pointer += K */
12876 return adjust_ptr_min_max_vals(env, insn,
12880 /* Got here implies adding two SCALAR_VALUEs */
12881 if (WARN_ON_ONCE(ptr_reg)) {
12882 print_verifier_state(env, state, true);
12883 verbose(env, "verifier internal error: unexpected ptr_reg\n");
12886 if (WARN_ON(!src_reg)) {
12887 print_verifier_state(env, state, true);
12888 verbose(env, "verifier internal error: no src_reg\n");
12891 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
12894 /* check validity of 32-bit and 64-bit arithmetic operations */
12895 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
12897 struct bpf_reg_state *regs = cur_regs(env);
12898 u8 opcode = BPF_OP(insn->code);
12901 if (opcode == BPF_END || opcode == BPF_NEG) {
12902 if (opcode == BPF_NEG) {
12903 if (BPF_SRC(insn->code) != BPF_K ||
12904 insn->src_reg != BPF_REG_0 ||
12905 insn->off != 0 || insn->imm != 0) {
12906 verbose(env, "BPF_NEG uses reserved fields\n");
12910 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
12911 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
12912 BPF_CLASS(insn->code) == BPF_ALU64) {
12913 verbose(env, "BPF_END uses reserved fields\n");
12918 /* check src operand */
12919 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12923 if (is_pointer_value(env, insn->dst_reg)) {
12924 verbose(env, "R%d pointer arithmetic prohibited\n",
12929 /* check dest operand */
12930 err = check_reg_arg(env, insn->dst_reg, DST_OP);
12934 } else if (opcode == BPF_MOV) {
12936 if (BPF_SRC(insn->code) == BPF_X) {
12937 if (insn->imm != 0 || insn->off != 0) {
12938 verbose(env, "BPF_MOV uses reserved fields\n");
12942 /* check src operand */
12943 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12947 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12948 verbose(env, "BPF_MOV uses reserved fields\n");
12953 /* check dest operand, mark as required later */
12954 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12958 if (BPF_SRC(insn->code) == BPF_X) {
12959 struct bpf_reg_state *src_reg = regs + insn->src_reg;
12960 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
12961 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
12962 !tnum_is_const(src_reg->var_off);
12964 if (BPF_CLASS(insn->code) == BPF_ALU64) {
12966 * copy register state to dest reg
12969 /* Assign src and dst registers the same ID
12970 * that will be used by find_equal_scalars()
12971 * to propagate min/max range.
12973 src_reg->id = ++env->id_gen;
12974 copy_register_state(dst_reg, src_reg);
12975 dst_reg->live |= REG_LIVE_WRITTEN;
12976 dst_reg->subreg_def = DEF_NOT_SUBREG;
12978 /* R1 = (u32) R2 */
12979 if (is_pointer_value(env, insn->src_reg)) {
12981 "R%d partial copy of pointer\n",
12984 } else if (src_reg->type == SCALAR_VALUE) {
12985 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
12987 if (is_src_reg_u32 && need_id)
12988 src_reg->id = ++env->id_gen;
12989 copy_register_state(dst_reg, src_reg);
12990 /* Make sure ID is cleared if src_reg is not in u32 range otherwise
12991 * dst_reg min/max could be incorrectly
12992 * propagated into src_reg by find_equal_scalars()
12994 if (!is_src_reg_u32)
12996 dst_reg->live |= REG_LIVE_WRITTEN;
12997 dst_reg->subreg_def = env->insn_idx + 1;
12999 mark_reg_unknown(env, regs,
13002 zext_32_to_64(dst_reg);
13003 reg_bounds_sync(dst_reg);
13007 * remember the value we stored into this reg
13009 /* clear any state __mark_reg_known doesn't set */
13010 mark_reg_unknown(env, regs, insn->dst_reg);
13011 regs[insn->dst_reg].type = SCALAR_VALUE;
13012 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13013 __mark_reg_known(regs + insn->dst_reg,
13016 __mark_reg_known(regs + insn->dst_reg,
13021 } else if (opcode > BPF_END) {
13022 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13025 } else { /* all other ALU ops: and, sub, xor, add, ... */
13027 if (BPF_SRC(insn->code) == BPF_X) {
13028 if (insn->imm != 0 || insn->off != 0) {
13029 verbose(env, "BPF_ALU uses reserved fields\n");
13032 /* check src1 operand */
13033 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13037 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13038 verbose(env, "BPF_ALU uses reserved fields\n");
13043 /* check src2 operand */
13044 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13048 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13049 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13050 verbose(env, "div by zero\n");
13054 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13055 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13056 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13058 if (insn->imm < 0 || insn->imm >= size) {
13059 verbose(env, "invalid shift %d\n", insn->imm);
13064 /* check dest operand */
13065 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13069 return adjust_reg_min_max_vals(env, insn);
13075 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13076 struct bpf_reg_state *dst_reg,
13077 enum bpf_reg_type type,
13078 bool range_right_open)
13080 struct bpf_func_state *state;
13081 struct bpf_reg_state *reg;
13084 if (dst_reg->off < 0 ||
13085 (dst_reg->off == 0 && range_right_open))
13086 /* This doesn't give us any range */
13089 if (dst_reg->umax_value > MAX_PACKET_OFF ||
13090 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13091 /* Risk of overflow. For instance, ptr + (1<<63) may be less
13092 * than pkt_end, but that's because it's also less than pkt.
13096 new_range = dst_reg->off;
13097 if (range_right_open)
13100 /* Examples for register markings:
13102 * pkt_data in dst register:
13106 * if (r2 > pkt_end) goto <handle exception>
13111 * if (r2 < pkt_end) goto <access okay>
13112 * <handle exception>
13115 * r2 == dst_reg, pkt_end == src_reg
13116 * r2=pkt(id=n,off=8,r=0)
13117 * r3=pkt(id=n,off=0,r=0)
13119 * pkt_data in src register:
13123 * if (pkt_end >= r2) goto <access okay>
13124 * <handle exception>
13128 * if (pkt_end <= r2) goto <handle exception>
13132 * pkt_end == dst_reg, r2 == src_reg
13133 * r2=pkt(id=n,off=8,r=0)
13134 * r3=pkt(id=n,off=0,r=0)
13136 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13137 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13138 * and [r3, r3 + 8-1) respectively is safe to access depending on
13142 /* If our ids match, then we must have the same max_value. And we
13143 * don't care about the other reg's fixed offset, since if it's too big
13144 * the range won't allow anything.
13145 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13147 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13148 if (reg->type == type && reg->id == dst_reg->id)
13149 /* keep the maximum range already checked */
13150 reg->range = max(reg->range, new_range);
13154 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13156 struct tnum subreg = tnum_subreg(reg->var_off);
13157 s32 sval = (s32)val;
13161 if (tnum_is_const(subreg))
13162 return !!tnum_equals_const(subreg, val);
13163 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13167 if (tnum_is_const(subreg))
13168 return !tnum_equals_const(subreg, val);
13169 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13173 if ((~subreg.mask & subreg.value) & val)
13175 if (!((subreg.mask | subreg.value) & val))
13179 if (reg->u32_min_value > val)
13181 else if (reg->u32_max_value <= val)
13185 if (reg->s32_min_value > sval)
13187 else if (reg->s32_max_value <= sval)
13191 if (reg->u32_max_value < val)
13193 else if (reg->u32_min_value >= val)
13197 if (reg->s32_max_value < sval)
13199 else if (reg->s32_min_value >= sval)
13203 if (reg->u32_min_value >= val)
13205 else if (reg->u32_max_value < val)
13209 if (reg->s32_min_value >= sval)
13211 else if (reg->s32_max_value < sval)
13215 if (reg->u32_max_value <= val)
13217 else if (reg->u32_min_value > val)
13221 if (reg->s32_max_value <= sval)
13223 else if (reg->s32_min_value > sval)
13232 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13234 s64 sval = (s64)val;
13238 if (tnum_is_const(reg->var_off))
13239 return !!tnum_equals_const(reg->var_off, val);
13240 else if (val < reg->umin_value || val > reg->umax_value)
13244 if (tnum_is_const(reg->var_off))
13245 return !tnum_equals_const(reg->var_off, val);
13246 else if (val < reg->umin_value || val > reg->umax_value)
13250 if ((~reg->var_off.mask & reg->var_off.value) & val)
13252 if (!((reg->var_off.mask | reg->var_off.value) & val))
13256 if (reg->umin_value > val)
13258 else if (reg->umax_value <= val)
13262 if (reg->smin_value > sval)
13264 else if (reg->smax_value <= sval)
13268 if (reg->umax_value < val)
13270 else if (reg->umin_value >= val)
13274 if (reg->smax_value < sval)
13276 else if (reg->smin_value >= sval)
13280 if (reg->umin_value >= val)
13282 else if (reg->umax_value < val)
13286 if (reg->smin_value >= sval)
13288 else if (reg->smax_value < sval)
13292 if (reg->umax_value <= val)
13294 else if (reg->umin_value > val)
13298 if (reg->smax_value <= sval)
13300 else if (reg->smin_value > sval)
13308 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13310 * 1 - branch will be taken and "goto target" will be executed
13311 * 0 - branch will not be taken and fall-through to next insn
13312 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13315 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13318 if (__is_pointer_value(false, reg)) {
13319 if (!reg_not_null(reg))
13322 /* If pointer is valid tests against zero will fail so we can
13323 * use this to direct branch taken.
13339 return is_branch32_taken(reg, val, opcode);
13340 return is_branch64_taken(reg, val, opcode);
13343 static int flip_opcode(u32 opcode)
13345 /* How can we transform "a <op> b" into "b <op> a"? */
13346 static const u8 opcode_flip[16] = {
13347 /* these stay the same */
13348 [BPF_JEQ >> 4] = BPF_JEQ,
13349 [BPF_JNE >> 4] = BPF_JNE,
13350 [BPF_JSET >> 4] = BPF_JSET,
13351 /* these swap "lesser" and "greater" (L and G in the opcodes) */
13352 [BPF_JGE >> 4] = BPF_JLE,
13353 [BPF_JGT >> 4] = BPF_JLT,
13354 [BPF_JLE >> 4] = BPF_JGE,
13355 [BPF_JLT >> 4] = BPF_JGT,
13356 [BPF_JSGE >> 4] = BPF_JSLE,
13357 [BPF_JSGT >> 4] = BPF_JSLT,
13358 [BPF_JSLE >> 4] = BPF_JSGE,
13359 [BPF_JSLT >> 4] = BPF_JSGT
13361 return opcode_flip[opcode >> 4];
13364 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13365 struct bpf_reg_state *src_reg,
13368 struct bpf_reg_state *pkt;
13370 if (src_reg->type == PTR_TO_PACKET_END) {
13372 } else if (dst_reg->type == PTR_TO_PACKET_END) {
13374 opcode = flip_opcode(opcode);
13379 if (pkt->range >= 0)
13384 /* pkt <= pkt_end */
13387 /* pkt > pkt_end */
13388 if (pkt->range == BEYOND_PKT_END)
13389 /* pkt has at last one extra byte beyond pkt_end */
13390 return opcode == BPF_JGT;
13393 /* pkt < pkt_end */
13396 /* pkt >= pkt_end */
13397 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13398 return opcode == BPF_JGE;
13404 /* Adjusts the register min/max values in the case that the dst_reg is the
13405 * variable register that we are working on, and src_reg is a constant or we're
13406 * simply doing a BPF_K check.
13407 * In JEQ/JNE cases we also adjust the var_off values.
13409 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13410 struct bpf_reg_state *false_reg,
13411 u64 val, u32 val32,
13412 u8 opcode, bool is_jmp32)
13414 struct tnum false_32off = tnum_subreg(false_reg->var_off);
13415 struct tnum false_64off = false_reg->var_off;
13416 struct tnum true_32off = tnum_subreg(true_reg->var_off);
13417 struct tnum true_64off = true_reg->var_off;
13418 s64 sval = (s64)val;
13419 s32 sval32 = (s32)val32;
13421 /* If the dst_reg is a pointer, we can't learn anything about its
13422 * variable offset from the compare (unless src_reg were a pointer into
13423 * the same object, but we don't bother with that.
13424 * Since false_reg and true_reg have the same type by construction, we
13425 * only need to check one of them for pointerness.
13427 if (__is_pointer_value(false, false_reg))
13431 /* JEQ/JNE comparison doesn't change the register equivalence.
13434 * if (r1 == 42) goto label;
13436 * label: // here both r1 and r2 are known to be 42.
13438 * Hence when marking register as known preserve it's ID.
13442 __mark_reg32_known(true_reg, val32);
13443 true_32off = tnum_subreg(true_reg->var_off);
13445 ___mark_reg_known(true_reg, val);
13446 true_64off = true_reg->var_off;
13451 __mark_reg32_known(false_reg, val32);
13452 false_32off = tnum_subreg(false_reg->var_off);
13454 ___mark_reg_known(false_reg, val);
13455 false_64off = false_reg->var_off;
13460 false_32off = tnum_and(false_32off, tnum_const(~val32));
13461 if (is_power_of_2(val32))
13462 true_32off = tnum_or(true_32off,
13463 tnum_const(val32));
13465 false_64off = tnum_and(false_64off, tnum_const(~val));
13466 if (is_power_of_2(val))
13467 true_64off = tnum_or(true_64off,
13475 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
13476 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13478 false_reg->u32_max_value = min(false_reg->u32_max_value,
13480 true_reg->u32_min_value = max(true_reg->u32_min_value,
13483 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
13484 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13486 false_reg->umax_value = min(false_reg->umax_value, false_umax);
13487 true_reg->umin_value = max(true_reg->umin_value, true_umin);
13495 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
13496 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13498 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13499 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13501 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
13502 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13504 false_reg->smax_value = min(false_reg->smax_value, false_smax);
13505 true_reg->smin_value = max(true_reg->smin_value, true_smin);
13513 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
13514 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13516 false_reg->u32_min_value = max(false_reg->u32_min_value,
13518 true_reg->u32_max_value = min(true_reg->u32_max_value,
13521 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
13522 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13524 false_reg->umin_value = max(false_reg->umin_value, false_umin);
13525 true_reg->umax_value = min(true_reg->umax_value, true_umax);
13533 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
13534 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13536 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13537 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13539 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
13540 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13542 false_reg->smin_value = max(false_reg->smin_value, false_smin);
13543 true_reg->smax_value = min(true_reg->smax_value, true_smax);
13552 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13553 tnum_subreg(false_32off));
13554 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13555 tnum_subreg(true_32off));
13556 __reg_combine_32_into_64(false_reg);
13557 __reg_combine_32_into_64(true_reg);
13559 false_reg->var_off = false_64off;
13560 true_reg->var_off = true_64off;
13561 __reg_combine_64_into_32(false_reg);
13562 __reg_combine_64_into_32(true_reg);
13566 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13567 * the variable reg.
13569 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13570 struct bpf_reg_state *false_reg,
13571 u64 val, u32 val32,
13572 u8 opcode, bool is_jmp32)
13574 opcode = flip_opcode(opcode);
13575 /* This uses zero as "not present in table"; luckily the zero opcode,
13576 * BPF_JA, can't get here.
13579 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13582 /* Regs are known to be equal, so intersect their min/max/var_off */
13583 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13584 struct bpf_reg_state *dst_reg)
13586 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13587 dst_reg->umin_value);
13588 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13589 dst_reg->umax_value);
13590 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13591 dst_reg->smin_value);
13592 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13593 dst_reg->smax_value);
13594 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13596 reg_bounds_sync(src_reg);
13597 reg_bounds_sync(dst_reg);
13600 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13601 struct bpf_reg_state *true_dst,
13602 struct bpf_reg_state *false_src,
13603 struct bpf_reg_state *false_dst,
13608 __reg_combine_min_max(true_src, true_dst);
13611 __reg_combine_min_max(false_src, false_dst);
13616 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13617 struct bpf_reg_state *reg, u32 id,
13620 if (type_may_be_null(reg->type) && reg->id == id &&
13621 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13622 /* Old offset (both fixed and variable parts) should have been
13623 * known-zero, because we don't allow pointer arithmetic on
13624 * pointers that might be NULL. If we see this happening, don't
13625 * convert the register.
13627 * But in some cases, some helpers that return local kptrs
13628 * advance offset for the returned pointer. In those cases, it
13629 * is fine to expect to see reg->off.
13631 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13633 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13634 WARN_ON_ONCE(reg->off))
13638 reg->type = SCALAR_VALUE;
13639 /* We don't need id and ref_obj_id from this point
13640 * onwards anymore, thus we should better reset it,
13641 * so that state pruning has chances to take effect.
13644 reg->ref_obj_id = 0;
13649 mark_ptr_not_null_reg(reg);
13651 if (!reg_may_point_to_spin_lock(reg)) {
13652 /* For not-NULL ptr, reg->ref_obj_id will be reset
13653 * in release_reference().
13655 * reg->id is still used by spin_lock ptr. Other
13656 * than spin_lock ptr type, reg->id can be reset.
13663 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13664 * be folded together at some point.
13666 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13669 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13670 struct bpf_reg_state *regs = state->regs, *reg;
13671 u32 ref_obj_id = regs[regno].ref_obj_id;
13672 u32 id = regs[regno].id;
13674 if (ref_obj_id && ref_obj_id == id && is_null)
13675 /* regs[regno] is in the " == NULL" branch.
13676 * No one could have freed the reference state before
13677 * doing the NULL check.
13679 WARN_ON_ONCE(release_reference_state(state, id));
13681 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13682 mark_ptr_or_null_reg(state, reg, id, is_null);
13686 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13687 struct bpf_reg_state *dst_reg,
13688 struct bpf_reg_state *src_reg,
13689 struct bpf_verifier_state *this_branch,
13690 struct bpf_verifier_state *other_branch)
13692 if (BPF_SRC(insn->code) != BPF_X)
13695 /* Pointers are always 64-bit. */
13696 if (BPF_CLASS(insn->code) == BPF_JMP32)
13699 switch (BPF_OP(insn->code)) {
13701 if ((dst_reg->type == PTR_TO_PACKET &&
13702 src_reg->type == PTR_TO_PACKET_END) ||
13703 (dst_reg->type == PTR_TO_PACKET_META &&
13704 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13705 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13706 find_good_pkt_pointers(this_branch, dst_reg,
13707 dst_reg->type, false);
13708 mark_pkt_end(other_branch, insn->dst_reg, true);
13709 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13710 src_reg->type == PTR_TO_PACKET) ||
13711 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13712 src_reg->type == PTR_TO_PACKET_META)) {
13713 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13714 find_good_pkt_pointers(other_branch, src_reg,
13715 src_reg->type, true);
13716 mark_pkt_end(this_branch, insn->src_reg, false);
13722 if ((dst_reg->type == PTR_TO_PACKET &&
13723 src_reg->type == PTR_TO_PACKET_END) ||
13724 (dst_reg->type == PTR_TO_PACKET_META &&
13725 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13726 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13727 find_good_pkt_pointers(other_branch, dst_reg,
13728 dst_reg->type, true);
13729 mark_pkt_end(this_branch, insn->dst_reg, false);
13730 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13731 src_reg->type == PTR_TO_PACKET) ||
13732 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13733 src_reg->type == PTR_TO_PACKET_META)) {
13734 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13735 find_good_pkt_pointers(this_branch, src_reg,
13736 src_reg->type, false);
13737 mark_pkt_end(other_branch, insn->src_reg, true);
13743 if ((dst_reg->type == PTR_TO_PACKET &&
13744 src_reg->type == PTR_TO_PACKET_END) ||
13745 (dst_reg->type == PTR_TO_PACKET_META &&
13746 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13747 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13748 find_good_pkt_pointers(this_branch, dst_reg,
13749 dst_reg->type, true);
13750 mark_pkt_end(other_branch, insn->dst_reg, false);
13751 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13752 src_reg->type == PTR_TO_PACKET) ||
13753 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13754 src_reg->type == PTR_TO_PACKET_META)) {
13755 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13756 find_good_pkt_pointers(other_branch, src_reg,
13757 src_reg->type, false);
13758 mark_pkt_end(this_branch, insn->src_reg, true);
13764 if ((dst_reg->type == PTR_TO_PACKET &&
13765 src_reg->type == PTR_TO_PACKET_END) ||
13766 (dst_reg->type == PTR_TO_PACKET_META &&
13767 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13768 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13769 find_good_pkt_pointers(other_branch, dst_reg,
13770 dst_reg->type, false);
13771 mark_pkt_end(this_branch, insn->dst_reg, true);
13772 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13773 src_reg->type == PTR_TO_PACKET) ||
13774 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13775 src_reg->type == PTR_TO_PACKET_META)) {
13776 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13777 find_good_pkt_pointers(this_branch, src_reg,
13778 src_reg->type, true);
13779 mark_pkt_end(other_branch, insn->src_reg, false);
13791 static void find_equal_scalars(struct bpf_verifier_state *vstate,
13792 struct bpf_reg_state *known_reg)
13794 struct bpf_func_state *state;
13795 struct bpf_reg_state *reg;
13797 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13798 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
13799 copy_register_state(reg, known_reg);
13803 static int check_cond_jmp_op(struct bpf_verifier_env *env,
13804 struct bpf_insn *insn, int *insn_idx)
13806 struct bpf_verifier_state *this_branch = env->cur_state;
13807 struct bpf_verifier_state *other_branch;
13808 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
13809 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
13810 struct bpf_reg_state *eq_branch_regs;
13811 u8 opcode = BPF_OP(insn->code);
13816 /* Only conditional jumps are expected to reach here. */
13817 if (opcode == BPF_JA || opcode > BPF_JSLE) {
13818 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
13822 if (BPF_SRC(insn->code) == BPF_X) {
13823 if (insn->imm != 0) {
13824 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13828 /* check src1 operand */
13829 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13833 if (is_pointer_value(env, insn->src_reg)) {
13834 verbose(env, "R%d pointer comparison prohibited\n",
13838 src_reg = ®s[insn->src_reg];
13840 if (insn->src_reg != BPF_REG_0) {
13841 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13846 /* check src2 operand */
13847 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13851 dst_reg = ®s[insn->dst_reg];
13852 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
13854 if (BPF_SRC(insn->code) == BPF_K) {
13855 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
13856 } else if (src_reg->type == SCALAR_VALUE &&
13857 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
13858 pred = is_branch_taken(dst_reg,
13859 tnum_subreg(src_reg->var_off).value,
13862 } else if (src_reg->type == SCALAR_VALUE &&
13863 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
13864 pred = is_branch_taken(dst_reg,
13865 src_reg->var_off.value,
13868 } else if (dst_reg->type == SCALAR_VALUE &&
13869 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
13870 pred = is_branch_taken(src_reg,
13871 tnum_subreg(dst_reg->var_off).value,
13872 flip_opcode(opcode),
13874 } else if (dst_reg->type == SCALAR_VALUE &&
13875 !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
13876 pred = is_branch_taken(src_reg,
13877 dst_reg->var_off.value,
13878 flip_opcode(opcode),
13880 } else if (reg_is_pkt_pointer_any(dst_reg) &&
13881 reg_is_pkt_pointer_any(src_reg) &&
13883 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
13887 /* If we get here with a dst_reg pointer type it is because
13888 * above is_branch_taken() special cased the 0 comparison.
13890 if (!__is_pointer_value(false, dst_reg))
13891 err = mark_chain_precision(env, insn->dst_reg);
13892 if (BPF_SRC(insn->code) == BPF_X && !err &&
13893 !__is_pointer_value(false, src_reg))
13894 err = mark_chain_precision(env, insn->src_reg);
13900 /* Only follow the goto, ignore fall-through. If needed, push
13901 * the fall-through branch for simulation under speculative
13904 if (!env->bypass_spec_v1 &&
13905 !sanitize_speculative_path(env, insn, *insn_idx + 1,
13908 *insn_idx += insn->off;
13910 } else if (pred == 0) {
13911 /* Only follow the fall-through branch, since that's where the
13912 * program will go. If needed, push the goto branch for
13913 * simulation under speculative execution.
13915 if (!env->bypass_spec_v1 &&
13916 !sanitize_speculative_path(env, insn,
13917 *insn_idx + insn->off + 1,
13923 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
13927 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
13929 /* detect if we are comparing against a constant value so we can adjust
13930 * our min/max values for our dst register.
13931 * this is only legit if both are scalars (or pointers to the same
13932 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
13933 * because otherwise the different base pointers mean the offsets aren't
13936 if (BPF_SRC(insn->code) == BPF_X) {
13937 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
13939 if (dst_reg->type == SCALAR_VALUE &&
13940 src_reg->type == SCALAR_VALUE) {
13941 if (tnum_is_const(src_reg->var_off) ||
13943 tnum_is_const(tnum_subreg(src_reg->var_off))))
13944 reg_set_min_max(&other_branch_regs[insn->dst_reg],
13946 src_reg->var_off.value,
13947 tnum_subreg(src_reg->var_off).value,
13949 else if (tnum_is_const(dst_reg->var_off) ||
13951 tnum_is_const(tnum_subreg(dst_reg->var_off))))
13952 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
13954 dst_reg->var_off.value,
13955 tnum_subreg(dst_reg->var_off).value,
13957 else if (!is_jmp32 &&
13958 (opcode == BPF_JEQ || opcode == BPF_JNE))
13959 /* Comparing for equality, we can combine knowledge */
13960 reg_combine_min_max(&other_branch_regs[insn->src_reg],
13961 &other_branch_regs[insn->dst_reg],
13962 src_reg, dst_reg, opcode);
13964 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
13965 find_equal_scalars(this_branch, src_reg);
13966 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
13970 } else if (dst_reg->type == SCALAR_VALUE) {
13971 reg_set_min_max(&other_branch_regs[insn->dst_reg],
13972 dst_reg, insn->imm, (u32)insn->imm,
13976 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
13977 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
13978 find_equal_scalars(this_branch, dst_reg);
13979 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
13982 /* if one pointer register is compared to another pointer
13983 * register check if PTR_MAYBE_NULL could be lifted.
13984 * E.g. register A - maybe null
13985 * register B - not null
13986 * for JNE A, B, ... - A is not null in the false branch;
13987 * for JEQ A, B, ... - A is not null in the true branch.
13989 * Since PTR_TO_BTF_ID points to a kernel struct that does
13990 * not need to be null checked by the BPF program, i.e.,
13991 * could be null even without PTR_MAYBE_NULL marking, so
13992 * only propagate nullness when neither reg is that type.
13994 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
13995 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
13996 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
13997 base_type(src_reg->type) != PTR_TO_BTF_ID &&
13998 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
13999 eq_branch_regs = NULL;
14002 eq_branch_regs = other_branch_regs;
14005 eq_branch_regs = regs;
14011 if (eq_branch_regs) {
14012 if (type_may_be_null(src_reg->type))
14013 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14015 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14019 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14020 * NOTE: these optimizations below are related with pointer comparison
14021 * which will never be JMP32.
14023 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14024 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14025 type_may_be_null(dst_reg->type)) {
14026 /* Mark all identical registers in each branch as either
14027 * safe or unknown depending R == 0 or R != 0 conditional.
14029 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14030 opcode == BPF_JNE);
14031 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14032 opcode == BPF_JEQ);
14033 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
14034 this_branch, other_branch) &&
14035 is_pointer_value(env, insn->dst_reg)) {
14036 verbose(env, "R%d pointer comparison prohibited\n",
14040 if (env->log.level & BPF_LOG_LEVEL)
14041 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14045 /* verify BPF_LD_IMM64 instruction */
14046 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14048 struct bpf_insn_aux_data *aux = cur_aux(env);
14049 struct bpf_reg_state *regs = cur_regs(env);
14050 struct bpf_reg_state *dst_reg;
14051 struct bpf_map *map;
14054 if (BPF_SIZE(insn->code) != BPF_DW) {
14055 verbose(env, "invalid BPF_LD_IMM insn\n");
14058 if (insn->off != 0) {
14059 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14063 err = check_reg_arg(env, insn->dst_reg, DST_OP);
14067 dst_reg = ®s[insn->dst_reg];
14068 if (insn->src_reg == 0) {
14069 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14071 dst_reg->type = SCALAR_VALUE;
14072 __mark_reg_known(®s[insn->dst_reg], imm);
14076 /* All special src_reg cases are listed below. From this point onwards
14077 * we either succeed and assign a corresponding dst_reg->type after
14078 * zeroing the offset, or fail and reject the program.
14080 mark_reg_known_zero(env, regs, insn->dst_reg);
14082 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14083 dst_reg->type = aux->btf_var.reg_type;
14084 switch (base_type(dst_reg->type)) {
14086 dst_reg->mem_size = aux->btf_var.mem_size;
14088 case PTR_TO_BTF_ID:
14089 dst_reg->btf = aux->btf_var.btf;
14090 dst_reg->btf_id = aux->btf_var.btf_id;
14093 verbose(env, "bpf verifier is misconfigured\n");
14099 if (insn->src_reg == BPF_PSEUDO_FUNC) {
14100 struct bpf_prog_aux *aux = env->prog->aux;
14101 u32 subprogno = find_subprog(env,
14102 env->insn_idx + insn->imm + 1);
14104 if (!aux->func_info) {
14105 verbose(env, "missing btf func_info\n");
14108 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14109 verbose(env, "callback function not static\n");
14113 dst_reg->type = PTR_TO_FUNC;
14114 dst_reg->subprogno = subprogno;
14118 map = env->used_maps[aux->map_index];
14119 dst_reg->map_ptr = map;
14121 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14122 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14123 dst_reg->type = PTR_TO_MAP_VALUE;
14124 dst_reg->off = aux->map_off;
14125 WARN_ON_ONCE(map->max_entries != 1);
14126 /* We want reg->id to be same (0) as map_value is not distinct */
14127 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14128 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14129 dst_reg->type = CONST_PTR_TO_MAP;
14131 verbose(env, "bpf verifier is misconfigured\n");
14138 static bool may_access_skb(enum bpf_prog_type type)
14141 case BPF_PROG_TYPE_SOCKET_FILTER:
14142 case BPF_PROG_TYPE_SCHED_CLS:
14143 case BPF_PROG_TYPE_SCHED_ACT:
14150 /* verify safety of LD_ABS|LD_IND instructions:
14151 * - they can only appear in the programs where ctx == skb
14152 * - since they are wrappers of function calls, they scratch R1-R5 registers,
14153 * preserve R6-R9, and store return value into R0
14156 * ctx == skb == R6 == CTX
14159 * SRC == any register
14160 * IMM == 32-bit immediate
14163 * R0 - 8/16/32-bit skb data converted to cpu endianness
14165 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14167 struct bpf_reg_state *regs = cur_regs(env);
14168 static const int ctx_reg = BPF_REG_6;
14169 u8 mode = BPF_MODE(insn->code);
14172 if (!may_access_skb(resolve_prog_type(env->prog))) {
14173 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14177 if (!env->ops->gen_ld_abs) {
14178 verbose(env, "bpf verifier is misconfigured\n");
14182 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14183 BPF_SIZE(insn->code) == BPF_DW ||
14184 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14185 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14189 /* check whether implicit source operand (register R6) is readable */
14190 err = check_reg_arg(env, ctx_reg, SRC_OP);
14194 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14195 * gen_ld_abs() may terminate the program at runtime, leading to
14198 err = check_reference_leak(env);
14200 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14204 if (env->cur_state->active_lock.ptr) {
14205 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14209 if (env->cur_state->active_rcu_lock) {
14210 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14214 if (regs[ctx_reg].type != PTR_TO_CTX) {
14216 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14220 if (mode == BPF_IND) {
14221 /* check explicit source operand */
14222 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14227 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
14231 /* reset caller saved regs to unreadable */
14232 for (i = 0; i < CALLER_SAVED_REGS; i++) {
14233 mark_reg_not_init(env, regs, caller_saved[i]);
14234 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14237 /* mark destination R0 register as readable, since it contains
14238 * the value fetched from the packet.
14239 * Already marked as written above.
14241 mark_reg_unknown(env, regs, BPF_REG_0);
14242 /* ld_abs load up to 32-bit skb data. */
14243 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14247 static int check_return_code(struct bpf_verifier_env *env)
14249 struct tnum enforce_attach_type_range = tnum_unknown;
14250 const struct bpf_prog *prog = env->prog;
14251 struct bpf_reg_state *reg;
14252 struct tnum range = tnum_range(0, 1);
14253 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14255 struct bpf_func_state *frame = env->cur_state->frame[0];
14256 const bool is_subprog = frame->subprogno;
14258 /* LSM and struct_ops func-ptr's return type could be "void" */
14260 switch (prog_type) {
14261 case BPF_PROG_TYPE_LSM:
14262 if (prog->expected_attach_type == BPF_LSM_CGROUP)
14263 /* See below, can be 0 or 0-1 depending on hook. */
14266 case BPF_PROG_TYPE_STRUCT_OPS:
14267 if (!prog->aux->attach_func_proto->type)
14275 /* eBPF calling convention is such that R0 is used
14276 * to return the value from eBPF program.
14277 * Make sure that it's readable at this time
14278 * of bpf_exit, which means that program wrote
14279 * something into it earlier
14281 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14285 if (is_pointer_value(env, BPF_REG_0)) {
14286 verbose(env, "R0 leaks addr as return value\n");
14290 reg = cur_regs(env) + BPF_REG_0;
14292 if (frame->in_async_callback_fn) {
14293 /* enforce return zero from async callbacks like timer */
14294 if (reg->type != SCALAR_VALUE) {
14295 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14296 reg_type_str(env, reg->type));
14300 if (!tnum_in(tnum_const(0), reg->var_off)) {
14301 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
14308 if (reg->type != SCALAR_VALUE) {
14309 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14310 reg_type_str(env, reg->type));
14316 switch (prog_type) {
14317 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14318 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14319 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14320 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14321 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14322 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14323 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14324 range = tnum_range(1, 1);
14325 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14326 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14327 range = tnum_range(0, 3);
14329 case BPF_PROG_TYPE_CGROUP_SKB:
14330 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14331 range = tnum_range(0, 3);
14332 enforce_attach_type_range = tnum_range(2, 3);
14335 case BPF_PROG_TYPE_CGROUP_SOCK:
14336 case BPF_PROG_TYPE_SOCK_OPS:
14337 case BPF_PROG_TYPE_CGROUP_DEVICE:
14338 case BPF_PROG_TYPE_CGROUP_SYSCTL:
14339 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14341 case BPF_PROG_TYPE_RAW_TRACEPOINT:
14342 if (!env->prog->aux->attach_btf_id)
14344 range = tnum_const(0);
14346 case BPF_PROG_TYPE_TRACING:
14347 switch (env->prog->expected_attach_type) {
14348 case BPF_TRACE_FENTRY:
14349 case BPF_TRACE_FEXIT:
14350 range = tnum_const(0);
14352 case BPF_TRACE_RAW_TP:
14353 case BPF_MODIFY_RETURN:
14355 case BPF_TRACE_ITER:
14361 case BPF_PROG_TYPE_SK_LOOKUP:
14362 range = tnum_range(SK_DROP, SK_PASS);
14365 case BPF_PROG_TYPE_LSM:
14366 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14367 /* Regular BPF_PROG_TYPE_LSM programs can return
14372 if (!env->prog->aux->attach_func_proto->type) {
14373 /* Make sure programs that attach to void
14374 * hooks don't try to modify return value.
14376 range = tnum_range(1, 1);
14380 case BPF_PROG_TYPE_NETFILTER:
14381 range = tnum_range(NF_DROP, NF_ACCEPT);
14383 case BPF_PROG_TYPE_EXT:
14384 /* freplace program can return anything as its return value
14385 * depends on the to-be-replaced kernel func or bpf program.
14391 if (reg->type != SCALAR_VALUE) {
14392 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14393 reg_type_str(env, reg->type));
14397 if (!tnum_in(range, reg->var_off)) {
14398 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14399 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14400 prog_type == BPF_PROG_TYPE_LSM &&
14401 !prog->aux->attach_func_proto->type)
14402 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14406 if (!tnum_is_unknown(enforce_attach_type_range) &&
14407 tnum_in(enforce_attach_type_range, reg->var_off))
14408 env->prog->enforce_expected_attach_type = 1;
14412 /* non-recursive DFS pseudo code
14413 * 1 procedure DFS-iterative(G,v):
14414 * 2 label v as discovered
14415 * 3 let S be a stack
14417 * 5 while S is not empty
14419 * 7 if t is what we're looking for:
14421 * 9 for all edges e in G.adjacentEdges(t) do
14422 * 10 if edge e is already labelled
14423 * 11 continue with the next edge
14424 * 12 w <- G.adjacentVertex(t,e)
14425 * 13 if vertex w is not discovered and not explored
14426 * 14 label e as tree-edge
14427 * 15 label w as discovered
14430 * 18 else if vertex w is discovered
14431 * 19 label e as back-edge
14433 * 21 // vertex w is explored
14434 * 22 label e as forward- or cross-edge
14435 * 23 label t as explored
14439 * 0x10 - discovered
14440 * 0x11 - discovered and fall-through edge labelled
14441 * 0x12 - discovered and fall-through and branch edges labelled
14452 static u32 state_htab_size(struct bpf_verifier_env *env)
14454 return env->prog->len;
14457 static struct bpf_verifier_state_list **explored_state(
14458 struct bpf_verifier_env *env,
14461 struct bpf_verifier_state *cur = env->cur_state;
14462 struct bpf_func_state *state = cur->frame[cur->curframe];
14464 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14467 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14469 env->insn_aux_data[idx].prune_point = true;
14472 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14474 return env->insn_aux_data[insn_idx].prune_point;
14477 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14479 env->insn_aux_data[idx].force_checkpoint = true;
14482 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14484 return env->insn_aux_data[insn_idx].force_checkpoint;
14489 DONE_EXPLORING = 0,
14490 KEEP_EXPLORING = 1,
14493 /* t, w, e - match pseudo-code above:
14494 * t - index of current instruction
14495 * w - next instruction
14498 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14501 int *insn_stack = env->cfg.insn_stack;
14502 int *insn_state = env->cfg.insn_state;
14504 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14505 return DONE_EXPLORING;
14507 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14508 return DONE_EXPLORING;
14510 if (w < 0 || w >= env->prog->len) {
14511 verbose_linfo(env, t, "%d: ", t);
14512 verbose(env, "jump out of range from insn %d to %d\n", t, w);
14517 /* mark branch target for state pruning */
14518 mark_prune_point(env, w);
14519 mark_jmp_point(env, w);
14522 if (insn_state[w] == 0) {
14524 insn_state[t] = DISCOVERED | e;
14525 insn_state[w] = DISCOVERED;
14526 if (env->cfg.cur_stack >= env->prog->len)
14528 insn_stack[env->cfg.cur_stack++] = w;
14529 return KEEP_EXPLORING;
14530 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14531 if (loop_ok && env->bpf_capable)
14532 return DONE_EXPLORING;
14533 verbose_linfo(env, t, "%d: ", t);
14534 verbose_linfo(env, w, "%d: ", w);
14535 verbose(env, "back-edge from insn %d to %d\n", t, w);
14537 } else if (insn_state[w] == EXPLORED) {
14538 /* forward- or cross-edge */
14539 insn_state[t] = DISCOVERED | e;
14541 verbose(env, "insn state internal bug\n");
14544 return DONE_EXPLORING;
14547 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14548 struct bpf_verifier_env *env,
14553 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14557 mark_prune_point(env, t + 1);
14558 /* when we exit from subprog, we need to record non-linear history */
14559 mark_jmp_point(env, t + 1);
14561 if (visit_callee) {
14562 mark_prune_point(env, t);
14563 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14564 /* It's ok to allow recursion from CFG point of
14565 * view. __check_func_call() will do the actual
14568 bpf_pseudo_func(insns + t));
14573 /* Visits the instruction at index t and returns one of the following:
14574 * < 0 - an error occurred
14575 * DONE_EXPLORING - the instruction was fully explored
14576 * KEEP_EXPLORING - there is still work to be done before it is fully explored
14578 static int visit_insn(int t, struct bpf_verifier_env *env)
14580 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14583 if (bpf_pseudo_func(insn))
14584 return visit_func_call_insn(t, insns, env, true);
14586 /* All non-branch instructions have a single fall-through edge. */
14587 if (BPF_CLASS(insn->code) != BPF_JMP &&
14588 BPF_CLASS(insn->code) != BPF_JMP32)
14589 return push_insn(t, t + 1, FALLTHROUGH, env, false);
14591 switch (BPF_OP(insn->code)) {
14593 return DONE_EXPLORING;
14596 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14597 /* Mark this call insn as a prune point to trigger
14598 * is_state_visited() check before call itself is
14599 * processed by __check_func_call(). Otherwise new
14600 * async state will be pushed for further exploration.
14602 mark_prune_point(env, t);
14603 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14604 struct bpf_kfunc_call_arg_meta meta;
14606 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14607 if (ret == 0 && is_iter_next_kfunc(&meta)) {
14608 mark_prune_point(env, t);
14609 /* Checking and saving state checkpoints at iter_next() call
14610 * is crucial for fast convergence of open-coded iterator loop
14611 * logic, so we need to force it. If we don't do that,
14612 * is_state_visited() might skip saving a checkpoint, causing
14613 * unnecessarily long sequence of not checkpointed
14614 * instructions and jumps, leading to exhaustion of jump
14615 * history buffer, and potentially other undesired outcomes.
14616 * It is expected that with correct open-coded iterators
14617 * convergence will happen quickly, so we don't run a risk of
14618 * exhausting memory.
14620 mark_force_checkpoint(env, t);
14623 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14626 if (BPF_SRC(insn->code) != BPF_K)
14629 /* unconditional jump with single edge */
14630 ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
14635 mark_prune_point(env, t + insn->off + 1);
14636 mark_jmp_point(env, t + insn->off + 1);
14641 /* conditional jump with two edges */
14642 mark_prune_point(env, t);
14644 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14648 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14652 /* non-recursive depth-first-search to detect loops in BPF program
14653 * loop == back-edge in directed graph
14655 static int check_cfg(struct bpf_verifier_env *env)
14657 int insn_cnt = env->prog->len;
14658 int *insn_stack, *insn_state;
14662 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14666 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14668 kvfree(insn_state);
14672 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14673 insn_stack[0] = 0; /* 0 is the first instruction */
14674 env->cfg.cur_stack = 1;
14676 while (env->cfg.cur_stack > 0) {
14677 int t = insn_stack[env->cfg.cur_stack - 1];
14679 ret = visit_insn(t, env);
14681 case DONE_EXPLORING:
14682 insn_state[t] = EXPLORED;
14683 env->cfg.cur_stack--;
14685 case KEEP_EXPLORING:
14689 verbose(env, "visit_insn internal bug\n");
14696 if (env->cfg.cur_stack < 0) {
14697 verbose(env, "pop stack internal bug\n");
14702 for (i = 0; i < insn_cnt; i++) {
14703 if (insn_state[i] != EXPLORED) {
14704 verbose(env, "unreachable insn %d\n", i);
14709 ret = 0; /* cfg looks good */
14712 kvfree(insn_state);
14713 kvfree(insn_stack);
14714 env->cfg.insn_state = env->cfg.insn_stack = NULL;
14718 static int check_abnormal_return(struct bpf_verifier_env *env)
14722 for (i = 1; i < env->subprog_cnt; i++) {
14723 if (env->subprog_info[i].has_ld_abs) {
14724 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14727 if (env->subprog_info[i].has_tail_call) {
14728 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14735 /* The minimum supported BTF func info size */
14736 #define MIN_BPF_FUNCINFO_SIZE 8
14737 #define MAX_FUNCINFO_REC_SIZE 252
14739 static int check_btf_func(struct bpf_verifier_env *env,
14740 const union bpf_attr *attr,
14743 const struct btf_type *type, *func_proto, *ret_type;
14744 u32 i, nfuncs, urec_size, min_size;
14745 u32 krec_size = sizeof(struct bpf_func_info);
14746 struct bpf_func_info *krecord;
14747 struct bpf_func_info_aux *info_aux = NULL;
14748 struct bpf_prog *prog;
14749 const struct btf *btf;
14751 u32 prev_offset = 0;
14752 bool scalar_return;
14755 nfuncs = attr->func_info_cnt;
14757 if (check_abnormal_return(env))
14762 if (nfuncs != env->subprog_cnt) {
14763 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14767 urec_size = attr->func_info_rec_size;
14768 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14769 urec_size > MAX_FUNCINFO_REC_SIZE ||
14770 urec_size % sizeof(u32)) {
14771 verbose(env, "invalid func info rec size %u\n", urec_size);
14776 btf = prog->aux->btf;
14778 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
14779 min_size = min_t(u32, krec_size, urec_size);
14781 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
14784 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
14788 for (i = 0; i < nfuncs; i++) {
14789 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
14791 if (ret == -E2BIG) {
14792 verbose(env, "nonzero tailing record in func info");
14793 /* set the size kernel expects so loader can zero
14794 * out the rest of the record.
14796 if (copy_to_bpfptr_offset(uattr,
14797 offsetof(union bpf_attr, func_info_rec_size),
14798 &min_size, sizeof(min_size)))
14804 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
14809 /* check insn_off */
14812 if (krecord[i].insn_off) {
14814 "nonzero insn_off %u for the first func info record",
14815 krecord[i].insn_off);
14818 } else if (krecord[i].insn_off <= prev_offset) {
14820 "same or smaller insn offset (%u) than previous func info record (%u)",
14821 krecord[i].insn_off, prev_offset);
14825 if (env->subprog_info[i].start != krecord[i].insn_off) {
14826 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
14830 /* check type_id */
14831 type = btf_type_by_id(btf, krecord[i].type_id);
14832 if (!type || !btf_type_is_func(type)) {
14833 verbose(env, "invalid type id %d in func info",
14834 krecord[i].type_id);
14837 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
14839 func_proto = btf_type_by_id(btf, type->type);
14840 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
14841 /* btf_func_check() already verified it during BTF load */
14843 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
14845 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
14846 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
14847 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
14850 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
14851 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
14855 prev_offset = krecord[i].insn_off;
14856 bpfptr_add(&urecord, urec_size);
14859 prog->aux->func_info = krecord;
14860 prog->aux->func_info_cnt = nfuncs;
14861 prog->aux->func_info_aux = info_aux;
14870 static void adjust_btf_func(struct bpf_verifier_env *env)
14872 struct bpf_prog_aux *aux = env->prog->aux;
14875 if (!aux->func_info)
14878 for (i = 0; i < env->subprog_cnt; i++)
14879 aux->func_info[i].insn_off = env->subprog_info[i].start;
14882 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
14883 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
14885 static int check_btf_line(struct bpf_verifier_env *env,
14886 const union bpf_attr *attr,
14889 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
14890 struct bpf_subprog_info *sub;
14891 struct bpf_line_info *linfo;
14892 struct bpf_prog *prog;
14893 const struct btf *btf;
14897 nr_linfo = attr->line_info_cnt;
14900 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
14903 rec_size = attr->line_info_rec_size;
14904 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
14905 rec_size > MAX_LINEINFO_REC_SIZE ||
14906 rec_size & (sizeof(u32) - 1))
14909 /* Need to zero it in case the userspace may
14910 * pass in a smaller bpf_line_info object.
14912 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
14913 GFP_KERNEL | __GFP_NOWARN);
14918 btf = prog->aux->btf;
14921 sub = env->subprog_info;
14922 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
14923 expected_size = sizeof(struct bpf_line_info);
14924 ncopy = min_t(u32, expected_size, rec_size);
14925 for (i = 0; i < nr_linfo; i++) {
14926 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
14928 if (err == -E2BIG) {
14929 verbose(env, "nonzero tailing record in line_info");
14930 if (copy_to_bpfptr_offset(uattr,
14931 offsetof(union bpf_attr, line_info_rec_size),
14932 &expected_size, sizeof(expected_size)))
14938 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
14944 * Check insn_off to ensure
14945 * 1) strictly increasing AND
14946 * 2) bounded by prog->len
14948 * The linfo[0].insn_off == 0 check logically falls into
14949 * the later "missing bpf_line_info for func..." case
14950 * because the first linfo[0].insn_off must be the
14951 * first sub also and the first sub must have
14952 * subprog_info[0].start == 0.
14954 if ((i && linfo[i].insn_off <= prev_offset) ||
14955 linfo[i].insn_off >= prog->len) {
14956 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
14957 i, linfo[i].insn_off, prev_offset,
14963 if (!prog->insnsi[linfo[i].insn_off].code) {
14965 "Invalid insn code at line_info[%u].insn_off\n",
14971 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
14972 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
14973 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
14978 if (s != env->subprog_cnt) {
14979 if (linfo[i].insn_off == sub[s].start) {
14980 sub[s].linfo_idx = i;
14982 } else if (sub[s].start < linfo[i].insn_off) {
14983 verbose(env, "missing bpf_line_info for func#%u\n", s);
14989 prev_offset = linfo[i].insn_off;
14990 bpfptr_add(&ulinfo, rec_size);
14993 if (s != env->subprog_cnt) {
14994 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
14995 env->subprog_cnt - s, s);
15000 prog->aux->linfo = linfo;
15001 prog->aux->nr_linfo = nr_linfo;
15010 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
15011 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
15013 static int check_core_relo(struct bpf_verifier_env *env,
15014 const union bpf_attr *attr,
15017 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15018 struct bpf_core_relo core_relo = {};
15019 struct bpf_prog *prog = env->prog;
15020 const struct btf *btf = prog->aux->btf;
15021 struct bpf_core_ctx ctx = {
15025 bpfptr_t u_core_relo;
15028 nr_core_relo = attr->core_relo_cnt;
15031 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15034 rec_size = attr->core_relo_rec_size;
15035 if (rec_size < MIN_CORE_RELO_SIZE ||
15036 rec_size > MAX_CORE_RELO_SIZE ||
15037 rec_size % sizeof(u32))
15040 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15041 expected_size = sizeof(struct bpf_core_relo);
15042 ncopy = min_t(u32, expected_size, rec_size);
15044 /* Unlike func_info and line_info, copy and apply each CO-RE
15045 * relocation record one at a time.
15047 for (i = 0; i < nr_core_relo; i++) {
15048 /* future proofing when sizeof(bpf_core_relo) changes */
15049 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15051 if (err == -E2BIG) {
15052 verbose(env, "nonzero tailing record in core_relo");
15053 if (copy_to_bpfptr_offset(uattr,
15054 offsetof(union bpf_attr, core_relo_rec_size),
15055 &expected_size, sizeof(expected_size)))
15061 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15066 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15067 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15068 i, core_relo.insn_off, prog->len);
15073 err = bpf_core_apply(&ctx, &core_relo, i,
15074 &prog->insnsi[core_relo.insn_off / 8]);
15077 bpfptr_add(&u_core_relo, rec_size);
15082 static int check_btf_info(struct bpf_verifier_env *env,
15083 const union bpf_attr *attr,
15089 if (!attr->func_info_cnt && !attr->line_info_cnt) {
15090 if (check_abnormal_return(env))
15095 btf = btf_get_by_fd(attr->prog_btf_fd);
15097 return PTR_ERR(btf);
15098 if (btf_is_kernel(btf)) {
15102 env->prog->aux->btf = btf;
15104 err = check_btf_func(env, attr, uattr);
15108 err = check_btf_line(env, attr, uattr);
15112 err = check_core_relo(env, attr, uattr);
15119 /* check %cur's range satisfies %old's */
15120 static bool range_within(struct bpf_reg_state *old,
15121 struct bpf_reg_state *cur)
15123 return old->umin_value <= cur->umin_value &&
15124 old->umax_value >= cur->umax_value &&
15125 old->smin_value <= cur->smin_value &&
15126 old->smax_value >= cur->smax_value &&
15127 old->u32_min_value <= cur->u32_min_value &&
15128 old->u32_max_value >= cur->u32_max_value &&
15129 old->s32_min_value <= cur->s32_min_value &&
15130 old->s32_max_value >= cur->s32_max_value;
15133 /* If in the old state two registers had the same id, then they need to have
15134 * the same id in the new state as well. But that id could be different from
15135 * the old state, so we need to track the mapping from old to new ids.
15136 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15137 * regs with old id 5 must also have new id 9 for the new state to be safe. But
15138 * regs with a different old id could still have new id 9, we don't care about
15140 * So we look through our idmap to see if this old id has been seen before. If
15141 * so, we require the new id to match; otherwise, we add the id pair to the map.
15143 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15145 struct bpf_id_pair *map = idmap->map;
15148 /* either both IDs should be set or both should be zero */
15149 if (!!old_id != !!cur_id)
15152 if (old_id == 0) /* cur_id == 0 as well */
15155 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15157 /* Reached an empty slot; haven't seen this id before */
15158 map[i].old = old_id;
15159 map[i].cur = cur_id;
15162 if (map[i].old == old_id)
15163 return map[i].cur == cur_id;
15164 if (map[i].cur == cur_id)
15167 /* We ran out of idmap slots, which should be impossible */
15172 /* Similar to check_ids(), but allocate a unique temporary ID
15173 * for 'old_id' or 'cur_id' of zero.
15174 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15176 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15178 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15179 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15181 return check_ids(old_id, cur_id, idmap);
15184 static void clean_func_state(struct bpf_verifier_env *env,
15185 struct bpf_func_state *st)
15187 enum bpf_reg_liveness live;
15190 for (i = 0; i < BPF_REG_FP; i++) {
15191 live = st->regs[i].live;
15192 /* liveness must not touch this register anymore */
15193 st->regs[i].live |= REG_LIVE_DONE;
15194 if (!(live & REG_LIVE_READ))
15195 /* since the register is unused, clear its state
15196 * to make further comparison simpler
15198 __mark_reg_not_init(env, &st->regs[i]);
15201 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15202 live = st->stack[i].spilled_ptr.live;
15203 /* liveness must not touch this stack slot anymore */
15204 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15205 if (!(live & REG_LIVE_READ)) {
15206 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15207 for (j = 0; j < BPF_REG_SIZE; j++)
15208 st->stack[i].slot_type[j] = STACK_INVALID;
15213 static void clean_verifier_state(struct bpf_verifier_env *env,
15214 struct bpf_verifier_state *st)
15218 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15219 /* all regs in this state in all frames were already marked */
15222 for (i = 0; i <= st->curframe; i++)
15223 clean_func_state(env, st->frame[i]);
15226 /* the parentage chains form a tree.
15227 * the verifier states are added to state lists at given insn and
15228 * pushed into state stack for future exploration.
15229 * when the verifier reaches bpf_exit insn some of the verifer states
15230 * stored in the state lists have their final liveness state already,
15231 * but a lot of states will get revised from liveness point of view when
15232 * the verifier explores other branches.
15235 * 2: if r1 == 100 goto pc+1
15238 * when the verifier reaches exit insn the register r0 in the state list of
15239 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15240 * of insn 2 and goes exploring further. At the insn 4 it will walk the
15241 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15243 * Since the verifier pushes the branch states as it sees them while exploring
15244 * the program the condition of walking the branch instruction for the second
15245 * time means that all states below this branch were already explored and
15246 * their final liveness marks are already propagated.
15247 * Hence when the verifier completes the search of state list in is_state_visited()
15248 * we can call this clean_live_states() function to mark all liveness states
15249 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15250 * will not be used.
15251 * This function also clears the registers and stack for states that !READ
15252 * to simplify state merging.
15254 * Important note here that walking the same branch instruction in the callee
15255 * doesn't meant that the states are DONE. The verifier has to compare
15258 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15259 struct bpf_verifier_state *cur)
15261 struct bpf_verifier_state_list *sl;
15264 sl = *explored_state(env, insn);
15266 if (sl->state.branches)
15268 if (sl->state.insn_idx != insn ||
15269 sl->state.curframe != cur->curframe)
15271 for (i = 0; i <= cur->curframe; i++)
15272 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15274 clean_verifier_state(env, &sl->state);
15280 static bool regs_exact(const struct bpf_reg_state *rold,
15281 const struct bpf_reg_state *rcur,
15282 struct bpf_idmap *idmap)
15284 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15285 check_ids(rold->id, rcur->id, idmap) &&
15286 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15289 /* Returns true if (rold safe implies rcur safe) */
15290 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15291 struct bpf_reg_state *rcur, struct bpf_idmap *idmap)
15293 if (!(rold->live & REG_LIVE_READ))
15294 /* explored state didn't use this */
15296 if (rold->type == NOT_INIT)
15297 /* explored state can't have used this */
15299 if (rcur->type == NOT_INIT)
15302 /* Enforce that register types have to match exactly, including their
15303 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15306 * One can make a point that using a pointer register as unbounded
15307 * SCALAR would be technically acceptable, but this could lead to
15308 * pointer leaks because scalars are allowed to leak while pointers
15309 * are not. We could make this safe in special cases if root is
15310 * calling us, but it's probably not worth the hassle.
15312 * Also, register types that are *not* MAYBE_NULL could technically be
15313 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15314 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15315 * to the same map).
15316 * However, if the old MAYBE_NULL register then got NULL checked,
15317 * doing so could have affected others with the same id, and we can't
15318 * check for that because we lost the id when we converted to
15319 * a non-MAYBE_NULL variant.
15320 * So, as a general rule we don't allow mixing MAYBE_NULL and
15321 * non-MAYBE_NULL registers as well.
15323 if (rold->type != rcur->type)
15326 switch (base_type(rold->type)) {
15328 if (env->explore_alu_limits) {
15329 /* explore_alu_limits disables tnum_in() and range_within()
15330 * logic and requires everything to be strict
15332 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15333 check_scalar_ids(rold->id, rcur->id, idmap);
15335 if (!rold->precise)
15337 /* Why check_ids() for scalar registers?
15339 * Consider the following BPF code:
15340 * 1: r6 = ... unbound scalar, ID=a ...
15341 * 2: r7 = ... unbound scalar, ID=b ...
15342 * 3: if (r6 > r7) goto +1
15344 * 5: if (r6 > X) goto ...
15345 * 6: ... memory operation using r7 ...
15347 * First verification path is [1-6]:
15348 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15349 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15350 * r7 <= X, because r6 and r7 share same id.
15351 * Next verification path is [1-4, 6].
15353 * Instruction (6) would be reached in two states:
15354 * I. r6{.id=b}, r7{.id=b} via path 1-6;
15355 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15357 * Use check_ids() to distinguish these states.
15359 * Also verify that new value satisfies old value range knowledge.
15361 return range_within(rold, rcur) &&
15362 tnum_in(rold->var_off, rcur->var_off) &&
15363 check_scalar_ids(rold->id, rcur->id, idmap);
15364 case PTR_TO_MAP_KEY:
15365 case PTR_TO_MAP_VALUE:
15368 case PTR_TO_TP_BUFFER:
15369 /* If the new min/max/var_off satisfy the old ones and
15370 * everything else matches, we are OK.
15372 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15373 range_within(rold, rcur) &&
15374 tnum_in(rold->var_off, rcur->var_off) &&
15375 check_ids(rold->id, rcur->id, idmap) &&
15376 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15377 case PTR_TO_PACKET_META:
15378 case PTR_TO_PACKET:
15379 /* We must have at least as much range as the old ptr
15380 * did, so that any accesses which were safe before are
15381 * still safe. This is true even if old range < old off,
15382 * since someone could have accessed through (ptr - k), or
15383 * even done ptr -= k in a register, to get a safe access.
15385 if (rold->range > rcur->range)
15387 /* If the offsets don't match, we can't trust our alignment;
15388 * nor can we be sure that we won't fall out of range.
15390 if (rold->off != rcur->off)
15392 /* id relations must be preserved */
15393 if (!check_ids(rold->id, rcur->id, idmap))
15395 /* new val must satisfy old val knowledge */
15396 return range_within(rold, rcur) &&
15397 tnum_in(rold->var_off, rcur->var_off);
15399 /* two stack pointers are equal only if they're pointing to
15400 * the same stack frame, since fp-8 in foo != fp-8 in bar
15402 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15404 return regs_exact(rold, rcur, idmap);
15408 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15409 struct bpf_func_state *cur, struct bpf_idmap *idmap)
15413 /* walk slots of the explored stack and ignore any additional
15414 * slots in the current stack, since explored(safe) state
15417 for (i = 0; i < old->allocated_stack; i++) {
15418 struct bpf_reg_state *old_reg, *cur_reg;
15420 spi = i / BPF_REG_SIZE;
15422 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15423 i += BPF_REG_SIZE - 1;
15424 /* explored state didn't use this */
15428 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15431 if (env->allow_uninit_stack &&
15432 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15435 /* explored stack has more populated slots than current stack
15436 * and these slots were used
15438 if (i >= cur->allocated_stack)
15441 /* if old state was safe with misc data in the stack
15442 * it will be safe with zero-initialized stack.
15443 * The opposite is not true
15445 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15446 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15448 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15449 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15450 /* Ex: old explored (safe) state has STACK_SPILL in
15451 * this stack slot, but current has STACK_MISC ->
15452 * this verifier states are not equivalent,
15453 * return false to continue verification of this path
15456 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15458 /* Both old and cur are having same slot_type */
15459 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15461 /* when explored and current stack slot are both storing
15462 * spilled registers, check that stored pointers types
15463 * are the same as well.
15464 * Ex: explored safe path could have stored
15465 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15466 * but current path has stored:
15467 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15468 * such verifier states are not equivalent.
15469 * return false to continue verification of this path
15471 if (!regsafe(env, &old->stack[spi].spilled_ptr,
15472 &cur->stack[spi].spilled_ptr, idmap))
15476 old_reg = &old->stack[spi].spilled_ptr;
15477 cur_reg = &cur->stack[spi].spilled_ptr;
15478 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15479 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15480 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15484 old_reg = &old->stack[spi].spilled_ptr;
15485 cur_reg = &cur->stack[spi].spilled_ptr;
15486 /* iter.depth is not compared between states as it
15487 * doesn't matter for correctness and would otherwise
15488 * prevent convergence; we maintain it only to prevent
15489 * infinite loop check triggering, see
15490 * iter_active_depths_differ()
15492 if (old_reg->iter.btf != cur_reg->iter.btf ||
15493 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15494 old_reg->iter.state != cur_reg->iter.state ||
15495 /* ignore {old_reg,cur_reg}->iter.depth, see above */
15496 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15501 case STACK_INVALID:
15503 /* Ensure that new unhandled slot types return false by default */
15511 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15512 struct bpf_idmap *idmap)
15516 if (old->acquired_refs != cur->acquired_refs)
15519 for (i = 0; i < old->acquired_refs; i++) {
15520 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15527 /* compare two verifier states
15529 * all states stored in state_list are known to be valid, since
15530 * verifier reached 'bpf_exit' instruction through them
15532 * this function is called when verifier exploring different branches of
15533 * execution popped from the state stack. If it sees an old state that has
15534 * more strict register state and more strict stack state then this execution
15535 * branch doesn't need to be explored further, since verifier already
15536 * concluded that more strict state leads to valid finish.
15538 * Therefore two states are equivalent if register state is more conservative
15539 * and explored stack state is more conservative than the current one.
15542 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15543 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15545 * In other words if current stack state (one being explored) has more
15546 * valid slots than old one that already passed validation, it means
15547 * the verifier can stop exploring and conclude that current state is valid too
15549 * Similarly with registers. If explored state has register type as invalid
15550 * whereas register type in current state is meaningful, it means that
15551 * the current state will reach 'bpf_exit' instruction safely
15553 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15554 struct bpf_func_state *cur)
15558 for (i = 0; i < MAX_BPF_REG; i++)
15559 if (!regsafe(env, &old->regs[i], &cur->regs[i],
15560 &env->idmap_scratch))
15563 if (!stacksafe(env, old, cur, &env->idmap_scratch))
15566 if (!refsafe(old, cur, &env->idmap_scratch))
15572 static bool states_equal(struct bpf_verifier_env *env,
15573 struct bpf_verifier_state *old,
15574 struct bpf_verifier_state *cur)
15578 if (old->curframe != cur->curframe)
15581 env->idmap_scratch.tmp_id_gen = env->id_gen;
15582 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
15584 /* Verification state from speculative execution simulation
15585 * must never prune a non-speculative execution one.
15587 if (old->speculative && !cur->speculative)
15590 if (old->active_lock.ptr != cur->active_lock.ptr)
15593 /* Old and cur active_lock's have to be either both present
15596 if (!!old->active_lock.id != !!cur->active_lock.id)
15599 if (old->active_lock.id &&
15600 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
15603 if (old->active_rcu_lock != cur->active_rcu_lock)
15606 /* for states to be equal callsites have to be the same
15607 * and all frame states need to be equivalent
15609 for (i = 0; i <= old->curframe; i++) {
15610 if (old->frame[i]->callsite != cur->frame[i]->callsite)
15612 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15618 /* Return 0 if no propagation happened. Return negative error code if error
15619 * happened. Otherwise, return the propagated bit.
15621 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15622 struct bpf_reg_state *reg,
15623 struct bpf_reg_state *parent_reg)
15625 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15626 u8 flag = reg->live & REG_LIVE_READ;
15629 /* When comes here, read flags of PARENT_REG or REG could be any of
15630 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15631 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15633 if (parent_flag == REG_LIVE_READ64 ||
15634 /* Or if there is no read flag from REG. */
15636 /* Or if the read flag from REG is the same as PARENT_REG. */
15637 parent_flag == flag)
15640 err = mark_reg_read(env, reg, parent_reg, flag);
15647 /* A write screens off any subsequent reads; but write marks come from the
15648 * straight-line code between a state and its parent. When we arrive at an
15649 * equivalent state (jump target or such) we didn't arrive by the straight-line
15650 * code, so read marks in the state must propagate to the parent regardless
15651 * of the state's write marks. That's what 'parent == state->parent' comparison
15652 * in mark_reg_read() is for.
15654 static int propagate_liveness(struct bpf_verifier_env *env,
15655 const struct bpf_verifier_state *vstate,
15656 struct bpf_verifier_state *vparent)
15658 struct bpf_reg_state *state_reg, *parent_reg;
15659 struct bpf_func_state *state, *parent;
15660 int i, frame, err = 0;
15662 if (vparent->curframe != vstate->curframe) {
15663 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15664 vparent->curframe, vstate->curframe);
15667 /* Propagate read liveness of registers... */
15668 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15669 for (frame = 0; frame <= vstate->curframe; frame++) {
15670 parent = vparent->frame[frame];
15671 state = vstate->frame[frame];
15672 parent_reg = parent->regs;
15673 state_reg = state->regs;
15674 /* We don't need to worry about FP liveness, it's read-only */
15675 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15676 err = propagate_liveness_reg(env, &state_reg[i],
15680 if (err == REG_LIVE_READ64)
15681 mark_insn_zext(env, &parent_reg[i]);
15684 /* Propagate stack slots. */
15685 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15686 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15687 parent_reg = &parent->stack[i].spilled_ptr;
15688 state_reg = &state->stack[i].spilled_ptr;
15689 err = propagate_liveness_reg(env, state_reg,
15698 /* find precise scalars in the previous equivalent state and
15699 * propagate them into the current state
15701 static int propagate_precision(struct bpf_verifier_env *env,
15702 const struct bpf_verifier_state *old)
15704 struct bpf_reg_state *state_reg;
15705 struct bpf_func_state *state;
15706 int i, err = 0, fr;
15709 for (fr = old->curframe; fr >= 0; fr--) {
15710 state = old->frame[fr];
15711 state_reg = state->regs;
15713 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15714 if (state_reg->type != SCALAR_VALUE ||
15715 !state_reg->precise ||
15716 !(state_reg->live & REG_LIVE_READ))
15718 if (env->log.level & BPF_LOG_LEVEL2) {
15720 verbose(env, "frame %d: propagating r%d", fr, i);
15722 verbose(env, ",r%d", i);
15724 bt_set_frame_reg(&env->bt, fr, i);
15728 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15729 if (!is_spilled_reg(&state->stack[i]))
15731 state_reg = &state->stack[i].spilled_ptr;
15732 if (state_reg->type != SCALAR_VALUE ||
15733 !state_reg->precise ||
15734 !(state_reg->live & REG_LIVE_READ))
15736 if (env->log.level & BPF_LOG_LEVEL2) {
15738 verbose(env, "frame %d: propagating fp%d",
15739 fr, (-i - 1) * BPF_REG_SIZE);
15741 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15743 bt_set_frame_slot(&env->bt, fr, i);
15747 verbose(env, "\n");
15750 err = mark_chain_precision_batch(env);
15757 static bool states_maybe_looping(struct bpf_verifier_state *old,
15758 struct bpf_verifier_state *cur)
15760 struct bpf_func_state *fold, *fcur;
15761 int i, fr = cur->curframe;
15763 if (old->curframe != fr)
15766 fold = old->frame[fr];
15767 fcur = cur->frame[fr];
15768 for (i = 0; i < MAX_BPF_REG; i++)
15769 if (memcmp(&fold->regs[i], &fcur->regs[i],
15770 offsetof(struct bpf_reg_state, parent)))
15775 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15777 return env->insn_aux_data[insn_idx].is_iter_next;
15780 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
15781 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15782 * states to match, which otherwise would look like an infinite loop. So while
15783 * iter_next() calls are taken care of, we still need to be careful and
15784 * prevent erroneous and too eager declaration of "ininite loop", when
15785 * iterators are involved.
15787 * Here's a situation in pseudo-BPF assembly form:
15789 * 0: again: ; set up iter_next() call args
15790 * 1: r1 = &it ; <CHECKPOINT HERE>
15791 * 2: call bpf_iter_num_next ; this is iter_next() call
15792 * 3: if r0 == 0 goto done
15793 * 4: ... something useful here ...
15794 * 5: goto again ; another iteration
15797 * 8: call bpf_iter_num_destroy ; clean up iter state
15800 * This is a typical loop. Let's assume that we have a prune point at 1:,
15801 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
15802 * again`, assuming other heuristics don't get in a way).
15804 * When we first time come to 1:, let's say we have some state X. We proceed
15805 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
15806 * Now we come back to validate that forked ACTIVE state. We proceed through
15807 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
15808 * are converging. But the problem is that we don't know that yet, as this
15809 * convergence has to happen at iter_next() call site only. So if nothing is
15810 * done, at 1: verifier will use bounded loop logic and declare infinite
15811 * looping (and would be *technically* correct, if not for iterator's
15812 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
15813 * don't want that. So what we do in process_iter_next_call() when we go on
15814 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
15815 * a different iteration. So when we suspect an infinite loop, we additionally
15816 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
15817 * pretend we are not looping and wait for next iter_next() call.
15819 * This only applies to ACTIVE state. In DRAINED state we don't expect to
15820 * loop, because that would actually mean infinite loop, as DRAINED state is
15821 * "sticky", and so we'll keep returning into the same instruction with the
15822 * same state (at least in one of possible code paths).
15824 * This approach allows to keep infinite loop heuristic even in the face of
15825 * active iterator. E.g., C snippet below is and will be detected as
15826 * inifintely looping:
15828 * struct bpf_iter_num it;
15831 * bpf_iter_num_new(&it, 0, 10);
15832 * while ((p = bpf_iter_num_next(&t))) {
15834 * while (x--) {} // <<-- infinite loop here
15838 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
15840 struct bpf_reg_state *slot, *cur_slot;
15841 struct bpf_func_state *state;
15844 for (fr = old->curframe; fr >= 0; fr--) {
15845 state = old->frame[fr];
15846 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15847 if (state->stack[i].slot_type[0] != STACK_ITER)
15850 slot = &state->stack[i].spilled_ptr;
15851 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
15854 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
15855 if (cur_slot->iter.depth != slot->iter.depth)
15862 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
15864 struct bpf_verifier_state_list *new_sl;
15865 struct bpf_verifier_state_list *sl, **pprev;
15866 struct bpf_verifier_state *cur = env->cur_state, *new;
15867 int i, j, err, states_cnt = 0;
15868 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
15869 bool add_new_state = force_new_state;
15871 /* bpf progs typically have pruning point every 4 instructions
15872 * http://vger.kernel.org/bpfconf2019.html#session-1
15873 * Do not add new state for future pruning if the verifier hasn't seen
15874 * at least 2 jumps and at least 8 instructions.
15875 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
15876 * In tests that amounts to up to 50% reduction into total verifier
15877 * memory consumption and 20% verifier time speedup.
15879 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
15880 env->insn_processed - env->prev_insn_processed >= 8)
15881 add_new_state = true;
15883 pprev = explored_state(env, insn_idx);
15886 clean_live_states(env, insn_idx, cur);
15890 if (sl->state.insn_idx != insn_idx)
15893 if (sl->state.branches) {
15894 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
15896 if (frame->in_async_callback_fn &&
15897 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
15898 /* Different async_entry_cnt means that the verifier is
15899 * processing another entry into async callback.
15900 * Seeing the same state is not an indication of infinite
15901 * loop or infinite recursion.
15902 * But finding the same state doesn't mean that it's safe
15903 * to stop processing the current state. The previous state
15904 * hasn't yet reached bpf_exit, since state.branches > 0.
15905 * Checking in_async_callback_fn alone is not enough either.
15906 * Since the verifier still needs to catch infinite loops
15907 * inside async callbacks.
15909 goto skip_inf_loop_check;
15911 /* BPF open-coded iterators loop detection is special.
15912 * states_maybe_looping() logic is too simplistic in detecting
15913 * states that *might* be equivalent, because it doesn't know
15914 * about ID remapping, so don't even perform it.
15915 * See process_iter_next_call() and iter_active_depths_differ()
15916 * for overview of the logic. When current and one of parent
15917 * states are detected as equivalent, it's a good thing: we prove
15918 * convergence and can stop simulating further iterations.
15919 * It's safe to assume that iterator loop will finish, taking into
15920 * account iter_next() contract of eventually returning
15921 * sticky NULL result.
15923 if (is_iter_next_insn(env, insn_idx)) {
15924 if (states_equal(env, &sl->state, cur)) {
15925 struct bpf_func_state *cur_frame;
15926 struct bpf_reg_state *iter_state, *iter_reg;
15929 cur_frame = cur->frame[cur->curframe];
15930 /* btf_check_iter_kfuncs() enforces that
15931 * iter state pointer is always the first arg
15933 iter_reg = &cur_frame->regs[BPF_REG_1];
15934 /* current state is valid due to states_equal(),
15935 * so we can assume valid iter and reg state,
15936 * no need for extra (re-)validations
15938 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
15939 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
15940 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
15943 goto skip_inf_loop_check;
15945 /* attempt to detect infinite loop to avoid unnecessary doomed work */
15946 if (states_maybe_looping(&sl->state, cur) &&
15947 states_equal(env, &sl->state, cur) &&
15948 !iter_active_depths_differ(&sl->state, cur)) {
15949 verbose_linfo(env, insn_idx, "; ");
15950 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
15953 /* if the verifier is processing a loop, avoid adding new state
15954 * too often, since different loop iterations have distinct
15955 * states and may not help future pruning.
15956 * This threshold shouldn't be too low to make sure that
15957 * a loop with large bound will be rejected quickly.
15958 * The most abusive loop will be:
15960 * if r1 < 1000000 goto pc-2
15961 * 1M insn_procssed limit / 100 == 10k peak states.
15962 * This threshold shouldn't be too high either, since states
15963 * at the end of the loop are likely to be useful in pruning.
15965 skip_inf_loop_check:
15966 if (!force_new_state &&
15967 env->jmps_processed - env->prev_jmps_processed < 20 &&
15968 env->insn_processed - env->prev_insn_processed < 100)
15969 add_new_state = false;
15972 if (states_equal(env, &sl->state, cur)) {
15975 /* reached equivalent register/stack state,
15976 * prune the search.
15977 * Registers read by the continuation are read by us.
15978 * If we have any write marks in env->cur_state, they
15979 * will prevent corresponding reads in the continuation
15980 * from reaching our parent (an explored_state). Our
15981 * own state will get the read marks recorded, but
15982 * they'll be immediately forgotten as we're pruning
15983 * this state and will pop a new one.
15985 err = propagate_liveness(env, &sl->state, cur);
15987 /* if previous state reached the exit with precision and
15988 * current state is equivalent to it (except precsion marks)
15989 * the precision needs to be propagated back in
15990 * the current state.
15992 err = err ? : push_jmp_history(env, cur);
15993 err = err ? : propagate_precision(env, &sl->state);
15999 /* when new state is not going to be added do not increase miss count.
16000 * Otherwise several loop iterations will remove the state
16001 * recorded earlier. The goal of these heuristics is to have
16002 * states from some iterations of the loop (some in the beginning
16003 * and some at the end) to help pruning.
16007 /* heuristic to determine whether this state is beneficial
16008 * to keep checking from state equivalence point of view.
16009 * Higher numbers increase max_states_per_insn and verification time,
16010 * but do not meaningfully decrease insn_processed.
16012 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
16013 /* the state is unlikely to be useful. Remove it to
16014 * speed up verification
16017 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
16018 u32 br = sl->state.branches;
16021 "BUG live_done but branches_to_explore %d\n",
16023 free_verifier_state(&sl->state, false);
16025 env->peak_states--;
16027 /* cannot free this state, since parentage chain may
16028 * walk it later. Add it for free_list instead to
16029 * be freed at the end of verification
16031 sl->next = env->free_list;
16032 env->free_list = sl;
16042 if (env->max_states_per_insn < states_cnt)
16043 env->max_states_per_insn = states_cnt;
16045 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16048 if (!add_new_state)
16051 /* There were no equivalent states, remember the current one.
16052 * Technically the current state is not proven to be safe yet,
16053 * but it will either reach outer most bpf_exit (which means it's safe)
16054 * or it will be rejected. When there are no loops the verifier won't be
16055 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16056 * again on the way to bpf_exit.
16057 * When looping the sl->state.branches will be > 0 and this state
16058 * will not be considered for equivalence until branches == 0.
16060 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16063 env->total_states++;
16064 env->peak_states++;
16065 env->prev_jmps_processed = env->jmps_processed;
16066 env->prev_insn_processed = env->insn_processed;
16068 /* forget precise markings we inherited, see __mark_chain_precision */
16069 if (env->bpf_capable)
16070 mark_all_scalars_imprecise(env, cur);
16072 /* add new state to the head of linked list */
16073 new = &new_sl->state;
16074 err = copy_verifier_state(new, cur);
16076 free_verifier_state(new, false);
16080 new->insn_idx = insn_idx;
16081 WARN_ONCE(new->branches != 1,
16082 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16085 cur->first_insn_idx = insn_idx;
16086 clear_jmp_history(cur);
16087 new_sl->next = *explored_state(env, insn_idx);
16088 *explored_state(env, insn_idx) = new_sl;
16089 /* connect new state to parentage chain. Current frame needs all
16090 * registers connected. Only r6 - r9 of the callers are alive (pushed
16091 * to the stack implicitly by JITs) so in callers' frames connect just
16092 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16093 * the state of the call instruction (with WRITTEN set), and r0 comes
16094 * from callee with its full parentage chain, anyway.
16096 /* clear write marks in current state: the writes we did are not writes
16097 * our child did, so they don't screen off its reads from us.
16098 * (There are no read marks in current state, because reads always mark
16099 * their parent and current state never has children yet. Only
16100 * explored_states can get read marks.)
16102 for (j = 0; j <= cur->curframe; j++) {
16103 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16104 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16105 for (i = 0; i < BPF_REG_FP; i++)
16106 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16109 /* all stack frames are accessible from callee, clear them all */
16110 for (j = 0; j <= cur->curframe; j++) {
16111 struct bpf_func_state *frame = cur->frame[j];
16112 struct bpf_func_state *newframe = new->frame[j];
16114 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16115 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16116 frame->stack[i].spilled_ptr.parent =
16117 &newframe->stack[i].spilled_ptr;
16123 /* Return true if it's OK to have the same insn return a different type. */
16124 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16126 switch (base_type(type)) {
16128 case PTR_TO_SOCKET:
16129 case PTR_TO_SOCK_COMMON:
16130 case PTR_TO_TCP_SOCK:
16131 case PTR_TO_XDP_SOCK:
16132 case PTR_TO_BTF_ID:
16139 /* If an instruction was previously used with particular pointer types, then we
16140 * need to be careful to avoid cases such as the below, where it may be ok
16141 * for one branch accessing the pointer, but not ok for the other branch:
16146 * R1 = some_other_valid_ptr;
16149 * R2 = *(u32 *)(R1 + 0);
16151 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16153 return src != prev && (!reg_type_mismatch_ok(src) ||
16154 !reg_type_mismatch_ok(prev));
16157 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16158 bool allow_trust_missmatch)
16160 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16162 if (*prev_type == NOT_INIT) {
16163 /* Saw a valid insn
16164 * dst_reg = *(u32 *)(src_reg + off)
16165 * save type to validate intersecting paths
16168 } else if (reg_type_mismatch(type, *prev_type)) {
16169 /* Abuser program is trying to use the same insn
16170 * dst_reg = *(u32*) (src_reg + off)
16171 * with different pointer types:
16172 * src_reg == ctx in one branch and
16173 * src_reg == stack|map in some other branch.
16176 if (allow_trust_missmatch &&
16177 base_type(type) == PTR_TO_BTF_ID &&
16178 base_type(*prev_type) == PTR_TO_BTF_ID) {
16180 * Have to support a use case when one path through
16181 * the program yields TRUSTED pointer while another
16182 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16185 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16187 verbose(env, "same insn cannot be used with different pointers\n");
16195 static int do_check(struct bpf_verifier_env *env)
16197 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16198 struct bpf_verifier_state *state = env->cur_state;
16199 struct bpf_insn *insns = env->prog->insnsi;
16200 struct bpf_reg_state *regs;
16201 int insn_cnt = env->prog->len;
16202 bool do_print_state = false;
16203 int prev_insn_idx = -1;
16206 struct bpf_insn *insn;
16210 env->prev_insn_idx = prev_insn_idx;
16211 if (env->insn_idx >= insn_cnt) {
16212 verbose(env, "invalid insn idx %d insn_cnt %d\n",
16213 env->insn_idx, insn_cnt);
16217 insn = &insns[env->insn_idx];
16218 class = BPF_CLASS(insn->code);
16220 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16222 "BPF program is too large. Processed %d insn\n",
16223 env->insn_processed);
16227 state->last_insn_idx = env->prev_insn_idx;
16229 if (is_prune_point(env, env->insn_idx)) {
16230 err = is_state_visited(env, env->insn_idx);
16234 /* found equivalent state, can prune the search */
16235 if (env->log.level & BPF_LOG_LEVEL) {
16236 if (do_print_state)
16237 verbose(env, "\nfrom %d to %d%s: safe\n",
16238 env->prev_insn_idx, env->insn_idx,
16239 env->cur_state->speculative ?
16240 " (speculative execution)" : "");
16242 verbose(env, "%d: safe\n", env->insn_idx);
16244 goto process_bpf_exit;
16248 if (is_jmp_point(env, env->insn_idx)) {
16249 err = push_jmp_history(env, state);
16254 if (signal_pending(current))
16257 if (need_resched())
16260 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16261 verbose(env, "\nfrom %d to %d%s:",
16262 env->prev_insn_idx, env->insn_idx,
16263 env->cur_state->speculative ?
16264 " (speculative execution)" : "");
16265 print_verifier_state(env, state->frame[state->curframe], true);
16266 do_print_state = false;
16269 if (env->log.level & BPF_LOG_LEVEL) {
16270 const struct bpf_insn_cbs cbs = {
16271 .cb_call = disasm_kfunc_name,
16272 .cb_print = verbose,
16273 .private_data = env,
16276 if (verifier_state_scratched(env))
16277 print_insn_state(env, state->frame[state->curframe]);
16279 verbose_linfo(env, env->insn_idx, "; ");
16280 env->prev_log_pos = env->log.end_pos;
16281 verbose(env, "%d: ", env->insn_idx);
16282 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16283 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16284 env->prev_log_pos = env->log.end_pos;
16287 if (bpf_prog_is_offloaded(env->prog->aux)) {
16288 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16289 env->prev_insn_idx);
16294 regs = cur_regs(env);
16295 sanitize_mark_insn_seen(env);
16296 prev_insn_idx = env->insn_idx;
16298 if (class == BPF_ALU || class == BPF_ALU64) {
16299 err = check_alu_op(env, insn);
16303 } else if (class == BPF_LDX) {
16304 enum bpf_reg_type src_reg_type;
16306 /* check for reserved fields is already done */
16308 /* check src operand */
16309 err = check_reg_arg(env, insn->src_reg, SRC_OP);
16313 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16317 src_reg_type = regs[insn->src_reg].type;
16319 /* check that memory (src_reg + off) is readable,
16320 * the state of dst_reg will be updated by this func
16322 err = check_mem_access(env, env->insn_idx, insn->src_reg,
16323 insn->off, BPF_SIZE(insn->code),
16324 BPF_READ, insn->dst_reg, false);
16328 err = save_aux_ptr_type(env, src_reg_type, true);
16331 } else if (class == BPF_STX) {
16332 enum bpf_reg_type dst_reg_type;
16334 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16335 err = check_atomic(env, env->insn_idx, insn);
16342 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16343 verbose(env, "BPF_STX uses reserved fields\n");
16347 /* check src1 operand */
16348 err = check_reg_arg(env, insn->src_reg, SRC_OP);
16351 /* check src2 operand */
16352 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16356 dst_reg_type = regs[insn->dst_reg].type;
16358 /* check that memory (dst_reg + off) is writeable */
16359 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16360 insn->off, BPF_SIZE(insn->code),
16361 BPF_WRITE, insn->src_reg, false);
16365 err = save_aux_ptr_type(env, dst_reg_type, false);
16368 } else if (class == BPF_ST) {
16369 enum bpf_reg_type dst_reg_type;
16371 if (BPF_MODE(insn->code) != BPF_MEM ||
16372 insn->src_reg != BPF_REG_0) {
16373 verbose(env, "BPF_ST uses reserved fields\n");
16376 /* check src operand */
16377 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16381 dst_reg_type = regs[insn->dst_reg].type;
16383 /* check that memory (dst_reg + off) is writeable */
16384 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16385 insn->off, BPF_SIZE(insn->code),
16386 BPF_WRITE, -1, false);
16390 err = save_aux_ptr_type(env, dst_reg_type, false);
16393 } else if (class == BPF_JMP || class == BPF_JMP32) {
16394 u8 opcode = BPF_OP(insn->code);
16396 env->jmps_processed++;
16397 if (opcode == BPF_CALL) {
16398 if (BPF_SRC(insn->code) != BPF_K ||
16399 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16400 && insn->off != 0) ||
16401 (insn->src_reg != BPF_REG_0 &&
16402 insn->src_reg != BPF_PSEUDO_CALL &&
16403 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16404 insn->dst_reg != BPF_REG_0 ||
16405 class == BPF_JMP32) {
16406 verbose(env, "BPF_CALL uses reserved fields\n");
16410 if (env->cur_state->active_lock.ptr) {
16411 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16412 (insn->src_reg == BPF_PSEUDO_CALL) ||
16413 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16414 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16415 verbose(env, "function calls are not allowed while holding a lock\n");
16419 if (insn->src_reg == BPF_PSEUDO_CALL)
16420 err = check_func_call(env, insn, &env->insn_idx);
16421 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16422 err = check_kfunc_call(env, insn, &env->insn_idx);
16424 err = check_helper_call(env, insn, &env->insn_idx);
16428 mark_reg_scratched(env, BPF_REG_0);
16429 } else if (opcode == BPF_JA) {
16430 if (BPF_SRC(insn->code) != BPF_K ||
16432 insn->src_reg != BPF_REG_0 ||
16433 insn->dst_reg != BPF_REG_0 ||
16434 class == BPF_JMP32) {
16435 verbose(env, "BPF_JA uses reserved fields\n");
16439 env->insn_idx += insn->off + 1;
16442 } else if (opcode == BPF_EXIT) {
16443 if (BPF_SRC(insn->code) != BPF_K ||
16445 insn->src_reg != BPF_REG_0 ||
16446 insn->dst_reg != BPF_REG_0 ||
16447 class == BPF_JMP32) {
16448 verbose(env, "BPF_EXIT uses reserved fields\n");
16452 if (env->cur_state->active_lock.ptr &&
16453 !in_rbtree_lock_required_cb(env)) {
16454 verbose(env, "bpf_spin_unlock is missing\n");
16458 if (env->cur_state->active_rcu_lock) {
16459 verbose(env, "bpf_rcu_read_unlock is missing\n");
16463 /* We must do check_reference_leak here before
16464 * prepare_func_exit to handle the case when
16465 * state->curframe > 0, it may be a callback
16466 * function, for which reference_state must
16467 * match caller reference state when it exits.
16469 err = check_reference_leak(env);
16473 if (state->curframe) {
16474 /* exit from nested function */
16475 err = prepare_func_exit(env, &env->insn_idx);
16478 do_print_state = true;
16482 err = check_return_code(env);
16486 mark_verifier_state_scratched(env);
16487 update_branch_counts(env, env->cur_state);
16488 err = pop_stack(env, &prev_insn_idx,
16489 &env->insn_idx, pop_log);
16491 if (err != -ENOENT)
16495 do_print_state = true;
16499 err = check_cond_jmp_op(env, insn, &env->insn_idx);
16503 } else if (class == BPF_LD) {
16504 u8 mode = BPF_MODE(insn->code);
16506 if (mode == BPF_ABS || mode == BPF_IND) {
16507 err = check_ld_abs(env, insn);
16511 } else if (mode == BPF_IMM) {
16512 err = check_ld_imm(env, insn);
16517 sanitize_mark_insn_seen(env);
16519 verbose(env, "invalid BPF_LD mode\n");
16523 verbose(env, "unknown insn class %d\n", class);
16533 static int find_btf_percpu_datasec(struct btf *btf)
16535 const struct btf_type *t;
16540 * Both vmlinux and module each have their own ".data..percpu"
16541 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16542 * types to look at only module's own BTF types.
16544 n = btf_nr_types(btf);
16545 if (btf_is_module(btf))
16546 i = btf_nr_types(btf_vmlinux);
16550 for(; i < n; i++) {
16551 t = btf_type_by_id(btf, i);
16552 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16555 tname = btf_name_by_offset(btf, t->name_off);
16556 if (!strcmp(tname, ".data..percpu"))
16563 /* replace pseudo btf_id with kernel symbol address */
16564 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16565 struct bpf_insn *insn,
16566 struct bpf_insn_aux_data *aux)
16568 const struct btf_var_secinfo *vsi;
16569 const struct btf_type *datasec;
16570 struct btf_mod_pair *btf_mod;
16571 const struct btf_type *t;
16572 const char *sym_name;
16573 bool percpu = false;
16574 u32 type, id = insn->imm;
16578 int i, btf_fd, err;
16580 btf_fd = insn[1].imm;
16582 btf = btf_get_by_fd(btf_fd);
16584 verbose(env, "invalid module BTF object FD specified.\n");
16588 if (!btf_vmlinux) {
16589 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16596 t = btf_type_by_id(btf, id);
16598 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16603 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16604 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16609 sym_name = btf_name_by_offset(btf, t->name_off);
16610 addr = kallsyms_lookup_name(sym_name);
16612 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16617 insn[0].imm = (u32)addr;
16618 insn[1].imm = addr >> 32;
16620 if (btf_type_is_func(t)) {
16621 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16622 aux->btf_var.mem_size = 0;
16626 datasec_id = find_btf_percpu_datasec(btf);
16627 if (datasec_id > 0) {
16628 datasec = btf_type_by_id(btf, datasec_id);
16629 for_each_vsi(i, datasec, vsi) {
16630 if (vsi->type == id) {
16638 t = btf_type_skip_modifiers(btf, type, NULL);
16640 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16641 aux->btf_var.btf = btf;
16642 aux->btf_var.btf_id = type;
16643 } else if (!btf_type_is_struct(t)) {
16644 const struct btf_type *ret;
16648 /* resolve the type size of ksym. */
16649 ret = btf_resolve_size(btf, t, &tsize);
16651 tname = btf_name_by_offset(btf, t->name_off);
16652 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16653 tname, PTR_ERR(ret));
16657 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16658 aux->btf_var.mem_size = tsize;
16660 aux->btf_var.reg_type = PTR_TO_BTF_ID;
16661 aux->btf_var.btf = btf;
16662 aux->btf_var.btf_id = type;
16665 /* check whether we recorded this BTF (and maybe module) already */
16666 for (i = 0; i < env->used_btf_cnt; i++) {
16667 if (env->used_btfs[i].btf == btf) {
16673 if (env->used_btf_cnt >= MAX_USED_BTFS) {
16678 btf_mod = &env->used_btfs[env->used_btf_cnt];
16679 btf_mod->btf = btf;
16680 btf_mod->module = NULL;
16682 /* if we reference variables from kernel module, bump its refcount */
16683 if (btf_is_module(btf)) {
16684 btf_mod->module = btf_try_get_module(btf);
16685 if (!btf_mod->module) {
16691 env->used_btf_cnt++;
16699 static bool is_tracing_prog_type(enum bpf_prog_type type)
16702 case BPF_PROG_TYPE_KPROBE:
16703 case BPF_PROG_TYPE_TRACEPOINT:
16704 case BPF_PROG_TYPE_PERF_EVENT:
16705 case BPF_PROG_TYPE_RAW_TRACEPOINT:
16706 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16713 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16714 struct bpf_map *map,
16715 struct bpf_prog *prog)
16718 enum bpf_prog_type prog_type = resolve_prog_type(prog);
16720 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16721 btf_record_has_field(map->record, BPF_RB_ROOT)) {
16722 if (is_tracing_prog_type(prog_type)) {
16723 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16728 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16729 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16730 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16734 if (is_tracing_prog_type(prog_type)) {
16735 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16739 if (prog->aux->sleepable) {
16740 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16745 if (btf_record_has_field(map->record, BPF_TIMER)) {
16746 if (is_tracing_prog_type(prog_type)) {
16747 verbose(env, "tracing progs cannot use bpf_timer yet\n");
16752 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16753 !bpf_offload_prog_map_match(prog, map)) {
16754 verbose(env, "offload device mismatch between prog and map\n");
16758 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16759 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16763 if (prog->aux->sleepable)
16764 switch (map->map_type) {
16765 case BPF_MAP_TYPE_HASH:
16766 case BPF_MAP_TYPE_LRU_HASH:
16767 case BPF_MAP_TYPE_ARRAY:
16768 case BPF_MAP_TYPE_PERCPU_HASH:
16769 case BPF_MAP_TYPE_PERCPU_ARRAY:
16770 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16771 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16772 case BPF_MAP_TYPE_HASH_OF_MAPS:
16773 case BPF_MAP_TYPE_RINGBUF:
16774 case BPF_MAP_TYPE_USER_RINGBUF:
16775 case BPF_MAP_TYPE_INODE_STORAGE:
16776 case BPF_MAP_TYPE_SK_STORAGE:
16777 case BPF_MAP_TYPE_TASK_STORAGE:
16778 case BPF_MAP_TYPE_CGRP_STORAGE:
16782 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
16789 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
16791 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
16792 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
16795 /* find and rewrite pseudo imm in ld_imm64 instructions:
16797 * 1. if it accesses map FD, replace it with actual map pointer.
16798 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
16800 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
16802 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
16804 struct bpf_insn *insn = env->prog->insnsi;
16805 int insn_cnt = env->prog->len;
16808 err = bpf_prog_calc_tag(env->prog);
16812 for (i = 0; i < insn_cnt; i++, insn++) {
16813 if (BPF_CLASS(insn->code) == BPF_LDX &&
16814 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
16815 verbose(env, "BPF_LDX uses reserved fields\n");
16819 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
16820 struct bpf_insn_aux_data *aux;
16821 struct bpf_map *map;
16826 if (i == insn_cnt - 1 || insn[1].code != 0 ||
16827 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
16828 insn[1].off != 0) {
16829 verbose(env, "invalid bpf_ld_imm64 insn\n");
16833 if (insn[0].src_reg == 0)
16834 /* valid generic load 64-bit imm */
16837 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
16838 aux = &env->insn_aux_data[i];
16839 err = check_pseudo_btf_id(env, insn, aux);
16845 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
16846 aux = &env->insn_aux_data[i];
16847 aux->ptr_type = PTR_TO_FUNC;
16851 /* In final convert_pseudo_ld_imm64() step, this is
16852 * converted into regular 64-bit imm load insn.
16854 switch (insn[0].src_reg) {
16855 case BPF_PSEUDO_MAP_VALUE:
16856 case BPF_PSEUDO_MAP_IDX_VALUE:
16858 case BPF_PSEUDO_MAP_FD:
16859 case BPF_PSEUDO_MAP_IDX:
16860 if (insn[1].imm == 0)
16864 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
16868 switch (insn[0].src_reg) {
16869 case BPF_PSEUDO_MAP_IDX_VALUE:
16870 case BPF_PSEUDO_MAP_IDX:
16871 if (bpfptr_is_null(env->fd_array)) {
16872 verbose(env, "fd_idx without fd_array is invalid\n");
16875 if (copy_from_bpfptr_offset(&fd, env->fd_array,
16876 insn[0].imm * sizeof(fd),
16886 map = __bpf_map_get(f);
16888 verbose(env, "fd %d is not pointing to valid bpf_map\n",
16890 return PTR_ERR(map);
16893 err = check_map_prog_compatibility(env, map, env->prog);
16899 aux = &env->insn_aux_data[i];
16900 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
16901 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
16902 addr = (unsigned long)map;
16904 u32 off = insn[1].imm;
16906 if (off >= BPF_MAX_VAR_OFF) {
16907 verbose(env, "direct value offset of %u is not allowed\n", off);
16912 if (!map->ops->map_direct_value_addr) {
16913 verbose(env, "no direct value access support for this map type\n");
16918 err = map->ops->map_direct_value_addr(map, &addr, off);
16920 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
16921 map->value_size, off);
16926 aux->map_off = off;
16930 insn[0].imm = (u32)addr;
16931 insn[1].imm = addr >> 32;
16933 /* check whether we recorded this map already */
16934 for (j = 0; j < env->used_map_cnt; j++) {
16935 if (env->used_maps[j] == map) {
16936 aux->map_index = j;
16942 if (env->used_map_cnt >= MAX_USED_MAPS) {
16947 /* hold the map. If the program is rejected by verifier,
16948 * the map will be released by release_maps() or it
16949 * will be used by the valid program until it's unloaded
16950 * and all maps are released in free_used_maps()
16954 aux->map_index = env->used_map_cnt;
16955 env->used_maps[env->used_map_cnt++] = map;
16957 if (bpf_map_is_cgroup_storage(map) &&
16958 bpf_cgroup_storage_assign(env->prog->aux, map)) {
16959 verbose(env, "only one cgroup storage of each type is allowed\n");
16971 /* Basic sanity check before we invest more work here. */
16972 if (!bpf_opcode_in_insntable(insn->code)) {
16973 verbose(env, "unknown opcode %02x\n", insn->code);
16978 /* now all pseudo BPF_LD_IMM64 instructions load valid
16979 * 'struct bpf_map *' into a register instead of user map_fd.
16980 * These pointers will be used later by verifier to validate map access.
16985 /* drop refcnt of maps used by the rejected program */
16986 static void release_maps(struct bpf_verifier_env *env)
16988 __bpf_free_used_maps(env->prog->aux, env->used_maps,
16989 env->used_map_cnt);
16992 /* drop refcnt of maps used by the rejected program */
16993 static void release_btfs(struct bpf_verifier_env *env)
16995 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
16996 env->used_btf_cnt);
16999 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17000 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17002 struct bpf_insn *insn = env->prog->insnsi;
17003 int insn_cnt = env->prog->len;
17006 for (i = 0; i < insn_cnt; i++, insn++) {
17007 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17009 if (insn->src_reg == BPF_PSEUDO_FUNC)
17015 /* single env->prog->insni[off] instruction was replaced with the range
17016 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
17017 * [0, off) and [off, end) to new locations, so the patched range stays zero
17019 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17020 struct bpf_insn_aux_data *new_data,
17021 struct bpf_prog *new_prog, u32 off, u32 cnt)
17023 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17024 struct bpf_insn *insn = new_prog->insnsi;
17025 u32 old_seen = old_data[off].seen;
17029 /* aux info at OFF always needs adjustment, no matter fast path
17030 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17031 * original insn at old prog.
17033 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17037 prog_len = new_prog->len;
17039 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17040 memcpy(new_data + off + cnt - 1, old_data + off,
17041 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17042 for (i = off; i < off + cnt - 1; i++) {
17043 /* Expand insni[off]'s seen count to the patched range. */
17044 new_data[i].seen = old_seen;
17045 new_data[i].zext_dst = insn_has_def32(env, insn + i);
17047 env->insn_aux_data = new_data;
17051 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17057 /* NOTE: fake 'exit' subprog should be updated as well. */
17058 for (i = 0; i <= env->subprog_cnt; i++) {
17059 if (env->subprog_info[i].start <= off)
17061 env->subprog_info[i].start += len - 1;
17065 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17067 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17068 int i, sz = prog->aux->size_poke_tab;
17069 struct bpf_jit_poke_descriptor *desc;
17071 for (i = 0; i < sz; i++) {
17073 if (desc->insn_idx <= off)
17075 desc->insn_idx += len - 1;
17079 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17080 const struct bpf_insn *patch, u32 len)
17082 struct bpf_prog *new_prog;
17083 struct bpf_insn_aux_data *new_data = NULL;
17086 new_data = vzalloc(array_size(env->prog->len + len - 1,
17087 sizeof(struct bpf_insn_aux_data)));
17092 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17093 if (IS_ERR(new_prog)) {
17094 if (PTR_ERR(new_prog) == -ERANGE)
17096 "insn %d cannot be patched due to 16-bit range\n",
17097 env->insn_aux_data[off].orig_idx);
17101 adjust_insn_aux_data(env, new_data, new_prog, off, len);
17102 adjust_subprog_starts(env, off, len);
17103 adjust_poke_descs(new_prog, off, len);
17107 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17112 /* find first prog starting at or after off (first to remove) */
17113 for (i = 0; i < env->subprog_cnt; i++)
17114 if (env->subprog_info[i].start >= off)
17116 /* find first prog starting at or after off + cnt (first to stay) */
17117 for (j = i; j < env->subprog_cnt; j++)
17118 if (env->subprog_info[j].start >= off + cnt)
17120 /* if j doesn't start exactly at off + cnt, we are just removing
17121 * the front of previous prog
17123 if (env->subprog_info[j].start != off + cnt)
17127 struct bpf_prog_aux *aux = env->prog->aux;
17130 /* move fake 'exit' subprog as well */
17131 move = env->subprog_cnt + 1 - j;
17133 memmove(env->subprog_info + i,
17134 env->subprog_info + j,
17135 sizeof(*env->subprog_info) * move);
17136 env->subprog_cnt -= j - i;
17138 /* remove func_info */
17139 if (aux->func_info) {
17140 move = aux->func_info_cnt - j;
17142 memmove(aux->func_info + i,
17143 aux->func_info + j,
17144 sizeof(*aux->func_info) * move);
17145 aux->func_info_cnt -= j - i;
17146 /* func_info->insn_off is set after all code rewrites,
17147 * in adjust_btf_func() - no need to adjust
17151 /* convert i from "first prog to remove" to "first to adjust" */
17152 if (env->subprog_info[i].start == off)
17156 /* update fake 'exit' subprog as well */
17157 for (; i <= env->subprog_cnt; i++)
17158 env->subprog_info[i].start -= cnt;
17163 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17166 struct bpf_prog *prog = env->prog;
17167 u32 i, l_off, l_cnt, nr_linfo;
17168 struct bpf_line_info *linfo;
17170 nr_linfo = prog->aux->nr_linfo;
17174 linfo = prog->aux->linfo;
17176 /* find first line info to remove, count lines to be removed */
17177 for (i = 0; i < nr_linfo; i++)
17178 if (linfo[i].insn_off >= off)
17183 for (; i < nr_linfo; i++)
17184 if (linfo[i].insn_off < off + cnt)
17189 /* First live insn doesn't match first live linfo, it needs to "inherit"
17190 * last removed linfo. prog is already modified, so prog->len == off
17191 * means no live instructions after (tail of the program was removed).
17193 if (prog->len != off && l_cnt &&
17194 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17196 linfo[--i].insn_off = off + cnt;
17199 /* remove the line info which refer to the removed instructions */
17201 memmove(linfo + l_off, linfo + i,
17202 sizeof(*linfo) * (nr_linfo - i));
17204 prog->aux->nr_linfo -= l_cnt;
17205 nr_linfo = prog->aux->nr_linfo;
17208 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
17209 for (i = l_off; i < nr_linfo; i++)
17210 linfo[i].insn_off -= cnt;
17212 /* fix up all subprogs (incl. 'exit') which start >= off */
17213 for (i = 0; i <= env->subprog_cnt; i++)
17214 if (env->subprog_info[i].linfo_idx > l_off) {
17215 /* program may have started in the removed region but
17216 * may not be fully removed
17218 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17219 env->subprog_info[i].linfo_idx -= l_cnt;
17221 env->subprog_info[i].linfo_idx = l_off;
17227 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17229 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17230 unsigned int orig_prog_len = env->prog->len;
17233 if (bpf_prog_is_offloaded(env->prog->aux))
17234 bpf_prog_offload_remove_insns(env, off, cnt);
17236 err = bpf_remove_insns(env->prog, off, cnt);
17240 err = adjust_subprog_starts_after_remove(env, off, cnt);
17244 err = bpf_adj_linfo_after_remove(env, off, cnt);
17248 memmove(aux_data + off, aux_data + off + cnt,
17249 sizeof(*aux_data) * (orig_prog_len - off - cnt));
17254 /* The verifier does more data flow analysis than llvm and will not
17255 * explore branches that are dead at run time. Malicious programs can
17256 * have dead code too. Therefore replace all dead at-run-time code
17259 * Just nops are not optimal, e.g. if they would sit at the end of the
17260 * program and through another bug we would manage to jump there, then
17261 * we'd execute beyond program memory otherwise. Returning exception
17262 * code also wouldn't work since we can have subprogs where the dead
17263 * code could be located.
17265 static void sanitize_dead_code(struct bpf_verifier_env *env)
17267 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17268 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17269 struct bpf_insn *insn = env->prog->insnsi;
17270 const int insn_cnt = env->prog->len;
17273 for (i = 0; i < insn_cnt; i++) {
17274 if (aux_data[i].seen)
17276 memcpy(insn + i, &trap, sizeof(trap));
17277 aux_data[i].zext_dst = false;
17281 static bool insn_is_cond_jump(u8 code)
17285 if (BPF_CLASS(code) == BPF_JMP32)
17288 if (BPF_CLASS(code) != BPF_JMP)
17292 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17295 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17297 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17298 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17299 struct bpf_insn *insn = env->prog->insnsi;
17300 const int insn_cnt = env->prog->len;
17303 for (i = 0; i < insn_cnt; i++, insn++) {
17304 if (!insn_is_cond_jump(insn->code))
17307 if (!aux_data[i + 1].seen)
17308 ja.off = insn->off;
17309 else if (!aux_data[i + 1 + insn->off].seen)
17314 if (bpf_prog_is_offloaded(env->prog->aux))
17315 bpf_prog_offload_replace_insn(env, i, &ja);
17317 memcpy(insn, &ja, sizeof(ja));
17321 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17323 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17324 int insn_cnt = env->prog->len;
17327 for (i = 0; i < insn_cnt; i++) {
17331 while (i + j < insn_cnt && !aux_data[i + j].seen)
17336 err = verifier_remove_insns(env, i, j);
17339 insn_cnt = env->prog->len;
17345 static int opt_remove_nops(struct bpf_verifier_env *env)
17347 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17348 struct bpf_insn *insn = env->prog->insnsi;
17349 int insn_cnt = env->prog->len;
17352 for (i = 0; i < insn_cnt; i++) {
17353 if (memcmp(&insn[i], &ja, sizeof(ja)))
17356 err = verifier_remove_insns(env, i, 1);
17366 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17367 const union bpf_attr *attr)
17369 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17370 struct bpf_insn_aux_data *aux = env->insn_aux_data;
17371 int i, patch_len, delta = 0, len = env->prog->len;
17372 struct bpf_insn *insns = env->prog->insnsi;
17373 struct bpf_prog *new_prog;
17376 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17377 zext_patch[1] = BPF_ZEXT_REG(0);
17378 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17379 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17380 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17381 for (i = 0; i < len; i++) {
17382 int adj_idx = i + delta;
17383 struct bpf_insn insn;
17386 insn = insns[adj_idx];
17387 load_reg = insn_def_regno(&insn);
17388 if (!aux[adj_idx].zext_dst) {
17396 class = BPF_CLASS(code);
17397 if (load_reg == -1)
17400 /* NOTE: arg "reg" (the fourth one) is only used for
17401 * BPF_STX + SRC_OP, so it is safe to pass NULL
17404 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17405 if (class == BPF_LD &&
17406 BPF_MODE(code) == BPF_IMM)
17411 /* ctx load could be transformed into wider load. */
17412 if (class == BPF_LDX &&
17413 aux[adj_idx].ptr_type == PTR_TO_CTX)
17416 imm_rnd = get_random_u32();
17417 rnd_hi32_patch[0] = insn;
17418 rnd_hi32_patch[1].imm = imm_rnd;
17419 rnd_hi32_patch[3].dst_reg = load_reg;
17420 patch = rnd_hi32_patch;
17422 goto apply_patch_buffer;
17425 /* Add in an zero-extend instruction if a) the JIT has requested
17426 * it or b) it's a CMPXCHG.
17428 * The latter is because: BPF_CMPXCHG always loads a value into
17429 * R0, therefore always zero-extends. However some archs'
17430 * equivalent instruction only does this load when the
17431 * comparison is successful. This detail of CMPXCHG is
17432 * orthogonal to the general zero-extension behaviour of the
17433 * CPU, so it's treated independently of bpf_jit_needs_zext.
17435 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17438 /* Zero-extension is done by the caller. */
17439 if (bpf_pseudo_kfunc_call(&insn))
17442 if (WARN_ON(load_reg == -1)) {
17443 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17447 zext_patch[0] = insn;
17448 zext_patch[1].dst_reg = load_reg;
17449 zext_patch[1].src_reg = load_reg;
17450 patch = zext_patch;
17452 apply_patch_buffer:
17453 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17456 env->prog = new_prog;
17457 insns = new_prog->insnsi;
17458 aux = env->insn_aux_data;
17459 delta += patch_len - 1;
17465 /* convert load instructions that access fields of a context type into a
17466 * sequence of instructions that access fields of the underlying structure:
17467 * struct __sk_buff -> struct sk_buff
17468 * struct bpf_sock_ops -> struct sock
17470 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17472 const struct bpf_verifier_ops *ops = env->ops;
17473 int i, cnt, size, ctx_field_size, delta = 0;
17474 const int insn_cnt = env->prog->len;
17475 struct bpf_insn insn_buf[16], *insn;
17476 u32 target_size, size_default, off;
17477 struct bpf_prog *new_prog;
17478 enum bpf_access_type type;
17479 bool is_narrower_load;
17481 if (ops->gen_prologue || env->seen_direct_write) {
17482 if (!ops->gen_prologue) {
17483 verbose(env, "bpf verifier is misconfigured\n");
17486 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17488 if (cnt >= ARRAY_SIZE(insn_buf)) {
17489 verbose(env, "bpf verifier is misconfigured\n");
17492 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17496 env->prog = new_prog;
17501 if (bpf_prog_is_offloaded(env->prog->aux))
17504 insn = env->prog->insnsi + delta;
17506 for (i = 0; i < insn_cnt; i++, insn++) {
17507 bpf_convert_ctx_access_t convert_ctx_access;
17509 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17510 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17511 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17512 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
17514 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17515 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17516 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17517 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17518 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17519 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17520 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17521 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17527 if (type == BPF_WRITE &&
17528 env->insn_aux_data[i + delta].sanitize_stack_spill) {
17529 struct bpf_insn patch[] = {
17534 cnt = ARRAY_SIZE(patch);
17535 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17540 env->prog = new_prog;
17541 insn = new_prog->insnsi + i + delta;
17545 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17547 if (!ops->convert_ctx_access)
17549 convert_ctx_access = ops->convert_ctx_access;
17551 case PTR_TO_SOCKET:
17552 case PTR_TO_SOCK_COMMON:
17553 convert_ctx_access = bpf_sock_convert_ctx_access;
17555 case PTR_TO_TCP_SOCK:
17556 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17558 case PTR_TO_XDP_SOCK:
17559 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17561 case PTR_TO_BTF_ID:
17562 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17563 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17564 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17565 * be said once it is marked PTR_UNTRUSTED, hence we must handle
17566 * any faults for loads into such types. BPF_WRITE is disallowed
17569 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17570 if (type == BPF_READ) {
17571 insn->code = BPF_LDX | BPF_PROBE_MEM |
17572 BPF_SIZE((insn)->code);
17573 env->prog->aux->num_exentries++;
17580 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17581 size = BPF_LDST_BYTES(insn);
17583 /* If the read access is a narrower load of the field,
17584 * convert to a 4/8-byte load, to minimum program type specific
17585 * convert_ctx_access changes. If conversion is successful,
17586 * we will apply proper mask to the result.
17588 is_narrower_load = size < ctx_field_size;
17589 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17591 if (is_narrower_load) {
17594 if (type == BPF_WRITE) {
17595 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17600 if (ctx_field_size == 4)
17602 else if (ctx_field_size == 8)
17603 size_code = BPF_DW;
17605 insn->off = off & ~(size_default - 1);
17606 insn->code = BPF_LDX | BPF_MEM | size_code;
17610 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17612 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17613 (ctx_field_size && !target_size)) {
17614 verbose(env, "bpf verifier is misconfigured\n");
17618 if (is_narrower_load && size < target_size) {
17619 u8 shift = bpf_ctx_narrow_access_offset(
17620 off, size, size_default) * 8;
17621 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17622 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17625 if (ctx_field_size <= 4) {
17627 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17630 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17631 (1 << size * 8) - 1);
17634 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17637 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17638 (1ULL << size * 8) - 1);
17642 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17648 /* keep walking new program and skip insns we just inserted */
17649 env->prog = new_prog;
17650 insn = new_prog->insnsi + i + delta;
17656 static int jit_subprogs(struct bpf_verifier_env *env)
17658 struct bpf_prog *prog = env->prog, **func, *tmp;
17659 int i, j, subprog_start, subprog_end = 0, len, subprog;
17660 struct bpf_map *map_ptr;
17661 struct bpf_insn *insn;
17662 void *old_bpf_func;
17663 int err, num_exentries;
17665 if (env->subprog_cnt <= 1)
17668 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17669 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17672 /* Upon error here we cannot fall back to interpreter but
17673 * need a hard reject of the program. Thus -EFAULT is
17674 * propagated in any case.
17676 subprog = find_subprog(env, i + insn->imm + 1);
17678 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17679 i + insn->imm + 1);
17682 /* temporarily remember subprog id inside insn instead of
17683 * aux_data, since next loop will split up all insns into funcs
17685 insn->off = subprog;
17686 /* remember original imm in case JIT fails and fallback
17687 * to interpreter will be needed
17689 env->insn_aux_data[i].call_imm = insn->imm;
17690 /* point imm to __bpf_call_base+1 from JITs point of view */
17692 if (bpf_pseudo_func(insn))
17693 /* jit (e.g. x86_64) may emit fewer instructions
17694 * if it learns a u32 imm is the same as a u64 imm.
17695 * Force a non zero here.
17700 err = bpf_prog_alloc_jited_linfo(prog);
17702 goto out_undo_insn;
17705 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17707 goto out_undo_insn;
17709 for (i = 0; i < env->subprog_cnt; i++) {
17710 subprog_start = subprog_end;
17711 subprog_end = env->subprog_info[i + 1].start;
17713 len = subprog_end - subprog_start;
17714 /* bpf_prog_run() doesn't call subprogs directly,
17715 * hence main prog stats include the runtime of subprogs.
17716 * subprogs don't have IDs and not reachable via prog_get_next_id
17717 * func[i]->stats will never be accessed and stays NULL
17719 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17722 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17723 len * sizeof(struct bpf_insn));
17724 func[i]->type = prog->type;
17725 func[i]->len = len;
17726 if (bpf_prog_calc_tag(func[i]))
17728 func[i]->is_func = 1;
17729 func[i]->aux->func_idx = i;
17730 /* Below members will be freed only at prog->aux */
17731 func[i]->aux->btf = prog->aux->btf;
17732 func[i]->aux->func_info = prog->aux->func_info;
17733 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17734 func[i]->aux->poke_tab = prog->aux->poke_tab;
17735 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17737 for (j = 0; j < prog->aux->size_poke_tab; j++) {
17738 struct bpf_jit_poke_descriptor *poke;
17740 poke = &prog->aux->poke_tab[j];
17741 if (poke->insn_idx < subprog_end &&
17742 poke->insn_idx >= subprog_start)
17743 poke->aux = func[i]->aux;
17746 func[i]->aux->name[0] = 'F';
17747 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17748 func[i]->jit_requested = 1;
17749 func[i]->blinding_requested = prog->blinding_requested;
17750 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17751 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17752 func[i]->aux->linfo = prog->aux->linfo;
17753 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17754 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17755 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17757 insn = func[i]->insnsi;
17758 for (j = 0; j < func[i]->len; j++, insn++) {
17759 if (BPF_CLASS(insn->code) == BPF_LDX &&
17760 BPF_MODE(insn->code) == BPF_PROBE_MEM)
17763 func[i]->aux->num_exentries = num_exentries;
17764 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
17765 func[i] = bpf_int_jit_compile(func[i]);
17766 if (!func[i]->jited) {
17773 /* at this point all bpf functions were successfully JITed
17774 * now populate all bpf_calls with correct addresses and
17775 * run last pass of JIT
17777 for (i = 0; i < env->subprog_cnt; i++) {
17778 insn = func[i]->insnsi;
17779 for (j = 0; j < func[i]->len; j++, insn++) {
17780 if (bpf_pseudo_func(insn)) {
17781 subprog = insn->off;
17782 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
17783 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
17786 if (!bpf_pseudo_call(insn))
17788 subprog = insn->off;
17789 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
17792 /* we use the aux data to keep a list of the start addresses
17793 * of the JITed images for each function in the program
17795 * for some architectures, such as powerpc64, the imm field
17796 * might not be large enough to hold the offset of the start
17797 * address of the callee's JITed image from __bpf_call_base
17799 * in such cases, we can lookup the start address of a callee
17800 * by using its subprog id, available from the off field of
17801 * the call instruction, as an index for this list
17803 func[i]->aux->func = func;
17804 func[i]->aux->func_cnt = env->subprog_cnt;
17806 for (i = 0; i < env->subprog_cnt; i++) {
17807 old_bpf_func = func[i]->bpf_func;
17808 tmp = bpf_int_jit_compile(func[i]);
17809 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
17810 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
17817 /* finally lock prog and jit images for all functions and
17818 * populate kallsysm. Begin at the first subprogram, since
17819 * bpf_prog_load will add the kallsyms for the main program.
17821 for (i = 1; i < env->subprog_cnt; i++) {
17822 bpf_prog_lock_ro(func[i]);
17823 bpf_prog_kallsyms_add(func[i]);
17826 /* Last step: make now unused interpreter insns from main
17827 * prog consistent for later dump requests, so they can
17828 * later look the same as if they were interpreted only.
17830 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17831 if (bpf_pseudo_func(insn)) {
17832 insn[0].imm = env->insn_aux_data[i].call_imm;
17833 insn[1].imm = insn->off;
17837 if (!bpf_pseudo_call(insn))
17839 insn->off = env->insn_aux_data[i].call_imm;
17840 subprog = find_subprog(env, i + insn->off + 1);
17841 insn->imm = subprog;
17845 prog->bpf_func = func[0]->bpf_func;
17846 prog->jited_len = func[0]->jited_len;
17847 prog->aux->extable = func[0]->aux->extable;
17848 prog->aux->num_exentries = func[0]->aux->num_exentries;
17849 prog->aux->func = func;
17850 prog->aux->func_cnt = env->subprog_cnt;
17851 bpf_prog_jit_attempt_done(prog);
17854 /* We failed JIT'ing, so at this point we need to unregister poke
17855 * descriptors from subprogs, so that kernel is not attempting to
17856 * patch it anymore as we're freeing the subprog JIT memory.
17858 for (i = 0; i < prog->aux->size_poke_tab; i++) {
17859 map_ptr = prog->aux->poke_tab[i].tail_call.map;
17860 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
17862 /* At this point we're guaranteed that poke descriptors are not
17863 * live anymore. We can just unlink its descriptor table as it's
17864 * released with the main prog.
17866 for (i = 0; i < env->subprog_cnt; i++) {
17869 func[i]->aux->poke_tab = NULL;
17870 bpf_jit_free(func[i]);
17874 /* cleanup main prog to be interpreted */
17875 prog->jit_requested = 0;
17876 prog->blinding_requested = 0;
17877 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17878 if (!bpf_pseudo_call(insn))
17881 insn->imm = env->insn_aux_data[i].call_imm;
17883 bpf_prog_jit_attempt_done(prog);
17887 static int fixup_call_args(struct bpf_verifier_env *env)
17889 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17890 struct bpf_prog *prog = env->prog;
17891 struct bpf_insn *insn = prog->insnsi;
17892 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
17897 if (env->prog->jit_requested &&
17898 !bpf_prog_is_offloaded(env->prog->aux)) {
17899 err = jit_subprogs(env);
17902 if (err == -EFAULT)
17905 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17906 if (has_kfunc_call) {
17907 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
17910 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
17911 /* When JIT fails the progs with bpf2bpf calls and tail_calls
17912 * have to be rejected, since interpreter doesn't support them yet.
17914 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
17917 for (i = 0; i < prog->len; i++, insn++) {
17918 if (bpf_pseudo_func(insn)) {
17919 /* When JIT fails the progs with callback calls
17920 * have to be rejected, since interpreter doesn't support them yet.
17922 verbose(env, "callbacks are not allowed in non-JITed programs\n");
17926 if (!bpf_pseudo_call(insn))
17928 depth = get_callee_stack_depth(env, insn, i);
17931 bpf_patch_call_args(insn, depth);
17938 /* replace a generic kfunc with a specialized version if necessary */
17939 static void specialize_kfunc(struct bpf_verifier_env *env,
17940 u32 func_id, u16 offset, unsigned long *addr)
17942 struct bpf_prog *prog = env->prog;
17943 bool seen_direct_write;
17947 if (bpf_dev_bound_kfunc_id(func_id)) {
17948 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
17950 *addr = (unsigned long)xdp_kfunc;
17953 /* fallback to default kfunc when not supported by netdev */
17959 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
17960 seen_direct_write = env->seen_direct_write;
17961 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
17964 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
17966 /* restore env->seen_direct_write to its original value, since
17967 * may_access_direct_pkt_data mutates it
17969 env->seen_direct_write = seen_direct_write;
17973 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
17974 u16 struct_meta_reg,
17975 u16 node_offset_reg,
17976 struct bpf_insn *insn,
17977 struct bpf_insn *insn_buf,
17980 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
17981 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
17983 insn_buf[0] = addr[0];
17984 insn_buf[1] = addr[1];
17985 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
17986 insn_buf[3] = *insn;
17990 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
17991 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
17993 const struct bpf_kfunc_desc *desc;
17996 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18002 /* insn->imm has the btf func_id. Replace it with an offset relative to
18003 * __bpf_call_base, unless the JIT needs to call functions that are
18004 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18006 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18008 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18013 if (!bpf_jit_supports_far_kfunc_call())
18014 insn->imm = BPF_CALL_IMM(desc->addr);
18017 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18018 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18019 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18020 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18022 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18023 insn_buf[1] = addr[0];
18024 insn_buf[2] = addr[1];
18025 insn_buf[3] = *insn;
18027 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18028 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18029 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18030 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18032 insn_buf[0] = addr[0];
18033 insn_buf[1] = addr[1];
18034 insn_buf[2] = *insn;
18036 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18037 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18038 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18039 int struct_meta_reg = BPF_REG_3;
18040 int node_offset_reg = BPF_REG_4;
18042 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18043 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18044 struct_meta_reg = BPF_REG_4;
18045 node_offset_reg = BPF_REG_5;
18048 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18049 node_offset_reg, insn, insn_buf, cnt);
18050 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18051 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18052 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18058 /* Do various post-verification rewrites in a single program pass.
18059 * These rewrites simplify JIT and interpreter implementations.
18061 static int do_misc_fixups(struct bpf_verifier_env *env)
18063 struct bpf_prog *prog = env->prog;
18064 enum bpf_attach_type eatype = prog->expected_attach_type;
18065 enum bpf_prog_type prog_type = resolve_prog_type(prog);
18066 struct bpf_insn *insn = prog->insnsi;
18067 const struct bpf_func_proto *fn;
18068 const int insn_cnt = prog->len;
18069 const struct bpf_map_ops *ops;
18070 struct bpf_insn_aux_data *aux;
18071 struct bpf_insn insn_buf[16];
18072 struct bpf_prog *new_prog;
18073 struct bpf_map *map_ptr;
18074 int i, ret, cnt, delta = 0;
18076 for (i = 0; i < insn_cnt; i++, insn++) {
18077 /* Make divide-by-zero exceptions impossible. */
18078 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18079 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18080 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18081 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18082 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18083 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18084 struct bpf_insn *patchlet;
18085 struct bpf_insn chk_and_div[] = {
18086 /* [R,W]x div 0 -> 0 */
18087 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18088 BPF_JNE | BPF_K, insn->src_reg,
18090 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18091 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18094 struct bpf_insn chk_and_mod[] = {
18095 /* [R,W]x mod 0 -> [R,W]x */
18096 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18097 BPF_JEQ | BPF_K, insn->src_reg,
18098 0, 1 + (is64 ? 0 : 1), 0),
18100 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18101 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18104 patchlet = isdiv ? chk_and_div : chk_and_mod;
18105 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18106 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18108 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18113 env->prog = prog = new_prog;
18114 insn = new_prog->insnsi + i + delta;
18118 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18119 if (BPF_CLASS(insn->code) == BPF_LD &&
18120 (BPF_MODE(insn->code) == BPF_ABS ||
18121 BPF_MODE(insn->code) == BPF_IND)) {
18122 cnt = env->ops->gen_ld_abs(insn, insn_buf);
18123 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18124 verbose(env, "bpf verifier is misconfigured\n");
18128 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18133 env->prog = prog = new_prog;
18134 insn = new_prog->insnsi + i + delta;
18138 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
18139 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18140 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18141 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18142 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18143 struct bpf_insn *patch = &insn_buf[0];
18144 bool issrc, isneg, isimm;
18147 aux = &env->insn_aux_data[i + delta];
18148 if (!aux->alu_state ||
18149 aux->alu_state == BPF_ALU_NON_POINTER)
18152 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18153 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18154 BPF_ALU_SANITIZE_SRC;
18155 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18157 off_reg = issrc ? insn->src_reg : insn->dst_reg;
18159 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18162 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18163 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18164 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18165 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18166 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18167 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18168 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18171 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18172 insn->src_reg = BPF_REG_AX;
18174 insn->code = insn->code == code_add ?
18175 code_sub : code_add;
18177 if (issrc && isneg && !isimm)
18178 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18179 cnt = patch - insn_buf;
18181 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18186 env->prog = prog = new_prog;
18187 insn = new_prog->insnsi + i + delta;
18191 if (insn->code != (BPF_JMP | BPF_CALL))
18193 if (insn->src_reg == BPF_PSEUDO_CALL)
18195 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18196 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18202 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18207 env->prog = prog = new_prog;
18208 insn = new_prog->insnsi + i + delta;
18212 if (insn->imm == BPF_FUNC_get_route_realm)
18213 prog->dst_needed = 1;
18214 if (insn->imm == BPF_FUNC_get_prandom_u32)
18215 bpf_user_rnd_init_once();
18216 if (insn->imm == BPF_FUNC_override_return)
18217 prog->kprobe_override = 1;
18218 if (insn->imm == BPF_FUNC_tail_call) {
18219 /* If we tail call into other programs, we
18220 * cannot make any assumptions since they can
18221 * be replaced dynamically during runtime in
18222 * the program array.
18224 prog->cb_access = 1;
18225 if (!allow_tail_call_in_subprogs(env))
18226 prog->aux->stack_depth = MAX_BPF_STACK;
18227 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18229 /* mark bpf_tail_call as different opcode to avoid
18230 * conditional branch in the interpreter for every normal
18231 * call and to prevent accidental JITing by JIT compiler
18232 * that doesn't support bpf_tail_call yet
18235 insn->code = BPF_JMP | BPF_TAIL_CALL;
18237 aux = &env->insn_aux_data[i + delta];
18238 if (env->bpf_capable && !prog->blinding_requested &&
18239 prog->jit_requested &&
18240 !bpf_map_key_poisoned(aux) &&
18241 !bpf_map_ptr_poisoned(aux) &&
18242 !bpf_map_ptr_unpriv(aux)) {
18243 struct bpf_jit_poke_descriptor desc = {
18244 .reason = BPF_POKE_REASON_TAIL_CALL,
18245 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18246 .tail_call.key = bpf_map_key_immediate(aux),
18247 .insn_idx = i + delta,
18250 ret = bpf_jit_add_poke_descriptor(prog, &desc);
18252 verbose(env, "adding tail call poke descriptor failed\n");
18256 insn->imm = ret + 1;
18260 if (!bpf_map_ptr_unpriv(aux))
18263 /* instead of changing every JIT dealing with tail_call
18264 * emit two extra insns:
18265 * if (index >= max_entries) goto out;
18266 * index &= array->index_mask;
18267 * to avoid out-of-bounds cpu speculation
18269 if (bpf_map_ptr_poisoned(aux)) {
18270 verbose(env, "tail_call abusing map_ptr\n");
18274 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18275 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18276 map_ptr->max_entries, 2);
18277 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18278 container_of(map_ptr,
18281 insn_buf[2] = *insn;
18283 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18288 env->prog = prog = new_prog;
18289 insn = new_prog->insnsi + i + delta;
18293 if (insn->imm == BPF_FUNC_timer_set_callback) {
18294 /* The verifier will process callback_fn as many times as necessary
18295 * with different maps and the register states prepared by
18296 * set_timer_callback_state will be accurate.
18298 * The following use case is valid:
18299 * map1 is shared by prog1, prog2, prog3.
18300 * prog1 calls bpf_timer_init for some map1 elements
18301 * prog2 calls bpf_timer_set_callback for some map1 elements.
18302 * Those that were not bpf_timer_init-ed will return -EINVAL.
18303 * prog3 calls bpf_timer_start for some map1 elements.
18304 * Those that were not both bpf_timer_init-ed and
18305 * bpf_timer_set_callback-ed will return -EINVAL.
18307 struct bpf_insn ld_addrs[2] = {
18308 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18311 insn_buf[0] = ld_addrs[0];
18312 insn_buf[1] = ld_addrs[1];
18313 insn_buf[2] = *insn;
18316 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18321 env->prog = prog = new_prog;
18322 insn = new_prog->insnsi + i + delta;
18323 goto patch_call_imm;
18326 if (is_storage_get_function(insn->imm)) {
18327 if (!env->prog->aux->sleepable ||
18328 env->insn_aux_data[i + delta].storage_get_func_atomic)
18329 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18331 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18332 insn_buf[1] = *insn;
18335 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18340 env->prog = prog = new_prog;
18341 insn = new_prog->insnsi + i + delta;
18342 goto patch_call_imm;
18345 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18346 * and other inlining handlers are currently limited to 64 bit
18349 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18350 (insn->imm == BPF_FUNC_map_lookup_elem ||
18351 insn->imm == BPF_FUNC_map_update_elem ||
18352 insn->imm == BPF_FUNC_map_delete_elem ||
18353 insn->imm == BPF_FUNC_map_push_elem ||
18354 insn->imm == BPF_FUNC_map_pop_elem ||
18355 insn->imm == BPF_FUNC_map_peek_elem ||
18356 insn->imm == BPF_FUNC_redirect_map ||
18357 insn->imm == BPF_FUNC_for_each_map_elem ||
18358 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18359 aux = &env->insn_aux_data[i + delta];
18360 if (bpf_map_ptr_poisoned(aux))
18361 goto patch_call_imm;
18363 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18364 ops = map_ptr->ops;
18365 if (insn->imm == BPF_FUNC_map_lookup_elem &&
18366 ops->map_gen_lookup) {
18367 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18368 if (cnt == -EOPNOTSUPP)
18369 goto patch_map_ops_generic;
18370 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18371 verbose(env, "bpf verifier is misconfigured\n");
18375 new_prog = bpf_patch_insn_data(env, i + delta,
18381 env->prog = prog = new_prog;
18382 insn = new_prog->insnsi + i + delta;
18386 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18387 (void *(*)(struct bpf_map *map, void *key))NULL));
18388 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18389 (long (*)(struct bpf_map *map, void *key))NULL));
18390 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18391 (long (*)(struct bpf_map *map, void *key, void *value,
18393 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18394 (long (*)(struct bpf_map *map, void *value,
18396 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18397 (long (*)(struct bpf_map *map, void *value))NULL));
18398 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18399 (long (*)(struct bpf_map *map, void *value))NULL));
18400 BUILD_BUG_ON(!__same_type(ops->map_redirect,
18401 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18402 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18403 (long (*)(struct bpf_map *map,
18404 bpf_callback_t callback_fn,
18405 void *callback_ctx,
18407 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18408 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18410 patch_map_ops_generic:
18411 switch (insn->imm) {
18412 case BPF_FUNC_map_lookup_elem:
18413 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18415 case BPF_FUNC_map_update_elem:
18416 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18418 case BPF_FUNC_map_delete_elem:
18419 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18421 case BPF_FUNC_map_push_elem:
18422 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18424 case BPF_FUNC_map_pop_elem:
18425 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18427 case BPF_FUNC_map_peek_elem:
18428 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18430 case BPF_FUNC_redirect_map:
18431 insn->imm = BPF_CALL_IMM(ops->map_redirect);
18433 case BPF_FUNC_for_each_map_elem:
18434 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18436 case BPF_FUNC_map_lookup_percpu_elem:
18437 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18441 goto patch_call_imm;
18444 /* Implement bpf_jiffies64 inline. */
18445 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18446 insn->imm == BPF_FUNC_jiffies64) {
18447 struct bpf_insn ld_jiffies_addr[2] = {
18448 BPF_LD_IMM64(BPF_REG_0,
18449 (unsigned long)&jiffies),
18452 insn_buf[0] = ld_jiffies_addr[0];
18453 insn_buf[1] = ld_jiffies_addr[1];
18454 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18458 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18464 env->prog = prog = new_prog;
18465 insn = new_prog->insnsi + i + delta;
18469 /* Implement bpf_get_func_arg inline. */
18470 if (prog_type == BPF_PROG_TYPE_TRACING &&
18471 insn->imm == BPF_FUNC_get_func_arg) {
18472 /* Load nr_args from ctx - 8 */
18473 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18474 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18475 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18476 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18477 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18478 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18479 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18480 insn_buf[7] = BPF_JMP_A(1);
18481 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18484 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18489 env->prog = prog = new_prog;
18490 insn = new_prog->insnsi + i + delta;
18494 /* Implement bpf_get_func_ret inline. */
18495 if (prog_type == BPF_PROG_TYPE_TRACING &&
18496 insn->imm == BPF_FUNC_get_func_ret) {
18497 if (eatype == BPF_TRACE_FEXIT ||
18498 eatype == BPF_MODIFY_RETURN) {
18499 /* Load nr_args from ctx - 8 */
18500 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18501 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18502 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18503 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18504 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18505 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18508 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18512 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18517 env->prog = prog = new_prog;
18518 insn = new_prog->insnsi + i + delta;
18522 /* Implement get_func_arg_cnt inline. */
18523 if (prog_type == BPF_PROG_TYPE_TRACING &&
18524 insn->imm == BPF_FUNC_get_func_arg_cnt) {
18525 /* Load nr_args from ctx - 8 */
18526 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18528 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18532 env->prog = prog = new_prog;
18533 insn = new_prog->insnsi + i + delta;
18537 /* Implement bpf_get_func_ip inline. */
18538 if (prog_type == BPF_PROG_TYPE_TRACING &&
18539 insn->imm == BPF_FUNC_get_func_ip) {
18540 /* Load IP address from ctx - 16 */
18541 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18543 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18547 env->prog = prog = new_prog;
18548 insn = new_prog->insnsi + i + delta;
18553 fn = env->ops->get_func_proto(insn->imm, env->prog);
18554 /* all functions that have prototype and verifier allowed
18555 * programs to call them, must be real in-kernel functions
18559 "kernel subsystem misconfigured func %s#%d\n",
18560 func_id_name(insn->imm), insn->imm);
18563 insn->imm = fn->func - __bpf_call_base;
18566 /* Since poke tab is now finalized, publish aux to tracker. */
18567 for (i = 0; i < prog->aux->size_poke_tab; i++) {
18568 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18569 if (!map_ptr->ops->map_poke_track ||
18570 !map_ptr->ops->map_poke_untrack ||
18571 !map_ptr->ops->map_poke_run) {
18572 verbose(env, "bpf verifier is misconfigured\n");
18576 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18578 verbose(env, "tracking tail call prog failed\n");
18583 sort_kfunc_descs_by_imm_off(env->prog);
18588 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18591 u32 callback_subprogno,
18594 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18595 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18596 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18597 int reg_loop_max = BPF_REG_6;
18598 int reg_loop_cnt = BPF_REG_7;
18599 int reg_loop_ctx = BPF_REG_8;
18601 struct bpf_prog *new_prog;
18602 u32 callback_start;
18603 u32 call_insn_offset;
18604 s32 callback_offset;
18606 /* This represents an inlined version of bpf_iter.c:bpf_loop,
18607 * be careful to modify this code in sync.
18609 struct bpf_insn insn_buf[] = {
18610 /* Return error and jump to the end of the patch if
18611 * expected number of iterations is too big.
18613 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18614 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18615 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18616 /* spill R6, R7, R8 to use these as loop vars */
18617 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18618 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18619 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18620 /* initialize loop vars */
18621 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18622 BPF_MOV32_IMM(reg_loop_cnt, 0),
18623 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18625 * if reg_loop_cnt >= reg_loop_max skip the loop body
18627 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18629 * correct callback offset would be set after patching
18631 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18632 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18634 /* increment loop counter */
18635 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18636 /* jump to loop header if callback returned 0 */
18637 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18638 /* return value of bpf_loop,
18639 * set R0 to the number of iterations
18641 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18642 /* restore original values of R6, R7, R8 */
18643 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18644 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18645 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18648 *cnt = ARRAY_SIZE(insn_buf);
18649 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18653 /* callback start is known only after patching */
18654 callback_start = env->subprog_info[callback_subprogno].start;
18655 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18656 call_insn_offset = position + 12;
18657 callback_offset = callback_start - call_insn_offset - 1;
18658 new_prog->insnsi[call_insn_offset].imm = callback_offset;
18663 static bool is_bpf_loop_call(struct bpf_insn *insn)
18665 return insn->code == (BPF_JMP | BPF_CALL) &&
18666 insn->src_reg == 0 &&
18667 insn->imm == BPF_FUNC_loop;
18670 /* For all sub-programs in the program (including main) check
18671 * insn_aux_data to see if there are bpf_loop calls that require
18672 * inlining. If such calls are found the calls are replaced with a
18673 * sequence of instructions produced by `inline_bpf_loop` function and
18674 * subprog stack_depth is increased by the size of 3 registers.
18675 * This stack space is used to spill values of the R6, R7, R8. These
18676 * registers are used to store the loop bound, counter and context
18679 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18681 struct bpf_subprog_info *subprogs = env->subprog_info;
18682 int i, cur_subprog = 0, cnt, delta = 0;
18683 struct bpf_insn *insn = env->prog->insnsi;
18684 int insn_cnt = env->prog->len;
18685 u16 stack_depth = subprogs[cur_subprog].stack_depth;
18686 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18687 u16 stack_depth_extra = 0;
18689 for (i = 0; i < insn_cnt; i++, insn++) {
18690 struct bpf_loop_inline_state *inline_state =
18691 &env->insn_aux_data[i + delta].loop_inline_state;
18693 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18694 struct bpf_prog *new_prog;
18696 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18697 new_prog = inline_bpf_loop(env,
18699 -(stack_depth + stack_depth_extra),
18700 inline_state->callback_subprogno,
18706 env->prog = new_prog;
18707 insn = new_prog->insnsi + i + delta;
18710 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18711 subprogs[cur_subprog].stack_depth += stack_depth_extra;
18713 stack_depth = subprogs[cur_subprog].stack_depth;
18714 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18715 stack_depth_extra = 0;
18719 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18724 static void free_states(struct bpf_verifier_env *env)
18726 struct bpf_verifier_state_list *sl, *sln;
18729 sl = env->free_list;
18732 free_verifier_state(&sl->state, false);
18736 env->free_list = NULL;
18738 if (!env->explored_states)
18741 for (i = 0; i < state_htab_size(env); i++) {
18742 sl = env->explored_states[i];
18746 free_verifier_state(&sl->state, false);
18750 env->explored_states[i] = NULL;
18754 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18756 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18757 struct bpf_verifier_state *state;
18758 struct bpf_reg_state *regs;
18761 env->prev_linfo = NULL;
18764 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18767 state->curframe = 0;
18768 state->speculative = false;
18769 state->branches = 1;
18770 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18771 if (!state->frame[0]) {
18775 env->cur_state = state;
18776 init_func_state(env, state->frame[0],
18777 BPF_MAIN_FUNC /* callsite */,
18780 state->first_insn_idx = env->subprog_info[subprog].start;
18781 state->last_insn_idx = -1;
18783 regs = state->frame[state->curframe]->regs;
18784 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
18785 ret = btf_prepare_func_args(env, subprog, regs);
18788 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
18789 if (regs[i].type == PTR_TO_CTX)
18790 mark_reg_known_zero(env, regs, i);
18791 else if (regs[i].type == SCALAR_VALUE)
18792 mark_reg_unknown(env, regs, i);
18793 else if (base_type(regs[i].type) == PTR_TO_MEM) {
18794 const u32 mem_size = regs[i].mem_size;
18796 mark_reg_known_zero(env, regs, i);
18797 regs[i].mem_size = mem_size;
18798 regs[i].id = ++env->id_gen;
18802 /* 1st arg to a function */
18803 regs[BPF_REG_1].type = PTR_TO_CTX;
18804 mark_reg_known_zero(env, regs, BPF_REG_1);
18805 ret = btf_check_subprog_arg_match(env, subprog, regs);
18806 if (ret == -EFAULT)
18807 /* unlikely verifier bug. abort.
18808 * ret == 0 and ret < 0 are sadly acceptable for
18809 * main() function due to backward compatibility.
18810 * Like socket filter program may be written as:
18811 * int bpf_prog(struct pt_regs *ctx)
18812 * and never dereference that ctx in the program.
18813 * 'struct pt_regs' is a type mismatch for socket
18814 * filter that should be using 'struct __sk_buff'.
18819 ret = do_check(env);
18821 /* check for NULL is necessary, since cur_state can be freed inside
18822 * do_check() under memory pressure.
18824 if (env->cur_state) {
18825 free_verifier_state(env->cur_state, true);
18826 env->cur_state = NULL;
18828 while (!pop_stack(env, NULL, NULL, false));
18829 if (!ret && pop_log)
18830 bpf_vlog_reset(&env->log, 0);
18835 /* Verify all global functions in a BPF program one by one based on their BTF.
18836 * All global functions must pass verification. Otherwise the whole program is rejected.
18847 * foo() will be verified first for R1=any_scalar_value. During verification it
18848 * will be assumed that bar() already verified successfully and call to bar()
18849 * from foo() will be checked for type match only. Later bar() will be verified
18850 * independently to check that it's safe for R1=any_scalar_value.
18852 static int do_check_subprogs(struct bpf_verifier_env *env)
18854 struct bpf_prog_aux *aux = env->prog->aux;
18857 if (!aux->func_info)
18860 for (i = 1; i < env->subprog_cnt; i++) {
18861 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
18863 env->insn_idx = env->subprog_info[i].start;
18864 WARN_ON_ONCE(env->insn_idx == 0);
18865 ret = do_check_common(env, i);
18868 } else if (env->log.level & BPF_LOG_LEVEL) {
18870 "Func#%d is safe for any args that match its prototype\n",
18877 static int do_check_main(struct bpf_verifier_env *env)
18882 ret = do_check_common(env, 0);
18884 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18889 static void print_verification_stats(struct bpf_verifier_env *env)
18893 if (env->log.level & BPF_LOG_STATS) {
18894 verbose(env, "verification time %lld usec\n",
18895 div_u64(env->verification_time, 1000));
18896 verbose(env, "stack depth ");
18897 for (i = 0; i < env->subprog_cnt; i++) {
18898 u32 depth = env->subprog_info[i].stack_depth;
18900 verbose(env, "%d", depth);
18901 if (i + 1 < env->subprog_cnt)
18904 verbose(env, "\n");
18906 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
18907 "total_states %d peak_states %d mark_read %d\n",
18908 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
18909 env->max_states_per_insn, env->total_states,
18910 env->peak_states, env->longest_mark_read_walk);
18913 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
18915 const struct btf_type *t, *func_proto;
18916 const struct bpf_struct_ops *st_ops;
18917 const struct btf_member *member;
18918 struct bpf_prog *prog = env->prog;
18919 u32 btf_id, member_idx;
18922 if (!prog->gpl_compatible) {
18923 verbose(env, "struct ops programs must have a GPL compatible license\n");
18927 btf_id = prog->aux->attach_btf_id;
18928 st_ops = bpf_struct_ops_find(btf_id);
18930 verbose(env, "attach_btf_id %u is not a supported struct\n",
18936 member_idx = prog->expected_attach_type;
18937 if (member_idx >= btf_type_vlen(t)) {
18938 verbose(env, "attach to invalid member idx %u of struct %s\n",
18939 member_idx, st_ops->name);
18943 member = &btf_type_member(t)[member_idx];
18944 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
18945 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
18948 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
18949 mname, member_idx, st_ops->name);
18953 if (st_ops->check_member) {
18954 int err = st_ops->check_member(t, member, prog);
18957 verbose(env, "attach to unsupported member %s of struct %s\n",
18958 mname, st_ops->name);
18963 prog->aux->attach_func_proto = func_proto;
18964 prog->aux->attach_func_name = mname;
18965 env->ops = st_ops->verifier_ops;
18969 #define SECURITY_PREFIX "security_"
18971 static int check_attach_modify_return(unsigned long addr, const char *func_name)
18973 if (within_error_injection_list(addr) ||
18974 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
18980 /* list of non-sleepable functions that are otherwise on
18981 * ALLOW_ERROR_INJECTION list
18983 BTF_SET_START(btf_non_sleepable_error_inject)
18984 /* Three functions below can be called from sleepable and non-sleepable context.
18985 * Assume non-sleepable from bpf safety point of view.
18987 BTF_ID(func, __filemap_add_folio)
18988 BTF_ID(func, should_fail_alloc_page)
18989 BTF_ID(func, should_failslab)
18990 BTF_SET_END(btf_non_sleepable_error_inject)
18992 static int check_non_sleepable_error_inject(u32 btf_id)
18994 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
18997 int bpf_check_attach_target(struct bpf_verifier_log *log,
18998 const struct bpf_prog *prog,
18999 const struct bpf_prog *tgt_prog,
19001 struct bpf_attach_target_info *tgt_info)
19003 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19004 const char prefix[] = "btf_trace_";
19005 int ret = 0, subprog = -1, i;
19006 const struct btf_type *t;
19007 bool conservative = true;
19011 struct module *mod = NULL;
19014 bpf_log(log, "Tracing programs must provide btf_id\n");
19017 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19020 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19023 t = btf_type_by_id(btf, btf_id);
19025 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19028 tname = btf_name_by_offset(btf, t->name_off);
19030 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19034 struct bpf_prog_aux *aux = tgt_prog->aux;
19036 if (bpf_prog_is_dev_bound(prog->aux) &&
19037 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19038 bpf_log(log, "Target program bound device mismatch");
19042 for (i = 0; i < aux->func_info_cnt; i++)
19043 if (aux->func_info[i].type_id == btf_id) {
19047 if (subprog == -1) {
19048 bpf_log(log, "Subprog %s doesn't exist\n", tname);
19051 conservative = aux->func_info_aux[subprog].unreliable;
19052 if (prog_extension) {
19053 if (conservative) {
19055 "Cannot replace static functions\n");
19058 if (!prog->jit_requested) {
19060 "Extension programs should be JITed\n");
19064 if (!tgt_prog->jited) {
19065 bpf_log(log, "Can attach to only JITed progs\n");
19068 if (tgt_prog->type == prog->type) {
19069 /* Cannot fentry/fexit another fentry/fexit program.
19070 * Cannot attach program extension to another extension.
19071 * It's ok to attach fentry/fexit to extension program.
19073 bpf_log(log, "Cannot recursively attach\n");
19076 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19078 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19079 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19080 /* Program extensions can extend all program types
19081 * except fentry/fexit. The reason is the following.
19082 * The fentry/fexit programs are used for performance
19083 * analysis, stats and can be attached to any program
19084 * type except themselves. When extension program is
19085 * replacing XDP function it is necessary to allow
19086 * performance analysis of all functions. Both original
19087 * XDP program and its program extension. Hence
19088 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19089 * allowed. If extending of fentry/fexit was allowed it
19090 * would be possible to create long call chain
19091 * fentry->extension->fentry->extension beyond
19092 * reasonable stack size. Hence extending fentry is not
19095 bpf_log(log, "Cannot extend fentry/fexit\n");
19099 if (prog_extension) {
19100 bpf_log(log, "Cannot replace kernel functions\n");
19105 switch (prog->expected_attach_type) {
19106 case BPF_TRACE_RAW_TP:
19109 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19112 if (!btf_type_is_typedef(t)) {
19113 bpf_log(log, "attach_btf_id %u is not a typedef\n",
19117 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19118 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19122 tname += sizeof(prefix) - 1;
19123 t = btf_type_by_id(btf, t->type);
19124 if (!btf_type_is_ptr(t))
19125 /* should never happen in valid vmlinux build */
19127 t = btf_type_by_id(btf, t->type);
19128 if (!btf_type_is_func_proto(t))
19129 /* should never happen in valid vmlinux build */
19133 case BPF_TRACE_ITER:
19134 if (!btf_type_is_func(t)) {
19135 bpf_log(log, "attach_btf_id %u is not a function\n",
19139 t = btf_type_by_id(btf, t->type);
19140 if (!btf_type_is_func_proto(t))
19142 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19147 if (!prog_extension)
19150 case BPF_MODIFY_RETURN:
19152 case BPF_LSM_CGROUP:
19153 case BPF_TRACE_FENTRY:
19154 case BPF_TRACE_FEXIT:
19155 if (!btf_type_is_func(t)) {
19156 bpf_log(log, "attach_btf_id %u is not a function\n",
19160 if (prog_extension &&
19161 btf_check_type_match(log, prog, btf, t))
19163 t = btf_type_by_id(btf, t->type);
19164 if (!btf_type_is_func_proto(t))
19167 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19168 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19169 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19172 if (tgt_prog && conservative)
19175 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19181 addr = (long) tgt_prog->bpf_func;
19183 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19185 if (btf_is_module(btf)) {
19186 mod = btf_try_get_module(btf);
19188 addr = find_kallsyms_symbol_value(mod, tname);
19192 addr = kallsyms_lookup_name(tname);
19197 "The address of function %s cannot be found\n",
19203 if (prog->aux->sleepable) {
19205 switch (prog->type) {
19206 case BPF_PROG_TYPE_TRACING:
19208 /* fentry/fexit/fmod_ret progs can be sleepable if they are
19209 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19211 if (!check_non_sleepable_error_inject(btf_id) &&
19212 within_error_injection_list(addr))
19214 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
19215 * in the fmodret id set with the KF_SLEEPABLE flag.
19218 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19221 if (flags && (*flags & KF_SLEEPABLE))
19225 case BPF_PROG_TYPE_LSM:
19226 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
19227 * Only some of them are sleepable.
19229 if (bpf_lsm_is_sleepable_hook(btf_id))
19237 bpf_log(log, "%s is not sleepable\n", tname);
19240 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19243 bpf_log(log, "can't modify return codes of BPF programs\n");
19247 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19248 !check_attach_modify_return(addr, tname))
19252 bpf_log(log, "%s() is not modifiable\n", tname);
19259 tgt_info->tgt_addr = addr;
19260 tgt_info->tgt_name = tname;
19261 tgt_info->tgt_type = t;
19262 tgt_info->tgt_mod = mod;
19266 BTF_SET_START(btf_id_deny)
19269 BTF_ID(func, migrate_disable)
19270 BTF_ID(func, migrate_enable)
19272 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19273 BTF_ID(func, rcu_read_unlock_strict)
19275 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19276 BTF_ID(func, preempt_count_add)
19277 BTF_ID(func, preempt_count_sub)
19279 #ifdef CONFIG_PREEMPT_RCU
19280 BTF_ID(func, __rcu_read_lock)
19281 BTF_ID(func, __rcu_read_unlock)
19283 BTF_SET_END(btf_id_deny)
19285 static bool can_be_sleepable(struct bpf_prog *prog)
19287 if (prog->type == BPF_PROG_TYPE_TRACING) {
19288 switch (prog->expected_attach_type) {
19289 case BPF_TRACE_FENTRY:
19290 case BPF_TRACE_FEXIT:
19291 case BPF_MODIFY_RETURN:
19292 case BPF_TRACE_ITER:
19298 return prog->type == BPF_PROG_TYPE_LSM ||
19299 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19300 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19303 static int check_attach_btf_id(struct bpf_verifier_env *env)
19305 struct bpf_prog *prog = env->prog;
19306 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19307 struct bpf_attach_target_info tgt_info = {};
19308 u32 btf_id = prog->aux->attach_btf_id;
19309 struct bpf_trampoline *tr;
19313 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19314 if (prog->aux->sleepable)
19315 /* attach_btf_id checked to be zero already */
19317 verbose(env, "Syscall programs can only be sleepable\n");
19321 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19322 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19326 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19327 return check_struct_ops_btf_id(env);
19329 if (prog->type != BPF_PROG_TYPE_TRACING &&
19330 prog->type != BPF_PROG_TYPE_LSM &&
19331 prog->type != BPF_PROG_TYPE_EXT)
19334 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19338 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19339 /* to make freplace equivalent to their targets, they need to
19340 * inherit env->ops and expected_attach_type for the rest of the
19343 env->ops = bpf_verifier_ops[tgt_prog->type];
19344 prog->expected_attach_type = tgt_prog->expected_attach_type;
19347 /* store info about the attachment target that will be used later */
19348 prog->aux->attach_func_proto = tgt_info.tgt_type;
19349 prog->aux->attach_func_name = tgt_info.tgt_name;
19350 prog->aux->mod = tgt_info.tgt_mod;
19353 prog->aux->saved_dst_prog_type = tgt_prog->type;
19354 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19357 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19358 prog->aux->attach_btf_trace = true;
19360 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19361 if (!bpf_iter_prog_supported(prog))
19366 if (prog->type == BPF_PROG_TYPE_LSM) {
19367 ret = bpf_lsm_verify_prog(&env->log, prog);
19370 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
19371 btf_id_set_contains(&btf_id_deny, btf_id)) {
19375 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19376 tr = bpf_trampoline_get(key, &tgt_info);
19380 prog->aux->dst_trampoline = tr;
19384 struct btf *bpf_get_btf_vmlinux(void)
19386 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19387 mutex_lock(&bpf_verifier_lock);
19389 btf_vmlinux = btf_parse_vmlinux();
19390 mutex_unlock(&bpf_verifier_lock);
19392 return btf_vmlinux;
19395 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19397 u64 start_time = ktime_get_ns();
19398 struct bpf_verifier_env *env;
19399 int i, len, ret = -EINVAL, err;
19403 /* no program is valid */
19404 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19407 /* 'struct bpf_verifier_env' can be global, but since it's not small,
19408 * allocate/free it every time bpf_check() is called
19410 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19416 len = (*prog)->len;
19417 env->insn_aux_data =
19418 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19420 if (!env->insn_aux_data)
19422 for (i = 0; i < len; i++)
19423 env->insn_aux_data[i].orig_idx = i;
19425 env->ops = bpf_verifier_ops[env->prog->type];
19426 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19427 is_priv = bpf_capable();
19429 bpf_get_btf_vmlinux();
19431 /* grab the mutex to protect few globals used by verifier */
19433 mutex_lock(&bpf_verifier_lock);
19435 /* user could have requested verbose verifier output
19436 * and supplied buffer to store the verification trace
19438 ret = bpf_vlog_init(&env->log, attr->log_level,
19439 (char __user *) (unsigned long) attr->log_buf,
19444 mark_verifier_state_clean(env);
19446 if (IS_ERR(btf_vmlinux)) {
19447 /* Either gcc or pahole or kernel are broken. */
19448 verbose(env, "in-kernel BTF is malformed\n");
19449 ret = PTR_ERR(btf_vmlinux);
19450 goto skip_full_check;
19453 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19454 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19455 env->strict_alignment = true;
19456 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19457 env->strict_alignment = false;
19459 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19460 env->allow_uninit_stack = bpf_allow_uninit_stack();
19461 env->bypass_spec_v1 = bpf_bypass_spec_v1();
19462 env->bypass_spec_v4 = bpf_bypass_spec_v4();
19463 env->bpf_capable = bpf_capable();
19466 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19468 env->explored_states = kvcalloc(state_htab_size(env),
19469 sizeof(struct bpf_verifier_state_list *),
19472 if (!env->explored_states)
19473 goto skip_full_check;
19475 ret = add_subprog_and_kfunc(env);
19477 goto skip_full_check;
19479 ret = check_subprogs(env);
19481 goto skip_full_check;
19483 ret = check_btf_info(env, attr, uattr);
19485 goto skip_full_check;
19487 ret = check_attach_btf_id(env);
19489 goto skip_full_check;
19491 ret = resolve_pseudo_ldimm64(env);
19493 goto skip_full_check;
19495 if (bpf_prog_is_offloaded(env->prog->aux)) {
19496 ret = bpf_prog_offload_verifier_prep(env->prog);
19498 goto skip_full_check;
19501 ret = check_cfg(env);
19503 goto skip_full_check;
19505 ret = do_check_subprogs(env);
19506 ret = ret ?: do_check_main(env);
19508 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19509 ret = bpf_prog_offload_finalize(env);
19512 kvfree(env->explored_states);
19515 ret = check_max_stack_depth(env);
19517 /* instruction rewrites happen after this point */
19519 ret = optimize_bpf_loop(env);
19523 opt_hard_wire_dead_code_branches(env);
19525 ret = opt_remove_dead_code(env);
19527 ret = opt_remove_nops(env);
19530 sanitize_dead_code(env);
19534 /* program is valid, convert *(u32*)(ctx + off) accesses */
19535 ret = convert_ctx_accesses(env);
19538 ret = do_misc_fixups(env);
19540 /* do 32-bit optimization after insn patching has done so those patched
19541 * insns could be handled correctly.
19543 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19544 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19545 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19550 ret = fixup_call_args(env);
19552 env->verification_time = ktime_get_ns() - start_time;
19553 print_verification_stats(env);
19554 env->prog->aux->verified_insns = env->insn_processed;
19556 /* preserve original error even if log finalization is successful */
19557 err = bpf_vlog_finalize(&env->log, &log_true_size);
19561 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19562 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19563 &log_true_size, sizeof(log_true_size))) {
19565 goto err_release_maps;
19569 goto err_release_maps;
19571 if (env->used_map_cnt) {
19572 /* if program passed verifier, update used_maps in bpf_prog_info */
19573 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19574 sizeof(env->used_maps[0]),
19577 if (!env->prog->aux->used_maps) {
19579 goto err_release_maps;
19582 memcpy(env->prog->aux->used_maps, env->used_maps,
19583 sizeof(env->used_maps[0]) * env->used_map_cnt);
19584 env->prog->aux->used_map_cnt = env->used_map_cnt;
19586 if (env->used_btf_cnt) {
19587 /* if program passed verifier, update used_btfs in bpf_prog_aux */
19588 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19589 sizeof(env->used_btfs[0]),
19591 if (!env->prog->aux->used_btfs) {
19593 goto err_release_maps;
19596 memcpy(env->prog->aux->used_btfs, env->used_btfs,
19597 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19598 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19600 if (env->used_map_cnt || env->used_btf_cnt) {
19601 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
19602 * bpf_ld_imm64 instructions
19604 convert_pseudo_ld_imm64(env);
19607 adjust_btf_func(env);
19610 if (!env->prog->aux->used_maps)
19611 /* if we didn't copy map pointers into bpf_prog_info, release
19612 * them now. Otherwise free_used_maps() will release them.
19615 if (!env->prog->aux->used_btfs)
19618 /* extension progs temporarily inherit the attach_type of their targets
19619 for verification purposes, so set it back to zero before returning
19621 if (env->prog->type == BPF_PROG_TYPE_EXT)
19622 env->prog->expected_attach_type = 0;
19627 mutex_unlock(&bpf_verifier_lock);
19628 vfree(env->insn_aux_data);